Problems
Define what a system compiles to: a problem, its kernels, and run frames.
A problem holds the values of a system in flat vectors and the compiled functions of its laws, such as the one state
'population.x' of a logistic growth. The bases, the problems of the general compiler and of operator systems, and the
frames stay public for observers, analyses, and system packages that bring a form of their own.
AgentSnapshotSpec(ids, values, locations=None, roles=dict())
dataclass
Bases: BaseSpec
A spec of the agents of one group alive at one frame.
It holds the ids of the agents, such as [1, 2, 3, 4, 5] for five traders, their values by name, their places, and
the members their roles name. Trajectory.get_agents returns one, for the traders of a market, the birds of a
flock, and the residents of a city.
Read more in the user guide, under Agents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ids
|
IntArray
|
The unique id of every agent. |
required |
values
|
Mapping[str, AnyArray]
|
A mapping from state name to one value per agent. |
required |
locations
|
AnyArray | None
|
One row per agent: grid coordinates, a network node, or a continuous position, or |
None
|
roles
|
Mapping[str, str]
|
A mapping from the name of a state with a role to its role, |
dict()
|
See Also
Trajectory: Returns it from get_agents.
Examples:
>>> from skcomplex.systems.economics.econophysics import BoltzmannWealthSystem
>>> trajectory = BoltzmannWealthSystem(n_agents=5).prepare().simulate(until=1)
>>> trajectory.get_agents('traders', 1).ids.tolist()
[1, 2, 3, 4, 5]
BaseKernel
Bases: BaseConfig[object, RunStateSpec]
An abstract kernel, a compiled piece of a problem that a solver evaluates.
A kernel is a law turned into numbers, such as the matrix of a coupling between two qubits that a solver multiplies
by the state. It stores what the compiler built in its constructor, such as compiled functions and the indices they
read. prepare(problem) checks them and sets what a run needs, and run(state) acts at a RunStateSpec, the time,
the state, the parameters, and the random generator, and keeps what it computes, such as the next state, in
values_. A new kind of law comes with a subclass, the pass that builds it, and a solver that runs it, as for the
jumps of molecules, the moves of spins, and the trades of agents.
Read more in the user guide, under Extend the library.
Attributes:
| Name | Type | Description |
|---|---|---|
values_ |
object
|
What the last run computed. Each kernel narrows its type. |
See Also
RunStateSpec: The state of a run a kernel acts at. OperatorKernel: A kernel of a matrix on a Hilbert space.
Examples:
>>> from skcomplex.core.engine.problems import BaseKernel
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.physics.common.quantum import QubitElement
>>> problem = System(elements=[QubitElement('a')]).prepare().simulate(until=0).problem
>>> isinstance(problem.generator[0], BaseKernel)
True
BasePrinter
Bases: BaseConfig[ContextT, InputT]
An abstract printer, which writes Sage expressions as code of a language.
A printer stores its target in its constructor, prepare(symbols) takes the symbols the code reads, in order, and
run(expressions) keeps the code of the expressions, or a function that evaluates them, in code_, such as
'3*_cse0' for 3 * (x + 1) ** 2. A printer names the types of the symbols and expressions it takes, which differ
between targets. Printers write the laws of a reaction for NumPy, of a gas for Numba, and of a pair energy for
LAMMPS.
Read more in the user guide, under Extend the library.
Attributes:
| Name | Type | Description |
|---|---|---|
code_ |
object
|
The code of the last run. Each printer narrows its type. |
See Also
ExpressionPrinter: Prints for NumPy, Numba, and LAMMPS.
Examples:
>>> from skcomplex.core.engine.problems import BasePrinter, ExpressionPrinter
>>> isinstance(ExpressionPrinter(), BasePrinter)
True
BaseProblemSpec(form, states, parameters, initial_state, initial_parameters, time, *, symbols=dict(), elements=(), interactions=(), system=None, agents=(), agent_space=None, companions=dict(), renewals=(), transfer_network=None, topology=None, observables=())
dataclass
Bases: BaseSpec
An abstract spec of a problem that a system compiles to.
It holds what every solver, observer, and visual reads of a problem, such as the names of the states and their starting values, with empty defaults for what a form does not have, and its readers answer the questions of the run. A form that brings its own solver adds the fields that solver reads. It is the base of the problems of a growing population, a quantum circuit, and a market of agents.
Read more in the user guide, under Extend the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
form
|
FormKind | str
|
The mathematical form. |
required |
states
|
LayoutSpec
|
The layout of the state vector. |
required |
parameters
|
LayoutSpec
|
The layout of the parameter vector. |
required |
initial_state
|
Array
|
The initial state vector. |
required |
initial_parameters
|
Array
|
The initial parameter vector. |
required |
time
|
Expression
|
The time symbol. |
required |
symbols
|
Mapping[str, Expression | FreeModuleElement]
|
A mapping from dotted name to the symbol of a scalar or the column of symbols of a vector. The symbols of a group stand for one member. |
dict()
|
elements
|
tuple[CompiledElementSpec, ...]
|
The compiled elements and groups. |
()
|
interactions
|
tuple[_CompiledInteractionSpec, ...]
|
The compiled interactions in tree order. |
()
|
system
|
_CompositeSystem | None
|
The system the problem was compiled from, or |
None
|
agents
|
tuple[_CompiledAgentsSpec, ...]
|
The agent elements and groups of an agent-based problem. |
()
|
agent_space
|
BaseSpace | None
|
The space the agents of an agent-based problem live in, or |
None
|
companions
|
Mapping[str, tuple[str, str, int]]
|
A mapping from the name of every companion state to its kind, |
dict()
|
renewals
|
tuple[RenewalKernel, ...]
|
The renewal laws, whose members renew on their own clocks. |
()
|
transfer_network
|
TransferNetworkSpec | None
|
The quantities, flows, objectives, and feedback terms of the system, or |
None
|
topology
|
TopologyKernel | None
|
The topology requests of the laws and the networks they change, or |
None
|
observables
|
tuple[tuple[str, Observable], ...]
|
The observables of the system tree, each with the path of the system that declares it, empty for the root, which the compiler collects. |
()
|
See Also
ProblemSpec: The problem of the general compiler. OperatorProblemSpec: The problem of operator systems.
Examples:
>>> from skcomplex.core.engine.problems import BaseProblemSpec
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> problem = LogisticGrowthSystem().prepare().simulate(until=0).problem
>>> isinstance(problem, BaseProblemSpec), problem.states.names
(True, ['population.x'])
adaptive_parameters
property
Declarations of the adaptive parameters, by dotted state name.
Adaptive parameters are states that a schedule may set.
partition_problems
property
Problems of the partitions of a co-simulation problem.
A problem of one form has none.
stochastic
property
Whether the problem draws random values.
A problem that draws them has a solver that takes the random number generator.
get_lattice_shape(name)
Return the lattice shape of a state that lives on the sites of a lattice.
Other states return None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted name of the state. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
shape |
tuple[int, ...] | None
|
The number of sites along every dimension, or |
Source code in src/skcomplex/core/engine/problems/_base_problem_spec.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
BaseRecordSpec()
dataclass
Bases: BaseSpec
An abstract spec of a record of something that happened during a run.
A record holds what happened at one time of a run, such as an event, a cascade, or a renewal, with the readers
label, the name of what happened, and time, when it happened. A run keeps them in Trajectory.events, such as
the jumps of walkers, the bounces of a ball, and the avalanches of a sandpile.
Read more in the user guide, under Analyse.
See Also
RenewalRecordSpec: A record of renewals.
Examples:
>>> from skcomplex.core.engine.problems import BaseRecordSpec
>>> from skcomplex.systems.physics.soft_matter import ContinuousTimeRandomWalkSystem
>>> trajectory = ContinuousTimeRandomWalkSystem(n_walkers=3).prepare().simulate(until=10, random_state=0)
>>> isinstance(trajectory.events[0], BaseRecordSpec), trajectory.events[0].label
(True, 'jumps')
BaseSearch
Bases: BaseConfig[None, RunStateSpec]
An abstract search of the neighbours of members at a state.
A search finds the neighbours a kernel reads at a state, such as the atoms of a gas within a radius of each atom. It
stores the entries and the neighbourhood it reads in its constructor, and run(state) keeps the neighbours at a
RunStateSpec in pairs_, as the row starts and the neighbours of every member, or the members of every pair. It
finds the atoms near an atom, the birds a bird sees, and the people a walker meets.
Read more in the user guide, under Extend the library.
Attributes:
| Name | Type | Description |
|---|---|---|
pairs_ |
object
|
The neighbours of the last run. Each search narrows its type. |
See Also
BaseKernel: Reads the neighbours a search finds.
Examples:
>>> from skcomplex.core.engine.problems import BaseSearch
>>> from skcomplex.core.engine.problems._pair_search import PairSearch
>>> issubclass(PairSearch, BaseSearch)
True
CompiledElementSpec(path, element, states, parameters, visual, members=None, adaptive=dict(), lattice_shape=None, roles=dict())
dataclass
Bases: BaseSpec
A spec of an element of a compiled problem, with the names of its values.
It holds the path of the element, the element, and the names its states and parameters take in the flat vectors,
such as {'x': 'population.x'}, with its members, adaptive values, lattice shape, and roles. Observers and visuals
read it to find the values of an element, for a population, a magnet, and a flock.
Read more in the user guide, under Extend the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The slash-separated path of the element or group in the system tree. |
required |
element
|
Element | _GroupElement
|
The element or group. |
required |
states
|
Mapping[str, str]
|
A mapping from state name to dotted name. |
required |
parameters
|
Mapping[str, str]
|
A mapping from parameter name to dotted name. |
required |
members
|
int | None
|
The size of a group, or |
None
|
adaptive
|
Mapping[str, _VariableSpec]
|
The declarations of the adaptive parameters, states that a schedule may set, by state name. |
dict()
|
lattice_shape
|
tuple[int, ...] | None
|
The number of sites along every dimension of the lattice the element or group lives on, or |
None
|
roles
|
Mapping[str, str]
|
The roles of the states that declare one, by state name. |
dict()
|
See Also
ProblemSpec: Holds one per element.
Examples:
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> element = LogisticGrowthSystem().prepare().simulate(until=0).problem.elements[0]
>>> element.path, element.states
('population', {'x': 'population.x'})
ExpressionPrinter(dialect='numpy', *, time=None, names=None, prefix='_cse', shared=True, compiled=False)
Bases: BasePrinter[Sequence[Expression], Sequence[Expression]]
A printer of Sage expressions as code of NumPy, Numba, or LAMMPS.
prepare(symbols) takes the symbols the code reads, in order, and run(expressions) keeps in code_ the
subexpressions that repeat, bound to numbered names, and the code of every expression, such as '3*_cse0' for
3 * (x + 1) ** 2. It orders the terms of sums and products the same way in every process, so the Numba backend
reuses the code it cached. A compiled printer keeps instead the NumPy or JAX function f(t, *symbols) of the
expressions. Lepton has neither comparisons nor remainders, so conditions become step and select and remainders
floor. It prints the laws of a reaction, of a gas, and of a pair energy for LAMMPS.
Read more in the user guide, under Extend the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dialect
|
str
|
The target language, |
'numpy'
|
time
|
Expression | None
|
The time symbol, the first argument of a compiled function. |
None
|
names
|
Callable[[Expression], str] | None
|
The function that gives the code name of a symbol, or |
None
|
prefix
|
str
|
The prefix of the names of bound subexpressions. |
'_cse'
|
shared
|
bool
|
Whether repeated subexpressions are bound to names, false for languages without assignments. |
True
|
compiled
|
bool
|
Whether |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
code_ |
tuple[list[tuple[str, str]], list[str]] | Callable[..., list[ArrayLike]]
|
The assignments of the repeated subexpressions and the code of every expression of the last run, or the
NumPy function |
See Also
BasePrinter: The base of every printer.
Examples:
>>> from skcomplex.core.engine._utils import symbol
>>> from skcomplex.core.engine.problems import ExpressionPrinter
>>> x = symbol('x')
>>> ExpressionPrinter().prepare().run([(x + 1) ** 2, 3 * (x + 1) ** 2]).code_
([('_cse0', '(x + 1)**2')], ['_cse0', '3*_cse0'])
Source code in src/skcomplex/core/engine/problems/_expression_printer.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | |
FrameSpec(step, time, state, parameters, problem, agents=dict(), reporters=dict(), observables=dict(), events=(), structures=dict())
dataclass
Bases: BaseSpec
A spec of the state of a run at one time, which observers receive.
It holds the step, the time, the states and parameters, and the agents, reporters, observables, events, and structures of one frame, such as the size 10 of a population at time 0. A run hands one to every observer at every frame. It records the course of an epidemic, the prices of a market, and the moves of a flock.
Read more in the user guide, under Observe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step
|
int
|
The index of the frame, starting at 0. |
required |
time
|
float
|
The simulated time. |
required |
state
|
Array
|
A copy of the state vector. |
required |
parameters
|
Array
|
A copy of the parameter vector. |
required |
problem
|
BaseProblemSpec
|
The compiled problem, which gives the names of the vector components. |
required |
agents
|
Mapping[str, AgentSnapshotSpec]
|
A mapping from agent group path to the agents alive at this frame. |
dict()
|
reporters
|
Mapping[str, float]
|
A mapping from dotted reporter name to its value at this frame. |
dict()
|
observables
|
Mapping[str, ArrayLike]
|
A mapping from observable path to its value at this frame. |
dict()
|
events
|
tuple[BaseRecordSpec, ...]
|
The events, cascades, and renewals since the previous frame, in order. |
()
|
structures
|
Mapping[str, object]
|
A mapping from the path of a rewritten element to its word or patch at this frame. |
dict()
|
See Also
BaseObserver: Receives the frames of a run.
Examples:
>>> from skcomplex.core.engine.runtime import RecorderObserver
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> recorder = RecorderObserver()
>>> _ = LogisticGrowthSystem().prepare().simulate(until=1, dt=1, observers=[recorder])
>>> recorder.frames_[0].time, recorder.frames_[0].state.tolist()
(0.0, [10.0])
get_lattice(name)
Return the values of a lattice state in lattice shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted name of a state of a lattice group, such as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
values |
AnyArray
|
The array of the lattice shape, with the components of a vector or a tensor state on a last axis. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The name is not a state of a lattice group. |
Source code in src/skcomplex/core/engine/problems/_frame_spec.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
get_value(name)
Return the value of a state or a parameter by dotted name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted name, such as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
value |
ArrayLike
|
A number for a scalar and an array for a vector. |
Source code in src/skcomplex/core/engine/problems/_frame_spec.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
LayoutSpec(entries)
dataclass
Bases: BaseSpec
A spec of the named values stored in one flat vector, in order.
It names each slice of a flat vector, such as 'population.x' at index 0, and reads a value by its name, so solvers
work on plain arrays while users read values by name. It lays out the states of a population, the spins of a magnet,
and the positions of a gas.
Read more in the user guide, under Extend the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entries
|
tuple[EntrySpec, ...]
|
The entries, in vector order. |
required |
See Also
ProblemSpec: Holds the layouts of its states and parameters.
Examples:
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> problem = LogisticGrowthSystem().prepare().simulate(until=0).problem
>>> problem.states.names, problem.states.read(problem.initial_state, 'population.x')
(['population.x'], 10.0)
component_names
property
Names of the components, in vector order.
names
property
Dotted names of the variables, in vector order.
size
property
Number of components of the flat vector.
get_entry(name)
Return the entry of a variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted name of the variable, such as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
entry |
EntrySpec
|
The entry of the variable. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The name is not part of the layout. |
Source code in src/skcomplex/core/engine/problems/_layout_spec.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
get_relaid(vector, layout, initial)
Return a flat vector of another layout laid out in this one.
Every variable keeps the rows and columns both layouts hold, and the rows only this layout holds, such as the
free rows of a group that grew, keep their values in initial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
NDArray[float64]
|
A flat vector of the other layout. |
required |
layout
|
LayoutSpec
|
The other layout. |
required |
initial
|
Array
|
A flat vector of this layout whose values fill what the other layout lacks. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
vector |
Array
|
The flat vector of this layout. |
Source code in src/skcomplex/core/engine/problems/_layout_spec.py
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | |
get_values(vector)
Return the value of every variable of a flat vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
NDArray[float64]
|
A flat vector. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
values |
dict[str, Array | ComplexArray | float | complex]
|
A mapping from dotted name to value. |
Source code in src/skcomplex/core/engine/problems/_layout_spec.py
189 190 191 192 193 194 195 196 197 198 199 200 | |
has(name)
Check whether a variable name is part of the layout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted name of a variable, such as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
found |
bool
|
Whether the layout has a variable of that name. |
Source code in src/skcomplex/core/engine/problems/_layout_spec.py
79 80 81 82 83 84 85 86 87 88 89 90 | |
locate(name)
Return the entry of a variable or of one of its components.
It also returns the slice of the vector that the variable covers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted name of a variable, or of one component such as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
location |
tuple[EntrySpec, slice]
|
The entry of the variable, a scalar entry for a component, and the slice of its values. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The name is neither a variable nor a component of the layout. |
Examples:
>>> from skcomplex.core.components import EntrySpec
>>> from skcomplex.core.engine.problems import LayoutSpec
>>> from sage.all__sagemath_symbolics import CC, RR
>>> layout = LayoutSpec((EntrySpec('a.n', 0, (), RR), EntrySpec('b.w', 1, (3,), RR)))
>>> entry, indices = layout.locate('b.w[1]')
>>> entry.name, entry.shape, indices
('b.w[1]', (), slice(2, 3, None))
Source code in src/skcomplex/core/engine/problems/_layout_spec.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
read(vector, name)
Return the value of a variable from a flat vector or from rows of flat vectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
NDArray[float64]
|
A flat vector, or a 2D array with one flat vector per row. |
required |
name
|
str
|
The dotted name of the variable. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
value |
Array | ComplexArray | float | complex
|
A number for a scalar in a flat vector, or an array whose shape is the leading shape of |
Source code in src/skcomplex/core/engine/problems/_layout_spec.py
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
LocalOperatorSpec(name, matrix=None, hermitian=False)
dataclass
Bases: BaseSpec
A spec of a named operator that acts on the space of one subsystem.
It holds the name and the matrix of an operator of one subsystem, such as the raising operator 'plus' of a qubit,
and gives its adjoint, the lowering operator 'minus'. Products of them make the operators of the whole system, for
qubits, spins, and the modes of light.
Read more in the user guide, under Extend the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the operator, unique among the operators of its subsystem. |
required |
matrix
|
object
|
The matrix of the operator. |
None
|
hermitian
|
bool
|
Whether the operator equals its adjoint. |
False
|
See Also
OperatorSpec: A sum of products of local operators.
Examples:
>>> import qutip
>>> from skcomplex.core.engine.problems import LocalOperatorSpec
>>> LocalOperatorSpec('plus', qutip.sigmap()).get_adjoint().name
'minus'
get_adjoint()
Return the adjoint of the operator.
Returns:
| Name | Type | Description |
|---|---|---|
adjoint |
LocalOperatorSpec
|
The operator itself when it is Hermitian, or the operator with the conjugate transposed matrix. |
Source code in src/skcomplex/core/engine/problems/_local_operator_spec.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
NetworkSnapshotSpec(nodes, sources, targets, edges, hyperedges=None)
dataclass
Bases: BaseSpec
A spec of the nodes, links, and hyperedges of a network at one frame.
It holds the nodes, the sources and targets of the links, the links themselves, and the hyperedges of a network
whose links change, such as the 50 links added to 100 nodes by explosive percolation. Trajectory.get_network
returns one, for a growing web, a changing friendship network, and a power grid that fails.
Read more in the user guide, under Analyse.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
NDArray[intp]
|
The rows of the nodes present, in increasing order. |
required |
sources
|
NDArray[intp]
|
The node row of the source of every edge present. |
required |
targets
|
NDArray[intp]
|
The node row of the target of every edge present. |
required |
edges
|
NDArray[intp]
|
The row of every edge present in its edge group. |
required |
hyperedges
|
NDArray[intp] | None
|
The member nodes of every hyperedge present, one row per hyperedge, or |
None
|
See Also
Trajectory: Returns it from get_network.
Examples:
>>> from skcomplex.systems.mathematics.networks import ExplosivePercolationSystem
>>> trajectory = ExplosivePercolationSystem(100).prepare().simulate(until=50, random_state=0)
>>> len(trajectory.get_network(-1).sources)
50
get_graph()
Return the NetworkX graph of the snapshot.
Its nodes are the node rows present.
Returns:
| Name | Type | Description |
|---|---|---|
graph |
Graph
|
The undirected graph of the nodes and edges present. |
Examples:
>>> import numpy as np
>>> from skcomplex.core.engine.problems import NetworkSnapshotSpec
>>> rows = np.array([0, 1, 2])
>>> snapshot = NetworkSnapshotSpec(rows, np.array([0, 1]), np.array([1, 2]), np.array([0, 1]))
>>> sorted(snapshot.get_graph().edges())
[(0, 1), (1, 2)]
Source code in src/skcomplex/core/engine/problems/_network_snapshot_spec.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | |
OperatorKernel(matrix, coefficient, function=None)
Bases: BaseKernel
A kernel of a sparse matrix on the whole Hilbert space, with a coefficient.
It holds the matrix of an operator on all subsystems, such as the coupling of two qubits, and the compiled function of its coefficient, which may change with the parameters and the time. A solver of operator problems multiplies the state by the sum of these kernels. It moves qubits, spin chains, and atoms in a cavity.
Read more in the user guide, under Extend the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
csr_array
|
The sparse matrix. |
required |
coefficient
|
Expression
|
The symbolic coefficient, 1 for a constant matrix. |
required |
function
|
Callable[[float, Array], complex] | None
|
The function |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
values_ |
complex
|
The coefficient at the time and the parameters of the state of the last run. |
See Also
BaseKernel: The base of every kernel.
Examples:
>>> from skcomplex.core.engine.problems import OperatorKernel
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.physics.common.quantum import QubitElement
>>> problem = System(elements=[QubitElement('a')]).prepare().simulate(until=0).problem
>>> isinstance(problem.generator[0], OperatorKernel)
True
Source code in src/skcomplex/core/engine/problems/_operator_kernel.py
55 56 57 58 59 60 61 62 63 | |
time_dependent
property
Whether the coefficient depends on time.
OperatorProblemSpec(form, states, parameters, initial_state, initial_parameters, time, dimensions=(), subsystems=(), generator=(), dissipators=(), pure=True, namespaces=dict(), members=dict(), lowering=None, generator_operator=SR(0), cache=dict(), *, symbols=dict(), elements=(), interactions=(), system=None, agents=(), agent_space=None, companions=dict(), renewals=(), transfer_network=None, topology=None, observables=())
dataclass
Bases: BaseProblemSpec
A spec of a problem of the operator form, a state vector and its operators.
Its state is a pure state or a density matrix, stored as pairs of real numbers, over the subsystems of the system,
such as two qubits of dimensions (2, 2). Its operators hold the coefficients that move the state. It is the
problem of qubits, spin chains, and quantum optics.
Read more in the user guide, under Extend the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dimensions
|
tuple[int, ...]
|
The Hilbert space dimensions of the subsystems, in tensor product order. |
()
|
subsystems
|
tuple[str, ...]
|
The keys of the subsystems, such as |
()
|
generator
|
tuple[OperatorKernel, ...]
|
The terms of the generator. |
()
|
dissipators
|
tuple[tuple[OperatorKernel, ...], ...]
|
The terms of every collapse operator, each with the square root of its rate in the coefficients. |
()
|
pure
|
bool
|
Whether the state is a pure state vector rather than a density matrix. |
True
|
namespaces
|
Mapping[str, SimpleNamespace]
|
The namespace of every system, by its path, which observables receive. |
dict()
|
members
|
Mapping[str, tuple[SimpleNamespace, ...]]
|
The namespaces of the members of every operator element or group, by path. |
dict()
|
lowering
|
OperatorLowering | None
|
The lowering of operators to matrices and functions. |
None
|
generator_operator
|
Expression
|
The sum of the operators of the generator laws, a Sage expression of local operators. |
SR(0)
|
cache
|
dict[str, list[csr_array]]
|
The matrices of local operators computed so far. |
dict()
|
See Also
OperatorSpec: A sum of products of local operators.
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
>>> type(problem).__name__, problem.dimensions, problem.subsystems
('OperatorProblemSpec', (2, 2), ('a', 'b'))
OperatorSpec(terms)
dataclass
Bases: BaseSpec
A spec of a sum of products of local operators of subsystems.
Each product of local operators has a coefficient, a number or a Sage expression of parameters and time, such as
J*a.x*b.x for the coupling of two spins. Operators combine with add, subtract, multiply, divide, negate,
and adjoint, a number stands for that multiple of the identity, and a product keeps its order. The compiler turns
the operator expressions of laws and observables into it, for qubits, spin chains, and quantum optics.
Read more in the user guide, under Extend the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
terms
|
Mapping[Product, object]
|
A mapping from a tuple of factors, each the key of a subsystem and a local operator, in product order, to the coefficient of the product. The empty tuple is the identity. |
required |
See Also
LocalOperatorSpec: An operator of one subsystem.
Examples:
>>> import qutip
>>> from skcomplex.core.engine.problems import LocalOperatorSpec, OperatorSpec
>>> x = LocalOperatorSpec('x', qutip.sigmax(), hermitian=True)
>>> OperatorSpec({(('a', x),): 1}).multiply(OperatorSpec({(('b', x),): 1})).text
'a.x*b.x'
subsystems
property
Keys of the subsystems every term acts on, in term order.
text
property
OperatorSpec in operator notation.
It is a sum of coefficients times products of local operators.
add(other)
Return the sum of the operator and an operator or a multiple of the identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
An operator, or a number or a Sage expression, which stands for that multiple of the identity. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
sum |
OperatorSpec
|
The sum. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
The operand is neither an operator nor a scalar. |
Examples:
>>> import qutip
>>> from skcomplex.core.engine.problems import LocalOperatorSpec, OperatorSpec
>>> z = OperatorSpec({(('q', LocalOperatorSpec('z', qutip.sigmaz(), hermitian=True)),): 1})
>>> z.add(1).text
'q.z + 1'
Source code in src/skcomplex/core/engine/problems/_operator_spec.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
divide(other)
Return the operator divided by a scalar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
A number or a Sage expression. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
quotient |
OperatorSpec
|
The quotient. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
The operand is not a scalar. |
Source code in src/skcomplex/core/engine/problems/_operator_spec.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
get_adjoint()
Return the adjoint operator.
It has conjugate coefficients and reversed products of adjoint factors.
Returns:
| Name | Type | Description |
|---|---|---|
adjoint |
OperatorSpec
|
The adjoint operator. |
Examples:
>>> import qutip
>>> from skcomplex.core.engine.problems import LocalOperatorSpec, OperatorSpec
>>> plus = LocalOperatorSpec('plus', qutip.sigmap())
>>> OperatorSpec({(('q', plus),): 1}).multiply(2j).get_adjoint().text
'(-2j)*q.minus'
Source code in src/skcomplex/core/engine/problems/_operator_spec.py
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
multiply(other)
Return the product of the operator and an operator or a scalar, in this order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
The right factor, an operator, or a number or a Sage expression, which stands for that multiple of the identity. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
product |
OperatorSpec
|
The product. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
The operand is neither an operator nor a scalar. |
Source code in src/skcomplex/core/engine/problems/_operator_spec.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
negate()
Return the operator with every coefficient negated.
Returns:
| Name | Type | Description |
|---|---|---|
negation |
OperatorSpec
|
The negated operator. |
Source code in src/skcomplex/core/engine/problems/_operator_spec.py
136 137 138 139 140 141 142 143 | |
subtract(other)
Return the difference of the operator and an operator or a multiple of identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
object
|
An operator, or a number or a Sage expression, which stands for that multiple of the identity. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
difference |
OperatorSpec
|
The difference. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
The operand is neither an operator nor a scalar. |
Source code in src/skcomplex/core/engine/problems/_operator_spec.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
ProblemSpec(form, states, parameters, initial_state, initial_parameters, time, equations, equation_symbols, has_callables, has_group_sums, system_rules=(), partitions=(), delays=(), events=(), breakpoints=_BreakpointsSpec(), history=dict(), lattice=(), stable_step=None, diffusive_limits=(), linear=(), observed=dict(), stream=RandomStream(), volumes=(), constrained=(lambda: np.zeros(0, dtype=np.intp))(), reductions=(), neighbourhoods=(), jacobian=None, unknowns=(lambda: np.zeros(0, dtype=np.intp))(), objective=None, objective_targets=(lambda: np.zeros(0, dtype=np.intp))(), terminal=None, drift=None, sources=None, diffusion=None, noise_rows=(lambda: np.zeros(0, dtype=np.intp))(), noise_columns=(lambda: np.zeros(0, dtype=np.intp))(), n_processes=0, noise_blocks=(), propensities=None, jumps=(), update=None, boundary=None, algebraic=None, programs=(), draws=None, fractional=(), orders=(lambda: np.zeros(0))(), backend='numpy', backends=dict(), accelerated=None, *, symbols=dict(), elements=(), interactions=(), system=None, agents=(), agent_space=None, companions=dict(), renewals=(), transfer_network=None, topology=None, observables=())
dataclass
Bases: BaseProblemSpec
A spec of a system compiled by the general compiler, with flat value vectors.
It holds the states and parameters of a system in two flat vectors, such as the one state 'population.x' of a
logistic growth, and the functions of its form. drift, diffusion, and noise_rows belong to differential
equations with or without noise, propensities and jumps to jump processes, update to discrete maps, and
boundary to any form with boundary laws. It is the problem of a population, a reaction network, and a flock.
Read more in the user guide, under Extend the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
form
|
FormKind | str
|
The mathematical form. |
required |
states
|
LayoutSpec
|
The layout of the state vector. |
required |
parameters
|
LayoutSpec
|
The layout of the parameter vector. |
required |
initial_state
|
Array
|
The initial state vector. |
required |
initial_parameters
|
Array
|
The initial parameter vector. |
required |
time
|
Expression
|
The time symbol. |
required |
symbols
|
Mapping[str, Expression | FreeModuleElement]
|
A mapping from dotted name to the symbol of a scalar or the column of symbols of a vector. The symbols of a group stand for one member. |
dict()
|
equations
|
Mapping[str, Expression]
|
A mapping from state component name to its symbolic drift, or to its next value for the discrete form.
Group components are named with the member index |
required |
equation_symbols
|
Mapping[str, Expression]
|
A mapping from the names of |
required |
stream
|
RandomStream
|
The random stream the functions of the laws receive, which a solver binds when it prepares. |
RandomStream()
|
has_callables
|
bool
|
Whether any law is a callable. |
required |
has_group_sums
|
bool
|
Whether any law sums over group members or pairs. |
required |
elements
|
tuple[CompiledElementSpec, ...]
|
The compiled elements and groups in state vector order. |
()
|
interactions
|
tuple[_CompiledInteractionSpec, ...]
|
The compiled interactions in tree order. |
()
|
system
|
_CompositeSystem | None
|
The system the problem was compiled from. |
None
|
agents
|
tuple[_CompiledAgentsSpec, ...]
|
The agent elements and groups of an agent-based problem. |
()
|
system_rules
|
tuple[tuple[str, BaseLaw], ...]
|
The rules of interactions of an agent-based problem, with the path of their interaction. |
()
|
agent_space
|
BaseSpace | None
|
The space the agents of an agent-based problem live in, or |
None
|
companions
|
Mapping[str, tuple[str, str, int]]
|
A mapping from the name of every companion state to its kind, |
dict()
|
partitions
|
tuple[PartitionSpec, ...]
|
The partitions of a co-simulation problem, in system order. |
()
|
delays
|
tuple[_DelaySpec, ...]
|
The delayed states that laws read, which solvers fill from the run's history. |
()
|
events
|
tuple[EventKernel, ...]
|
The discrete events, with their guard and reset functions. |
()
|
breakpoints
|
_BreakpointsSpec
|
The times where time-dependent inputs jump, at which solvers restart. |
_BreakpointsSpec()
|
history
|
Mapping[str, object]
|
The values of states before the start, by dotted state path, as numbers or functions of time. |
dict()
|
lattice
|
tuple[BaseKernel, ...]
|
The steps that change the states of sites, such as the local rules of a lattice problem, in the order they apply within a step. |
()
|
linear
|
tuple[LinearTermSpec, ...]
|
The linear terms with constant coefficients of the rates of fields, which implicit and exponential solvers treat exactly while the rest of the rates is the nonlinear remainder. |
()
|
observed
|
Mapping[str, LawKernel]
|
The kernels of the observables of fields whose expressions apply field operators, such as a streamfunction inverted from a vorticity, by the path of the observable, each giving the expression at every site. |
dict()
|
volumes
|
tuple[FiniteVolumeKernel, ...]
|
The conservation laws of finite-volume fields, whose flux differences the drift includes. |
()
|
constrained
|
NDArray[intp]
|
The state indices held at their initial values, the fixed boundary nodes of finite element fields. |
(lambda: zeros(0, dtype=intp))()
|
reductions
|
tuple[ReductionKernel, ...]
|
The reductions that laws read, in the order they are evaluated before the kernels. |
()
|
neighbourhoods
|
tuple[NeighborhoodKernel, ...]
|
The reductions over neighbours that laws read, each with the symbol that stands for it in the equations. |
()
|
unknowns
|
Indices
|
The positions in the state vector that the equations of a static problem solve for numerically. |
(lambda: zeros(0, dtype=intp))()
|
objective
|
Expression | None
|
The sum of the objective laws, the scalar a static solver minimises or the running cost an optimal
control solver integrates over a run, or |
None
|
objective_targets
|
Indices
|
The positions in the state vector that the objective is minimised over, or of the controls it steers. |
(lambda: zeros(0, dtype=intp))()
|
terminal
|
Expression | None
|
The sum of the terminal costs of the objective laws with controls, the cost at the end of a run. |
None
|
jacobian
|
JacobianKernel | None
|
The Jacobian of the drift of an ODE problem, derived from its laws: its sparsity pattern and, for laws with
a symbolic form, its exact value. |
None
|
stable_step
|
float | None
|
The largest step of explicit fixed-step solvers for which the diffusion of fields is stable,
|
None
|
diffusive_limits
|
tuple[DiffusiveLimitSpec, ...]
|
The stability limits of the diffusion of finite-volume fields, which depend on the parameters. |
()
|
drift
|
VectorFunction | None
|
The function |
None
|
sources
|
VectorFunction | None
|
The part of the drift without the flux differences of finite-volume fields, or |
None
|
diffusion
|
VectorFunction | None
|
The function |
None
|
noise_rows
|
NDArray[intp]
|
The state index each amplitude of |
(lambda: zeros(0, dtype=intp))()
|
noise_columns
|
NDArray[intp]
|
The Wiener process each amplitude of |
(lambda: zeros(0, dtype=intp))()
|
n_processes
|
int
|
The number of standard normal increments drawn per step. |
0
|
noise_blocks
|
tuple[_WienerBlockSpec, ...]
|
The blocks of correlated processes, whose increments their covariance factor scales. |
()
|
propensities
|
VectorFunction | None
|
The function |
None
|
jumps
|
tuple[_JumpChannelsSpec, ...]
|
The channels of every jump law. |
()
|
update
|
Callable[..., Array] | None
|
The function |
None
|
boundary
|
VectorFunction | None
|
The function |
None
|
programs
|
tuple[LinearProgramKernel, ...]
|
The linear programs that the functions of the problem solve, with those of its partitions. |
()
|
algebraic
|
VectorFunction | None
|
The function |
None
|
draws
|
DrawKernel | None
|
The random values the update draws at every step, or |
None
|
matrices
|
The transition and emission matrices of the Markov laws, checked when their parameters change. |
required | |
renewals
|
tuple[RenewalKernel, ...]
|
The renewal laws, whose members renew on their own clocks. |
()
|
fractional
|
tuple[_FractionalRowsSpec, ...]
|
The noise rows that noise laws with a Hurst index drive, with their indices. |
()
|
orders
|
Array
|
The order of the Caputo derivative that the drift gives for every state component of a problem of the fractional form, 1 for the ordinary states, and empty for the other forms. |
(lambda: zeros(0))()
|
transfer_network
|
TransferNetworkSpec | None
|
The quantities, flows, objectives, and feedback terms of the system, or |
None
|
backend
|
str
|
The name of the backend that produced the numeric functions. |
'numpy'
|
backends
|
Mapping[str, str]
|
The backend that runs every part of the problem: its form by the form's name, and the kernels of every law
kind by the kind's name, |
dict()
|
accelerated
|
_AcceleratedSpec | None
|
The compiled stepper loops, or |
None
|
topology
|
TopologyKernel | None
|
The topology requests of the laws and the networks they change, which the stepper applies between steps,
or |
None
|
See Also
BaseProblemSpec: The base of every problem. LayoutSpec: The names of the values of a flat vector.
Examples:
>>> from skcomplex.core.engine.problems import ProblemSpec
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> problem = LogisticGrowthSystem().prepare().simulate(until=0).problem
>>> isinstance(problem, ProblemSpec), problem.initial_state.tolist()
(True, [10.0])
adaptive_parameters
property
Declarations of the adaptive parameters of the elements and groups.
They are keyed by dotted state name.
parameter_symbols
property
Symbols of the parameter components of interactions, elements, and groups.
Elements contribute when single, and groups the symbols of one member each.
partition_problems
property
Problems of the partitions of a co-simulation problem.
A problem of one form has none.
state_symbols
property
Symbols of the state components of single elements and of group members.
Groups contribute the symbols of one member each.
stochastic
property
Whether the update draws random values.
An update that draws them takes the random number generator.
stoichiometry
property
Increments of the state vector, one row per jump channel.
get_lattice_shape(name)
Return the lattice shape of a state that lattice laws read or change.
Other states return None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted name of the state. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
shape |
tuple[int, ...] | None
|
The number of sites along every dimension. |
Source code in src/skcomplex/core/engine/problems/_problem_spec.py
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
RenewalRecordSpec(label, times, members, before, after, states)
dataclass
Bases: BaseRecordSpec
A spec of the renewals of one renewal law that fired in one pass.
It holds the label of the law, the time and the member of each renewal, such as the walkers that jumped, and the states before and after. It records the jumps of walkers in a glass, the spikes of neurons, and the repairs of machines.
Read more in the user guide, under Analyse.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The name of the renewal law. |
required |
times
|
Array
|
The time of every renewal. |
required |
members
|
NDArray[intp]
|
The member of every renewal. |
required |
before
|
Array
|
The states of every renewing member before its reset, one row per renewal and one column per state. |
required |
after
|
Array
|
The states of every renewing member after its reset. |
required |
states
|
tuple[str, ...]
|
The dotted state name, with the component of a vector state, of every column. |
required |
See Also
BaseRecordSpec: The base of every record.
Examples:
>>> from skcomplex.systems.physics.soft_matter import ContinuousTimeRandomWalkSystem
>>> trajectory = ContinuousTimeRandomWalkSystem(n_walkers=3).prepare().simulate(until=10, random_state=0)
>>> type(trajectory.events[0]).__name__, trajectory.events[0].label
('RenewalRecordSpec', 'jumps')
time
property
Time of the last renewal of the pass.
RunStateSpec(t, x, p, rng=None, source=None)
dataclass
Bases: BaseSpec
A spec of the state of a run at one time, which kernels and searches act at.
It holds the time t, the state x, the parameters p, the random generator, and the source of outside data, such
as the size 10 of a population at time 0. Kernels and searches read it in run. It carries the state of a
population, a magnet, and a market alike.
Read more in the user guide, under Extend the library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
float
|
The time. |
required |
x
|
Array
|
The state vector. |
required |
p
|
Array
|
The parameter vector, extended with the reductions or the draws when a kernel reads them. |
required |
rng
|
Generator | None
|
The random number generator of the run, or |
None
|
source
|
Mapping[str, Array] | None
|
The values of the node a topology request starts from by dotted name, or |
None
|
See Also
BaseKernel: Acts at a run state.
Examples:
>>> import numpy as np
>>> from skcomplex.core.engine.problems import RunStateSpec
>>> RunStateSpec(0.0, np.ones(2), np.zeros(0)).x.tolist()
[1.0, 1.0]