metatron_qso
QSO — validated quantum simulation in pure Rust.
Exact state-vector and density-matrix simulation, VQE and QAOA with exact gradients, Grover search, QFT and phase estimation; continuous- and discrete-time quantum walks on arbitrary graphs (including Metatron's Cube), reduced by symmetry to exact low-dimensional problems where possible, with state-transfer analysis and walk circuits; graph isomorphism; exact boson sampling; device-like noise models with quantum trajectories; and error mitigation (readout calibration, zero-noise extrapolation, probabilistic error cancellation, Pauli twirling) and classical shadows, with standard errors on every estimate; Hamiltonian simulation (Trotter-Suzuki with error bounds, qDRIFT); electronic structure (fermion-to-qubit mappings, FCIDUMP integrals, UCCSD, k-UpCCGSD, ADAPT-VQE); excited states (VQD, SSVQE); quantum Fisher information, natural gradient and imaginary-time evolution; QUBO/Ising problems with QAOA mixers; and amplitude estimation.
Conventions: qubit 0 is the least significant bit of a basis index; bit
strings print qubit n-1 first; time evolution is exp(-iHt); rotations are
R_P(theta) = exp(-i theta P / 2). Invalid input raises ValueError.
1"""QSO — validated quantum simulation in pure Rust. 2 3Exact state-vector and density-matrix simulation, VQE and QAOA with exact 4gradients, Grover search, QFT and phase estimation; continuous- and 5discrete-time quantum walks on arbitrary graphs (including Metatron's Cube), 6reduced by symmetry to exact low-dimensional problems where possible, with 7state-transfer analysis and walk circuits; graph isomorphism; exact boson 8sampling; device-like noise models with quantum trajectories; and error 9mitigation (readout calibration, zero-noise extrapolation, probabilistic 10error cancellation, Pauli twirling) and classical shadows, with standard 11errors on every estimate; Hamiltonian simulation (Trotter-Suzuki with error 12bounds, qDRIFT); electronic structure (fermion-to-qubit mappings, FCIDUMP 13integrals, UCCSD, k-UpCCGSD, ADAPT-VQE); excited states (VQD, SSVQE); 14quantum Fisher information, natural gradient and imaginary-time evolution; 15QUBO/Ising problems with QAOA mixers; and amplitude estimation. 16 17Conventions: qubit 0 is the least significant bit of a basis index; bit 18strings print qubit n-1 first; time evolution is exp(-iHt); rotations are 19R_P(theta) = exp(-i theta P / 2). Invalid input raises ``ValueError``. 20""" 21 22from ._core import ( 23 AmplitudeProblem, 24 BosonSampler, 25 Channel, 26 Circuit, 27 ClassicalShadow, 28 CoinedWalk, 29 ContinuousWalk, 30 DensityMatrix, 31 DephasingWalk, 32 DeviceModel, 33 Estimate, 34 FermionOperator, 35 Graph, 36 GraphClassifier, 37 LineWalk, 38 MAX_DENSITY_QUBITS, 39 MAX_QUBITS, 40 MaxCutQaoa, 41 MolecularIntegrals, 42 NoiseModel, 43 Parameter, 44 PauliSum, 45 Program, 46 Qaoa, 47 QubitOperator, 48 Qubo, 49 Quotient, 50 QuotientSearch, 51 QuotientWalk, 52 ReadoutCalibration, 53 SpatialSearch, 54 StateTransfer, 55 StateVector, 56 SzegedyWalk, 57 TrajectorySimulator, 58 VariationalClassifier, 59 __version__, 60 adapt_vqe, 61 beam_splitter, 62 bitstring, 63 canonical_amplitude_estimation, 64 cayley_walk_circuit, 65 circulant_walk_circuit, 66 classical_hitting_times, 67 classical_walk_probabilities, 68 diagonal_unitary_circuit, 69 efficient_su2, 70 estimate, 71 estimate_expectation, 72 estimate_phase, 73 expectation_and_gradient, 74 expectation_and_gradient_batch, 75 expectation_batch, 76 extrapolate, 77 fold, 78 grover_circuit, 79 grover_search, 80 h2_sto3g, 81 haar_unitary, 82 hardware_efficient, 83 heisenberg_xxz, 84 imaginary_time_evolution, 85 inverse_qft, 86 iterative_amplitude_estimation, 87 k_upccgsd, 88 maxcut_cost, 89 metatron_line_lengths, 90 ml_amplitude_estimation, 91 natural_gradient, 92 nearest_probability_distribution, 93 optimize_qaoa_layerwise, 94 pec_expectation, 95 permanent, 96 qaoa_maxcut_circuit, 97 qdrift_circuit, 98 qdrift_error_bound, 99 qft, 100 quantum_fisher_information, 101 quantum_natural_gradient, 102 real_amplitudes, 103 run_vqe, 104 simulate, 105 ssvqe, 106 transverse_field_ising, 107 trotter_circuit, 108 trotter_error_bound, 109 trotter_walk_circuit, 110 twirl, 111 twirled_average, 112 uccsd, 113 vqd, 114 zne, 115) 116 117__all__ = [ 118 "AmplitudeProblem", 119 "BosonSampler", 120 "Channel", 121 "Circuit", 122 "ClassicalShadow", 123 "CoinedWalk", 124 "ContinuousWalk", 125 "DensityMatrix", 126 "DephasingWalk", 127 "DeviceModel", 128 "Estimate", 129 "FermionOperator", 130 "Graph", 131 "GraphClassifier", 132 "LineWalk", 133 "MAX_DENSITY_QUBITS", 134 "MAX_QUBITS", 135 "MaxCutQaoa", 136 "MolecularIntegrals", 137 "NoiseModel", 138 "Parameter", 139 "PauliSum", 140 "Program", 141 "Qaoa", 142 "QubitOperator", 143 "Qubo", 144 "Quotient", 145 "QuotientSearch", 146 "QuotientWalk", 147 "ReadoutCalibration", 148 "SpatialSearch", 149 "StateTransfer", 150 "StateVector", 151 "SzegedyWalk", 152 "TrajectorySimulator", 153 "VariationalClassifier", 154 "__version__", 155 "adapt_vqe", 156 "beam_splitter", 157 "bitstring", 158 "canonical_amplitude_estimation", 159 "cayley_walk_circuit", 160 "circulant_walk_circuit", 161 "classical_hitting_times", 162 "classical_walk_probabilities", 163 "diagonal_unitary_circuit", 164 "efficient_su2", 165 "estimate", 166 "estimate_expectation", 167 "estimate_phase", 168 "expectation_and_gradient", 169 "expectation_and_gradient_batch", 170 "expectation_batch", 171 "extrapolate", 172 "fold", 173 "grover_circuit", 174 "grover_search", 175 "h2_sto3g", 176 "haar_unitary", 177 "hardware_efficient", 178 "heisenberg_xxz", 179 "imaginary_time_evolution", 180 "inverse_qft", 181 "iterative_amplitude_estimation", 182 "k_upccgsd", 183 "maxcut_cost", 184 "metatron_line_lengths", 185 "ml_amplitude_estimation", 186 "natural_gradient", 187 "nearest_probability_distribution", 188 "optimize_qaoa_layerwise", 189 "pec_expectation", 190 "permanent", 191 "qaoa_maxcut_circuit", 192 "qdrift_circuit", 193 "qdrift_error_bound", 194 "qft", 195 "quantum_fisher_information", 196 "quantum_natural_gradient", 197 "real_amplitudes", 198 "run_vqe", 199 "simulate", 200 "ssvqe", 201 "transverse_field_ising", 202 "trotter_circuit", 203 "trotter_error_bound", 204 "trotter_walk_circuit", 205 "twirl", 206 "twirled_average", 207 "uccsd", 208 "vqd", 209 "zne", 210]
Amplitude a = P(objective = 1) of circuit|0⟩.
n single photons sent through an m-mode interferometer.
unitary is the m × m interferometer (input mode j → output mode
i with amplitude U[i, j]); input[j] is the number of photons
entering mode j. Probabilities are exact permanents; sample draws
exact samples (Clifford & Clifford 2018).
Probability of output for distinguishable photons.
Exact output distribution: (patterns, probabilities) with one
pattern per row.
Completely positive trace-preserving map on one or two qubits, given by Kraus operators.
Channel from explicit 2×2 or 4×4 Kraus operators (checked for
Σ K†K = I).
Pauli channel from probabilities of non-identity Pauli strings, e.g.
{"ZZ": 0.02, "XI": 0.001} (first letter on the first qubit).
Unitary channel ρ ↦ UρU† (coherent error) from a 2×2 or 4×4
unitary.
Quantum circuit with symbolic, differentiable parameters.
Builder methods return the circuit, so calls chain:
Circuit(2).h(0).cx(0, 1). Qubit 0 is the least significant bit.
Custom unitary on 1–6 targets with optional controls.
matrix is 2^k × 2^k (checked for unitarity); targets[0] is the
most significant bit of its row/column index.
Instructions as (name, targets, controls, params) tuples; params
are floats or Parameters.
Parse an OpenQASM 2.0 program; measurements are dropped. Use
Program.from_qasm for OpenQASM 3 and for programs with mid-circuit
measurements, resets or conditions.
Classical shadow: snapshots of a state measured in random Pauli bases.
snapshots snapshots of circuit(theta), measured exactly, with a
noise model or on a device (see estimate).
Coined quantum walk on the arcs u → v of a graph with the flip-flop
shift. coin is "grover" (default), "fourier", "hadamard" (degree
2 only) or a unitary matrix (regular graphs); marked nodes get the
coin −I (Shenvi–Kempe–Whaley search).
Walker at node with coin state coin (one amplitude per arc
leaving the node), by default the uniform superposition.
Probability of each node (total weight of the arcs leaving it).
Node probabilities after steps steps from start (uniform coin).
Continuous-time quantum walk |ψ(t)⟩ = exp(−iHt)|ψ(0)⟩ with
H = γL ("laplacian") or H = −γA ("adjacency").
Graphs with up to 2048 nodes are diagonalised once; larger graphs use Krylov propagation, and limiting and averaged distributions through the start node's cyclic subspace (small for symmetric graphs); the dense propagator needs at most 2048 nodes.
Infinite-time-averaged distribution (degenerate eigenspaces grouped).
Dimension of the smallest invariant subspace containing the start node: the number of distinct eigenvalues the walker sees.
Exact time average of the node probabilities over [0, t_max].
Density matrix of up to 14 qubits.
Run circuit(theta) on |0…0⟩⟨0…0|, inserting noise after every
gate if given, or with the noise of device.
Apply circuit(theta) (with optional noise or device) in place.
Measure all qubits shots times with optional readout flips
(P(1|0), P(0|1)): {bitstring: count}.
Quantum walk with site dephasing at rate rate (Lindblad evolution of
the density matrix; graphs with up to 512 nodes).
A device: per-qubit T1, T2 and readout errors, and gate rules (gate name, qubits, size) with durations, depolarising errors, over-rotations and further channels. The first matching rule applies to a gate. Builder methods return a new model.
Set T1, T2 (≤ 2·T1) and readout errors (P(1|0), P(0|1)) of qubit
q; values left out follow the default qubit.
Set the properties of every qubit not set with with_qubit.
Append a gate rule. gate ("cx", "rz", …), qubits (controls
first) and num_qubits select gates (None: any); channels act
after the gate (one-qubit channels on each qubit, two-qubit channels
on consecutive pairs).
A value with its standard error and the number of samples behind it.
Fermionic operator, parsed from text such as "0.5 [2^ 0] + 0.5 [0^ 2]"
(p^ creates, p annihilates a fermion in mode p).
Map to qubits: mapping is "jordan_wigner", "parity" or
"bravyi_kitaev"; n_modes defaults to num_modes.
Undirected weighted graph (no self loops or multi-edges) with optional 3-D node positions.
Graph from (u, v) or (u, v, w) edges; weights (one per edge)
may be given for unweighted edges.
Graph from a NetworkX graph (or anything with nodes() and
edges(data=True)); nodes are numbered in the order of nodes(),
weights are read from the edge attribute weight (default 1).
NetworkX itself is not needed.
Graph from an edge list: one u v [weight] per line, nodes from 0,
# or % comments, # nodes N for the number of nodes.
Graph from a GraphML document (nodes, edges and a weight key;
node ids are numbered in order of appearance).
Graph from a specification string such as "metatron",
"fruit-of-life", "cycle:8", "grid:3x4", "platonic:cube" or
"random-regular:12,3,7" (same syntax as the qso CLI).
Lines of Metatron's Cube of length ≤ max_length (circle
diameters).
Edge graph of a Platonic solid: tetrahedron, cube, octahedron, dodecahedron or icosahedron.
Johnson graph J(n, k): k-subsets of n elements, adjacent when they share k − 1 elements.
Kneser graph K(n, k): k-subsets, adjacent when disjoint (K(5, 2) is the Petersen graph).
Hamming graph H(d, q): words of length d over q letters, adjacent when they differ in one letter (H(d, 2) is the hypercube).
Cayley graph of Z_2^d: node x joined to x XOR g for every generator g.
The Shrikhande graph: strongly regular (16, 6, 2, 2) like the 4 × 4 rook's graph, but not isomorphic to it.
Canonical labelling: labels[u] is the canonical index of node u;
isomorphic graphs get identical canonical forms.
Graph classifier with QAOA-type quantum layers.
Each graph G defines its cut operator C_G; layers trainable blocks
exp(−iβ Σ X)·exp(−iγ C_G) act on |+⟩ⁿ with the same parameters for
every graph, and p(y = 1 | G) = σ(a·(⟨C_G⟩/W − ½) + b). Graphs are
simulated exactly, so each needs at most about 20 nodes.
Train on graphs with 0/1 labels (L-BFGS, restarts seeded
starts, best loss kept).
Coined walk on the integer line with the moving shift; coin state 0
moves left, 1 right. coin=None is the Hadamard walk.
QAOA for weighted MaxCut at depth p, simulated exactly on 2ⁿ
amplitudes. Parameters are [γ₁…γ_p, β₁…β_p].
One- and two-electron integrals of a molecule (FCIDUMP).
Qubit Hamiltonian (constant term = core energy).
Noise inserted after every gate: single_qubit channels after one-qubit
gates, multi_qubit channels after multi-qubit gates (one-qubit channels
on each qubit, two-qubit channels on consecutive pairs), plus classical
readout flips (P(1|0), P(0|1)).
Symbolic circuit parameter scale·θ[index] + offset.
Created by Circuit.new_parameter(); supports 2.0 * p, p + 0.5,
p - 0.5, p / 2 and -p.
Real linear combination of Pauli strings (a Hermitian observable).
Parsed from text such as "0.5*Z0 Z1 - 1.2 X0 + 0.3".
Exact ground-state energy on n_qubits (default: min_qubits).
A quantum program: gates, measurements into classical bits, resets and gates conditioned on bits, read from OpenQASM 2 or 3.
Bit strings put bit 0 on the right, like Circuit puts qubit 0.
The program of circuit with parameters theta bound, measuring
every qubit into the bit of the same index if measure.
Exact probabilities of the classical records, {bitstring: p}
(records with probability below 1e-15 are left out). Mid-circuit
measurements are followed branch by branch.
shots (at most 10⁷) seeded samples of the classical record,
{bitstring: count}.
QAOA for a diagonal cost with mixer "x", "xy_ring", "xy_complete"
(from the Dicke state of Hamming weight weight) or "warm_start"
(from warm_start values in [0, 1], clipped to [ε, 1 − ε]).
Linear combination of Pauli strings with complex coefficients.
Quadratic unconstrained binary optimisation min Σ Q_ij x_i x_j + offset.
Equitable partition of a graph's nodes and its quotient matrix: every
node of cell i has total edge weight matrix[i][j] into cell j.
A walker started in a cell (a single node, or the uniform superposition
over the cell) stays in the span of the cell states, so its dynamics
are exact in num_cells dimensions however large the graph is.
Build one from a graph (with_singletons, equitable, from_cells),
from a matrix (from_matrix), or directly for the distance partitions
of hypercubes, Hamming, Johnson, complete and complete multipartite
graphs, which are never built (hypercube(30) has 2^30 nodes and 31
cells).
Coarsest equitable partition in which each of nodes is a cell of
its own (the reduction for a walker started at, or a search for,
those nodes).
Quotient from cell sizes and the matrix of weights between cells
(sizes[i]·matrix[i][j] = sizes[j]·matrix[j][i] is checked).
Spatial search for marked cells of a Quotient, from the uniform
superposition (a single marked node must be a cell of its own).
⟨C|L⁺|C⟩: the Childs–Goldstone rate for one marked node of a
vertex-transitive graph, from the reduced Laplacian.
Optimise the hopping rate and the measurement time together.
t_max=None uses π√N.
Continuous-time walk on a Quotient. Starting "at cell c" means the
cell state: the node itself for a single-node cell.
Probability of each cell at time t for the walk started at start.
⟨C_to| exp(−iHt) |C_from⟩ (the node amplitude for single-node cells).
Limiting (infinite-time-averaged) probability of each cell.
Readout calibration: per-qubit (tensored) or full confusion matrix.
Tensored calibration from known per-qubit errors
[(P(1|0), P(0|1)), …] (qubit 0 first).
Full calibration from the confusion matrix A[measured, prepared]
(columns are probability distributions).
Measure a tensored calibration (|0…0⟩ and |1…1⟩, shots each).
Childs–Goldstone spatial search: start in the uniform superposition and
evolve under γL − Σ_w |w⟩⟨w| (or −γA − Σ_w |w⟩⟨w|).
Childs–Goldstone critical hopping rate (1/N) Σ_{λ>0} 1/λ over the
Laplacian spectrum.
Optimise the hopping rate (around the critical rate) and the
measurement time together. t_max=None uses π√N. On complete
graphs this recovers the exact optimum γ = 1/N with success 1.
State transfer from node u to node v: perfect state transfer
(strong cospectrality and the eigenvalue condition, decided exactly up
to floating-point tolerances), amplitudes and the best fidelity within
a time window. Runs on the quotient in which u is a single cell.
Transfer from the single-node cell from_cell to cell to_cell of
a quotient (for example Quotient.hypercube(30), cells 0 → 30).
Pure state of n qubits (2ⁿ complex amplitudes, qubit 0 least
significant).
Measure all qubits shots times: {bitstring: count} with qubit
n−1 first.
Szegedy walk of the random walk P_uv = w_uv/d_u with the marked
nodes absorbing; hitting_time is Szegedy's quantum hitting time,
which grows as the square root of the classical one.
Simulates noisy circuits by averaging quantum trajectories (Monte-Carlo wave functions) on state vectors: any register size the state-vector simulator supports.
Average of ⟨ψ|H|ψ⟩ over the trajectories, with its standard error.
Averages of several observables over the same trajectories.
Measure all qubits shots times with the device's readout errors.
Variational quantum classifier with data re-uploading;
p(y=1|x) = (1 − ⟨Z₀⟩)/2.
ADAPT-VQE from the Hartree–Fock state with the UCCSD pool (or the generalised pair-double and single pool).
Two-mode beam splitter [[cos θ, −e^{−iφ} sin θ], [e^{iφ} sin θ, cos θ]]
(theta = π/4 is 50:50).
Format basis index index as a bit string with qubit n−1 first.
Canonical (phase-estimation) amplitude estimation with m evaluation
qubits: exact outcome distribution.
Exact walk circuit for a Cayley graph of Z_2^n (hypercubes and relatives): commuting X-string rotations.
Exact walk circuit exp(−iHt) for a circulant graph on 2^n nodes
(inverse QFT, diagonal phases, QFT).
Expected hitting times of target for the discrete simple random walk
(inf for unreachable nodes).
Classical continuous-time random walk p(t) = exp(−r·t·L)·e_start.
Exact circuit for the diagonal unitary diag(exp(i·phases)) (length a
power of two), global phase included.
RY·RZ layers with CX entanglers (2n·(layers+1) parameters).
Estimate ⟨H⟩ of circuit(theta) from shots shots in total (at least
two per group), spread over the groups of qubit-wise commuting terms
(allocation: "uniform", "weighted" by Σ|c|, or "adaptive" Neyman
allocation chosen with a pilot fraction of the shots, which do not
enter the estimate). With readout_calibration the measured parities are
mitigated. Returns (estimate, groups) where each group is a dict with
basis, terms, shots and estimate.
Estimate ⟨H⟩ of circuit(theta) from shots measurements per group
of qubit-wise commuting terms — on the exact state-vector backend, with
a noise model, or on a device (density matrices, or at most
trajectories trajectories per run). See estimate for a total shot
budget, allocation and standard errors.
Phase estimation of a single-qubit unitary (2×2) with precision
counting qubits on its eigenstate (length 2).
⟨ψ(θ)|H|ψ(θ)⟩ and its gradient (adjoint, parameter_shift or
finite_difference with step step).
Values (k,) and gradients (k, num_parameters) for every row of
thetas, in parallel as for expectation_batch.
⟨H⟩ for every row of thetas (shape (k, num_parameters)); below 16
qubits the rows are evaluated in parallel, one per thread.
Extrapolate values (floats or Estimates) at scales to zero noise.
method: "linear", "richardson", "polynomial" (with degree) or
"exponential" (with asymptote).
Fold circuit to amplify its noise by about scale; returns the folded
circuit and the realised scale. folding: "global" or "random".
Grover circuit: Hadamards then iterations × (oracle, diffusion).
Simulate Grover search for marked items (iterations=None → optimal).
H₂ (STO-3G, 0.735 Å, parity mapping, 2 qubits) with reference data.
Haar-random modes × modes unitary.
layers × (rotations on every qubit, CX entanglers) plus a final
rotation layer. rotations: any of rx, ry, rz (default
("ry", "rz")); entanglement: linear, circular or full.
XXZ chain H = J Σ (X_i X_{i+1} + Y_i Y_{i+1} + Δ Z_i Z_{i+1}).
Variational imaginary-time evolution (McLachlan, RK4).
Inverse quantum Fourier transform.
Iterative amplitude estimation to half-width epsilon at confidence
1 − alpha.
k-UpCCGSD circuit with k layers.
MaxCut cost C = Σ w_uv (1 − Z_u Z_v)/2 (eigenvalue = cut weight).
Distinct line lengths of Metatron's Cube with multiplicities (ascending; the counts sum to 78).
Maximum-likelihood amplitude estimation with powers 0, 1, 2, 4, ….
Energy, gradient and natural-gradient direction (F/4 + λI)⁻¹∇E.
The probability distribution nearest to quasi-probabilities (bit strings of one length, summing to one), Smolin, Gambetta and Smith 2012.
Optimise depths 1..=p_max, seeding each with the INTERP extrapolation of the previous optimum.
Probabilistic error cancellation of the Pauli noise of device:
returns a dict with estimate, overhead (Γ) and noisy_operations.
Permanent of a square complex matrix (Glynn's formula, O(n·2ⁿ);
dimension at most 40).
Gate-level QAOA circuit for MaxCut with parameters [γ…, β…].
One random qDRIFT circuit for exp(−iHt) with samples rotations.
Campbell's bound 2λ²t²/N·e^{2λt/N} on the qDRIFT channel error.
Quantum Fourier transform on n qubits (bit-reversed output without
swaps).
Quantum Fisher information matrix F_ij = 4 Re(⟨∂iψ|∂jψ⟩ − ⟨∂iψ|ψ⟩⟨ψ|∂jψ⟩).
Minimise ⟨H⟩ by quantum natural gradient descent.
RY layers with CX entanglers (n·(layers+1) parameters).
Variational eigensolver: minimise ⟨H⟩ over the ansatz parameters from
restarts seeded random starts (run in parallel).
method: lbfgs, adam, gradient_descent, nelder_mead or spsa;
gradient: adjoint, parameter_shift or finite_difference.
Final state of circuit(theta) applied to |0…0⟩.
The lowest n_states eigenvalues by weighted subspace-search VQE.
Transverse-field Ising chain H = −J Σ Z_i Z_{i+1} − h Σ X_i.
Circuit for exp(−iHt) from steps steps of the product formula of
order (1, 2, 4, 6, …).
Upper bound on ‖U − exp(−iHt)‖ for trotter_circuit with the same
arguments (commutator bounds for orders 1 and 2).
Product-formula walk circuit for any graph: steps steps of order 1 or
2, one two-level rotation per edge; the error falls as steps^-order.
circuit with random Pauli frames around every cx, cy, cz and swap
(the ideal circuit is unchanged up to a global phase).
Average of execute(twirled) -> float | Estimate over count twirled
copies of circuit.
UCCSD circuit (Hartree–Fock state, then one parameter per excitation).
The lowest n_states eigenstates by variational quantum deflation.
Zero-noise extrapolation: fold circuit to each scale, evaluate it with
execute(folded) -> float | Estimate and extrapolate to zero noise.
Returns a dict with estimate, scales (realised) and values.