Skip to content

Compile

Compile systems into problems that solvers run.

A prepared system hands its components to a compiler, which checks them and turns their laws into one problem with numeric functions, such as the two equations of LotkaVolterraSystem. A system package that brings a kind of problem of its own writes its compiler on BaseCompiler, with passes on BasePass and lowerings on BaseLowering.

BaseCompiler(backend=None, solver=None, observables=())

Bases: BaseConfig[_Composite, Mapping[str, object]]

An abstract compiler that turns a system into a problem that a solver runs.

prepare(system) checks the settings and the system and lists what is wrong in report_, and run(initial_state) raises the errors of the report and sets problem_, the compiled problem, and solver_, the solver that runs it. A subclass fills in the hooks _issues and _compile, and a compiler of a kind of problem that the engine does not know names the solver of its problems in _get_solver. PassCompiler compiles every system of the catalog, and a field package writes its own compiler on this base, as the quantum package does for operators.

Read more in the user guide, under Extend the library.

Parameters:

Name Type Description Default
backend BaseBackend | None

The backend instance, or None for the backend that suits the size of the system.

None
solver object

The solver the problem runs on, or None for the default solver of its form, whose limits compiling checks.

None
observables Sequence[Observable]

The observables to compute at every frame, labelled by their path from the root, such as village/mean_wealth for an observable of the nested system village.

()

Attributes:

Name Type Description
system_ _Composite

The prepared system, with the observables of the run.

report_ ValidationReportSpec

The issues of the prepared system.

problem_ BaseProblemSpec

The compiled problem.

solver_ object

The solver the compiled problem runs on: the solver setting, the solver the compiler names, or None for the default solver of the problem's form.

See Also

PassCompiler: Compiles a system through a sequence of passes. OperatorCompiler: Compiles a system of operator elements.

Examples:

>>> from skcomplex.core.engine.compile import BaseCompiler
>>> from skcomplex.core.engine.compile._pass_compiler import PassCompiler
>>> issubclass(PassCompiler, BaseCompiler)
True
Source code in src/skcomplex/core/engine/compile/_base.py
114
115
116
117
118
119
120
121
122
def __init__(
    self,
    backend: BaseBackend | None = None,
    solver: object = None,
    observables: Sequence[Observable] = (),
) -> None:
    self.backend = backend
    self.solver = solver
    self.observables = observables

BaseLowering

Bases: BaseConfig[Compilation, InputT]

An abstract lowering, a helper that rewrites one family of laws.

To lower a law is to rewrite it in simpler terms that the numeric functions can evaluate, such as a random draw read as a number stored after the parameters, or a Laplacian read as the values of the neighbouring sites. One pass creates the lowering, later passes may finish it, and the compilation keeps it. The constructor stores what the lowering reads, prepare(compilation) gathers what it needs from the compilation, and run(laws) sets lowered_, the rewritten laws. A subclass fills in the hooks _prepare and _run. A lowering that adds new symbols to the laws notes where they read their values with _add_reference, and _apply_references gives every changed component the new references, in every field of the compilation.

Read more in the user guide, under Extend the library.

Attributes:

Name Type Description
compilation_ Compilation

The compilation the lowering serves.

added_ dict[int, tuple[KernelSpec, dict[Expression, ReferenceSpec]]]

The spec and the references the lowering added to it, by the identity of the spec.

lowered_ LoweredT

The laws the last run lowered, in the shape of its input.

See Also

BasePass: The base of the steps of a compilation. DrawLowering: Rewrites random draws as stored numbers.

Examples:

>>> from skcomplex.core.engine.compile import BaseLowering
>>> from skcomplex.core.engine.compile._draw_lowering import DrawLowering
>>> issubclass(DrawLowering, BaseLowering)
True

BasePass

Bases: BaseConfig[Compilation, None]

An abstract pass, one step of a compilation that reads fields and writes others.

A compilation turns a system into a problem in small steps, and each step is a pass, such as the pass that finds the states of every element or the pass that writes the equations. A pass names the fields of the compilation it reads and writes in the hooks _get_reads and _get_writes, which set the order in which the passes run. prepare(compilation) takes the compilation, and run() calls the hook _run, which reads its fields from compilation_ and writes the new ones. A field package adds a pass on this base to compile laws of its own.

Read more in the user guide, under Extend the library.

Attributes:

Name Type Description
compilation_ Compilation

The compilation the pass reads and writes.

See Also

Compilation: Holds the fields that passes read and write. PassCompiler: Runs the passes over a compilation.

Examples:

>>> from skcomplex.core.engine.compile import BasePass, FlattenPass
>>> issubclass(FlattenPass, BasePass)
True

FlattenPass

Bases: BasePass

A pass that lists every component of a nested system in one flat list.

A system may nest other systems, such as villages inside a country, and this pass walks the tree once and lists every element, group, and interaction with its full path, such as village.households. The passes after it read this list in place of the tree.

Read more in the user guide, under Extend the library.

See Also

CensusPass: Lists the laws of the components. PassCompiler: Runs the passes over a compilation.

Examples:

>>> from skcomplex.core.engine.compile._pass_compiler import PassCompiler
>>> from skcomplex.systems.biology.ecology import LotkaVolterraSystem
>>> compilation = PassCompiler().prepare(LotkaVolterraSystem()).compilation_
>>> [node.path for node in compilation.nodes]
['prey', 'predators', 'growth', 'predation', 'death']

HilbertSpaceError

Bases: SkcomplexError

An error for an operator system whose Hilbert space exceeds its limit.

The Hilbert space of a system of operators has one dimension per joint state of its elements, so it doubles with every qubit, and ten qubits already make 1024 dimensions. Use fewer elements or levels, or raise max_dimension when the memory allows. It bounds registers of qubits, chains of spins, and modes of light.

Read more in the user guide, under Troubleshooting.

See Also

OperatorCompiler: Compiles systems of operators. SpaceTooLargeError: Raised for a space with too many sites.

Examples:

>>> from skcomplex.core.engine.compile import HilbertSpaceError
>>> from skcomplex.core.errors import SkcomplexError
>>> issubclass(HilbertSpaceError, SkcomplexError)
True

IssueSpec(code, path, message, fix, severity=SeverityKind.ERROR, error=ValidationError) dataclass

Bases: BaseSpec

A spec of one problem found in a system, with where it is and how to fix it.

When prepare checks a system, it collects every problem it finds as an issue, such as a law that reads a value its element does not hold, with a short code, the path of the component, what is wrong, and how to fix it. The issues go into one report, so a model of an ecosystem, a circuit, or a market shows all its mistakes at once.

Read more in the user guide, under Troubleshooting.

Parameters:

Name Type Description Default
code str

The stable code of the problem, such as 'law-domain'.

required
path str

The slash path of the component or system the problem is in.

required
message str

What is wrong and why.

required
fix str

The change that makes the system valid.

required
severity str

'error' for problems that stop compilation, 'warning' otherwise.

ERROR
error type[SkcomplexError]

The class of the error raised for the problem: ValidationError or one of its subclasses for the problems validation finds, and the class of the original error for a component that fails to declare.

ValidationError
See Also

ValidationReportSpec: Holds every issue of a system.

Examples:

>>> from skcomplex.core.engine.compile import IssueSpec
>>> issue = IssueSpec('empty', 'system', 'It has no element.', 'Add one.')
>>> issue.severity.value
'error'

text property

IssueSpec as one line.

The line holds its path, code, message, and fix.

OperatorCompiler(backend=None, solver=None, observables=(), max_dimension=DEFAULT_MAX_DIMENSION)

Bases: BaseCompiler

A compiler that turns a system of operator elements into an operator problem.

An operator element holds the space of its states, such as the two levels of a qubit, and a value whose class names the compiler of the field that runs it. The compiler builds the joint space of all elements, and a subclass in that field adds the laws of its elements to the generator or the dissipators in _add_law and names the default solver. It compiles qubits, spins, and modes of light.

Read more in the user guide, under Extend the library.

Parameters:

Name Type Description Default
backend BaseBackend | None

The backend requested for the problem, which the operator form does not use.

None
solver object

The solver the problem runs on. A solver with a largest dimension of its own limits the Hilbert space.

None
observables Sequence[Observable]

The observables to compute at every frame, labelled by their path from the root.

()
max_dimension int

The largest dimension of the Hilbert space, for a solver without a largest dimension of its own.

DEFAULT_MAX_DIMENSION
See Also

BaseCompiler: The base of every compiler. HilbertSpaceError: Raised for a space past its limit.

Examples:

>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.physics.common.quantum import QubitElement
>>> problem = System(elements=[QubitElement('a'), QubitElement('b')]).prepare().simulate(until=0).problem
>>> problem.dimensions
(2, 2)
Source code in src/skcomplex/core/engine/compile/passes/_operator_compiler.py
 93
 94
 95
 96
 97
 98
 99
100
101
def __init__(
    self,
    backend: BaseBackend | None = None,
    solver: object = None,
    observables: Sequence[Observable] = (),
    max_dimension: int = DEFAULT_MAX_DIMENSION,
) -> None:
    super().__init__(backend, solver, observables)
    self.max_dimension = max_dimension

PhaseSpec(name, activation='random', repeat=1, groups=None, visits=1.0, period=1, offset=0) dataclass

Bases: BaseSpec

A spec of a named phase of a step, in which agents run some of their rules.

A step of an agent model can be split into phases, such as producing and then trading, and each rule names its phase. In a phase the agents run their rules in the order its activation policy gives: 'random', every agent in a new random order, 'sequential', every agent in the order of creation, 'simultaneous', every agent reading the states of the start of the phase while its changes apply at its end, 'by-type', group after group, each in random order, and 'visits', visits to agents drawn at random with replacement, visits times the number of agents. The rules of interactions run once after the agents. A phase repeats repeat times per step, such as rounds of trading within a day, and runs in the steps k for which k - offset is a multiple of period, so a period of seven runs it once a week. Phases order the days of a market, the seasons of a farm, and the rounds of a game.

Read more in the user guide, under Agents.

Parameters:

Name Type Description Default
name str

The name of the phase, which rules name in UpdateLaw(s, rule, phase=name).

required
activation str

The activation policy.

'random'
repeat int

The number of rounds of the phase per step.

1
groups Sequence[str] | None

The paths of the agent groups in their order of activation for 'by-type', or the groups whose agents 'visits' draws, or None for every group in the order of declaration.

None
visits float

The number of visits of 'visits' per agent of the groups at the start of the phase.

1.0
period int

The number of steps between two runs of the phase.

1
offset int

The step, modulo the period, in which the phase runs.

0
See Also

PhasesScheduleSpec: Runs the phases in order at every step.

Examples:

>>> from skcomplex.core.engine.compile import PhaseSpec
>>> PhaseSpec('trade', activation='simultaneous', repeat=3)
PhaseSpec(name='trade', activation='simultaneous', repeat=3, groups=None, visits=1.0, period=1, offset=0)

PhasesScheduleSpec(phases) dataclass

Bases: ScheduleSpec

A spec of a schedule that runs named phases in order at every step.

An agent model in discrete time may split each step into phases, such as producing goods and then trading them, and this schedule runs them in the order given. It orders the days of a market, the seasons of a farm, and the rounds of a game.

Read more in the user guide, under Agents.

Parameters:

Name Type Description Default
phases Sequence[PhaseSpec]

The phases, each with its rules and activation policy.

required
See Also

PhaseSpec: One named phase with its activation policy.

Examples:

>>> from skcomplex.core.engine.compile import PhaseSpec, PhasesScheduleSpec
>>> [phase.name for phase in PhasesScheduleSpec((PhaseSpec('produce'), PhaseSpec('trade'))).phases]
['produce', 'trade']

ValidationReportSpec(issues=()) dataclass

Bases: BaseSpec

A spec of the report of every problem a compiler found in a system.

prepare checks the system, its solver, and its backend, and gathers every problem it finds in this report, such as a law that reads a value its element does not hold. Its check shows the warnings and raises one error that lists all the errors, so a model of an ecosystem, a circuit, or a market shows every mistake at once and a valid report passes.

Read more in the user guide, under Troubleshooting.

Parameters:

Name Type Description Default
issues tuple[IssueSpec, ...]

The issues, in the order they were found.

()
See Also

IssueSpec: One problem of the report.

Examples:

>>> from skcomplex.core.engine.compile import IssueSpec, ValidationReportSpec
>>> report = ValidationReportSpec((IssueSpec('empty', 'system', 'It has no element.', 'Add one.'),))
>>> ValidationReportSpec().ok, report.ok
(True, False)

errors property

Return the issues that stop compilation.

ok property

Check whether the report holds no error.

warnings property

Return the issues that do not stop compilation.