Skip to content

Specs

Specs that name classes of the core: the parts of a system as a compilation reads them.

CensusRecordSpec(path, owner, law, targets, vectors, component, space, processes=(), driven=(), reads=(), members=1, handles=()) dataclass

Bases: BaseSpec

Law of a component with the element it changes and the states it targets.

Parameters:

Name Type Description Default
path str

The path of the component that returns the law.

required
owner str

The path of the element or group whose state the law changes, or that a rule acts for.

required
law BaseLaw

The law.

required
targets tuple[EntrySpec, ...]

The layout entries of the states the law targets.

required
vectors frozenset[str]

The names of the targets declared as vector states.

required
component ElementKind

The kind of the owner: an element, a fixed or variable group, or a group on the sites of a space.

required
space BaseSpace | None

The nearest space enclosing the component.

required
processes tuple[ProcessKey | None, ...]

For a noise law, the Wiener process of every target component: None for an independent process, ('local', path, label) for a local label, or ('wiener', path, index) for a process of a WienerProcessSpec.

()
driven tuple[tuple[str, int], ...]

For a noise law, the state entry name and column of every target component.

()
reads tuple[frozenset[tuple[str, int]], ...]

For a noise law, the state components that the amplitude of every target component depends on.

()
members int

The number of members the law is evaluated for.

1
handles tuple[str, ...]

The handles of Wiener processes that the law uses outside the process of a noise law.

()

CensusSpec(system, records, errors, agents=dict()) dataclass

Bases: BaseSpec

Laws of every component of a system, and the errors of the components that fail to declare or collect.

Parameters:

Name Type Description Default
system System

The system.

required
records list[CensusRecordSpec]

The laws of the components that declare and collect without error.

required
errors list[tuple[str, SkcomplexError]]

The path of every failing component with its error.

required
agents dict[Expression, tuple[str, str]]

The path of the agent group and the variable of every symbol that reduces agents, an empty variable for the symbol of the members.

dict()

CompiledAgentsSpec(path, element, size, states, values, parameters, rules, visual, objects=(), roles=dict()) dataclass

Bases: BaseSpec

Agent element or agent group of an agent-based problem, whose states live in the Mesa model.

Parameters:

Name Type Description Default
path str

The slash-separated path of the agents in the system tree.

required
element Element | GroupElement

The agent element or the agent group.

required
size int

The initial number of agents.

required
states tuple[str, ...]

The names of the states every agent holds.

required
values Mapping[str, object]

A mapping from state name to its initial per-agent array or shared value.

required
parameters Mapping[str, str]

A mapping from parameter name to dotted name in the parameter vector.

required
rules tuple[BaseLaw, ...]

The rules every agent runs each step, in declaration order.

required
visual VisualSpec

The visual that draws the agents.

required
objects tuple[str, ...]

The names of the states that hold hashable objects.

()
roles Mapping[str, str]

A mapping from the name of a state with a role in a snapshot to its role.

dict()

CompiledElementSpec(path, element, states, parameters, visual, members=None, adaptive=dict(), lattice_shape=None, roles=dict()) dataclass

Bases: BaseSpec

Element or group of a compiled problem with the dotted names of its variables.

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
visual VisualSpec

The visual that draws the element or group.

required
members int | None

The size of a group, or None for a single element.

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 off a lattice.

None
roles Mapping[str, str]

The roles of the states that declare one, by state name.

dict()

CompiledInteractionSpec(path, interaction, roles) dataclass

Bases: BaseSpec

Interaction of a compiled problem with the paths its roles are bound to.

Parameters:

Name Type Description Default
path str

The slash-separated path of the interaction in the system tree.

required
interaction BaseInteraction

The interaction.

required
roles Mapping[str, str | tuple[str, ...]]

A mapping from role name to the path of the element, group, or observable bound to it, or to the paths of the elements of an element set.

required

LatticeContextSpec(owner, states, arguments, fused=False, others=dict()) dataclass

Bases: BaseSpec

What lattice laws are compiled against: the lattice of every state and the symbols a component reads.

Parameters:

Name Type Description Default
owner str

The path of the component that declares the laws.

required
states Mapping[Expression, LatticeStateSpec]

The lattice state of every target symbol.

required
arguments Mapping[Expression, tuple[str, bool, int, int]]

The parameters and states the component reads, by symbol, with their keyword names.

required
fused bool

Whether lookup rules run as compiled loops.

False
others Mapping[Expression, str]

The entry name of every symbol of a neighbour, the namespace s.other of the laws.

dict()

LatticeStateSpec(name, start, space) dataclass

Bases: BaseSpec

State of a lattice group in the state vector.

Parameters:

Name Type Description Default
name str

The dotted name of the state.

required
start int

The index of its first component.

required
space BaseSpace

The lattice of the group, or the network whose nodes are its sites.

required

shape cached property

Shape of the sites of the group.

sites cached property

Slice of the group's components in the state vector.

size cached property

Number of sites of the group.

NodeSpec(path, scope, component, space, component_type, members=None, interaction=False, agent=False, active=None) dataclass

Bases: BaseSpec

Element or interaction with its place in the system tree.

Parameters:

Name Type Description Default
path str

The slash-separated path of the component.

required
scope str

The path prefix of the system that holds the component.

required
component Element | GroupElement | BaseInteraction | WienerProcessSpec

The element, group, or interaction, or the Wiener processes that the noise role of an interaction binds.

required
space BaseSpace | None

The nearest enclosing space.

required
component_type type

The element type of a group, or the type of an element, an interaction, or a Wiener process.

required
members int | None

The size of a group, or None for a single element, an interaction, or a Wiener process.

None
interaction bool

Whether the component is not an element or a group: an interaction or a Wiener process.

False
agent bool

Whether the component runs on the agent stepper, as a pass of a formalism decides.

False
active int | None

The initial number of members of a variable group on the sites or edges of a network, whose capacity is its size, or None for every other component.

None

is_agent property

Whether the node is an agent element or an agent group, which runs on the agent stepper.

OperatorViewSpec(element, state, space) dataclass

Bases: BaseSpec

View of an element with a state in a Hilbert space, as the operator compiler reads it.

Parameters:

Name Type Description Default
element Element

The element.

required
state str

The name of the state of the element in its Hilbert space.

required
space HilbertSpec

The Hilbert space of the element.

required

Examples:

>>> import numpy as np
>>> from typing import Annotated
>>> from sage.all__sagemath_symbolics import CC
>>> from skcomplex.core.elements import Element
>>> from skcomplex.specs import HilbertSpec, StateSpec
>>> from skcomplex.core.specs import OperatorViewSpec
>>> QUBIT = HilbertSpec(2, {'z': (np.diag([1.0, -1.0]), True)}, basis={'up': 0, 'down': 1})
>>> class TwoLevelElement(Element):
...     def __init__(self, label, psi: Annotated[object, StateSpec(domain=CC**2)] = 'up', hilbert=QUBIT):
...         super().__init__(label)
...         self.psi = psi
...         self.hilbert = hilbert
>>> OperatorViewSpec(TwoLevelElement('q', psi='down'), 'psi', QUBIT).initial_vector().tolist()
[0j, (1+0j)]

dimension property

Dimension of the Hilbert space.

display property

Operator whose expectation visuals show for a group, or None for the probabilities of the basis.

label property

Label of the element.

basis_index(label)

Return the index of the basis state of a label or an index.

Parameters:

Name Type Description Default
label object

The label of a basis state, or its index.

required

Returns:

Name Type Description
index int

The index of the basis state.

Raises:

Type Description
ValidationError

The label names no basis state.

Source code in src/skcomplex/core/specs/_operator_view_spec.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def basis_index(self, label: object) -> int:
    """Return the index of the basis state of a label or an index.

    Args:
        label:
            The label of a basis state, or its index.

    Returns:
        index:
            The index of the basis state.

    Raises:
        ValidationError:
            The label names no basis state.
    """
    space = self.space
    if isinstance(label, str) and label in space.basis:
        return space.basis[label]
    if isinstance(label, int | np.integer) and not isinstance(label, bool) and 0 <= label < space.dimension:
        return int(label)
    labels = ', '.join(map(repr, space.basis)) or 'none'
    error_msg = (
        f'{type(self.element).__name__} {self.label!r}: {label!r} is no basis state. Use a label ({labels}) or an '
        f'index from 0 to {space.dimension - 1}.'
    )
    raise ValidationError(error_msg)

initial_vector()

Return the initial state of the element as a normalised vector.

Returns:

Name Type Description
vector NDArray[complex128]

The initial state.

Raises:

Type Description
ValidationError

The initial state names no basis state, or is a vector of the wrong size or norm.

Source code in src/skcomplex/core/specs/_operator_view_spec.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def initial_vector(self) -> npt.NDArray[np.complex128]:
    """Return the initial state of the element as a normalised vector.

    Returns:
        vector:
            The initial state.

    Raises:
        ValidationError:
            The initial state names no basis state, or is a vector of the wrong size or norm.
    """
    initial = getattr(self.element, self.state)
    if isinstance(initial, str | int | np.integer):
        vector = np.zeros(self.dimension, dtype=complex)
        vector[self.basis_index(initial)] = 1.0
        return vector
    vector = np.asarray(initial, dtype=complex).ravel()
    norm = float(np.linalg.norm(vector))
    if vector.size != self.dimension or abs(norm - 1) > NORM_TOLERANCE:
        error_msg = (
            f'The initial vector of {self.label!r} has {vector.size} components and norm {norm:.6g}, but its '
            f'space has dimension {self.dimension} and states have norm 1. Normalise the vector.'
        )
        raise ValidationError(error_msg)
    return vector

local_operators()

Return the local operators of the element by name.

Returns:

Name Type Description
operators dict[str, LocalOperatorSpec]

A mapping from name to local operator.

Source code in src/skcomplex/core/specs/_operator_view_spec.py
72
73
74
75
76
77
78
79
80
81
82
def local_operators(self) -> dict[str, LocalOperatorSpec]:
    """Return the local operators of the element by name.

    Returns:
        operators:
            A mapping from name to local operator.
    """
    return {
        name: LocalOperatorSpec(name, LocalOperatorSpec._sparse_matrix(matrix), hermitian=hermitian)
        for name, (matrix, hermitian) in self.space.operators.items()
    }

ScenarioSpec(name='baseline', overrides=None, schedule=(), system=None) dataclass

Bases: BaseSpec

Named variant of a model: overrides before the run, parameter changes at given times, or another system.

Every scenario of an experiment runs with the same random streams per design row and replicate, so scenarios differ only through what they change.

Parameters:

Name Type Description Default
name str

The name of the scenario.

'baseline'
overrides Mapping[str, object] | None

A mapping from factory argument or dotted path to the value it takes before the run.

None
schedule Sequence[tuple[float, str, object]]

The changes during the run, as (time, dotted parameter path, value), applied from the first frame at or after their time.

()
system System | None

A system that replaces the model's system, for structural changes, or None.

None

Examples:

>>> from skcomplex.core.specs import ScenarioSpec
>>> ScenarioSpec('reduced', schedule=[(50.0, 'source.rate', 0.025)]).schedule
[(50.0, 'source.rate', 0.025)]