daitum-model
daitum_model — Model and formula generation for the Daitum platform.
A model consists of three main parts: the model definition, model configuration, and UI definition.
The model definition contains tables, named values (calculations and parameters), and fields. These elements either contain static data or can be dynamic, such as calculations and calculated fields. Calculated fields and named values use a custom modelling language which is loosely based on Microsoft Excel.
The model configuration specifies the optimisation parameters, such as decision variables, objectives, and constraints. It also sets up the algorithm configuration, data stores and data processors.
The UI definition specifies the user interface components and functionality that will be visible when the model is uploaded to the platform.
This package covers the model definition, and also provides all formula functions via
daitum_model.formulas.
Usage:
from daitum_model import ModelBuilder, DataType, formulas
model = ModelBuilder()
table = model.add_data_table("Jobs", key_column="ID")
cost = table.add_data_field("Cost", DataType.DECIMAL)
is_valid = formulas.NOT(formulas.ISBLANK(cost))
- class BaseDataType(*args, **kwargs)[source]
Structural protocol shared by every data type used in the model:
DataType,ObjectDataTypeandMapDataType.isinstancechecks against this protocol are supported, but production code should generally prefer the concrete classes when behaviour differs.- to_array()[source]
- Return type:
BaseDataType
- from_array()[source]
- Return type:
BaseDataType
- class DataType(*values)[source]
Enumeration representing various data types.
This enumeration is used to specify different data types that can be used in calculations, parameters, or tables within a model.
- INTEGER = 'INTEGER'
Integer data type.
- DECIMAL = 'DECIMAL'
Decimal data type.
- STRING = 'STRING'
String data type.
- BOOLEAN = 'BOOLEAN'
Boolean data type.
- DATE = 'DATE'
Date data type.
- DATETIME = 'DATETIME'
Datetime data type.
- TIME = 'TIME'
Time data type.
- INTEGER_ARRAY = 'INTEGER_ARRAY'
Array of INTEGER data type.
- DECIMAL_ARRAY = 'DECIMAL_ARRAY'
Array of DECIMAL data type.
- STRING_ARRAY = 'STRING_ARRAY'
Array of STRING data type.
- BOOLEAN_ARRAY = 'BOOLEAN_ARRAY'
Array of BOOLEAN data type.
- DATE_ARRAY = 'DATE_ARRAY'
Array of DATE data type.
- DATETIME_ARRAY = 'DATETIME_ARRAY'
Array of DATETIME data type.
- TIME_ARRAY = 'TIME_ARRAY'
Array of TIME data type.
- NULL = 'NULL'
Used to identify BLANK() formulae. Should never be used explicitly in models
- class ObjectDataType(source_table, is_array=False)[source]
A composite data type used for references to other Tables.
- __init__(source_table, is_array=False)[source]
- Parameters:
source_table (
_TableBase) – The table this data type references.is_array (
bool) – Whether this is anOBJECT_ARRAYtype rather than a singularOBJECT.
- is_array()[source]
Checks if the data type is an array.
- Returns:
True if the data type is an array, otherwise False.
- Return type:
- to_array()[source]
Converts an object type to an object array type.
- Returns:
The array equivalent of the data type.
- Return type:
- Raises:
ValueError – If the data type is already an array.
- from_array()[source]
Converts an object array type to a singular object type.
- Returns:
The singular (non-array) equivalent of the data type.
- Return type:
- Raises:
ValueError – If the data type is not an array.
- class MapDataType(data_type, source_table)[source]
A composite data type used to represent key-value maps into other Tables.
- Raises:
TypeError – If the data type is an array type.
- __init__(data_type, source_table)[source]
- property data_type: DataType
The primitive data type of the map values.
- Returns:
The primitive data type.
- Return type:
- is_array()[source]
Always False. Used to simplify array checks without having to check if a data type is a MapDataType
- Returns:
False
- Return type:
- to_array()[source]
Always raises. Mirrors
from_array()so callers can treatMapDataTypeuniformly withDataTypeandObjectDataTypewithout isinstance checks.- Raises:
ValueError – Always — map data types cannot be arrays.
- Return type:
- from_array()[source]
Always raises an error. Used to simplify array checks without having to check if a data type is a MapDataType.
- Returns:
The singular (non-array) equivalent of the data type.
- Return type:
- Raises:
ValueError – Always, as map data types cannot be an array.
- class SortDirection(*values)[source]
Enumeration representing the possible sorting options for a SortKey in a DerivedTable.
- ASCENDING = 'ASCENDING'
Ascending sort direction.
- DESCENDING = 'DESCENDING'
Descending sort direction.
- class AggregationMethod(*values)[source]
Enumeration listing the possible aggregation methods for aggregated fields.
- BLANK = 'BLANK'
Returns a typed null for the target field without aggregating values. Allowed DataTypes: any type. Return DataTypes: same as the allowed type.
- COUNT = 'COUNT'
Counts the number of non-null input items and returns that count. Result type is INTEGER irrespective of the source item type. Allowed DataTypes: any type. Return DataTypes: INTEGER.
- SUM = 'SUM'
Sums numeric inputs. For array targets, performs element-wise sum across arrays. Allowed DataTypes: INTEGER, DECIMAL, INTEGER_ARRAY, DECIMAL_ARRAY. Return DataTypes: same as the allowed type.
- MIN = 'MIN'
Returns the minimum (by natural ordering) of the inputs. Allowed DataTypes: any comparable scalar type (INTEGER, DECIMAL, STRING, BOOLEAN, DATE, TIME, DATETIME) and other comparable values. Not intended for arrays. Return DataTypes: same as the allowed type.
- MAX = 'MAX'
Returns the maximum (by natural ordering) of the inputs. Allowed DataTypes: any comparable scalar type (INTEGER, DECIMAL, STRING, BOOLEAN, DATE, TIME, DATETIME) and other comparable values. Not intended for arrays. Return DataTypes: same as the allowed type.
- AVERAGE = 'AVERAGE'
Calculates the arithmetic mean of numeric inputs and returns a DECIMAL value. Allowed DataTypes: INTEGER, DECIMAL. Return DataTypes: DECIMAL.
- FIRST = 'FIRST'
Returns the first input value encountered (typed), or null if none. Allowed DataTypes: any type. Return DataTypes: same as the allowed type.
- LAST = 'LAST'
Returns the last input value encountered (typed), or null if none. Allowed DataTypes: any type. Return DataTypes: same as the allowed type.
- EQUAL = 'EQUAL'
If all input values are equal, returns that value; otherwise returns typed null. Allowed DataTypes: any type. Return DataTypes: same as the allowed type.
- AND = 'AND'
Logical AND over boolean inputs. Nulls are treated as false by booleanValue() conversion. Allowed DataTypes: BOOLEAN. Return DataTypes: same as the allowed type.
- OR = 'OR'
Logical OR over boolean inputs. Nulls are treated as false by booleanValue() conversion. Allowed DataTypes: BOOLEAN. Return DataTypes: same as the allowed type.
- ARRAY = 'ARRAY'
Collects input items into an array of the target element type, preserving order. Allowed DataTypes: any non-array types except MapDataType (e.g., INTEGER, DECIMAL, STRING, BOOLEAN, DATE, TIME, DATETIME, OBJECT) Return DataTypes: the corresponding array type of the allowed type. (e.g., INTEGER_ARRAY, DECIMAL_ARRAY, STRING_ARRAY, BOOLEAN_ARRAY, DATE_ARRAY, TIME_ARRAY, DATETIME_ARRAY, OBJECT_ARRAY)
- REFERENCE = 'REFERENCE'
Creates an OBJECT_ARRAY of references from row ids provided by the evaluation engine. Allowed DataTypes: any type. Return DataTypes: OBJECT_ARRAY for a specific table.
- INTERSECTION = 'INTERSECTION'
Computes the set intersection across array inputs and returns an array result. Allowed DataTypes: any scalar or array type. Return DataTypes: the array of the scalar type when scalar target is provided, or the same array type when the target is already an array.
- UNION = 'UNION'
Computes the set union of inputs. If inputs are arrays, unions their elements; if inputs are scalars, unions individual values.. Allowed DataTypes: any scalar or array type. Return DataTypes: the array of the scalar type when scalar target is provided, or the same array type when the target is already an array.
- class JoinType(*values)[source]
The type of join used by a
JoinConditionto combine rows from two tables.- LEFT = 'LEFT'
Keep every row from the left table; attach matching right-table values where they exist, and leave the right-side cells blank otherwise.
Example — joining
Orders(3 rows) toCustomers(2 rows) onOrders.customer_id == Customers.id:Orders Customers order_id cust_id cust_id name -------- ------- ------- ----- 1 A A Alice 2 B C Carol 3 D LEFT result (3 rows -- one per Orders row): order_id cust_id name -------- ------- ------- 1 A Alice 2 B <blank> 3 D <blank>
- RIGHT = 'RIGHT'
Keep every row from the right table; attach matching left-table values where they exist, and leave the left-side cells blank otherwise. Mirror image of
LEFT.Same source tables as the LEFT example:
RIGHT result (2 rows -- one per Customers row): order_id cust_id name -------- ------- ----- 1 A Alice <blank> C Carol
- INNER = 'INNER'
Keep only rows where the join condition matches on both sides. Unmatched rows from either table are dropped.
Same source tables as the LEFT example:
INNER result (1 row -- only A matches on both sides): order_id cust_id name -------- ------- ----- 1 A Alice
- FULL = 'FULL'
Keep every row from both tables. Where a row has no match on the other side, the missing cells are blank. Equivalent to a
LEFTjoin unioned with aRIGHTjoin.Same source tables as the LEFT example:
FULL result (4 rows -- 3 from Orders + 1 unmatched Customer): order_id cust_id name -------- ------- ------- 1 A Alice 2 B <blank> 3 D <blank> <blank> C Carol
- class Severity(*values)[source]
Enumeration of validation severity levels.
- INFO = 'Info'
- WARNING = 'Warning'
- ERROR = 'Error'
- CRITICAL = 'Critical'
- class ModelBuilder[source]
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 callwrite_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, tracking_group=None)[source]
Add a
Calculationto 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. AFormulaor any value accepted byCONST()(number, bool, or string), which is wrapped automatically.model_level (
bool) – IfTrue, the calculation is evaluated once for the whole model. IfFalse(the default) it is scenario-level.tracking_group (
str|None) – Optional change-tracking group. When set, a sibling*_TRACKING_*calculation is generated with references to other tracked named values and fields rewritten to their tracking ids.
- Return type:
Calculation- Returns:
The newly added
Calculation.- Raises:
ValueError – If a calculation or parameter with the same
idalready exists in the model.
- add_parameter(id, data_type, value, model_level=False, tracking_group=None)[source]
Add a
Parameterto the model.- Parameters:
id (
str) – Unique identifier for the parameter.data_type (
BaseDataType) – Data type of the parameter — aDataType,ObjectDataType, orMapDataType.value (
Any) – Initial value. Must be compatible withdata_type.model_level (
bool) – IfTrue, the parameter is shared across all scenarios. IfFalse(the default) it is scenario-level.tracking_group (
str|None) – Optional change-tracking group. When set, a sibling*_TRACKING_*parameter is generated with the same value.
- Return type:
Parameter- Returns:
The newly added
Parameter.
- add_data_table(id)[source]
Add a
DataTableto 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:
- Returns:
The newly added
DataTable. Use itsadd_data_field/add_calculated_field/set_key_columnmethods to populate it.- Raises:
ValueError – If a table with the same
idalready exists.
- add_derived_table(id, source_table, group_by=None, filter_field=None)[source]
Add a
DerivedTableto 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 anAggregationMethod.filter_field (
Field|None) – OptionalBOOLEANfield onsource_table; only rows where it isTrueare kept.
- Return type:
- Returns:
The newly added
DerivedTable.- Raises:
ValueError – If a table with the same
idalready exists.
- add_joined_table(id, join_conditions)[source]
Add a
JoinedTableto the model.A joined table is the result of joining two or more tables on a list of
JoinConditionrows.- Parameters:
id (
str) – Unique identifier for the joined table.join_conditions (
list[JoinCondition]) – One condition per joined table pairing. TheJoinTypeof each condition controls how unmatched rows are handled.
- Return type:
- Returns:
The newly added
JoinedTable.- Raises:
ValueError – If a table with the same
idalready exists.
- add_union_table(id, source_tables)[source]
Add a
UnionTableto the model.A union table stacks rows from multiple source tables. Pass a
UnionSourceinstead of a bareTablewhen 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 wrappedUnionSourceinstances) whose rows are stacked.
- Return type:
- Returns:
The newly added
UnionTable.- Raises:
ValueError – If a table with the same
idalready 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) –Trueto allow partial evaluation.
- set_data_validation_rule(named_value)[source]
Gate optimisation on a boolean named value.
Optimisation is allowed only while
named_valueevaluates toTrue. When it isFalseand the UI definition specifies a validation screen, the user is redirected there on attempting to start optimisation.- Parameters:
named_value (
Parameter|Calculation) – AParameterorCalculationof typeBOOLEAN.- Raises:
ValueError – If
named_valueis not of boolean data type.
- get_tables()[source]
Return every table that has been added to the model, in insertion order.
- get_table(id)[source]
Return the table with the given id.
- Parameters:
id (
str) – Identifier of the table to look up.- Return type:
- 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
ParameterorCalculation. Parameters are searched first, so a parameter is returned if both exist with the same id (whichadd_parameter/add_calculationwould 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_RANKamong every field, parameter, and calculation whose__invalid__formula is currentlyTrue, or0when nothing is invalid. Useful as the gating value forset_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
Calculationwhose integer value is the highest severity rank of any currently-invalid entity.
- 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 frombuild().scenarios/Initial/named-values.json— scenario-level named values (those added withmodel_level=False).model-data/named-values.json— model-level named values (those added withmodel_level=True).
- build()[source]
Build the JSON-compatible dict representation of the model.
On the first call, change-tracking metadata is resolved: tracked calculated fields have their formulas rewritten to reference the
*_TRACKING_*ids of any other tracked named values and fields. This step is idempotent and only runs once per builder.
- to_named_value_dict(model_level)[source]
Build the JSON-compatible dict of parameter values for one scope.
- Parameters:
model_level (
bool) – WhenTrue, include only model-level parameters (written tomodel-data/named-values.json). WhenFalse, include only scenario-level parameters (written toscenarios/Initial/named-values.json).- Return type:
- Returns:
{"values": {parameter_id: value_dict, ...}}.
- class Table(id)[source]
The base class for all table types.
This class defines the core structure and behavior of a table, including field management and relationships with derived tables.
- property key_column: str | None
The key column field ID used for object references, or
Noneif not set.
- property validation_group: str | None
The validation group identifier, or
Noneif not assigned to a group.
- property display_name: str
The human-readable display name for this table. Defaults to the table ID.
- set_key_column(key_column)[source]
Sets the key column for this table. Returns self.
- Return type:
- set_model_level(model_level)[source]
Sets whether this table is model-level. Returns self.
- Return type:
- set_validation_group(group)[source]
Sets the validation group for this table. Returns self.
- Return type:
- set_display_name(name)[source]
Sets the display name for this table. Returns self.
- Return type:
- set_export_as_key_column(export_as_key=True)[source]
- Configures the table to export its key column instead of the row number when generating
reports. Returns self.
- initialise_field(id, data_type)[source]
Registers a placeholder field with the given ID and data type.
Use this when a field must exist before its final definition is known — for example, when using PREV or NEXT, or to resolve circular dependencies in combo fields. The placeholder will be automatically replaced when add_calculated_field or add_combo_field is later called with the same id.
- add_data_field(id, data_type, tracking_group=None)[source]
Adds a data field to the table.
This method should be implemented by subclasses and is not valid for the base Table class.
- Raises:
NotImplementedError – Always raised since this method is not applicable to Table.
- Return type:
- add_object_reference_field(id, table, is_array=False, tracking_group=None)[source]
Adds an object reference field to the table.
- add_map_field(id, data_type, table, tracking_group=None)[source]
Adds a map field to the table.
- add_calculated_field(id, formula, order_index=None, description=None, tracking_group=None)[source]
Adds a CalculatedField to the table.
- get_field(id)[source]
Retrieves a field from the table.
- Parameters:
id (
str) – The ID of the field to retrieve.- Returns:
The field object matching the given ID.
- Return type:
- Raises:
ValueError – If the field does not exist in the table.
- get_fields()[source]
Retrieves all fields in the table.
- get_validation_state()[source]
Build a calculated field representing the maximum severity rank among all currently-invalid fields in this table.
For each field with validators,
COUNT(table[field__invalid__severity], True) > 0is used to check whether any row is invalid at that severity level. The result is a scalar formula — all rows will carry the same value — evaluating to the highestSEVERITY_RANKamong failing fields, or0when nothing is invalid.The result is registered in the table as a calculated field named
__validation_state__. Subsequent calls return the already-registered field without rebuilding it.- Returns:
A calculated field whose value is the highest severity rank of any currently-invalid field in this table.
- Return type:
- class Formula(data_type, formula_string)[source]
Represents a formula used in calculations or data processing.
- data_type
The type of data that the formula returns.
- Type:
- formula_string
The Excel formula as a string.
- Type:
- to_data_type()[source]
Retrieves the data type of the formula.
- Returns:
The data type associated with the formula.
- Return type:
BaseDataType
- class Field(id, table, data_type)[source]
Abstract base for a column on a
Table.Use the concrete subclasses
DataField,CalculatedField, andComboFieldrather than constructingFielddirectly. Every field has anid, an owningtable, and adata_type; optionally anorder_index, adescription, and zero or moreValidatorinstances (at most one perSeverity).- table_id
The owning table’s id.
- data_type
The
BaseDataTypeof this field.
- property tracking_group: str | None
Tracking-group identifier, or
Nonewhen change tracking is disabled.
- property tracking_id: str
ID of the matching tracking field, or empty string when this field is not tracked.
- set_order_index(idx)[source]
Set the field’s position within its table (lower values come first).
- Return type:
- set_tracking_group(group)[source]
Enable change tracking by assigning this field to a tracking group.
When set,
build()generates a sibling<group>_TRACKING_<id>field; references to other tracked fields within the same group are rewritten to their tracking ids.- Return type:
- to_data_type()[source]
- Return type:
BaseDataType
- add_validator(validator)[source]
Attach a
Validatorto this field.Each field may carry at most one validator per
Severity.- Raises:
ValueError – If a validator with the same severity is already attached.
- Return type:
- get_validation_fields(severity=None)[source]
Return the synthetic validation fields generated for this field’s validators.
- Parameters:
severity (
Severity|None) – When given, return only the validation fields for that severity. WhenNone, return oneValidationFieldsContainerper attached validator, sorted by ascending severity rank.- Return type:
list[ValidationFieldsContainer] |ValidationFieldsContainer|None- Returns:
A single
ValidationFieldsContainer, a list of them, orNoneif no validator matches.
- get_combined_message_field()[source]
Return a single calculated field combining all per-severity messages.
The combined field is a STRING_ARRAY ordered from highest to lowest severity (CRITICAL → ERROR → WARNING → INFO); blank messages are excluded. The field is registered on the table as
{id}__message__combinedon first call and cached for subsequent calls.
- class Calculation(id, formula, model_level=False, model=None)[source]
A calculation is one of the three basic objects that make up a V3 Model. It consists of a name, data_type, and a formula.
- id
The id or ID of the calculation.
- Type:
- formula
The formula defining the calculation.
- Type:
model_generator.structures.Formula
- depends_on_decision
Indicates if the calculation depends on a decision.
- Type:
- model_level
Indicates if the calculation is at the model level.
- Type:
- required_by_output
Indicates if the calculation is required by the output.
- Type:
- __init__(id, formula, model_level=False, model=None)[source]
- Parameters:
id (
str) – Unique identifier for this calculation. Must be a valid Python-style identifier.formula (
Formula) – The formula that defines the calculated value.model_level (
bool) – IfTrue, the calculation is model-level; otherwise scenario-level.model (
ModelBuilder|None) – TheModelBuilderthis calculation belongs to. Can be set later viaModelBuilder.add_calculation.
- property id: str
The unique identifier for this calculation.
- property tracking_group: str | None
The tracking group identifier, or
Noneif change tracking is not enabled.
- property tracking_id: str
The ID of the corresponding tracking calculation, or an empty string if not tracked.
- set_tracking_group(group)[source]
Sets the tracking group for this calculation. Returns self.
- Return type:
Calculation
- set_depends_on_decision(depends_on_decision)[source]
Sets whether this calculation depends on a decision variable.
- Return type:
Calculation
- set_required_by_output(required_by_output)[source]
Sets whether this calculation is required by the output.
- Return type:
Calculation
- to_data_type()[source]
- Return type:
BaseDataType
- add_validator(validator)[source]
Attach a validator to this named value.
Each named value can only have one validator per severity level. Attempting to add another validator with the same severity will raise a ValueError.
- Parameters:
validator (
Validator) – The validator instance to attach.- Raises:
ValueError – If a validator with the same severity has already been added to this field.
- Return type:
- get_validation_values(severity=None)[source]
Retrieve the validation values associated with this named value’s validators.
- Parameters:
severity (
Severity|None) – If provided, returns only the validation values for that severity level. If None, returns validation values for all attached validators.- Return type:
list[ValidationValuesContainer] |ValidationValuesContainer|None- Returns:
A list of
ValidationValuesContainerifseverityis None and validators exist.A single
ValidationValuesContainerif a validator matchingseverityis found.Noneif no validators are attached, or if no validator matches the given severity.
- get_combined_message_value()[source]
Returns a single calculated named value that combines all per-severity message values into one array, ordered from highest to lowest severity (CRITICAL → ERROR → WARNING → INFO). Blank messages are excluded from the array.
The resulting value is registered on the model with the ID
{id}__message__combinedand cached so subsequent calls return the same value without rebuilding it.- Returns:
The combined message calculated value, or
Noneif this named value has no validators.- Return type:
Calculation|Parameter|None- Raises:
NotImplementedError – If this named value has not yet been attached to a model.
- class Parameter(id, data_type, value=None, model_level=False)[source]
A parameter is one of the three basic objects that make up a model. It is the simplest of these three objects and consists only of a data_type, a id, as well as optional import_format and model_level.
- id
The id or ID of the parameter.
- Type:
- data_type
The type of data that the parameter takes.
- Type:
- model_level
Indicates if the parameter is at the model level.
- Type:
- __init__(id, data_type, value=None, model_level=False)[source]
- Parameters:
id (
str) – Unique identifier for this parameter. Must be a valid Python-style identifier.data_type (
BaseDataType) – The data type of the parameter value.value (
Any|None) – The initial value of the parameter, orNoneif not yet set.model_level (
bool) – IfTrue, the parameter is model-level; otherwise scenario-level.
- property id: str
The unique identifier for this parameter.
- property tracking_group: str | None
The tracking group identifier, or
Noneif change tracking is not enabled.
- property tracking_id: str
The ID of the corresponding tracking parameter, or an empty string if not tracked.
- set_tracking_group(group)[source]
Sets the tracking group for this parameter. Returns self.
- Return type:
Parameter
- set_model(model)[source]
Attach this parameter to a
ModelBuilder. Returns self.- Return type:
Parameter
- set_import_format(import_format)[source]
Sets the import format string for this parameter.
- Return type:
Parameter
- to_data_type()[source]
- Return type:
BaseDataType
- to_named_value_dict()[source]
Converts the Parameter object to a dictionary representation for JSON serialisation.
- add_validator(validator)[source]
Attach a validator to this named value.
Each named value can only have one validator per severity level. Attempting to add another validator with the same severity will raise a ValueError.
- Parameters:
validator (
Validator) – The validator instance to attach.- Raises:
ValueError – If a validator with the same severity has already been added to this field.
- Return type:
- get_validation_values(severity=None)[source]
Retrieve the validation values associated with this named value’s validators.
- Parameters:
severity (
Severity|None) – If provided, returns only the validation values for that severity level. If None, returns validation values for all attached validators.- Return type:
list[ValidationValuesContainer] |ValidationValuesContainer|None- Returns:
A list of
ValidationValuesContainerifseverityis None and validators exist.A single
ValidationValuesContainerif a validator matchingseverityis found.Noneif no validators are attached, or if no validator matches the given severity.
- get_combined_message_value()[source]
Returns a single calculated named value that combines all per-severity message values into one array, ordered from highest to lowest severity (CRITICAL → ERROR → WARNING → INFO). Blank messages are excluded from the array.
The resulting value is registered on the model with the ID
{id}__message__combinedand cached so subsequent calls return the same value without rebuilding it.- Returns:
The combined message calculated value, or
Noneif this named value has no validators.- Return type:
Calculation|Parameter|None- Raises:
NotImplementedError – If this named value has not yet been attached to a model.
- class UnionSource(source_table, mapping_key)[source]
A source table in a union. Multiple
UnionSourceinstances in aUnionTablemay reference the same underlying table, distinguished bymapping_key.- property source_table: Table
- class FieldMapping(union_source)
- add_map(field_name, source_field)
- build()
Serialise this object to a JSON-compatible dict.
Converts public, non-
Noneinstance attributes to camelCase keys. Recursively builds nestedBuildableobjects, convertsEnumvalues, and serialisesdate/time/datetimeinstances as lists of components.
- property mapping_key: str
mapping_key for this field mapping.
- Type:
Returns
- property source_table: Table
the source table for this field mapping.
- Type:
Returns
- class Validator(severity, custom_message=None, custom_summary_message=None)[source]
Abstract base class for field validators.
Validators check field values and generate error messages when validation fails. They can be combined using AND (&) and OR (|) operators to create complex validation rules.
- __init__(severity, custom_message=None, custom_summary_message=None)[source]
Initialize a validator.
- Parameters:
severity (
Severity) – The severity level of validation failures (INFO, WARNING, ERROR, CRITICAL).custom_message (
Formula|str|None) – Optional custom error message to use instead of the default message.custom_summary_message (
str|None) – Optional custom summary error message to use instead of the default summary message.
- summary_message: str
- invalid(field, table)[source]
Return a formula indicating whether the field is invalid
- Return type:
- message(field, table)[source]
Return a formula containing the message if the field is invalid
- class RangeValidator(severity, min_value, max_value)[source]
Validator that checks if a field value is within a specified range.
The range can have a min_value, max_value, or both bounds. Bounds can be static values or dynamic field references.
- __init__(severity, min_value, max_value)[source]
Initialize a range validator.
- allow_blank: bool
- min_bound_type: BoundType
- max_bound_type: BoundType
- set_allow_blank(allow_blank)[source]
Sets whether blank values are considered valid.
- Return type:
RangeValidator
- set_custom_message(custom_message)[source]
Sets a custom error message to use instead of the default.
- Return type:
RangeValidator
- set_custom_summary_message(custom_summary_message)[source]
Sets a custom summary error message to use instead of the default.
- Return type:
RangeValidator
- set_min_bound_type(min_bound_type)[source]
Sets whether the lower bound is inclusive or exclusive.
- Return type:
RangeValidator
- set_max_bound_type(max_bound_type)[source]
Sets whether the upper bound is inclusive or exclusive.
- Return type:
RangeValidator
- invalid(field, table)[source]
Return a formula indicating whether the field value or named value is outside the valid range.
- message(field, table)[source]
Return a formula containing the validation error message.
- class NonBlankValidator(severity, custom_message=None, custom_summary_message=None)[source]
Validator that checks if a field is not blank.
A field is considered blank if it is empty or null.
- invalid(field, table)[source]
Return a formula indicating whether the field or named value is null/empty. If array/map provided, performs the validation on each element of the array/map.
- message(field, table)[source]
Return a formula containing the validation error message.
- class UniqueValidator(severity, allow_blank=False, custom_message=None, custom_summary_message=None)[source]
Validator that checks if a field value is unique within the table.
A field is considered invalid if its value appears more than once across all rows in the table for that field.
- __init__(severity, allow_blank=False, custom_message=None, custom_summary_message=None)[source]
Initialize a Unique validator.
- invalid(field, table)[source]
Return a formula indicating whether the field value is duplicated in the table.
- message(field, table)[source]
Return a formula containing the validation error message.
- class ListValidator(severity, values, custom_message=None, custom_summary_message=None)[source]
Validator that checks if a field value is within a provided set of allowed values.
The list of allowed values must be non-empty and all values must share the same data type, consistent with the field being validated.
- __init__(severity, values, custom_message=None, custom_summary_message=None)[source]
Initialize a list validator.
- Parameters:
severity (
Severity) – The severity level of validation failures.values (
Sequence[Operand|str|int|float|bool]) – The sequence of allowed values. Must be non-empty and all elements must share the same data type.custom_message (
Formula|str|None) – Optional custom error message.custom_summary_message (
str|None) – Optional custom summary error message.
- Raises:
ValueError – If values is empty.
- invalid(field, table)[source]
Return a formula indicating whether the field value or named value is not in the allowed set. If array/map provided, performs the validation on each element of the array/map.
- message(field, table)[source]
Return a formula containing the validation error message.
- class LengthValidator(severity, length, custom_message=None, custom_summary_message=None)[source]
Validator that checks if an array field has a specified number of elements.
Only applicable to array fields. The field is considered invalid if its element count does not equal the expected length.
- __init__(severity, length, custom_message=None, custom_summary_message=None)[source]
Initialize a length validator.
- Parameters:
- Raises:
ValueError – If length is negative.
- invalid(field, table)[source]
Return a formula indicating whether the array length does not match the expected length.
- message(field, table)[source]
Return a formula containing the validation error message.
- class DerivedTable(id, source_table, group_by=None, filter_field=None)[source]
Represents a derived table that is based on another source table and supports grouping, sorting, and filtering.
- source_table_id: str
- sort_keys: list[_SortKey]
- grouping_configuration: _GroupingConfiguration | None
- add_source_fields(source_fields=None, include_validators=False)[source]
Adds fields to the current object from the source table or grouping configuration.
This method checks whether the source_fields parameter is provided. If source_fields is None, it adds all fields from the source table or grouped fields (depending on whether the grouping configuration is present). If source_fields is provided, it validates that each field is present in the available fields before adding it.
- Parameters:
- Raises:
ValueError – If Any field in source_fields is not found in the available fields.
Note
If _grouping_configuration is None, fields are taken from self.source_table._fields. If _grouping_configuration is not None, fields are taken from self.grouping_configuration.group_by_fields.
- add_sort_key(field, direction)[source]
Adds a sort key to the derived table.
- Parameters:
field (
Field) – The field to sort by.direction (
SortDirection) – The direction in which to sort.
- add_aggregated_field(id, source_field, aggregation_method, tracking_group=None)[source]
Adds an aggregated field to the table.
- Parameters:
id (
str) – The unique identifier for the aggregated field.source_field (
Field) – The source field that will be aggregated.aggregation_method (
AggregationMethod) – The method used to aggregate the source_field.tracking_group (
str|None) – Group identifier for change tracking.
- Raises:
ValueError – If no grouped fields are present in the table.
ValueError – If the aggregation method is not valid for the source field’s data type.
- Return type:
- class JoinedTable(id, join_conditions)[source]
Represents a table resulting from a join operation.
A JoinedTable is a table that is constructed by joining two or more other tables based on specific join conditions. A join operation combines rows from different tables based on a related field (column) between them. The join_conditions list defines how these tables are connected and which fields from the tables are used for the join.
Joins can be of different types, such as INNER, LEFT, RIGHT, and FULL, and they dictate how the rows from the tables are combined and which rows are included in the final result.
- A JoinCondition consists of the following:
left_table: The left table involved in the join.
left_field: The field in the left table that is used to match with the right table.
right_table: The right table involved in the join.
right_field: The field in the right table that is used to match with the left table.
join_type: The type of join (e.g., INNER, LEFT, RIGHT, FULL).
Multiple JoinCondition objects can be specified to represent more complex join scenarios. Each condition defines how a pair of tables are joined, and having multiple conditions allows for joining more than two tables at once, with each pair of tables joined based on the specific conditions defined. When there are multiple JoinCondition objects, the joins are performed in sequence, and the resulting table combines the results of all the joins.
- add_table_reference(source_table)[source]
Adds a reference to a table in the JoinedTable.
This method allows for adding a reference field for a source table that is part of the join conditions. If the source table is not part of the join conditions, a ValueError will be raised.
- Parameters:
source_table (
Table) – The table to be referenced.- Returns:
The reference field for the source table.
- Return type:
- Raises:
ValueError – If the source table is not present in any of the join conditions.
- class JoinCondition(left_table, left_field, right_table, right_field, join_type)[source]
Represents a condition for joining two tables.
- property left_table: Table
- property left_field: Field
- property right_table: Table
- property right_field: Field
Getting Started