The expression block
Expression is the library's block for "a few lines of code" in a model: one
formula over the block's inputs and named parameters, like Simulink's Fcn
block, Xcos's EXPRESSION block or an equation in a Modelica model. The formula
is parsed with Python's ast, checked against a fixed grammar and evaluated by
walking the checked tree with the backend's array functions (jax.numpy under
JAX). No source text is compiled to code or run, so a formula can say no more
than the grammar allows, and a model document holding one loads through
load_model_strict.
import jaxonomy
from jaxonomy.library import Expression, Integrator, Ramp
from jaxonomy.simulation import SimulatorOptions
b = jaxonomy.DiagramBuilder()
ramp = b.add(Ramp(start_value=0.0, slope=1.0, start_time=0.0, name="ramp"))
rate = b.add(Expression(
"up if u > limit else down",
input_names=("u",),
parameters={"up": 5.0, "down": -1.0, "limit": 2.5},
name="rate",
))
plant = b.add(Integrator(0.0, name="plant"))
b.connect(ramp.output_ports[0], rate.input_ports[0])
b.connect(rate.output_ports[0], plant.input_ports[0])
diagram = b.build()
results = jaxonomy.simulate(
diagram, diagram.create_context(), (0.0, 5.0),
options=SimulatorOptions(record_event_times=True),
recorded_signals={"y": plant.output_ports[0]},
)
print(results.event_times[0][0]) # 2.5 to 1e-9: the switching instant
print(results.outputs["y"][-1]) # 10.0 to 1e-6, -2.5 + 5 * 2.5
The grammar
| Allowed | Written |
|---|---|
| numbers | int and float literals, finite, at most 63 bits, read as floats |
| names | the block's inputs (input_names) and parameters (parameters) |
| arithmetic | -u, +u, a + b, a - b, a * b, a / b, a ** b |
| comparisons | < <= > >= == !=, chained as in Python (0 < u < 1); == and != are exact |
| logic | and, or, not; a number is true when it is not zero |
| a conditional | a if condition else b |
| functions | abs sqrt exp log log10 sin cos tan asin acos atan atan2 sinh cosh tanh min max, each on its positional arguments (atan2, min and max take two) |
Anything else raises ExpressionError when the block is built, naming the
offending node, its line and column (both from 1) and the reason:
Expression 'code': column 5, Attribute: an attribute access is not allowed (in 'u + np.pi') in block code with parameter expression
Refused, among others: an attribute (np.pi), a subscript (u[0]), an import,
a statement or an assignment, a lambda, a name that is neither an input nor a
parameter, a call to any other function (eval, open, __import__), a
keyword argument, a string or True/False literal, the operators
% // @ << >> | ^ & ~, is and in, more than 1000 characters, nesting deeper
than 32 levels, non-ASCII text, and a part made of numbers only whose value is
not finite (log(0), 9**9**9: a part made of numbers only is computed in
floating point, so a tower of powers overflows at once). Another language's operators, &&, ||, !, ? and
~=, are refused at their own column with what a formula writes instead:
and, or, not, a if condition else b, !=. An input or parameter name is a letter followed by
letters, digits or _; Python's keywords, the function names and the block's
own keywords are refused as names.
Values, gradients and events
- Element by element. Inputs and parameters broadcast as arrays do, so a vector input gives a vector output of the same shape.
- A real number. An integer or true/false result is given as a float, as
Simulink's Fcn gives a double, so
5 if u > 2.5 else -1ora and bfeeds an integrator; a float input keeps its precision. - Traceable. The output works under
jax.jit,jax.vmapandjax.grad. The parameters are dynamic: they are tuned or differentiated without rebuilding the block. A comparison passes no gradient; a conditional passes the gradient of the branch it selects. - Both branches are computed. As with
jnp.where, a branch that is not finite where it is not selected (sqrt(u) if u > 0 else 0atu < 0) makes the gradient there NaN. - Switching instants are events. A comparison, and a number read as true or
false, is a place where the output can jump. When the block's inputs vary
with time or continuous state and its output is read between samples (by an
ODE, or by a recorded signal), the block declares a zero-crossing event for
each one, as a
Comparatordoes, so the solver stops at the switching instant. The kinks ofabs,minandmaxare not events.
In a model document
The block is written as a core.Expression node: its formula is the string
parameter expression, its parameters are the node's other parameters, and its
inputs are the node's input ports, in order. Both load_model and
load_model_strict read the formula with the block's own grammar; a refusal
names the node, then the syntax and its column.