Skip to content

math_spec.program

The program: what a file declares, with names resolved and shapes fixed.

The second public state, and the one a consumer reads. A :class:Program is every declaration a file makes and no data at all; :func:~math_spec.lowering.to_program is the only thing that builds one, so nothing here re-checks a hand-built one.

Node and declaration classes are matched with isinstance. The rules a node's structure does not show are :func:children and :func:fan_in; the questions over the walk are :func:walk and the filters beside it. A resolved where arrives as a :class:Mask. Frozen dataclasses only — no execution logic, and nothing imported from a consumer. How a consumer reads one: docs/reference/language/reading.md.

Check = Increasing | Curved | AtLeastTwo | Contiguous module-attribute #

ConnectiveWhereNode = NotNode | AndNode | OrNode module-attribute #

ConstraintSense = ComparisonOperator module-attribute #

Coverage = _model.Coverage module-attribute #

Derivation = MaskOf | FirstOf | LastOf module-attribute #

DimensionDtype = _model.DimensionDtype module-attribute #

ExpressionNode = Constant | Parameter | Variable | Dual | Negate | Add | Multiply | Power | Divide | Sum | GroupSum | At | Translate | Window | Cases module-attribute #

FanIn = Literal['one-to-one', 'many-to-one', 'one-to-many'] module-attribute #

ObjectiveSense = Literal['minimize', 'maximize'] module-attribute #

ParameterDtype = _model.ParameterDtype module-attribute #

PredicateOperator = Literal['<=', '>=', '==', '!=', '<', '>'] module-attribute #

QUADRATIC_POSITIONS = frozenset(get_args(QuadraticPosition)) module-attribute #

QuadraticPosition = Literal['objective', 'constraint'] module-attribute #

TypedPredicateNode = ParameterComparisonNode | ParameterDefinedNode | VariableDefinedNode | DimensionComparisonNode | DimensionPositionNode | RelationComparisonNode | RelationPairComparisonNode | RelationDefinedNode module-attribute #

VariableAbsence = _model.VariableAbsence module-attribute #

VariableDomain = _model.VariableDomain module-attribute #

WhereNode = BooleanLiteralNode | DimensionPositionNode | ParameterDefinedNode | VariableDefinedNode | ParameterComparisonNode | DimensionComparisonNode | RelationComparisonNode | RelationPairComparisonNode | RelationDefinedNode | NotNode | AndNode | OrNode module-attribute #

Add(left, right) dataclass #

Bases: Expression

left instance-attribute #

right instance-attribute #

AndNode(left, right) dataclass #

left instance-attribute #

right instance-attribute #

At(operand, walks) dataclass #

Bases: Expression

Read operand through relations — the adjoint of :class:GroupSum.

Same tables, walked the other way: this consumes the dims in into and produces the dims in over, one value per coordinate because every walk reads value columns at a key the operand fixes (Walk.is_function_read). The join fans out, many over tuples sharing one into tuple — at each coordinate of the joined columns, which the operand carries and the result keeps. As on :class:GroupSum, walks is the fact and the three are read off it.

coordinate property #

into property #

operand instance-attribute #

over property #

walks instance-attribute #

AtLeastTwo(over, mask) dataclass #

Each curve has at least two breakpoints — every position along over, or those mask admits.

mask instance-attribute #

over instance-attribute #

BooleanLiteralNode(value) dataclass #

value instance-attribute #

Cases(regions) dataclass #

Bases: Expression

A value defined by region — exactly one region applies at each coordinate.

The regions are disjoint and total, so a consumer adds them rather than ranking them. Not a shape operator: every region spans the dims the expression does.

regions instance-attribute #

Constant(value) dataclass #

Bases: Expression

A scalar constant.

value instance-attribute #

ConstraintDeclaration(dims, lhs, sense, rhs, where=None) dataclass #

lhs sense rhs for each coord combination of dims.

Either side may carry variables and constants alike; which side a consumer gathers them onto is its own arrangement and not stated here. where masks out coord combinations (row absence, like variables).

dims instance-attribute #

lhs instance-attribute #

rhs instance-attribute #

sense instance-attribute #

where = None class-attribute instance-attribute #

Contiguous(mask, values) dataclass #

mask admits one consecutive run of at least one breakpoint per curve.

mask instance-attribute #

values instance-attribute #

Curved(x, y, over, curvature) dataclass #

y over x bends, along over, the way curvature says.

That is the shape the method is exact for. either is the hull's weaker condition: any single bend, so only a mixed curve fails it.

curvature instance-attribute #

over instance-attribute #

x instance-attribute #

y instance-attribute #

DimensionComparisonNode(name, op, value) dataclass #

Compare a dimension's own coordinates against a literal.

name instance-attribute #

op instance-attribute #

value instance-attribute #

DimensionDeclaration(relations=(), dtype='str') dataclass #

A dimension and the relations with a column over it.

dtype = 'str' class-attribute instance-attribute #

relations = () class-attribute instance-attribute #

DimensionPositionNode(name, op, position, partition=None) dataclass #

Compare where a row sits along a dimension against a position — position(snapshot) == 0.

Both sides are integers, negative counting from the end. With a partition the position is counted within each group the relation makes, walked as :class:Translate walks one: its consumed column is the key column over name, the group is its produced columns, and its joined columns are the other key columns, whose dimensions the frame carries.

name instance-attribute #

op instance-attribute #

partition = None class-attribute instance-attribute #

position instance-attribute #

Divide(numerator, divisor) dataclass #

Bases: Expression

Quotient numerator / divisor, the divisor variable-free wherever the math reads it (math_spec.degree).

divisor instance-attribute #

numerator instance-attribute #

Dual(constraint) dataclass #

Bases: Expression

A constraint's dual — its shadow price, read after the solve.

Stands only under an :class:ExpressionDeclaration the math never reads: the loader refuses dual() anywhere a solver ingests. One value per coordinate of the named constraint's own dims frame, which is what :func:fan_in answers one-to-one for — the leaf reshapes nothing, like a parameter.

constraint instance-attribute #

Expression() dataclass #

Base class for expressions over variables and parameters.

The degree rules (math_spec.degree) hold on every tree the math reads — :attr:Program.expressions, a bound, and a named expression that is in_math — affine but where a :class:QuadraticPosition admits a :class:Multiply of two variable-carrying operands. A :class:ExpressionDeclaration the math never reads is held to none of them. No node records which tree it stands in.

ExpressionDeclaration(expression, in_math) dataclass #

A named quantity — one the math reads, or one only read back after a solve.

in_math where the objective or a constraint inlines it, directly or through another entry or a macro; its body then stands inside :attr:Program.expressions and is held to the degree rules where it is read. Otherwise nothing a solver sees contains it: it is a reported quantity, its body held to no degree, the one place a :class:Dual may stand. A bound and a where name no entry, so neither decides this.

expression instance-attribute #

in_math instance-attribute #

FirstOf(block, mask) dataclass #

A bool parameter marking, per curve, the first breakpoint mask admits.

block instance-attribute #

mask instance-attribute #

Footprint(quadratic, domains, sos_types, shapes) dataclass #

Which of the language's constructs one program uses.

A subset, never the whole: an empty field says this program does not use the construct.

ATTRIBUTE DESCRIPTION
quadratic

Each position a product of two variable-carrying operands stands in; empty is affine throughout.

TYPE: frozenset[QuadraticPosition]

domains

Every domain declared.

TYPE: frozenset[VariableDomain]

sos_types

The order of each special-ordered set declared.

TYPE: frozenset[Literal[1, 2]]

shapes

Every expression node kind that appears.

TYPE: frozenset[type[ExpressionNode]]

domains instance-attribute #

quadratic instance-attribute #

shapes instance-attribute #

sos_types instance-attribute #

GroupSum(operand, walks) dataclass #

Bases: Expression

Sum operand through relations, consuming the dims over and producing into.

walks says, per relation, which columns are consumed, which produced and which joined on, and is the one fact the node holds: coordinate names the relations, over is the dims every walk consumes and into the dims they produce, in walk order, so that several coordinates are one grouping into a product of targets, consumed in a single join. The result replaces every dim in over with every dim in into. The join keys on the consumed columns and every joined column, and on a produced column too where the operand already carries its dimension.

coordinate property #

into property #

operand instance-attribute #

over property #

walks instance-attribute #

Increasing(parameter, over) dataclass #

parameter is strictly increasing along over within each curve — the x-axis a method sorts by.

over instance-attribute #

parameter instance-attribute #

LastOf(block, mask) dataclass #

Its sibling for the last breakpoint.

block instance-attribute #

mask instance-attribute #

Mask(root) dataclass #

A resolved where and the questions the language answers about it.

root is the predicate a consumer dispatches on with isinstance; every question below is derived from it. Construction folds, so a boolean literal stands at the root or nowhere in it, and refuses an unresolved tree.

ATTRIBUTE DESCRIPTION
root

The resolved predicate the mask restricts rows by, folded.

TYPE: WhereNode

atoms cached property #

The mask's leaves, connectives removed — the one walk the other questions read.

Held rather than re-walked: construction takes this walk anyway, to refuse an unresolved tree, and a mask cannot change afterwards.

conjuncts property #

The predicates the mask joins with AND — its AND spine flattened, stopping at an OR or a NOT.

dims property #

The dims the mask is read at — the union of what each leaf carries.

Empty for a mask over nothing but literals. Read off the leaves, which resolution stamped with their declarations' dims, so a predicate built from resolved pieces answers exactly as a declaration's own does.

names_read property #

The parameters, relations and variables the mask names.

root instance-attribute #

MaskOf(block, values) dataclass #

A bool parameter true wherever values has a row.

The mask a points: naming one of the block's own breakpoints derives: the curve runs as far as its values do. values is the name the file wrote, so a refusal about the mask can say it.

block instance-attribute #

values instance-attribute #

Multiply(left, right) dataclass #

Bases: Expression

Product of two operands.

Affine where at least one factor is variable-free; degree 2 where neither is, which math_spec.degree admits in a :data:QuadraticPosition alone.

left instance-attribute #

right instance-attribute #

Negate(operand) dataclass #

Bases: Expression

operand instance-attribute #

NotNode(operand) dataclass #

operand instance-attribute #

ObjectiveDeclaration(sense, expression) dataclass #

Objective — scalar, every reduction in it one the file wrote.

expression instance-attribute #

sense instance-attribute #

OrNode(left, right) dataclass #

left instance-attribute #

right instance-attribute #

Parameter(name) dataclass #

Bases: Expression

A parameter reference — contributes to the constant part.

name instance-attribute #

ParameterComparisonNode(name, op, value, dims) dataclass #

Compare a parameter against a literal, element-wise.

dims instance-attribute #

name instance-attribute #

op instance-attribute #

value instance-attribute #

ParameterDeclaration(dims, dtype='float', derivation=None, coverage='total') dataclass #

Shape declaration; data is bound at execution time by name.

dtype is what the declaration claims the values are, and a consumer binding data refuses a column that is not it — so the declaration is what is read, rather than whatever the column happens to hold.

coverage = 'total' class-attribute instance-attribute #

derivation = None class-attribute instance-attribute #

dims instance-attribute #

dtype = 'float' class-attribute instance-attribute #

ParameterDefinedNode(name, dims) dataclass #

True wherever the named parameter is non-null and finite.

dims is the parameter's own, copied off the declaration during resolution; every leaf below that names a declaration carries its dims (or over) the same way.

dims instance-attribute #

name instance-attribute #

PiecewiseDeclaration(over, method, breakpoints, checks) dataclass #

A piecewise: block, kept as the facts a consumer binding its data reads.

The expansion lowered the links into constraints and emitted the parameters it needs — each of those says how it is filled, on its own :attr:ParameterDeclaration.derivation. What is left here is the curve and what the block assumes of it.

ATTRIBUTE DESCRIPTION
over

The breakpoint dimension.

TYPE: str

method

How the weights are restricted.

TYPE: PiecewiseMethod

breakpoints

The links' values parameters, in link order.

TYPE: tuple[str, ...]

checks

What the block assumes of the numbers, each carrying its own subjects, for the consumer holding them to check.

TYPE: tuple[Check, ...]

breakpoints instance-attribute #

checks instance-attribute #

method instance-attribute #

over instance-attribute #

Power(base, exponent) dataclass #

Bases: Expression

base ** exponent, both variable-free wherever the math reads it.

The language refuses a variable anywhere under it (math_spec.degree), so in the program a solver sees it is degree 0 and folds to one number per coordinate like any other parameter arithmetic.

base instance-attribute #

exponent instance-attribute #

Program(*, parameters, variables, constraints, objective, dimensions=Sealed({}), sos=Sealed({}), piecewise=Sealed({}), named_expressions=Sealed({})) dataclass #

A complete declarative description of a mathematical program, with no data in it.

Every group of declarations is keyed by the name the file wrote, in the order it wrote them, and is read-only: the mappings are wrapped at construction, so a consumer cannot rewrite what another consumer reads. A whole program is not hashable — the declarations and expression nodes inside it are, which is what dedup and memoisation ask for.

constraints instance-attribute #

dimensions = Sealed({}) class-attribute instance-attribute #

expressions property #

Every expression a row is built from — the objective and both sides of each constraint.

A :attr:named_expressions entry builds no row and is not among them.

footprint cached property #

Which constructs this program uses — walked once, then held.

named_expressions = Sealed({}) class-attribute instance-attribute #

objective instance-attribute #

parameters instance-attribute #

piecewise = Sealed({}) class-attribute instance-attribute #

relations property #

Every relation in the program by name, each once — a relation keyed by two dimensions sits under both.

separability cached property #

Every axis, to what building it a window at a time asks and what it would break.

The locality :doc:the ceiling </about/ceiling> argues in — pointwise, bounded halo, global — asked about the axes rather than about the operators, so a driver may know before it cuts a horizon whether every row it builds is complete inside some window.

A reduction means opposite things by position, which is the whole of the care: in a constraint a sum over the axis ties every window to every other, and in the objective it is additively separable, an objective being a sum already.

Every declared dimension has an entry, an axis nothing mentions being trivially windowable. Walked once and held, like :attr:footprint and for the same reason — a program cannot change after construction — and answering for every axis costs what answering for one did, every construct that ties an axis naming the axis it ties (#248).

sos = Sealed({}) class-attribute instance-attribute #

variables instance-attribute #

dimension(name) #

Source code in src/math_spec/program.py
def dimension(self, name: str) -> DimensionDeclaration:
    return _declared(self.dimensions, name, 'dimension')

parameter(name) #

Source code in src/math_spec/program.py
def parameter(self, name: str) -> ParameterDeclaration:
    return _declared(self.parameters, name, 'parameter')

variable(name) #

Source code in src/math_spec/program.py
def variable(self, name: str) -> VariableDeclaration:
    return _declared(self.variables, name, 'variable')

Reach(label, name, kind) dataclass #

One read along an axis whose distance only data can say.

ATTRIBUTE DESCRIPTION
label

The declaration reading, as the lowering's messages label it.

TYPE: str

name

The parameter or relation that says how far.

TYPE: str

kind

An offset is a parameter's values, which :meth:Separability.resolved folds in; a partition and a coordinate are a relation's groups, which it does not.

TYPE: Literal['offset', 'partition', 'coordinate']

kind instance-attribute #

label instance-attribute #

name instance-attribute #

Region(when, value) dataclass #

One region of a :class:Cases: where it applies, and the value there.

when is stated on every region; the one the file wrote as otherwise: carries the negation of the others.

value instance-attribute #

when instance-attribute #

RelationComparisonNode(name, column, op, value, dims=()) dataclass #

Compare one value column of a keyed relation against a literal — period_of == 2030.

column is the role read, and dims the dimensions of the key columns: the leaf is read at them, one value per coordinate.

column instance-attribute #

dims = () class-attribute instance-attribute #

name instance-attribute #

op instance-attribute #

value instance-attribute #

RelationDeclaration #

Bases: NamedTuple

One declared relation: a relation over its columns, single-valued per key.

columns binds each role to its dimension in the order the table carries them; key is the roles a row is identified by, empty for a bare relation. Every value is checked at bind to be a label of its column's dimension, and a keyed table to have one row per key tuple — which keeps a mistyped label from silently dropping its terms in the join that places them, and is what lets at read one value.

columns instance-attribute #

coverage = 'total' class-attribute instance-attribute #

dims property #

key = () class-attribute instance-attribute #

name instance-attribute #

roles property #

values property #

The roles the key determines.

dim(role) #

Source code in src/math_spec/program.py
def dim(self, role: str) -> str:
    return dict(self.columns)[role]

RelationDefinedNode(name, dims=()) dataclass #

True where the relation has a row at the frame's coordinates.

dims is what the frame supplies: the key's dimensions for a keyed relation, whose row is then the one the key finds; every column's for a bare relation, where a row is the whole tuple.

dims = () class-attribute instance-attribute #

name instance-attribute #

RelationPairComparisonNode(name, column, other, other_column, op, dims=()) dataclass #

Compare a value column of one keyed relation with one of another — from_bus != to_bus — row by row on the key.

Both keys are over the same dims, and the two columns are over one dimension, so a match is possible at all.

column instance-attribute #

dims = () class-attribute instance-attribute #

name instance-attribute #

op instance-attribute #

other instance-attribute #

other_column instance-attribute #

Separability(dimension, ahead, coupled, undecided, restarts) dataclass #

What building one dimension a window at a time asks of a driver, and what it would break.

A rolling-horizon or myopic driver cuts an axis into windows and builds each on its own. What the program can say is whether every row it builds is then complete inside some window: how far a row reads ahead along the axis, and which declarations tie the axis together so that no window holds them. It cannot say whether the windowed answer is the one a whole-horizon solve would give — a store carried over one row windows cleanly, and a rolling solve of it is still a different answer — which is the driver's design and not the model's.

What a row reads behind is not reported. A window starts where the driver puts it, and what its first rows meet there is the edge policy: the opening state a rolling horizon seeds, and the driver's to carry.

ATTRIBUTE DESCRIPTION
dimension

The axis asked about.

TYPE: str

ahead

Coordinates a window must see after its last row for every row it builds to be complete — what a negative shift reads. 0 is pointwise; a shift of -2 is 2.

TYPE: int

coupled

Each declaration that ties the axis together, to what ties it and the one modelling change that would not: a sum over the axis in a constraint, a grouping that consumes it, a wrapped translation, a set. No window satisfies these, and no rewrite here would keep the model's meaning, so the remedy is named rather than applied.

TYPE: Mapping[str, str]

undecided

Each read along the axis whose reach only data can say — a named offset, a partition whose groups a window may cut, a read through a relation at a coordinate the data chooses. :meth:resolved folds a parameter's values in.

TYPE: tuple[Reach, ...]

restarts

Each declaration counting a position along the axis, which a window restarts at its first row. Whether that is wanted — a seed once per window, or once per horizon — is the modeller's, so it is reported rather than refused.

TYPE: Mapping[str, str]

ahead instance-attribute #

coupled instance-attribute #

dimension instance-attribute #

restarts instance-attribute #

undecided instance-attribute #

windowable property #

Whether every row builds complete inside a window looking :attr:ahead past its last row.

False while a reach is :attr:undecided, which a driver holding the data may resolve; :attr:restarts do not count against it.

resolved(least) #

The same verdict with each named offset folded into :attr:ahead.

A driver holding the data reads the least value of each parameter an :attr:undecided reach names and hands it here, so the rule that turns a value into a reach — a negative offset reads ahead by that much, a positive one reads behind and asks nothing — has one home.

PARAMETER DESCRIPTION
least

Parameter name to the least of its values. A reach through a relation — a partition, a coordinate — cannot be folded this way and stays undecided, as does a parameter left out.

TYPE: Mapping[str, int]

RAISES DESCRIPTION
KeyError

A name no undecided reach along this axis waits on.

Source code in src/math_spec/program.py
def resolved(self, least: Mapping[str, int]) -> Separability:
    """The same verdict with each named offset folded into :attr:`ahead`.

    A driver holding the data reads the least value of each parameter an
    :attr:`undecided` reach names and hands it here, so the rule that
    turns a value into a reach — a negative offset reads ahead by that
    much, a positive one reads behind and asks nothing — has one home.

    Args:
        least: Parameter name to the least of its values. A reach through
            a relation — a partition, a coordinate — cannot be folded this
            way and stays undecided, as does a parameter left out.

    Raises:
        KeyError: A name no undecided reach along this axis waits on.
    """
    waiting = {reach.name for reach in self.undecided if reach.kind == 'offset'}
    for name in least:
        if name not in waiting:
            raise KeyError(
                f"'{name}' is not a parameter an undecided reach along '{self.dimension}' waits on. "
                + did_you_mean(name, sorted(waiting))
            )
    folded = {reach for reach in self.undecided if reach.kind == 'offset' and reach.name in least}
    ahead = max([self.ahead, *(-least[reach.name] for reach in folded)])
    return replace(self, ahead=ahead, undecided=tuple(r for r in self.undecided if r not in folded))

SosDeclaration(variable, over, sos_type, big_m=None) dataclass #

One special-ordered set per coordinate of the variable's dims minus over.

The only declaration that adds neither a column nor a row: it names columns a consumer already has and says what may be nonzero among them. Which dims those are is the variable's own dims and is read from it: a copy here would be a second home for a fact (:meth:Program.variable).

big_m caps the linking coefficient a consumer without the concept reformulates with, and is None where the variable's own upper bound is the only cap.

big_m = None class-attribute instance-attribute #

over instance-attribute #

sos_type instance-attribute #

variable instance-attribute #

Sum(operand, over) dataclass #

Bases: Expression

Sum operand over the named dims, removing them from the result.

operand instance-attribute #

over instance-attribute #

Translate(operand, dimension, offset, wrap, fill=None, partition=None) dataclass #

Bases: Expression

Re-index along one dimension: the result at t is operand at t - offset.

wrap is edge='wrap' in the file: periodic, and stated on every node. fill is what an acyclic shift leaves behind: None leaves the vacated positions absent, so the row drops; a number makes them present and contribute it. Always None under wrap.

offset is an integer, or the name of an integer parameter that does not depend on dimension and carries its sign in the values.

partition is a relation walked along dimension — its consumed column is a key over that dimension, its produced columns are the group — and the translation then happens inside each group: the neighbour is the one before in the same group, the edge is the group's, and a wrap closes each group onto itself. A coordinate the relation sends nowhere reaches nothing.

dimension instance-attribute #

fill = None class-attribute instance-attribute #

offset instance-attribute #

operand instance-attribute #

partition = None class-attribute instance-attribute #

wrap instance-attribute #

Variable(name) dataclass #

Bases: Expression

A variable reference — one term per existing variable row.

name instance-attribute #

VariableDeclaration(dims, where=None, lower=(lambda: Constant(float('-inf')))(), upper=(lambda: Constant(float('inf')))(), domain='continuous', absence='undefined') dataclass #

absence = 'undefined' class-attribute instance-attribute #

dims instance-attribute #

domain = 'continuous' class-attribute instance-attribute #

lower = field(default_factory=lambda: Constant(float('-inf'))) class-attribute instance-attribute #

upper = field(default_factory=lambda: Constant(float('inf'))) class-attribute instance-attribute #

where = None class-attribute instance-attribute #

VariableDefinedNode(name, dims) dataclass #

True at the coordinates where the named variable exists.

dims instance-attribute #

name instance-attribute #

Walk #

Bases: NamedTuple

One relation as an operator walks it — which columns are consumed, which produced, which joined on.

consumed, produced and joined are roles — column names of relation, which binds every role to its dimension and names the key. joined is the key roles not walked (every role, for a bare relation): the join keys on them, and a value role not walked is not read. For a partition (shift, sum_back, position) consumed is the key role over the dimension walked and produced the value roles that make the group — every value role unless the call named some with within=.

consumed instance-attribute #

consumed_dims property #

is_function_read property #

Whether the walk reads one value per coordinate: the key lies inside what is fixed.

joined instance-attribute #

joined_dims property #

key property #

name property #

produced instance-attribute #

produced_dims property #

relation instance-attribute #

roles property #

values property #

dim(role) #

The dimension role is bound to.

Source code in src/math_spec/program.py
def dim(self, role: str) -> str:
    """The dimension *role* is bound to."""
    return self.relation.dim(role)

Window(operand, dimension, width, wrap, partition=None) dataclass #

Bases: Expression

Sum operand over a trailing window along one dimension.

The result at t is the sum of the operand at every position from t - width + 1 through t, so a width of 1 is the operand itself. The dimension survives: this replicates terms onto the positions that can see them rather than reducing anything away.

width is a whole number, or the name of an integer parameter when the window differs per entity — a minimum up time, a rolling budget, a delivery horizon. A named width may not depend on the dimension being summed over.

wrap says whether the window reaches around the start of the axis instead of stopping short at it, and is stated on every node.

partition names a relation over that dimension, and the window then stops at each group's edge. Positions are counted inside the group, so a coordinate the relation places nowhere reaches nothing — not even itself.

dimension instance-attribute #

operand instance-attribute #

partition = None class-attribute instance-attribute #

width instance-attribute #

wrap instance-attribute #

carries_variable(expression) #

Whether a variable appears anywhere under expression.

Source code in src/math_spec/program.py
def carries_variable(expression: ExpressionNode) -> bool:
    """Whether a variable appears anywhere under *expression*."""
    return any(isinstance(node, Variable) for node in walk(expression))

check_message(block, pw, check) #

The sentence a consumer raises when the data bound to block fails check.

The language's own wording, so every consumer refuses in the same words; a consumer appends what it saw.

Source code in src/math_spec/program.py
def check_message(block: str, pw: PiecewiseDeclaration, check: Check) -> str:
    """The sentence a consumer raises when the data bound to *block* fails *check*.

    The language's own wording, so every consumer refuses in the same words;
    a consumer appends what it saw.
    """
    ctx = f"piecewise '{block}'"
    match check:
        case Increasing(parameter, over):
            return (
                f"{ctx}: method: {pw.method} requires strictly increasing breakpoints in '{parameter}' along '{over}'"
            )
        case Curved(x, y, over, curvature):
            shape = 'a single bend' if curvature == 'either' else f'a {curvature} curve'
            return (
                f"{ctx}: method: {pw.method} is exact only for {shape}, and '{y}' over '{x}' along "
                f"'{over}' is not one, so the answer is wrong rather than loose. Use method: adjacency "
                f'or sos2, which take a curve of any shape.'
            )
        case AtLeastTwo():
            return (
                f'{ctx}: method: lp needs at least two breakpoints per curve — the method *is* its segment '
                f'lines, so a curve with no segment states nothing and leaves the bounded link on its own '
                f'bound. Use method: adjacency, sos2 or convex, which pin it to the points it does have.'
            )
        case Contiguous(mask, values):
            return (
                f"{ctx}: points: '{values if values is not None else mask}' must mark a consecutive run of at "
                f'least one breakpoint per curve — the chord row joins a breakpoint to the one before it, and '
                f"the domain rows sit on the curve's own first and last."
            )
        case _:
            assert_never(check)

children(expression) #

The sub-expressions of expression — what every walk recurses through.

Source code in src/math_spec/program.py
def children(expression: ExpressionNode) -> tuple[ExpressionNode, ...]:
    """The sub-expressions of *expression* — what every walk recurses through."""
    if isinstance(expression, Negate):
        return (expression.operand,)
    if isinstance(expression, (Add, Multiply)):
        return (expression.left, expression.right)
    if isinstance(expression, Divide):
        return (expression.numerator, expression.divisor)
    if isinstance(expression, Power):
        return (expression.base, expression.exponent)
    if isinstance(expression, (Sum, GroupSum, At, Translate, Window)):
        return (expression.operand,)
    if isinstance(expression, Cases):
        return tuple(region.value for region in expression.regions)
    if isinstance(expression, (Constant, Parameter, Variable, Dual)):
        return ()
    assert_never(expression)

divisor_parameters(*expressions) #

Every parameter named anywhere in a divisor under expressions.

Source code in src/math_spec/program.py
def divisor_parameters(*expressions: ExpressionNode) -> frozenset[str]:
    """Every parameter named anywhere in a divisor under *expressions*."""
    return frozenset().union(*(parameters_of(q.divisor) for q in quotients(*expressions)))

fan_in(expression) #

How expression's output rows relate to its input slots.

For the absence rules, both classes other than 'one-to-one' sum several input slots into an output row.

Source code in src/math_spec/program.py
def fan_in(expression: ExpressionNode) -> FanIn:
    """How *expression*'s output rows relate to its input slots.

    For the absence rules, both classes other than ``'one-to-one'`` sum
    several input slots into an output row.
    """
    if isinstance(expression, (Sum, GroupSum)):
        return 'many-to-one'
    if isinstance(expression, Window):
        return 'one-to-many'
    if isinstance(
        expression,
        (Constant, Parameter, Variable, Dual, Negate, Add, Multiply, Power, Divide, At, Translate, Cases),
    ):
        return 'one-to-one'
    assert_never(expression)

is_quadratic(expression) #

Whether expression contains a product of two variable-carrying operands.

A structural question over the program, and unrelated consumers ask it — what a solver must support, which declarations to build last, whether this form can be represented at all — so it is answered once here beside the other walks rather than once per consumer in its own terms.

Whether a degree may be written is the language's verdict, and this is not a second opinion on it: by the time a program exists the question is which shape the expression has, and the program is what is in hand to answer it.

Source code in src/math_spec/program.py
def is_quadratic(expression: ExpressionNode) -> bool:
    """Whether *expression* contains a product of two variable-carrying operands.

    A structural question over the program, and unrelated consumers ask it —
    what a solver must support, which declarations to build last, whether this
    form can be represented at all — so it is answered once here beside the
    other walks rather than once per consumer in its own terms.

    Whether a degree *may be written* is the language's verdict, and this is
    not a second opinion on it: by the time a program exists the question is
    which shape the expression has, and the program is what is in hand to
    answer it.
    """
    return any(
        isinstance(node, Multiply) and all(carries_variable(side) for side in (node.left, node.right))
        for node in walk(expression)
    )

parameters_of(*expressions) #

Every parameter named anywhere under expressions.

Source code in src/math_spec/program.py
def parameters_of(*expressions: ExpressionNode) -> frozenset[str]:
    """Every parameter named anywhere under *expressions*."""
    return frozenset(node.name for node in walk(*expressions) if isinstance(node, Parameter))

quotients(*expressions) #

Every division under expressions, each kept whole.

The divisor and the numerator answer different questions and one consumer needs them paired: a divisor is judged against the rows the declaration builds narrowed by the variables in its own numerator, which the flat :func:divisor_parameters cannot say.

Source code in src/math_spec/program.py
def quotients(*expressions: ExpressionNode) -> tuple[Divide, ...]:
    """Every division under *expressions*, each kept whole.

    The divisor and the numerator answer different questions and one consumer
    needs them paired: a divisor is judged against the rows the declaration
    builds *narrowed by the variables in its own numerator*, which the flat
    :func:`divisor_parameters` cannot say.
    """
    return tuple(node for node in walk(*expressions) if isinstance(node, Divide))

variables_of(*expressions) #

Every variable named anywhere under expressions.

Source code in src/math_spec/program.py
def variables_of(*expressions: ExpressionNode) -> frozenset[str]:
    """Every variable named anywhere under *expressions*."""
    return frozenset(node.name for node in walk(*expressions) if isinstance(node, Variable))

walk(*expressions) #

Every node under expressions, each expression itself included, parents first.

The traversal every question about a program is a filter of — which names it mentions, whether a variable stands under it, which divisions it contains. One generator rather than that five-line recursion once per question: how a program is traversed is one fact, so a node kind :func:children learns to descend into reaches every caller at once rather than the callers that remembered.

Source code in src/math_spec/program.py
def walk(*expressions: ExpressionNode) -> Iterator[ExpressionNode]:
    """Every node under *expressions*, each expression itself included, parents first.

    The traversal every *question* about a program is a filter of — which names
    it mentions, whether a variable stands under it, which divisions it
    contains. One generator rather than that five-line recursion once per
    question: how a program is traversed is one fact, so a node kind
    :func:`children` learns to descend into reaches every caller at once
    rather than the callers that remembered.
    """
    for expression in expressions:
        yield expression
        yield from walk(*children(expression))

where_children(where) #

The predicates under where — a connective's operands, and nothing under a leaf.

What every walk over a predicate recurses through, as :func:children is for an expression. A leaf has nothing under it whether or not it is resolved, so the grammar measures its own output with this too.

Source code in src/math_spec/program.py
def where_children(where: WhereNode) -> tuple[WhereNode, ...]:
    """The predicates under *where* — a connective's operands, and nothing under a leaf.

    What every walk over a predicate recurses through, as :func:`children` is
    for an expression. A leaf has nothing under it whether or not it is
    resolved, so the grammar measures its own output with this too.
    """
    if isinstance(where, NotNode):
        return (where.operand,)
    if isinstance(where, (AndNode, OrNode)):
        return (where.left, where.right)
    return ()