Engines

Engines are the computational backends that perform low-level state operations. Each kind has an abstract interface, so a custom engine can be swapped in.

Two Engine Types:

  1. Stabilizer Engines: Handle Clifford gates efficiently

  2. Tensor Network Engines: Manage non-Clifford effects via MPO

Stabilizer Engine

Stabilizers engine backed by stim.

class mpstab.engines.stabilizers.stim.StimEngine[source]

Bases: StabilizersEngine

Clifford backpropagation of Pauli observables, powered by stim.

backpropagate(observable: str, clifford_circuit: Circuit)[source]

Evolve observable back through clifford_circuit (Heisenberg picture).

Returns:

(pauli_string, sign) for U^dag . O . U, with U the circuit.

backpropagate_at(observables: Sequence[str], breakpoints: Sequence[int], clifford_circuit: Circuit) → list[source]

Backpropagate each observable through its own prefix of clifford_circuit with one stim tableau pass.

The circuit is simulated once, a segment at a time in breakpoint order, and each observable is conjugated by the inverse tableau of its prefix, so the cost is one pass over the circuit plus one conjugation per observable.

Raises:

ValueError – on a breakpoint outside [0, len(clifford_circuit.queue)].

backpropagate_many(observables, clifford_circuit: Circuit) → list[source]

backpropagate() every observable through the same circuit.

The circuit’s U^dag tableau is built once and cached, so a whole Hamiltonian costs one stim simulation plus one tableau lookup per term, and repeated calls on an unchanged circuit skip the simulation too.

instructions(circuit: Circuit) → list[source]

One stim instruction line per gate of circuit, None for gates that leave the Pauli frame untouched.

stim parses a whole program from text far faster than it appends instructions one call at a time, so circuits are assembled as text.

Raises:

ValueError – on a non-Clifford rotation angle, or a gate with no stim equivalent. Unsupported gates fail loudly rather than being dropped, which would silently give a wrong Pauli frame.

mpstab.engines.stabilizers.stim.circuit_instructions(circuit: Circuit) → list[source]

One stim instruction line per gate of circuit, None for no-ops.

mpstab.engines.stabilizers.stim.gate_instruction(gate)[source]

The stim instruction line for one Clifford qibo gate, or None if it is a no-op on the Pauli frame.

Raises:

ValueError – on a non-Clifford rotation angle, or a gate with no stim equivalent.

Stim Engine: Clifford backpropagation of Pauli observables with the C++ Stim simulator.

Tensor Network Engine

Tensor-network engine backed by quimb.

mpstab.engines.tensor_networks.quimb.GATE_MAP = {'ccx': 'CCX', 'ccy': 'CCY', 'ccz': 'CCZ', 'cnot': 'CNOT', 'cswap': 'CSWAP', 'cx': 'CX', 'cy': 'CY', 'cz': 'CZ', 'fredkin': 'FREDKIN', 'fsim': 'fsim', 'h': 'H', 'iswap': 'ISWAP', 'measure': 'measure', 'rx': 'RX', 'rxx': 'RXX', 'ry': 'RY', 'ryy': 'RYY', 'rz': 'RZ', 'rzz': 'RZZ', 's': 'S', 'swap': 'SWAP', 't': 'T', 'toffoli': 'TOFFOLI', 'u3': 'U3', 'x': 'X', 'y': 'Y', 'z': 'Z'}

qibo gate names mapped to their quimb equivalents.

class mpstab.engines.tensor_networks.quimb.QuimbEngine(backend: str = 'numpy', svd_cutoff: float | None = None)[source]

Bases: TensorNetworkEngine

MPS evolution and MPO expectation values via quimb.

Besides evolving states, it conjugates operators, which HQSMPO’s head/tail split needs, and its MPS feeds quimb’s DMRG.

apply_pauli_sum(state_circuit: MatrixProductState, paulis, coefficients, max_bond_dimension: int | None) → MatrixProductState[source]

A new state sum_t c_t P_t |state>.

The terms are stacked into block-diagonal MPOs of _PAULI_SUM_CHUNK terms each, compressed exactly and summed (a sum of local strings keeps a small bond), and the result is applied to the state and compressed to max_bond_dimension.

apply_rotation(state_circuit: MatrixProductState, rotation, max_bond_dimension: int | None)[source]

Apply a rotation_operator() result to the state in place, then compress.

A (generator, angle) tuple only touches the sites between the first and last non-identity letter of its generator, recompressing that window alone; an MPO goes through quimb’s gate_with_mpo, which recompresses the whole chain. Both truncate with the same rule.

bond_dimension(state_circuit: MatrixProductState) → int[source]

The largest bond dimension of the MPS.

build_circuit_mps(n: int, initial_state_circuit: Any, max_bond_dimension: int | None = None)[source]

Build the MPS by running initial_state_circuit through quimb.

circuit_truncation_fidelity(nqubits: int, circuit, max_bond_dimension: int | None) → float[source]

quimb’s CircuitMPS.fidelity_estimate after running circuit.

conjugate_operator(operator: MatrixProductOperator, generator: str, angle: float, max_bond_dimension: int)[source]

Heisenberg-conjugate operator by R = exp(-i angle/2 generator), returning R^dag . operator . R.

Folds the rotation into the observable so that <R psi| O |R psi> = <psi| R^dag O R |psi>. The generators are Pauli strings, so R(angle)^dag == R(-angle), and each MPO-MPO product is compressed to max_bond_dimension.

Even at max_bond_dimension=None quimb applies its default SVD cutoff, and the exact operator rank of a scrambled observable grows exponentially, so folding a long tail accrues truncation error. Keeping this exact is only affordable for modest tail lengths; see tail_truncation() to quantify it.

conjugate_operator_many(operator: MatrixProductOperator, rotations, max_bond_dimension: int | None)[source]

Conjugate operator by each (generator, angle) rotation in turn, the first one innermost, as repeated conjugate_operator() calls.

On the numpy backend the MPO is unpacked once into canonical site arrays, and each conjugation touches only its generator’s window (operator_conjugation()), with the same truncation rule as quimb’s compress, so a whole tail costs about as much as evolving a state through it. Other backends go through quimb.

copy_state(state_circuit: MatrixProductState)[source]

An independent copy of the state.

On the numpy backend the copy has its own tensors but shares their arrays: the windowed kernels, like quimb’s own operations, replace a tensor’s array rather than write into it, so neither state can change the other. The cached canonical form is carried over, so the copy needs no re-canonicalization. Other backends get a deep copy.

expval(state_circuit: MatrixProductState, operator: MatrixProductOperator)[source]

Expectation value of operator on state_circuit, normalised.

Truncation costs the state its unit norm, so the contraction is divided by it.

A Pauli string from pauli_mpo() is evaluated directly on the state’s canonical form, over the sites between the string’s support and the orthogonality center only. This may move the center, a pure gauge change that leaves the state itself untouched.

Any other operator MPO has upper (output) index k{i} and lower (input) index b{i}. The ket must feed the operator’s input, so it is reindexed k -> b while the conjugated bra keeps k{i} to meet the output. Reindexing the bra instead would evaluate <psi|O^T|psi>, which differs for any operator with an odd number of Y’s.

minimize_energy(operator: MatrixProductOperator, initial_state: MatrixProductState, bond_dims: list, cutoff: float, tol: float, max_sweeps: int, verbosity: int) → dict[source]

Two-site DMRG with quimb’s DMRG2, on a copy of initial_state.

operator_site_arrays(operator: MatrixProductOperator) → list[source]

The MPO’s site tensors as numpy arrays ordered (left, right, k, b), k the upper (output) and b the lower (input) index.

pauli_expvals(state_circuit: MatrixProductState, paulis)[source]

Normalised expectation values of many Pauli strings on one state.

The strings are visited in order of their first non-identity site, with the orthogonality center moved to each in turn, so a whole Hamiltonian costs one sweep of the chain plus each term’s own support rather than a full contraction per term.

Returns:

a real array on the numpy backend, a list of backend scalars otherwise.

Return type:

One value per string, in the order given

pauli_mpo(pauli_string: str | object)[source]

Build the MPO for a Pauli string.

pauli_rot(state_circuit: MatrixProductState, generator: str, angle: float, max_bond_dimension: int)[source]

Apply exp(-i angle/2 generator) to the state in place, then compress.

pauli_sum_mpo(terms: dict) → MatrixProductOperator[source]

The MPO of sum_P c_P P.

Raises:

ValueError – if terms is empty.

pauli_transitions(bra_state: MatrixProductState, ket_state: MatrixProductState, paulis, normalize: bool = True)[source]

Transition amplitudes <bra|P|ket> of many Pauli strings between two states, with normalize divided by the norms of both states.

Returns:

A complex array on the numpy backend, a list of backend scalars otherwise.

rotation_operator(generator: str, angle: float)[source]

exp(-i angle/2 generator) in a form apply_rotation() accepts: a (generator, angle) tuple on the numpy backend, applied by the windowed kernel, and the backend MPO otherwise.

site_arrays(state_circuit: MatrixProductState)[source]

The state as the form _mps_kernels works on: a list of (left, phys, right) arrays in mixed canonical form, and the orthogonality center. numpy backend only.

The arrays are read-only and shared with the state; the kernels never write into an array, they replace it in the list.

squared_norm(state_circuit: MatrixProductState)[source]

<psi|psi> of the MPS. On the numpy backend it is read off the orthogonality center of the cached canonical form, no full contraction needed; other backends return quimb’s backend scalar, so it stays differentiable.

On the numpy backend, when the state has no valid cached canonical form (a fresh state, or one changed outside the engine), it is canonicalized in place first: its tensors are transposed and gauge-transformed, the state itself is unchanged.

static state_from_arrays(arrays) → MatrixProductState[source]

An MPS from (left, phys, right) site arrays, two sites or more.

property truncation_cutoff: float

The relative singular-value cutoff rotations are compressed with.

Quimb Engine: MPS evolution, MPO expectation values and operator conjugation with quimb, on the numpy, jax or torch backend.

Native Engines

Pure-Python implementations of the two interfaces, kept as readable examples of what an engine does rather than for performance. They give the same expectation values as stim and quimb, but are slower and cover less: the native tensor-network engine has no operator-side conjugation (so no head/tail split in HQSMPO) and no DMRG.

Pure-Python stabilizers engine.

mpstab.engines.stabilizers.native.engine.GATE_TABLEAUS = {'cx': 'CNOT', 'cz': 'CZ', 'gpi2': 'GPI2', 'h': 'H', 'rx': 'RX', 'ry': 'RY', 'rz': 'RZ', 's': 'S', 'sdg': 'Sdg', 'swap': 'SWAP', 'x': 'X', 'y': 'Y', 'z': 'Z'}

qibo gate names mapped to the tableau class in tableaus that implements them.

class mpstab.engines.stabilizers.native.engine.NativeStabilizersEngine[source]

Bases: StabilizersEngine

Clifford backpropagation by composing per-gate tableaus.

A pure-Python example of the StabilizersEngine interface, written to be read rather than to be fast: use StimEngine for real workloads.

backpropagate(observable: str, clifford_circuit: Circuit)[source]

Evolve observable back through clifford_circuit, applying each gate’s inverse in reverse order.

Returns:

(pauli_string, sign) for U^dag . O . U, with U the circuit.

Native Stabilizers Engine: backpropagates a Pauli string by composing one tableau per gate, on the XZ-encoded Pauli arithmetic of mpstab.engines.stabilizers.native.pauli_string.

Pure-Python tensor-network engine.

class mpstab.engines.tensor_networks.native.engine.NativeTensorNetworkEngine[source]

Bases: TensorNetworkEngine

MPS evolution and expectation values on the in-package tensor network.

A pure-Python example of the TensorNetworkEngine interface, written to be read rather than to be fast: use QuimbEngine for real workloads. Supports state-side evolution and expectation values. Operator-side conjugation, and so the whole head/tail split of HQSMPO, needs QuimbEngine.

build_circuit_mps(n: int, initial_state_circuit: Any, max_bond_dimension: int | None = None)[source]

Build a CircuitMPS in the product state a qibo circuit of one-qubit gates prepares, simulating each qubit on its own.

expval(state_circuit: CircuitMPS, operator: PauliMPO)[source]

Expectation value of operator on state_circuit.

pauli_mpo(pauli_string: str | object)[source]

Build the PauliMPO for a Pauli string.

pauli_rot(state_circuit: CircuitMPS, generator: str, angle: float, max_bond_dimension: int)[source]

Apply exp(-i angle/2 generator) to the state.

The bond cap comes from the CircuitMPS itself, set at construction, so max_bond_dimension is ignored here.

squared_norm(state_circuit: CircuitMPS) → float[source]

<psi|psi>, the expectation value of the identity.

Native Tensor Network Engine: an MPS in Vidal canonical form on a small in-package tensor-network layer (mpstab.engines.tensor_networks.native.circuit_mps), evolved by applying MPOs and re-splitting by SVD.

Selecting Engines

Engines are automatically selected based on your circuit type and parameters:

from qibo import Circuit, gates
from mpstab import HSMPO
from mpstab.models.ansatze import HardwareEfficient

clifford_circuit = Circuit(nqubits=10)
# Add only Clifford gates
for q in range(10):
     clifford_circuit.add(gates.H(q))
     clifford_circuit.add(gates.CNOT(q0=q%10, q1=(q+1)%10))

# Clifford circuit - uses stabilizer engine only
simulator = HSMPO(ansatz=clifford_circuit)

# Constructing a circuit with also magic gates
mixed_circuit = HardwareEfficient(
     nqubits=10,
     nlayers=3,
)

# Mixed circuit with bond limit - uses both engines
simulator = HSMPO(
    ansatz=mixed_circuit,
    max_bond_dimension=32  # Enables tensor network engine
)

For detailed guidance, see Working with Engines

Engine Interface

All engines implement standardized interfaces for compatibility.

Base Engine Classes:

from mpstab.engines import StabilizersEngine, TensorNetworkEngine

These abstract base classes define the required methods that any engine must implement.

The evolutors never look inside an engine’s states or operators: everything they need goes through these methods, so a new tensor-network engine only has to implement them. tests/test_engine_agnostic.py enforces this with an engine whose states and operators expose nothing.

TensorNetworkEngine methods

Needed for

build_circuit_mps, pauli_mpo, expval, pauli_rot, squared_norm

Required: building and evolving the MPS, expectation values and truncation fidelities.

pauli_expvals, rotation_operator, apply_rotation, copy_state, bond_dimension

Optional, with a generic default an engine may override for speed.

conjugate_operator, operator_site_arrays

Optional: the head/tail split of HQSMPO and its measurement routes. Operators leave the engine only as numpy site arrays.

pauli_sum_mpo, minimize_energy

Optional: DMRG (HSMPO.minimize_expectation).

circuit_truncation_fidelity

Optional: HSMPO.truncation_fidelity_pure_tn.

An optional method an engine does not implement raises NotImplementedError only when the feature that needs it is used.

A stabilizers engine is where the Clifford part of the circuit is handled; the evolutors and the noise compiler only ask it for backpropagated Pauli strings.

StabilizersEngine methods

Needed for

backpropagate

Required: dressing observables with the Clifford circuit.

backpropagate_many

Optional, with a generic default an engine may override to share work across observables.

backpropagate_at

Dressing each magic gate and noise event with the Clifford gates before it. The default replays each prefix through backpropagate; StimEngine overrides it with a single tableau pass.

See Also