Skip to content

Expression Language ‐ How Its Built

James Dunkerley edited this page Nov 20, 2026 · 3 revisions

Home · Architecture · Backend core

In short

  • One language serves two purposes: a custom constraint added to the optimisation, and a derived value (a custom statistic) worked out from a run's results.
  • The grammar is one contract in contracts/grammar/, and a Python parser and a TypeScript parser are generated from it.
  • tz_ps_expressions parses, checks and evaluates. A framework package answers questions about names and never sees the expression text.
  • The expression language describes the language for a modeller: what to write, with examples.

The contract

The contract is contracts/grammar/:

File Holds
Expression.g4 An ANTLR grammar. A constraint is expression sense expression; a derived value is one expression
functions.json The function table
messages.json Every error message
cases.json Conformance cases

Two parsers are generated from it:

  • Python, by make grammar, into tz_ps_expressions/_generated/.
  • TypeScript, in frontend-sdk, for the editor.

Both test suites read cases.json, and both word their errors from messages.json. The HTTP API and the contracts describes the generators and the drift checks.

What an expression looks like

  • An expression refers to values as Type[filters].attribute.
  • The selection is a list of names, or filters such as carrier = "wind".
  • It combines values with arithmetic, and with functions that take over= to say which dimension to aggregate.

Who does what

The work is split across three layers:

Layer What it does
tz_ps_models/expressions.py Holds the reference types (Quantity, Selection, Filter), the value grid Cells, and the lookup Protocols ConstraintLookup and ValueLookup
A framework package Implements the lookups. It says what an attribute is and which components a selection matches, and it never sees the expression text
tz_ps_expressions Parses, checks shape and dimensions (list_constraint_problems, list_derived_value_problems), and evaluates (calculate_derived_value)

Measures are declared in the shared catalogue, tz_ps_expressions/measures.py, where each Measure names the frameworks that provide it.

The stages an expression passes through

  1. Check. tz_ps_conductor/expression_checks.py takes the framework's lookup and calls the shared check.
    • An error raises InvalidConstraintsError or InvalidDerivedValuesError.
    • The check runs on a model built without its series.
  2. Solve. Each solver parses the constraints again and compiles them.
    • tz_ps_solver_pypsa compiles them onto the linopy model.
    • tz_ps_files_calliope compiles them into Calliope maths.
  3. Read. tz_ps_conductor/derived_value_results.py evaluates a derived value over a stored version's inputs, outputs and measures, for Project.calculate_derived_values.

Clone this wiki locally