Skip to content

Python API

Every public name, rendered from its docstring. A spec is the YAML file; what it may contain is the language.

Reference

specsolve holds what you call, specsolve.types what a call hands back, and specsolve.errors what a call raises or warns. Every other module starts with an underscore, and any other name under specsolve. is internal. The glossary defines the house terms.

Run a spec

check

check(spec)

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

Every other verb reads the spec through this, so what this refuses they refuse too. Whether a sink takes the model is a fact about the build, and Model.check_sink answers it with no solve.

PARAMETER DESCRIPTION
spec

A YAML path, a mapping, or a Spec — what mathspec.to_spec takes. A compiled 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 as binaries every sink takes.

TYPE: SpecLike

RETURNS DESCRIPTION
Program

The compiled program; typeset it or read its entries through

Program

mathspec. No verb takes it back; keep the

Program

Spec for that.

RAISES DESCRIPTION
LanguageError

A construct outside the language, a piecewise: block still to be written out, or a fragment that reads a name under given: — mathspec.merge composes it.

SpecsolveError

Two entries whose names differ only by case, or a name that starts with specsolve_ in any letter case, which is reserved.

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: SpecLike

sources

Parameter names to parquet paths or in-memory tables, and dimension names to their labels — a table of labels, a parquet path, or a bare sequence — wherever the YAML declares none. The shapes a value may take, and what attaching refuses, are the data contract. Each is read once and kept without a copy, so it must not change while the model or its answers are in use; change data through Model.update.

TYPE: Mapping[str, Source]

RETURNS DESCRIPTION
Model

The built model.

RAISES DESCRIPTION
LanguageError

A construct outside the language.

DataError

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

solve

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

Build spec and solve it in one call.

To solve the same spec again with new numbers, use build and Model.update.

PARAMETER DESCRIPTION
spec

As check takes it.

TYPE: SpecLike

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

also_record

As Model.solve takes them.

TYPE: Sequence[str] | None DEFAULT: None

archive

As Model.solve takes it — a .zip, or a directory.

TYPE: str | Path | None DEFAULT: None

outputs

As Model.solve takes them.

TYPE: Iterable[Output] DEFAULT: ()

start

As Model.solve takes it.

TYPE: Result | Start | None DEFAULT: None

RETURNS DESCRIPTION
Result

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

Result

released before this returns.

RAISES DESCRIPTION
SpecsolveError

A solver name nothing serves, or outputs that Model.solve refuses — both checked before the build — or as Model.solve raises.

write

write(spec, sources, out, *, names=False)

Build spec and stream it to out, in the format its suffix names.

PARAMETER DESCRIPTION
spec

As check takes it.

TYPE: SpecLike

sources

As build takes them.

TYPE: Mapping[str, Source]

out

Where to write; .lp and .mps ship, and name a model's columns and rows the same way.

TYPE: str | Path

names

Name each column and row by its entry and coordinate, as Model.write does.

TYPE: bool DEFAULT: False

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, read off the built model, naming the sinks that take it; or, with names, two coordinates of one entry that write as one name.

evaluate

evaluate(spec, sources, expression)

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

A spec with only dimensions, parameters, relations and expressions: is a calculation: each expression reads only the attached data. This attaches sources and values one expression, the way evaluate does at a solution. The spec is read as solve reads it; one that declares variables belongs there.

PARAMETER DESCRIPTION
spec

As check takes it.

TYPE: SpecLike

sources

As build takes them.

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 dimensions. Only

DataFrame

this expression's query is built.

RAISES DESCRIPTION
LanguageError

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

SpecsolveError

A spec that declares variables, constraints or an objective.

DataError

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

tidy

tidy(spec, sources)

The tables a solve of spec attaches from sources, one per name the spec declares.

Every source is read and checked as build does. The tables are what an archive holds under sources/, less its specsolve_run column, so a returned table goes back in as a source unchanged.

PARAMETER DESCRIPTION
spec

As check takes it.

TYPE: SpecLike

sources

As build takes them.

TYPE: Mapping[str, Source]

RETURNS DESCRIPTION
dict[str, DataFrame]

Each dimension as (dim, specsolve_position): its labels once each,

dict[str, DataFrame]

and the Int64 position from 0 that shift counts. The labels

dict[str, DataFrame]

of a str dimension are String, whatever encoding they arrived

dict[str, DataFrame]

in. Each parameter as (dims…, value) and each relation as the

dict[str, DataFrame]

columns it declares. Every other column is in the type it arrived in,

dict[str, DataFrame]

a datetime in microseconds.

RAISES DESCRIPTION
LanguageError

A construct outside the language.

DataError

As build refuses the sources.

Run it many times

Sweeps says how a sweep is cut and read.

solve_over

solve_over(spec, sources, over, *, executor=None, solver_options=None, also_record=None, solver_name='highs', archive=None, outputs=(), start='previous')

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

The rules are sweeps.

PARAMETER DESCRIPTION
spec

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

TYPE: SpecLike

sources

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

TYPE: Mapping[str, Source]

over

The axis: EachLabel or EachWindow, or the plain data its to_dict writes. An axis's carry= chains its slices, and its key_name= names the slice column.

TYPE: Axis | Mapping[str, Any]

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. A source given as a path crosses as the path, so every worker has to read it; pass the table instead where they cannot, and it crosses as parquet bytes.

TYPE: Executor | None DEFAULT: None

solver_options

As solve takes them.

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

also_record

As solve takes them, reaching every slice.

TYPE: Sequence[str] | None DEFAULT: None

solver_name

As solve takes it.

TYPE: str DEFAULT: 'highs'

archive

Where to write the model, the sources the sweep was cut from, the axis that cut them and every slice's answer, so that read_archive gives all four back and the sweep runs again from the file alone. A sliced source is archived whole. Anything but a .zip is a directory, and each slice's tables are written into it as the fold goes, one file per slice of each name under answer/<kind>/<name>/, so the sweep holds one slice in memory however many there are and Sweep.scan reads a name off it lazily. A directory holds one sweep: the same sweep run at it again does not solve the slices already there, which is how an interrupted sweep resumes. A .zip is packed into one file once the sweep ends, and the sweep returned then holds its answer in memory; an interrupted one leaves no file, and is not resumed. The sweep returned carries the archived sources: the paths under sources/ for a directory, the tables for a zip.

TYPE: str | Path | None DEFAULT: None

outputs

As solve takes them, reaching every slice. The sweep and its archive carry these and nothing else; an archive directory solved with others is refused rather than resumed.

TYPE: Iterable[Output] DEFAULT: ()

start

What each slice starts from, as solve takes it: an earlier answer, an earlier sweep, or a Start of tables. Each table is cut by the axis as a source is: one that carries the sliced dimension gives each slice its own rows, and one without reaches every slice whole. An earlier sweep is its answer, so each slice starts from the earlier slice of its key, and each window from the hours it covers. 'previous', the default, carries each slice on from the one before it on the model updated in place, as solve does, and under an executor starts every slice from nothing. None starts every slice from nothing.

TYPE: Sweep | Result | Start | Literal['previous'] | None DEFAULT: 'previous'

RETURNS DESCRIPTION
Sweep

The sweep, which reads its answer and carries the axis that cut it.

RAISES DESCRIPTION
SpecsolveError

Before a slice is taken: an over that is no axis, or a mapping whose keys name none; 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 tables carry; an axis the program does not allow; an archive directory holding another sweep, or this one solved from another spec, axis or sources; outputs that solve refuses; a start word other than 'previous' — each answerable from the entries alone; keys of more than one type, or two keys of one text; or a start solve refuses.

LayoutError

An archive directory that holds something other than a sweep archive, or one in a layout that has changed since it was written.

DataError

No source carries an EachLabel axis, a labels table carries it, an EachWindow axis's dimension has no labels, or the axis produced no slices.

WARNS DESCRIPTION
SpecsolveWarning

A source carrying an EachLabel axis that is short of a label another has — that slice builds it empty — or a start that leaves a slice no row, which starts that slice from nothing.

build_slice

build_slice(spec, sources, over, key, *, sweep=None)

Build the model of one slice of over, as solve_over builds it.

For looking at one slice alone: writing its LP file, reading a row, or solving it with other options.

PARAMETER DESCRIPTION
spec

As solve_over takes it.

TYPE: SpecLike

sources

The sources the sweep is cut from, as solve_over takes them. A parameter the axis carries is a source like any other: the slice is built from the value given here, whichever slice it is.

TYPE: Mapping[str, Source]

over

The axis, as solve_over takes it.

TYPE: Axis | Mapping[str, Any]

key

The slice's key, one of Sweep.keys: the label of an EachLabel slice, or the first label of an EachWindow window.

TYPE: Label

sweep

A sweep solved over these sources and this axis. Each carried parameter is then what the slice before key left in it, in place of the value in sources, so the model is the one that sweep solved. The first slice has none before it and takes sources as given, and so does every slice of an axis without a carry.

TYPE: Sweep | None DEFAULT: None

RETURNS DESCRIPTION
Model

The slice's model, as build returns it.

RAISES DESCRIPTION
SpecsolveError

A key that is no slice of the axis, a sweep in which the slice before key did not run or left no values, or an axis or a carry solve_over refuses.

DataError

As solve_over raises it.

EachLabel dataclass

EachLabel(dim, *, carry=dict(), key_name=None)

One slice per label of dim, a dimension the sources carry and the spec does not declare.

Scenarios, draws and investment periods are such dimensions.

Each slice squeezes dim: the parameters and relations carrying it are cut to one label and the column dropped, so the model never mentions it. A dim the spec declares is refused, and so is a labels table that carries it. Every other source passes through untouched. Slices run in sorted label order, and the answer lifts each label back as the key column, named dim unless key_name= names it.

carry={parameter: variable} chains them in that order: each slice's answer is copied into the next slice's data, and the first slice takes the parameter from the sources as its seed.

carry class-attribute instance-attribute
carry = field(default_factory=dict, kw_only=True, hash=False)

{parameter: variable} handed from each slice to the next; empty for slices that do not depend on one another.

dim instance-attribute
dim
key_name class-attribute instance-attribute
key_name = field(default=None, kw_only=True)

What to call the key column in every table of the answer; None takes the default the class documents.

to_dict
to_dict()

This axis as plain data, which solve_over takes in its place.

json.dumps writes it, and an archive's axis.json is this. It holds carry and key_name only where the axis sets them.

EachWindow dataclass

EachWindow(dim, *, horizon, lookahead, carry=dict(), key_name=None)

One slice per window of consecutive labels of dim, an ordered dimension the spec declares.

Each window keeps dim and is the model over its own labels: the labels of dim are narrowed to them, and every parameter and relation over dim is cut to the rows they hold. Nothing is squeezed or renamed, so the spec and the sources are the ones a single solve takes, and every table comes back over dim's own labels.

Each window keeps horizon labels and sees lookahead labels beyond them, so a lookahead above zero is overlap. An int keeps the same number every window; a sequence keeps those numbers in order, for horizons that grow window by window or a month at a time. Both count labels in label order, not values, so datetimes, strings and gapped integers all work.

A rule for a window's first row is written position(dim) == 0: a position counts within the window, which is what a rolling horizon seeding its opening state means. A label written as a literal names that one label in whichever window holds it.

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

carry={parameter: variable} chains the windows in order: each window's answer is copied into the next window's data. Where the two are over different dimensions, the dropped one is dim, and the row at the window's horizon end is handed on. The first window takes the parameter from the sources as its seed.

per_window=True reads each window under the key column, named <dim>_start unless key_name= names it.

carry class-attribute instance-attribute
carry = field(default_factory=dict, kw_only=True, hash=False)

{parameter: variable} handed from each window to the next; empty for windows that do not depend on one another.

dim instance-attribute
dim
horizon class-attribute instance-attribute
horizon = field(kw_only=True)
key_name class-attribute instance-attribute
key_name = field(default=None, kw_only=True)

What to call the key column in every table of the answer; None takes the default the class documents.

lookahead class-attribute instance-attribute
lookahead = field(kw_only=True)
to_dict
to_dict()

This axis as plain data, which solve_over takes in its place.

json.dumps writes it, and an archive's axis.json is this. It holds carry and key_name only where the axis sets them.

What comes back

Model

Model(spec, sources)

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

check → Program (the math) → build → Model (the math with your data) → solve → Result (one answer).

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

check_sink
check_sink(sink, *, names=False)

Refuse the built model where sink cannot take it; no solve, no file.

::

sps.build('dispatch.yaml', sources).check_sink('highs')

The answer is read off the built model, not the file: a square the data prices at zero, an integer variable with no built column or a set with no members asks for nothing. solve and write refuse exactly what this refuses, with the same message.

PARAMETER DESCRIPTION
sink

A solver name (highs, gurobi, xpress) or an output suffix (.lp, .mps).

TYPE: str

names

Also refuse what write's names refuses: two coordinates of one entry that write as one name. Read by an output suffix only.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
SpecsolveError

A construct the sink cannot take, naming it and the sinks that do; a name belonging to no sink; names for a sink that writes no file; or, with names, two coordinates of one entry that write as one name.

close
close()

Release the built model, and any solver still holding it. A Result keeps its own tables.

diagnostics
diagnostics()

What the build looks like that the answer does not show: what it left out and how its numbers spread.

Answerable after close, and after a build that raised. A raise leaves the sizes at zero, since they are taken once a model is whole, and everything measured before it stands.

infeasible_subsystem
infeasible_subsystem()

The rows and bounds that make the last solve infeasible, by entry and coordinate.

The verb for this model has no solution and I do not know why. It asks the solver that ran the last solve for an IIS (irreducible infeasible subsystem). The search runs only on this call, since it can cost more than the solve, and under the solve's solver_options, so a solver's IIS settings and time limit go there. Read a member row's terms with row.

Every sink finds one for a linear model. For a discrete model, every sink leaves out the integrality that makes the rows and bounds conflict, and highs can find none where integrality causes the conflict.

RAISES DESCRIPTION
SpecsolveError

The model has not been solved since it was built, updated or closed; the last solve was not infeasible; or the solver found no subsystem, or stopped at a limit before it was irreducible.

Example

model.solve().termination_condition # doctest: +SKIP 'infeasible' print(model.infeasible_subsystem()) # doctest: +SKIP balance[snapshot=1] == 200 p[snapshot=1, tech=gas] <= 100 (upper bound) p[snapshot=1, tech=wind] <= 50 (upper bound)

metrics
metrics()

This model's size, counters and clocks over its whole life, taken now.

solves counts every solve, and each clock sums every lap of its phase in timings. A result's metrics is its run's, frozen when it was handed back, so an archive's landing, which comes after, is in the run here and not in the result. Answerable after close, and after a build that raised, which leaves the sizes at zero.

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. It reads the built model and needs no solve: a term whose variable was absent is missing, and a row a where leaves absent is not there at all. 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 dimension 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 dimensions, 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[snapshot=1, tech=wind] +50 p[snapshot=1, tech=gas] >= 60

solve
solve(solver_name='highs', *, solver_options=None, also_record=None, archive=None, outputs=(), start='previous')

Hand the built model to a solver and solve it.

A solver that can stay loaded is kept between calls, so an updated model pushes only its numbers; diagnostics counts the solves that loaded it again.

PARAMETER DESCRIPTION
solver_name

highs, which ships with the package; gurobi, which needs the [gurobi] extra; or xpress, which needs the [xpress] extra.

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. The result's provenance records the value of an option that changes the answer, such as a time limit or a gap, and the name alone of any other.

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

also_record

Option names whose value the result records as well, beside the ones the solver records already, in any letter case. Name no credential here: an archive goes to shared storage.

TYPE: Sequence[str] | None DEFAULT: None

archive

Where to write the spec, the data attached to it now, and this answer, so that read_archive gives all three back and the model solves again from the file alone. A .zip suffix packs it into one file; anything else is a directory. What the build and its solves spent goes in beside the answer, as Metrics. Each source goes in as the table tidy returns, with specsolve_run added, and members are stored uncompressed. The answer returned carries the archived sources: the paths under sources/ for a directory, the tables for a zip.

TYPE: str | Path | None DEFAULT: None

outputs

Each Output the answer carries beside the primal, the duals and the declared expressions: activity for each constraint's left-hand side, reduced_cost for each variable's reduced cost, slack for each constraint's distance to binding, and basis for the basis status each variable and constraint ended on, read with variable_basis and constraint_basis. The result and its archive carry these and nothing else, and the reader of one not asked for refuses.

TYPE: Iterable[Output] DEFAULT: ()

start

What the solve begins from; it changes how the solver gets to the optimum, never which one. 'previous', the default, carries on from the last solve while the solver stays loaded, and begins from nothing after an update that loads it again. None begins from nothing. An earlier answer, live or read from an archive, or a Start of tables keyed by reader, is matched by coordinate, so one from another build of the spec, with rows or columns gained or lost, starts it too. An LP starts from a basis where one is given, which an answer carries when solved with outputs={'basis'}: a coordinate it leaves out starts at a bound if it is a variable's, and not binding if it is a constraint's. Otherwise an LP, and a mixed-integer model always, starts from values, which the solver completes and repairs. Where a solver takes values for an LP and no gain from them is known, the solve warns.

TYPE: Result | Start | Literal['previous'] | None DEFAULT: 'previous'

RETURNS DESCRIPTION
Result

The solution, holding this model.

RAISES DESCRIPTION
SpecsolveError

A solver name nothing serves, one this environment cannot run, a bare string as also_record or outputs, a name in outputs that is not an output, a start word other than 'previous', or a start this model or solver cannot start from: a key that names no reader, a table naming no entry or lacking its dimensions, a basis status outside the five words, a basis alone for a mixed-integer model, a start that lands on no coordinate, or values for an LP that the solver cannot take.

LayoutError

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

timings
timings()

Every lap of this model's life, one row each: (run, phase, step, entry, seconds).

Each lap begins where the one before it ended, so the rows of a phase add up to its *_seconds in metrics, and the rows of a run to what the model took between handing back two results. run counts the results handed back before the lap: 0 up to the first. step says what a lap did inside a phase that has steps, and entry names the entry it built. The build's steps are variable, sos and constraint, one row per entry; the objective, which has no name; matrix, every constraint's share stacked into one matrix in row order; and sink_tables, the rest of what a solver is handed. An entry's seconds are its own: they hold when the entries build in another order. An update that gives only new numbers logs splice, the entries it reads again and sink_tables. The tidy's steps are read, every path read at once, and shape, one row per dimension, relation and parameter, each held to its columns and their types, the first parameter's also holding every parameter's shaping, and a last row with no entry for the refusal that needs every source read. The attach's steps are encode, one row per relation and parameter, its labels turned into its dimensions' own type; content, one row per relation and parameter, checked to hold only its dimensions' labels, no coordinate twice, and a row wherever it refuses to lack one; fill, the missing rows a divisor reads written in; specialize, each condition the data decides read once and the program rewritten with them; and assumptions, the spec's assumptions checked. An update logs a shape, encode and content row only for a parameter it reads again. The handoff's steps are digest, the held solver's fingerprint of its model, read before a rebuild; match, the start= matched to this build; capability, the solver checked to take the model; push, the held solver kept and the new numbers pushed onto it, or solver_instance, a new solver instance given the model, the held one closed, as solver_instances counts them; and start, the start given to the solver, or its last solve forgotten. The same steps for every solver. Elsewhere both are null.

update
update(sources)

Put new numbers on the same model, in place.

::

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

model.update(x) answers what build(spec, sources | x) answers, whatever changed. Data that changes which coordinates a condition admits renumbers solver indices, so the model is rebuilt and solved cold rather than pushed onto a loaded solver; solver_instances says which ran.

Results taken before the update keep reading their own tables, and keep their build's index tables alive until dropped or until close is called. A sweep, a rolling horizon or a myopic pathway is solve_over, which runs this loop.

A parameter whose own source and whose dimensions' labels sources leaves alone is not read or checked again: a file rewritten in place at a path it was built from is read once its name is passed again.

PARAMETER DESCRIPTION
sources

Only what changed; the rest keeps what build attached. A dimension's labels count too, 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, refused before anything changes. Data the build refuses releases the model, as a build that raises does.

write
write(path, *, names=False)

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

PARAMETER DESCRIPTION
path

Where to write; the suffix picks the format.

TYPE: str | Path

names

Name each column and row by its entry and coordinate, p(2030,wind) and balance(2030), rather than x7 and c3. A label keeps letters, digits and !"#$%&'.;?@`{|}~ and writes any other character as _; an entry with no dimensions is total(). LP and MPS name a model the same way either way.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError

A suffix nothing writes.

SpecsolveError

What check_sink refuses for this suffix and names.

ConstraintRow dataclass

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

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

The row at one coordinate as the model built it, read off the built model, so it needs no solve. where: conditions, absent variables and coefficients the data made exactly zero have already removed their terms, so it can be shorter than the file suggests.

Printed, it is one line of math, each term at its named coordinate; a row wider than display_terms prints each variable's term count and coefficient span instead. terms is the same content as a table.

ATTRIBUTE DESCRIPTION
name

The constraint this row belongs to.

TYPE: str

coordinate

Where in that entry 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 coordinate as one string, t=1, g=gas, in its variable's dimension order.

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(_answer, _expressions=Expressions(), _dual_rays=None, _no_dual_ray=None, _spec=None, _sources=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 an update, another solve or model.close(). It keeps the index tables of the build it answered alive until close, which is optional.

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.

metrics property
metrics

What reaching this answer took — its solve's share of the model's clocks — or None for one built by hand.

The share runs from where the model's previous answer was handed back, so the first answer of a model carries its load and its build, and a later one the update, handoff and solve that led to it. solves is 1. An answer solved with archive= also carries the archive, as the archive records it. Read back as it was written.

objective property
objective

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

provenance property
provenance

The solver, its options and the package versions that produced this answer.

Read back as it was written, so an answer read from an archive names the environment that solved it rather than the one reading it.

record property
record

How this solve terminated, as the one row an archive writes for it, which adds the run.

A sweep keeps the same row per slice in records. objective is None rather than nan where there are no values.

solved_at property
solved_at

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

solver_settings property
solver_settings

The solver and options this answer was solved with, as the keywords every solving call takes.

sps.solve(result.spec, result.sources, **result.solver_settings) asks the question again on the same solver and options. Read off provenance, so an answer read from an archive gives what that archive recorded. An option it kept no value of holds '<not recorded>', which every solving call refuses by name: pass the value again, as {**settings['solver_options'], name: value}.

RAISES DESCRIPTION
SpecsolveError

No solve wrote this answer, so it records no solver.

sources property
sources

The data this answered, keyed as the file declares it, as its archive holds it; None where no archive holds this answer.

An answer solved with archive= into a directory holds the path to each sources/<key>.parquet and no table in memory; into a .zip, which has no file to point at, the tables the archive was written from. read_archive gives each source as the table tidy returns, and scan_archive the path to its member. sps.solve(result.spec, result.sources) asks the question again.

spec property
spec

The spec this answered, as written; None where the solve ran off a compiled program.

Two answers whose specs compare equal answered the same document, perhaps over other data.

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, and readable whenever there is a solution, a mixed-integer one included. Carried only where the solve was asked for it with outputs={'activity'}.

RAISES DESCRIPTION
NoSolutionError

The solve left no values to read.

SpecsolveError

This result was closed, or the solve was not asked for its activity.

KeyError

No constraint is called name.

close
close()

Release this result's tables, and its hold on the build's index tables, early. Optional.

Tables already read stay valid. The model and the solver are the Model's to close.

constraint_basis
constraint_basis(name)

The basis status of each row of constraint name where the solve ended — (dims…, value), dual's shape and order.

In variable_basis's words, with the right-hand side as the row's bound: a binding <= row is at_upper, a binding >= row at_lower, a binding == row fixed, and a row that is not binding basic. Carried only where the solve was asked for it with outputs={'basis'}, and only an LP that ended on a basis has one.

RAISES DESCRIPTION
NoSolutionError

The solve left no values to read.

SpecsolveError

This result was closed, the solve was not asked for its basis, or it ended on none.

KeyError

No constraint is called name.

dual
dual(name)

Shadow prices of constraint name — (dims…, value), primal's shape and order.

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 dual(c) for every comparator, sense and sink, so which side a term is written on decides the sign.

Duals exist only where a solver ran here, not for a model written to a file and solved elsewhere.

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 or an sos: set makes them undefined, whichever solver branched on it.

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, 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, and the row's own sign on every sink. Where every column is held only by a lower bound of zero, the proof is Σ weight * right-hand side > 0.

highs always produces a certificate; gurobi needs {'InfUnbdInfo': 1} and xpress needs {'presolve': 0} in solver_options, set before the solve. A ray is live only: an archive holds none.

RAISES DESCRIPTION
SpecsolveError

This result was closed; it was read out of an archive; the solve was not infeasible; or the sink produced no ray, in which case the message names the solver option that would have.

KeyError

No constraint is called name.

evaluate
evaluate(expression)

The value of expression at this solution — (dims…, value), primal's shape and order.

expression is what one expressions: entry takes: a name the file declares, an expression string, or the mapping carrying cases: with dims: and otherwise:. The value is aggregated to the expression's own dimensions, in the order it declares them.

Anything but a declared name compiles the spec as written, which costs what check costs. An archive holds only the expressions declared under expressions:.

RAISES DESCRIPTION
NoSolutionError

The solve left no values to read.

SpecsolveError

This result was closed; an undeclared expression on a model built from a compiled Program, which has nothing to compile it against; an archive whose sources build another model than the one this answered; or a divisor with no value.

LanguageError

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

primal
primal(name)

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

Rows come back in index 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.

reduced_cost
reduced_cost(name)

Reduced costs of variable name — (dims…, value), primal's shape and order.

Each is the rate at which the optimal objective rises as the variable's binding bound rises, in the sign convention of dual for every sense and sink: of x >= l, the rate in d of x >= l + d. A variable strictly between its bounds has zero.

It is computed from the duals as the objective's gradient less each row's gradient times that row's dual, so it exists wherever dual does and nowhere else. Carried only where the solve was asked for it with outputs={'reduced_cost'}.

RAISES DESCRIPTION
NoSolutionError

The solve left no values at all.

SpecsolveError

This result was closed; the solve was not asked for reduced costs; or it left primals but no duals, as dual raises.

KeyError

No variable is called name.

slack
slack(name)

How far constraint name is from binding at the solution — (dims…, value), dual's shape and order.

Non-negative wherever the row holds, whichever side a term is written on: rhs - lhs for <=, lhs - rhs for >=, and -|rhs - lhs| for ==, which holds only at zero. A binding row reads zero, and a violated one, such as at an incumbent within the solver's tolerance, reads below zero by how much. Computed from activity, so readable wherever it is, and carried only where the solve was asked for it with outputs={'slack'}.

RAISES DESCRIPTION
NoSolutionError

The solve left no values to read.

SpecsolveError

This result was closed, or the solve was not asked for its slack.

KeyError

No constraint is called name.

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 dimensions: an absent coordinate comes back NaN.

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

The named values of one kind as one xarray.Dataset; every name of that kind where none is given.

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

to_pandas
to_pandas(name, kind='primal')

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

name is read through the reader kind names: primal, dual, expression, or the reader of an Output the solve was asked for. Needs pandas, which specsolve does not install; the xarray bridges need xarray too.

variable_basis
variable_basis(name)

The basis status of each column of variable name where the solve ended — (dims…, value), primal's shape and order.

value is one of basic, at_lower, at_upper, fixed (nonbasic at bounds that are equal) and superbasic (nonbasic between its bounds), in that order as an Enum, the same words for every sink. Carried only where the solve was asked for it with outputs={'basis'}, and only an LP that ended on a basis has one.

RAISES DESCRIPTION
NoSolutionError

The solve left no values to read.

SpecsolveError

This result was closed, the solve was not asked for its basis, or it ended on none.

KeyError

No variable is called name.

InfeasibleSubsystem dataclass

InfeasibleSubsystem(constraints, bounds)

The rows and bounds that cannot hold together — what infeasible_subsystem returns.

Irreducible: drop any one member and the rest can hold. A model can have several, and each solver may find a different one. Printed, it is one line per member, constraints first.

ATTRIBUTE DESCRIPTION
constraints

(dims…, sense, rhs) per constraint with a row in it, in entry order, its rows in index order.

TYPE: Mapping[str, DataFrame]

bounds

(dims…, bound, value) per variable with a bound in it, in entry order. bound is lower or upper.

TYPE: Mapping[str, DataFrame]

bounds instance-attribute
bounds
constraints instance-attribute
constraints

Sweep dataclass

Sweep(key_name, records, metrics, spec, sources=None, axis=None, _slices=dict(), _reasons=dict(), _stitch=None, _outputs=frozenset(), _evaluate=None)

What a fold returned: the answer over the model's own coordinates, and a record per slice.

Result's readers, same names and shapes, and each returns the answer by default. An EachWindow sweep is read over the dimension it sliced: each coordinate comes from the window whose horizon holds it, and the lookahead rows are dropped. An EachLabel sweep is keyed by slice, the key prepended, each slice being a whole answer. Nothing is combined across slices.

per_window=True reads an EachWindow sweep one window at a time: keyed by where each window started, over the window's own labels, lookahead rows included.

axis class-attribute instance-attribute
axis = None

What cut the sources, with the carry= it chained the slices with, archived or not; None only for a sweep no solve_over made. sps.solve_over(sweep.spec, sweep.sources, sweep.axis) runs it again.

key_name instance-attribute
key_name
keys property
keys

Each slice's key, in slice order.

A key is the label of an EachLabel slice, or the first label of an EachWindow window.

metrics instance-attribute
metrics

One Metrics per slice, keyed as records is and in slice order — diagnostics one dimension wider, its counts and clocks only. Each row is the slice's own share: solves is 1, and solver_instances is 1 where the slice took a new solver. Under a serial fold the first slice does and the rest are pushed values, so a later 1 is a slice whose data changed what a condition leaves absent; under an executor every slice builds alone and takes its own. So a slow sweep says which slice, and which phase of it.

records instance-attribute
records

One Record per slice, in slice order — how every slice terminated, whether or not it produced an answer. The key column comes first, as its own type, so the table joins to the tables; slice_axis and slice name the slice again as text, and are what an archive writes in its place. A slice that reached no objective holds null there rather than nan, so the column aggregates over the slices that solved.

solver_settings property
solver_settings

The solver and options every slice was solved with, as the keywords every solving call takes.

sps.solve_over(sweep.spec, sweep.sources, sweep.axis, **sweep.solver_settings) runs the sweep again on the same solver and options. Read off records, as Result.solver_settings reads one answer's.

RAISES DESCRIPTION
SpecsolveError

The slices were solved with different settings, as a resumed directory archive can be, or no solve wrote them.

sources class-attribute instance-attribute
sources = None

The data the sweep was cut from, uncut and keyed as the file declares it, as its archive holds it; None where no archive holds this sweep. A source an EachLabel axis cuts holds the axis column first. Each is held as Result.sources holds one: a path into a directory archive, a table for a .zip and for a read, a path for a scan.

spec instance-attribute
spec

The spec every slice answered, as written; None only for an archive whose answer holds none.

activity
activity(name, *, per_window=False)

One constraint's left-hand side at every slice's solution.

primal's shape and arguments, and carried only where the sweep was asked for it with outputs={'activity'}. In the answer of an EachWindow sweep each coordinate carries the window whose horizon holds it.

RAISES DESCRIPTION
SpecsolveError

The sweep was not asked for its activity, or as primal raises.

constraint_basis
constraint_basis(name, *, per_window=False)

One constraint's basis status where every slice's solve ended.

primal's shape and arguments, and Result.constraint_basis's words. Carried only where the sweep was asked for it with outputs={'basis'}. A slice that ended on no basis contributes none.

RAISES DESCRIPTION
SpecsolveError

The sweep was not asked for its basis, no slice ended on one, or as primal raises.

dual
dual(name, *, per_window=False)

One constraint's shadow prices.

primal's shape and arguments. A slice whose model had an integer variable contributes no duals. In the answer of an EachWindow sweep each coordinate carries the price of the window whose horizon holds it, never a blend of several.

RAISES DESCRIPTION
SpecsolveError

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

evaluate
evaluate(expression, *, per_window=False)

The value of expression at every slice's solution, as an answer.

evaluate over the sweep, with primal's shape. A declared name is read from what the sweep holds, live or off disk. Anything else is valued at each slice's own solution with no re-solve, which needs the spec, sources and axis the sweep read_archive hands back carries; a Sweep a live solve returned 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.

In an EachWindow sweep's answer each coordinate carries the value of the window whose horizon holds it, so a sum does not double-count the lookahead.

PARAMETER DESCRIPTION
expression

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

TYPE: str | Mapping[str, object]

per_window

Read an EachWindow sweep one window at a time instead of its answer.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
SpecsolveError

No slice produced a declared expression (an evaluation that failed on every slice carries its own reason); an undeclared expression on a Sweep with no model behind it, or one that reads a parameter the sweep carried; a quantity reduced over an EachWindow sweep's windowed dimension, which has an answer only per window; or per_window as primal raises it.

LanguageError

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

primal
primal(name, *, per_window=False)

One variable's answer.

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

PARAMETER DESCRIPTION
name

A variable the sweep's spec declares.

TYPE: str

per_window

Read an EachWindow sweep one window at a time instead of its answer.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
SpecsolveError

No slice of the sweep produced name; a variable that is not over an EachWindow sweep's windowed dimension, which has an answer only per window; or per_window on a sweep that was not cut into windows.

reduced_cost
reduced_cost(name, *, per_window=False)

One variable's reduced costs at every slice's solution.

primal's shape and arguments, and Result.reduced_cost's sign. Carried only where the sweep was asked for it with outputs={'reduced_cost'}. A slice whose model had an integer variable contributes none, as it contributes no duals.

RAISES DESCRIPTION
SpecsolveError

The sweep was not asked for reduced costs, no slice produced them — the message says why — or as primal raises.

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

One name's answer as a polars.LazyFrame: primal, dual, evaluate or an output, not collected.

On a sweep whose tables lie on disk — solved with archive= a directory, or read by scan_archive — nothing is read until the table is collected, so a filter or a select runs before the bytes move.

PARAMETER DESCRIPTION
name

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

TYPE: str

kind

primal, dual, expression, or an Output the sweep was asked for — the reader this stands in for.

TYPE: str DEFAULT: 'primal'

per_window

Read an EachWindow sweep one window at a time instead of its answer.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
SpecsolveError

No slice produced name, a kind that names no reader, an output the sweep was not asked for, or per_window where there are no windows to read.

slack
slack(name, *, per_window=False)

One constraint's distance to binding at every slice's solution.

primal's shape and arguments, and Result.slack's sign. Carried only where the sweep was asked for it with outputs={'slack'}.

RAISES DESCRIPTION
SpecsolveError

The sweep was not asked for its slack, or as primal raises.

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

One name's answer as a xarray.DataArray; to_pandas's arguments.

An EachWindow sweep's answer is indexed by the dimension it sliced. Any other sweep adds the slice key as a dimension named by the axis, (scenario, …), and a read per window adds <dim>_start; there a slice that reached no solution comes back NaN, as an absent coordinate does from Result.

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

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

PARAMETER DESCRIPTION
names

What to include; none means every name of kind the sweep has an answer for. A name an EachWindow sweep cannot stitch is left out, as an archive leaves out its file; named, or read per_window, it is read as primal reads it.

TYPE: str DEFAULT: ()

kind

As scan takes it.

TYPE: str DEFAULT: 'primal'

per_window

Read an EachWindow sweep one window at a time instead of its answer.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
SpecsolveError

The sweep has no answer of kind at all — the message names each name it left out, and why — or as primal raises.

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

One name's answer as a tidy pandas.DataFrame; scan's arguments.

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

variable_basis
variable_basis(name, *, per_window=False)

One variable's basis status where every slice's solve ended.

primal's shape and arguments, and Result.variable_basis's words. Carried only where the sweep was asked for it with outputs={'basis'}. A slice that ended on no basis contributes none.

RAISES DESCRIPTION
SpecsolveError

The sweep was not asked for its basis, no slice ended on one, or as primal raises.

ArchivedInputs dataclass

ArchivedInputs(spec, sources, axis)

A spec and the data it was solved with, read off an archive without its answer.

sps.solve(inputs.spec, inputs.sources) asks the question again, and sps.solve_over(inputs.spec, inputs.sources, inputs.axis) runs a sweep again.

ATTRIBUTE DESCRIPTION
spec

The spec as written.

TYPE: Spec

sources

What was attached, keyed as the file declares it, as the tables tidy returns. A sweep's are uncut, as Sweep.sources holds them.

TYPE: Mapping[str, Source]

axis

What cut the sources, with the carry= it chained the slices with, or None for an archive of one solve.

TYPE: Axis | None

axis instance-attribute
axis
sources instance-attribute
sources
spec instance-attribute
spec

The rows and tables those hand back:

Diagnostics dataclass

Diagnostics(omissions, sparse_parameters, coefficient_range, bound_range, rhs_range, objective_range)

What the build looks like that the answer does not show: per entry, what it left out and how its numbers spread.

Advisory, all of it: no answer depends on any field. What the build and its solves took is Model.metrics, lap by lap Model.timings.

bound_range instance-attribute
bound_range

(variable, smallest, largest) — the bound magnitudes each variable put on its columns, one row per variable 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 put in the matrix, one row per constraint that kept a term, in build order. largest / smallest over the table is the conditioning to compare against the solver's.

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 because a propagated absence deleted it. A row left with no variable is built, so it is not here. Empty where every declared row was built. A recurrence's first coordinate counts, so a shift against the edge of its dimension reports here, as the boundary rather than a fault.

rhs_range instance-attribute
rhs_range

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

sparse_parameters instance-attribute
sparse_parameters

(parameter, coordinates, rows, missing) — one row per parameter whose source is short of the coordinates its dimensions reach, in entry order. Empty where every one is complete. A row is a report, not a fault: a missing row is how data leaves a coordinate absent. A parameter over no dimensions is never here.

Record

How a solve terminated, what it reached, and when.

One row per solve, and the same columns whoever wrote them: a result writes one, a sweep one per slice, which slice_axis and slice name. A run that left no values writes this and nothing else.

dual_bound class-attribute instance-attribute
dual_bound = None

The bound the solver's search proved on the optimum, on the objective this row holds: no better objective exists than this. Null where no search proved one, as an LP or a run stopped before its first bound. A mixed-integer solve searches, and so does Gurobi on a quadratic model that is not convex. linopy calls it dual_bound too.

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.

mathspec_version class-attribute instance-attribute
mathspec_version = None
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.

optimality_gap class-attribute instance-attribute
optimality_gap = None

The relative optimality gap: how far objective may still be from the optimum, |objective - dual_bound| / |objective|. Not a duality gap, nor the gap tolerance a solve was asked for. Computed here from the two columns rather than taken from the solver, whose formulas differ, so one definition holds for every solver. Null without both numbers, or where the objective is zero.

provenance property
provenance

What produced the answer this row records.

slice class-attribute instance-attribute
slice = None
slice_axis class-attribute instance-attribute
slice_axis = None

What the sweep that solved this called its slices — scenario, snapshot_start, draw — and which slice this is, as text. Both null for a single solve. Fixed names rather than a column named for the axis, so every table written here has the same columns.

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.

solver class-attribute instance-attribute
solver = None

Provenance's fields, one column each.

solver_options class-attribute instance-attribute
solver_options = None
solver_version class-attribute instance-attribute
solver_version = None
specsolve_run class-attribute instance-attribute
specsolve_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. Every other table the archive holds carries the same column, specsolve_run.

specsolve_version class-attribute instance-attribute
specsolve_version = None
status instance-attribute
status
termination_condition instance-attribute
termination_condition
of classmethod
of(termination_condition, objective, *, has_primal, solved_at, provenance=NO_PROVENANCE, dual_bound=None)

The row a solve that terminated this way writes; each argument fills the column of its name.

status is derived from termination_condition, objective is kept only where has_primal says there are values, optimality_gap is computed from it and dual_bound, and provenance fills its own fields' columns.

Provenance

What produced an answer: the solver, the options it ran with, and the packages that built the model.

Enough to install the same environment again and ask the same question. Every field is None for an answer no solve wrote, such as one built by hand.

mathspec_version class-attribute instance-attribute
mathspec_version = None
solver class-attribute instance-attribute
solver = None

The solver's name, as solver_name takes it.

solver_options class-attribute instance-attribute
solver_options = None

The options the solver ran with, as one JSON object with sorted keys: {} where none were passed. An option that changes the answer, such as a time limit or a gap, keeps its value, and an infinite or nan one is the string "inf", "-inf" or "nan"; any other has the value <not recorded>, so a licence credential reaches an archive only where also_record names it.

solver_version class-attribute instance-attribute
solver_version = None

The installed version of the solver's Python package.

specsolve_version class-attribute instance-attribute
specsolve_version = None

SolverSettings

The solver and options an answer was solved with, in the keywords every solving call takes.

sps.solve(result.spec, result.sources, **result.solver_settings) asks the question again on the same solver and options. Each value is exactly what the record holds, converted to nothing. An option whose value the answer did not record keeps '<not recorded>', which every solving call refuses by name, so a solve never runs on a value nobody chose. An infinite number is recorded as the string 'inf', which HiGHS reads as the number and Gurobi and Xpress refuse: pass the number again for those.

solver_name instance-attribute
solver_name

The solver, as solver_name takes it.

solver_options instance-attribute
solver_options

Each option the solve was given, with its recorded value or '<not recorded>'.

Metrics

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

The same columns whoever writes them — a result, an archive, a sweep's slice, or Model.metrics — so rows from unrelated runs concatenate into one table.

The *_seconds columns are the phases of a call, in the order they run: load, tidy, attach, build, handoff, solve, readback, write and archive. Each starts from what the one before it produced, so together they are the whole call and no step is in two of them; each column says what its phase holds. A phase that never ran reads zero rather than no column. phases lays them out as a table.

Cumulative over the solves it counts, which solves says: every solve of the model on Model.metrics(), and 1 on the row of a result, an archive and a sweep's slice, whose clocks are that solve's own share, from where the answer before it was handed back. There solver_instances is 1 where the solve took a new solver and 0 where its values were pushed onto the one held, and load_seconds is on the row of the answer that built the model. A slice's write_seconds and archive_seconds are zero: a sweep writes no model file, and cutting, stitching and archiving the sweep are not one slice's.

archive_seconds instance-attribute
archive_seconds

The spec, the sources and the answer written to disk. Every member is timed but this row itself, which is written last: writing it and landing the archive are in its run in Model.timings and in Model.metrics, not in this row.

attach_seconds instance-attribute
attach_seconds

The tidy tables encoded against the program's dimensions, a parameter's missing rows filled or refused, and the spec's assumptions: checked on them.

build_seconds instance-attribute
build_seconds

Every entry into the model's columns, rows and matrix.

columns instance-attribute
columns

How many columns the build produced: one per variable at each coordinate it exists at.

handoff_seconds instance-attribute
handoff_seconds

A start= read and matched to this build, the solver checked to take the model, the model loaded into a new solver or its new numbers pushed onto the one held, and the start given. After an update it also holds the held solver's digest of its last model, which decides between the two.

load_seconds instance-attribute
load_seconds

mathspec's load: to_spec on the spec as given, a path read and parsed, every rule that needs no data checked, and the program compiled. Creating a solver is handoff_seconds's.

nonzeros instance-attribute
nonzeros

How many coefficients the constraint matrix holds: one per row and column a linear term reaches, the terms at one pair summed and a sum of exactly zero dropped. A quadratic term is not one.

phases property
phases

The clocks as a table, one row per phase in the order the phases run: (phase, seconds).

A phase that never ran is a row of zero. Each phase is defined beside its *_seconds column.

readback_seconds instance-attribute
readback_seconds

Those vectors laid out by coordinate as the result, and when and how it was solved recorded on it. Its tables are read lazily, so turning one into rows is spent where it is read: in archive_seconds for an archive, in your code otherwise.

rows instance-attribute
rows

How many rows the build produced: one per constraint at each coordinate it is built at, a row with no term or whose terms sum to zero among them.

slice class-attribute instance-attribute
slice = None
slice_axis class-attribute instance-attribute
slice_axis = None

Which sweep slice this row is, as Record.slice_axis and Record.slice say it; null for a single solve.

solve_seconds instance-attribute
solve_seconds

The solver's own run, up to the vectors it returns.

solver_instances instance-attribute
solver_instances

How many solver instances those solves took: a new one wherever the solver could not keep the model and take its new values. As many as there are solves on an iterating driver means the model has a condition on a parameter that varies.

solves instance-attribute
solves

How many solves the row covers. The clocks are cumulative over exactly these solves.

specsolve_run class-attribute instance-attribute
specsolve_run = None

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

tidy_seconds instance-attribute
tidy_seconds

The source keys checked against the spec, and each source read into its tidy table, the way tidy returns it.

write_seconds instance-attribute
write_seconds

The format checked to take the model, and the model streamed to an LP or MPS file by write.

Output module-attribute

Output = Literal['activity', 'reduced_cost', 'slack', 'basis']

What an answer carries only where the solve asked for it with outputs=, beside the primal, the duals and the declared expressions it always carries. activity is each constraint's left-hand side at the solution, reduced_cost each variable's reduced cost, slack each constraint's distance to binding, and basis the basis status the solve ended on, of each variable and each constraint.

Start

What a solve starts from, given as tables: under the name of each reader, a table per entry in that reader's shape.

Each table is (dims…, value) and is matched by coordinate, so it may leave out entries and coordinates. primal gives values, and variable_basis and constraint_basis give a basis status in Result.variable_basis's words, as a string or as that Enum. An earlier Result is the same, from the tables it carries. Given to solve_over, a table that carries the sliced dimension is cut per slice, as a source is.

Example::

start: Start = {
    'primal': {'on': on},
    'variable_basis': {'p': p_status},
    'constraint_basis': {'balance': balance_status},
}
constraint_basis instance-attribute
constraint_basis
primal instance-attribute
primal
variable_basis instance-attribute
variable_basis

Read an answer back

An answer carries its sources exactly where an archive holds it:

result = sps.solve(spec, sources)  # result.sources is None: no archive
result = sps.solve(spec, sources, archive='case/')  # the paths under case/sources/
result = sps.read_archive('case/')  # the tables
sps.solve(result.spec, result.sources, **result.solver_settings)

read_archive

read_archive(path, into=None)

Read an archive back whole: the answer, its tables in memory, carrying the spec and the sources as tables.

sps.solve(result.spec, result.sources) asks the question again, and sps.solve_over(sweep.spec, sweep.sources, sweep.axis) runs a sweep again.

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
Result | Sweep

The Sweep where the archive carries an axis, with its

Result | Sweep

sources uncut and its

Result | Sweep

axis; the

Result | Sweep

Result where it does not, with its

Result | Sweep

sources and the

Result | Sweep

metrics reaching it took.

RAISES DESCRIPTION
LanguageError

A spec.yaml the language does not accept.

LayoutError

A member outside the layout, an into given for a directory, or a spec, sources or answer whose layout has changed since it was written. Where only the answer's has, read_inputs still reads the spec and the sources.

SpecsolveError

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

BadZipFile

A file that is not a zip archive.

read_inputs

read_inputs(path, into=None)

Read the spec and the data an archive holds, without its answer.

The spec and the sources have a layout of their own, so this reads an archive whose answer read_archive refuses because its layout has moved.

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

RAISES DESCRIPTION
LanguageError

A spec.yaml the language does not accept.

LayoutError

A member outside the layout, an into given for a directory, or a spec and sources whose layout has changed since they were written.

BadZipFile

A file that is not a zip archive.

scan_archive

scan_archive(path, into=None)

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

As read_archive, except that into is required for a zip, and kept, since the members have to outlive the value; a zip with no into raises LayoutError.

Errors and warnings

Every error is rooted at SpecsolveError. A spec the language accepts and specsolve cannot build raises SpecsolveError itself. LanguageError, SchemaError and DimensionError are faults in the spec, and the language's own: which error you get.

SpecsolveError

Base class for every error this package raises on purpose.

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 changed since it was written. The layout is the one an archive stamps in its format.json.

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 functions

Names that differ only by case

Two entries of one namespace whose names differ only by case are refused by every function. A case-insensitive filesystem folds p and P into one file on disk.

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'.

Constraints are a namespace of their own, so a constraint P beside a variable p is accepted.

Names that start with specsolve_

A declared name that starts with specsolve_, in any letter case, is refused by every function. The prefix is reserved for the columns specsolve adds, such as specsolve_run. The rule covers dimensions, relations and their columns, parameters, variables, constraints, named expressions, sos: sets and assumptions. A key_name= with the prefix is refused too, and so is a dimension called value.

variable 'Specsolve_p' starts with 'specsolve_', which is reserved in any
letter case for the columns specsolve adds, so it could collide with one.
Rename it.

The type of a label

Every function that returns a table names a str label as a String, whatever encoding the label arrived in. The type of a label has the other types.

What each sink takes

Model.check_sink(sink) refuses a built model the sink cannot ingest, naming the sinks that do. solve and write refuse the same. The check reads the built model, so a square the data prices at zero, an integer variable with no column or an empty set asks for nothing. Where a model can land is a separate question from whether the language states it.

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 refuses a nonconvex quadratic, and a quadratic with integrality.
  • The lp_file column says what is written, not what reads back. HiGHS reads the quadratic-objective section back and refuses the sos and quadratic-constraint sections.
  • "No path here" describes this package, not Xpress. The Xpress sink never hands the Optimizer a Hessian.