Skip to content

Declaration layer

units

Units, dimensions and the 2*pi convention.

The conventions are hbar = 1, the energy unit rad/ms and the time unit ms; frequencies are angular. Ordinary frequencies quoted in Hz or kHz are converted by from_hertz and from_kilohertz and their inverses; for instance, from_hertz(33.0) == 2*pi * 33 / 1000 == 0.2073....

Dimension

Bases: Enum

The physical dimension of a parameter.

ENERGY class-attribute instance-attribute
ENERGY = 'energy'

An energy, equivalently an angular frequency, in rad/ms.

TIME class-attribute instance-attribute
TIME = 'time'

A time, in ms.

DIMENSIONLESS class-attribute instance-attribute
DIMENSIONLESS = 'dimensionless'

A pure number: a ratio, a count, or a lattice spacing at a = 1.

unit property
unit: str

The unit string used when a value of this dimension is printed.

from_hertz

from_hertz(frequency_hz: float) -> float

Convert an ordinary frequency in Hz to an energy in rad/ms.

to_hertz

to_hertz(energy: float) -> float

Convert an energy in rad/ms to an ordinary frequency in Hz.

from_kilohertz

from_kilohertz(frequency_khz: float) -> float

Convert an ordinary frequency in kHz to an energy in rad/ms.

to_kilohertz

to_kilohertz(energy: float) -> float

Convert an energy in rad/ms to an ordinary frequency in kHz.

scalar

A symbolic scalar algebra for parameters and coefficients.

The algebra has six node kinds, Const, Symbol, Add, Mul, Pow and Abs, with evaluation, substitution, interval arithmetic and simplify. Evaluation uses only +, *, ** and abs, so that it applies to Python numbers and to JAX scalars alike. str() renders the simplified expression; the stored expression is unchanged.

DomainError

Bases: ZeroDivisionError

The error raised when a scalar expression is evaluated at a division by zero.

Attributes:

Name Type Description
expression

the vanishing sub-expression.

Scalar

Bases: ABC

A symbolic scalar expression over named parameters.

evaluate abstractmethod
evaluate(env: Mapping[str, NumericValue]) -> NumericValue

Evaluate the expression.

Parameters:

Name Type Description Default
env Mapping[str, NumericValue]

the values of the free symbols. Python numbers yield a Python number; JAX scalars yield a traceable JAX scalar.

required

Returns:

Type Description
NumericValue

The value, in the numeric type supplied by env.

Raises:

Type Description
KeyError

if a free symbol is missing from env.

DomainError

on a division by zero.

symbols abstractmethod
symbols() -> frozenset[str]

The names of the free symbols occurring in the expression.

substitute abstractmethod
substitute(env: Mapping[str, ScalarLike]) -> Scalar

Replace symbols by expressions or values and return a new expression.

interval abstractmethod
interval(env: Mapping[str, Interval]) -> Interval

Bound the expression by interval arithmetic, given interval bounds on its symbols.

Parameters:

Name Type Description Default
env Mapping[str, Interval]

an interval per symbol; unbounded symbols default to the whole real line.

required

Returns:

Type Description
Interval

A sound enclosure, not necessarily tight.

evaluate_real
evaluate_real(env: Mapping[str, NumericValue]) -> float

Evaluate the expression and return a real float.

Parameters:

Name Type Description Default
env Mapping[str, NumericValue]

the values of the free symbols.

required

Returns:

Type Description
float

The real part of the value.

Raises:

Type Description
ValueError

if the value has a non-negligible imaginary part.

is_constant
is_constant() -> bool

Whether the expression has no free symbols.

simplified
simplified() -> Scalar

The expression with constants folded and nesting flattened.

See simplify.

Const dataclass

Bases: Scalar

A numeric literal.

evaluate
evaluate(env: Mapping[str, NumericValue]) -> NumericValue

Return the literal value.

symbols
symbols() -> frozenset[str]

The empty set; a literal has no free symbols.

substitute
substitute(env: Mapping[str, ScalarLike]) -> Scalar

A literal is unchanged by substitution.

interval
interval(env: Mapping[str, Interval]) -> Interval

A literal is a degenerate interval.

Raises:

Type Description
ValueError

if the literal is complex.

Symbol dataclass

Bases: Scalar

A named free parameter.

evaluate
evaluate(env: Mapping[str, NumericValue]) -> NumericValue

Look the symbol up in env.

Raises:

Type Description
KeyError

if the symbol is unbound.

symbols
symbols() -> frozenset[str]

The symbol itself.

substitute
substitute(env: Mapping[str, ScalarLike]) -> Scalar

Replace the symbol if env binds it.

interval
interval(env: Mapping[str, Interval]) -> Interval

Look up the bounds of the symbol in env, defaulting to the whole real line.

Add dataclass

Bases: Scalar

A sum of two or more terms.

evaluate
evaluate(env: Mapping[str, NumericValue]) -> NumericValue

Sum the terms.

symbols
symbols() -> frozenset[str]

The union of the symbols of the terms.

substitute
substitute(env: Mapping[str, ScalarLike]) -> Scalar

Substitute into every term.

interval
interval(env: Mapping[str, Interval]) -> Interval

Sum the intervals of the terms.

Mul dataclass

Bases: Scalar

A product of two or more factors.

evaluate
evaluate(env: Mapping[str, NumericValue]) -> NumericValue

Multiply the factors.

symbols
symbols() -> frozenset[str]

The union of the symbols of the factors.

substitute
substitute(env: Mapping[str, ScalarLike]) -> Scalar

Substitute into every factor.

interval
interval(env: Mapping[str, Interval]) -> Interval

Multiply the intervals of the factors.

Pow dataclass

Bases: Scalar

A power with a fixed real exponent.

evaluate
evaluate(env: Mapping[str, NumericValue]) -> NumericValue

Raise the base to the exponent.

Raises:

Type Description
DomainError

if the exponent is negative and the base vanishes.

symbols
symbols() -> frozenset[str]

The symbols of the base.

substitute
substitute(env: Mapping[str, ScalarLike]) -> Scalar

Substitute into the base.

interval
interval(env: Mapping[str, Interval]) -> Interval

Bound the power.

Abs dataclass

Bases: Scalar

The absolute value of an expression.

evaluate
evaluate(env: Mapping[str, NumericValue]) -> NumericValue

The magnitude of the argument.

symbols
symbols() -> frozenset[str]

The symbols of the argument.

substitute
substitute(env: Mapping[str, ScalarLike]) -> Scalar

Substitute into the argument.

interval
interval(env: Mapping[str, Interval]) -> Interval

Bound the magnitude; an interval that contains zero has the least magnitude 0.

Interval dataclass

A closed real interval with sound arithmetic.

Division by an interval that contains zero yields the whole real line.

Attributes:

Name Type Description
lo float

the lower endpoint; may be -inf.

hi float

the upper endpoint; may be +inf.

is_bounded property
is_bounded: bool

Whether both endpoints are finite.

contains
contains(value: float, tolerance: float = 0.0) -> bool

Whether value lies in the interval, within tolerance.

straddles_zero
straddles_zero() -> bool

Whether the interval contains zero.

as_scalar

as_scalar(value: ScalarLike) -> Scalar

Coerce a number to a Const; a Scalar is passed through.

Parameters:

Name Type Description Default
value ScalarLike

a Scalar or a number.

required

Returns:

Type Description
Scalar

The scalar expression.

Raises:

Type Description
TypeError

if value is neither a number nor a Scalar.

simplify

simplify(expression: ScalarLike) -> Scalar

Fold constants and flatten nesting without changing the value or domain of the expression.

Nested sums and products are flattened, constant terms and factors combined, additive zeros and multiplicative ones dropped, unit exponents removed, and constants raised to integer powers evaluated. Constants raised to fractional powers are not folded, nor are products with a zero factor whose other factors can raise a DomainError.

Parameters:

Name Type Description Default
expression ScalarLike

the expression to fold.

required

Returns:

Type Description
Scalar

An expression with the same value and domain as the original.

sqrt

sqrt(value: ScalarLike) -> Scalar

The square root of an expression.

absolute

absolute(value: ScalarLike) -> Scalar

The magnitude of an expression.

summation

summation(terms: Iterable[ScalarLike]) -> Scalar

The sum of an iterable of expressions; the empty sum is zero.

envelope

envelope(intervals: Sequence[Interval]) -> Interval

The smallest interval containing all of intervals.

Raises:

Type Description
ValueError

if intervals is empty.

affine

Affine arithmetic: interval bounds that retain first-order correlations between symbols.

An affine form is x = x0 + sum_i x_i e_i + e * eta, where each e_i is an unknown in [-1, 1] shared between forms, one per bounded symbol, and eta is a private unknown carrying the non-linear remainder. Every operation over-approximates, so that bound returns a sound enclosure, which may be intersected with the plain interval bound. Sub-expressions that admit no affine approximation enter as their interval bound, as a form without shared dependence.

AffineForm dataclass

A value as a centre, a linear part over shared unknowns, and a private error.

Attributes:

Name Type Description
center float

the constant term.

deviations Mapping[int, float]

the coefficient of each shared unknown, keyed by symbol index; absent keys are zero.

error float

the non-negative radius of the private unknown.

radius property
radius: float

The largest deviation of the form from its centre.

interval property
interval: Interval

The interval that contains the form.

of_interval classmethod
of_interval(
    interval: Interval, index: int | None = None
) -> AffineForm

A form for a quantity known only to lie in interval.

Parameters:

Name Type Description Default
interval Interval

the bounds, which must be finite.

required
index int | None

the shared unknown that carries the width; None places the whole width in the private error.

None

Returns:

Type Description
AffineForm

The form.

scaled
scaled(factor: float) -> AffineForm

The form multiplied by a constant.

shifted
shifted(offset: float) -> AffineForm

The form with a constant added.

widened
widened(extra: float) -> AffineForm

The form with additional private error.

bound

bound(
    expression: Scalar, env: Mapping[str, Interval]
) -> Interval | None

Bound expression by affine arithmetic over an interval environment.

Parameters:

Name Type Description Default
expression Scalar

the expression to bound.

required
env Mapping[str, Interval]

an interval per symbol. A symbol absent from env, or one with an unbounded interval, causes the traversal to abandon the affine bound.

required

Returns:

Type Description
Interval | None

A sound interval, or None if no affine bound can be formed.

structure

Structural types: the geometry, degrees of freedom with their algebra, and declared symmetries.

The type is a symbolic representation of the physical and mathematical properties of the operators without numerics; no Hilbert space is constructed. A StructureType is compared structurally; a StructurePattern constrains only the aspects it lists and yields StructureMismatch records on failure.

Site indexing is interleaved at every abstraction level: matter site l is register index 2*l (l = 0 .. N-1) and gauge link (l, l+1) is register index 2*l + 1 (l = 0 .. N-2), so that N matter sites occupy 2*N - 1 register positions.

Algebra

Bases: Enum

The operator algebra a degree of freedom obeys.

FERMION class-attribute instance-attribute
FERMION = 'fermion'

A spinless fermionic mode with canonical anticommutation relations and occupation in {0, 1}.

BOSON class-attribute instance-attribute
BOSON = 'boson'

A bosonic mode with canonical commutation relations and occupation in {0, 1, 2, ...}.

SPIN_HALF class-attribute instance-attribute
SPIN_HALF = 'spin-1/2'

A spin-1/2 degree of freedom, described by S^z and S^+-.

QUBIT class-attribute instance-attribute
QUBIT = 'qubit'

A qubit, described by Pauli operators, with S^z = sigma^z / 2; the algebra is distinct from SPIN_HALF.

GAUGE_LINK_U1 = 'gauge-link-U(1)'

An untruncated compact U(1) link with unbounded electric field and no finite-dimensional representation.

local_dimension property
local_dimension: int | None

The dimension of the Hilbert space of one site, or None if not fixed by the algebra.

The dimension of a bosonic mode is None; it is fixed by an occupation cutoff at the numerical realisation.

is_finite_dimensional property
is_finite_dimensional: bool

Whether the algebra has a finite-dimensional representation.

LatticeGeometry

Bases: Enum

The spatial arrangement of the sites.

spatial_dimension property
spatial_dimension: int

The number of spatial dimensions.

Lattice dataclass

The lattice geometry of a model.

Attributes:

Name Type Description
geometry LatticeGeometry

the arrangement of the sites.

matter_sites int

the number of sites carrying the primary degree of freedom.

link_count int | None

the number of additional link positions, or None to derive it from the geometry, N - 1 on an open chain and N on a periodic one. The value 0 declares a lattice without link degrees of freedom.

links: int

The number of link positions.

register_size property
register_size: int

The number of interleaved register positions, 2*N - 1 on an open chain.

spatial_dimension property
spatial_dimension: int

The number of spatial dimensions.

DegreeOfFreedom dataclass

One family of degrees of freedom: a role, an algebra and a set of sites.

Attributes:

Name Type Description
role str

the physical role of the family, for instance "matter" or "gauge".

algebra Algebra

the operator algebra obeyed on these sites.

sites tuple[int, ...]

the register indices occupied, in ascending order.

label str

a description used in reports only.

count property
count: int

The number of sites in the family.

SymmetryDeclaration dataclass

A declared symmetry of a model; the generators are stored on the model.

Attributes:

Name Type Description
name str

the identifier under which the constraint operators of the model are stored.

group str

the symmetry group, for instance "U(1)".

local bool

whether there is one generator per site, as for a gauge symmetry.

StructureType dataclass

The structural type of a model; == is structural equality.

Attributes:

Name Type Description
lattice Lattice

the geometry.

degrees_of_freedom tuple[DegreeOfFreedom, ...]

the degree-of-freedom families, with distinct roles.

symmetries frozenset[SymmetryDeclaration]

the declared symmetries.

name str

a name used in reports.

sites property
sites: tuple[int, ...]

Every occupied register position, in ascending order.

is_finite_dimensional property
is_finite_dimensional: bool

Whether every family admits a finite-dimensional representation.

dof
dof(role: str) -> DegreeOfFreedom

The degree-of-freedom family with the given role.

Raises:

Type Description
KeyError

if no family has that role.

roles
roles() -> tuple[str, ...]

The roles present, in declaration order.

dof_at
dof_at(site: int) -> DegreeOfFreedom

The degree-of-freedom family occupying a register position.

Raises:

Type Description
KeyError

if no declared family occupies that site.

algebra_at
algebra_at(site: int) -> Algebra

The algebra obeyed at a register position.

Raises:

Type Description
KeyError

if no declared family occupies that site.

role_at
role_at(site: int) -> str

The role of the family occupying a register position.

Raises:

Type Description
KeyError

if no declared family occupies that site.

symmetry
symmetry(name: str) -> SymmetryDeclaration | None

The declared symmetry of that name, or None.

with_symmetry
with_symmetry(
    declaration: SymmetryDeclaration,
) -> StructureType

A copy with one more declared symmetry.

StructureMismatch dataclass

One reason for which a structure fails to match a pattern.

Attributes:

Name Type Description
aspect str

the part of the type that did not match, for instance "lattice.geometry" or "dof[matter].algebra".

required str

the requirement of the pattern, rendered for the diagnostic.

found str

the value found in the structure.

StructureTypeError

Bases: TypeError

The diagnostic raised when the structure of a model does not match a required source type.

Attributes:

Name Type Description
subject

the name of the checked object.

mismatches

the individual mismatches.

DofRequirement dataclass

The requirement of a pattern on one degree-of-freedom family.

Attributes:

Name Type Description
role str

the role that must be present.

algebras frozenset[Algebra]

the accepted algebras; the empty set accepts any algebra.

min_sites int

the least number of sites accepted.

check
check(structure: StructureType) -> list[StructureMismatch]

The mismatches of this requirement against structure.

StructurePattern dataclass

A partial description of a structural type; unmentioned aspects are accepted.

Attributes:

Name Type Description
geometries frozenset[LatticeGeometry]

the accepted lattice geometries; the empty set accepts any geometry.

dofs tuple[DofRequirement, ...]

the requirements on individual degree-of-freedom families.

required_symmetries frozenset[str]

the names of symmetries that must be declared.

forbidden_roles frozenset[str]

the roles that must not be present.

forbidden_symmetries frozenset[str]

the names of symmetries that must not be declared.

description str

a summary used in diagnostics.

mismatches
mismatches(
    structure: StructureType,
) -> list[StructureMismatch]

Every mismatch of structure against the pattern, or an empty list.

matches
matches(structure: StructureType) -> bool

Whether structure matches the pattern.

guarantee_gaps
guarantee_gaps(
    demanded: StructurePattern,
) -> list[StructureMismatch]

The aspects in which this pattern, taken as a declaration, may fail demanded.

The pattern is taken as the structural type the producing transformation declares for its target.

Parameters:

Name Type Description Default
demanded StructurePattern

the source pattern required by the next transformation.

required

Returns:

Type Description
list[StructureMismatch]

The gaps; empty if the two patterns compose.

meets
meets(demanded: StructurePattern) -> bool

Whether this pattern, taken as a declaration, satisfies demanded.

check
check(structure: StructureType, subject: str) -> None

Raise a diagnostic if structure does not match the pattern.

Parameters:

Name Type Description Default
structure StructureType

the structure to check.

required
subject str

the name used in the diagnostic, for instance the name of the transformation.

required

Raises:

Type Description
StructureTypeError

on any mismatch.

interleaved_matter_index

interleaved_matter_index(matter_site: int) -> int

The register index of matter site l: 2*l.

interleaved_link_index(left_matter_site: int) -> int

The register index of the link (l, l+1): 2*l + 1.

interleaved_site_count

interleaved_site_count(matter_sites: int) -> int

The register size for N matter sites on an open chain: 2*N - 1.

matter_indices

matter_indices(matter_sites: int) -> tuple[int, ...]

The register indices of the matter sites, in ascending order.

link_indices(matter_sites: int) -> tuple[int, ...]

The register indices of the links of an open chain, in ascending order.

open_chain_pattern

open_chain_pattern(
    description: str,
    requirements: Iterable[DofRequirement],
    *,
    required_symmetries: Iterable[str] = (),
    forbidden_symmetries: Iterable[str] = (),
) -> StructurePattern

A structural pattern over an open 1D chain, with requirements on its roles.

Parameters:

Name Type Description Default
description str

a summary used in diagnostics.

required
requirements Iterable[DofRequirement]

the requirements on individual degree-of-freedom families.

required
required_symmetries Iterable[str]

the names of symmetries that must be declared.

()
forbidden_symmetries Iterable[str]

the names of symmetries that must not be declared.

()

Returns:

Type Description
StructurePattern

The pattern.

open_chain_structure

open_chain_structure(
    matter_sites: int,
    matter_algebra: Algebra,
    gauge_algebra: Algebra,
    *,
    name: str,
    symmetries: Iterable[SymmetryDeclaration] = (),
    matter_role: str = "matter",
    gauge_role: str = "gauge",
) -> StructureType

Build an interleaved open-chain structure, matter on even and gauge on odd positions.

Parameters:

Name Type Description Default
matter_sites int

the number of matter sites N.

required
matter_algebra Algebra

the algebra on the even register positions.

required
gauge_algebra Algebra

the algebra on the odd register positions.

required
name str

a name for the structural type, used in reports.

required
symmetries Iterable[SymmetryDeclaration]

declared symmetries.

()
matter_role str

the role name for the matter family.

'matter'
gauge_role str

the role name for the gauge family.

'gauge'

Returns:

Type Description
StructureType

The structural type.

symbolic

Symbolic operators: site operators, terms and operator sums.

A Hamiltonian is a tuple of Term, each a Scalar coefficient times an ordered tuple of SiteOperator factors. Operator order within a term is preserved and significant; no reordering or normal ordering is performed symbolically. Exact commutators are computed in the Pauli representation of qsimod.pauli.

ZERO module-attribute

ZERO = OperatorSum(())

The empty sum.

OpSymbol

Bases: Enum

A primitive single-site operator.

CREATE class-attribute instance-attribute
CREATE = 'create'

The creation operator, fermionic or bosonic according to the algebra of the site.

ANNIHILATE class-attribute instance-attribute
ANNIHILATE = 'annihilate'

The annihilation operator, fermionic or bosonic according to the algebra of the site.

NUMBER class-attribute instance-attribute
NUMBER = 'number'

The occupation number. On a qubit it is (sigma^z + 1) / 2.

PARITY class-attribute instance-attribute
PARITY = 'parity'

1 - 2n, the fermionic parity of a two-level site, -Z on a qubit. It is the factor of a Jordan-Wigner string; as a single operator, a string of length L is one word of L factors rather than 2**L words.

SPIN_Z class-attribute instance-attribute
SPIN_Z = 'spin-z'

S^z, with eigenvalues +-1/2.

SPIN_PLUS class-attribute instance-attribute
SPIN_PLUS = 'spin-plus'

S^+, the spin-1/2 raising operator.

SPIN_MINUS class-attribute instance-attribute
SPIN_MINUS = 'spin-minus'

S^-, the spin-1/2 lowering operator.

SIGMA_PLUS class-attribute instance-attribute
SIGMA_PLUS = 'sigma-plus'

sigma^+ = |n=1><n=0| = (X + iY)/2.

SIGMA_MINUS class-attribute instance-attribute
SIGMA_MINUS = 'sigma-minus'

sigma^- = |n=0><n=1| = (X - iY)/2.

LINK_U = 'link-U'

The compact U(1) link operator of the Kogut-Susskind Hamiltonian.

ELECTRIC_FIELD class-attribute instance-attribute
ELECTRIC_FIELD = 'electric-field'

The link electric field E, with unbounded spectrum.

adjoint property
adjoint: OpSymbol

The Hermitian adjoint of this operator.

is_self_adjoint property
is_self_adjoint: bool

Whether the operator equals its own adjoint.

render
render(site: int, ladder_glyph: str = 'b') -> str

A compact unicode rendering of the operator at site.

Parameters:

Name Type Description Default
site int

the register position.

required
ladder_glyph str

the letter used for the creation, annihilation and number operators, for instance the Greek letter psi for a fermionic site and "b" for a bosonic one.

'b'

SiteOperator dataclass

A primitive operator acting on one register position.

adjoint property
adjoint: SiteOperator

The Hermitian adjoint, on the same site.

render
render(ladder_glyph: str = 'b') -> str

A compact unicode rendering, with ladder_glyph for the ladder operators.

Term dataclass

A coefficient times an ordered product of site operators.

Attributes:

Name Type Description
coefficient Scalar

the scalar coefficient.

operators tuple[SiteOperator, ...]

the factors, in order; the empty tuple denotes the identity.

support property
support: frozenset[int]

The register positions on which the term acts.

locality property
locality: int

The number of distinct register positions on which the term acts.

is_constant property
is_constant: bool

Whether the term is a multiple of the identity.

adjoint
adjoint() -> Term

The Hermitian adjoint, with the factors reversed and each conjugated.

scaled
scaled(factor: ScalarLike) -> Term

The term with its coefficient multiplied by factor.

substitute
substitute(env: Mapping[str, ScalarLike]) -> Term

The term with parameter values substituted into its coefficient.

render
render(glyphs: Mapping[int, str] | None = None) -> str

Render the term, optionally with a ladder-operator glyph per site.

OperatorSum dataclass

A symbolic sum of operator products; the representation of a Hamiltonian.

Attributes:

Name Type Description
terms tuple[Term, ...]

the terms, in the order written.

name str

a display name.

support property
support: frozenset[int]

Every register position on which some term acts.

max_locality property
max_locality: int

The largest number of positions on which a single term acts.

parameters property
parameters: frozenset[str]

The free parameter names occurring in the coefficients.

adjoint
adjoint() -> OperatorSum

The Hermitian adjoint of the whole sum.

plus_adjoint
plus_adjoint() -> OperatorSum

self + self.adjoint(), the + h.c. of the printed Hamiltonians.

substitute
substitute(env: Mapping[str, ScalarLike]) -> OperatorSum

Substitute parameter values into every coefficient.

renamed
renamed(name: str) -> OperatorSum

A copy carrying a different display name.

constant_part
constant_part() -> Scalar

The sum of the coefficients of the identity terms.

without_constants
without_constants() -> OperatorSum

A copy with the additive constants removed.

collected
collected() -> OperatorSum

A copy with terms of identical operator tuples merged, in order of first occurrence.

Terms are merged by exact identity of the operator tuple; b_0 b_1 and b_1 b_0 remain distinct.

validate_against
validate_against(algebra_at: Mapping[int, Algebra]) -> None

Check that every factor is admissible on the algebra of the site on which it acts.

Parameters:

Name Type Description Default
algebra_at Mapping[int, Algebra]

the algebra of each register position.

required

Raises:

Type Description
ValueError

if a factor acts on an undeclared site, or on a site whose algebra does not admit that operator.

pretty
pretty(glyphs: Mapping[int, str] | None = None) -> str

A multi-line rendering, one term per line.

Parameters:

Name Type Description Default
glyphs Mapping[int, str] | None

the ladder-operator letter per register position, for instance the Greek letter psi on fermionic sites and "b" on bosonic ones.

None

Returns:

Type Description
str

The rendered Hamiltonian.

create

create(site: int) -> SiteOperator

A creation operator on site.

annihilate

annihilate(site: int) -> SiteOperator

An annihilation operator on site.

number

number(site: int) -> SiteOperator

An occupation-number operator on site.

parity

parity(site: int) -> SiteOperator

1 - 2 n_site, the parity of a fermionic or qubit site.

spin_z

spin_z(site: int) -> SiteOperator

S^z on site.

spin_plus

spin_plus(site: int) -> SiteOperator

S^+ on site.

spin_minus

spin_minus(site: int) -> SiteOperator

S^- on site.

pauli_x

pauli_x(site: int) -> SiteOperator

X on site.

pauli_y

pauli_y(site: int) -> SiteOperator

Y on site.

pauli_z

pauli_z(site: int) -> SiteOperator

Z on site.

sigma_plus

sigma_plus(site: int) -> SiteOperator

sigma^+ on site.

sigma_minus

sigma_minus(site: int) -> SiteOperator

sigma^- on site.

link_u(site: int, *, dagger: bool = False) -> SiteOperator

The compact link operator U, or U^dagger, on site.

electric_field

electric_field(site: int) -> SiteOperator

The link electric field E on site.

identity_term

identity_term(coefficient: ScalarLike) -> Term

A purely additive constant.

word

word(
    coefficient: ScalarLike, *operators: SiteOperator
) -> OperatorSum

A one-term operator sum: coefficient times the given ordered product.

constant

constant(coefficient: ScalarLike) -> OperatorSum

A purely additive constant, as a one-term operator sum.

normal_form

A normal form for symbolic operator sums, and the equivalence of two sums.

normal_form rewrites an OperatorSum into a canonical one: at most one canonical operator per site (c^dag, c, n on a fermion, X, Y, Z on a qubit, S^z, S^+, S^- on a spin-1/2, normal-ordered (a^dag)^p a^q on a boson), sites in ascending order, fermionic signs carried by the reordering. Two sums are equivalent when their normal forms agree term by term, the coefficients compared as expressions in the parameters. No matrix is constructed; the algebra tables match the local matrices of qsimod.realise.hilbert.

normal_form

normal_form(
    operator: OperatorSum, algebra_at: Mapping[int, Algebra]
) -> OperatorSum

The canonical form of an operator sum.

Parameters:

Name Type Description Default
operator OperatorSum

the sum to normalise.

required
algebra_at Mapping[int, Algebra]

the algebra of every register site the sum may act on.

required

Returns:

Type Description
OperatorSum

A sum with one term per distinct canonical word, the sites in ascending order within

OperatorSum

each word, the coefficients simplified, and terms whose coefficient folds to zero

OperatorSum

removed. The identity term, if present, is first; the others follow in order of

OperatorSum

first occurrence.

Raises:

Type Description
ValueError

if a factor acts on a site algebra_at does not declare.

product

product(
    left: OperatorSum, right: OperatorSum
) -> OperatorSum

The operator product left * right: every pair of words concatenated, in order.

rewrite

rewrite(
    operator: OperatorSum, image: OperatorImage
) -> OperatorSum

Replace every site operator by its image, multiplying the images out in order.

The rule is applied factor by factor, so that it must be an algebra homomorphism on the factors it is applied to: the image of a product is the product of the images. A rule may map one factor to a sum, for instance n -> 1 - n, or to a word on several sites, for instance a Jordan-Wigner string.

Parameters:

Name Type Description Default
operator OperatorSum

the sum to rewrite.

required
image OperatorImage

the per-factor rule.

required

Returns:

Type Description
OperatorSum

The rewritten sum, not normalised.

sample_environments

sample_environments(
    symbols: Iterable[str],
    count: int = 3,
    seed: int = DEFAULT_SAMPLE_SEED,
) -> tuple[dict[str, float], ...]

Deterministic parameter points at which coefficient expressions are compared.

The values lie in [0.5, 1.5], away from zero, so that a ratio of parameters is finite.

difference

difference(
    left: OperatorSum,
    right: OperatorSum,
    algebra_at: Mapping[int, Algebra],
    *,
    tolerance: float = 1e-09,
    samples: Sequence[Mapping[str, float]] | None = None,
) -> OperatorSum

left - right in normal form, with the terms whose coefficients vanish removed.

A coefficient vanishes when it folds to the constant zero, or when it evaluates to at most tolerance times the largest coefficient magnitude of either operand at every sample point.

Parameters:

Name Type Description Default
left OperatorSum

one operand.

required
right OperatorSum

the other.

required
algebra_at Mapping[int, Algebra]

the algebra of every register site either may act on.

required
tolerance float

the relative tolerance on a coefficient.

1e-09
samples Sequence[Mapping[str, float]] | None

the parameter points; defaults to sample_environments over both operands' parameters.

None

Returns:

Type Description
OperatorSum

The surviving terms of the difference; empty exactly when the operands are equivalent.

equivalent

equivalent(
    left: OperatorSum,
    right: OperatorSum,
    algebra_at: Mapping[int, Algebra],
    *,
    tolerance: float = 1e-09,
) -> bool

Whether two sums denote the same operator on the given algebras.

constant_word

constant_word(coefficient: ScalarLike) -> OperatorSum

A one-term identity sum, used to build images.

parameters

Parameters, bindings, and the admissible set of knob settings a hardware model declares.

Parameters are named symbols with a physical dimension, namespaced by the owning model, for instance "bose_hubbard.J". An AdmissibleSet holds Bound records and InequalityConstraint expressions of the form expression >= 0.

EMPTY_ADMISSIBLE_SET module-attribute

EMPTY_ADMISSIBLE_SET = AdmissibleSet(
    description="unconstrained"
)

The admissible set of a model that declares no knob limits.

Parameter dataclass

A named physical parameter.

Attributes:

Name Type Description
name str

the symbol name used in coefficient expressions, namespaced by the owning model ("bose_hubbard.J").

dimension Dimension

the physical dimension of the parameter.

description str

a one-line description, used in reports.

symbol property
symbol: Symbol

The scalar symbol for this parameter.

local_name property
local_name: str

The part of the name after the last dot, that is, the name without its namespace.

ParameterSet dataclass

An ordered, name-indexed collection of parameters with distinct names.

Attributes:

Name Type Description
parameters tuple[Parameter, ...]

the parameters, in declaration order.

names property
names: tuple[str, ...]

The parameter names, in declaration order.

get
get(name: str) -> Parameter

The parameter of that name.

Raises:

Type Description
KeyError

if no parameter has that name.

union
union(other: ParameterSet) -> ParameterSet

The union with another set, keeping this set's entry on a name clash.

symbols
symbols() -> dict[str, Symbol]

A mapping from local name to scalar symbol, used to build expressions.

Namespace dataclass

The prefix carried by the parameter names of a model.

hardware = Namespace("device")
hardware("J")  # 'device.J'
hardware.parameter("J", description="tunnelling")

Attributes:

Name Type Description
prefix str

the namespace, without the separating dot.

symbol
symbol(local: str) -> Symbol

The scalar symbol of a local parameter name.

parameter
parameter(
    local: str,
    dimension: Dimension = Dimension.ENERGY,
    description: str = "",
) -> Parameter

A Parameter in this namespace.

parameter_set
parameter_set(
    *locals_: tuple[str, Dimension, str],
) -> ParameterSet

A parameter set from (local name, dimension, description) triples.

Bound dataclass

A box bound on one knob, with optional strictness.

J in (0, J_max] is Bound("J", 0.0, j_max, strict_lower=True).

Attributes:

Name Type Description
parameter str

the name of the knob.

lower float

the lower endpoint; may be -inf.

upper float

the upper endpoint; may be +inf.

strict_lower bool

whether the lower endpoint is excluded.

strict_upper bool

whether the upper endpoint is excluded.

margin float

the distance inside a strict endpoint at which a point satisfies the bound.

interval property
interval: Interval

The bound as an interval, ignoring strictness.

effective_lower property
effective_lower: float

The lower endpoint after the strictness margin.

effective_upper property
effective_upper: float

The upper endpoint after the strictness margin.

violation
violation(value: float) -> float

The distance by which value lies outside the bound.

The distance is zero at a satisfied bound and at an excluded endpoint alike; contains decides satisfaction.

contains
contains(value: float) -> bool

Whether value satisfies the bound, honouring strict endpoints.

intersect
intersect(other: Bound) -> Bound

The tighter of two bounds on the same knob.

Raises:

Type Description
ValueError

if the bounds name different knobs, or their intersection is empty.

ConstraintOrigin

Bases: Enum

The origin of a coupled constraint.

See AdmissibleSet.apparatus_only.

APPARATUS class-attribute instance-attribute
APPARATUS = 'apparatus'

A limit of the apparatus, independent of the theory derived on it.

DERIVATION class-attribute instance-attribute
DERIVATION = 'derivation'

A requirement of one particular derivation, which may be dropped for a different theory.

InequalityConstraint dataclass

A coupled constraint between knobs, in the form expression >= 0.

Attributes:

Name Type Description
name str

a short name, used in reports.

expression Scalar

the constrained quantity, satisfied where it is non-negative.

description str

a one-line description.

origin ConstraintOrigin

whether the constraint is a limit of the apparatus, the default, or a requirement of one derivation.

slack
slack(assignment: Mapping[str, float]) -> float

The value of the expression; the constraint is satisfied where it is >= 0.

satisfied
satisfied(assignment: Mapping[str, float]) -> bool

Whether the constraint holds at assignment.

ConstraintViolation dataclass

A record of one admissibility constraint that a point fails.

Attributes:

Name Type Description
constraint str

a rendering of the violated constraint.

parameter str | None

the knob involved, if the constraint is a box bound.

value float

the offending value, or the value of the constraint expression.

amount float

the amount by which the constraint is violated.

AdmissibleSet dataclass

The set of knob settings to which a hardware model can be tuned.

Attributes:

Name Type Description
bounds tuple[Bound, ...]

the box bounds, at most one per knob.

constraints tuple[InequalityConstraint, ...]

the coupled constraints between knobs.

description str

a name for the operating envelope of the hardware model.

parameters property
parameters: tuple[str, ...]

The knobs constrained by the set, box-bounded knobs first, then those in constraints.

bound_for
bound_for(parameter: str) -> Bound | None

The box bound on parameter, if declared.

interval_environment
interval_environment() -> dict[str, Interval]

The box bounds as an interval environment, used in reachability analysis.

violations
violations(
    assignment: Mapping[str, float],
) -> list[ConstraintViolation]

Every constraint that assignment fails, the box bounds first.

admits
admits(assignment: Mapping[str, float]) -> bool

Whether assignment lies in the admissible set.

constraints_from
constraints_from(
    origin: ConstraintOrigin,
) -> tuple[InequalityConstraint, ...]

The coupled constraints of one origin.

apparatus_only
apparatus_only() -> AdmissibleSet

A copy carrying the box bounds and the apparatus constraints alone.

Constraints marked DERIVATION are dropped.

Returns:

Type Description
AdmissibleSet

The reach of the apparatus alone.

union
union(other: AdmissibleSet) -> AdmissibleSet

Conjoin two admissible sets: every constraint, and the tighter of the bounds per knob.

with_pinned
with_pinned(pinned: Mapping[str, float]) -> AdmissibleSet

A copy in which each named knob is pinned to a single value.

Binding dataclass

An assignment of values to parameter names.

Attributes:

Name Type Description
values Mapping[str, float]

the bound values by name; may be partial or empty.

get
get(
    name: str, default: float | None = None
) -> float | None

The value bound to name, or default.

with_values
with_values(**values: float) -> Binding

A copy with additional or overridden values.

merged
merged(other: Mapping[str, float]) -> Binding

A copy with the values of other merged in, overriding those of this binding.

as_dict
as_dict() -> dict[str, float]

A plain mutable copy of the assignment.

covers
covers(names: Iterable[str]) -> bool

Whether every name in names is bound.

missing
missing(names: Iterable[str]) -> tuple[str, ...]

The names in names that are not bound, sorted.

box

box(**bounds: tuple[float, float]) -> AdmissibleSet

Build an AdmissibleSet of plain box bounds.

Parameters:

Name Type Description Default
**bounds tuple[float, float]

a (low, high) pair per knob name.

{}

Returns:

Type Description
AdmissibleSet

The admissible set.

artifact

Artifacts: the nodes of the model graph.

An artifact carries an operator, a structural type that describes the physical and mathematical properties of a model, and a configurable parameter set. Artifact is the abstract artifact with a structural type, a parameter set and an ArtifactKind; HamiltonianModel and ProductFormulaModel are its subclasses. Constraint operators and the target sector are attributes of the model, not of its structural type.

AbstractionLevel

Bases: Enum

The layer of the model graph at which an artifact is located.

The values are the level numbers, so that levels are ordered.

APPLICATION class-attribute instance-attribute
APPLICATION = 1

The application layer: a physical theory stated in its own terms, independent of any hardware model.

INTERMEDIATE class-attribute instance-attribute
INTERMEDIATE = 2

An intermediate representation, shaped by the theory and by the hardware, usually still a Hamiltonian.

HARDWARE class-attribute instance-attribute
HARDWARE = 3

The hardware layer: the model a simulator realises natively, either an analogue Hamiltonian over the hardware knobs or a digital ordered product of k-local unitaries on a qubit register.

EXECUTABLE class-attribute instance-attribute
EXECUTABLE = 4

The executable layer: a routed and scheduled gate set, or a pulse schedule. This layer is out of scope.

in_scope property
in_scope: bool

Whether the package models the level.

label property
label: str

A short lower-case name for reports and table columns.

ArtifactKind

Bases: Enum

The kind of object an artifact of the model graph represents.

HAMILTONIAN class-attribute instance-attribute
HAMILTONIAN = 'Hamiltonian'

A symbolic sum of operator products under which a quantum system evolves.

PRODUCT_FORMULA class-attribute instance-attribute
PRODUCT_FORMULA = 'product formula'

An ordered product of k-local unitaries on an explicit register.

ArtifactKindError

Bases: TypeError

A transformation was applied to an artifact of the wrong kind.

Attributes:

Name Type Description
subject

the transformation or operation that was attempted.

expected

the artifact kind the subject requires.

found

the artifact kind that was supplied.

artifact

the name of the artifact in question.

ConstraintOperator dataclass

One declared constraint operator, for instance a Gauss operator G_l.

Attributes:

Name Type Description
name str

the family name, shared by every index ("G").

index int

the member of the family (l).

operator OperatorSum

the operator in symbolic form.

target_value float

the eigenvalue the physical sector requires of this member; boundary members of an open chain may differ from the bulk.

is_boundary bool

whether this member is located at an end of the chain.

label property
label: str

A short label, for instance "G_2".

Sector dataclass

A declared superselection sector: the target eigenvalues of a constraint family.

Attributes:

Name Type Description
name str

the name of the sector, used in reports.

family str

the constraint-operator family the sector refers to.

values Mapping[int, float]

the target eigenvalue per constraint index, boundary members included.

description str

a one-line description.

DroppedConstant dataclass

An additive constant discarded by a transformation on the way to a model.

Attributes:

Name Type Description
description str

the term that became the constant.

value Scalar

the constant, in the energy unit of the package.

LocalSubspace dataclass

A declared per-site occupation subspace, for instance the {0,1} / {0,2} subspace.

Attributes:

Name Type Description
name str

a name used in reports.

allowed_occupations Mapping[int, tuple[int, ...]]

the occupations permitted at each register position.

description str

a one-line description.

dimension property
dimension: int

The dimension of the subspace, the product of the per-site occupation counts.

required_cutoff
required_cutoff() -> int

The least bosonic occupation cutoff that represents the subspace.

Artifact dataclass

Bases: ABC

An artifact of the model graph: a typed, parametrised symbolic object.

An artifact carries a structural type that describes the physical and mathematical properties of a model and a configurable parameter set; the subclasses carry the operator.

Attributes:

Name Type Description
name str

the name of the artifact, used in every report and diagnostic.

structure StructureType

the structural type.

level AbstractionLevel

the abstraction level of the model.

parameters ParameterSet

the named parameters, with dimensions.

binding Binding

the values bound to parameters; the binding may be partial or empty.

admissible_set AdmissibleSet

the values the parameters may take; non-trivial only for a model of the hardware layer.

origin str

a one-line note on the derivation of the artifact, for reports.

kind abstractmethod property
kind: ArtifactKind

The kind of the artifact.

free_parameters property
free_parameters: tuple[str, ...]

The declared parameters that are not bound to a value.

is_fully_bound property
is_fully_bound: bool

Whether every declared parameter is bound to a value.

support_structure abstractmethod
support_structure() -> tuple[frozenset[int], ...]

The register positions each constituent acts on, in order.

For a Hamiltonian model, the support of each term; for a product formula, the support of each factor in schedule order.

bind
bind(**values: float) -> Artifact

A copy of the artifact with additional parameter values bound.

Raises:

Type Description
KeyError

if a name is not a declared parameter of the artifact.

bind_all
bind_all(values: Mapping[str, float]) -> Artifact

A copy of the artifact with the given parameter values bound.

Raises:

Type Description
KeyError

if a name is not a declared parameter of the artifact.

environment
environment() -> dict[str, float]

The bound values, as a plain mapping for the evaluation of expressions.

Raises:

Type Description
ValueError

if a declared parameter is unbound.

HamiltonianModel dataclass

Bases: Artifact

An artifact whose operator is a Hamiltonian, a symbolic sum of operator products.

Attributes:

Name Type Description
hamiltonian OperatorSum

the symbolic sum.

constraint_operators tuple[ConstraintOperator, ...]

the declared constraint operators, for instance Gauss operators.

sector Sector | None

the target superselection sector, if declared.

local_subspace LocalSubspace | None

the declared per-site occupation subspace, if any.

dropped_constants tuple[DroppedConstant, ...]

the additive constants discarded by the transformations that produced the model.

kind property
kind: ArtifactKind
max_locality property
max_locality: int

The largest number of register positions on which a term acts.

support_structure
support_structure() -> tuple[frozenset[int], ...]

The support of each term, in the order in which the terms are written.

constraints_named
constraints_named(
    family: str,
) -> tuple[ConstraintOperator, ...]

Every declared constraint operator of the family family.

validate
validate() -> None

Check that the operators of the Hamiltonian are legal on the algebras of their sites.

Raises:

Type Description
ValueError

for an illegal operator.

substituted
substituted() -> OperatorSum

The Hamiltonian with every bound parameter substituted.

Raises:

Type Description
ValueError

if a declared parameter is unbound.

total_dropped_constant
total_dropped_constant() -> float

The sum of the additive constants discarded on the way to the model.

Raises:

Type Description
KeyError

if a constant refers to a parameter of an unbound source model.

pretty
pretty() -> str

The Hamiltonian rendered with a per-site ladder glyph taken from the structure.

as_hamiltonian

as_hamiltonian(
    artifact: Artifact, subject: str = "this operation"
) -> HamiltonianModel

Narrow an artifact to a Hamiltonian model after checking its kind.

Parameters:

Name Type Description Default
artifact Artifact

the artifact to narrow.

required
subject str

the name reported in the diagnostic.

'this operation'

Returns:

Type Description
HamiltonianModel

The artifact, typed as a Hamiltonian model.

Raises:

Type Description
ArtifactKindError

if the artifact is not a Hamiltonian model.

relations

Parameter relations between the source and target parameters of a transformation.

A relation is a system of Equation objects over Scalar expressions together with optional Definition solved forms, each tagged with the equation it solves. The direction is chosen at classification time (ParameterRelation.classify). The composition of relations is the union of their equation sets, with intermediate parameters left free.

EMPTY_RELATION module-attribute

EMPTY_RELATION = ParameterRelation(name='empty')

A relation without equations: the parameters of the two sides are unrelated.

RelationKind

Bases: Enum

The case of a relation in one direction, out of four.

The classification is directional. A relation that is CLOSED_FORM in both directions is invertible, which ParameterRelation.is_invertible reports.

CLOSED_FORM class-attribute instance-attribute
CLOSED_FORM = 'CLOSED_FORM'

An explicit expression per unknown, evaluable directly.

UNDER_DETERMINED class-attribute instance-attribute
UNDER_DETERMINED = 'UNDER_DETERMINED'

Fewer equations than unknowns: a solution manifold, which requires a selection policy or an objective.

OVER_DETERMINED class-attribute instance-attribute
OVER_DETERMINED = 'OVER_DETERMINED'

More equations than unknowns: generically no exact solution exists, only a residual.

IMPLICIT class-attribute instance-attribute
IMPLICIT = 'IMPLICIT'

Determined, but without a closed form in this direction.

needs_solver property
needs_solver: bool

Whether obtaining a point requires a numerical or symbolic solve.

can_be_exact property
can_be_exact: bool

Whether an exact solution can exist; false only for OVER_DETERMINED.

Equation dataclass

One equation left = right over named parameters.

Attributes:

Name Type Description
name str

a stable identifier, referenced by Definition and by per-equation residuals.

left Scalar

the left-hand side.

right Scalar

the right-hand side.

description str

a one-line description.

residual property
residual: Scalar

The expression left - right, which a solve drives to zero.

parameters
parameters() -> frozenset[str]

Every parameter the equation mentions.

substituted
substituted(env: Mapping[str, ScalarLike]) -> Equation

A copy with the substitutions applied to both sides.

Definition dataclass

An explicit solved form of one equation for one parameter.

Attributes:

Name Type Description
parameter str

the parameter the expression defines.

expression Scalar

the expression, in terms of other parameters.

equation str

the name of the Equation the definition solves.

note str

a caveat, typically the branch of a multi-valued inverse that was taken.

inputs
inputs() -> frozenset[str]

The parameters the expression reads.

substituted
substituted(env: Mapping[str, ScalarLike]) -> Definition

A copy with the substitutions applied to the expression.

RelationClassification dataclass

The static classification of a relation in one requested direction.

Attributes:

Name Type Description
kind RelationKind

the case that applies, out of four.

unknowns tuple[str, ...]

the parameters solved for, sorted.

known tuple[str, ...]

the parameters treated as given, sorted.

equations tuple[str, ...]

the names of the equations involved, in order.

elimination tuple[Definition, ...] | None

the solved forms in evaluation order; present exactly when kind is CLOSED_FORM.

note str

a one-line explanation of the classification, for reports.

degrees_of_freedom property
degrees_of_freedom: int

The number of unknowns minus the number of equations.

A positive value is the rank of the solution manifold.

ParameterRelation dataclass

A system of equations relating the parameters of a transformation.

Attributes:

Name Type Description
name str

a name used in reports.

equations tuple[Equation, ...]

the equations, with distinct names.

definitions tuple[Definition, ...]

the solved forms; each refers to an equation of the relation. A relation without definitions is implicit in every direction.

parameters
parameters() -> frozenset[str]

Every parameter mentioned by any equation.

equation_named
equation_named(name: str) -> Equation

The equation of the given name.

Raises:

Type Description
KeyError

if the relation has no equation of that name.

definitions_of
definitions_of(parameter: str) -> tuple[Definition, ...]

Every solved form that defines parameter.

compose
compose(
    other: ParameterRelation, name: str = ""
) -> ParameterRelation

Conjoin two relations by uniting their equations and definitions.

Equation names must be distinct; see prefixed.

Parameters:

Name Type Description Default
other ParameterRelation

the relation to conjoin with.

required
name str

a name for the composite; by default the two names joined by &.

''

Returns:

Type Description
ParameterRelation

The composite relation.

prefixed
prefixed(prefix: str) -> ParameterRelation

A copy with every equation name prefixed; parameter names are unchanged.

substituted
substituted(
    env: Mapping[str, ScalarLike],
) -> ParameterRelation

A copy with the substitutions applied throughout.

with_equations
with_equations(
    extra: Sequence[Equation],
    extra_definitions: Sequence[Definition] = (),
    name: str = "",
) -> ParameterRelation

A copy with additional equations, for instance parameter pins or a selection policy.

classify
classify(
    known: Set[str], unknowns: Set[str] | None = None
) -> RelationClassification

Classify the relation in the direction of solving for the unknowns given known.

Parameters:

Name Type Description Default
known Set[str]

the parameters treated as given.

required
unknowns Set[str] | None

the parameters to solve for; by default every parameter the equations mention that is not in known.

None

Returns:

Type Description
RelationClassification

The classification, including an elimination order if a closed form exists.

is_invertible
is_invertible(side_a: Set[str], side_b: Set[str]) -> bool

Whether the relation is a closed form in both directions between the two sides.

evaluate_closed_form
evaluate_closed_form(
    elimination: Sequence[Definition],
    known: Mapping[str, float],
) -> dict[str, float]

Evaluate an elimination chain and return the full parameter assignment.

Parameters:

Name Type Description Default
elimination Sequence[Definition]

the chain from classify.

required
known Mapping[str, float]

the values of the known parameters.

required

Returns:

Type Description
dict[str, float]

known extended by a value for every defined parameter.

residuals
residuals(
    assignment: Mapping[str, float],
) -> dict[str, float]

The residual of every equation whose parameters are all assigned.

equation

equation(
    name: str,
    left: ScalarLike,
    right: ScalarLike,
    description: str = "",
) -> Equation

Convenience constructor for Equation.

residuals_of

residuals_of(
    equations: Iterable[Equation],
    assignment: Mapping[str, float],
) -> dict[str, float]

The residual of each equation whose parameters assignment covers, by name.

Equations that mention an unassigned parameter are omitted.

identity_relation

identity_relation(
    pairs: Iterable[tuple[str, str]], name: str = ""
) -> ParameterRelation

A relation that carries parameters over unchanged, with one equation per pair.

Each pair (source, target) becomes an equation target = source with solved forms in both directions; the relation is therefore invertible.

Parameters:

Name Type Description Default
pairs Iterable[tuple[str, str]]

the (source, target) pairs of parameter names.

required
name str

a name used in reports.

''

Returns:

Type Description
ParameterRelation

The relation.

validity

Validity conditions: the declared regime within which an approximate transformation holds.

A regime condition a << b is evaluated as |a / b| <= threshold with a default threshold of 0.1; a domain condition x != 0 is evaluated as |x| / scale > tolerance with a default tolerance of 1e-3. Margins are reported in decades of slack, the log10 of the ratio to the boundary: zero at the boundary, positive inside the regime. The outcome of a condition is valid, out of regime, domain error, or undetermined if a parameter was unbound.

Severity

Bases: Enum

Whether the failure of a condition is a mathematical or a physical failure.

DOMAIN class-attribute instance-attribute
DOMAIN = 'domain'

The parameter map is undefined (a pole). The condition cannot be overridden.

REGIME class-attribute instance-attribute
REGIME = 'regime'

The parameter map is defined, but the assumptions of the derivation are violated. The condition can be overridden on explicit request.

ConditionStatus

Bases: Enum

The outcome of the evaluation of one condition.

UNDETERMINED class-attribute instance-attribute
UNDETERMINED = 'undetermined'

A parameter read by the condition was unbound.

is_failure property
is_failure: bool

Whether the outcome means that the transformation is not valid at the point.

ConditionOutcome dataclass

The evaluation of one validity condition at one parameter point.

Attributes:

Name Type Description
name str

the name of the condition.

quantity str

the compared quantity, rendered for a report, for instance "J/delta".

value float

the value of that quantity.

requirement str

the requirement, rendered, for instance "<< 1 (ratio <= 0.1)".

margin float

the decades of slack; positive inside the regime, negative outside.

status ConditionStatus

the outcome.

severity Severity

whether a failure of the condition is a domain or a regime failure.

rationale str

the reason for the condition, for the report.

passed property
passed: bool

Whether the condition holds.

ValidityCondition

Bases: ABC

A predicate over parameter values, with a margin and a severity.

Attributes:

Name Type Description
name str

the name of the condition.

severity Severity

whether a failure is a domain or a regime failure.

rationale str

the reason for the condition, for reports.

evaluate abstractmethod
evaluate(env: Mapping[str, float]) -> ConditionOutcome

Evaluate the condition at a parameter point.

Parameters:

Name Type Description Default
env Mapping[str, float]

the parameter values.

required

Returns:

Type Description
ConditionOutcome

The outcome; a missing parameter gives

ConditionOutcome
parameters abstractmethod
parameters() -> frozenset[str]

The names of the parameters the condition reads.

substituted abstractmethod
substituted(
    env: Mapping[str, ScalarLike],
) -> ValidityCondition

A copy with the parameter substitutions applied to its expressions.

margin_expression
margin_expression() -> Scalar | None

A smooth expression with the sign and zero set of the margin; None if none exists.

MuchLessThan dataclass

Bases: ValidityCondition

The regime condition |numerator / denominator| <= threshold, that is a << b.

Attributes:

Name Type Description
numerator Scalar

the small quantity.

denominator Scalar

the large quantity.

threshold float

the ratio at which the condition lies exactly on the boundary.

name str

the name of the condition.

quantity_label str

the rendering of the ratio, for instance "J/delta".

rationale str

the reason for the condition.

parameters
parameters() -> frozenset[str]

The parameters of both expressions.

evaluate
evaluate(env: Mapping[str, float]) -> ConditionOutcome

Evaluate the ratio and report its margin in decades.

substituted
substituted(env: Mapping[str, ScalarLike]) -> MuchLessThan

A copy with the substitutions applied to numerator and denominator.

margin_expression
margin_expression() -> Scalar

The expression threshold * |denominator| - |numerator|, positive inside the regime.

The expression is a linear surrogate with the same sign and zero set as the logarithmic margin.

NonZero dataclass

Bases: ValidityCondition

The domain condition |expression| / scale > tolerance, that is, the absence of a pole.

Attributes:

Name Type Description
expression Scalar

the quantity that must not vanish.

scale Scalar

the scale against which the separation is measured.

tolerance float

the dimensionless separation required.

name str

the name of the condition.

quantity_label str

the rendering of the ratio.

rationale str

the reason for the condition.

parameters
parameters() -> frozenset[str]

The parameters of the expression and of the scale.

evaluate
evaluate(env: Mapping[str, float]) -> ConditionOutcome

Evaluate the separation from the pole.

substituted
substituted(env: Mapping[str, ScalarLike]) -> NonZero

A copy with the substitutions applied to expression and scale.

margin_expression
margin_expression() -> Scalar

expression**2 - (tolerance * scale)**2, which is positive away from the pole.

ValidityReport dataclass

The evaluation of a conjunction of conditions at one parameter point.

Attributes:

Name Type Description
outcomes tuple[ConditionOutcome, ...]

one outcome per condition, in declaration order.

point Mapping[str, float]

the parameter point evaluated, for the reproducibility of the report.

is_valid property
is_valid: bool

Whether every condition holds.

has_domain_error property
has_domain_error: bool

Whether a condition failed as a domain error, that is, at a pole.

domain_errors property
domain_errors: tuple[ConditionOutcome, ...]

The outcomes that failed as domain errors.

regime_violations property
regime_violations: tuple[ConditionOutcome, ...]

The outcomes that failed as regime violations.

failures property
failures: tuple[ConditionOutcome, ...]

Every failing outcome, domain errors first.

undetermined property
undetermined: tuple[ConditionOutcome, ...]

The outcomes that could not be decided because a parameter value was missing.

weakest_margin property
weakest_margin: float

The least regime margin, in decades; nan if no condition was decidable.

weakest
weakest(
    severity: Severity | None = Severity.REGIME,
) -> ConditionOutcome | None

The outcome with the least margin, optionally restricted to one severity.

margins
margins() -> dict[str, float]

The margin of each condition, by name.

Conjunction dataclass

A conjunction of validity conditions.

Attributes:

Name Type Description
conditions tuple[ValidityCondition, ...]

the conditions, in declaration order.

parameters
parameters() -> frozenset[str]

Every parameter read by any condition.

report
report(env: Mapping[str, float]) -> ValidityReport

Evaluate every condition at env.

is_valid
is_valid(env: Mapping[str, float]) -> bool

Whether every condition holds at env.

and_also
and_also(other: Conjunction) -> Conjunction

The conjunction with another conjunction, preserving order and omitting duplicates.

substituted
substituted(env: Mapping[str, ScalarLike]) -> Conjunction

A copy with the substitutions applied to every condition.

by_severity
by_severity(severity: Severity) -> Conjunction

The sub-conjunction of conditions of one severity.

conjunction

conjunction(
    conditions: Sequence[ValidityCondition],
) -> Conjunction

Build a Conjunction from a sequence of conditions.

much_less_than

much_less_than(
    numerator: ScalarLike,
    denominator: ScalarLike,
    *,
    name: str,
    label: str = "",
    threshold: float = DEFAULT_MUCH_LESS_THAN_THRESHOLD,
    rationale: str = "",
) -> MuchLessThan

Convenience constructor for MuchLessThan.

non_zero

non_zero(
    expression: ScalarLike,
    scale: ScalarLike,
    *,
    name: str,
    label: str = "",
    tolerance: float = DEFAULT_NONZERO_TOLERANCE,
    rationale: str = "",
) -> NonZero

Convenience constructor for NonZero.

transform

Transformations between abstraction levels, and their attributes.

A transformation is a typed edge between artifacts. Like an artifact, a transformation is a declaration before it is a computation. A Transformation declares the source it requires (source_pattern, source_kind), whether the operator form of the target is unitarily equivalent to that of the source (exactness) and, if it is approximate, the ApproximationKind: valid within a declared regime of the parameters (regime-limited) or with an error controlled by a resource parameter (resource-controlled). The realisability of the coefficients is a matter of the parameter relation and the admissible set.

ArtifactKindError

Bases: TypeError

A transformation was applied to an artifact of the wrong kind.

Attributes:

Name Type Description
subject

the transformation or operation that was attempted.

expected

the artifact kind the subject requires.

found

the artifact kind that was supplied.

artifact

the name of the artifact in question.

ExactnessError

Bases: ValueError

The declared target of an EXACT transformation is not the symbolic image of its source.

Raised when the source Hamiltonian, rewritten in the operators of the target by Transformation.image, differs from the Hamiltonian of the target model by more than an additive constant.

Attributes:

Name Type Description
transformation

the name of the transformation.

defect

the surviving terms of target - image, in normal form.

Exactness

Bases: Enum

Whether the operator form of the target is unitarily equivalent to that of the source.

EXACT may hold only after restriction to a stated subspace and up to a stated additive constant. It makes no statement about the realisability of the coefficients.

ApproximationKind

Bases: Enum

The kind of approximation of an approximate transformation.

REGIME_LIMITED class-attribute instance-attribute
REGIME_LIMITED = 'regime-limited'

Valid only within a declared regime of the parameters; the error cannot be driven to zero. Reported as the margins of the regime conditions.

RESOURCE_CONTROLLED class-attribute instance-attribute
RESOURCE_CONTROLLED = 'resource-controlled'

The error shrinks to zero as a resource parameter grows, at a cost. Reported as the error against its cost.

Approximation dataclass

The declaration that accompanies an APPROXIMATE transformation.

Attributes:

Name Type Description
kind ApproximationKind

regime-limited or resource-controlled.

leading_error_order str

the leading surviving correction, where known, for instance "fourth order in J; relative error ~ (J/U)**2".

resource_parameters tuple[str, ...]

the names of the resource parameters; non-empty exactly for a resource-controlled approximation.

note str

a further caveat to be printed in a report.

Transformation dataclass

Bases: ABC

A typed edge from one artifact to another.

Like an artifact, a transformation is a declaration before it is a computation.

Attributes:

Name Type Description
name str

a short identifier, for instance "spin-1/2 quantum-link truncation".

source_pattern StructurePattern

the structural type the transformation requires of its source.

target_pattern StructurePattern

the structural type the transformation declares for its target; used to type-check a composition.

source_kind ArtifactKind

the artifact kind of the source.

target_kind ArtifactKind

the artifact kind of the target.

exactness Exactness

whether the operator form of the target is unitarily equivalent to that of the source.

approximation Approximation | None

the approximation declaration, required exactly when exactness is APPROXIMATE.

relation ParameterRelation

the parameter relation.

validity Conjunction

the validity conditions, required for an approximate transformation.

source_parameters tuple[str, ...]

the source-side parameter names the relation involves.

target_parameters tuple[str, ...]

the target-side parameter names the relation involves.

source_level AbstractionLevel | None

the abstraction level of the source; None admits any level.

target_level AbstractionLevel | None

the abstraction level of the target.

description str

a longer description, printed in reports and pipeline tables.

dropped_constant str

a description of the additive constant the transformation discards, or empty; its value is computed by dropped_constant_at.

is_exact property
is_exact: bool

Whether the operator forms of source and target are unitarily equivalent.

approximation_kind property
approximation_kind: ApproximationKind | None

The kind of approximation, or None for an exact transformation.

forward_relation_kind property
forward_relation_kind: RelationKind

The case of the relation in the forward direction of the derivation.

The source parameters are given.

inverse_relation_kind property
inverse_relation_kind: RelationKind

The case of the relation in the inverse direction, the solve for the knob settings.

The target parameters are given.

levels property
levels: tuple[AbstractionLevel, AbstractionLevel] | None

The levels the transformation spans, or None if they are not declared.

check
check(artifact: Artifact) -> None

Type-check artifact against the source kind and pattern of the transformation.

Raises:

Type Description
ArtifactKindError

if the artifact is of the wrong kind.

StructureTypeError

if the structure of the artifact does not match; every mismatch is named.

accepts
accepts(artifact: Artifact) -> bool

Whether check passes for artifact.

target_structure
target_structure(source: StructureType) -> StructureType

The structural type produced from source; unchanged by default.

target_sites
target_sites(source_sites: int) -> int

The chain length of the target given that of the source; the same length by default.

Parameters:

Name Type Description Default
source_sites int

the chain length of the source artifact.

required

Returns:

Type Description
int

The chain length of the target artifact.

Raises:

Type Description
ValueError

if no target length corresponds to source_sites.

apply
apply(artifact: Artifact) -> Artifact

Type-check artifact and then transform it.

Raises:

Type Description
ArtifactKindError

via check.

StructureTypeError

via check.

dropped_constant_at
dropped_constant_at(
    source: Artifact,
) -> DroppedConstant | None

The additive constant discarded from source; None by default.

image
image(source: HamiltonianModel) -> OperatorSum | None

The source Hamiltonian rewritten in the target operators, in the source parameters.

For an EXACT transformation that implements this method, the claim is checked on every application: the target model of the library must equal this image up to an additive constant (exactness_defect). The default returns None: no symbolic image is available and nothing is checked.

forward_definitions
forward_definitions() -> dict[str, Scalar]

Each target parameter as an expression in the source parameters, where solved.

exactness_defect
exactness_defect(
    source: HamiltonianModel, target: HamiltonianModel
) -> OperatorSum | None

target - image(source) in normal form, or None if no image is available.

The Hamiltonian of the target is first expressed in the source parameters through the forward solved forms of the relation, so that both sides read the same symbols. An empty result means that the transformation is exact as declared; a result with an identity term only means exact up to that additive constant; any other result is a defect.

relation_kind
relation_kind(known: frozenset[str]) -> RelationKind

The case of the relation when solving for every parameter known does not fix.

classify_relation
classify_relation(
    known: frozenset[str],
) -> RelationClassification

The full static classification of the relation in the requested direction.

validity_report
validity_report(env: dict[str, float]) -> ValidityReport

Evaluate the validity conditions at a parameter point.

carry_parameters
carry_parameters(
    source: Artifact, target: Artifact
) -> dict[str, float]

Propagate the bound values of the source through the solved forms of the relation.

Only the parameters of the target are set, and only where a solved form reads values the source already binds.

Parameters:

Name Type Description Default
source Artifact

the artifact being transformed.

required
target Artifact

the artifact being produced.

required

Returns:

Type Description
dict[str, float]

The values to bind on the target.

parameter_set
parameter_set() -> ParameterSet

The source and target parameters, as a set of energy-dimensioned parameters.

pipeline

Pipelines and the model graph.

Transformations compose into a pipeline; a composed pipeline is itself a transformation. A Pipeline is a composite Transformation: the junctions are type-checked at composition time, the pipeline is EXACT if and only if every constituent transformation is exact, its validity conditions are the conjunction of those of its constituents, and its parameter relation is the union of those of its constituents with intermediate parameters left free. A ModelGraph is the directed acyclic graph of artifacts and transformations from which pipelines are enumerated. An ErrorReport reports the structural approximations, the residual of a solve, the margins of the regime conditions and the resource cost on separate axes.

CompositionError

Bases: TypeError

Two transformations were composed whose types do not meet.

Attributes:

Name Type Description
first

the name of the producing transformation.

second

the name of the consuming transformation.

gaps

the structural mismatches.

kind_problem

a description of a mismatch of artifact kinds, or empty.

StructuralApproximation dataclass

One approximate transformation, as it appears in an error report.

Attributes:

Name Type Description
step str

the name of the transformation.

kind ApproximationKind

regime-limited or resource-controlled.

leading_error_order str

the leading surviving correction, where known.

note str

a further caveat.

ResourceCost dataclass

The error-against-cost entry of a resource-controlled transformation.

Attributes:

Name Type Description
step str

the name of the transformation.

settings Mapping[str, float]

the resource parameters and their values, for instance {"n": 32, "order": 2}.

error_bound float

the a-priori error bound at those settings.

cost Mapping[str, int]

hardware-agnostic resource counts, for instance the number of factors and the depth in layers.

ErrorReport dataclass

The independent error axes of a pipeline; the axes are not summable.

Attributes:

Name Type Description
structural tuple[StructuralApproximation, ...]

the approximate transformations and their kinds.

regime ValidityReport

the validity report at the operating point.

solver_residuals Mapping[str, float]

the per-equation residual left by the parameter solve; empty when the solve was exact or no solve was needed.

resource_costs tuple[ResourceCost, ...]

the error-against-cost entries of the resource-controlled transformations.

approximation_kinds property
approximation_kinds: frozenset[ApproximationKind]

The set of approximation kinds along the pipeline.

max_solver_residual property
max_solver_residual: float

The largest absolute solver residual, or 0.0 if there is none.

Pipeline dataclass

Bases: Transformation

A composite transformation: an ordered chain of transformations that type-check pairwise.

A composed pipeline is itself a transformation. It is exact only if every constituent transformation is exact.

Attributes:

Name Type Description
steps tuple[Transformation, ...]

the constituent transformations, source-most first.

approximation_kinds property
approximation_kinds: frozenset[ApproximationKind]

The set of approximation kinds along the pipeline.

approximate_steps property
approximate_steps: tuple[Transformation, ...]

The constituent transformations that are APPROXIMATE, in order.

of classmethod
of(
    steps: Sequence[Transformation], name: str = ""
) -> Pipeline

Compose steps into a pipeline, type-checking each junction.

Parameters:

Name Type Description Default
steps Sequence[Transformation]

the transformations, source-most first.

required
name str

a name for the composite; by default the names of the constituents joined.

''

Returns:

Type Description
Pipeline

The composite transformation.

Raises:

Type Description
ValueError

if steps is empty.

CompositionError

if the types of two adjacent transformations do not meet.

then
then(other: Transformation) -> Pipeline

Extend the pipeline by one further transformation.

Raises:

Type Description
CompositionError

if the types do not meet.

target_structure
target_structure(source: StructureType) -> StructureType

Propagate a structural type through every constituent transformation.

structural_approximations
structural_approximations() -> tuple[
    StructuralApproximation, ...
]

The approximate transformations, as entries of an error report.

dropped_constants
dropped_constants() -> tuple[tuple[str, str], ...]

The constituents discarding an additive constant, as (step, description) pairs.

error_report
error_report(
    point: Mapping[str, float],
    solver_residuals: Mapping[str, float] | None = None,
    resource_costs: Sequence[ResourceCost] = (),
) -> ErrorReport

Assemble the error report at an operating point.

Parameters:

Name Type Description Default
point Mapping[str, float]

the parameter values.

required
solver_residuals Mapping[str, float] | None

the per-equation residuals left by a parameter solve, if any.

None
resource_costs Sequence[ResourceCost]

the error-against-cost entries of the resource-controlled transformations.

()

Returns:

Type Description
ErrorReport

The report.

classify_relation
classify_relation(
    known: frozenset[str],
) -> RelationClassification

Classify the united relation of the whole pipeline in one direction.

sub_pipeline
sub_pipeline(
    start: int = 0, stop: int | None = None
) -> Pipeline

The pipeline formed by a contiguous slice of the constituent transformations.

with_step_replaced
with_step_replaced(
    index: int, step: Transformation
) -> Pipeline

A copy with one constituent replaced; the junctions are type-checked again.

Raises:

Type Description
CompositionError

if the types of the new transformation do not meet those of its neighbours.

summary_lines
summary_lines() -> list[str]

One line per constituent transformation, for printing a pipeline in a report.

Edge dataclass

One directed edge of the model graph.

Attributes:

Name Type Description
source str

the name of the source artifact.

target str

the name of the target artifact.

transformation Transformation

the transformation the edge carries.

BranchSummary dataclass

One row of the side-by-side comparison of the branches of a model graph.

Attributes:

Name Type Description
target str

the name of the terminal artifact.

pipeline Pipeline

the pipeline that reaches it.

artifact_kind ArtifactKind

the kind of artifact the branch produces.

exactness Exactness

the exactness of the composite.

approximation_kinds frozenset[ApproximationKind]

the set of approximation kinds along the branch.

step_names tuple[str, ...]

the names of the constituent transformations, in order.

ModelGraph

The model graph: a directed acyclic graph of artifacts, keyed by name, and transformations.

The graph is built incrementally with add_node and add_edge; adding an edge type-checks the transformation against both of its endpoints. An artifact may have several outgoing and several incoming edges.

Attributes:

Name Type Description
name

the name of the graph, used in diagnostics.

nodes property
nodes: tuple[str, ...]

The name of every registered artifact, in registration order.

edges property
edges: tuple[Edge, ...]

Every registered edge, in registration order.

add_node
add_node(artifact: Artifact) -> Artifact

Register an artifact in the graph.

Raises:

Type Description
ValueError

if an artifact of that name is already registered.

add_edge
add_edge(
    source: str, target: str, transformation: Transformation
) -> Edge

Register a transformation as an edge, type-checking both endpoints.

Raises:

Type Description
KeyError

if an endpoint is not a registered artifact.

ArtifactKindError

if the artifact kinds of the transformation do not match the endpoints.

StructureTypeError

if the structure of an endpoint does not match.

node
node(name: str) -> Artifact

The artifact of the given name.

Raises:

Type Description
KeyError

if no artifact of that name is registered.

outgoing
outgoing(node: str) -> tuple[Edge, ...]

The edges leaving the artifact node.

incoming
incoming(node: str) -> tuple[Edge, ...]

The edges entering the artifact node.

reachable
reachable(source: str) -> tuple[str, ...]

Every artifact reachable from source, excluding source itself, sorted by name.

terminal_targets
terminal_targets(source: str) -> tuple[str, ...]

The reachable artifacts without outgoing edges: the end points of the pipelines.

paths
paths(
    source: str, target: str
) -> tuple[tuple[Edge, ...], ...]

Every simple path from source to target, as a sequence of edges.

pipelines
pipelines(source: str, target: str) -> tuple[Pipeline, ...]

Every distinct pipeline from source to target.

branches
branches(source: str) -> tuple[BranchSummary, ...]

Side-by-side summaries of every pipeline to every terminal artifact.

Resource costs are not included; see Pipeline.error_report.

with_binding
with_binding(node: str, **values: float) -> Artifact

Bind parameters on a registered artifact and return the bound copy.

replace_node
replace_node(artifact: Artifact) -> Artifact

Replace a registered artifact of the same name, keeping the edges.

Raises:

Type Description
KeyError

if no artifact of that name is registered.