Qubit codes specified by signed stabilizer generators.
API contents
Python — ppvm
- code
- code
- Code
- Parity
- · contains_stabilizer
- · encoder_tableau
- · from_css
- · from_stabilizers
- · from_tableau
- · implements_logical_clifford
- · state_stabilizers
- · synthesize_encoder
- · synthesize_logical_clifford
- · synthesize_state_prep
- · terminal_readout
- k
- logical_xs
- logical_zs
- n
- stabilizers
- generalized_tableau
- GeneralizedTableau
- MeasurementResult
- sample_stim
- · asymmetric_loss_channel
- · coefficients
- · current_measurement_record
- · cz_block
- · expectation
- · fork
- · is_leaked
- · is_lost
- · leakage_channel
- · leakage_values
- · loss_values
- · measure
- · measure_many
- · num_coefficients
- · project
- · reset
- · reset_leakage_channel
- · reset_loss_channel
- · reset_state
- · reset_x
- · reset_y
- · reset_z
- · run
- · sample
- · t
- · t_dag
- · trace
- · u3
- MAX_N_QUBITS
- generalized_tableau_sum
- GeneralizedTableauSum
- TableauSumSampler
- · measure
- · reset
- · reset_loss_channel
- · reset_state
- · sampler
- · t
- · t_dag
- · u3
- · raw_sample
- · raw_shots
- · sample
- · sample_shots
- lindblad
- lindblad
- Lindbladian
- sigma_minus
- sigma_plus
- · action
- · action_arr
- · generator
- · generator_arr
- · leakage
- · leakage_arr
- · pc_step
- · pc_step_arr
- · pc_step_orbit_rep
- mixins
- CliffordExtensionMixin
- CliffordMixin
- LossMixin
- NoiseMixin
- RotationsMixin
- TruncatingCliffordExtensionMixin
- TruncatingCliffordMixin
- TruncatingNoiseMixin
- TruncatingRotationsMixin
- · cy
- · s_dag
- · sqrt_x
- · sqrt_x_dag
- · sqrt_y
- · sqrt_y_dag
- · cnot
- · cz
- · h
- · s
- · x
- · y
- · z
- · correlated_loss_channel
- · loss_channel
- · depolarize1
- · depolarize2
- · pauli_error
- · two_qubit_pauli_error
- · two_qubit_pauli_error_probabilities
- · x_error
- · y_error
- · z_error
- · r
- · rx
- · rxx
- · ry
- · ryy
- · rz
- · rzz
- · cy
- · s_dag
- · sqrt_x
- · sqrt_x_dag
- · sqrt_y
- · sqrt_y_dag
- · cnot
- · cz
- · h
- · s
- · x
- · y
- · z
- · depolarize1
- · depolarize2
- · pauli_error
- · two_qubit_pauli_error
- · x_error
- · y_error
- · z_error
- · r
- · rx
- · rxx
- · ry
- · ryy
- · rz
- · rzz
- paulisum
- LossyPauliSum
- PauliSum
- · correlated_loss_channel
- · loss_channel
- · momentum_merge
- · reset_loss_channel
- · symmetry_merge
- · amplitude_damping
- · copy
- · current_max_weight
- · momentum_merge
- · new
- · overlap
- · overlap_with_zero
- · symmetry_merge
- · trace
- · truncate
- · weights
- terms
- squin_interpreter
- squin_interpreter
- impls
- · ccz
Rust
- Modules
- ppvm_traits
- Structs
- NoStrategy
- Enums
- Pauli
- Traits
- Config
- CRx
- Projection
- RotationOne
- RotXY
- RotationTwo
- TGate
- U3Gate
- Clifford
- CliffordBatch
- CliffordExtensions
- CliffordExtensionsBatch
- Coefficient
- ComplexCoefficient
- HashFinalize
- ACMap
- ACMapAddAssign
- ACMapBase
- ACMapConsume
- ACMapContains
- ACMapInsert
- ACMapIter
- ACMapMulAssign
- ACMapRetain
- ACMapScale
- LossyMeasure
- Measure
- AmplitudeDamping
- AsymmetricLossChannel
- CorrelatedLossChannel
- Depolarizing
- Depolarizing2
- LeakageChannel
- LossChannel
- PauliError
- ResetLeakageChannel
- ResetLossChannel
- TwoQubitPauliError
- Reset
- ResetState
- WordReset
- PauliStorage
- Strategy
- Trace
- PauliIter
- PauliWordTrait
- Type aliases
- FoldBuildHasher
- FoldHashMap
- Structs
- ByteFxHash
- Byte8
- Byte
- ByteFxHash
- CoefficientThreshold
- CombinedStrategy
- MaxLossWeight
- MaxPauliWeight
- Empty
- SetCapacity
- SetNQubits
- SetPreserveStrings
- SetStrategy
- PauliSum
- PauliSumBuilder
- TranslationGroup
- CharacterTable
- Traits
- IsComplete
- State
- Functions
- aux
- data
- truncate
- canonicalize
- canonicalize_in_sector
- canonicalize_in_sector_indexed
- canonicalize_with_index
- canonicalize_with_shift
- chain_1d
- character
- character_table
- from_generators
- ladder
- orbit
- order
- torus_2d
- torus_3d
- try_from_generators
- canonicalize_pauli_sum
- symmetry_merge_pauli_sum
- canonicalize_pauli_sum_complex
- value
- check_momentum_sector
- momentum_merge_pauli_sum_pair
- Type aliases
- ByteFxHashF64
- Byte8F64
- ByteF64
- ByteFxHashF64
- Modules
- ppvm_tableau
- data
- display
- expectation
- gates
- measure
- noise
- prelude
- qubit_status
- sparsevec
- tableau_index
- tableau_like
- Enums
- QubitStatus
API Reference
Pythonppvm
Pythonic wrapper around the native Rust runtime. All items below live under the ppvm top-level module.
code
Joint +1 eigenspace of signed, commuting qubit Pauli generators.
Full docstring
Joint +1 eigenspace of signed, commuting qubit Pauli generators.
Column zero is qubit zero. Redundant, consistent checks retain their input order. The default logical basis is deterministic; supply both ordered logical X and Z lists to use a particular convention.
XOR the indicated record bits and the offset to evaluate the parity.
Test membership in the signed stabilizer group, including the phase.
Forward Stim Clifford tableau. The last k inputs carry logical data.
Full docstring
Forward Stim Clifford tableau. The last k inputs carry logical data.
The first n-k inputs are zero ancillas. Their Z images are the independent checks, and both Pauli images of every data input use our logical basis.
Construct from positive X and Z checks with the same physical-qubit order.
Construct from rows such as '+XZZXI' or '-YY'; I and _ mean identity.
Each row is one check. (x,z)=(1,1) is Y; sign 1 denotes minus.
Check a physical Clifford's action on the codespace up to global phase.
Independent signed generators of a logical computational-basis state.
Full docstring
Independent signed generators of a logical computational-basis state.
Defaults to all logical zeros. bits[i] sets the eigenvalue of logical_zs[i].
Return a verified ideal encoding circuit using Stim.
Return a verified ideal circuit acting as logical on the encoded data.
Full docstring
Return a verified ideal circuit acting as logical on the encoded data.
Its target is logical decoding, the requested Clifford, then re-encoding. Fault tolerance requires a separate circuit-level analysis.
Prepare and verify the signed logical basis state. Returns a Stim circuit.
Derive parities for destructive single-qubit Pauli measurements.
Full docstring
Derive parities for destructive single-qubit Pauli measurements.
bases[q] is the physical X/Y/Z axis on qubit q. order[j] is the qubit measured into record j (default: identity). logical_bases chooses X, Y or Z for each logical qubit, or I to skip it; defaults to all Z. Detectors form an independent basis of measurable stabilizers. Observables are returned in logical order, using equivalent representatives when needed.
Number of encoded qubits (n minus stabilizer rank).
Ordered logical X representatives in physical-qubit order.
Ordered logical Z representatives paired with logical_xs.
Number of physical qubits.
Original signed checks, including redundant rows.
generalized_tableau
Generalized stabilizer tableau for quantum circuit simulation.
Full docstring
Generalized stabilizer tableau for quantum circuit simulation.
Represents an arbitrary quantum state in the basis spanned by the stabilizer tableau. It supports Clifford gates, arbitrary single- and two-qubit rotations, noise channels, and mid-circuit measurement. The coefficient vector grows exponentially with the number of non-Clifford operations applied.
A measurement outcome, which accounts for a qubit being potentially lost.
Multi-shot sampling of a Stim program.
Full docstring
Multi-shot sampling of a Stim program.
method="tableau" runs GeneralizedTableau.sample. method="css" runs the
CSS frame sampler, which simulates loss and leakage exactly with many shots per
machine word, but only for circuits that are CSS up to Hadamard gates (see
StimProgram.is_css); it ignores min_abs_coeff and needs no n_qubits.
method="auto" (the default) uses the CSS sampler whenever the program allows
it. Both samplers draw from the same distribution, but a given seed yields
different shots in each.
When n_qubits is None (the default) the qubit count is inferred from
the program; see GeneralizedTableau.sample. Shots are sampled in parallel
across CPU cores with the GIL released; see GeneralizedTableau.sample for
seeding, RAYON_NUM_THREADS and the as_numpy array format.
Apply a state-dependent ("asymmetric") loss channel to a qubit.
Full docstring
Apply a state-dependent ("asymmetric") loss channel to a qubit.
The qubit is lost from |0> with probability p0 and from |1> with
probability p1, so the total loss probability depends on the
current populations: p_tot = p0 * (1 + <Z>)/2 + p1 * (1 - <Z>)/2.
.. note::
This is the trajectory approximation of the loss channel. It is
exact for the loss statistics and in the symmetric limit
p0 == p1 (where it matches loss_channel), but it does
not apply the survival back-action, so for p0 != p1 the
surviving qubit's state is left unchanged. See issue #39.
Parameters
addr0intThe index of the target qubit.
p0floatThe loss probability from the |0> state.
p1floatThe loss probability from the |1> state.
Return a snapshot of the sparse coefficient vector.
Full docstring
Return a snapshot of the sparse coefficient vector.
The tableau represents the state as a sparse superposition over the basis states of its stabilizer frame. This returns that vector as a mapping from basis-state index to complex amplitude.
The returned dict is a copy: mutating it does not affect the tableau's internal state.
Returns
A dict mapping each populated basis-state index to its complex amplitude.
Return all measurement outcomes recorded so far.
Full docstring
Return all measurement outcomes recorded so far.
Returns
A list of
MeasurementResultoutcomes in measurement order.
Apply a fused block of CZ gates over constant-offset qubit pairs.
Full docstring
Apply a fused block of CZ gates over constant-offset qubit pairs.
Applies CZ to (control_base + i, target_base + i) for i in
range(count) -- i.e. the gates zip(range(control_base, ...), range(target_base, ...)) would produce. Disjoint constant-offset
blocks use a word-level kernel that is much faster than the equivalent
cz call (e.g. entangling two adjacent qubit registers). Overlapping
/ brickwork pairs such as cz_block(0, 1, n) are still correct: they
fall back to the per-pair loop. For scattered pairs, use cz.
CZ is symmetric, so control_base and target_base may be given in
either order.
Parameters
control_baseintFirst qubit of the control run.
target_baseintFirst qubit of the target run.
countintNumber of CZ pairs.
Compute ⟨ψ|word|ψ⟩ for a single multi-qubit Pauli string.
Full docstring
Compute ⟨ψ|word|ψ⟩ for a single multi-qubit Pauli string.
Parameters
wordstrA dense Pauli string with one character per qubit, each drawn from
I,X,Y,Z(e.g."ZZ"for a two-qubit state). Its length must equal the tableau's qubit count.
Returns
floatThe real expectation value of
wordin the current state.
Fork this tableau into an independent simulation branch.
Full docstring
Fork this tableau into an independent simulation branch.
Clones all quantum state but reinitializes the RNG, so the returned
tableau evolves independently from this one. If seed is provided
the new RNG is seeded deterministically; otherwise it is seeded from
OS entropy.
Use this when branching a simulation into independent trajectories.
To preserve the RNG state exactly (e.g. for checkpointing), use
copy.copy() or copy.deepcopy() instead.
Parameters
seedOptional integer seed for the forked RNG.
Returns
GeneralizedTableauA new
GeneralizedTableauwith the same quantum state but an independent RNG.
Check whether a qubit has leaked out of the computational subspace.
Full docstring
Check whether a qubit has leaked out of the computational subspace.
A leaked qubit is still present and measures as a pinned 0/1;
gates skip it. Distinct from is_lost.
Parameters
addr0intThe index of the qubit.
Returns
boolTrue if the qubit is leaked, False otherwise.
Check whether a qubit has been lost.
Full docstring
Check whether a qubit has been lost.
Parameters
addr0intThe index of the qubit.
Returns
boolTrue if the qubit is lost, False otherwise.
Apply a leakage channel that pins the qubit out of the computational subspace.
Full docstring
Apply a leakage channel that pins the qubit out of the computational subspace.
With probability p0 the qubit leaks and is pinned to |0⟩; with
probability p1 it leaks and is pinned to |1⟩. The total leak
probability is p0 + p1 (independent of the current state). A
leaked qubit still measures as the pinned bit; gates skip it.
Distinct from asymmetric_loss_channel, whose p0 / p1 are
loss probabilities from |0⟩ / |1⟩.
Parameters
addr0intThe index of the target qubit.
p0floatProbability of leaking into a pinned
|0⟩.p1floatProbability of leaking into a pinned
|1⟩.
Return the leakage state of all qubits.
Full docstring
Return the leakage state of all qubits.
Returns
A list of booleans of length
n_qubits, where each entry is True if the corresponding qubit is leaked and False otherwise.
Return the loss state of all qubits.
Full docstring
Return the loss state of all qubits.
Returns
A list of booleans of length
n_qubits, where each entry is True if the corresponding qubit is lost and False otherwise.
Measure the specified qubit in the Z basis.
Full docstring
Measure the specified qubit in the Z basis.
Parameters
addr0intThe index of the target qubit.
Returns
MeasurementResultThe measurement outcome as a
MeasurementResult, which isLOSTif the qubit has been lost,ZEROorONEotherwise.
Measure several qubits in the Z basis.
Full docstring
Measure several qubits in the Z basis.
Parameters
*targetsThe indices of the target qubits.
Returns
A list of
MeasurementResultoutcomes, one per target.
Return the number of branches in the coefficient vector.
Full docstring
Return the number of branches in the coefficient vector.
This is the number of entries in the dict returned by
coefficients, computed without materializing it.
Returns
intThe count of populated entries in the sparse coefficient vector.
Post-select a measurement of the specified qubit onto outcome.
Full docstring
Post-select a measurement of the specified qubit onto outcome.
Collapses the state as measure would have on outcome and records
it. LOST has probability 1 on a lost qubit and 0 on a live one.
Chaining it gives exact bitstring probabilities:
python p = 1.0 for q, bit in enumerate(bits): p *= tab.project(q, MeasurementResult(bit))
Parameters
addr0intThe index of the target qubit.
outcomeMeasurementResultThe outcome to project onto.
tolfloatSmallest probability accepted for
outcome, in(0, 1].
Returns
floatThe probability of measuring
outcomebefore the projection.
Raises
ValueErrorIf
tolis invalid, or, leaving the state unchanged, if the probability ofoutcomeis belowtol.
Reset each target qubit to the |0> state.
Full docstring
Reset each target qubit to the |0> state.
Lost and leaked qubits are first returned to the computational subspace.
Parameters
*targetsThe indices of the target qubits.
Return a leaked qubit to the computational subspace in |0⟩.
Full docstring
Return a leaked qubit to the computational subspace in |0⟩.
No-op if the qubit is live. A lost qubit cannot be recovered this way.
Parameters
addr0intThe index of the target qubit.
Reset a lost qubit to being active again.
Full docstring
Reset a lost qubit to being active again.
Parameters
addr0intThe index of the target qubit.
Reset the state of each live target qubit to the |0> state.
Full docstring
Reset the state of each live target qubit to the |0> state.
Lost and leaked qubits are left untouched. Use reset for a full reset.
Parameters
*targetsThe indices of the target qubits.
Reset each target qubit to the |+> state.
Full docstring
Reset each target qubit to the |+> state.
Lost and leaked qubits are first returned to the computational subspace.
Parameters
*targetsThe indices of the target qubits.
Reset each target qubit to the |+i> state.
Full docstring
Reset each target qubit to the |+i> state.
Lost and leaked qubits are first returned to the computational subspace.
Parameters
*targetsThe indices of the target qubits.
Reset each target qubit to the |0> state.
Full docstring
Reset each target qubit to the |0> state.
Lost and leaked qubits are first returned to the computational subspace.
Parameters
*targetsThe indices of the target qubits.
Execute a parsed Stim program against this tableau (single shot).
Full docstring
Execute a parsed Stim program against this tableau (single shot).
.. note::
This mutates the tableau in place. For independent shots use
fork or ppvm.sample_stim / sample helpers (which build a
fresh tableau per shot).
Run num_shots shots of prog and return all measurement results.
Full docstring
Run num_shots shots of prog and return all measurement results.
Each shot starts from a fresh tableau, so this is the right entry point for multi-shot sampling.
When n_qubits is None (the default) the qubit count is inferred
from the program via prog.num_qubits (one past the highest qubit
index it references), falling back to 1 for a program that touches no
qubits. Pass an explicit n_qubits to size the tableau larger.
Shots run in parallel across CPU cores (the GIL is released during
sampling), with a serial fallback for small batches. When seed is
given (it must fit in an unsigned 64-bit integer), each shot's seed is
derived deterministically from seed and the shot index, so results
are reproducible and independent of the number of threads, and nearby
seeds (seed and seed + 1) give unrelated shots. Set the
RAYON_NUM_THREADS environment variable before the first call to
control the pool size (it defaults to the number of logical cores).
With as_numpy=True the results come back as a writable int8
array of shape (num_shots, n_measurements) holding the
MeasurementResult values (0/1/2 = zero/one/lost), which avoids
building one Python object per measurement.
Apply a T gate (π/8 rotation) to each target qubit.
Full docstring
Apply a T gate (π/8 rotation) to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply a T adjoint gate (negative π/8 rotation) to each target qubit.
Full docstring
Apply a T adjoint gate (negative π/8 rotation) to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Sum Pauli expectations over every word matching pattern.
Full docstring
Sum Pauli expectations over every word matching pattern.
Enumerates each PauliWord accepted by pattern and returns
the sum of their expectations. Star quantifiers (X*) are not
supported — use counted repetition (Z?{n}) or positional
anchors instead.
Parameters
patternstrA Pauli pattern string (e.g.
"Z?{2}"or"Z0Z1").
Returns
floatThe summed expectation value.
Apply the U3 gate to the specified qubit.
Full docstring
Apply the U3 gate to the specified qubit.
U3(θ, φ, λ) = RZ(φ) · RY(θ) · RZ(λ)
The corresponding unitary matrix is:
[ cos(θ/2) -e^(iλ)·sin(θ/2) ]
[ e^(iφ)·sin(θ/2) e^(i(φ+λ))·cos(θ/2) ]
Parameters
addr0intThe address of the qubit to apply the gate to.
thetafloatRotation angle θ (in radians) for the RY component.
phifloatRotation angle φ (in radians) for the first RZ component.
lamfloatRotation angle λ (in radians) for the second RZ component.
Maximum number of qubits supported by the Python bindings.
Full docstring
Maximum number of qubits supported by the Python bindings.
The native module pre-compiles a fixed set of tableau interfaces; beyond this limit, use the Rust crate directly.
generalized_tableau_sum
A sum over generalized tableaus, representing a density matrix that is a weighted sum over pure state projectors (classical mixture). Each projector is represented by a generalized tableau. The respective weights are the probabilities wi…
Full docstring
A sum over generalized tableaus, representing a density matrix that is a weighted sum over pure state projectors (classical mixture). Each projector is represented by a generalized tableau. The respective weights are the probabilities with which the system is in the corresponding state.
Sample a GeneralizedTableauSum.
Full docstring
Sample a GeneralizedTableauSum.
Construct via GeneralizedTableauSum.sampler().
Branch on a mid-circuit Z measurement and return outcome probabilities.
Full docstring
Branch on a mid-circuit Z measurement and return outcome probabilities.
Parameters
addr0intThe index of the target qubit.
Returns
A mapping from
MeasurementResult(ZERO,ONE,LOST) to the corresponding outcome probability.
Reset each target qubit to the |0> state.
Full docstring
Reset each target qubit to the |0> state.
Lost qubits are first returned to the computational subspace.
Parameters
*targetsThe indices of the target qubits.
Reset a lost qubit to being active again.
Full docstring
Reset a lost qubit to being active again.
Parameters
addr0intThe index of the target qubit.
Reset the state of each live target qubit to the |0> state.
Full docstring
Reset the state of each live target qubit to the |0> state.
Lost qubits are left untouched. Use reset for a full reset.
Parameters
*targetsThe indices of the target qubits.
Compile a sampler over a snapshot of the current state.
Full docstring
Compile a sampler over a snapshot of the current state.
The sampler holds its own RNG and a copy of the sum's branches, so further gates applied to this tableau do not affect it.
Returns
TableauSumSamplerA sampler drawing shots from the current state.
Apply a T gate (π/8 rotation) to each target qubit.
Full docstring
Apply a T gate (π/8 rotation) to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply a T adjoint gate (negative π/8 rotation) to each target qubit.
Full docstring
Apply a T adjoint gate (negative π/8 rotation) to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply the U3 gate to the specified qubit.
Full docstring
Apply the U3 gate to the specified qubit.
U3(θ, φ, λ) = RZ(φ) · RY(θ) · RZ(λ)
The corresponding unitary matrix is:
[ cos(θ/2) -e^(iλ)·sin(θ/2) ]
[ e^(iφ)·sin(θ/2) e^(i(φ+λ))·cos(θ/2) ]
Parameters
addr0intThe address of the qubit to apply the gate to.
thetafloatRotation angle θ (in radians) for the RY component.
phifloatRotation angle φ (in radians) for the first RZ component.
lamfloatRotation angle λ (in radians) for the second RZ component.
Draw a single shot as raw integer codes (0/1/2 for |0>/|1>/lost).
Full docstring
Draw a single shot as raw integer codes (0/1/2 for |0>/|1>/lost).
Faster than sample, as it skips the MeasurementResult conversion.
Returns
Per-qubit integer outcome codes, indexed by qubit address.
Draw num_shots shots as raw integer codes (0/1/2 for |0>/|1>/lost).
Full docstring
Draw num_shots shots as raw integer codes (0/1/2 for |0>/|1>/lost).
Faster than sample_shots, as it skips the MeasurementResult conversion.
Parameters
num_shotsintThe number of shots to draw.
Returns
One list of per-qubit integer outcome codes per shot.
Draw a single shot: one measurement outcome per qubit.
Full docstring
Draw a single shot: one measurement outcome per qubit.
Returns
Per-qubit outcomes, indexed by qubit address.
Draw num_shots shots, each with one outcome per qubit.
Full docstring
Draw num_shots shots, each with one outcome per qubit.
Parameters
num_shotsintThe number of shots to draw.
Returns
One list of per-qubit outcomes per shot.
lindblad
Direct Pauli-Lindbladian time evolution on an adaptive Pauli-string basis.
Full docstring
Direct Pauli-Lindbladian time evolution on an adaptive Pauli-string basis.
Given a Hermitian Pauli Hamiltonian H = Σ c_i P_i and jump operators L_k = Σ_a λ_{k,a} P_{k,a} (each a complex linear combination of Pauli strings) with rates γ_k ≥ 0, this module exposes the primitives for adaptive Heisenberg-picture evolution:
pc_step(...)/pc_step_arr(...): one adaptive predictor-corrector stepO ← exp(dt·L*) O;pc_step_orbit_rep(...)is the translation-symmetric (momentum-sector) variantaction(p)/action_arr(p): L*(p) for one Pauli string pleakage(basis, coeffs)/leakage_arr(...): off-basis component of L*(Σ c_j p_j), driving basis expansiongenerator(basis): COO triples(rows, cols, vals)for the generator matrix M such that L* restricted tobasisisM @ coeffs. Users wanting a sparse matrix can wrap them — e.g.scipy.sparse.coo_matrix((vals, (rows, cols)), shape=(N, N)).tocsc()
The *_arr variants pass Pauli strings as (N, n_qubits) uint8
arrays of Pauli codes (0=I, 1=X, 2=Z, 3=Y) and skip string
construction entirely — at ~10^5 basis rows per evolution step, per-row
str.join dominates wall time.
Each jump term can be either:
- a single Hermitian Pauli (
("ZZII", γ)), routed to a fast diagonal path, or - a complex Pauli sum (
([("XIII", 0.5+0j), ("YIII", 0+0.5j)], γ)) to describe e.g. amplitude-damping (σ⁻) and excitation (σ⁺) operators.
For the general case the dissipator
γ ( L† p L − ½ {L†L, p} ) is evaluated directly; the L†L Pauli
expansion is precomputed once at construction.
Pre-compiled adjoint Pauli-Lindbladian acting on Pauli strings.
Full docstring
Pre-compiled adjoint Pauli-Lindbladian acting on Pauli strings.
Parameters
n_qubits:
Number of qubits, at most 512. The Pauli word width is chosen
automatically: up to 128 qubits uses the original 128-bit layout,
then 256- and 512-bit words. Narrow problems are unaffected by the
wider layouts being available.
h_terms:
Iterable of (pauli_string, coefficient) pairs for the
Hermitian Hamiltonian H = Σ c_i P_i. Each pauli_string is
a length-n_qubits str over "IXYZ".
jump_terms:
Iterable of (jump_op, rate) pairs. jump_op is either a
Pauli string "XYZI..." (treated as a Hermitian-Pauli jump
with coefficient 1, hitting the fast path) or an iterable of
(pauli_string, complex_coeff) pairs for a general complex
Pauli linear combination such as sigma_plus or
sigma_minus. rate is the non-negative GKSL rate
γ_k.
kossakowski:
Optional (ops, K) pair adding a Kossakowski-form dissipator
D*(O) = Σ_nm K_nm (A_n† O A_m − ½{A_n†A_m, O}). ops is a
length-M sequence of Pauli lincombs (same format as a
jump_op, e.g. [sigma_minus(j, n) for j in range(n)]);
K is an (M, M) Hermitian positive-semidefinite array
(e.g. the collective-decay pair matrix Γ_nm). Mathematically
identical to passing the eigenmode jumps
L_ν = √γ_ν Σ_j V*_jν A_j of K = V diag(γ) V†, but the
per-string action cost scales with the number of nonzero
K_nm entries instead of carrying an extra factor of M.
May coexist with jump_terms (both contribute). Raises
ValueError if K is not Hermitian or has an eigenvalue
below −tol·‖K‖ (a non-PSD K is not a valid GKSL
generator; no silent clipping).
Examples
Dephasing (Hermitian Pauli):
Lindbladian(2, [("XX", 1.0)], [("ZI", 0.3), ("IZ", 0.3)])
Amplitude damping on site 0 (non-Hermitian):
jumps = [(sigma_minus(0, 2), 0.5)] Lindbladian(2, [("XX", 1.0)], jumps)
Collective decay from a pair matrix:
ops = [sigma_minus(j, 2) for j in range(2)] gamma = [[1.0, 0.6], [0.6, 1.0]] Lindbladian(2, [("XX", 1.0)], kossakowski=(ops, gamma))
σ⁻_q = (X_q − i Y_q) / 2. Use as a Lindblad jump for amplitude damping.
σ⁺_q = (X_q + i Y_q) / 2. Use as a Lindblad jump for excitation.
Apply L* to a single Pauli string p (string-keyed dict).
Apply L* to a single Pauli string given as uint8 codes.
Full docstring
Apply L* to a single Pauli string given as uint8 codes.
Returns (out_basis, out_coeffs): a (M, n_qubits) uint8
array and a length-M float64 array.
Generator matrix as COO triples (rows, cols, vals), basis given as strings. See generator_arr for the conversion to a SciPy sparse matrix.
Full docstring
Generator matrix as COO triples (rows, cols, vals),
basis given as strings. See generator_arr for the conversion
to a SciPy sparse matrix.
Generator matrix as COO triples (rows, cols, vals).
Full docstring
Generator matrix as COO triples (rows, cols, vals).
Basis given as uint8 codes. To get a SciPy sparse matrix:
import scipy.sparse as sp rows, cols, vals = L_op.generator_arr(basis_arr) M = sp.coo_matrix( ... (vals, (rows, cols)), shape=(len(basis_arr), len(basis_arr)) ... ).tocsc()
Off-basis leakage as a dict[str, float] (slower API).
Off-basis component of L*( Σ_j coeffs[j] basis[j] ).
Full docstring
Off-basis component of L*( Σ_j coeffs[j] basis[j] ).
basis_arr: (N, n_qubits) uint8. coeffs: length-N float64.
protected_arr: optional (K, n_qubits) uint8 of Pauli strings
that must NEVER appear in the leakage output.
Returns (out_basis, out_coeffs) packed the same way as
action_arr.
String-keyed variant of pc_step_arr.
One predictor-corrector adaptive step.
Full docstring
One predictor-corrector adaptive step.
All work — leakage expansion, matrix-exponential step, second-hop
re-expansion, corrector — runs in Rust; SciPy is not required.
The matrix-exponential action is computed matrix-free via the
external quspin-expm crate.
Truncation. max_basis is a hard rank cap on the live basis:
enrichment adds at most max_basis - len(basis) of the largest
leakage strings, and the post-step basis is trimmed to the
top-max_basis entries by |coeff| (protected words always
kept). Pass a large value (e.g. 10_000_000) for the near-exact,
uncapped case. drop_tol additionally prunes basis entries whose
absolute coefficient is below the threshold after the corrector
(unless the word is protected).
num_threads, when set, pins this call to a freshly-built rayon
pool of that size — useful for benchmarking parallel scaling.
tau_add, when set, filters leakage admission by an absolute
coefficient-rate threshold (a dt- and drop_tol-independent
parameterization). Off by default — with cap-based truncation it
is at most a modest wall optimization.
admit_basis, when set (must be >= max_basis), bounds the
enriched working set during the step instead of max_basis: the
step may hold up to admit_basis strings transiently, and the
final truncation keeps the top-max_basis by evolved |coeff|
over the whole union (retained + newly admitted) — rank
displacement, so no drop_tol is needed to sustain membership
turnover. With the default None, admission is bounded by
max_basis and turnover requires drop_tol > 0.
Returns (new_basis_arr, new_coeffs); the basis may have grown
(or shrunk, if max_basis / drop_tol pruned entries).
Per-step orbit-representative pc evolution.
Full docstring
Per-step orbit-representative pc evolution.
State lives entirely in orbit-rep form throughout: basis_arr
contains only canonical translation-orbit representatives,
coeffs are complex, and the action is phase-aware. The basis
is ~|group|× smaller than the equivalent full-basis complex
evolution, and the reduction persists across every step.
Coefficients use the same convention as
ppvm.canonicalize_basis_arr_complex: coeffs[i] is the plain
coefficient of the representative Pauli word itself (the
orbit-averaged convention, not the summing one
PauliSum.momentum_merge uses). Reps whose orbit cannot carry
momentum — its stabilizer has a non-trivial character — are
dropped, matching that projection.
Truncation. max_basis is a hard rank cap on the live orbit-rep
basis: enrichment adds at most max_basis - len(basis) of the
largest leakage reps, and the post-step basis is trimmed to the
top-max_basis reps by |c| (protected reps always kept).
Pass a large value (e.g. 10_000_000) for the near-exact,
uncapped case. drop_tol additionally prunes reps whose absolute
coefficient is below the threshold after the corrector.
admit_basis, when set (>= max_basis), bounds the enriched
working set instead of max_basis: the step may hold up to
admit_basis reps transiently and the final truncation keeps the
top-max_basis by evolved |c| over the whole union — the
displacement scheme, matching the real-space pc_step_arr.
basis_arr is assumed to contain canonical reps only. Pass
canonicalize_first=True to rewrite each row to its canonical
rep on entry (coefficients unchanged).
num_threads, when set, pins this call to a freshly-built rayon
pool of that size, exactly as for pc_step_arr.
mixins
Additional Clifford gates without per-gate truncation control.
Clifford gates without per-gate truncation control.
Loss channels without per-gate truncation control.
Noise channels without per-gate truncation control.
Rotation gates without per-gate truncation control.
Additional Clifford gates with a per-gate truncate kwarg.
Clifford gates with a per-gate truncate kwarg (used by PauliSum).
Noise channels with a per-gate truncate kwarg (used by PauliSum).
Full docstring
Noise channels with a per-gate truncate kwarg (used by PauliSum).
two_qubit_pauli_error_probabilities is inherited unchanged from
NoiseMixin.
Rotation gates with a per-gate truncate kwarg (used by PauliSum).
Apply controlled-Y gates over consecutive control/target pairs.
Full docstring
Apply controlled-Y gates over consecutive control/target pairs.
Parameters
*targetsA flat list of qubit indices, broadcast as
(control, target)pairs.
Apply an S adjoint gate (sqrt(Z) dagger) to each target qubit.
Full docstring
Apply an S adjoint gate (sqrt(Z) dagger) to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply a sqrt(X) gate to each target qubit.
Full docstring
Apply a sqrt(X) gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply a sqrt(X) adjoint gate to each target qubit.
Full docstring
Apply a sqrt(X) adjoint gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply a sqrt(Y) gate to each target qubit.
Full docstring
Apply a sqrt(Y) gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply a sqrt(Y) adjoint gate to each target qubit.
Full docstring
Apply a sqrt(Y) adjoint gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply CNOT (controlled-X) gates over consecutive control/target pairs.
Full docstring
Apply CNOT (controlled-X) gates over consecutive control/target pairs.
Parameters
*targetsA flat list of qubit indices, broadcast as
(control, target)pairs.
Apply CZ (controlled-Z) gates over consecutive qubit pairs.
Full docstring
Apply CZ (controlled-Z) gates over consecutive qubit pairs.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
Apply a Hadamard gate to each target qubit.
Full docstring
Apply a Hadamard gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply an S gate (sqrt(Z)) to each target qubit.
Full docstring
Apply an S gate (sqrt(Z)) to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply a Pauli X gate to each target qubit.
Full docstring
Apply a Pauli X gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply a Pauli Y gate to each target qubit.
Full docstring
Apply a Pauli Y gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply a Pauli Z gate to each target qubit.
Full docstring
Apply a Pauli Z gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
Apply a correlated loss channel to two qubits.
Full docstring
Apply a correlated loss channel to two qubits.
Parameters
addr0intThe index of the first target qubit.
addr1intThe index of the second target qubit.
pA list of three probabilities:
p[0]: probability of losing both qubits simultaneously when both are in the qubit subspace.p[1]: probability of losing a named one of the two qubits when both are in the qubit subspace. The two single-loss events are disjoint, so the probability of losing exactly one qubit is2 * p[1]and the probability that both remain is1 - 2 * p[1] - p[0](which qubit is lost is 50/50 random).p[2]: probability of losing the remaining active qubit when the other has already been lost prior to this channel.
Apply a loss channel to the specified qubit.
Full docstring
Apply a loss channel to the specified qubit.
Parameters
addr0intThe index of the target qubit.
pfloatThe loss probability.
Apply a single-qubit depolarizing channel to each target qubit.
Full docstring
Apply a single-qubit depolarizing channel to each target qubit.
Parameters
*targetsThe indices of the target qubits.
pThe depolarizing probability.
Apply a two-qubit depolarizing channel over consecutive qubit pairs.
Full docstring
Apply a two-qubit depolarizing channel over consecutive qubit pairs.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
pThe depolarizing probability.
Apply a single-qubit Pauli error channel to each target qubit.
Full docstring
Apply a single-qubit Pauli error channel to each target qubit.
Parameters
*targetsThe indices of the target qubits.
pError probabilities [p_x, p_y, p_z] for X, Y, Z errors. The identity probability is implicitly 1 - sum(p).
Apply a two-qubit Pauli error channel over consecutive qubit pairs.
Full docstring
Apply a two-qubit Pauli error channel over consecutive qubit pairs.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
pError probabilities for the 15 non-identity two-qubit Pauli operators. Use two_qubit_pauli_error_probabilities to convert from a dictionary format.
Convert a dictionary of two-qubit Pauli error probabilities to a list.
Full docstring
Convert a dictionary of two-qubit Pauli error probabilities to a list.
Convenience method to convert a dictionary mapping two-qubit Pauli strings (e.g., "IX", "ZZ") to their probabilities into the ordered list format required by two_qubit_pauli_error.
Parameters
error_probabilitiesDictionary mapping two-qubit Pauli strings to their error probabilities. Missing keys default to 0.0.
Returns
A list of 15 probabilities in the canonical order (excludes "II").
Apply an X error channel to each target qubit.
Full docstring
Apply an X error channel to each target qubit.
Parameters
*targetsThe indices of the target qubits.
pThe probability of applying an X error.
Apply a Y error channel to each target qubit.
Full docstring
Apply a Y error channel to each target qubit.
Parameters
*targetsThe indices of the target qubits.
pThe probability of applying a Y error.
Apply a Z error channel to each target qubit.
Full docstring
Apply a Z error channel to each target qubit.
Parameters
*targetsThe indices of the target qubits.
pThe probability of applying a Z error.
Apply a rotation about an axis in the X-Y plane to the specified qubit.
Full docstring
Apply a rotation about an axis in the X-Y plane to the specified qubit.
math R(\phi, \theta) = e^{-i \frac{\theta}{2} (\cos\phi\, X + \sin\phi\, Y)} = R_Z(\phi) R_X(\theta) R_Z(-\phi)
Parameters
addr0intThe index of the target qubit.
axis_anglefloatThe angle
φ(in radians) of the rotation axis within the X-Y plane, measured from the X-axis.thetafloatThe rotation angle in radians.
Apply an RX rotation gate to each target qubit.
Full docstring
Apply an RX rotation gate to each target qubit.
math R_X(\theta) = e^{-i \frac{\theta}{2} X} = \cos\frac{\theta}{2} I - i \sin\frac{\theta}{2} X
Parameters
*targetsThe indices of the target qubits.
thetaThe rotation angle in radians.
Apply RXX (Ising XX) rotation gates over consecutive qubit pairs.
Full docstring
Apply RXX (Ising XX) rotation gates over consecutive qubit pairs.
math R_{XX}(\theta) = e^{-i \frac{\theta}{2} X \otimes X}
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
thetaThe rotation angle in radians.
Apply an RY rotation gate to each target qubit.
Full docstring
Apply an RY rotation gate to each target qubit.
math R_Y(\theta) = e^{-i \frac{\theta}{2} Y} = \cos\frac{\theta}{2} I - i \sin\frac{\theta}{2} Y
Parameters
*targetsThe indices of the target qubits.
thetaThe rotation angle in radians.
Apply RYY (Ising YY) rotation gates over consecutive qubit pairs.
Full docstring
Apply RYY (Ising YY) rotation gates over consecutive qubit pairs.
math R_{YY}(\theta) = e^{-i \frac{\theta}{2} Y \otimes Y}
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
thetaThe rotation angle in radians.
Apply an RZ rotation gate to each target qubit.
Full docstring
Apply an RZ rotation gate to each target qubit.
math R_Z(\theta) = e^{-i \frac{\theta}{2} Z} = \cos\frac{\theta}{2} I - i \sin\frac{\theta}{2} Z
Parameters
*targetsThe indices of the target qubits.
thetaThe rotation angle in radians.
Apply RZZ (Ising ZZ) rotation gates over consecutive qubit pairs.
Full docstring
Apply RZZ (Ising ZZ) rotation gates over consecutive qubit pairs.
math R_{ZZ}(\theta) = e^{-i \frac{\theta}{2} Z \otimes Z}
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
thetaThe rotation angle in radians.
Apply controlled-Y gates over consecutive control/target pairs.
Full docstring
Apply controlled-Y gates over consecutive control/target pairs.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
truncateboolSee
TruncatingCliffordMixin.x.
Apply an S adjoint gate (sqrt(Z) dagger) to each target qubit.
Full docstring
Apply an S adjoint gate (sqrt(Z) dagger) to each target qubit.
Parameters
*targetsThe indices of the target qubits.
truncateboolSee
TruncatingCliffordMixin.x.
Apply a sqrt(X) gate to each target qubit.
Full docstring
Apply a sqrt(X) gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
truncateboolSee
TruncatingCliffordMixin.x.
Apply a sqrt(X) adjoint gate to each target qubit.
Full docstring
Apply a sqrt(X) adjoint gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
truncateboolSee
TruncatingCliffordMixin.x.
Apply a sqrt(Y) gate to each target qubit.
Full docstring
Apply a sqrt(Y) gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
truncateboolSee
TruncatingCliffordMixin.x.
Apply a sqrt(Y) adjoint gate to each target qubit.
Full docstring
Apply a sqrt(Y) adjoint gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
truncateboolSee
TruncatingCliffordMixin.x.
Apply CNOT (controlled-X) gates over consecutive control/target pairs.
Full docstring
Apply CNOT (controlled-X) gates over consecutive control/target pairs.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
truncateboolSee
x.
Apply CZ (controlled-Z) gates over consecutive qubit pairs.
Full docstring
Apply CZ (controlled-Z) gates over consecutive qubit pairs.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
truncateboolSee
x.
Apply a Hadamard gate to each target qubit.
Full docstring
Apply a Hadamard gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
truncateboolSee
x.
Apply an S gate (sqrt(Z)) to each target qubit.
Full docstring
Apply an S gate (sqrt(Z)) to each target qubit.
Parameters
*targetsThe indices of the target qubits.
truncateboolSee
x.
Apply a Pauli X gate to each target qubit.
Full docstring
Apply a Pauli X gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
truncateboolIf
True(default), run the configured truncation strategy after the gate; ifFalse, leave the map untruncated so the next gate sees the full unpruned state.
Apply a Pauli Y gate to each target qubit.
Full docstring
Apply a Pauli Y gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
truncateboolSee
x.
Apply a Pauli Z gate to each target qubit.
Full docstring
Apply a Pauli Z gate to each target qubit.
Parameters
*targetsThe indices of the target qubits.
truncateboolSee
x.
Apply a single-qubit depolarizing channel to each target qubit.
Full docstring
Apply a single-qubit depolarizing channel to each target qubit.
Parameters
*targetsThe indices of the target qubits.
pThe depolarizing probability.
truncateboolSee
pauli_error.
Apply a two-qubit depolarizing channel over consecutive qubit pairs.
Full docstring
Apply a two-qubit depolarizing channel over consecutive qubit pairs.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
pThe depolarizing probability.
truncateboolSee
pauli_error.
Apply a single-qubit Pauli error channel to each target qubit.
Full docstring
Apply a single-qubit Pauli error channel to each target qubit.
Parameters
*targetsThe indices of the target qubits.
pError probabilities [p_x, p_y, p_z] for X, Y, Z errors. The identity probability is implicitly 1 - sum(p).
truncateboolIf
True(default), run the configured truncation strategy after the channel; ifFalse, defer it.
Apply a two-qubit Pauli error channel over consecutive qubit pairs.
Full docstring
Apply a two-qubit Pauli error channel over consecutive qubit pairs.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
pError probabilities for the 15 non-identity two-qubit Pauli operators. Use two_qubit_pauli_error_probabilities to convert from a dictionary format.
truncateboolSee
pauli_error.
Apply an X error channel to each target qubit.
Full docstring
Apply an X error channel to each target qubit.
Parameters
*targetsThe indices of the target qubits.
pThe probability of applying an X error.
truncateboolSee
pauli_error.
Apply a Y error channel to each target qubit.
Full docstring
Apply a Y error channel to each target qubit.
Parameters
*targetsThe indices of the target qubits.
pThe probability of applying a Y error.
truncateboolSee
pauli_error.
Apply a Z error channel to each target qubit.
Full docstring
Apply a Z error channel to each target qubit.
Parameters
*targetsThe indices of the target qubits.
pThe probability of applying a Z error.
truncateboolSee
pauli_error.
Apply a rotation about an axis in the X-Y plane to the specified qubit.
Full docstring
Apply a rotation about an axis in the X-Y plane to the specified qubit.
See RotationsMixin.r for the gate definition.
Parameters
addr0intThe index of the target qubit.
axis_anglefloatThe angle
φ(in radians) of the rotation axis within the X-Y plane, measured from the X-axis.thetafloatThe rotation angle in radians.
truncateboolSee
rx.
Apply an RX rotation gate to each target qubit.
Full docstring
Apply an RX rotation gate to each target qubit.
See RotationsMixin.rx for the gate definition.
Parameters
*targetsThe indices of the target qubits.
thetaThe rotation angle in radians.
truncateboolIf
True(default), run the configured truncation strategy after the gate; ifFalse, defer it.
Apply RXX (Ising XX) rotation gates over consecutive qubit pairs.
Full docstring
Apply RXX (Ising XX) rotation gates over consecutive qubit pairs.
See RotationsMixin.rxx for the gate definition.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
thetaThe rotation angle in radians.
truncateboolIf
True(default), run the configured truncation strategy after the gate. Set toFalseto compose a U(1)-conserving step likerxx + ryyon the same edge without dropping the conserved-charge component between them — then callPauliSum.truncateonce at the end of the composition.
Apply an RY rotation gate to each target qubit.
Full docstring
Apply an RY rotation gate to each target qubit.
See RotationsMixin.ry for the gate definition.
Parameters
*targetsThe indices of the target qubits.
thetaThe rotation angle in radians.
truncateboolSee
rx.
Apply RYY (Ising YY) rotation gates over consecutive qubit pairs.
Full docstring
Apply RYY (Ising YY) rotation gates over consecutive qubit pairs.
See RotationsMixin.ryy for the gate definition.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
thetaThe rotation angle in radians.
truncateboolSee
rxx.
Apply an RZ rotation gate to each target qubit.
Full docstring
Apply an RZ rotation gate to each target qubit.
See RotationsMixin.rz for the gate definition.
Parameters
*targetsThe indices of the target qubits.
thetaThe rotation angle in radians.
truncateboolSee
rx.
Apply RZZ (Ising ZZ) rotation gates over consecutive qubit pairs.
Full docstring
Apply RZZ (Ising ZZ) rotation gates over consecutive qubit pairs.
See RotationsMixin.rzz for the gate definition.
Parameters
*targetsA flat list of qubit indices, broadcast as pairs.
thetaThe rotation angle in radians.
truncateboolSee
rxx.
paulisum
A PauliSum that supports modelling qubit loss.
Full docstring
A PauliSum that supports modelling qubit loss.
This is achieved by extending the set of Pauli basis operators to include
an addition operator {I, X, Y, Z, L}, where L is the projector on
a third loss state |L⟩. Distinct from leakage on
GeneralizedTableau, which pins a qubit to |0⟩/|1⟩. This basis
effectively allows simulating qutrits, where we neglect any coherences
between the qubit subspace and the loss state.
In addition to the new channels, there is also another truncation strategy:
Since Pauli Strings that have an L at multiple positions contribute only
minimally, these can get truncated by setting an appropriate max_loss_weight.
The truncation is similar to how max_pauli_weight truncates strings, but only
counting Ls.
A weighted sum of Pauli strings for quantum simulation.
Full docstring
A weighted sum of Pauli strings for quantum simulation.
PauliSum represents a linear combination of Pauli operators, commonly used to represent quantum observables or Hamiltonians. It provides methods for applying quantum gates (Clifford operations and rotations) and computing expectation values via the trace operation.
Apply a correlated loss channel.
Full docstring
Apply a correlated loss channel.
This applies a correlated loss channel to the qubits at addr0 and addr1.
The channel accepts 3 probabilities as argument:
* p[0]: The probability of losing both qubits, when they are originally
in the qubit subspace.
* p[1]: The probability of losing a named one of the two qubits,
when both qubits are originally in the qubit subspace. The two
single-loss events are disjoint, so the probability of losing
exactly one qubit is 2 * p[1], and the probability that
both qubits remain in the qubit subspace — the factor a fully
in-subspace observable is scaled by — is 1 - 2 * p[1] - p[0].
* p[2]: The probability of losing one qubit when the other one
has already been lost prior to applying the channel. This is to
account for the fact that when one qubit is missing during e.g.
a controlled gate, the remaining qubit undergoes a different dynamic.
We account for this difference with this distinct probability.
truncate: If True (default), run the configured truncation
strategy after the channel; if False, defer it.
Apply a single-qubit loss channel.
Full docstring
Apply a single-qubit loss channel.
Reduces the trace of qubit-subspace operators by (1 - p).
Adds back population into I or Z if the Pauli string has an L
at addr0. This can only occur if a reset channel has been applied before
and accounts for the fact of falsely counting a lost qubit as 0 in a
measurement.
Parameters
addr0intThe index of the target qubit.
pfloatLoss probability in [0, 1].
truncateboolIf
True(default), run the configured truncation strategy after the channel; ifFalse, defer it.
Not available on LossyPauliSum.
Full docstring
Not available on LossyPauliSum.
Raises
NotImplementedErroralways, for the same reason as
symmetry_merge.
Reset a lost qubit to the 0 state. Usually, you want to apply this channel at the end of the circuit, i.e. at the beginning when propagating backwards.
Full docstring
Reset a lost qubit to the 0 state. Usually, you want to apply this channel at the end of the circuit, i.e. at the beginning when propagating backwards.
NOTE: This channel causes exponential branching in I and Z.
Make sure to set an appropriate max_loss_weight to truncate.
Parameters
addr0intThe index of the qubit to reset.
truncateboolIf
True(default), run the configured truncation strategy after the channel; ifFalse, defer it.
Not available on LossyPauliSum.
Full docstring
Not available on LossyPauliSum.
Raises
NotImplementedErroralways. Canonicalizing a lossy Pauli word would have to permute the loss bitmap along with the Pauli alphabet, which the Rust core does not implement.
Apply an amplitude-damping channel.
Full docstring
Apply an amplitude-damping channel.
Parameters
addr0intThe index of the target qubit.
gammafloatThe damping rate.
XandYare damped withsqrt(1 - gamma), whereasZbranches intogamma * I + (1 - gamma) * Z.truncateboolIf
True(default), run the configured truncation strategy after the channel; ifFalse, defer it (usetruncateto fire the cut later).
Create a copy of the PauliSum instance.
Full docstring
Create a copy of the PauliSum instance.
Returns
SelfA new PauliSum instance that is a copy of the current one.
Get the current maximum weight of the Pauli sum.
Full docstring
Get the current maximum weight of the Pauli sum.
Returns
intThe weight as integer.
Phase-aware (momentum-sector) merge for a complex operator stored as a real pair: self is the real part and other the imaginary part of O = self + i·other. Both are overwritten in place with the orbit-representative form pr…
Full docstring
Phase-aware (momentum-sector) merge for a complex operator stored
as a real pair: self is the real part and other the
imaginary part of O = self + i·other. Both are overwritten in
place with the orbit-representative form projected onto momentum
sector momentum.
Generalizes symmetry_merge to non-trivial momentum sectors
(k != 0) while keeping real coefficients on both PauliSums — the
only complex arithmetic is the internal character-weighted fold. Like
symmetry_merge it is the summing projector
Σ_{p in orbit} χ_k(g_p)·c_p, hence idempotent on every orbit and
safe to apply after each Trotter step; at momentum=[0, ...] it
reduces exactly to symmetry_merge.
self and other must be distinct objects with the same qubit
count. Exact after a translation-covariant gate layer; under a
generic Trotter step it carries the same O(dt^{p+1}) equivariance
error as the k=0 merge.
Parameters
otherPauliSumthe PauliSum holding the imaginary component (modified in place).
groupa
ppvm.TranslationGroup.momentumsequence of integer modes, one per group generator (e.g.
[k]for a 1D chain;[0, ...]is the trivial sector).
Create a PauliSum from one or more terms with flexible input formats.
Full docstring
Create a PauliSum from one or more terms with flexible input formats.
Parameters
n_qubitsintNumber of qubits.
termsA single term or list of terms. Each term is either:
- A full Pauli string (e.g.
"IX"), with coefficient 1.0. - A compact string
"P{i}"(e.g."X1"), placing Pauli P at 0-based qubit index i with coefficient 1.0. - A tuple
(str, float)pairing either of the above with an explicit coefficient.
- A full Pauli string (e.g.
min_abs_coefffloatTerms with absolute coefficient below this threshold are dropped. Defaults to 1e-10.
max_pauli_weightMaximum number of non-identity Paulis per term. If None, truncation is disabled.
max_loss_weightMaximum loss weight per term (only used by LossyPauliSum). If None, truncation is disabled. Note, that this should usually be chosen to be quite low, since e.g. 10 would correspond to keeping terms that contribute if up to 10 qubits are lost simultaneously.
preserve_stringsPauli strings (length
n_qubitseach) that truncation must never drop. Empty by default.
Returns
SelfA new instance of the class this method is called on.
Raises
ValueErrorIf a compact qubit index is out of range for n_qubits.
Compute the overlap of the current PauliSum with another PauliSum. The overlap is defined as
Full docstring
Compute the overlap of the current PauliSum with another PauliSum. The overlap is defined as
math \text{tr}(A^\dagger \cdot B),
where self -> A other -> B
Returns
floatThe trace overlap of the PauliSums.
Compute the overlap with the all-zeros computational basis state.
Full docstring
Compute the overlap with the all-zeros computational basis state.
Returns
floatThe expectation value of the Pauli sum with respect to |0...0>.
Merge entries into orbit-representative form under a translation group.
Full docstring
Merge entries into orbit-representative form under a translation group.
Each Pauli word in the sum is replaced by its canonical (lex-min)
representative under the action of group; coefficients of words
that collapse to the same representative are summed. Entry count
reduces by up to |group|× for translation-invariant operators.
For a translation-invariant dynamics that you apply between
merging steps, this preserves all group-invariant expectation
values (Theorem 1 of Teng et al., arXiv:2512.12094). Plain
real-coefficient merge — handles the trivial (k=0) momentum
sector only.
Parameters
groupA
ppvm.TranslationGroup(useTranslationGroup.chain_1d(n),.torus_2d,.torus_3d,.ladder, or.from_generators).
Compute the trace using a pattern string.
Full docstring
Compute the trace using a pattern string.
Parameters
patternstrA pattern specifying which terms to include in the trace. Use 'Z' to project onto |0>, '?' for any single character, and '*' to match zero or more characters.
Returns
floatThe trace result.
Run the configured truncation strategy (min_abs_coeff and/or max_pauli_weight) on the current state.
Full docstring
Run the configured truncation strategy (min_abs_coeff and/or
max_pauli_weight) on the current state.
Useful when gates were called with truncate=False to chain a
composition of commuting operations (e.g. rxx + ryy on the
same edge, an exchange-like step that conserves total Z), so
that intermediate truncation does not drop conserved-charge
components. Call truncate once at the end of the
composition to apply the cut to the combined result.
Get the weight of each Pauli term.
Full docstring
Get the weight of each Pauli term.
Returns
A list of tuples, each containing a Pauli string and its weight.
Get the list of Pauli terms and their coefficients.
Full docstring
Get the list of Pauli terms and their coefficients.
Returns
A list of tuples, each containing a Pauli string and its coefficient.
squin_interpreter
TODO: once we open-source, all of this will be moved into bloqade-circuit
Implementations for the Squin interpreter.
Apply CCZ using seven T/T-adjoint gates and six CNOTs.
symmetry
Translation-symmetry merging of Pauli sums.
Full docstring
Translation-symmetry merging of Pauli sums.
A TranslationGroup is a finite abelian group acting on qubit positions by
permutation. Every Pauli word then belongs to a translation orbit, and
dynamics that commutes with the group can be tracked using one canonical
representative per orbit instead of all |G| members — cutting per-step
memory and compute by up to |G|× (Teng et al., arXiv:2512.12094).
Two representations are supported:
ppvm.PauliSum.symmetry_merge/ppvm.PauliSum.momentum_mergefor the dictionary representation used by gate-based Trotter evolution.- the
*_arrfunctions here for the(basis_arr, coeffs)array representation used byppvm.Lindbladian.pc_step_arrandppvm.Lindbladian.pc_step_orbit_rep, wherebasis_arris an(N, n_qubits)uint8 array with the encoding0=I, 1=X, 2=Z, 3=Y.
These are thin wrappers over ppvm._core that coerce their arguments to the
dtypes the compiled entry points require (uint8 basis, float64 / complex128
coefficients, int32 momentum), so plain Python lists and default-dtype numpy
arrays work.
Merge a real-coefficient (basis_arr, coeffs) Pauli sum into orbit-representative form.
Full docstring
Merge a real-coefficient (basis_arr, coeffs) Pauli sum into
orbit-representative form.
Each row of basis_arr is replaced by its canonical representative
under group; coefficients of rows collapsing to the same
representative are summed. The output is no longer than the input.
This is the trivial (k=0) symmetry sector. For dynamics that commutes
with group and a group-invariant initial state, it preserves every
group-invariant expectation value. Use canonicalize_basis_arr_complex
for non-trivial momentum sectors.
Parameters
basis_arr(N, n_qubits)array of Pauli codes.coeffslength-
Nreal coefficients.groupTranslationGroupthe symmetry group to merge under.
Returns
(merged_basis_arr, merged_coeffs).
Phase-aware merge of a complex-coefficient (basis_arr, coeffs) Pauli sum into orbit-representative form, projected onto momentum sector momentum.
Full docstring
Phase-aware merge of a complex-coefficient (basis_arr, coeffs)
Pauli sum into orbit-representative form, projected onto momentum sector
momentum.
Coefficients on each orbit's distinct members are averaged with the
character weight χ_k(g) — a 1/|orbit| normalization that
canonicalize_basis_arr (which sums) does not apply. Orbits whose
stabilizer cannot carry momentum project to zero and are dropped.
If the input does not actually lie in sector momentum, the projection
silently discards the other components; call check_momentum_sector_arr
first to validate.
Parameters
basis_arr(N, n_qubits)array of Pauli codes.coeffslength-
Ncomplex coefficients.groupTranslationGroupthe symmetry group to merge under.
momentumone integer mode index per group generator. The wavenumber along generator
gis2π · momentum[g] / order_g;[0, ...]is the trivial sector.
Returns
(merged_basis_arr, merged_coeffs)with complex coefficients.
Verify that a (basis_arr, complex_coeffs) Pauli sum lies entirely in momentum sector momentum.
Full docstring
Verify that a (basis_arr, complex_coeffs) Pauli sum lies entirely
in momentum sector momentum.
For every orbit represented in the basis, all members must satisfy
c_{g·r} = χ_k(g)⁻¹ · c_r. Orbit members absent from basis_arr
count as zero rather than being ignored, so a partially-populated orbit
fails.
Run this on a user-supplied initial state before feeding it to
canonicalize_basis_arr_complex or
ppvm.Lindbladian.pc_step_orbit_rep — silently projecting a
wrongly-typed input throws away meaningful physics.
Parameters
basis_arr(N, n_qubits)array of Pauli codes.coeffslength-
Ncomplex coefficients.groupTranslationGroupthe symmetry group.
momentumone integer mode index per group generator.
tolfloatrelative tolerance on the coefficient comparison.
Raises
ValueErrorif the input is not in the sector, naming the offending orbit representative with its expected and actual coefficient.
Rustcrates
ppvm-traits
Trait system, the `Config` bundle, the `Pauli` alphabet, and map impls.
Foundational trait system, Config trait, single-qubit Pauli alphabet,
and the ACMap/Trace map implementations shared across ppvm crates.
Strategy that never truncates — exact simulation, all entries kept.
A single-qubit Pauli symbol.
Full docstring
A single-qubit Pauli symbol.
The four standard Paulis are encoded so that the low two bits identify
the operator (I = 0b00, X = 0b01, Z = 0b10, Y = 0b11), which is
the same encoding stabilizer-formalism tools commonly use. The extra
variant Pauli::L marks a qubit as lost, used by the loss-aware
portions of the runtime.
Examples
use ppvm_traits::char::Pauli;
assert_eq!(Pauli::I.to_string(), "I");
assert_eq!(Pauli::X.to_string(), "X");
assert_eq!(Pauli::Y.to_string(), "Y");
assert_eq!(Pauli::Z.to_string(), "Z");
assert_eq!(Pauli::L.to_string(), "L");
Compile-time configuration bundle for a PauliSum.
Full docstring
Compile-time configuration bundle for a PauliSum.
Config is a zero-cost generic dispatch mechanism: it pins down the
storage backing (Storage), coefficient type (Coeff), truncation
strategy (Strategy), hasher (BuildHasher), Pauli-word representation
(PauliWordType), and concrete map (Map) used by a single
PauliSum instantiation. Pre-built bundles live in the submodules
(fxhash, indexmap, …); user code may define its own.
Controlled RX rotation.
Projective Z-basis projectors |0⟩⟨0| and |1⟩⟨1|.
Single-qubit Pauli rotations exp(-i θ/2 · P).
Rotation about an axis in the x/y plane:
R(axis_angle, θ) = exp(-i θ/2 · (cos(axis_angle)·X + sin(axis_angle)·Y)).
Full docstring
Rotation about an axis in the x/y plane:
R(axis_angle, θ) = exp(-i θ/2 · (cos(axis_angle)·X + sin(axis_angle)·Y)).
The in-plane axis is X rotated about Z by axis_angle, so
R(axis_angle, θ) = RZ(axis_angle)·RX(θ)·RZ(−axis_angle).
Two-qubit Pauli rotations, generated by P_a ⊗ P_b for any pair of
non-identity Paulis. Provides the named convenience methods
rxx, rxy, …, rzz on top of the generic [rotate_2].
Full docstring
Two-qubit Pauli rotations, generated by P_a ⊗ P_b for any pair of
non-identity Paulis. Provides the named convenience methods
rxx, rxy, …, rzz on top of the generic rotate_2.
The non-Clifford T gate and its adjoint.
Full docstring
The non-Clifford T gate and its adjoint.
T = diag(1, e^{iπ/4}). Implemented by the simulator backends; see
the example in ppvm_tableau.
The general single-qubit U3(θ, φ, λ) gate.
The minimal Clifford gate set: the single-qubit Paulis (X, Y, Z),
Hadamard (H), phase gate (S), and the two entangling Cliffords
CNOT and CZ.
Full docstring
The minimal Clifford gate set: the single-qubit Paulis (X, Y, Z),
Hadamard (H), phase gate (S), and the two entangling Cliffords
CNOT and CZ.
Implemented by PauliSum, by every tableau type, and — via the
blanket impl in this module — by every PauliWordTrait
implementor.
Examples
Build the GHZ-preparation circuit on a PauliSum (Heisenberg picture,
so gates are applied in reverse). PauliSum lives in the downstream
ppvm-pauli-sum crate, so this example is ignored here:
use ppvm_pauli_sum::prelude::*;
let mut state: PauliSum<config::indexmap::ByteFxHashF64<1>> =
PauliSum::builder().n_qubits(2).build();
state += ("ZZ", 1.0);
state.cnot(0, 1);
state.h(0);
assert_eq!(state.len(), 1);
Batched Clifford gates: apply the same gate to many qubits in one call.
Full docstring
Batched Clifford gates: apply the same gate to many qubits in one call.
Default implementations loop over the corresponding single-qubit
(or single-pair) method on Clifford. Types like the stabilizer
Tableau override these methods with a fused inner-loop or bitmask
implementation. Types that don't need specialization can implement
this trait with an empty impl to use the defaults.
Additional Clifford gates beyond the minimal set: S†, √X, √X†,
√Y, √Y†, and CY.
Batched form of CliffordExtensions.
Numeric coefficient type usable inside a
PauliSum.
Full docstring
Numeric coefficient type usable inside a
PauliSum.
Coefficient bundles every arithmetic operation a Pauli-propagation
step needs — addition, multiplication, signed multiplication, half,
sin/cos, and a cutoff predicate used by truncation strategies. The
built-in f64 impl covers the common case; Complex<f64> is
available when phase tracking is required.
A Coefficient extended with multiplication by a fourth-root-of-unity
phase. Used by PhasedPauliWord.
Computes and finalizes cached Pauli-word hashes. Custom hashers can use the defaults with an empty implementation.
Aggregate trait combining every operation a backing map must support
to be usable as the storage for a PauliSum.
Full docstring
Aggregate trait combining every operation a backing map must support
to be usable as the storage for a PauliSum.
You don't normally implement ACMap directly: the blanket impl below
covers any type that implements all the constituent traits.
Map-backend implementor's guide
A new backing map (a GPU-resident map, a sharded map, anything beyond
the existing HashMap / IndexMap / AHashMap / DashMap backends)
needs these to satisfy the ACMap bound itself:
Clone.ACMapBase— construction, length, clear.ACMapAddAssign—+=insert-or-accumulate.ACMapMulAssign— scalar*=.ACMapInsert— justmap_insert_vecandmap_insert_multiple(there is no third variant to implement).ACMapContains— membership queries.ACMapScale— in-place per-entry transform.ACMapRetain— predicate-based entry removal.ACMapConsume— drain-and-accumulate merge of two maps.
Satisfying ACMap is necessary but not sufficient: ppvm-pauli-sum
bounds individual operations on further traits, so a backend that skips
them only fails to compile at those call sites. In practice you also
want:
ACMapIter— borrowing iteration over(key, value); needed byPauliSum::iter,Display, and the approximate-comparison helpers.Trace— needed byPauliSum::trace.Extend<(Word, Coeff)>— needed by the arithmetic operators.PartialEq— needed byPauliSum's approximate comparisons.
Of these, map_insert_vec, map_insert_multiple, scale,
mul_assign, retain, and consume are whole-collection batch entry
points: a concurrent or GPU backend can dispatch each of them as one
parallel pass over every entry. add_assign is the exception — it
operates on a single key at a time, so a thread-pool backend typically
only parallelizes its batch sibling, map_add_assign. See the
DashMap impl in crates/ppvm-traits/src/map/dashmap.rs for a working
concurrent precedent: map_add_assign, mul_assign, map_insert_vec,
map_insert_multiple, scale, consume, and trace all go through
rayon par_iter. retain is the one that does not — its FnMut
predicate is not shareable across threads, so DashMap forwards to the
sequential DashMap::retain.
+= semantics for an ACMap: insert a new entry or accumulate into
the existing one with the same key.
Minimal interface for any "associative coefficient map" backing a
PauliSum — construction, length, and clear.
Full docstring
Minimal interface for any "associative coefficient map" backing a
PauliSum — construction, length, and clear.
Implementations exist for HashMap, IndexMap, and DashMap; pick
one via a Config.
Merge two maps with accumulation: drain dest into self,
summing values that share a key.
Membership queries — (key, value) exact match or with a custom
predicate on the value.
In-place modify + insert pattern used to express branching gates (where one input entry can produce zero, one, or several output entries).
Borrowing iteration over an ACMap. Lives in its own trait so that
implementations may pick their own item / iterator types.
Scalar *= semantics for an ACMap: multiply every value by a
constant.
Drop entries that don't satisfy a predicate — used by truncation strategies.
In-place per-entry transformation of values.
Loss-aware Z-basis measurement.
Projective Z-basis measurement returning a bare boolean outcome.
Amplitude-damping channel (single qubit).
State-dependent ("asymmetric") single-qubit loss channel: a qubit is
lost from |0⟩ with probability p0 and from |1⟩ with probability
p1. Unlike LossChannel, the total loss probability depends on the
qubit's populations, so th…
Full docstring
State-dependent ("asymmetric") single-qubit loss channel: a qubit is
lost from |0⟩ with probability p0 and from |1⟩ with probability
p1. Unlike LossChannel, the total loss probability depends on the
qubit's populations, so the channel reads the current ⟨Z⟩.
Correlated two-qubit loss channel.
Full docstring
Correlated two-qubit loss channel.
The p[1] convention (normative)
This is the one place the parameterization is defined; every backend
(ppvm-pauli-sum, ppvm-tableau's trajectory, ppvm-tableau-sum's mixture)
and every binding cites it rather than restating it. In the paper's notation
p = [p_LL, p_LQ, p_LN], and p[1] = p_LQ is the probability that a
named one of the two atoms is lost while the other survives. The two
single-loss events are disjoint, so
- the probability of losing exactly one atom is
2·p[1], and - the probability that both remain in the qubit subspace — the factor a
fully in-subspace observable is scaled by — is
1 − 2·p[1] − p[0].
The channel is completely positive exactly on p[0], p[1] >= 0,
p[0] + 2·p[1] <= 1, p[2] ∈ [0, 1]; the tableau backends debug_assert
that region.
Single-qubit depolarizing channel.
Two-qubit depolarizing channel.
Single-qubit leakage channel — with probability p0 the qubit is
leaked and pinned to |0⟩, with probability p1 leaked and pinned
to |1⟩. Unlike LossChannel, a leaked qubit remains measurable
and returns the pinned computationa…
Full docstring
Single-qubit leakage channel — with probability p0 the qubit is
leaked and pinned to |0⟩, with probability p1 leaked and pinned
to |1⟩. Unlike LossChannel, a leaked qubit remains measurable
and returns the pinned computational bit; gates still skip it.
Single-qubit loss channel — with probability p, mark the qubit as
lost (Pauli::L).
Single-qubit Pauli error channel — apply X, Y, or Z with the
three given probabilities.
Reset leakage on a qubit — used to model a leakage-reduction event
that returns a previously-leaked qubit to the computational subspace
in |0⟩.
Reset the loss bit on a qubit — used to model a re-cooling / re-loading event that brings a previously-lost atom back.
Two-qubit Pauli error channel.
Reset one qubit to a computational/Pauli basis state.
Reset the state of a live qubit to |0⟩, leaving lost and leaked qubits
untouched.
Full reset to |0⟩ of a single Pauli word, in the Heisenberg picture.
Full docstring
Full reset to |0⟩ of a single Pauli word, in the Heisenberg picture.
Pauli-propagation backends build Reset from this: each term maps to
the words returned here, each carrying the term's coefficient.
Backing storage for a PauliWord — a
fixed-size, Copy-able block of bits (typically [u8; N] or
[u64; N]).
Full docstring
Backing storage for a PauliWord — a
fixed-size, Copy-able block of bits (typically [u8; N] or
[u64; N]).
The bytemuck::Pod bound guarantees the storage is a plain-old-data
type with no padding and all bit patterns valid, which lets
PauliWord::rehash view it as a &[u8] for
fast byte-slice hashing without unsafe. Every concrete storage used
here ([u8; N], [u64; N]) is already Pod.
A truncation policy applied to a PauliSum
during Pauli propagation.
Full docstring
A truncation policy applied to a PauliSum
during Pauli propagation.
The strategy controls two things: the initial capacity allocated
for the underlying map (estimating how many Pauli paths the
simulation is expected to generate) and the cut applied when
truncate is called explicitly. Implementations
include NoStrategy, the coefficient-magnitude threshold, the
max-Pauli-weight bound, etc.
Trait for computing trace(self * RHS).
Full docstring
Trait for computing trace(self * RHS).
If a type implements Trace, a corresponding TraceBy implementation
is also provided automatically.
Iterate over a Pauli word slot-by-slot.
Word-level Pauli operations. Types implementing this trait automatically
gain crate::traits::Clifford and crate::traits::CliffordExtensions
behavior via blanket impls in the crate::traits::clifford module, using
get_lbit / `g…
Full docstring
Word-level Pauli operations. Types implementing this trait automatically
gain crate::traits::Clifford and crate::traits::CliffordExtensions
behavior via blanket impls in the crate::traits::clifford module, using
get_lbit / get_xbit / set_xbit / set_zbit / rehash to transform
Pauli words.
Word-level vs. state-level gate semantics
The blanket Clifford impl applies gates at the bit level of a single
Pauli word. X / Y / Z are bit-level no-ops on a Pauli word — they affect
phase, not the X/Z bits — so word.x(i), word.y(i), word.z(i) are
deliberately silent. Phase is tracked separately by
PhasedPauliWord, which implements Clifford manually.
If you need a word representation whose gate behavior is not pure
bit manipulation (phase tracking, fused multi-qubit updates, alternative
loss semantics), do not implement PauliWordTrait on it — define a
specialized Clifford impl instead, the way PhasedPauliWord does.
Implementing both PauliWordTrait and a custom impl Clifford for ...
for the same type will not compile: the blanket impl overlaps with your
custom impl (coherence error), not silently shadows it.
Fast hasher for internal maps and word hashes, with a fixed seed. Iteration is reproducible for the same build and insertion order.
A HashMap using FoldBuildHasher.
ppvm-pauli-word
Packed Pauli strings: `PauliWord`, phased, lossy, and pattern variants.
Packed Pauli-word types: PauliWord, PhasedPauliWord, LossyPauliWord,
and PauliPattern. Built on the ppvm-traits foundation.
A PauliWord-like type that additionally
tracks per-qubit loss.
Full docstring
A PauliWord-like type that additionally
tracks per-qubit loss.
In neutral-atom hardware (and in any loss-aware error model), a
measurement can return "lost" instead of 0 or 1. LossyPauliWord
adds a parallel lbits array marking which qubits have been lost; a
set loss bit excludes that qubit from the standard Pauli operations
and shows up as the Pauli::L symbol.
Examples
use ppvm_traits::char::Pauli;
use ppvm_pauli_word::loss::LossyPauliWord;
use ppvm_traits::traits::PauliWordTrait;
let w: LossyPauliWord<[u8; 1]> = "XLZL".into();
assert_eq!(w.weight(), 4); // X, L, Z, L are all non-identity
assert_eq!(w.loss_weight(), 2); // two qubits are lost
assert!(w.is(1, Pauli::L));
assert!(w.is(0, Pauli::X));
A Pauli pattern representing a set of matching Pauli words.
Full docstring
A Pauli pattern representing a set of matching Pauli words.
Example
[XY]2Z3 represents X2Z3 or Y2Z3.
Z? represents any Pauli word with I or Z.
Iterator over the concrete [PauliWord]s accepted by a [PauliPattern].
A PauliWord paired with one of the four fourth-roots of unity.
Full docstring
A PauliWord paired with one of the four fourth-roots of unity.
The phase field encodes the scalar prefactor:
phase |
scalar |
|---|---|
0 |
+1 |
1 |
+i |
2 |
-1 |
3 |
-i |
(i.e. the low bit is the imaginary flag and the high bit is the sign.)
Examples
use ppvm_pauli_word::phase::PhasedPauliWord;
// Parse from a "[sign][i]<PauliString>" literal.
let pw: PhasedPauliWord<u64> = "+iXYZI".into();
assert_eq!(pw.n_qubits(), 4);
assert_eq!(pw.phase, 1); // +i
assert!(pw.is_positive());
let neg: PhasedPauliWord<u64> = "-XYZI".into();
assert_eq!(neg.phase, 2); // -1
assert!(!neg.is_positive());
A fixed-width Pauli string stored as parallel x and z bit arrays.
Full docstring
A fixed-width Pauli string stored as parallel x and z bit arrays.
Each qubit slot is encoded by two bits, (x, z), giving the four
Pauli operators I = (0,0), X = (1,0), Z = (0,1), Y = (1,1) —
the same encoding stabilizer-formalism tools use. The bit arrays live
in a single PauliStorage blob (typically [u8; N] or [u64; N]),
so a PauliWord<[u8; 1]> packs up to 8 qubits, [u8; 2] up to 16,
etc.
A cached hash speeds up use as a map key; pass REHASH = false if
you build words in bulk and want to control rehashing manually.
Examples
use ppvm_traits::char::Pauli;
use ppvm_traits::traits::PauliWordTrait;
use ppvm_pauli_word::word::PauliWord;
// Build a word from a string …
let w: PauliWord<[u8; 1]> = "XYZI".into();
assert_eq!(w.n_qubits(), 4);
assert_eq!(w.get(0), Pauli::X);
assert_eq!(w.get(3), Pauli::I);
// … or build it slot-by-slot.
let mut w2: PauliWord<[u8; 1]> = PauliWord::new(2);
w2.set(0, Pauli::X).set(1, Pauli::Y);
assert_eq!(w2.to_string(), "XY");
assert_eq!(w2.weight(), 2);
A single-qubit Pauli that is not the identity: X, Y, or Z. Encoded so
the low two bits match Pauli (X = 1, Z = 2, Y = 3),
which lets From<NotIdentity> for Pauli be a no-op transmute.
Membership test for pattern types.
Full docstring
Membership test for pattern types.
Implemented by Pauli patterns over symbols (Contains<Pauli>) and
over whole words (Contains<W: PauliIter>); used by the masking
machinery to ask "does this pattern accept this concrete word?"
ppvm-pauli-sum
The `PauliSum` engine, truncation strategies, and concrete config bundles.
PauliSum Pauli-propagation engine, truncation
strategies, and pre-built Config bundles. Built on ppvm-traits and
ppvm-pauli-word.
Pre-built configs backed by dashmap::DashMap for concurrent access.
Native-only: dashmap pulls rayon, which needs OS threads, so this
module is unavailable on wasm32.
Pre-built configs using rustc-hash's FxHasher and f64 coefficients.
Pre-built configs using FxHasher.
Pre-built configs backed by indexmap::IndexMap, preserving
insertion order — useful for deterministic iteration and snapshot
testing.
Drop-in replacement for the old ppvm_runtime::prelude.
Lattice translation symmetry groups for operator-space Pauli evolution.
Full docstring
Lattice translation symmetry groups for operator-space Pauli evolution.
A TranslationGroup represents a finite abelian group G acting on
qubit positions by permutations. Given such a group, every Pauli word
belongs to a translation orbit, and operator dynamics that commute
with G can be tracked using one canonical representative per
orbit instead of all |G| orbit members — reducing per-step memory
and compute by a factor up to |G|.
Following Teng, Chang, Rudolph, and Holmes (arXiv:2512.12094), this
module implements plain (real-coefficient) merging of Pauli sums
into orbit-representative form — see canonicalize_pauli_sum and
symmetry_merge_pauli_sum. This handles observables in the trivial
(k=0) symmetry sector, e.g. sums of single-Z operators over the
lattice.
Non-trivial momentum sectors (k ≠ 0) fold with the character
phase χ_k(g) of each translation. Two conventions share one core:
canonicalize_pauli_sum_complex averages over each orbit's
distinct members (1/|orbit|), while
momentum_merge_pauli_sum_pair sums — the convention that is
idempotent on every orbit and reduces exactly to
symmetry_merge_pauli_sum at k = 0. Note |orbit| = |G| only for
free orbits, so the two are not related by a global |G| factor.
On the Python side, an operator in sector k is carried as a real
pair (real + imaginary components, two real PauliSums) and merged
via PauliSum.momentum_merge — letting gate-based Trotter evolution
stay symmetry-compressed in any momentum sector with real
coefficients throughout.
Data model
A TranslationGroup is specified by a list of generator permutations
and their exact cyclic orders. TranslationGroup::order is the
abstract product of those orders. The combined permutation action need
not be faithful: different mixed-radix counters can induce the same
permutation, so the action may have a kernel and
TranslationGroup::orbit may repeat words. For instance, a 2D
L × L torus has two generators (translation in x and y) each of
order L.
Canonicalization
TranslationGroup::canonicalize returns the lex-minimum Pauli
word reachable from the input via group action. The ordering is the
standard Ord impl on PauliWord (compare xbits, then zbits).
All orbit members canonicalize to the same representative; orbits are
disjoint by construction, so the rep uniquely identifies the orbit.
Merging
canonicalize_pauli_sum takes parallel Vec<Word> / Vec<f64>
buffers (the representation used by ppvm-lindblad's adaptive
evolution) and replaces each Pauli by its canonical rep, summing
coefficients for collisions. The output is an orbit-rep basis with
coefficients equal to the sum of the input coefficients over each
orbit's members. For dynamics that commute with G and initial
states that are also G-invariant, this preserves the expectation
value of any G-invariant observable (Theorem 1 of arXiv:2512.12094).
This real-coefficient merge sums collisions. By contrast, complex
projection into the trivial (k=0) momentum sector averages over the
distinct members of each orbit. Non-trivial sectors incompatible with
an orbit stabilizer project that orbit to zero.
See the dedicated tests for correctness against full-basis evolution on small systems with no truncation.
DashMap-backed concurrent Config with [u8; N] storage and FxHasher.
HashMap-backed Config with native-word ([usize; N]) storage and
FxHasher.
Full docstring
HashMap-backed Config with native-word ([usize; N]) storage and
FxHasher.
The storage element is usize, i.e. the target's native machine word:
u64 on 64-bit targets (identical layout and performance to a hardcoded
[u64; N]) and u32 on 32-bit targets such as wasm32. Using usize
rather than u64 keeps this config available on every target — bitvec
only implements BitStore for u64 on 64-bit pointer widths, but always
implements it for usize. (The Byte8 name refers to the 64-bit word
this config packs into on native targets.)
HashMap-backed Config with [u8; N] storage and FxHasher.
IndexMap-backed Config with [u8; N] storage and FxHasher.
Drop terms whose coefficient magnitude falls below the given threshold.
Defaults to 1e-12.
Full docstring
Drop terms whose coefficient magnitude falls below the given threshold.
Defaults to 1e-12.
Examples
use ppvm_pauli_sum::prelude::*;
use ppvm_pauli_sum::strategy::CoefficientThreshold;
let strict = CoefficientThreshold(1e-6);
let mut state: PauliSum<config::indexmap::ByteFxHashF64<1, CoefficientThreshold>> =
PauliSum::builder().n_qubits(2).strategy(strict).build();
state += ("ZZ", 1.0);
state += ("XX", 1e-9); // below threshold
state.truncate();
assert_eq!(state.len(), 1); // the XX term was dropped
Two strategies run in sequence: S1 then S2.
Full docstring
Two strategies run in sequence: S1 then S2.
The capacity hint is the smaller of the two; truncation applies both policies in order, so use this when you want, e.g., "drop by coefficient threshold and cap maximum Pauli weight".
Drop terms whose loss weight (number of lost qubits) exceeds the
given bound. Only meaningful for LossyPauliWord.
Drop terms whose Pauli weight (number of non-identity slots) exceeds the given bound.
Full docstring
Drop terms whose Pauli weight (number of non-identity slots) exceeds the given bound.
Examples
use ppvm_pauli_sum::prelude::*;
use ppvm_pauli_sum::strategy::MaxPauliWeight;
// Keep only weight-1 terms.
let strat = MaxPauliWeight(1);
let mut state: PauliSum<config::indexmap::ByteFxHashF64<1, MaxPauliWeight>> =
PauliSum::builder().n_qubits(3).strategy(strat).build();
state += ("XII", 1.0); // weight 1, kept
state += ("XYI", 1.0); // weight 2, dropped
state.truncate();
assert_eq!(state.len(), 1);
Represents a [State] that has [IsUnset] implemented for all members.
Full docstring
Represents a [State] that has [IsUnset] implemented for all members.
This is the initial state of the builder before any setters are called.
Represents a [State] that has [IsSet] implemented for [State::Capacity].
Full docstring
Represents a [State] that has [IsSet] implemented for [State::Capacity].
The state for all other members is left the same as in the input state.
Represents a [State] that has [IsSet] implemented for [State::NQubits].
Full docstring
Represents a [State] that has [IsSet] implemented for [State::NQubits].
The state for all other members is left the same as in the input state.
Represents a [State] that has [IsSet] implemented for [State::PreserveStrings].
Full docstring
Represents a [State] that has [IsSet] implemented for [State::PreserveStrings].
The state for all other members is left the same as in the input state.
Represents a [State] that has [IsSet] implemented for [State::Strategy].
Full docstring
Represents a [State] that has [IsSet] implemented for [State::Strategy].
The state for all other members is left the same as in the input state.
A sparse formal sum Σ cᵢ Pᵢ of Pauli strings.
Full docstring
A sparse formal sum Σ cᵢ Pᵢ of Pauli strings.
The central data type of the Pauli-propagation backend. Keys are
PauliWord-shaped Pauli strings; values are
numeric coefficients. Generic over a Config that fixes the
concrete storage / hasher / coefficient / strategy.
Internally PauliSum holds two maps — a primary and an auxiliary —
and swaps between them during gate propagation to avoid repeated
allocations. The PauliSum::data / PauliSum::aux accessors
expose the current orientation; most callers will only ever touch
the primary side via the high-level gate / measurement traits.
Examples
Heisenberg-picture propagation of ZZ through the GHZ circuit:
use ppvm_pauli_sum::prelude::*;
let mut state: PauliSum<config::indexmap::ByteFxHashF64<1>> =
PauliSum::builder().n_qubits(2).build();
state += ("ZZ", 1.0);
// Circuit: H(0); CNOT(0, 1) — apply in reverse for Heisenberg propagation.
state.cnot(0, 1);
state.h(0);
// ZZ → IZ under the GHZ circuit, with coefficient 1.0.
assert_eq!(state.len(), 1);
Use builder syntax to set the inputs and finish with build().
A finite abelian symmetry group acting on qubit positions by permutations.
Full docstring
A finite abelian symmetry group acting on qubit positions by permutations.
Build via the convenience constructors Self::chain_1d,
Self::torus_2d, Self::torus_3d, Self::ladder, or
Self::from_generators for an arbitrary list of generator
permutations.
perms[g] is the permutation that generator g applies to qubit
indices: a qubit at position q moves to position perms[g][q]
under one application of generator g. orders[g] is the exact
cyclic order of generator g. The abstract group is the direct
product of these cyclic groups, with order Π orders[g]. Its combined
permutation action may have a kernel, so distinct group elements can
act identically.
Only the generators are stored; Self::canonicalize either runs
the O(N) least-rotation scan (chain/ladder layouts) or walks the
group as a mixed-radix odometer.
The characters χ_k(g) of one momentum sector for every element of a
TranslationGroup, indexed by group-element index. Built by
TranslationGroup::character_table.
A precondition violation in TranslationGroup::try_from_generators.
Full docstring
A precondition violation in TranslationGroup::try_from_generators.
Every variant is caller-supplied-input error, and its Display
text is exactly what TranslationGroup::from_generators panics
with.
Detail report for a failed check_momentum_sector.
Marker trait that indicates that all required members are set.
Full docstring
Marker trait that indicates that all required members are set.
In this state, you can finish building by calling the method PauliSumBuilder::build()
Builder's type state specifies if members are set or not (unset).
Full docstring
Builder's type state specifies if members are set or not (unset).
You can use the associated types of this trait to control the state of individual members with the [IsSet] and [IsUnset] traits. You can change the state of the members with the Set* structs available in this module.
ByteFxHash specialised to f64 coefficients.
Byte8 specialised to f64 coefficients.
Byte specialised to f64 coefficients.
ByteFxHash specialised to f64 coefficients.
Reference to the auxiliary map — the scratch buffer gates write into.
Reference to the primary map — the one that currently holds the "active" entries.
Apply the configured truncation Strategy
to the primary map, dropping entries that fall outside its policy.
Full docstring
Apply the configured truncation Strategy
to the primary map, dropping entries that fall outside its policy.
If preserve_strings is non-empty, any of those Pauli strings
that the strategy would have dropped are re-inserted afterwards
with their pre-truncate coefficient. The mechanism composes with
any Strategy (coefficient-magnitude, max-weight, combinations
— anything) because the strategy runs unchanged in the middle.
Lex-min canonical representative of w's translation orbit
under this group.
Full docstring
Lex-min canonical representative of w's translation orbit
under this group.
For chain/ladder layouts this is O(N) via the least-rotation
canonicalizer ([Self::canonicalize_block_cyclic]); otherwise it
walks the full group as a mixed-radix odometer, O(|G| × N).
Everything the phase-aware routines need about w's orbit in
momentum sector k_modes, from ONE orbit traversal: the lex-min
representative r, the mixed-radix counter of the group element
mapping r to w (as [`Self::canonicalize_w…
Full docstring
Everything the phase-aware routines need about w's orbit in
momentum sector k_modes, from ONE orbit traversal: the lex-min
representative r, the mixed-radix counter of the group element
mapping r to w (as Self::canonicalize_with_shift), and the
number of distinct orbit members |orbit|.
Returns None when the orbit's stabilizer is incompatible with
k_modes — i.e. some s with s·w = w has χ_k(s) ≠ 1. Such an
orbit cannot carry this sector: its momentum projection is
identically zero, and the rep coefficient a single traversal would
report depends on which counter the traversal happens to pick.
|orbit| = |G| / |stabilizer| (orbit-stabilizer), and equals
|G| only for free orbits.
Same cost as Self::canonicalize_with_shift. Hot loops should
build a CharacterTable once and call
Self::canonicalize_in_sector_indexed instead.
Self::canonicalize_in_sector against a precomputed
CharacterTable: returns the rep, the index of the group
element mapping it to w (look its character up with
CharacterTable::value), and |orbit| — or None when the
o…
Full docstring
Self::canonicalize_in_sector against a precomputed
CharacterTable: returns the rep, the index of the group
element mapping it to w (look its character up with
CharacterTable::value), and |orbit| — or None when the
orbit cannot carry the table's sector.
Allocation-free apart from the returned word; O(N) for chain /
ladder layouts, else O(|G| × N).
Lex-min canonical representative r of w together with the
mixed-radix index (generator 0 fastest) of the group element
g such that g·r = w — i.e. the index of the counter returned by
Self::canonicalize_with_shift.
Full docstring
Lex-min canonical representative r of w together with the
mixed-radix index (generator 0 fastest) of the group element
g such that g·r = w — i.e. the index of the counter returned by
Self::canonicalize_with_shift.
The index is directly usable as a subscript into a
CharacterTable, which is how the
phase-aware evolution gets χ_k(g) without decoding a counter or
calling sin/cos per term.
Cost: O(N) for chain/ladder layouts, else O(|G| × N).
Allocation-free apart from the returned word.
Lex-min canonical representative r of w together with the
mixed-radix counter c = (c_0, c_1, …) of the group element
g such that g·r = w.
Full docstring
Lex-min canonical representative r of w together with the
mixed-radix counter c = (c_0, c_1, …) of the group element
g such that g·r = w.
In other words: if r = self.canonicalize(w), this returns
(r, c) where applying generator i exactly c[i] times in
sequence to r produces w. It returns the first valid counter
selected by the deterministic mixed-radix traversal. Counters are
not unique when r has a non-trivial stabilizer (or when the
combined action has a kernel). The counter is used to compute
momentum phases by the phase-aware merge routines.
Same cost as Self::canonicalize, plus the counter Vec. Hot
paths should prefer Self::canonicalize_with_index, which is
allocation-free and indexes a precomputed
Self::character_table.
1D chain of n sites with periodic boundary conditions.
Single generator: cyclic shift by one site.
Momentum-sector character χ_k(g) = exp(i Σ_g 2π · k[g] · counter[g] / orders[g])
where k[g] ∈ ℤ is the integer momentum mode along generator g
(the corresponding wavenumber is 2π · k[g] / orders[g]).
Full docstring
Momentum-sector character χ_k(g) = exp(i Σ_g 2π · k[g] · counter[g] / orders[g])
where k[g] ∈ ℤ is the integer momentum mode along generator g
(the corresponding wavenumber is 2π · k[g] / orders[g]).
k.len() must equal self.n_generators(). The character of the
identity element (counter = [0, …]) is 1. For the trivial
(k = [0, …]) sector all characters are 1.
All |G| momentum-sector characters of sector k_modes, indexed
by group-element index (mixed-radix, generator 0 fastest):
table.value(idx) == self.character(k_modes, &self.counter_from_index(idx))
exactly, bit for bit.
Full docstring
All |G| momentum-sector characters of sector k_modes, indexed
by group-element index (mixed-radix, generator 0 fastest):
table.value(idx) == self.character(k_modes, &self.counter_from_index(idx))
exactly, bit for bit.
Build this once per evolution step and index it with the value from
Self::canonicalize_with_index or
Self::canonicalize_in_sector_indexed; the alternative — calling
Self::character per action term — costs a counter Vec, the
exact-numerator arithmetic and a sin/cos pair every time.
Construct from explicit generator permutations and orders, panicking on any precondition violation.
Full docstring
Construct from explicit generator permutations and orders, panicking on any precondition violation.
Each perm must be a permutation of 0..n_qubits. Each order
must be the permutation's exact cyclic order, not merely a
multiple for which perm^order == identity. Generators must
commute, but their combined action may still have a kernel.
Use Self::try_from_generators when the generators come from
outside the program (an FFI boundary, a config file) and a
precondition violation should be reported rather than abort.
Multi-leg ladder: l sites along the chain × n_legs legs.
Single generator: cyclic shift along the chain direction (all
legs simultaneously). Qubit at (leg, j) indexed as
leg * l + j. No translation along the leg axis (legs are
di…
Full docstring
Multi-leg ladder: l sites along the chain × n_legs legs.
Single generator: cyclic shift along the chain direction (all
legs simultaneously). Qubit at (leg, j) indexed as
leg * l + j. No translation along the leg axis (legs are
distinguished).
Iterate over all abstract group elements applied to w. Yields
Self::order Pauli words (including w itself for the identity
element).
Full docstring
Iterate over all abstract group elements applied to w. Yields
Self::order Pauli words (including w itself for the identity
element).
Words may repeat when w has a stabilizer or the combined action
has a kernel; this is not an iterator over distinct orbit members.
Abstract product-group order: Π orders[g].
Full docstring
Abstract product-group order: Π orders[g].
This can exceed the number of distinct permutations in the action when the combined action has a kernel.
2D lx × ly torus, qubit at (i, j) indexed as j*lx + i.
Two generators: x-shift (i → i+1 mod lx) and y-shift (j → j+1 mod ly).
3D lx × ly × lz torus, qubit at (i, j, k) indexed as
k*lx*ly + j*lx + i.
Fallible Self::from_generators: validates every precondition
on the caller-supplied generators and reports the first violation
as a GroupError instead of panicking.
Replace (basis, coeffs) in-place with the orbit-representative
form: each Pauli word becomes its canonical rep, and coefficients
of words that collapse to the same rep are summed.
Full docstring
Replace (basis, coeffs) in-place with the orbit-representative
form: each Pauli word becomes its canonical rep, and coefficients
of words that collapse to the same rep are summed.
Output length ≤ input length. Entries whose summed coefficient
equals zero exactly are not removed — caller should run a final
drop_tol prune if desired.
For dynamics that commute with group and initial states that are
group-invariant (i.e. in the trivial momentum sector), this
preserves all G-invariant expectation values.
Symmetry-merge a PauliSum in place: each Pauli word becomes its
canonical orbit representative, and entries collapsing to the same
rep accumulate coefficients.
Full docstring
Symmetry-merge a PauliSum in place: each Pauli word becomes its
canonical orbit representative, and entries collapsing to the same
rep accumulate coefficients.
This is the Trotter-mode counterpart to canonicalize_pauli_sum
(which operates on the Vec<Word>, Vec<f64> representation used by
ppvm-lindblad's adaptive evolution). Same semantics: preserves all
G-invariant expectation values when the dynamics commutes with
group and the initial state is group-invariant.
Generic over the Config but constrained to PauliWord-backed
representations (i.e. not the loss-aware variant) since
canonicalization needs raw (xbit, zbit) access.
Replace (basis, complex_coeffs) in-place with the orbit-rep form
projected onto momentum sector k_modes.
Full docstring
Replace (basis, complex_coeffs) in-place with the orbit-rep form
projected onto momentum sector k_modes.
For each represented orbit, coefficients on its distinct orbit
members are averaged with the momentum character weight:
(1/|orbit|) · Σ_{p ∈ orbit} χ_k(g_p) · c_p where g_p is the group
element such that g_p · rep = p.
Orbits whose stabilizer is incompatible with k_modes (the same orbit
member is reached with different character numerators) project to zero
and are omitted from the output.
If the input was already a momentum-k_modes eigenstate (i.e. the
coefficients satisfy c_{g·p} = χ_k(g)⁻¹ · c_p for every orbit),
the output is the orbit-rep coefficients of that state unchanged.
Otherwise the projection discards the components in other sectors —
use check_momentum_sector beforehand to validate.
For the k_modes = [0, 0, …] (trivial) sector all characters are 1,
so projection averages the distinct orbit members onto each rep. This
differs from plain super::canonicalize_pauli_sum, whose real-coefficient
merging sums collisions without orbit-size normalization.
χ_k of the group element with index idx.
Verify that a (basis, complex_coeffs) Pauli sum lies entirely in
the momentum sector k_modes under group.
Full docstring
Verify that a (basis, complex_coeffs) Pauli sum lies entirely in
the momentum sector k_modes under group.
Concretely: for every orbit represented in the basis, all members
must satisfy c_{g·r} = χ_k(g)⁻¹ · c_r for some choice of orbit-rep
coefficient c_r. Orbit members absent from basis are treated as
having coefficient zero, rather than being ignored.
An orbit with a stabilizer incompatible with k_modes cannot carry
that sector and fails with SectorCheckError::IncompatibleStabilizer;
the corresponding momentum projection would be zero.
Returns Ok(()) on pass; Err(SectorCheckError) on fail with the
offending orbit-rep, expected coefficient, and actual coefficient.
Use this on a user-supplied initial state before feeding it to a phase-aware merging pipeline — silently projecting a wrongly-typed input throws away meaningful physics.
Momentum-sector merge of a complex operator carried as a real
pair: re and im are the real and imaginary parts of
O = re + i·im. Both are overwritten in place with the
orbit-representative form of O projected onto momentum se…
Full docstring
Momentum-sector merge of a complex operator carried as a real
pair: re and im are the real and imaginary parts of
O = re + i·im. Both are overwritten in place with the
orbit-representative form of O projected onto momentum sector
k_modes.
This is the momentum-sector counterpart of
super::symmetry_merge_pauli_sum, and generalizes it to k ≠ 0
while keeping real coefficients on both sums — the only complex
arithmetic is the internal character-weighted fold, which reuses
canonicalize_pauli_sum_complex.
This is the summing projector
Σ_{p ∈ orbit} χ_k(g_p) · c_p over each orbit's distinct members, not the
orbit-averaged one that canonicalize_pauli_sum_complex returns.
Summing is what makes the merge idempotent — and hence safe to apply
after every Trotter step — for every orbit, including orbits with a
non-trivial stabilizer, and it reduces exactly to
super::symmetry_merge_pauli_sum at k = 0.
Entries whose component is exactly zero are dropped, so a purely real
operator leaves im empty.
Panics
If re and im disagree on qubit count, if either disagrees with
group.n_qubits(), or if k_modes.len() != group.n_generators().
Implement multiplication by a scalar coefficient for PauliSum.
Use this macro to implement MulAssign for other scalar types
if needed. This macro will forward the multiplication to the underlying map's
mul_assign method.
ppvm-tableau
Generalized stabilizer tableau simulator (Clifford + non-Clifford).
Generalized stabilizer-tableau simulator built on top of the ppvm core
crates (ppvm-traits and ppvm-pauli-word).
Full docstring
Generalized stabilizer-tableau simulator built on top of the ppvm core
crates (ppvm-traits and ppvm-pauli-word).
Provides a forward-evolving state representation using the stabilizer
formalism, extended to non-Clifford gates by tracking a sparse vector
of coefficients indexed over bitstrings. The two top-level types are
data::Tableau (pure Clifford) and data::GeneralizedTableau
(Clifford + non-Clifford with sparse coefficient tracking).
Quick example
Prepare a Bell pair and verify the two measurements are perfectly correlated:
use ppvm_tableau::prelude::*;
use ppvm_pauli_sum::config::fxhash::ByteF64;
let mut tab: GeneralizedTableau<ByteF64<1>> =
GeneralizedTableau::new_with_seed(2, 1e-12, 0);
tab.h(0);
tab.cnot(0, 1);
let r0 = LossyMeasure::measure(&mut tab, 0);
let r1 = LossyMeasure::measure(&mut tab, 1);
assert_eq!(r0, r1);
Data-parallel / GPU-offloadable surface
A handful of primitives in this crate operate on whole contiguous arrays at once, with no per-element host closures — the shape a thread pool or a CUDA kernel would want:
- Every tableau row (
PhasedPauliWord) stores its Pauli word as fixed-sizebytemuck::Podinteger bit-planes (xbits/zbits, backed by[u8; N]or[u64; N]), reachable as contiguous raw integer slices viaas_raw_slice/as_raw_mut_slice— plain-old-data, not a bit-addressed abstraction. - The single-gate Clifford path
(
crates/ppvm-tableau/src/gates/clifford.rs) has one shared implementation per gate that loops over rows operating directly on those raw integer slices with a hoisted word-index/bit/mask, bypassingbitvec's per-bit bounds checks inside the loop. Bothdata::Tableauanddata::GeneralizedTableau(via theimpl_generalized_tableau_clifford*macros) funnel through it. - The batch path does not share that implementation. The
CliffordBatchmethods (x_many,cz_many, …) each carry their own raw-plane loop that fuses many gates into a single pass over the rows, andTableauandGeneralizedTableauhave separateCliffordBatchimpls (the latter via theimpl_gen_tableau_batch_*macros). Anyone porting the Clifford layer to a thread pool or a CUDA kernel has to cover both the single-gate implementation and these batch bodies. - The batch methods take arbitrary index lists (
&[usize],&[(usize, usize)]).data::GeneralizedTableau::cz_block/cz_block_pairs/cz_block_pairs_cross_wordare the contiguous-block variants: they apply CZ to a whole contiguous range of qubits as bulk masked slice operations, which is the layout a kernel can address without an index indirection. GeneralizedTableau::branch_with_coefficients(crate-private) transforms the whole coefficient array in one pass. Its#[cfg(feature = "rayon")]path (branch_coefficients_parallel, gated byRAYON_COEFF_THRESHOLD) computes the per-entry branch/non-branch coefficient math in parallel, with no shared mutable state — the accumulation of those results into the coefficient map afterwards remains sequential.
Core Tableau and
GeneralizedTableau types.
Display implementations for tableau types.
Pauli-string expectation values and pattern traces.
Pauli-string expectation values for GeneralizedTableau.
Full docstring
Pauli-string expectation values and pattern traces.
Pauli-string expectation values for GeneralizedTableau.
Two entry points:
GeneralizedTableau::expectation— single-Pauli⟨ψ|P|ψ⟩for aPauliWord. ConjugatesPthrough the tableau and overlaps the resulting Pauli with the sparse coefficient vector using the same formulas as the measurement code.GeneralizedTableau::trace—Σ_{P matches pattern} ⟨ψ|P|ψ⟩for aPauliPattern. Enumerates the matching Paulis and sums their expectations.
Decision 9 in the multi-backend plan calls these out as the natural primitive for the tableau backend; semantics intentionally diverge from the PauliSum trace.
Gate implementations (Clifford, T, rotations).
Z-basis measurement, including loss-aware variants.
Noise channels: depolarizing, Pauli error, loss.
Convenience re-exports for downstream code.
Per-qubit QubitStatus relative to the
computational subspace.
SparseVector trait and implementations.
TableauIndex — abstraction over
the bitstring index type (usize, u128, U256, …).
TableauLike — shared trait for
stabilizer-tableau backends.
TableauLike trait: shared interface for stabilizer-tableau backends.
Full docstring
TableauLike — shared trait for
stabilizer-tableau backends.
TableauLike trait: shared interface for stabilizer-tableau backends.
Any type implementing TableauLike gets default implementations of
single- and two-qubit Pauli noise channels (Depolarizing, PauliError,
Depolarizing2, TwoQubitPauliError). New tableau backends only need to
provide TableauLike::rng_mut and (optionally) override
TableauLike::is_qubit_lost
(which reports lost or leaked qubits; two-qubit channels marginalize them out).
A Tableau extended with sparse coefficient tracking to handle
non-Clifford gates.
Full docstring
A Tableau extended with sparse coefficient tracking to handle
non-Clifford gates.
Non-Clifford gates (T, rotations) split a single tableau into a sum
of weighted branches indexed by bitstrings. GeneralizedTableau
stores those weights in a SparseVector keyed by an
IndexType. Choose:
IndexType = usizefor up to 64 qubits,IndexType = u128for up to 128,IndexType = bnum::types::U256and friends for the very wide regime.
Per-qubit status (loss / leakage) is tracked in
qubit_status; gates skip any qubit that is
not QubitStatus::Live.
Examples
Prepare a Bell pair and sample one shot. With a fixed seed the two measurements are perfectly correlated on every shot:
use ppvm_pauli_sum::config::fxhash::ByteF64;
use ppvm_traits::traits::{Clifford, LossyMeasure};
use ppvm_tableau::data::GeneralizedTableau;
let mut tab: GeneralizedTableau<ByteF64<1>> =
GeneralizedTableau::new_with_seed(2, 1e-12, 0);
tab.h(0);
tab.cnot(0, 1);
let r0 = LossyMeasure::measure(&mut tab, 0);
let r1 = LossyMeasure::measure(&mut tab, 1);
assert_eq!(r0, r1);
Non-Clifford gates work through the same interface — apply a T gate
followed by T† and the state is unchanged:
use ppvm_pauli_sum::config::fxhash::ByteF64;
use ppvm_traits::traits::{Clifford, TGate};
use ppvm_tableau::data::GeneralizedTableau;
let mut tab: GeneralizedTableau<ByteF64<1>> =
GeneralizedTableau::new_with_seed(1, 1e-12, 0);
tab.h(0);
tab.t(0);
tab.t_dag(0);
// T followed by T† is the identity; the |+⟩ state is restored.
A 2n-row stabilizer / destabilizer tableau.
Full docstring
A 2n-row stabilizer / destabilizer tableau.
Rows 0..n hold the destabilizers; rows n..2n hold the
stabilizers. Each row is a PhasedPauliWord tracking both its
X/Z bits and a phase in {±1, ±i}. Implements every
Clifford-only operation natively (Hadamard, phase, CNOT, CZ, etc.).
Examples
use ppvm_pauli_sum::config::fxhash::ByteF64;
use ppvm_traits::traits::Clifford;
use ppvm_tableau::data::Tableau;
let mut tab: Tableau<ByteF64<1>> = Tableau::new(2);
tab.h(0);
tab.cnot(0, 1);
assert_eq!(tab.n_qubits, 2);
assert_eq!(tab.stabilizers().len(), 2);
GeneralizedTableau::project was asked for an outcome with probability
below tol. The tableau is left as it was before the call.
Per-measurement scratch buffers, reused across qubits within a single
measure_all invocation — and, when threaded through
measure_all_with_scratch,
across many shots of a sampler too. R…
Full docstring
Per-measurement scratch buffers, reused across qubits within a single
measure_all invocation — and, when threaded through
measure_all_with_scratch,
across many shots of a sampler too. Reusing one scratch keeps the case-a
HashMap and the b-entries Vec out of the per-shot allocator churn.
odd_phase_maskis lazily computed and cached until the destabilizers change (i.e. until a case-a measurement runsupdate_tableau_according_to_outcome).coeff_mapis the case-a HashMap holding(idx → amplitude)between the overlap, partition, and merge passes.b_entriesis the case-a partition's "k-bit = 1" scratch Vec.
Construct one per active sampling thread; the type is not meant to be shared across threads concurrently.
Per-qubit status relative to the computational subspace.
Full docstring
Per-qubit status relative to the computational subspace.
Loss and leakage both take a qubit out of the computational subspace, so
gates skip any status other than QubitStatus::Live. They differ only
at measurement: a lost qubit reports None, a leaked qubit reports the
pinned computational bit. Loss overwrites leakage — a leaked qubit that is
later lost is QubitStatus::Lost, indistinguishable from a qubit lost
from the computational subspace.
A sparse vector keyed by index type I with values of type T.
Full docstring
A sparse vector keyed by index type I with values of type T.
Used by GeneralizedTableau to
store the coefficient over each branching bitstring. The default
implementation is Vec<(T, I)>; alternative backings (BTreeMap,
HashMap, etc.) can be provided by downstream code.
Bit-string index type used by
GeneralizedTableau to address
individual branches of its sparse coefficient vector.
Full docstring
Bit-string index type used by
GeneralizedTableau to address
individual branches of its sparse coefficient vector.
Blanket-implemented for every primitive (and bnum-style) integer
type that supports the required bit operations. Pick:
usizefor ≤ 64 qubits,u128for ≤ 128,bnum::types::U256/U512/U1024for the wide regime.
A stabilizer-tableau-like backend that supports Clifford gates and an RNG.
Full docstring
A stabilizer-tableau-like backend that supports Clifford gates and an RNG.
Implementing this trait grants default implementations of the Pauli noise
channels via TableauLike::depolarize_impl and friends. The associated
Rng type lets each backend choose its own RNG; nothing in this trait
depends on SmallRng.
Apply CZ to count pairs with a constant offset, given in qubit-index
terms: (control_base + i, target_base + i) for i in 0..count.
Full docstring
Apply CZ to count pairs with a constant offset, given in qubit-index
terms: (control_base + i, target_base + i) for i in 0..count.
This is the high-level entry point for a fused block of CZs: it splits
the run at storage-word boundaries internally and dispatches each
segment to Self::cz_block_pairs (control and target in the same
word) or Self::cz_block_pairs_cross_word (straddling two words), so
callers never need to reason about the u64 packing. CZ is symmetric,
so the two bases may be passed in either order.
Overlapping pairs — |target_base - control_base| < count, of which
adjacent-pair brickwork cz_block(0, 1, n) is the extreme case — are
handled: the same-word segments route through Self::cz_block_pairs
into Tableau::cz_block_pairs, which falls back to the per-pair
loop. A cross-word segment is always disjoint (its run never exceeds
the offset), so the fused kernel stays live there.
Apply CZ to N pairs with constant offset: (base+i, base+offset+i) for i in 0..count.
Falls back to individual CZ calls if any qubit in the range is lost or leaked.
Overlap (offset < count) is owned by Tableau::cz_block_pairs.
Apply CZ to N cross-word pairs. Controls at word_c, targets at word_t. Falls back to individual CZ calls if any qubit is lost or leaked.
⟨ψ|word|ψ⟩ for the multi-qubit Pauli word.
Full docstring
⟨ψ|word|ψ⟩ for the multi-qubit Pauli word.
Conjugates word through the Clifford tableau (giving a Pauli on the
canonical basis: an X-mask, Z-mask, and i^φ phase), then sums
⟨α|P_conj|β⟩ c_α* c_β over the sparse coefficient vector. Always
returns a real number (Hermitian operator on a normalized state).
Same as LossyMeasureAll::measure_all, but the caller supplies a
MeasureScratch that's reused across the n per-qubit measurements
(and, if the caller chooses, across many invocations / shots).
Full docstring
Same as LossyMeasureAll::measure_all, but the caller supplies a
MeasureScratch that's reused across the n per-qubit measurements
(and, if the caller chooses, across many invocations / shots).
This is the entry point samplers should use when running many shots: initialize one scratch alongside the sampler and thread it through every shot to amortize the case-a HashMap and b_entries allocations.
Construct a generalized tableau in the |0…0⟩ state.
Full docstring
Construct a generalized tableau in the |0…0⟩ state.
Branches whose coefficient magnitude falls below
coefficient_threshold are dropped during gate application.
Post-selected measurement: collapse qubit addr0 onto outcome (as
returned by measure, None = lost), record
it, and return its probability. Chaining it gives
P(z) = Π_i P(z_i | z_<i).
Full docstring
Post-selected measurement: collapse qubit addr0 onto outcome (as
returned by measure, None = lost), record
it, and return its probability. Chaining it gives
P(z) = Π_i P(z_i | z_<i).
Loss is classical: None has probability 1 on a lost qubit and 0 on a
live one, and Some(_) has probability 0 on a lost qubit.
tol must be in (0, 1]. Returns ImpossibleOutcome,
leaving the tableau untouched, if P(outcome) < tol.
Σ_{P matches pattern} ⟨ψ|P|ψ⟩.
Full docstring
Σ_{P matches pattern} ⟨ψ|P|ψ⟩.
Enumerates every PauliWord accepted by pattern via
PauliPattern::enumerate_matches and sums their expectations.
Star quantifiers (X*) panic — the pattern must be bounded; use
counted repetition (Z?{n}) or positional anchors instead.
Symplectic inner product of two tableau index values — the count of shared set bits, used in stabilizer phase calculations.
Apply CZ to N pairs with constant offset: (base+i, base+offset+i) for i in 0..count. All pairs must be in the same u64 word. This replaces N individual CZ calls with a single word-level shift+XOR operation per row.
Full docstring
Apply CZ to N pairs with constant offset: (base+i, base+offset+i) for i in 0..count. All pairs must be in the same u64 word. This replaces N individual CZ calls with a single word-level shift+XOR operation per row.
Preconditions
The fused kernel needs offset >= count, i.e. pairwise-disjoint
supports (pairs i != j collide iff |i - j| == offset, which needs
offset < count, or offset == 0). Both fused updates need it: the
single count_ones() & 1 phase reads the pre-update z plane for
every pair at once (Batch.lean::czSeq_phase proves it equal to the
sequential loop only under pairwise disjointness, and
czSeq_phase_needs_disjoint exhibits a counterexample), and the z
delta ORs the two shifted planes, so a z bit written by two pairs
is set once instead of XOR-cancelled.
Overlapping pairs (offset < count, including offset == 0) fall
back to the per-pair cz loop, so this method is safe in release.
Panics
Debug-asserts that all bits are within the same word.
Construct a fresh tableau initialised to |0…0⟩.
true iff p is an admissible correlated-loss parameter triple.
Full docstring
true iff p is an admissible correlated-loss parameter triple.
The channel is completely positive exactly when every event weight is
nonnegative, i.e. p0, p1 >= 0, p0 + 2·p1 <= 1 (p1 is the probability
that a named one of the pair is lost, so the exactly-one event carries
2·p1) and p2 ∈ [0, 1]. Outside that region the mixture truncates a
negative survivor weight and renormalizes, and the trajectory's cumulative
scan stops being a categorical sampler — both silently.
Coefficients are checked in Coeff space via PartialOrd<f64> (the
bound every loss-channel impl already carries). Slack still applies
to the p0 + 2·p1 <= 1 sum so a saturated [1/3, 1/3, _] is not
rejected by last-bit rounding.
ppvm-sym
Symbolic, parametric Pauli propagation.
Symbolic, parametric Pauli propagation.
Full docstring
Symbolic, parametric Pauli propagation.
ppvm-sym provides a Term type that represents a polynomial in
sines and cosines of symbolic parameters. It is used by ppvm to
propagate Pauli operators through parametric circuits (e.g.,
variational ansätze) without committing to specific angle values
until the very end.
Quick example
Build the symbolic expression sin(x0) * cos(x1), then evaluate it
at a concrete (x0, x1):
use ppvm_sym::Term;
let expr = Term::var(0).sin() * Term::var(1).cos();
let v = expr.eval(&[0.5, 1.0]).unwrap();
let expected = 0.5_f64.sin() * 1.0_f64.cos();
assert!((v - expected).abs() < 1e-12);
<coeff> sin^m cos^n
Full docstring
<coeff> sin^m cos^n
A single product of trigonometric atoms over symbolic variables.
Sines and cosines are grouped by variable id; powers are tracked as
totals so we can quickly compute and bound them. The order of
variables is kept canonical (ascending) so two Prod values
representing the same monomial compare equal.
A formal sum c₀ + Σᵢ cᵢ · pᵢ, where each pᵢ is a Prod and
cᵢ is an f64 coefficient.
A symbolic polynomial in sin(x_i) and cos(x_i).
Full docstring
A symbolic polynomial in sin(x_i) and cos(x_i).
Term is the public-facing wrapper around its Inner enum. It
also carries two truncation parameters, applied during multiplication
and addition:
Examples
use ppvm_sym::Term;
// sin²(x0) at x0 = π/2 equals 1.
let expr = Term::var(0).sin() * Term::var(0).sin();
let v = expr.eval(&[std::f64::consts::FRAC_PI_2]).unwrap();
assert!((v - 1.0).abs() < 1e-12);
max_sin— drop terms whose total sine power exceeds this bound.min_eps— drop terms whose coefficient magnitude falls below this threshold.
Internal representation of a Term.
Full docstring
Internal representation of a Term.
Sum holds a full formal sum; One is the optimisation for a
single weighted product; Var is a bare symbolic variable used
before it has been wrapped in a sin or cos; Const is a
numeric scalar.
ppvm-lindblad
Adaptive Heisenberg-picture Lindbladian evolution on a truncated Pauli-string basis.
Direct Heisenberg-picture Lindbladian evolution on an adaptive Pauli-string basis.
Full docstring
Direct Heisenberg-picture Lindbladian evolution on an adaptive Pauli-string basis.
For a Hermitian Pauli Hamiltonian H = Σ c_i P_i and jump operators
L_k = Σ_a λ_{k,a} P_{k,a} (each a Hermitian-Pauli linear combination
with possibly complex coefficients) with rates γ_k ≥ 0, the adjoint
Lindbladian acts on a single Pauli string p as
L*(p) = i [H, p] + Σ_k γ_k ( L_k† p L_k − 1/2 {L_k† L_k, p} ).
Two jump shapes are supported with separate code paths:
Hermitian Pauli (
L = P,λ ∈ ℝ): the dissipator collapses to a diagonal-2γon Pauli strings that anti-commute withP. Same fast path used by every dephasing-style model.General (complex
λ_a, e.g.σ± = (X ± iY)/2): the dissipator becomes a double sumΣ_{a,b} λ_a* λ_b P_a p P_bplus a Pauli- linear-combination anti-commutator withL†L, which is precomputed once at construction. Intermediate coefficients are complex; the result is real becauseL*preserves Hermiticity, so we cast back tof64at the boundary (with a debug-only check that|Im|is at FP noise).
Pauli strings are stored as ppvm_pauli_word::word::PauliWord backed by
a fixed array of C chunks (64-bit, or 32-bit on 32-bit targets) with
cached hashes for fast HashMap lookup. The crate is const-generic in C
(Word, LindbladSpec); the default is the 128-qubit width,
and chunks_for picks the narrowest of the 128/256/512-qubit widths
for a register. The hot-path commutator/
product loops bypass the higher-level word API and operate directly on
the raw chunks for speed.
Configuration objects for the predictor-corrector stepper.
Error type for crate::LindbladSpec construction and stepping.
Momentum sectors of a translation group, and the phase-aware canonicalization that drives orbit-representative evolution.
Full docstring
Momentum sectors of a translation group, and the phase-aware canonicalization that drives orbit-representative evolution.
On the orbit-rep path the state lives entirely in orbit-rep form
throughout: the basis contains only canonical translation-orbit
representatives and the coefficients are complex (one per rep). The
dynamics L* is computed with phase-aware action — for each
output Pauli q, we canonicalize q to its orbit rep r_q with
shift counter cnt_q, and accumulate
χ_k(g_{cnt_q}) · v · c_r · |orbit_r| / |orbit_{r_q}| (where v is
the matrix element of L* between input rep r and output q).
Sector::canonicalize_phase is that step.
Coefficients are in the averaged convention: c_r is the plain
coefficient of the rep word, as produced by
canonicalize_pauli_sum_complex. The character-weighted action is
naturally the generator in the summing convention
ĉ_r = |orbit_r| · c_r, which is where the orbit-size ratio comes
from; it is 1 whenever both orbits are free.
The orbit-rep basis is ~|G|× smaller than the full-basis
representation, throughout the entire evolution.
Limitations
- Callers are responsible for ensuring the input basis is in
orbit-rep form (i.e. each entry is the canonical representative of
its translation orbit). Use
canonicalize_basis_to_repif needed. - A
Sectoris fixed for the duration of oneLindbladSpec::pc_step_orbit_repcall. To compute a full site-resolved profile, call it once per momentum mode and inverse-Fourier the results.
Truncation and execution policy for a single predictor-corrector step
(crate::LindbladSpec::pc_step, crate::LindbladSpec::pc_step_timed).
Full docstring
Truncation and execution policy for a single predictor-corrector step
(crate::LindbladSpec::pc_step, crate::LindbladSpec::pc_step_timed).
These are the per-run tuning knobs, kept separate from the per-call data
(basis, coeffs, dt, protected).
max_basis is the primary accuracy/cost dial; admit_basis selects the
displacement scheme; drop_tol is the churn valve of the admission-bound
scheme; tau_add is a wall optimization at most.
A momentum sector of a translation group: the group G together with
one integer mode index per generator. The wavenumber along generator
g is 2π · k_modes[g] / group.generator_order(g); k_modes = [0, …]
is the trivial sector.
Full docstring
A momentum sector of a translation group: the group G together with
one integer mode index per generator. The wavenumber along generator
g is 2π · k_modes[g] / group.generator_order(g); k_modes = [0, …]
is the trivial sector.
The two halves are meaningless apart — every phase-aware routine
needs both — so they travel as one value. Construction precomputes the
sector's CharacterTable (|G| entries), so the per-term work in the
hot loops is one canonicalization and a table lookup; build a Sector
once per step and pass it by reference.
User-facing description of one jump operator: a complex Pauli linear combination together with its rate.
Precompiled Lindbladian. Constructed once from string-form Hamiltonian
terms + jump operators; reused across many calls to Self::action,
Self::leakage, Self::generator. L*(p) is recomputed on every
call rather than cached: …
Full docstring
Precompiled Lindbladian. Constructed once from string-form Hamiltonian
terms + jump operators; reused across many calls to Self::action,
Self::leakage, Self::generator. L*(p) is recomputed on every
call rather than cached: for sparse-local Hamiltonians a per-word cache
costs more than the recompute (hash lookup ≳ recompute) and its several
KB per cached word dominate memory at large basis sizes.
Per-phase timing breakdown (microseconds) returned by
LindbladSpec::pc_step_timed.
Errors raised when constructing a crate::LindbladSpec.
The Pauli-word storage type used throughout this crate, C chunks wide.
Full docstring
The Pauli-word storage type used throughout this crate, C chunks wide.
The crate is const-generic in the chunk count so a register of any size
up to MAX_SUPPORTED_QUBITS gets a fixed-size word; the default
C = W_CHUNKS covers 128 qubits, byte-for-byte the historical layout.
The FxBuildHasher matches the hash used by the FxHashMap keys we
wrap with; REHASH=true means set() keeps the cached hash in sync.
Build a word → row map for a basis assumed to contain unique Pauli
words; debug-asserts the uniqueness invariant.
Replace each entry of basis with its canonical orbit
representative under group. Pure rewrite; coefficients are
untouched. Useful to enforce the orbit-rep invariant before calling
[LindbladSpec::pc_step_orbit_rep](crate::LindbladSp…
Full docstring
Replace each entry of basis with its canonical orbit
representative under group. Pure rewrite; coefficients are
untouched. Useful to enforce the orbit-rep invariant before calling
LindbladSpec::pc_step_orbit_rep.
Does NOT deduplicate — if multiple input entries collapse to the same rep, both are kept (caller should run a merge afterwards).
Canonicalize q to its orbit representative r_q and return it
alongside the character phase χ_k(g_{cnt_q}) of the group
element that maps q to r_q, and the number of distinct
members of that orbit. The phase weights the matr…
Full docstring
Canonicalize q to its orbit representative r_q and return it
alongside the character phase χ_k(g_{cnt_q}) of the group
element that maps q to r_q, and the number of distinct
members of that orbit. The phase weights the matrix element of
L* when it is accumulated onto r_q; the orbit size converts
between the two coefficient conventions (see
Self::orbit_size).
None when q's orbit cannot carry this sector (its stabilizer
is incompatible with k): the coefficient of such a rep is
identically zero, so the term is dropped.
Number of distinct members of w's translation orbit, or
None if the orbit cannot carry this sector.
Full docstring
Number of distinct members of w's translation orbit, or
None if the orbit cannot carry this sector.
This is the factor between the two orbit-rep coefficient
conventions: the averaged one, in which c_r is the plain
coefficient of the rep word (what canonicalize_pauli_sum_complex
and this crate's public orbit-rep API use), and the summing one
ĉ_r = |orbit_r| · c_r (what momentum_merge_pauli_sum_pair
uses). It is |G| only for free orbits.
Apply L* to a single Pauli string p. Returns the output Pauli
strings and their real coefficients (zero entries omitted).
Sparse generator matrix in COO form: returns (row, col, val)
triplets. Row = output Pauli's position in basis; col = input
Pauli's position. Output Paulis not in basis are silently dropped.
Full docstring
Sparse generator matrix in COO form: returns (row, col, val)
triplets. Row = output Pauli's position in basis; col = input
Pauli's position. Output Paulis not in basis are silently dropped.
Precondition: basis must not contain duplicate Pauli words
(asserted in debug builds).
Off-basis component of L*( Σ_j coeffs[j] · basis[j] ). Output
strings that lie in basis or in protected are dropped.
Like Self::leakage, but caps the live off-basis leakage map to
the available room room = max_basis − basis.len() — only the
strings we could actually add to the basis are worth keeping. The
cap is applied during accumulation (aft…
Full docstring
Like Self::leakage, but caps the live off-basis leakage map to
the available room room = max_basis − basis.len() — only the
strings we could actually add to the basis are worth keeping. The
cap is applied during accumulation (after each chunk), keeping the
room largest-magnitude entries.
Basis indices are processed in descending-|c| order so the
running cap keeps the entries that are most likely to be the true
largest contributors. When max_basis is large enough that
room ≥ all candidates, nothing is dropped — the near-exact case.
One predictor-corrector step O ← exp(dt·L*) O in the adaptive
real-coefficient Pauli basis: first-hop leakage admission, predictor
exponential, second-hop admission from the predicted state, corrector
exponential from the saved pre-ste…
Full docstring
One predictor-corrector step O ← exp(dt·L*) O in the adaptive
real-coefficient Pauli basis: first-hop leakage admission, predictor
exponential, second-hop admission from the predicted state, corrector
exponential from the saved pre-step state, then truncation (prune +
rank cap) per PcStepConfig. Exact in dt within the working
basis — the only error is basis truncation.
When the second hop admits no string (in particular when the first
hop already filled the admission room admit_basis − |basis|, the
usual case once the basis has reached max_basis), the corrector
would repeat the predictor exactly; the second leakage pass (if
room = 0) and the corrector exponential are then skipped, with
bit-identical results. The step's timings report 0 for skipped
phases.
protected words are never dropped. All tuning knobs live in cfg.
One predictor-corrector step in orbit-rep form at momentum
sector: the same five phases as Self::pc_step, but the basis
holds only canonical translation-orbit representatives, the
coefficients are complex, and the L* action i…
Full docstring
One predictor-corrector step in orbit-rep form at momentum
sector: the same five phases as Self::pc_step, but the basis
holds only canonical translation-orbit representatives, the
coefficients are complex, and the L* action is phase-aware (see
crate::sector). The basis stays ~|G|× smaller than the
equivalent full-basis complex evolution, every step.
max_basis is a hard rank cap on the live orbit-rep basis:
enrichment adds at most admit − basis.len() of the largest
leakage reps, the leakage map is capped to the same room, and the
post-step basis is trimmed to the top-max_basis reps by |c|.
Pass a large value (e.g. usize::MAX) for the near-exact,
uncapped case. drop_tol additionally prunes by magnitude.
protected reps are never dropped.
basis is assumed to contain only canonical orbit
representatives. If not, call
canonicalize_basis_to_rep
first.
Honours cfg.num_threads the same way Self::pc_step does.
Same as Self::pc_step but also returns a per-phase timing
breakdown (microseconds), for profiling parallel scaling and hot
spots.
The narrowest entry of WIDTHS that holds n_qubits, or None above
MAX_SUPPORTED_QUBITS.
Inverse of word_from_codes: write n_qubits Pauli labels into out.
Capacity of a C-chunk Word, in qubits.
Parse a "IXYZ..." string into a Word together with the list of
qubits where the Pauli is non-identity (the term's support).
Build a Word from a length-n_qubits slice of Pauli labels
(0=I, 1=X, 2=Z, 3=Y — the ppvm_traits::char::Pauli discriminants).
Sets all bits and rehashes once.