Model Builder

The ModelBuilder is the entry point for defining a model. Use its factory methods to add tables and named values, then call write_to_file() to emit the model definition JSON.

Related pages:

  • Tables — the table types (data, derived, joined, union)

  • Fields — fields that live on tables

  • Named Values — calculations and parameters

  • Formulas — the formula language and built-in functions

class ModelBuilder[source]

Bases: object

Top-level entry point for building a Daitum model.

A model holds tables and named values (calculations and parameters). Build one incrementally with the add_* factory methods, then call write_to_file() to emit the JSON output.

__init__()[source]

Initialise an empty model with no tables, calculations, or parameters.

add_calculation(id, formula, model_level=False)[source]

Add a Calculation to the model.

Parameters:
  • id (str) – Unique identifier for the calculation. Must not collide with any existing calculation or parameter id.

  • formula (Operand | float | int | bool | str) – The expression. A Formula or any value accepted by CONST() (number, bool, or string), which is wrapped automatically.

  • model_level (bool) – If True, the calculation is evaluated once for the whole model. If False (the default) it is scenario-level.

Return type:

Calculation

Returns:

The newly added Calculation.

Raises:

ValueError – If a calculation or parameter with the same id already exists in the model.

add_parameter(id, data_type, value, model_level=False)[source]

Add a Parameter to the model.

Parameters:
  • id (str) – Unique identifier for the parameter.

  • data_type (BaseDataType) – Data type of the parameter — a DataType, ObjectDataType, or MapDataType.

  • value (Any) – Initial value. Must be compatible with data_type.

  • model_level (bool) – If True, the parameter is shared across all scenarios. If False (the default) it is scenario-level.

Return type:

Parameter

Returns:

The newly added Parameter.

add_tracking_group(name)[source]

Declare a change-tracking group.

Tag fields, parameters, and calculations with the returned group (via set_tracking_groups) to include them in baselines that capture it.

Parameters:

name (str) – Unique identifier for the tracking group.

Return type:

TrackingGroup

Returns:

The newly declared TrackingGroup.

Raises:

ValueError – If a tracking group with the same name already exists.

add_baseline(name, tracking_groups, auto_capture=AutoCapture.NONE)[source]

Declare a baseline — a named point in time that snapshots tracking groups.

Parameters:
  • name (str) – Unique identifier for the baseline.

  • tracking_groups (list[str | TrackingGroup]) – The tracking groups (or their names) this baseline captures.

  • auto_capture (AutoCapture) – Platform milestone that triggers an automatic capture, or NONE (the default) for manual capture only.

Return type:

Baseline

Returns:

The newly declared Baseline.

Raises:

ValueError – If a baseline with the same name already exists.

add_data_table(id)[source]

Add a DataTable to the model.

A data table holds raw imported rows and is the only table type that supports decision variables.

Parameters:

id (str) – Unique identifier for the table. Must not collide with any existing table id.

Return type:

DataTable

Returns:

The newly added DataTable. Use its add_data_field / add_calculated_field / set_key_column methods to populate it.

Raises:

ValueError – If a table with the same id already exists.

add_derived_table(id, source_table, group_by=None, filter_field=None)[source]

Add a DerivedTable to the model.

A derived table is a grouped, filtered, and/or sorted view of an existing source table.

Parameters:
  • id (str) – Unique identifier for the derived table.

  • source_table (Table) – The table whose rows the derived table draws from.

  • group_by (list[Field] | None) – Optional fields to group rows by. When supplied, non-group fields must be added with an AggregationMethod.

  • filter_field (Field | None) – Optional BOOLEAN field on source_table; only rows where it is True are kept.

Return type:

DerivedTable

Returns:

The newly added DerivedTable.

Raises:

ValueError – If a table with the same id already exists.

add_joined_table(id, join_conditions)[source]

Add a JoinedTable to the model.

A joined table is the result of joining two or more tables on a list of JoinCondition rows.

Parameters:
  • id (str) – Unique identifier for the joined table.

  • join_conditions (list[JoinCondition]) – One condition per joined table pairing. The JoinType of each condition controls how unmatched rows are handled. A CROSS condition pairs every left row with every right row and takes no match fields.

Return type:

JoinedTable

Returns:

The newly added JoinedTable.

Raises:

ValueError – If a table with the same id already exists.

add_union_table(id, source_tables)[source]

Add a UnionTable to the model.

A union table stacks rows from multiple source tables. Pass a UnionSource instead of a bare Table when the source schema does not line up with the union table’s fields.

Parameters:
  • id (str) – Unique identifier for the union table.

  • source_tables (list[Table | UnionSource]) – The tables (or wrapped UnionSource instances) whose rows are stacked.

Return type:

UnionTable

Returns:

The newly added UnionTable.

Raises:

ValueError – If a table with the same id already exists.

set_partial_evaluation_allowed(partial_evaluation_allowed=True)[source]

Toggle partial evaluation for this model.

When enabled (the default), the platform re-evaluates only the calculations affected by a change rather than the whole model, which speeds up UI rendering. Disable only if a model has dependencies that the partial evaluator cannot track correctly.

Parameters:

partial_evaluation_allowed (bool) – True to allow partial evaluation.

set_data_validation_rule(named_value)[source]

Gate optimisation on a boolean named value.

Optimisation is allowed only while named_value evaluates to True. When it is False and the UI definition specifies a validation screen, the user is redirected there on attempting to start optimisation.

Parameters:

named_value (Parameter | Calculation) – A Parameter or Calculation of type BOOLEAN.

Raises:

ValueError – If named_value is not of boolean data type.

get_tables()[source]

Return every table that has been added to the model, in insertion order.

Return type:

list[Table]

get_table(id)[source]

Return the table with the given id.

Parameters:

id (str) – Identifier of the table to look up.

Return type:

Table

Returns:

The matching Table.

Raises:

ValueError – If no table with that id exists in the model.

get_named_value(id)[source]

Return the named value (parameter or calculation) with the given id.

Parameters:

id (str) – Identifier of the named value to look up.

Return type:

Parameter | Calculation

Returns:

The matching Parameter or Calculation. Parameters are searched first, so a parameter is returned if both exist with the same id (which add_parameter / add_calculation would normally prevent).

Raises:

ValueError – If no named value with that id exists in the model.

get_validation_state()[source]

Return (and lazily build) a calculation summarising current validity.

The calculation evaluates to the highest SEVERITY_RANK among every field, parameter, and calculation whose __invalid__ formula is currently True, or 0 when nothing is invalid. Useful as the gating value for set_data_validation_rule().

The result is registered in the model under the id __validation_state__. Subsequent calls return the already-registered calculation without rebuilding it, so call this only after every validator has been attached.

Return type:

Calculation | Parameter

Returns:

A model-level Calculation whose integer value is the highest severity rank of any currently-invalid entity.

classmethod read_from_file(model_directory)[source]

Reconstruct a live ModelBuilder from the canonical Daitum directory layout.

The inverse of write_to_file(). Reads model-definition.json and the scenario- and model-level named-values.json files from disk, then delegates to read_from_dict() to do the actual decoding.

Parameters:

model_directory (str | PathLike[str]) – The directory previously written by write_to_file().

Return type:

ModelBuilder

Returns:

A ModelBuilder equivalent to the one that produced the files.

classmethod read_from_dict(definition, named_values=None)[source]

Reconstruct a live ModelBuilder from already-parsed JSON dicts.

The dict-level inverse of build(). Rebuilds the tables, calculations, and parameters from definition, then restores each parameter’s value from the named_values payloads. The returned builder is fully re-editable (decoding routes through the add_* factories) and exposes the populated LoadContext via load_context for a configuration or UI load to consume.

Parameters:
  • definition (dict[str, Any]) – The dict produced by build() (model-definition.json).

  • named_values (list[dict[str, Any]] | None) – Parsed named-values.json payloads (each a {"values": {...}} dict) supplying parameter values. May be omitted when no values are needed.

Return type:

ModelBuilder

Returns:

A ModelBuilder equivalent to the one that produced the dict.

property load_context

The LoadContext populated by read_from_file().

None on a builder that was constructed directly rather than loaded.

write_to_file(model_directory)[source]

Serialise the model into the canonical Daitum directory layout.

Writes three files under model_directory, creating it if it does not exist:

  • model-definition.json — the full model definition from build().

  • scenarios/Initial/named-values.json — scenario-level named values (those added with model_level=False).

  • model-data/named-values.json — model-level named values (those added with model_level=True).

Parameters:

model_directory (str | PathLike[str]) – Destination directory. Parents are created as needed.

Return type:

None

build()[source]

Build the JSON-compatible dict representation of the model.

Change-tracking declarations are validated here (see _validate_tracking()). The trackingGroupDefinitions and baselineDefinitions keys are only emitted when at least one tracking group or baseline has been declared, so untracked models are unaffected.

Return type:

dict[str, Any]

Returns:

A dict suitable for json.dump containing calculationDefinitions, parameterDefinitions, tableDefinitions, optimisationCheckNamedValue, partialEvaluationAllowed and, when present, the change-tracking definition maps.

Raises:

ValueError – If a change-tracking declaration is invalid.

to_named_value_dict(model_level)[source]

Build the JSON-compatible dict of parameter values for one scope.

Parameters:

model_level (bool) – When True, include only model-level parameters (written to model-data/named-values.json). When False, include only scenario-level parameters (written to scenarios/Initial/named-values.json).

Return type:

dict[str, Any]

Returns:

{"values": {parameter_id: value_dict, ...}}.