QPU

Everything needed to run an HQSMPO head/tail split on a quantum device. The pipeline is three steps, one subpackage each, and every circuit is decided classically before anything reaches a backend.

Running part of an expectation value on a QPU.

HQSMPO splits a circuit’s dressed rotations into a head, run on the device, and a tail, folded classically into the observable. Getting from that split to a number is a three-step pipeline, one subpackage each:

  1. synthesis turns the head into a runnable circuit plus a pure-Clifford residual, folded into the observable.

  2. measurement fixes the circuits and shots that measure the folded observable, and turns the measured frequencies into an ExpectationResult.

  3. execution runs those circuits on a backend, or exports them as OpenQASM to run on a device.

Synthesisers and measurement methods are objects holding their own options, passed to HQSMPO:

from mpstab import HQSMPO
from mpstab.qpu import ClassicalShadows, ExtractionSynthesis

model = HQSMPO(ansatz, head_synthesis=ExtractionSynthesis(connectivity="line"))
result = model.expectation_at_cut(H, cut_index, method=ClassicalShadows(), n_shots=10_000)

Importing this package never requires the optional rustiq dependency: rustiq only needs it when it synthesises.

Synthesis

Turns a head’s dressed rotations into a runnable circuit plus a pure-Clifford residual.

Step 1 of the QPU pipeline: head synthesis.

A head of dressed Pauli rotations is turned into a hardware-native gate list plus a pure-Clifford residual applied last:

target = U(residual) . U(head)
<target|O|target> = <head 0| residual^dag . O . residual |head 0>

The residual is therefore reabsorbed into the observable with a Clifford simulator (conjugate()), never with dense matrices.

A synthesiser is a HeadSynthesis holding its own options. Three are available, one module each:

  • RustiqSynthesis: rustiq’s Pauli-network synthesis (optional dependency, needed only when synthesising).

  • ExtractionSynthesis: Clifford extraction, dependency-free and connectivity-aware.

  • CnotLadderSynthesis: the textbook decomposition, with an identity residual.

synthesize(paulis, angles) returns (head, residual_tableau, residual_gates), with head in the gate-list format of utils.

mpstab.qpu.synthesis.resolve_synthesis(synthesis) → HeadSynthesis[source]

A HeadSynthesis from either an instance, returned as is, or its name, giving the default options.

Raises:

ValueError – on an unknown name.

The interface every head synthesiser implements.

class mpstab.qpu.synthesis.abstract.HeadSynthesis[source]

Bases: ABC

How a head of dressed Pauli rotations becomes a runnable gate list plus a pure-Clifford residual, applied last.

Subclasses are frozen dataclasses holding their own options, so an instance is hashable and resynthesize_head() can cache resyntheses on it. They implement _synthesize().

name: ClassVar[str]

Short name, reported as method.

synthesize(paulis: list[str], angles: list[float], nqubits: int | None = None) → tuple[source]

Synthesise the rotations exp(-i angle P / 2), in order.

Parameters:
  • paulis – dressed Pauli axis strings (qubit-0-leftmost), in circuit order.

  • angles – matching rotation angles.

  • nqubits – circuit width; defaults to the width of the strings, and sizes the residual of an empty head.

Returns:

the head as a gate list in the format of utils, and the Clifford residual both as a stim.Tableau and as a gate list.

Return type:

(head, residual_tableau, residual_gates)

Head synthesis with rustiq’s Pauli-network synthesis, which cancels gates across rotations.

rustiq is optional and not on PyPI: this module imports without it, and synthesising raises an ImportError with the install hint pip install git+https://github.com/smartiel/rustiq.git.

class mpstab.qpu.synthesis.rustiq.RustiqSynthesis(metric: str = 'count', preserve_order: bool = True)[source]

Bases: HeadSynthesis

rustiq’s Pauli-network synthesis, which cancels gates across rotations.

rustiq.pauli_network_synthesis called with fix_clifford=False returns a skeleton that is a prefix of the one it returns with fix_clifford=True. The prefix becomes the head; what the longer version appends is the residual. The residual gate list is non-deterministic across runs (fix_clifford=True draws randomly) even though the Clifford it implements is unique, so compare tableaus rather than gate lists.

Parameters:
  • metric – what rustiq minimises, "count" or "depth".

  • preserve_order – keep the (non-commuting) rotation order.

name: ClassVar[str] = 'rustiq'

Short name, reported as method.

synthesize(paulis, angles, nqubits=None)[source]

Synthesise the rotations exp(-i angle P / 2), in order.

Parameters:
  • paulis – dressed Pauli axis strings (qubit-0-leftmost), in circuit order.

  • angles – matching rotation angles.

  • nqubits – circuit width; defaults to the width of the strings, and sizes the residual of an empty head.

Returns:

the head as a gate list in the format of utils, and the Clifford residual both as a stim.Tableau and as a gate list.

Return type:

(head, residual_tableau, residual_gates)

Head synthesis by Clifford extraction (the idea of QuCLEAR, arXiv:2408.13316).

Each rotation is reduced to a single qubit by a Clifford that is never undone but pushed through the rotations still to come. It needs no extra dependency and can be told the device connectivity, so that the CNOTs it chooses stay local.

mpstab.qpu.synthesis.extraction.EXTRACTION_STRATEGIES = ({'locality': 2.0, 'lookahead': 8, 'reorder': True}, {'locality': 2.0, 'lookahead': 8, 'reorder': False}, {'locality': 2.0, 'lookahead': 4, 'reorder': False}, {'locality': 0.0, 'lookahead': 8, 'reorder': True}, {'locality': 0.0, 'lookahead': 8, 'reorder': False})

What ExtractionSynthesis tries, keeping the cheapest: locality weighs how far apart the sites of the coming strings end up (it only matters with a connectivity), reorder lets a rotation overtake the ones it commutes with, lookahead is how many coming strings a CNOT is judged on. No single setting wins on every circuit.

class mpstab.qpu.synthesis.extraction.ExtractionSynthesis(connectivity: object = None, strategies: tuple = ({'locality': 2.0, 'lookahead': 8, 'reorder': True}, {'locality': 2.0, 'lookahead': 8, 'reorder': False}, {'locality': 2.0, 'lookahead': 4, 'reorder': False}, {'locality': 0.0, 'lookahead': 8, 'reorder': True}, {'locality': 0.0, 'lookahead': 8, 'reorder': False}))[source]

Bases: HeadSynthesis

Synthesise a head circuit and its pure-Clifford residual by Clifford extraction. Deterministic.

A rotation of a weight-w string needs w - 1 CNOTs to bring it onto one qubit, and the textbook circuit spends as many again to undo them. Here they are not undone: the Clifford is pushed through the rotations still to come, whose strings change accordingly, and what has accumulated at the end is the residual, folded into the observable. This is the idea of QuCLEAR (Liu et al., arXiv:2408.13316); the choice of each CNOT is our own greedy rule, see _extraction_skeleton().

Every strategy of strategies is run and the cheapest head kept, cost being the two-qubit gates the device would need: with a connectivity a CNOT between distant qubits is charged the SWAPs that route it.

Parameters:
  • connectivity – None (all-to-all), "line", or the edges [(q0, q1), ...] of the device coupling graph, in the qubit numbering of the strings. The CNOTs chosen stay local on it.

  • strategies – the settings to try, keeping the cheapest head, see EXTRACTION_STRATEGIES.

name: ClassVar[str] = 'extraction'

Short name, reported as method.

mpstab.qpu.synthesis.extraction.connectivity_distances(connectivity, nqubits: int)[source]

All-pairs distances of a device connectivity, as a nqubits x nqubits list, or None for all-to-all.

Parameters:
  • connectivity – None (all-to-all), "line" (qubit q next to q + 1), or the edges [(q0, q1), ...] of the coupling graph.

  • nqubits – number of qubits.

Head synthesis by the textbook CNOT-ladder decomposition: no extra dependency, 2*(w-1) CNOTs per weight-w rotation, and an identity residual.

class mpstab.qpu.synthesis.cnot_ladder.CnotLadderSynthesis[source]

Bases: HeadSynthesis

Decompose every dressed rotation into an exact CNOT-ladder circuit.

Uses the textbook identity exp(-i theta P / 2) = U^dag L^dag RZ(theta) L U, where U rotates every non-identity site of P into the Z frame and L is a CNOT ladder chaining the parity of the support onto its last qubit. Every gate is placed exactly, so nothing is left over and the residual is the identity – at the cost of 2*(w-1) CNOTs per weight-w rotation and no cancellation across rotations.

name: ClassVar[str] = 'cnot_ladder'

Short name, reported as method.

The gate-list format every head synthesiser returns, and what they share.

A synthesised head is a list of two entry shapes: a placed rotation (axis, [qubit], angle) with axis in ROTATION_GATES, or a Clifford gate (name, qubits) with name in CLIFFORD_GATES.

mpstab.qpu.synthesis.utils.CLIFFORD_GATES = {'CNOT': <class 'qibo.gates.gates.CNOT'>, 'CZ': <class 'qibo.gates.gates.CZ'>, 'H': <class 'qibo.gates.gates.H'>, 'S': <class 'qibo.gates.gates.S'>, 'Sd': <class 'qibo.gates.gates.SDG'>, 'SqrtX': <class 'qibo.gates.gates.SX'>, 'SqrtXd': <class 'qibo.gates.gates.SXDG'>, 'X': <class 'qibo.gates.gates.X'>, 'Y': <class 'qibo.gates.gates.Y'>, 'Z': <class 'qibo.gates.gates.Z'>}

Clifford gate names appearing in a synthesised gate list, and their qibo gates.

mpstab.qpu.synthesis.utils.CLIFFORD_TABLEAUS = {'CNOT': stim.Tableau.from_conjugated_generators(     xs=[         stim.PauliString("+XX"),         stim.PauliString("+_X"),     ],     zs=[         stim.PauliString("+Z_"),         stim.PauliString("+ZZ"),     ], ), 'CZ': stim.Tableau.from_conjugated_generators(     xs=[         stim.PauliString("+XZ"),         stim.PauliString("+ZX"),     ],     zs=[         stim.PauliString("+Z_"),         stim.PauliString("+_Z"),     ], ), 'H': stim.Tableau.from_conjugated_generators(     xs=[         stim.PauliString("+Z"),     ],     zs=[         stim.PauliString("+X"),     ], ), 'S': stim.Tableau.from_conjugated_generators(     xs=[         stim.PauliString("+Y"),     ],     zs=[         stim.PauliString("+Z"),     ], ), 'Sd': stim.Tableau.from_conjugated_generators(     xs=[         stim.PauliString("-Y"),     ],     zs=[         stim.PauliString("+Z"),     ], ), 'SqrtX': stim.Tableau.from_conjugated_generators(     xs=[         stim.PauliString("+X"),     ],     zs=[         stim.PauliString("-Y"),     ], ), 'SqrtXd': stim.Tableau.from_conjugated_generators(     xs=[         stim.PauliString("+X"),     ],     zs=[         stim.PauliString("+Y"),     ], ), 'X': stim.Tableau.from_conjugated_generators(     xs=[         stim.PauliString("+X"),     ],     zs=[         stim.PauliString("-Z"),     ], ), 'Y': stim.Tableau.from_conjugated_generators(     xs=[         stim.PauliString("-X"),     ],     zs=[         stim.PauliString("-Z"),     ], ), 'Z': stim.Tableau.from_conjugated_generators(     xs=[         stim.PauliString("-X"),     ],     zs=[         stim.PauliString("+Z"),     ], )}

The same Clifford names as stim tableaus, for tracking Pauli images.

mpstab.qpu.synthesis.utils.ROTATION_GATES = {'RX': <class 'qibo.gates.gates.RX'>, 'RY': <class 'qibo.gates.gates.RY'>, 'RZ': <class 'qibo.gates.gates.RZ'>}

Rotation axis names appearing in a synthesised gate list, and their qibo gates.

mpstab.qpu.synthesis.utils.count_two_qubit_gates(head: list[tuple]) → int[source]

Number of two-qubit gates in a synthesised gate list.

mpstab.qpu.synthesis.utils.head_to_qibo_circuit(head: list[tuple], nqubits: int) → Circuit[source]

Convert a synthesised gate list into a runnable qibo Circuit.

mpstab.qpu.synthesis.utils.place_rotations(skeleton, paulis, angles, nqubits) → list[source]

Interleave one single-qubit rotation per Pauli into a Clifford skeleton.

A rotation can be emitted once its Pauli image has collapsed onto a single qubit and no earlier unresolved rotation anticommutes with it. Each image is carried as a stim.PauliString and updated only when a skeleton gate touches its support; the anticommutation graph is precomputed as bitmasks so the blocking test is a counter rather than a scan.

Measurement

Fixes the circuits and shots that measure the tail-folded observable, and recombines the measured frequencies into an expectation value with its error bars. One module per method.

Step 2 of the QPU pipeline: measuring the tail-folded observable.

A method is a MeasurementMethod holding its own options, with both halves of the job: building the MeasurementPlan (circuits and shots, fixed before anything runs) and estimating an ExpectationResult from the measured frequencies. One module each:

  • PauliSampling ("pauli"): sampled Pauli strings, grouped into qubit-wise-commuting settings.

  • ClassicalShadows ("shadows"): random Pauli bases, contracted with the observable MPO.

pauli_expansion turns the observable MPO into Pauli strings and variances, for the methods above.

mpstab.qpu.measurement.estimate(plan, frequencies, seed=None, **options) → ExpectationResult[source]

Recombine a plan’s frequencies with the method that built it, chosen by plan.method: the entry point for counts measured offline.

Parameters:
  • plan – a MeasurementPlan.

  • frequencies – one {bitstring: count} dict per circuit, in plan.circuits order.

  • seed – forwarded to the method’s estimate; the built-in methods ignore it, since their estimates involve no randomness.

  • options – options of the method, e.g. tail_handling for "shadows".

mpstab.qpu.measurement.resolve_method(method, **options) → MeasurementMethod[source]

A MeasurementMethod from either an instance, returned as is, or its name, built with options.

Raises:
  • ValueError – on an unknown name.

  • TypeError – if options come with an instance, which already holds its own, or are not options of the named method.

What every measurement method shares: the plan it builds before anything runs, and the result it estimates afterwards.

A MeasurementPlan fixes every circuit and its shot count up front, so the same plan can be replayed on a simulator or on hardware, and estimation only ever reads back frequencies.

Basis rotation is left to qibo: gates.M(*qubits, basis=[...]) measures each qubit in the given single-qubit Pauli basis, so no basis-change circuit is built here.

class mpstab.qpu.measurement.abstract.ExpectationResult(value: float, stderr: float, truncation_l1: object, truncation_l2: float, n_settings: int, n_shots: int, retained_weight: float | None = None, state_fidelity: float | None = None, bond_truncation_l2: float | None = None, antihermitian_l2: float | None = None)[source]

Bases: object

A measured expectation value, its shot noise and its truncation budget.

Variables:
  • value (float) – the (real) expectation value.

  • stderr (float) – standard error from shot noise alone.

  • truncation_l1 (object) – heuristic discarded-Pauli-mass estimate (see truncation_error_estimate() – an extrapolation, not a rigorous bound); None for the "shadows" route, whose bond truncation has no L1/L2 split.

  • truncation_l2 (float) – typical-case truncation estimate – Pauli-set truncation for "pauli", MPO bond truncation for "shadows".

  • n_settings (int) – number of distinct circuits the shots came from.

  • n_shots (int) – total shots used.

  • retained_weight (float | None) – "pauli" only, None otherwise – see retained_weight.

  • state_fidelity (float | None) – "simulation" only, None otherwise: the squared norm of the head MPS, which its truncation pushes below 1. The hardware methods run the head on the device, so they have no head truncation to report.

  • bond_truncation_l2 (float | None) – "pauli" only, None otherwise (there truncation_l2 already is the fold truncation): the bias estimate of truncating the tail fold (bond cap or SVD cutoff) – see bond_truncation_l2. Part of total_error.

  • antihermitian_l2 (float | None) – "pauli" only, None otherwise: the size of the anti-Hermitian part the bond truncation left in the sampled coefficients, which was projected out – see antihermitian_l2. A diagnostic, not part of total_error.

property total_error: float

A practical accuracy bound, not a standard error itself: sqrt(stderr**2 + truncation_l2**2 + bond_truncation_l2**2) (the last term for "pauli" only, where truncation_l2 is the Pauli-set truncation and the bond truncation is reported apart), combining contributions of different nature in quadrature. stderr is a statistical quantity (shot noise, shrinks with more shots); truncation_l2 is a systematic-bias estimate (bond-dimension or Pauli-coverage truncation, independent of shot count – see truncation_l1 and retained_weight to tell which one is dominating). Combining them in quadrature is a convenient, common convention, not a rigorous derivation of a single confidence interval – but it is still the number to report in a results table, since stderr alone omits the truncation bias entirely. For "simulation" it covers the tail truncation only; the head truncation shows in state_fidelity.

class mpstab.qpu.measurement.abstract.MeasurementMethod[source]

Bases: ABC

How the tail-folded observable is measured: which circuits to run with how many shots (build_plan()), and how their counts become an expectation value (estimate()).

Subclasses are frozen dataclasses holding their own options, passed as method to plan() and expectation_at_cut().

abstractmethod build_plan(model, terms: dict, constant: float, cut_index: int, resynthesis, max_bond_dimension, n_shots, epsilon, seed) → MeasurementPlan[source]

Fold the tail of every term and fix the circuits and shots.

Parameters:
  • model – the HQSMPO whose tail is folded.

  • terms – the observable’s {pauli_string: coefficient}.

  • constant – the observable’s identity offset, added back on estimation.

  • cut_index – the split point.

  • resynthesis – the head, a ResynthesizedHead.

  • max_bond_dimension – bond cap for every tail fold, None for an exact fold.

  • n_shots – a fixed shot budget, or None to size it from epsilon.

  • epsilon – a target standard error, or None when n_shots is given.

  • seed – RNG seed.

abstractmethod estimate(plan: MeasurementPlan, frequencies, seed=None)[source]

Recombine one frequency dict per circuit, in plan.circuits order, into an ExpectationResult.

name: ClassVar[str]

Short name, stored as MeasurementPlan.method.

class mpstab.qpu.measurement.abstract.MeasurementPlan(method: str, circuits: tuple, shots: tuple, recombination: object, constant: float, truncation_l1: float | None, truncation_l2: float, retained_weight: float | None = None, bond_truncation_l2: float | None = None, antihermitian_l2: float | None = None)[source]

Bases: object

Circuits and their shot allocation, with whatever the estimator needs to recombine the results.

recombination is route-specific:

  • "pauli": (groups, coefficients), one QWCGroup per circuit in the same order, plus the {pauli_string: c_P} map the groups came from.

  • "shadows": (mpo_terms, bases), where mpo_terms holds (label, coefficient, sign, mpo) per Hamiltonian term, the folded tail mpo as its site arrays (operator_site_arrays()), and bases has one basis string per circuit.

Variables:
  • retained_weight (float | None) – "pauli" only, None for "shadows" (which sample nothing): the |coefficient|-weighted average, over Hamiltonian terms, of each term’s retained_weight – the fraction of the tail-folded observable’s Frobenius weight that n_string_samples actually covered.

  • bond_truncation_l2 (float | None) – "pauli" only, None for "shadows" (whose truncation_l2 already is this quantity): the bias estimate of truncating the tail fold (bond cap or SVD cutoff), sum_terms |coefficient| * sqrt(1 - ||O'||_F**2 / 2**n), from the norm each folded MPO lost. 0.0 for an untruncated fold (no bond cap and no SVD cutoff) or a loss within rounding. The "pauli" route’s truncation_l1/truncation_l2 only count the Pauli strings left unsampled of the already truncated MPO, so they miss it.

  • antihermitian_l2 (float | None) – "pauli" only, None otherwise: the size of the anti-Hermitian part the bond truncation left in the sampled coefficients and that was projected out, sqrt(sum_P Im(c_P)**2). A diagnostic of how hard the truncation hit, not an error of the estimate: the projection never moves the operator away from the exact, Hermitian one.

result(value, stderr, n_shots, n_settings) → ExpectationResult[source]

An ExpectationResult carrying this plan’s truncation diagnostics.

mpstab.qpu.measurement.abstract.basis_measurement(basis: str, nqubits: int) → Circuit[source]

A single gates.M layer measuring each qubit in its given Pauli basis.

mpstab.qpu.measurement.abstract.weighted_mean_and_variance(values, weights) → tuple[source]

(mean, variance of a single draw) of values repeated weights times each, the variance with Bessel’s correction.

The "pauli" method: measure the sampled Pauli strings of the tail-folded observable, grouped into qubit-wise-commuting settings.

class mpstab.qpu.measurement.pauli.PauliMeasurementPlan(groups: tuple, coefficients: dict)[source]

Bases: object

QWC groups plus the Pauli coefficients they were built from.

property group_variances: tuple

Per-group a-priori variance, sum_{P in group} |c_P|**2.

Each member’s single-shot parity variance is bounded by 1, saturated when <P> = 0, and covariance between members of a group is neglected. Needs no sampling and no state, which is what lets shot allocation and shot budgeting be decided up front.

shots_for_precision(epsilon: float) → float[source]

Total shots predicted for standard error epsilon under variance-proportional (Neyman-optimal) allocation across groups, (sum_G sqrt(V_G))**2 / epsilon**2.

By Cauchy-Schwarz sqrt(V_G) <= sum_{P in G} |c_P|, so this is never above the ungrouped ||c||_1**2 / epsilon**2: the difference is what grouping saves.

class mpstab.qpu.measurement.pauli.PauliSampling(n_string_samples: int = 200)[source]

Bases: MeasurementMethod

The "pauli" method: sample Pauli strings from each term’s tail MPO, pool them, fold the Clifford residual into them, and measure them grouped into qubit-wise-commuting settings.

Parameters:

n_string_samples – Pauli strings sampled per Hamiltonian term.

build_plan(model, terms, constant, cut_index, resynthesis, max_bond_dimension, n_shots, epsilon, seed) → MeasurementPlan[source]

Sample each term’s tail MPO, pool the strings, fold the residual, group.

Two truncations are reported, of different origin. truncation_l1 / truncation_l2 count the Pauli strings of each folded MPO that n_string_samples left out. bond_truncation_l2 is the bias of truncating the fold (bond cap or SVD cutoff), estimated from each folded MPO’s norm (see fold_fidelity()) as in the "shadows" method: the string truncation is measured against the already truncated MPO, so it cannot see it. antihermitian_l2 is the size of the anti-Hermitian part that truncation leaves in the pooled coefficients, projected out by _real_coefficients().

estimate(plan, frequencies, seed=None) → ExpectationResult[source]

Sum each setting’s mean of sum_P c_P parity_P(bitstring), with its standard error from the same per-bitstring values, which carry the members’ full covariance. seed is unused, nothing is random.

name: ClassVar[str] = 'pauli'

Short name, stored as MeasurementPlan.method.

class mpstab.qpu.measurement.pauli.QWCGroup(setting: str, members: tuple)[source]

Bases: object

One measurement setting: a merged basis string and its Pauli members.

mpstab.qpu.measurement.pauli.allocate_shots_by_variance(plan: PauliMeasurementPlan, n_shots: int) → tuple[source]

Split n_shots across groups proportionally to sqrt(V_G), respecting n_shots exactly.

This is the Neyman-optimal allocation, and matches the variance model PauliMeasurementPlan.shots_for_precision() sizes the total against. Every group needs at least one shot to be measured at all, so one shot is reserved for each group first; the remainder is allocated by weight and rounded with the largest-remainder method, so the returned shot counts always sum to exactly n_shots (rounding a raw fractional allocation per group, as a naive round() would, can drift the total away from n_shots in either direction).

Raises:

ValueError – if n_shots is smaller than the number of groups, since every group needs at least one shot.

mpstab.qpu.measurement.pauli.build_measurement_plan(coefficients: dict) → PauliMeasurementPlan[source]

QWC-group a {pauli_string: c_P} map into a PauliMeasurementPlan.

mpstab.qpu.measurement.pauli.group_qwc(strings, weights=None) → tuple[source]

Group Pauli strings into qubit-wise-commuting sets, largest coefficient first.

Only qubit-wise commutation is exploited, not the more general “fully commuting” partition, because the latter needs an entangling Clifford basis change that would add two-qubit gates to the very head circuit this scheme exists to keep cheap. Minimising the number of QWC groups is NP-hard, so this greedy count is an upper bound on the true number of settings.

Parameters:
  • strings – Pauli strings to group.

  • weights – optional per-string sort key, e.g. |c_P|.

Returns:

A tuple of QWCGroup, with leftover I in each merged setting resolved to Z.

The "shadows" method: classical shadows from random single-qubit Pauli bases, contracted with the tail-folded observable MPO through the canonical dual.

Random local Pauli-basis measurements are the six-effect-per-qubit POVM

Pi_k in {|0><0|/3, |1><1|/3, |+><+|/3, |-><-|/3, |+i><+i|/3, |-i><-i|/3}

indexed k = 0..5 in that order (outcome_index()). Every operator is handled as the MPS of its Pauli coefficients (O = sum_P c_P P, as mpo_to_pauli_mps() returns it). Because each effect is a fixed combination of single-qubit Paulis, the canonical dual is a site-local map (LOCAL_CANONICAL_DUAL_MAP): applied to O’s Pauli-coefficient MPS it gives, at O’s own bond dimension, the MPS omega of per-outcome estimator values (canonical_omega_seed()). Estimating is then a batched lookup of omega at every measured outcome (evaluate_omega()).

class mpstab.qpu.measurement.shadows.ClassicalShadows(shots_per_setting: int = 1, tail_handling: str = 'append_to_head_circuit')[source]

Bases: MeasurementMethod

The "shadows" method: measure random single-qubit Pauli bases and contract each snapshot with the tail-folded observable MPO.

Parameters:
  • shots_per_setting – shots reused per random basis. Larger values cut the number of distinct circuits at the price of correlated snapshots.

  • tail_handling – what to do with a non-trivial Clifford residual left by the resynthesis. "append_to_head_circuit" (default) runs it as extra gates after the head; "fold" reabsorbs it into the tail MPO (see build_post_head_mpo()), so the device runs the head alone at a possibly much higher shadow variance.

Raises:

ValueError – on an unknown tail_handling.

build_plan(model, terms, constant, cut_index, resynthesis, max_bond_dimension, n_shots, epsilon, seed) → MeasurementPlan[source]

Fold each term’s tail MPO and pick one random basis per setting.

With epsilon the shots are sized from the exact snapshot variance of shadow_variance_from_mpo(). truncation_l2 is estimated from each folded MPO’s norm (see fold_truncation_l2()), so no reference fold and no head state are built.

estimate(plan, frequencies, seed=None) → ExpectationResult[source]

The canonical-dual estimate over every shot; seed is unused, nothing is random.

name: ClassVar[str] = 'shadows'

Short name, stored as MeasurementPlan.method.

mpstab.qpu.measurement.shadows.LOCAL_CANONICAL_DUAL_MAP = array([[ 1.,  0.,  0.,  3.],        [ 1.,  0.,  0., -3.],        [ 1.,  3.,  0.,  0.],        [ 1., -3.,  0.,  0.],        [ 1.,  0.,  3.,  0.],        [ 1.,  0., -3.,  0.]])

the canonical dual D_k = 9 Pi_k - I, scaled so that applying it site-wise to a Pauli-coefficient MPS gives the canonical-dual omega, see canonical_omega_seed().

Type:

(6, 4)

mpstab.qpu.measurement.shadows.LOCAL_EFFECT_MAP = array([[ 0.16666667,  0.        ,  0.        ,  0.16666667],        [ 0.16666667,  0.        ,  0.        , -0.16666667],        [ 0.16666667,  0.16666667,  0.        ,  0.        ],        [ 0.16666667, -0.16666667,  0.        ,  0.        ],        [ 0.16666667,  0.        ,  0.16666667,  0.        ],        [ 0.16666667,  0.        , -0.16666667,  0.        ]])

Pi_k = sum_p LOCAL_EFFECT_MAP[k, p] P_p.

Type:

(6, 4)

mpstab.qpu.measurement.shadows.TAIL_HANDLINGS = ('append_to_head_circuit', 'fold')

What ClassicalShadows can do with a non-trivial Clifford residual.

mpstab.qpu.measurement.shadows.canonical_omega_seed(pauli_mps: list) → list[source]

The canonical-dual omega MPS of an operator: site tensors shaped (6, left, right) whose value at an outcome string is the classical-shadow estimate of the operator from that single shot.

Parameters:

pauli_mps – the operator’s Pauli-coefficient MPS, as mpo_to_pauli_mps() returns it; made real by real_pauli_mps() first.

mpstab.qpu.measurement.shadows.estimate_with_omega(plan, frequencies, outcomes, weights, omega_of, n_shots) → ExpectationResult[source]

Sum each term’s omega estimate over the shots (outcomes, weights).

Parameters:
  • plan – a shadows-shaped plan and its measured frequencies.

  • frequencies – a shadows-shaped plan and its measured frequencies.

  • outcomes – the shots the estimate is averaged over.

  • weights – the shots the estimate is averaged over.

  • omega_of – maps a term’s Pauli-coefficient MPS to its omega MPS.

  • n_shots – the shots to report, including any not averaged over.

mpstab.qpu.measurement.shadows.evaluate_omega(omega_mps: list, outcomes: ndarray) → ndarray[source]

omega[k_1, ..., k_n] at every row of outcomes, batched: a chained bond-matrix lookup costing O(n_rows * n * chi**2).

mpstab.qpu.measurement.shadows.outcome_index(basis: str, bit: int) → int[source]

The outcome index 0..5 for measuring basis and getting bit.

mpstab.qpu.measurement.shadows.real_pauli_mps(pauli_mps: list) → list[source]

An exactly equivalent, real-valued copy of a Pauli-coefficient MPS.

A Hermitian operator’s Pauli coefficients are real, but the MPS mpo_to_pauli_mps() returns can still carry complex gauge phases on its bonds – and the real part of a product is not the product of the real parts, so taking site.real site by site would describe a different operator. Instead every site A = R + iI becomes the real block [[R, -I], [I, R]] (the 2x2 real representation of a complex number, bond dimension doubled), and the boundary sites keep only the row/column that selects the real part of the full contraction. The doubled train is then recompressed exactly by _compress_real_mps(): the coefficients being real, the rank of every unfolding is the same over the reals as over the complexes, so the bond dimension comes back to at most the original one. Sites that are already real are returned as they are, at their own bond dimension.

mpstab.qpu.measurement.shadows.shots_to_outcomes(bases: tuple, frequencies: list) → tuple[source]

Flatten a shadows plan’s (bases, frequencies) into (outcomes, counts): one row of per-qubit outcome indices per distinct (circuit, bitstring) pair, and its measured shot count.

Parameters:
  • bases – one basis string per circuit, as the plan’s recombination carries it.

  • frequencies – one {bitstring: count} dict per circuit, in the same order.

Returns:

an (M, n) int array and an (M,) float array.

Return type:

(outcomes, counts)

Pauli-basis expansion of an MPO: exact coefficients, sampling and variances.

The tail of a head/tail split is a Pauli rotation chain folded into the observable, which leaves an MPO. To measure that observable on a device it has to be turned back into Pauli strings with coefficients. This module does that change of basis and everything that follows directly from it.

Every function takes the MPO as its site arrays, the engine-independent form operator_site_arrays() exports: one numpy array per site ordered (left, right, k, b), with k the upper (output) and b the lower (input) index, and boundary bonds as singleton axes. The recurring contraction is Tr[sigma O] = sum_{k,b} O[k,b] sigma[b,k], hence the "kb,bk" index patterns below.

class mpstab.qpu.measurement.pauli_expansion.PauliEnsemble(strings: tuple, coefficients: ndarray, retained_weight: float, total_weight: float)[source]

Bases: object

A retained subset of an operator’s Pauli expansion, coefficients included.

Variables:
  • strings (tuple) – the retained Pauli strings.

  • coefficients (numpy.ndarray) – their c_P, in the same order.

  • retained_weight (float) – fraction of the operator’s Frobenius weight the retained strings capture, sum |c_P|**2 / total_weight.

  • total_weight (float) – sum_P |c_P|**2 over the whole expansion.

mpstab.qpu.measurement.pauli_expansion.fold_fidelity(mpo, nqubits: int) → float[source]

||O||_F**2 / 2**n of a folded tail MPO: 1 for an exact fold of a Pauli string, since conjugation by a unitary preserves the norm, and lower by the weight the truncation discarded.

mpstab.qpu.measurement.pauli_expansion.fold_pool_through_tableau(pool: dict, residual_tableau) → dict[source]

Conjugate every pooled {pauli: coefficient} entry through residual_tableau.

A device running a resynthesised head prepares U(head)|psi_0>, not the exact head state the tail-folded coefficients were derived against; the two differ by the resynthesis Clifford residual. Every sampled string therefore has to be conjugated through that residual before QWC grouping, since conjugation does not preserve qubit-wise commutativity and folding afterwards would silently invalidate the measurement settings. Strings that collide after folding are summed.

Parameters:
  • pool – {pauli: coefficient}, already pooled across Hamiltonian terms.

  • residual_tableau – the Clifford residual R, a stim.Tableau; every string P becomes R^dag P R.

mpstab.qpu.measurement.pauli_expansion.fold_truncation_l2(coefficient, mpo, nqubits: int) → float[source]

|c| sqrt(1 - fold_fidelity): a term’s share of the bias of truncating its tail fold (bond cap or SVD cutoff), from the norm the fold lost.

A lost share 1 - fold_fidelity at or below _WEIGHT_ROUNDOFF (1e-12, the floor truncation_error_estimate() uses) is rounding drift, not truncation, and reads as 0: an exact fold drifts by ~1e-14, which the square root would turn into a spurious ~1e-7. The price is a resolution of |c| * 1e-6 per term.

mpstab.qpu.measurement.pauli_expansion.mpo_to_pauli_mps(mpo) → list[source]

Rewrite an MPO in the Pauli basis, exactly.

Each site tensor A[l, r, k, b] becomes B[i, l, r] with physical dimension 4, one entry per label of PAULI_LABELS, and unchanged bond dimension. Contracting the resulting train at a fixed label sequence P gives c_P = Tr[O P] / 2**n. Being only a change of basis on the physical index, it makes sample_pauli_strings() exact and shadow_variance_from_mpo() enumeration-free.

mpstab.qpu.measurement.pauli_expansion.operator_distance(left_sites, right_sites) → float[source]

Frobenius distance ||A - B||_F of two MPOs given as site arrays, from ||A||**2 + ||B||**2 - 2 Re Tr[A^dag B].

mpstab.qpu.measurement.pauli_expansion.operator_inner(left_sites, right_sites) → complex[source]

Hilbert-Schmidt inner product Tr[A^dag B] of two MPOs given as site arrays, contracted site by site in O(n chi**3).

mpstab.qpu.measurement.pauli_expansion.operator_norm(sites) → float[source]

Frobenius norm sqrt(Tr[A^dag A]) of an MPO given as site arrays.

mpstab.qpu.measurement.pauli_expansion.pool_pauli_terms(terms) → dict[source]

Merge several Hamiltonian terms’ sampled ensembles into one coefficient map.

The head state does not depend on the observable, so once pooled every term’s strings can be measured from the same shots.

Parameters:

terms – iterable of (term_coefficient, PauliEnsemble) pairs.

Returns:

{pauli_string: combined coefficient}.

mpstab.qpu.measurement.pauli_expansion.sample_pauli_strings(mpo, n_samples: int, seed=None) → PauliEnsemble[source]

Sample Pauli strings from mpo with probability |c_P|**2 / sum |c|**2, deduplicated.

Exact and free of MCMC burn-in: the right environments marginalise over the unfixed suffix whatever prefix has been drawn, so every sweep draws from the true distribution. Cost O(n_samples * n * chi**2).

mpstab.qpu.measurement.pauli_expansion.shadow_variance_from_mpo(mpo) → float[source]

Exact single-snapshot classical-shadow variance of mpo, sum_P |c_P|**2 * 3**w_P.

The weight factor 3**w_P factorises site by site, so inserting diag(1, 3, 3, 3) at every site of the Pauli-basis MPS contracted against itself sums over all 4**n strings at once, in O(n chi**3).

mpstab.qpu.measurement.pauli_expansion.truncation_error_estimate(ensemble: PauliEnsemble)[source]

Estimate the systematic error from the Pauli strings ensemble left out.

The discarded operator contributes at most sum |c_P| (L1) and sqrt(sum |c_P|**2) (L2) over the discarded set, if that set could be summed exactly. The L2 value returned is exact – it comes straight from what PauliEnsemble already carries (the total weight minus the retained weight). The L1 value is not a rigorous bound: the discarded set is in general exponentially large and never enumerated, so it is only a heuristic extrapolation from the sampled tail – the smallest retained |c_P| sets an assumed coefficient scale at the sampling threshold, and dividing the exact discarded L2 mass by that scale gives an effective discarded-term count whose L1 mass is discarded_mass / c_min. Treat it as an order-of-magnitude indicator, not a certified error bound.

Returns:

(l1_estimate, l2_exact).

Execution

Runs a plan’s circuits on a backend, or exports them as OpenQASM to run on a device.

Step 3 of the QPU pipeline: running a plan’s circuits, here or elsewhere.

  • backend: the backend contract and run_plan(). Backends running the circuits with qibo are in mpstab.qibo_tools.

  • qasm: OpenQASM 2 export of a plan’s circuits.

  • storage: saving them to a folder, so they can run on a device.

Running a MeasurementPlan on a backend.

A backend is any object with an execute_circuits(circuits, nshots) method returning one frequency dictionary per circuit, as qibo’s Circuit.__call__(nshots=...).frequencies() does; there is no base class to subclass. The default, StatevectorExactSimulator, runs them with qibo.

Bitstrings are qubit-0-leftmost throughout mpstab, as in qibo. A backend whose provider reports them the other way round, qubit 0 rightmost as in qiskit, must reverse them before returning.

mpstab.qpu.execution.backend.run_plan(plan, backend) → list[source]

Run every circuit in a MeasurementPlan with its own shot count, batching circuits that share a shot count into a single backend.execute_circuits call instead of one call per circuit.

A "shadows" plan’s circuits mostly share shots_per_setting shots each, so this collapses what would otherwise be one backend call per shot into a handful of calls – the contract already supports a batch (execute_circuits takes a list), the naive call site just wasn’t using it.

Parameters:
  • plan – a plan whose circuits and shots are the same length.

  • backend – anything with execute_circuits(circuits, nshots).

Returns:

One frequency dict per circuit, in plan.circuits order and qubit-0-leftmost – what measurement assumes.

Raises:

ValueError – if the backend returns a different number of results than the circuits it was given, which would otherwise leave gaps that only surface later, inside the estimator.

OpenQASM 2 export of a plan’s circuits, the form a device backend works on; save_circuits() writes them to disk for an offline run.

mpstab.qpu.execution.qasm.QELIB1_GATES = frozenset({'ccx', 'ch', 'crz', 'cu1', 'cu3', 'cx', 'cy', 'cz', 'h', 'id', 'rx', 'ry', 'rz', 's', 'sdg', 't', 'tdg', 'u1', 'u2', 'u3', 'x', 'y', 'z'})

The gates of the original OpenQASM 2 qelib1.inc (Cross et al., 2017), the set every OpenQASM 2 parser knows. Later additions such as sx are missing from some parsers’ default include (qiskit’s needs LEGACY_CUSTOM_INSTRUCTIONS), so circuit_to_qasm() emits only these.

mpstab.qpu.execution.qasm.circuit_to_qasm(circuit) → str[source]

OpenQASM 2 text of a qibo circuit, e.g. one of a plan’s circuits.

Only the gates of the original qelib1.inc (QELIB1_GATES) are written by name, so any OpenQASM 2 parser reads the text without custom definitions. Every other one-qubit gate becomes a u3 gate equal to it up to a global phase: the Unitary basis changes a plan adds before measurement, which qibo’s own Circuit.to_qasm() rejects, and gates such as SX/SXDG that rustiq’s resynthesis emits, which qiskit’s parser rejects by default. Qubit i is measured into c[i], so a provider reporting counts as c[n-1]...c[0] (as qiskit does) returns them qubit 0 rightmost: reverse them before estimating.

This only translates the circuit: mapping it to a device’s native gates and qubits is the provider’s transpiler’s job.

Raises:

ValueError – on a gate acting on more than one qubit that is not in QELIB1_GATES.

mpstab.qpu.execution.qasm.plan_to_qasm(plan) → list[source]

circuit_to_qasm() of every circuit of a plan, in plan.circuits order: circuit i runs plan.shots[i] shots, and its counts must come back in position i for estimate().

Saving a measurement plan’s circuits, so they can run elsewhere and later.

save_circuits() writes them to a folder:

out_folder/
    planned_circuits/circ_0000.qasm, circ_0001.qasm, ...
    shots.json

That is all a device backend needs: one OpenQASM 2 file per circuit, and the {file name: shots} map, in plan order.

The circuits are written once and never rebuilt: rustiq draws the residual’s gates at random, so building the same plan again can give a different circuit.

mpstab.qpu.execution.storage.save_circuits(plan: MeasurementPlan, out_folder) → None[source]

Write the circuits and shots of plan to out_folder, creating it as needed.

File names are zero-padded, so sorting them gives the plan order, which is the order estimate() expects the counts in.

Parameters:
  • plan – the plan to save.

  • out_folder – the folder to write into.

Raises:

FileExistsError – if out_folder already holds circuits. Replacing them would orphan any counts already measured from them.