Skip to content

Python API

This page is the reference for running a spec from Python: every public name, rendered from its docstring. A spec is the YAML file; what it may contain is the language.

import specsolve as sps

sps.check('spec.yaml')  # compiles? no data needed

result = sps.solve('spec.yaml', sources)
result.objective
result.primal('p')  # a polars.DataFrame
result.dual('power_balance')

Reference

Every public name, rendered from its docstring. The glossary defines model, result, sink and the other house terms the entries use.

Run a spec

check

check(spec, sink=None)

Parse, validate and lower a spec; attach no data.

The CI verb: with no data and no solver, a spec repository validates every commit. Every other verb reads the spec through the same door, so what this refuses they refuse too.

With sink, also: will that sink take it? Bare check says nothing about portability. The answer is read off a declared table with no data attached, so it needs no solver installed, and solve and write read the same table, so the refusal comes whether or not it was asked for. The solver-independent advice is issued either way.

PARAMETER DESCRIPTION
spec

A YAML path, a mapping, or a Spec — what mathspec.to_spec takes, so a framework that emits declarations passes the mapping and writes no file. A Spec is not read again. A lowered Program is not taken. A piecewise: block is written out first: to_spec(spec).expand('piecewise') keeps every sos: set for a sink that takes one, and to_spec(spec).expand() writes the sets out too, as binaries every sink takes.

TYPE: Buildable

sink

A solver name (highs, gurobi, xpress) or an output suffix (.lp, .mps). None asks only whether the spec is sayable.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
Program

The lowered program: what a build reads rows off, for reading the plan.

Program

No verb takes it back; keep the Spec for that. It is the

Program

language's own type — typeset it, or read its declarations, through

Program

mathspec.

RAISES DESCRIPTION
LanguageError

A construct outside the streaming language, or a piecewise: block still to be written out.

SpecsolveError

A sink that cannot take this spec, naming the construct and the sinks that do; a name belonging to no sink; or two declarations whose names differ only by case.

ValueError

A schema or expression that does not parse.

WARNS DESCRIPTION
SpecsolveWarning

Advice short of an error — a declared dimension nothing uses as an axis, a variable the objective drives to infinity with nothing to stop it. Issued here and nowhere else.

build

build(spec, sources)

Attach sources to spec and build it — the model with your data on it.

PARAMETER DESCRIPTION
spec

As check takes it.

TYPE: Buildable

sources

Parameter names to parquet paths or in-memory tables, and dimension names to their labels — an index table, a parquet path, or a bare sequence — wherever the YAML declares none. The whole of the build's input: the shapes a value may take, and what attaching refuses, are the data contract.

TYPE: Mapping[str, Source]

RETURNS DESCRIPTION
Model

The built model.

RAISES DESCRIPTION
LanguageError

A construct outside the streaming language.

DataError

A source that is missing, unreadable, or the wrong shape.

solve

solve(spec, sources, solver_name='highs', *, solver_options=None, archive=None)

Build spec and solve it in one call.

The one-shot spelling: a caller who will solve the same spec again with new numbers wants build and Model.update.

There is no keep here — this builds the model it solves, so the solve is the first of that model's life and kept is always nothing. Choosing what to keep is Model.solve.

PARAMETER DESCRIPTION
spec

As check takes it.

TYPE: Buildable

sources

As build takes them.

TYPE: Mapping[str, Source]

solver_name

As Model.solve takes it.

TYPE: str DEFAULT: 'highs'

solver_options

As Model.solve takes them.

TYPE: Mapping[str, object] | None DEFAULT: None

archive

Where to write the spec, its data and this answer, as Model.solve takes it — a .zip, or a directory.

TYPE: str | Path | None DEFAULT: None

RETURNS DESCRIPTION
Result

The solution. It owns its frames; the model and the solver are

Result

released before this returns. result.close() drops its own hold

Result

early.

RAISES DESCRIPTION
SpecsolveError

A solver name nothing serves — checked before the build.

write

write(spec, sources, out)

Build spec and stream it to a file, in the format out's suffix names.

PARAMETER DESCRIPTION
spec

As check takes it.

TYPE: Buildable

sources

As build takes them.

TYPE: Mapping[str, Source]

out

Where to write; .lp and .mps are what ship. The two describe one model and name its columns and rows the same way.

TYPE: str | Path

RETURNS DESCRIPTION
Path

The path written.

RAISES DESCRIPTION
ValueError

A suffix nothing writes — checked before the build.

SpecsolveError

A construct the format has no section for, as check(spec, sink=out.suffix) reports.

evaluate

evaluate(spec, sources, expression)

The value of expression over a spec with no variables — arithmetic, no solver.

A spec that declares no variables is a calculation, not an optimisation: dimensions, parameters, relations and expressions:. Each expression reads only the attached data, so it has a value with no solve and no chosen point. This attaches sources and values one expression, the way evaluate does at a solution. The language it is read through — what loads, what is refused, how a construct prints and lowers — is the one a spec that solves is read through; only the variables are absent.

A spec that declares variables is a problem to solve, and belongs to solve: an expression over a decision has no value until the decision is made.

PARAMETER DESCRIPTION
spec

As check takes it — a YAML path, a mapping, or a Spec.

TYPE: Buildable

sources

As build takes them: parameter names to tables or parquet paths, and dimension names to their labels.

TYPE: Mapping[str, Source]

expression

What one expressions: entry takes — a name the spec declares, an expression string, or the mapping carrying cases: with dims: and otherwise:.

TYPE: str | Mapping[str, object]

RETURNS DESCRIPTION
DataFrame

The value, (dims…, value) over the expression's own dims. Only

DataFrame

this expression is compiled: a declared one nothing asks for costs

DataFrame

nothing.

RAISES DESCRIPTION
LanguageError

A construct outside the streaming language, or a name the spec does not declare.

SpecsolveError

A spec that declares variables, constraints or an objective — a problem to solve, not a calculation to evaluate.

DataError

A source that is missing, unreadable, or the wrong shape, or a divisor with no value where the expression divides.

Run it many times

The fold and its two axes; sweeps says how a sweep is cut and read.

solve_over

solve_over(spec, sources, axis, *, carry=None, key_name=None, executor=None, workers_share_fs=None, solver_options=None, solver_name='highs', keep='solver', spill_to=None, archive=None)

Solve spec once per slice of axis and fold the answers together.

The rules — what a carry copies, how the key column is named, which executor to choose — are sweeps.

PARAMETER DESCRIPTION
spec

As check takes it. Parsed once, whichever executor runs the slices.

TYPE: Buildable

sources

As build takes them, every shape included; the axis filters the tables that carry it and passes the rest through.

TYPE: Mapping[str, Source]

axis

EachCoordinate, EachWindow, or a list of (key, sources) written by hand.

TYPE: Axis | Sequence[tuple[Label, Mapping[str, Source]]]

carry

{parameter: variable}: one slice's answer copied into the next slice's data. Where the two are over different dimensions, the last coordinate the slice owns is handed on. The first slice takes the parameter from sources as its seed.

TYPE: Mapping[str, str] | None DEFAULT: None

key_name

What to call the slice column; a class axis names its own, a hand-built list has to be told.

TYPE: str | None DEFAULT: None

executor

Any concurrent.futures.Executor; None runs the slices in order on one model. A process pool must be spawn or forkserver — a forked worker hangs.

TYPE: Executor | None DEFAULT: None

workers_share_fs

Whether the executor's workers can read this process's paths. Decided for the stdlib pools; anything else is assumed not to, and paths travel as bytes.

TYPE: bool | None DEFAULT: None

solver_options

As solve takes them.

TYPE: Mapping[str, object] | None DEFAULT: None

solver_name

As solve takes it.

TYPE: str DEFAULT: 'highs'

keep

As solve takes it, reaching every slice. Under an executor every slice is a first solve and keeps nothing, whatever was asked.

TYPE: Keep DEFAULT: 'solver'

spill_to

A directory to write each slice's frames to as the fold goes, so the sweep's memory stays at one slice however many there are. Read back through Sweep.scan. A directory holds one sweep: run the same sweep at it again and the slices already there are not solved again, which is how an interrupted sweep resumes.

TYPE: str | Path | None DEFAULT: None

archive

Where to write the whole thing — the model, the sources the sweep was cut from, the axis that cut them, and every slice's answer — so that sps.load_archive gives all four back and the sweep runs again from the file alone. A .zip suffix packs it into one file and anything else is a directory. Given beside spill_to, the spill is what the archive packs, so a sweep too large to hold is archived without ever being held. The archive is a second copy of the answers on disk; the memory is what spill_to bounds. A sliced source is archived whole, the column the axis cuts on included. A hand-built axis is refused, since a list of (key, sources) is a set of sources per slice: archive one solve each.

TYPE: str | Path | None DEFAULT: None

RETURNS DESCRIPTION
Sweep

Every slice's answers, keyed by slice.

RAISES DESCRIPTION
SpecsolveError

A carry that cannot line up, has no seed, collapses a dimension the axis does not advance along, or is asked together with an executor; a key that collides with a column the frames carry; an axis the program does not allow; a spill_to directory holding another sweep. All refused before a slice is taken, and every one answerable from the declarations before a source is read.

DataError

No source carries the axis, or the axis produced no slices.

WARNS DESCRIPTION
SpecsolveWarning

A source carrying the axis that is short of a coordinate another has — that slice builds it empty — or a position the model counts, which every window restarts.

EachCoordinate dataclass

EachCoordinate(dim)

One slice per coordinate of dim — a column the sources carry.

Scenarios, draws, investment periods. Sources carrying dim are filtered to one coordinate and the column dropped, so the model never mentions it — a dim the spec declares is refused; every other source passes through untouched. The slices run in the coordinates' sorted order, which is the order a carry chains them in.

dim instance-attribute
dim
slices
slices(sources)

The (key, sources) list this axis would run — what axis= takes hand-built.

For building one slice alone: sps.build(spec, axis.slices(sources)[3][1]).

EachWindow dataclass

EachWindow(dim, *, steps, lookahead, into)

One slice per window of consecutive coordinates of dim.

steps is what each window keeps and lookahead is what it sees beyond that, so a window is steps + lookahead coordinates long and a lookahead above zero is overlap. An int keeps the same number every window; a sequence keeps those numbers in order, which is a telescoping horizon or a month at a time. Both count coordinates rather than coordinate values, so dim need only be orderable — datetimes, strings and gapped integers all work. The dimension is re-indexed rather than dropped, into a dense 0..n-1 column the model addresses by the name into gives it, which the spec has to declare.

Whether the model can be cut this way is asked before a slice is taken (separability): a coupling along into is refused, naming the declaration and the change that would lift it; lookahead has to cover what the rows read ahead; and a position() the model counts warns, since every window restarts it. What the rows read behind is the rolling-horizon seed, met by the edge policy, and is not refused.

dim instance-attribute
dim
into class-attribute instance-attribute
into = field(kw_only=True)
lookahead class-attribute instance-attribute
lookahead = field(kw_only=True)
steps class-attribute instance-attribute
steps = field(kw_only=True)
slices
slices(sources)

The (key, sources) list this axis would run — what axis= takes hand-built.

For building one window alone: sps.build(spec, axis.slices(sources)[37][1]). The pairs carry no ownership: solved as a list, the slices need key_name=, original_index is refused, and a carry cannot collapse a dimension.

What comes back

Model

Model(spec, sources)

A spec with your data attached to it — what build returns.

Three nouns, each arrow adding one thing: a Program is the math, a Model is the math with your data, a Result is one answer: check → Program → build → Model → solve → Result.

One build feeds any number of sinks — solve and write on the same object — update puts new numbers on it without re-reading the YAML or re-lowering the plan, and diagnostics says what it did. Nothing has to be released; close hands a large model back early.

close
close()

Release the built model, and any solver still holding it.

diagnostics
diagnostics()

What this build and its solves did that the answer does not show.

Answerable after close, and after a build that raised: every field is a count, a clock or a small frame the engine keeps, not a read of the model it releases. A raise leaves the sizes at zero — they are taken once a model is whole — and everything measured before it stands.

evaluator
evaluator(primals, duals, no_duals)

An ad-hoc expression reader over a saved solution, put back against this build.

What an archive and a sweep hand evaluate for a quantity the file never named: the saved frames are laid back in this build's label order, and the reader is the one a live solve gives. A build, never a solve.

PARAMETER DESCRIPTION
primals

The saved (dims…, value) frame per variable.

TYPE: Mapping[str, DataFrame]

duals

The same per constraint, or None where the solve left no duals.

TYPE: Mapping[str, DataFrame] | None

no_duals

Why there are no duals, raised at a dual read; None when duals holds them.

TYPE: str | None

row
row(name, /, **coordinate)

One built constraint row at one coordinate — its terms, sense and right-hand side.

The verb for this row is wrong and I do not know why. to_latex and its siblings render the spec as math before any data, and dual gives a row's number without its terms; this gives the row the build actually produced, at the coordinate you name.

Reads the built model and needs no solve, so it answers on a model that never reached a solver — and it is the built row, so a term whose variable was absent is missing from it and a row a where masked out is not there at all. It shows what the model says rather than what the file appears to say. A column has no reader: a variable's bounds are in the spec, and its coefficients are this read transposed.

PARAMETER DESCRIPTION
name

A declared constraint. Positional, so a dimension may be called name.

TYPE: str

coordinate

One label per dim of that constraint, all of them.

TYPE: Label DEFAULT: {}

RETURNS DESCRIPTION
ConstraintRow

The terms as (variable, coordinate, coefficient), beside the

ConstraintRow

comparison and the right-hand side.

RAISES DESCRIPTION
KeyError

No constraint is called name.

SpecsolveError

The coordinate names the wrong dims, holds a label its dimension cannot hold, matches no row the build produced, or the model has been closed.

Example

print(model.row('balance', snapshot=1)) # doctest: +SKIP balance[snapshot=1]: +1 p[1, wind] +50 p[1, gas] >= 60

solve
solve(solver_name='highs', *, solver_options=None, keep='solver', archive=None)

Hand the built model to a solver and solve it.

A solver that can stay loaded is kept between calls, so an updated model skips the hand-off and only its numbers are pushed. Whether the work that solver did is kept too is keep, off by default. How much this solve actually kept is its kept.

PARAMETER DESCRIPTION
solver_name

highs, which ships with the package; gurobi, which needs the [gurobi] extra; or xpress, which needs the [xpress] extra. The caller chooses: nothing in the spec names a solver.

TYPE: str DEFAULT: 'highs'

solver_options

Forwarded to the solver verbatim, in its own vocabulary, so a time limit is time_limit, TimeLimit or timelimit. Gurobi's are applied when its environment is created, so ComputeServer, TokenServer and WLSAccessID reach it too.

TYPE: Mapping[str, object] | None DEFAULT: None

keep

How much of the session this solve may keep: solver, progress or nothing. solver, the default, reuses the solver holding the model and discards the work it did; progress keeps that work too, which is what an iterating driver moving one step at a time wants; nothing keeps neither, which is what timing a build or comparing against a cold baseline needs and what no solver option can promise. A preference: a model whose structure moved is loaded again whatever was asked.

TYPE: Keep DEFAULT: 'solver'

archive

Where to write the whole thing — the spec, the data attached to it now, and this answer — so that load_archive gives all three back and the model solves again from the file alone. A .zip suffix packs it into one file and anything else is a directory. What the build and its solves have spent goes in beside the answer, as Metrics. The sources go in through the door build reads them through: a parquet path is copied as its own bytes, anything else is written as the table it stands for, and members are stored uncompressed.

TYPE: str | Path | None DEFAULT: None

RETURNS DESCRIPTION
Result

The solution, holding this model.

RAISES DESCRIPTION
SpecsolveError

A solver name nothing serves, one this environment cannot run, or a keep other than those three.

LayoutError

An archive directory that already holds something, refused before the solve.

update
update(sources)

Put new numbers on the same model, in place.

::

model.update({'cap_hat': capacity}).solve()

Any new data is accepted: model.update(x) answers what build(spec, sources | x) answers, whatever changed. Data that moves a mask renumbers labels, so the model is rebuilt and solved cold instead of pushed onto a loaded solver, and loads says which ran.

Results taken before the update keep reading: each owns the frames it reads, and an update builds new ones rather than touching those. A retained result keeps its build's label frames alive until it is dropped or close is called.

A loop whose next numbers depend on the last answer is this; a sweep, a rolling horizon or a myopic pathway is solve_over, which runs the loop.

PARAMETER DESCRIPTION
sources

Only what changed; the rest keeps what build attached. A dimension's labels as well as a parameter, which is how a coordinate set grows.

TYPE: Mapping[str, Source]

RETURNS DESCRIPTION
Model

This object.

RAISES DESCRIPTION
DataError

A name the spec does not declare, since an update that named nothing would solve the old numbers again. An update that raises releases the model, as a build that raises does.

write
write(path)

Stream the built model to path, in the format its suffix names.

RAISES DESCRIPTION
ValueError

A suffix nothing writes.

SpecsolveError

A construct the format has no section for, the same as check's sink= answer.

ConstraintRow dataclass

ConstraintRow(name, coordinate, terms, sense, rhs)

One built constraint row, spelled back out — what row returns.

The row a model actually built at one coordinate: every term with its coefficient, and the comparison and right-hand side it was built against. Read off the built model, so it needs no solve. It is the row after where masking, after any term whose variable was absent dropped out, and after a coefficient the data made exactly zero stopped being a term, so it can be shorter than the file suggests.

Printing it gives the row as one line of math in linopy's format. A row wider than display_terms prints instead how many terms each variable contributes and the span of their coefficients. terms is the same content as a frame, for the row too wide to read and for anything that filters or joins.

ATTRIBUTE DESCRIPTION
name

The constraint this row belongs to.

TYPE: str

coordinate

Where in that declaration it sits.

TYPE: Mapping[str, object]

terms

(variable, coordinate, coefficient), one row per term, in the solver's own column order. coordinate is the term's labels in its variable's dim order, rendered as one string.

TYPE: DataFrame

sense

<=, >= or ==.

TYPE: str

rhs

What the left-hand side is compared against.

TYPE: float

coordinate instance-attribute
coordinate
display_terms class-attribute instance-attribute
display_terms = 12

How many terms a line spells out before it summarises instead.

name instance-attribute
name
rhs instance-attribute
rhs
sense instance-attribute
sense
terms instance-attribute
terms

Result dataclass

Result(_status, _objective, _primals, _duals, _activities, _kept, _expressions=None, _evaluate=None, _no_duals=None, _dual_rays=None, _no_dual_ray=None, _spec_digest=None, _solved_at=None, _model_digest=None, _run=None)

What a solve returned — the outcome, and access to any values.

Returned whatever the solve concluded: test has_primal before reading values, or catch NoSolutionError. A result owns its values, so it outlives anything done to the model afterwards: an update, another solve, model.close(). Retaining one keeps the label frames of the build it answered alive; close releases them early, and nothing breaks without it.

has_primal property
has_primal

Whether there are values to read — what the accessors gate on.

Narrower than is_ok: a run stopped at a time limit before any incumbent is ok with nothing to read.

is_ok property
is_ok

The linopy rollup: not an error, an abort or a refusal.

kept property
kept

How much of the session this solve kept: solver, progress or nothing.

What happened, not what was asked: a first solve or a structure that moved keeps nothing whatever keep= requested, so a driver that asked for progress and reads nothing is being told its labels moved. Advisory, like Diagnostics: no answer depends on it.

objective property
objective

The objective value, or nan when there is no solution.

record property
record

How this solve terminated, as the one row save writes for it.

The fields above in one value, and the same row a sweep keeps per slice in record. objective is None rather than nan where there are no values. Asking computes model_digest once, as a save does.

solved_at property
solved_at

When the solver returned, in UTC — None where the solve carried no clock.

spec_digest property
spec_digest

Which spec this answered — a digest of the file, not its name.

Two answers carrying one digest answered the same document; their data may differ. None where the solve ran off a lowered program, which has no document.

status property
status

Coarse outcome: ok / warning / error / aborted / unknown.

termination_condition property
termination_condition

What the solver said — optimal, infeasible, time_limit and so on.

activity
activity(name)

The left-hand side of constraint name at the solution — (dims…, value).

dual's shape and order. The solver's own number, not a recomputation. Readable whenever there is a solution, a mixed-integer one included. On an == row it equals the right-hand side up to solver tolerance.

RAISES DESCRIPTION
NoSolutionError

The solve left no values to read.

SpecsolveError

This result was closed.

KeyError

No constraint is called name.

close
close()

Release what this result holds early. Optional.

Its frames and its hold on the label frames of the build it answered. Frames already read stay valid. The model and the solver are the Model's to close.

dual
dual(name)

Shadow prices of constraint name — (dims…, value).

Each is the rate at which the optimal objective rises as the row's right side rises: of lhs <= rhs, the rate in d of lhs <= rhs + d. That is mathspec's definition of dual(c), and it holds for every comparator, under either sense and on every sink, so which side a term is written on decides the sign.

primal's shape and order, over constraint rows. Duals exist only where a solver ran here: a model written to a file and solved elsewhere never passes back through this package. Reduced costs and slacks are not read.

RAISES DESCRIPTION
NoSolutionError

The solve left no values at all.

SpecsolveError

This result was closed, or it left primals but no duals — an integer variable makes them undefined, and so does an sos: set that Spec.expand() wrote out as binaries. gurobi and xpress branch on a set itself and keep them.

KeyError

No constraint is called name.

dual_ray
dual_ray(name)

Constraint name's share of the certificate that this model has no solution — (dims…, value).

The only reader that answers on an infeasible solve, where primal, dual and activity all raise. Weight every row by its value here and add them together, and the combined row demands more than the columns can deliver inside their bounds: the proof that nothing satisfies all of them at once, and what a Benders feasibility cut is built from.

dual's shape and order. The sign is the row's own, the same on every sink. Where every column is held only by a lower bound of zero, the proof is Σ weight * right-hand side > 0.

A certificate is computed only where it was asked for. highs always produces one; gurobi needs {'InfUnbdInfo': 1} and xpress needs {'presolve': 0} in solver_options, set before the solve. A ray is live only: save writes none, and no sweep spills one.

RAISES DESCRIPTION
SpecsolveError

This result was closed; or the solve was not infeasible, so there is nothing to certify; or the sink produced no ray, in which case the message names the solver option that would have.

KeyError

No constraint is called name.

Example

answer.dual_ray('balance') # doctest: +SKIP shape: (4, 2) ┌──────────┬───────┐ │ snapshot ┆ value │ ╞══════════╪═══════╡ │ 0 ┆ 1.0 │ └──────────┴───────┘

evaluate
evaluate(expression)

The value of expression at this solution — (dims…, value).

expression is what one expressions: entry takes: a name the file declares, an expression string, or the mapping carrying cases: with dims: and otherwise:. It may use every name the model declares and only those. The value is aggregated to the expression's own dims, in declaration order, rows in label order over them — primal's shape and order.

Anything but a declared name lowers the spec as written, which costs what check costs. An undeclared expression is not written by save or spilled by a sweep; to keep a quantity, declare it under expressions:.

RAISES DESCRIPTION
NoSolutionError

The solve left no values to read.

SpecsolveError

This result was closed; the model was built from an already-lowered Program or read back off disk, so there is nothing to lower an undeclared expression against; an archive whose sources build another model than the one this answered; or a divisor with no value where the expression divides.

LanguageError

A construct outside the language, or a name the spec does not declare — a new parameter is a build, not a read.

model_digest
model_digest()

Which model this answered — the document and the data it was attached to.

spec_digest names the document alone, so two scenarios of one spec share that and differ here. Computed on the first ask and kept.

primal
primal(name)

The tidy solution of variable name — (dims…, value).

Rows come back in label order, row-major over the variable's coordinate product, so two reads and two runs agree.

RAISES DESCRIPTION
NoSolutionError

The solve left no values to read.

SpecsolveError

This result was closed.

KeyError

No variable is called name.

save
save(directory)

Every kind this solve answered with, one file per name, into directory.

record.parquet holds the Record — how the solve terminated and what it reached; a solve that reached no objective writes null there rather than nan. Then primal/<name>.parquet for every variable, dual/<name>.parquet for every constraint where the duals are defined, activity/<name>.parquet for every constraint, and expression/<name>.parquet for every named expression this data can evaluate. The same model and data write the same bytes.

reasons.parquet holds (kind, name, reason) for whatever is deliberately not here, and is absent when everything is: one row per expression that failed, and one with an empty name for the duals.

format.json stamps the directory with the layout it is written in and the specsolve that wrote it: {"layout": 1, "specsolve": "…"}. Every reader refuses another layout with a LayoutError that says to solve the model again and save it.

A solve that left no values writes the record and nothing else.

The directory holds this answer and no other: whatever a previous save left there is removed first. Files that are not part of the layout are left alone.

RETURNS DESCRIPTION
Path

The directory.

RAISES DESCRIPTION
SpecsolveError

This result was closed.

to_dataarray
to_dataarray(name, kind='primal')

One name's values as a labelled xarray.DataArray, to_pandas's arguments.

Dense over the name's dims: a masked coordinate comes back NaN.

to_dataset
to_dataset(*names, kind='primal')

The named values of one kind as one xarray.Dataset; all of that kind by default.

Each arrives dense over its own dims, all at once — on a large model name the few you need.

PARAMETER DESCRIPTION
names

What to include; none means every name of kind.

TYPE: str DEFAULT: ()

kind

primal, dual or expression.

TYPE: str DEFAULT: 'primal'

to_pandas
to_pandas(name, kind='primal')

One name's values as a tidy pandas.DataFrame.

Needs pandas, which specsolve does not install; the xarray bridges need xarray too.

PARAMETER DESCRIPTION
name

A variable, a constraint or a named expression, as kind says.

TYPE: str

kind

primal, dual or expression — the reader this stands in for.

TYPE: str DEFAULT: 'primal'

Sweep dataclass

Sweep(key_name, record, metrics, _primals=dict(), _duals=dict(), _expressions=dict(), _no_duals=None, _no_expressions=dict(), _original=None, _hand_built=False, _spill=None, _evaluate=None)

What a fold returned: frames keyed by slice, never a scalar.

Result's readers one dimension wider — same names, same shapes, the slice key prepended. Nothing is combined across slices: each row says which slice computed it. A windowed sweep reads over that key unless a reader asks original_index=True, which gives the dimension the axis sliced and drops the lookahead rows every overlapping window recomputed.

key_name instance-attribute
key_name
keys property
keys
metrics instance-attribute
metrics

One SliceMetrics per slice, keyed and in slice order — diagnostics one dimension wider, its counts and clocks only. loaded says the solver took the model from scratch: under a serial fold the first slice does and the rest are pushed values, so a later True is a slice whose data moved a mask; under an executor every slice builds alone and every one loads. The _seconds columns are this slice's own share, so a slow sweep says which slice, and which phase of it.

record instance-attribute
record

One Record per slice, the key column first, in slice order — how every slice terminated, whether or not it produced an answer. A slice that reached no objective holds null there rather than nan, so the column aggregates over the slices that solved.

dual
dual(name, *, original_index=False)

One constraint's shadow prices across every slice, the key prepended.

primal's shape and arguments. A slice whose model had an integer variable contributes no duals; over the original index each coordinate carries the price of the window that owns it, never a blend of several.

RAISES DESCRIPTION
SpecsolveError

No slice produced duals for name — the message says which of the two it was.

evaluate
evaluate(expression, *, original_index=False)

The value of expression at every slice's solution, the slice key prepended.

evaluate one dimension wider, and primal's shape and arguments. expression is what one expressions: entry takes: a name the file declares, an expression string, or the mapping carrying cases: with dims: and otherwise:.

A declared name is stitched from what the sweep holds, live or off disk. Anything else is valued at each slice's own solution with no re-solve, so it is available on the sweep load_archive hands back, which carries the spec, sources and axis; a Sweep a live solve returned says it retains no model. An expression over a parameter the sweep carried is refused, that value being a previous slice's answer rather than stored data.

Over the original index each coordinate carries the value of the window that owns it — the recomputed lookahead rows are dropped, so summing the stitched frame does not double-count.

PARAMETER DESCRIPTION
expression

A declared name, an expression string, or the cases: mapping, as one expressions: entry takes.

TYPE: str | Mapping[str, object]

original_index

Read over the dimension the axis sliced instead of over the slice key.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
SpecsolveError

No slice produced a declared expression — an evaluation that failed on every slice carries its own reason — a spilled sweep, which scan reads instead; an undeclared expression on a Sweep with no model behind it, or one that reads a parameter the sweep carried; or original_index on a hand-built axis or a quantity reduced over the sliced dimension.

LanguageError

A construct outside the language, or a name the spec does not declare.

primal
primal(name, *, original_index=False)

One variable's values across every slice, the slice key prepended.

A slice that reached no solution contributes no rows, so this can be shorter than the sweep; record is one row per slice always.

PARAMETER DESCRIPTION
name

A variable the sweep's spec declares.

TYPE: str

original_index

Read over the dimension the axis sliced instead of over the slice key.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
SpecsolveError

No slice of the sweep produced name, or original_index on a sweep whose axis was hand-built and so named no dimension to read the keys back over.

save
save(directory)

Everything the sweep holds, written as spill_to= would have written it.

The same layout: <kind>/<name>/<position>.parquet for every primal, dual and expression, the slice key a column of each, with record/, metrics/ and the manifest beside them. So the directory is a spilled sweep: scan reads it, and the call that made this sweep, pointed at it with spill_to=, reads it back without solving a slice.

A sweep whose every slice terminated without values writes each slice's record and no frames, as one such solve does, rather than refusing.

RETURNS DESCRIPTION
Path

The directory.

RAISES DESCRIPTION
SpecsolveError

The sweep is spilled — its frames are in a directory already.

scan
scan(name, kind='primal', *, original_index=False)

One name's values across every slice as a polars.LazyFrame, the slice key prepended.

The reader for a sweep solved with spill_to=, whose frames are on disk; on one held in memory it is primal, dual or evaluate made lazy, so the same line reads either.

PARAMETER DESCRIPTION
name

A variable, a constraint or a named expression the spec declares, as kind says.

TYPE: str

kind

primal, dual or expression — the reader this stands in for.

TYPE: str DEFAULT: 'primal'

original_index

Read over the dimension the axis sliced instead of over the slice key.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
SpecsolveError

No slice produced name, or a kind that names no reader.

to_dataarray
to_dataarray(name, kind='primal', *, original_index=False)

One name's values as a xarray.DataArray, the slice key a dimension; to_pandas's arguments.

The extra dimension is named by the axis: (scenario, …) or (<dim>_start, …). A slice that reached no solution has no rows and comes back NaN, the same answer a masked coordinate gets from Result. original_index=True indexes the array by the dimension the axis sliced instead, so a rolling horizon's dispatch comes back indexed by time.

to_dataset
to_dataset(*names, kind='primal')

The named values of one kind as one xarray.Dataset; all of that kind by default.

One kind per call, since a dual and a variable may share a name; save writes every kind. No original_index: this and save export what the sweep holds, lookahead rows included.

PARAMETER DESCRIPTION
names

What to include; none means every name of kind some slice produced.

TYPE: str DEFAULT: ()

kind

primal, dual or expression.

TYPE: str DEFAULT: 'primal'

RAISES DESCRIPTION
SpecsolveError

The sweep holds no values of kind at all, or is spilled — its frames are on disk already.

to_pandas
to_pandas(name, kind='primal', *, original_index=False)

One name's values across every slice as a tidy pandas.DataFrame.

The name is resolved before pandas is imported, so a sweep that never held name says so on any install.

PARAMETER DESCRIPTION
name

A variable, a constraint or a named expression, as kind says.

TYPE: str

kind

primal, dual or expression — the reader this stands in for.

TYPE: str DEFAULT: 'primal'

original_index

Read over the dimension the axis sliced instead of over the slice key.

TYPE: bool DEFAULT: False

The rows and frames those hand back: how a solve terminated, what the build and its solves took, and what a slice of a sweep took.

Diagnostics dataclass

Diagnostics(columns, rows, nonzeros, omissions, sparse_parameters, coefficient_range, bound_range, rhs_range, objective_range, solves, loads, seconds)

What a build and its solves did that the answer does not show.

Advisory, all of it: no answer depends on any field.

bound_range instance-attribute
bound_range

(variable, smallest, largest) — the bound magnitudes each variable block put on its columns, one row per block that declared a finite one. Zero and infinity are excluded. A model can be clean on coefficient_range and still have bounds the solver asks to have scaled. A large largest is usually a big number standing in for "uncapped", and wants no upper bound at all rather than a rounder one.

coefficient_range instance-attribute
coefficient_range

(constraint, smallest, largest) — the coefficient magnitudes each constraint block put in the matrix, one row per block that kept a term, in build order. largest / smallest over the frame is the conditioning to compare against the solver's.

columns instance-attribute
columns

The shape the build produced: columns, rows, and matrix entries.

loads instance-attribute
loads
nonzeros instance-attribute
nonzeros
objective_range instance-attribute
objective_range

The same pair for the objective's coefficients, or None where the spec declares no objective and where every term of one cancelled.

omissions instance-attribute
omissions

(constraint, rows_not_built) — every declared row that did not reach the solver: one emptied of all its terms, and one a propagated absence deleted. Empty where every declared row was built. A recurrence's first coordinate counts, so a shift against the horizon's edge reports here, as the boundary rather than a fault.

rhs_range instance-attribute
rhs_range

(constraint, smallest, largest) — the same for each block's right-hand sides, over the rows that survived.

rows instance-attribute
rows
seconds instance-attribute
seconds

Cumulative wall-clock seconds per phase, keyed by the phase's name: attach (the caller's sources onto the plan), build (declarations into the model frames), handoff (the built model into a solver), solve (the solver's own run), write (the built model to a file). A phase that never ran has no key; one that ran again holds the sum.

solves instance-attribute
solves

How many times this model has been solved, and how many of those solves loaded the solver from scratch instead of pushing values onto one that already held it. loads == solves on an iterating driver means the model masks on a parameter that varies, unless the driver asked for keep='nothing'. loads ticks on exactly the solves that report Result.kept of nothing.

sparse_parameters instance-attribute
sparse_parameters

(parameter, coordinates, rows, missing) — one row per parameter whose source is short of the coordinates its dims reach, in declaration order. Empty where every one is complete. An entry is a report, not a fault: absence is how a model masks. A parameter over no dims is never here.

metrics
metrics()

The sizes, counters and clocks as one value — the row an archive records.

What archive= records beside the answer, and what a caller feeding its own store reads off a model it solved. Metrics says what each field means. A phase this build never entered reads zero, and run is null.

Record

How a solve terminated, what it reached, and which spec it answered.

One row per solve, and the same columns whoever wrote them: a result writes one, a sweep one per slice keyed by its own key. A run that left no values writes this and nothing else.

has_primal instance-attribute
has_primal

Whether the solve produced values, which the condition alone does not say: a run stopped at a limit before any incumbent is ok with nothing to read.

model_digest class-attribute instance-attribute
model_digest = None

A digest of the model this answered — the spec and its data, where spec_digest is the document alone. None for an answer that never held one.

objective instance-attribute
objective

What the solve reached, or None where it reached nothing — null rather than nan, which every aggregate reads as a number. Result.objective is a float and reads it back as nan.

run class-attribute instance-attribute
run = None

What the archive holding this answer was called — its file name without a .zip, so runs/nightly-2026-09-10.zip writes nightly-2026-09-10 and a directory called case.v2 keeps both halves of its name. Null until the archive is written.

solve_status property
solve_status

The status this row records, without the solver's own wording.

solved_at class-attribute instance-attribute
solved_at = None

When the solver returned, in UTC, or None for a solve that carried no clock, such as a result built by hand.

spec_digest instance-attribute
spec_digest

A digest of the spec this answered, or None where the solve was run off a lowered program. Null on disk, never an empty string.

status instance-attribute
status
termination_condition instance-attribute
termination_condition
of classmethod
of(termination_condition, objective, *, has_primal, spec_digest, solved_at, model_digest=None)

The row a solve that terminated this way writes.

status is derived from termination_condition.

PARAMETER DESCRIPTION
termination_condition

What the solver said.

TYPE: str

objective

What the solve reached. Written only where there are values to read.

TYPE: float

has_primal

Whether there are values, which the condition alone does not say.

TYPE: bool

spec_digest

A digest of the spec answered, or None.

TYPE: str | None

solved_at

When the solver returned, in UTC. None where the solve carried no clock.

TYPE: datetime | None

model_digest

The built model's digest, or None where this answer never held one.

TYPE: str | None DEFAULT: None

Metrics

What a build and its solves took, as the row an archive records beside the answer.

The scalars of Diagnostics, with the same columns whoever writes them, so rows written by runs that never met concatenate into one table.

Cumulative over the model's life. solves says how many solves the clocks cover; it reads 1 for the archive specsolve.solve writes.

attach_seconds instance-attribute
attach_seconds

Wall-clock seconds in each phase a build clocks, in the order they run: the caller's sources onto the plan, the declarations into the model frames, the built model into a solver, the solver's own run, and the built model streamed to an LP or MPS file. A phase that never ran writes zero rather than no column. write_seconds is write's clock, not the archive's: what writing the archive cost is recorded nowhere.

build_seconds instance-attribute
build_seconds
columns instance-attribute
columns

The shape the build produced, in the solver's own vocabulary.

handoff_seconds instance-attribute
handoff_seconds
loads instance-attribute
loads
nonzeros instance-attribute
nonzeros
rows instance-attribute
rows
run class-attribute instance-attribute
run = None

What the archive holding this row was called, as Record.run: its file name without a .zip. Null until one is written.

solve_seconds instance-attribute
solve_seconds
solves instance-attribute
solves

How many solves the row covers, and how many of those loaded the solver from scratch. The clocks are cumulative over exactly these solves.

write_seconds instance-attribute
write_seconds

SliceMetrics

What one slice of a sweep took — Metrics one dimension in.

A slice's clocks are its own share rather than a cumulative total, and loaded says whether the solver took this slice from scratch. Written per slice by the spill and read back as one table.

attach_seconds instance-attribute
attach_seconds

This slice's own seconds per phase. A sweep writes no file per slice, so there is no write.

build_seconds instance-attribute
build_seconds
columns instance-attribute
columns

The shape this slice built, as Metrics reports a whole model's.

handoff_seconds instance-attribute
handoff_seconds
loaded instance-attribute
loaded

Whether the solver took this slice's model from scratch instead of having values pushed onto one it already held. Under a serial fold the first slice does and the rest do not, so a later True is a slice whose data moved a mask; under an executor every slice loads.

nonzeros instance-attribute
nonzeros
rows instance-attribute
rows
solve_seconds instance-attribute
solve_seconds

Carry an answer

SolveArchive dataclass

SolveArchive(spec, sources, answer, source_digests, metrics)

A spec, the data it was solved with, and what one solve of it returned.

sps.solve(archive.spec, archive.sources) asks the question again.

ATTRIBUTE DESCRIPTION
spec

The spec as written, read back as one Spec whatever went in.

TYPE: Spec

sources

What was attached, keyed as the file declares it: a table from load_archive, the path to one from scan_archive.

TYPE: Mapping[str, Source]

answer

What came back.

TYPE: Result

source_digests

(run, source, digest), one row per source, so two archives of one spec over different numbers name the input that moved. A digest is of the parquet bytes the archive holds, so two polars versions can write one table to different digests, and reading an archive does not verify them.

TYPE: DataFrame

metrics

What reaching the answer took, as one Metrics.

TYPE: Metrics

answer instance-attribute
answer
metrics instance-attribute
metrics
source_digests instance-attribute
source_digests
sources instance-attribute
sources
spec instance-attribute
spec

SweepArchive dataclass

SweepArchive(spec, sources, axis, carry, answer, source_digests)

A spec, the data a sweep was solved over, the axis that cut it, and what came back.

sps.solve_over(sweep.spec, sweep.sources, sweep.axis, carry=sweep.carry) runs it again.

ATTRIBUTE DESCRIPTION
spec

The spec as written.

TYPE: Spec

sources

What the sweep was given, uncut. A table or a path, as SolveArchive holds them.

TYPE: Mapping[str, Source]

axis

What cut them.

TYPE: EachCoordinate | EachWindow

carry

{parameter: variable} the slices were chained with, empty where they were not.

TYPE: Mapping[str, str]

answer

Every slice's answer, keyed by slice. Held from load_archive, spilled from scan_archive.

TYPE: Sweep

source_digests

As SolveArchive holds it, of the uncut sources.

TYPE: DataFrame

answer instance-attribute
answer
axis instance-attribute
axis
carry instance-attribute
carry
source_digests instance-attribute
source_digests
sources instance-attribute
sources
spec instance-attribute
spec

load_archive

load_archive(path, into=None)

Read an archive back whole: the sources as tables, the answer's frames in memory.

PARAMETER DESCRIPTION
path

The archive, a .zip or the directory one was written to.

TYPE: str | Path

into

Where to unpack a zip, kept afterwards. Without it a zip unpacks to a scratch directory removed before this returns. Refused for a directory archive, which is read where it lies.

TYPE: str | Path | None DEFAULT: None

RETURNS DESCRIPTION
SolveArchive | SweepArchive

A SweepArchive where the archive carries an axis, a

SolveArchive | SweepArchive

SolveArchive where it does not.

RAISES DESCRIPTION
LanguageError

A spec.yaml the language does not accept.

LayoutError

A member outside the layout, an into given for a directory, or an answer whose layout has moved since it was written.

SpecsolveError

An answer that names a different spec than the one beside it.

BadZipFile

A file that is not a zip archive.

load_result

load_result(directory)

Read back an answer Result.save wrote — a solve, off disk.

Every reader answers what it answered in the session that solved: the values, the duals and activities, each named expression, and the reason behind anything the solve could not produce. None of it needs the build that made it or the solver that filled it.

Two things do not come back: kept reads nothing, this result holding no solver, and the solver's verbatim wording behind a refusal is not recorded — the termination condition is. A solve that reached no objective wrote null and reads back as nan.

PARAMETER DESCRIPTION
directory

Where save wrote it. One that came out of an archive is load_archive's to find.

TYPE: str | Path

RETURNS DESCRIPTION
Result

The result, read whole: the frames are in memory when this returns, so

Result

it owes directory nothing. scan_result is the same answer left

Result

on disk.

RAISES DESCRIPTION
LayoutError

A directory holding no record.parquet, or one whose layout has moved since it was written.

load_sweep

load_sweep(directory)

Read back a sweep Sweep.save wrote, or one solve_over(spill_to=) spilled.

The sweep comes back held: every slice's frames are in memory when this returns, so it is the value a sweep solved without spill_to= is — Sweep.primal, Sweep.to_dataset and Sweep.save all answer, and it owes directory nothing afterwards. A sweep larger than memory is scan_sweep instead.

Sweep.record and Sweep.metrics are one row per slice either way, and original_index works on both, the manifest carrying the dimension a window sliced.

PARAMETER DESCRIPTION
directory

Where the sweep was written.

TYPE: str | Path

RETURNS DESCRIPTION
Sweep

The sweep, keyed as it was solved.

RAISES DESCRIPTION
LayoutError

directory holds no sweep.json, misses a record every fold writes, or is in a layout that has moved since it was written.

scan_archive

scan_archive(path, into=None)

Read an archive back off disk: the sources as paths, each frame read at the call that asks for it.

As load_archive, except that into is required for a zip, and kept: the members have to outlive the value. LayoutError for a zip with no into.

scan_result

scan_result(directory)

The answer under directory, read as its readers are called rather than now.

load_result's other half, and the same value: every reader answers what that one's does. What differs is when the bytes move — each frame is a polars.scan_parquet of the file it lies in, so an answer far larger than memory is readable a name at a time, and one whose names go unread costs nothing to open.

The files stay where they are, so they have to outlive the result: a name read after the directory is gone raises where the scan is collected, and a file rewritten underneath it comes back changed.

PARAMETER DESCRIPTION
directory

As load_result takes it.

TYPE: str | Path

RAISES DESCRIPTION
LayoutError

As load_result raises it.

scan_sweep

scan_sweep(directory)

The sweep under directory, its frames left where they lie.

load_sweep's other half, and the value a sweep solved with spill_to= already is: nothing but the record is read, and Sweep.scan reads a name back as a polars.LazyFrame when one is asked for. That is the reader for a sweep too large to hold, and it costs the frame readers: Sweep.primal and its siblings refuse, naming Sweep.scan.

directory has to outlive the sweep.

PARAMETER DESCRIPTION
directory

As load_sweep takes it.

TYPE: str | Path

RAISES DESCRIPTION
LayoutError

As load_sweep raises it.

Errors and warnings

Every error is one tree, rooted at SpecsolveError. A spec the language accepts and specsolve cannot build raises SpecsolveError itself, and its message names the rewrite. LanguageError, with SchemaError and DimensionError, is a fault in the spec, and is the language's own: which error you get.

SpecsolveError module-attribute

SpecsolveError = MathSpecError

The root. An alias, not a subclass, so except sps.SpecsolveError catches a LanguageError.

LanguageError

The spec is not sayable in the language, or does not obey its rules.

SchemaError

What a load refuses: an unknown key, a bad dtype, a duplicate YAML key, an unparseable or unresolvable expression.

DimensionError

A dim-set rule was violated. Raised at load time, before any data.

The rest are specsolve's:

DataError

Data attached to a valid spec is missing or the wrong shape.

LayoutError

What is on disk is not a layout this package reads.

The fix is which path was named, or re-solving a model whose layout has moved since it was written. The layout is the one save stamps.

NoSolutionError

The solve returned no values to read — infeasible, unbounded, errored.

A scenario sweep catches this and records the outcome; a LanguageError instead means the file needs editing.

SpecsolveWarning

Advice from check: the spec loads and solves, and reads wrong.

Raised for a spec that is still part-written, where an expression has not yet reached what it declares.

Rules across the verbs

What no single entry above holds, because every verb keeps it.

Names that differ only by case

Two declarations of one namespace whose names differ only by case are refused, whichever verb lowers the spec. Every declaration is written to disk as a file named after it, and a case-insensitive filesystem, which a stock macOS or Windows volume is, folds p and P into one file.

variable 'P' and variable 'p' differ only by case, and one answer on disk
cannot hold both: ... Tell them apart by a suffix rather than a capital:
'p_rated' beside 'p'.

The namespaces are the language's own: one flat namespace holding dimensions, relations, parameters, variables and named expressions, and constraints beside it. A constraint may carry a variable's name already, so a constraint P beside a variable p is accepted. The two are written under dual/ and primal/, which nothing folds together.

What each sink takes

check(spec, sink=...) asks whether a sink takes a spec, and solve and write read the same table, so a refusal comes whether or not it was asked for. Where a spec can land is a separate question from whether it is sayable. The four quadratic rows, and the two sections HiGHS writes but will not read back, are probed against the shipped solvers by tests/test_sink_capability_probes.py and tests/test_gurobi_capability_probes.py. The rest are read off the APIs.

lp_file mps_file HiGHS direct Gurobi direct Xpress direct
affine rows, COO, integrality text text, MARKER native native native
semi-continuous text not written — no SC bound kSemiContinuous native native
SOS1 / SOS2 text section SOS section no concept — refused, naming Spec.expand() addSOS native
indicator text section not written no concept addGenConstrIndicator native
convex quadratic objective text section not written passHessian setMObjective no path here
nonconvex quadratic objective text section not written refused native, at default parameters no path here
quadratic objective and integrality text section not written refused native (MIQP) no path here
quadratic constraint text section, unreadable not written no concept addQConstr no path here
  • HiGHS excludes quadratic twice: by convexity, and by conjunction with integrality.
  • The lp_file column says what can be written, not what reads back. The same HiGHS parser takes the quadratic-objective section and refuses the sos and quadratic-constraint sections.
  • "No path here" describes this package, not Xpress. The Optimizer takes a Hessian; the sink in solvers/xpress.py never hands it one.