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]
class AmplitudeProblem:

Amplitude a = P(objective = 1) of circuit|0⟩.

def bernoulli(p):

One qubit with P(1) = p.

def exact(self, /):

The type of the None singleton.

def grover_operator(self, /):

The type of the None singleton.

def probabilities(self, /, powers):

P(objective = 1) in Q^k A|0⟩ for ascending powers k.

class BosonSampler:

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).

def amplitude(self, /, output):

Transition amplitude to the output occupation output.

def probability(self, /, output):

Probability of output for indistinguishable photons.

def probability_distinguishable(self, /, output):

Probability of output for distinguishable photons.

def distribution(self, /, distinguishable=False):

Exact output distribution: (patterns, probabilities) with one pattern per row.

def sample(self, /, shots, seed=0, distinguishable=False):

shots samples as an integer matrix (one output occupation per row). Indistinguishable photons need at most one photon per input mode.

n_modes
n_photons
unitary
input
class Channel:

Completely positive trace-preserving map on one or two qubits, given by Kraus operators.

def depolarizing(p):

ρ ↦ (1−p)ρ + p/3 (XρX + YρY + ZρZ).

def depolarizing_2q(p):

Two-qubit depolarising channel ρ ↦ (1−p)ρ + p/15 Σ_{P≠II} PρP.

def amplitude_damping(gamma):

Amplitude damping with decay probability gamma.

def phase_damping(lam):

Phase damping: coherences shrink by √(1−lam).

def bit_flip(p):

Bit flip with probability p.

def phase_flip(p):

Phase flip with probability p.

def thermal_relaxation(t1, t2, time):

Relaxation towards |0⟩ for duration time (t2 ≤ 2·t1).

def from_kraus(kraus, name='custom'):

Channel from explicit 2×2 or 4×4 Kraus operators (checked for Σ K†K = I).

def pauli(probabilities):

Pauli channel from probabilities of non-identity Pauli strings, e.g. {"ZZ": 0.02, "XI": 0.001} (first letter on the first qubit).

def unitary(matrix, name='unitary'):

Unitary channel ρ ↦ UρU† (coherent error) from a 2×2 or 4×4 unitary.

def rotation(pauli, angle):

Coherent rotation exp(−iθP/2) about a Pauli string ("X", "ZZ", …).

def pauli_probabilities(self, /):

Probabilities p_P (base-4 index, first qubit most significant) if this is a Pauli channel, else None.

def twirled(self, /):

The Pauli-twirled channel.

def compose(self, /, then):

then ∘ self: this channel followed by then on the same qubits.

def kraus_operators(self, /):

Kraus operators as complex matrices.

name
n_qubits
class Circuit:

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.

def h(self, /, q):

Hadamard.

def x(self, /, q):

Pauli X.

def y(self, /, q):

Pauli Y.

def z(self, /, q):

Pauli Z.

def s(self, /, q):

Phase gate S = diag(1, i).

def sdg(self, /, q):

S†.

def t(self, /, q):

T = diag(1, e^{iπ/4}).

def tdg(self, /, q):

T†.

def sx(self, /, q):

√X.

def sxdg(self, /, q):

(√X)†.

def rx(self, /, q, angle):

RX(θ) = exp(−iθX/2).

def ry(self, /, q, angle):

RY(θ) = exp(−iθY/2).

def rz(self, /, q, angle):

RZ(θ) = exp(−iθZ/2).

def p(self, /, q, angle):

Phase gate P(λ) = diag(1, e^{iλ}).

def u(self, /, q, theta, phi, lam):

Generic single-qubit gate U(θ, φ, λ) (OpenQASM convention).

def rxx(self, /, a, b, angle):

RXX(θ) = exp(−iθ X⊗X/2).

def ryy(self, /, a, b, angle):

RYY(θ) = exp(−iθ Y⊗Y/2).

def rzz(self, /, a, b, angle):

RZZ(θ) = exp(−iθ Z⊗Z/2).

def pauli_rotation(self, /, pauli, angle):

exp(−iθP/2) for a Pauli string label such as "X0 Y1 Z3".

def cx(self, /, control, target):

Controlled X (CNOT).

def cy(self, /, control, target):

Controlled Y.

def cz(self, /, control, target):

Controlled Z.

def ch(self, /, control, target):

Controlled Hadamard.

def swap(self, /, a, b):

SWAP.

def ccx(self, /, c1, c2, target):

Toffoli.

def cswap(self, /, control, a, b):

Fredkin (controlled SWAP).

def mcx(self, /, controls, target):

X on target controlled by all controls.

def mcz(self, /, qubits):

Multi-controlled Z on qubits (symmetric in its qubits).

def crx(self, /, control, target, angle):

Controlled RX.

def cry(self, /, control, target, angle):

Controlled RY.

def crz(self, /, control, target, angle):

Controlled RZ.

def cp(self, /, control, target, angle):

Controlled phase.

def unitary(self, /, matrix, targets, controls=Ellipsis):

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.

def new_parameter(self, /):

Fresh symbolic parameter.

def new_parameters(self, /, n):

n fresh symbolic parameters.

def gate_counts(self, /):

Gate counts by name; controls are prefixed with c (ccx, cry…).

def instructions(self, /):

Instructions as (name, targets, controls, params) tuples; params are floats or Parameters.

def inverse(self, /):

Adjoint circuit (gates reversed and inverted).

def bind(self, /, theta):

Copy with every parameter replaced by its value for theta.

def append(self, /, other):

Append the gates of other (on the first other.n_qubits qubits).

def append_mapped(self, /, other, qubits):

Append other with its qubit k mapped to qubits[k].

def to_qasm(self, /, theta=None, measure=False):

OpenQASM 2.0 text with parameters theta bound.

def to_qasm3(self, /, theta=None, measure=False):

OpenQASM 3.0 text with parameters theta bound.

def from_qasm(text):

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.

def copy(self, /):

The type of the None singleton.

depth
num_parameters
n_qubits
class ClassicalShadow:

Classical shadow: snapshots of a state measured in random Pauli bases.

def from_state(state, snapshots, seed=0):

snapshots random-basis snapshots of a state vector.

def collect( circuit, snapshots, theta=None, seed=0, noise=None, device=None, trajectories=None):

snapshots snapshots of circuit(theta), measured exactly, with a noise model or on a device (see estimate).

def estimate(self, /, observable):

Mean over the snapshots with its standard error.

def median_of_means(self, /, observable, groups):

Median of the means of groups blocks of snapshots.

n_qubits
class CoinedWalk:

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).

def arcs(self, /):

The arcs (tail, head) in the order of the state vector.

def localized_state(self, /, node, coin=None):

Walker at node with coin state coin (one amplitude per arc leaving the node), by default the uniform superposition.

def uniform_state(self, /):

Uniform superposition over all arcs.

def step(self, /, psi):

One step: coin, then shift.

def evolve(self, /, psi0, steps):

steps steps from psi0.

def node_probabilities(self, /, psi):

Probability of each node (total weight of the arcs leaving it).

def probabilities(self, /, start, steps):

Node probabilities after steps steps from start (uniform coin).

def search(self, /, max_steps):

Search from the uniform superposition: {"steps", "success_probability", "history"} with the step of the highest success probability within max_steps steps. The probability oscillates; about (π/2)·√(N/2) steps reach the first peak on the hypercube.

num_nodes
num_arcs

Dimension of the walk (twice the number of edges).

class ContinuousWalk:

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.

def probabilities(self, /, start, t):

Node probabilities at time t for a walker started at start.

def evolve(self, /, psi0, t):

exp(−iHt)|ψ₀⟩ for an arbitrary (not necessarily normalised) vector.

def limiting_distribution(self, /, start):

Infinite-time-averaged distribution (degenerate eigenspaces grouped).

def cyclic_dimension(self, /, start):

Dimension of the smallest invariant subspace containing the start node: the number of distinct eigenvalues the walker sees.

def average_distribution(self, /, start, t_max):

Exact time average of the node probabilities over [0, t_max].

def mixing_time(self, /, start, epsilon, t_max, steps=200):

Mixing time (Aharonov et al. 2001): smallest T on the grid t_max·k/steps from which on the time-averaged distribution stays within total-variation distance epsilon of the limit, up to t_max (None if the bound fails at t_max).

def propagator(self, /, t):

Dense propagator U(t) = exp(−iHt).

num_nodes
gamma
spectrum

Eigenvalues of H (ascending), or None for Krylov-only walks.

generator
class DensityMatrix:

Density matrix of up to 14 qubits.

def zero(n_qubits):

|0…0⟩⟨0…0|.

def maximally_mixed(n_qubits):

Maximally mixed state I/2ⁿ.

def from_pure(state):

|ψ⟩⟨ψ|.

def simulate(circuit, theta=None, noise=None, device=None):

Run circuit(theta) on |0…0⟩⟨0…0|, inserting noise after every gate if given, or with the noise of device.

def apply(self, /, circuit, theta=None, noise=None, device=None):

Apply circuit(theta) (with optional noise or device) in place.

def apply_channel(self, /, channel, qubits):

Apply channel to qubits (one or two) in place.

def probabilities(self, /):

Diagonal of ρ.

def purity(self, /):

Tr ρ² (1 for pure states, 2⁻ⁿ for the maximally mixed state).

def trace(self, /):

Tr ρ.

def expectation(self, /, observable):

Tr(ρH).

def fidelity_with_pure(self, /, state):

⟨ψ|ρ|ψ⟩.

def to_matrix(self, /):

Dense copy of ρ.

def sample(self, /, shots, seed=0, readout=None):

Measure all qubits shots times with optional readout flips (P(1|0), P(0|1)): {bitstring: count}.

def sample_with_readout(self, /, shots, readout, seed=0):

Measure all qubits with per-qubit readout errors [(P(1|0), P(0|1)), …] (qubit 0 first).

def copy(self, /):

The type of the None singleton.

n_qubits
class DephasingWalk:

Quantum walk with site dephasing at rate rate (Lindblad evolution of the density matrix; graphs with up to 512 nodes).

def populations(self, /, start, t):

Node populations at time t ≥ 0 for a walker started at start.

def evolve(self, /, rho0, t):

Evolve the density matrix rho0 (n × n) for time t ≥ 0.

num_nodes
class DeviceModel:

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.

def from_json(text):

Parse a JSON device description.

def from_noise_model(model):

The same noise as a NoiseModel.

def to_json(self, /):

The description as JSON.

def with_qubit(self, /, q, t1=None, t2=None, readout=None):

Set T1, T2 (≤ 2·T1) and readout errors (P(1|0), P(0|1)) of qubit q; values left out follow the default qubit.

def with_default_qubit(self, /, t1=None, t2=None, readout=None):

Set the properties of every qubit not set with with_qubit.

def with_rule( self, /, gate=None, qubits=None, num_qubits=None, duration=0.0, depolarizing=None, over_rotation=0.0, channels=Ellipsis):

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).

def readout_errors(self, /, n):

Readout errors (P(1|0), P(0|1)) of qubits 0..n.

num_qubits
name
idle_noise
class Estimate:

A value with its standard error and the number of samples behind it.

def confidence_interval(self, /, level=0.95):

Two-sided normal confidence interval (low, high) at level.

std_error
samples
value
class FermionOperator:

Fermionic operator, parsed from text such as "0.5 [2^ 0] + 0.5 [0^ 2]" (p^ creates, p annihilates a fermion in mode p).

def terms(self, /):

(coefficient, [(mode, is_creation), …]) pairs.

def adjoint(self, /):

The type of the None singleton.

def normal_ordered(self, /):

Canonical form: creators first, indices descending.

def is_hermitian(self, /, tol=1e-12):

The type of the None singleton.

def to_qubit(self, /, mapping='jordan_wigner', n_modes=None):

Map to qubits: mapping is "jordan_wigner", "parity" or "bravyi_kitaev"; n_modes defaults to num_modes.

num_terms
num_modes
class Graph:

Undirected weighted graph (no self loops or multi-edges) with optional 3-D node positions.

def from_edges(n, edges, weights=None):

Graph from (u, v) or (u, v, w) edges; weights (one per edge) may be given for unweighted edges.

def from_networkx(graph, weight='weight'):

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.

def from_edge_list(text):

Graph from an edge list: one u v [weight] per line, nodes from 0, # or % comments, # nodes N for the number of nodes.

def to_edge_list(self, /):

The graph as an edge list (see from_edge_list).

def from_graphml(text):

Graph from a GraphML document (nodes, edges and a weight key; node ids are numbered in order of appearance).

def to_graphml(self, /):

The graph as a GraphML document.

def add_edge(self, /, u, v, weight=1.0):

Add the edge {u, v} with weight weight (finite, non-zero).

def from_spec(spec):

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).

def metatron_cube():

Metatron's Cube: the complete graph K13 on the 13 Fruit-of-Life centres.

def fruit_of_life():

Fruit-of-Life contact graph (18 edges, symmetry group D6).

def metatron_distance_graph(max_length):

Lines of Metatron's Cube of length ≤ max_length (circle diameters).

def complete(n):

Complete graph K_n.

def cycle(n):

Cycle C_n (n ≥ 3).

def path(n):

Path P_n.

def star(n):

Star: node 0 joined to nodes 1..n.

def complete_bipartite(a, b):

Complete bipartite graph K_{a,b}.

def hypercube(d):

d-dimensional hypercube Q_d (2^d nodes, d ≤ 20).

def petersen():

The Petersen graph.

def heawood():

The Heawood graph, the smallest cubic graph of girth 6.

def grid(rows, cols, periodic=False):

rows × cols grid; a torus if periodic (each side ≥ 3).

def platonic(name):

Edge graph of a Platonic solid: tetrahedron, cube, octahedron, dodecahedron or icosahedron.

def random_regular(n, d, seed=0):

Random d-regular simple graph (n·d even, d < n).

def erdos_renyi(n, p, seed=0):

Erdős–Rényi graph G(n, p).

def johnson(n, k):

Johnson graph J(n, k): k-subsets of n elements, adjacent when they share k − 1 elements.

def kneser(n, k):

Kneser graph K(n, k): k-subsets, adjacent when disjoint (K(5, 2) is the Petersen graph).

def hamming(d, q):

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).

def rook(m, n):

Rook's graph K_m □ K_n (m × n board, adjacent in a row or column).

def paley(q):

Paley graph of prime order q ≡ 1 (mod 4).

def circulant(n, jumps):

Circulant graph: node i joined to i ± s (mod n) for every jump s.

def cayley_z2(d, generators):

Cayley graph of Z_2^d: node x joined to x XOR g for every generator g.

def shrikhande():

The Shrikhande graph: strongly regular (16, 6, 2, 2) like the 4 × 4 rook's graph, but not isomorphic to it.

def cartesian_product(self, /, other):

Cartesian product: node (g, h) has index g·|H| + h.

def strongly_regular_parameters(self, /):

(n, k, λ, μ) if the graph is strongly regular, else None.

def relabeled(self, /, perm):

The graph with node u renamed perm[u].

def canonical_labelling(self, /):

Canonical labelling: labels[u] is the canonical index of node u; isomorphic graphs get identical canonical forms.

def canonical_form(self, /):

The graph relabelled canonically.

def is_isomorphic(self, /, other):

Whether the graphs are isomorphic (edge weights included).

def isomorphism(self, /, other):

An isomorphism to other (node u maps to iso[u]), or None.

def degrees(self, /):

Node degrees.

def neighbors(self, /, u):

Sorted neighbours of u as (node, weight) pairs.

def adjacency_matrix(self, /):

Dense weighted adjacency matrix.

def laplacian_matrix(self, /):

Dense Laplacian L = D − A.

def adjacency_spectrum(self, /):

Eigenvalues of the adjacency matrix (ascending).

def laplacian_spectrum(self, /):

Eigenvalues of the Laplacian (ascending).

def summary(self, /):

Structural summary as a dict.

def automorphism_group_order(self, /):

Order of the automorphism group (None if it exceeds 2^128).

def automorphism_log10_order(self, /):

log10 of the automorphism group order (always finite).

def automorphism_orbits(self, /):

Orbits of the automorphism group (each sorted).

def automorphism_generators(self, /):

Strong generating set of the automorphism group; permutation p maps node u to p[u].

def is_connected(self, /):

The type of the None singleton.

def diameter(self, /):

Largest hop distance (None if disconnected).

def girth(self, /):

Length of the shortest cycle (None for a forest).

def triangle_count(self, /):

Number of triangles.

def copy(self, /):

The type of the None singleton.

edges

Edges (u, v, weight) with u < v, in insertion order.

num_edges
name
num_nodes
positions

Node coordinates as an (n, 3) array, or None.

class GraphClassifier:

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.

def fit(self, /, graphs, labels, max_iterations=300, restarts=4, seed=0):

Train on graphs with 0/1 labels (L-BFGS, restarts seeded starts, best loss kept).

def feature(self, /, graph, angles=None):

Normalised expected cut ⟨C_G⟩ / W(G), with the trained angles or with angles = [γ…, β…].

def predict_proba(self, /, graph):

p(y = 1 | G).

def predict(self, /, graph):

Predicted class (p ≥ ½).

def accuracy(self, /, graphs, labels):

Fraction of correctly classified graphs.

parameters

Trained parameters [γ…, β…, a, b] (empty before fit).

layers
num_parameters
class LineWalk:

Coined walk on the integer line with the moving shift; coin state 0 moves left, 1 right. coin=None is the Hadamard walk.

def distribution(self, /, steps, coin_state=None):

Position distribution after steps steps from the origin; entry k is position k − steps. The default coin state (|L⟩ + i|R⟩)/√2 gives the symmetric Hadamard walk.

MAX_DENSITY_QUBITS = 14
MAX_QUBITS = 34
class MaxCutQaoa:

QAOA for weighted MaxCut at depth p, simulated exactly on 2ⁿ amplitudes. Parameters are [γ₁…γ_p, β₁…β_p].

def expectation(self, /, params):

Expected cut weight ⟨C⟩.

def expectation_and_gradient(self, /, params):

⟨C⟩ and its exact gradient.

def analyze(self, /, params):

Statistics of the QAOA state at params.

def state(self, /, params):

QAOA state at params.

def optimize( self, /, restarts=8, seed=0, method='lbfgs', max_iterations=1000, initial=None):

Maximise ⟨C⟩ from restarts seeded starts (initial is used for the first one).

def optimal_cuts(self, /):

All optimal cuts as basis indices (bit q = side of node q).

def cut_value(self, /, b):

Weight of the cut encoded by basis index b.

max_cut

Exact maximum cut weight.

p
num_parameters
n_qubits
class MolecularIntegrals:

One- and two-electron integrals of a molecule (FCIDUMP).

def from_fcidump(text):

Parse the text of an FCIDUMP file.

def from_file(path):

Read an FCIDUMP file.

def to_fcidump(self, /):

The type of the None singleton.

def one_body(self, /, p, q):

The type of the None singleton.

def two_body(self, /, p, q, r, s):

The type of the None singleton.

def fermion_hamiltonian(self, /):

The type of the None singleton.

def qubit_hamiltonian(self, /, mapping='jordan_wigner', two_qubit_reduction=False):

Qubit Hamiltonian (constant term = core energy).

def hartree_fock_energy(self, /):

The type of the None singleton.

def hartree_fock_circuit(self, /, mapping='jordan_wigner', two_qubit_reduction=False):

X gates preparing the Hartree–Fock determinant.

def fci_energies(self, /, n_roots=1):

The lowest n_roots full-CI energies (core energy included).

n_alpha
n_orbitals
core_energy
n_beta
n_spin_orbitals
class NoiseModel:

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)).

def depolarizing(p1, p2):

Depolarising noise: p1 after one-qubit gates, two-qubit depolarising p2 after two-qubit gates.

readout
single_qubit
multi_qubit
class Parameter:

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.

def value(self, /, theta):

Value for the parameter vector theta.

offset
index
scale
class PauliSum:

Real linear combination of Pauli strings (a Hermitian observable).

Parsed from text such as "0.5*Z0 Z1 - 1.2 X0 + 0.3".

def from_terms(terms):

Sum of (coefficient, "Pauli string") terms.

def terms(self, /):

Terms as (coefficient, string) pairs ("I" for the identity).

def expectation(self, /, state):

⟨ψ|H|ψ⟩.

def ground_state_energy(self, /, n_qubits=None):

Exact ground-state energy on n_qubits (default: min_qubits).

def ground_state(self, /, n_qubits=None):

Ground-state energy and state (Lanczos) on n_qubits.

def to_matrix(self, /, n_qubits=None):

Dense 2ⁿ × 2ⁿ matrix (n ≤ 14; default min_qubits).

min_qubits

Smallest register containing every term.

num_terms
constant

Coefficient of the identity term.

class Program:

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.

def from_qasm(text):

Parse an OpenQASM 2 or 3 program (the version is read from its header).

def from_circuit(circuit, theta=None, measure=False):

The program of circuit with parameters theta bound, measuring every qubit into the bit of the same index if measure.

def probabilities(self, /):

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.

def sample(self, /, shots, seed=0):

shots (at most 10⁷) seeded samples of the classical record, {bitstring: count}.

def to_circuit(self, /):

The gates as a Circuit; a ValueError unless the program is unitary.

def to_qasm3(self, /):

OpenQASM 3.0 text of the program.

def to_qasm2(self, /):

OpenQASM 2.0 text of the program; a ValueError if it needs OpenQASM 3 (for example a condition on part of a register).

n_bits
qubit_registers

Qubit registers as {"name", "offset", "size"} dictionaries.

n_qubits
is_unitary

Whether the program has only gates.

bit_registers

Bit registers as {"name", "offset", "size"} dictionaries.

class Qaoa:

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 − ε]).

def circuit(self, /):

The parametrised circuit [γ…, β…] (apply to initial_state).

def initial_state(self, /):

The type of the None singleton.

def expectation_and_gradient(self, /, params):

(⟨C⟩, gradient) at [γ…, β…].

def analyze(self, /, params):

The type of the None singleton.

def optimize(self, /, restarts=8, seed=0, initial=None):

Minimise ⟨C⟩ from seeded random starts.

n_qubits
p
class QubitOperator:

Linear combination of Pauli strings with complex coefficients.

def terms(self, /):

(coefficient, label) pairs.

def is_hermitian(self, /, tol=1e-12):

The type of the None singleton.

def to_pauli_sum(self, /, tol=1e-12):

The operator as a PauliSum; fails if it is not Hermitian.

def adjoint(self, /):

The type of the None singleton.

def commutator(self, /, other):

[self, other].

def one_norm(self, /):

Sum of the absolute coefficients.

num_terms
class Qubo:

Quadratic unconstrained binary optimisation min Σ Q_ij x_i x_j + offset.

def from_entries(n, entries, offset=0.0):

From (i, j, value) entries.

def value(self, /, x):

f(x) for a bit mask or a 0/1 sequence.

def to_ising(self, /):

The Ising form as a dict with h, j (list of (i, j, J)) and offset.

def to_pauli_sum(self, /):

The diagonal cost Hamiltonian.

def brute_force(self, /):

(minimum, [bit masks]) by enumeration (at most 30 variables).

offset
num_variables
class Quotient:

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).

def equitable(graph, colours):

Coarsest equitable partition refining the node colouring colours.

def with_singletons(graph, nodes):

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).

def from_cells(graph, cell_of):

The partition cell_of (node → cell label), checked to be equitable.

def from_matrix(sizes, matrix):

Quotient from cell sizes and the matrix of weights between cells (sizes[i]·matrix[i][j] = sizes[j]·matrix[j][i] is checked).

def complete(n):

K_n seen from one node: the node and the n − 1 others.

def complete_multipartite(parts):

Complete multipartite graph seen from a node of the first part.

def hamming(d, q):

Hamming graph H(d, q) by distance from a word (d + 1 cells).

def hypercube(d):

Hypercube Q_d by Hamming weight (d + 1 cells, any d up to about 1000).

def johnson(n, k):

Johnson graph J(n, k) by distance from a k-subset.

def degrees(self, /):

Weighted degree of the nodes of each cell.

def adjacency(self, /):

Adjacency matrix on the normalised cell states (symmetric).

def laplacian(self, /):

Laplacian on the normalised cell states (symmetric).

def uniform_state(self, /):

The uniform superposition over all nodes in the cell basis.

def node_probabilities(self, /, per_cell):

Per-node probabilities from per-cell ones (explicit graphs only).

matrix

Weight from any node of cell i into cell j.

cell_of

Cell of every node (partitions of an explicit graph only).

name
num_nodes

Number of nodes of the graph (a float: implicit families can exceed every integer type).

num_cells
sizes

Number of nodes in each cell.

class QuotientSearch:

Spatial search for marked cells of a Quotient, from the uniform superposition (a single marked node must be a cell of its own).

def critical_gamma(quotient, cell):

⟨C|L⁺|C⟩: the Childs–Goldstone rate for one marked node of a vertex-transitive graph, from the reduced Laplacian.

def optimize( quotient, marked_cells, generator='laplacian', t_max=None, resolution=400):

Optimise the hopping rate and the measurement time together. t_max=None uses π√N.

def success_probability(self, /, t):

Probability of finding a node of a marked cell at time t.

def optimize_time(self, /, t_max, resolution=400):

Maximise the success probability over [0, t_max].

marked
gamma
class QuotientWalk:

Continuous-time walk on a Quotient. Starting "at cell c" means the cell state: the node itself for a single-node cell.

def cell_probabilities(self, /, start, t):

Probability of each cell at time t for the walk started at start.

def amplitude(self, /, from_cell, to_cell, t):

⟨C_to| exp(−iHt) |C_from⟩ (the node amplitude for single-node cells).

def evolve(self, /, c0, t):

exp(−iHt) applied to amplitudes in the cell basis.

def limiting_distribution(self, /, start):

Limiting (infinite-time-averaged) probability of each cell.

def average_distribution(self, /, start, t_max):

Exact time average of the cell probabilities over [0, t_max].

generator
spectrum

Eigenvalues of the reduced Hamiltonian (ascending).

gamma
quotient
class ReadoutCalibration:

Readout calibration: per-qubit (tensored) or full confusion matrix.

def from_errors(errors):

Tensored calibration from known per-qubit errors [(P(1|0), P(0|1)), …] (qubit 0 first).

def from_matrix(n_qubits, matrix):

Full calibration from the confusion matrix A[measured, prepared] (columns are probability distributions).

def tensored(n_qubits, shots, seed=0, noise=None, device=None, trajectories=None):

Measure a tensored calibration (|0…0⟩ and |1…1⟩, shots each).

def full(n_qubits, shots, seed=0, noise=None, device=None, trajectories=None):

Measure a full calibration (all 2ⁿ basis states, shots each).

def qubit_errors(self, /):

Per-qubit errors (P(1|0), P(0|1)).

def mitigate(self, /, counts):

Quasi-probabilities {bitstring: q} from measured counts.

n_qubits
class SpatialSearch:

Childs–Goldstone spatial search: start in the uniform superposition and evolve under γL − Σ_w |w⟩⟨w| (or −γA − Σ_w |w⟩⟨w|).

def critical_gamma(graph):

Childs–Goldstone critical hopping rate (1/N) Σ_{λ>0} 1/λ over the Laplacian spectrum.

def optimize(graph, marked, generator='laplacian', t_max=None, resolution=400):

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.

def success_probability(self, /, t):

Probability of measuring a marked node at time t.

def optimize_time(self, /, t_max, resolution=400):

Maximise the success probability over [0, t_max] (grid scan plus golden-section refinement).

marked
gamma
class StateTransfer:

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.

def from_quotient(quotient, from_cell, to_cell, generator='laplacian', gamma=1.0):

Transfer from the single-node cell from_cell to cell to_cell of a quotient (for example Quotient.hypercube(30), cells 0 → 30).

def amplitude(self, /, t):

⟨v| exp(−iHt) |u⟩.

def fidelity(self, /, t):

|⟨v| exp(−iHt) |u⟩|².

def best_transfer(self, /, t_max, resolution=2000):

Highest fidelity over [0, t_max], as {"time", "fidelity"}.

perfect_transfer_time

Earliest time of perfect state transfer, or None.

signs

Signs σ_θ with E_θ e_v = σ_θ E_θ e_u on the support, if the nodes are strongly cospectral.

strongly_cospectral
support

Distinct eigenvalues of H in the support of u.

class StateVector:

Pure state of n qubits (2ⁿ complex amplitudes, qubit 0 least significant).

def zero(n_qubits):

|0…0⟩.

def plus(n_qubits):

Uniform superposition |+⟩^⊗n.

def basis(n_qubits, index):

Computational basis state |index⟩.

def from_amplitudes(amplitudes):

State from amplitudes (length a power of two; normalised).

def random(n_qubits, seed=0):

Haar-random state.

def probabilities(self, /):

Probabilities of all basis states.

def sample(self, /, shots, seed=0):

Measure all qubits shots times: {bitstring: count} with qubit n−1 first.

def expectation(self, /, observable):

⟨ψ|H|ψ⟩.

def inner(self, /, other):

⟨self|other⟩.

def fidelity(self, /, other):

|⟨self|other⟩|².

def entanglement_entropy(self, /, qubits):

Von Neumann entropy (bits) of qubits against the rest.

def reduced_density_matrix(self, /, qubits):

Reduced density matrix of qubits (qubits[j] is bit j of the row/column index).

def apply(self, /, circuit, theta=None):

Apply circuit(theta) in place; returns the state.

def copy(self, /):

The type of the None singleton.

n_qubits
amplitudes

Amplitudes as a complex128 array (a copy).

class SzegedyWalk:

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.

def stationary_state(self, /):

The start state |π⟩ in the arc basis.

def step(self, /, psi):

One step W' = (S·R)².

def deviations(self, /, steps):

‖W'^t|π⟩ − |π⟩‖² for t = 0, …, steps.

def hitting_time(self, /, max_steps):

Quantum hitting time, or None if not reached within max_steps.

marked_weight

Stationary probability of the marked set.

dimension

Number of arcs the walk acts on.

class TrajectorySimulator:

Simulates noisy circuits by averaging quantum trajectories (Monte-Carlo wave functions) on state vectors: any register size the state-vector simulator supports.

def expectation(self, /, circuit, observable, theta=None):

Average of ⟨ψ|H|ψ⟩ over the trajectories, with its standard error.

def expectations(self, /, circuit, observables, theta=None):

Averages of several observables over the same trajectories.

def sample(self, /, circuit, shots, theta=None):

Measure all qubits shots times with the device's readout errors.

def density_matrix(self, /, circuit, theta=None):

Average of |ψ⟩⟨ψ| over the trajectories (up to 14 qubits).

def trajectory_state(self, /, circuit, k, theta=None):

Final state of trajectory k.

trajectories
class VariationalClassifier:

Variational quantum classifier with data re-uploading; p(y=1|x) = (1 − ⟨Z₀⟩)/2.

def fit(self, /, xs, ys, max_iterations=200, seed=0):

Train on samples xs (shape (m, n_features)) and 0/1 labels ys with L-BFGS from a seeded start.

def predict_proba(self, /, x):

p(y=1|x): a float for one sample, an array for a 2-D batch.

def predict(self, /, x):

Predicted class (p ≥ ½): a bool for one sample, an array for a batch.

def accuracy(self, /, xs, ys):

Fraction of correctly classified samples.

n_features
parameters

Trained parameters (empty before fit).

layers
n_qubits
num_parameters
__version__ = '1.4.0'
def adapt_vqe( molecule, mapping='jordan_wigner', two_qubit_reduction=False, generalized=False, gradient_tolerance=0.001, max_operators=40):

ADAPT-VQE from the Hartree–Fock state with the UCCSD pool (or the generalised pair-double and single pool).

def beam_splitter(theta, phi=0.0):

Two-mode beam splitter [[cos θ, −e^{−iφ} sin θ], [e^{iφ} sin θ, cos θ]] (theta = π/4 is 50:50).

def bitstring(index, n_qubits):

Format basis index index as a bit string with qubit n−1 first.

def canonical_amplitude_estimation(problem, m):

Canonical (phase-estimation) amplitude estimation with m evaluation qubits: exact outcome distribution.

def cayley_walk_circuit(graph, t, generator='laplacian', gamma=1.0):

Exact walk circuit for a Cayley graph of Z_2^n (hypercubes and relatives): commuting X-string rotations.

def circulant_walk_circuit(graph, t, generator='laplacian', gamma=1.0):

Exact walk circuit exp(−iHt) for a circulant graph on 2^n nodes (inverse QFT, diagonal phases, QFT).

def classical_hitting_times(graph, target):

Expected hitting times of target for the discrete simple random walk (inf for unreachable nodes).

def classical_walk_probabilities(graph, start, t, rate=1.0):

Classical continuous-time random walk p(t) = exp(−r·t·L)·e_start.

def diagonal_unitary_circuit(phases):

Exact circuit for the diagonal unitary diag(exp(i·phases)) (length a power of two), global phase included.

def efficient_su2(n, layers, entanglement='linear'):

RY·RZ layers with CX entanglers (2n·(layers+1) parameters).

def estimate( circuit, observable, shots, theta=None, allocation='weighted', pilot=0.1, readout_calibration=None, seed=0, noise=None, device=None, trajectories=None):

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.

def estimate_expectation( circuit, observable, theta=None, shots=10000, seed=0, noise=None, device=None, trajectories=None):

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.

def estimate_phase(precision, unitary, eigenstate):

Phase estimation of a single-qubit unitary (2×2) with precision counting qubits on its eigenstate (length 2).

def expectation_and_gradient( circuit, observable, theta, method='adjoint', step=1e-05, initial_state=None):

⟨ψ(θ)|H|ψ(θ)⟩ and its gradient (adjoint, parameter_shift or finite_difference with step step).

def expectation_and_gradient_batch( circuit, observable, thetas, method='adjoint', step=1e-05, initial_state=None):

Values (k,) and gradients (k, num_parameters) for every row of thetas, in parallel as for expectation_batch.

def expectation_batch(circuit, observable, thetas, initial_state=None):

⟨H⟩ for every row of thetas (shape (k, num_parameters)); below 16 qubits the rows are evaluated in parallel, one per thread.

def extrapolate(scales, values, method='richardson', degree=None, asymptote=0.0):

Extrapolate values (floats or Estimates) at scales to zero noise. method: "linear", "richardson", "polynomial" (with degree) or "exponential" (with asymptote).

def fold(circuit, scale, folding='global', seed=0):

Fold circuit to amplify its noise by about scale; returns the folded circuit and the realised scale. folding: "global" or "random".

def grover_circuit(n_qubits, marked, iterations=None):

Grover circuit: Hadamards then iterations × (oracle, diffusion).

def h2_sto3g():

H₂ (STO-3G, 0.735 Å, parity mapping, 2 qubits) with reference data.

def haar_unitary(modes, seed=0):

Haar-random modes × modes unitary.

def hardware_efficient(n, layers, rotations=None, entanglement='linear'):

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.

def heisenberg_xxz(n, j, delta, periodic=False):

XXZ chain H = J Σ (X_i X_{i+1} + Y_i Y_{i+1} + Δ Z_i Z_{i+1}).

def imaginary_time_evolution( circuit, observable, theta, time, steps=100, initial_state=None, rcond=1e-08):

Variational imaginary-time evolution (McLachlan, RK4).

def inverse_qft(n, swaps=True):

Inverse quantum Fourier transform.

def iterative_amplitude_estimation(problem, epsilon=0.01, alpha=0.05, shots=100, seed=0):

Iterative amplitude estimation to half-width epsilon at confidence 1 − alpha.

def k_upccgsd(molecule, k=1, mapping='jordan_wigner', two_qubit_reduction=False):

k-UpCCGSD circuit with k layers.

def maxcut_cost(graph):

MaxCut cost C = Σ w_uv (1 − Z_u Z_v)/2 (eigenvalue = cut weight).

def metatron_line_lengths():

Distinct line lengths of Metatron's Cube with multiplicities (ascending; the counts sum to 78).

def ml_amplitude_estimation(problem, levels=6, shots=100, confidence=0.95, seed=0):

Maximum-likelihood amplitude estimation with powers 0, 1, 2, 4, ….

def natural_gradient(circuit, observable, theta, initial_state=None, regularization=0.001):

Energy, gradient and natural-gradient direction (F/4 + λI)⁻¹∇E.

def nearest_probability_distribution(quasi):

The probability distribution nearest to quasi-probabilities (bit strings of one length, summing to one), Smolin, Gambetta and Smith 2012.

def optimize_qaoa_layerwise( graph, p_max, restarts=4, seed=0, method='lbfgs', max_iterations=1000):

Optimise depths 1..=p_max, seeding each with the INTERP extrapolation of the previous optimum.

def pec_expectation(circuit, observable, device, samples, theta=None, seed=0):

Probabilistic error cancellation of the Pauli noise of device: returns a dict with estimate, overhead (Γ) and noisy_operations.

def permanent(matrix):

Permanent of a square complex matrix (Glynn's formula, O(n·2ⁿ); dimension at most 40).

def qaoa_maxcut_circuit(graph, p):

Gate-level QAOA circuit for MaxCut with parameters [γ…, β…].

def qdrift_circuit(hamiltonian, n_qubits, t, samples, seed=0):

One random qDRIFT circuit for exp(−iHt) with samples rotations.

def qdrift_error_bound(hamiltonian, t, samples):

Campbell's bound 2λ²t²/N·e^{2λt/N} on the qDRIFT channel error.

def qft(n, swaps=True):

Quantum Fourier transform on n qubits (bit-reversed output without swaps).

def quantum_fisher_information(circuit, theta, initial_state=None):

Quantum Fisher information matrix F_ij = 4 Re(⟨∂iψ|∂jψ⟩ − ⟨∂iψ|ψ⟩⟨ψ|∂jψ⟩).

def quantum_natural_gradient( circuit, observable, theta, initial_state=None, learning_rate=0.1, regularization=0.001, max_iterations=500, gradient_tolerance=1e-06):

Minimise ⟨H⟩ by quantum natural gradient descent.

def real_amplitudes(n, layers, entanglement='linear'):

RY layers with CX entanglers (n·(layers+1) parameters).

def run_vqe( hamiltonian, ansatz, method='lbfgs', restarts=4, seed=0, max_iterations=1000, gradient='adjoint', initial_parameters=None, initial_state=None):

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.

def simulate(circuit, theta=None):

Final state of circuit(theta) applied to |0…0⟩.

def ssvqe(hamiltonian, ansatz, n_states, restarts=4, seed=0, weights=None):

The lowest n_states eigenvalues by weighted subspace-search VQE.

def transverse_field_ising(n, j, h, periodic=False):

Transverse-field Ising chain H = −J Σ Z_i Z_{i+1} − h Σ X_i.

def trotter_circuit(hamiltonian, n_qubits, t, steps=1, order=2):

Circuit for exp(−iHt) from steps steps of the product formula of order (1, 2, 4, 6, …).

def trotter_error_bound(hamiltonian, t, steps=1, order=2):

Upper bound on ‖U − exp(−iHt)‖ for trotter_circuit with the same arguments (commutator bounds for orders 1 and 2).

def trotter_walk_circuit(graph, t, steps, order=2, generator='laplacian', gamma=1.0):

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.

def twirl(circuit, seed=0):

circuit with random Pauli frames around every cx, cy, cz and swap (the ideal circuit is unchanged up to a global phase).

def twirled_average(circuit, count, execute, seed=0):

Average of execute(twirled) -> float | Estimate over count twirled copies of circuit.

def uccsd(molecule, mapping='jordan_wigner', two_qubit_reduction=False):

UCCSD circuit (Hartree–Fock state, then one parameter per excitation).

def vqd(hamiltonian, ansatz, n_states, restarts=4, seed=0, betas=None):

The lowest n_states eigenstates by variational quantum deflation.

def zne( circuit, scales, execute, folding='global', seed=0, method='richardson', degree=None, asymptote=0.0):

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.