Assertions¶
The qtest.assertions subpackage provides the core quantum-aware
assertions: distribution closeness, state closeness, unitarity, circuit
equivalence, noise robustness, and circuit resource/cost limits. Each is
re-exported at the top-level qtest namespace for convenience.
Public API¶
|
Assert that circuit's measurement distribution is close to expected. |
|
Assert that circuit's state vector equals expected_state. |
|
Assert that operation represents a unitary operator. |
|
Assert that circuit_a and circuit_b implement equivalent unitaries. |
|
Assert circuit's output stays within max_distance of expected under noise. |
|
Assert that circuit's state is entangled. |
|
Assert that circuit's state is separable (no entanglement). |
|
Assert the marginal distribution over bit_positions matches expected. |
|
Assert the relative phase |
|
Assert that operators a and b commute (or anticommute). |
|
Assert that circuit has depth at most max_depth. |
|
Assert that circuit contains at most max_count gates. |
|
Assert that circuit contains at most max_count two-qubit gates. |
|
Assert that circuit uses at most max_count T / T-dagger gates. |
Reference¶
qtest’s pytest-friendly assertion functions.
Public API:
assert_distribution_close()— compare a circuit’s measurement distribution to an expected one using a configurable statistical metric.assert_state_close()— compare a circuit’s state vector to an expected state (named, list, or array) using fidelity or raw L2 distance.assert_unitary()— verify that an operation is unitary by checking \(U^{\dagger}U \approx I\).assert_circuit_equivalent()— verify two circuits implement equivalent unitaries via process fidelity, Hilbert-Schmidt distance, or random-state sampling.assert_robust_to_noise()— sweep increasing noise strengths and verify the output distribution stays within a tolerance of the ideal.assert_entangled()/assert_separable()— entanglement-aware state assertions based on entanglement entropy.assert_measurement_probabilities()— compare a marginal measurement distribution over a subset of bits.assert_phase()— check the relative phase between two basis amplitudes.assert_commutes()— check operator (anti)commutation.assert_max_depth()/assert_max_gate_count()/assert_max_two_qubit_count()/assert_max_t_count()— guard a circuit’s resource cost (depth, gate counts, T-count) to catch optimisation and transpilation regressions.
- qtest.assertions.assert_circuit_equivalent(circuit_a, circuit_b, method='auto', tolerance=1e-6, n_samples=100, backend=None, seed=None, msg=None)[source]¶
Assert that circuit_a and circuit_b implement equivalent unitaries.
- Parameters:
circuit_a (Any) – Backend-native circuit objects with identical qubit counts. Must consist only of unitary operations (no measurements / resets).
circuit_b (Any) – Backend-native circuit objects with identical qubit counts. Must consist only of unitary operations (no measurements / resets).
method (str) – One of
"auto","unitary","hilbert_schmidt","random_sampling". See module docstring for semantics. With"auto"the method is chosen from the qubit count.tolerance (float) – Maximum permitted infidelity (
"unitary"/"random_sampling") or HS distance ("hilbert_schmidt"). Defaults to1e-6.n_samples (int) – Number of random Haar states for
"random_sampling". Ignored otherwise. Defaults to100.backend (Backend | None) – Backend used to extract unitaries. Defaults to the configured default backend.
seed (int | None) – Seed for the random state generator (
"random_sampling"only).msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For invalid
method, mismatched qubit counts, non-positiven_samples, etc.AssertionError – When the circuits diverge beyond
tolerance.
- Return type:
None
- qtest.assertions.assert_commutes(a, b, tolerance=1e-9, anti=False, backend=None, msg=None)[source]¶
Assert that operators a and b commute (or anticommute).
- Parameters:
a (Any) – Operators as
np.ndarray, gate objects withto_matrix(), or circuits. Must have identical shape.b (Any) – Operators as
np.ndarray, gate objects withto_matrix(), or circuits. Must have identical shape.tolerance (float) – Maximum permitted entry-wise magnitude of the (anti)commutator \(\max_{ij}|C_{ij}|\), where
C = AB - BA(commutator) orC = AB + BA(anticommutator whenanti=True).anti (bool) – When
Truecheck anticommutation (AB + BA ≈ 0) instead of commutation.backend (Backend | None) – Backend used to extract unitaries from circuit-shaped operands.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed or mismatched operand shapes.
AssertionError – When a and b do not (anti)commute within tolerance.
- Return type:
None
- qtest.assertions.assert_distribution_close(circuit, expected, shots=None, tolerance=None, metric=None, backend=None, seed=None, noise_model=None, msg=None)[source]¶
Assert that circuit’s measurement distribution is close to expected.
- Parameters:
circuit (Any) – A backend-native circuit object (e.g.
qiskit.QuantumCircuit). Must contain at least one measurement instruction.expected (dict[str, float]) – Reference probability distribution as
{bitstring: probability}. Must be non-empty, with values in[0, 1]summing to1. Bitstrings absent from expected are taken to have probability 0.shots (int | None) – Per-call overrides for the corresponding global config defaults.
Nonemeans “use config” — seeqtest.config.QtestConfig.tolerance (float | None) – Per-call overrides for the corresponding global config defaults.
Nonemeans “use config” — seeqtest.config.QtestConfig.metric (str | None) – Per-call overrides for the corresponding global config defaults.
Nonemeans “use config” — seeqtest.config.QtestConfig.backend (Backend | None) – Per-call overrides for the corresponding global config defaults.
Nonemeans “use config” — seeqtest.config.QtestConfig.seed (int | None) – Per-call overrides for the corresponding global config defaults.
Nonemeans “use config” — seeqtest.config.QtestConfig.noise_model (NoiseModel | str | None) – Optional
qtest.noise.NoiseModel(or the name of a built-in preset) applied during simulation.None(the default) uses thedefault_noiseconfig preset if set, otherwise runs noiseless.msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed input (empty distribution, inconsistent bitstring lengths, probabilities outside
[0, 1], no measurement in circuit, non-positive shots, etc.).AssertionError – When the measured distribution diverges from expected beyond the configured tolerance.
- Return type:
None
Examples
>>> from qiskit import QuantumCircuit >>> qc = QuantumCircuit(2, 2) >>> qc.h(0); qc.cx(0, 1); qc.measure([0, 1], [0, 1]) >>> assert_distribution_close( ... qc, {"00": 0.5, "11": 0.5}, shots=4000, seed=42 ... )
- qtest.assertions.assert_entangled(circuit, qubits=None, tolerance=_DEFAULT_TOL, backend=None, msg=None)[source]¶
Assert that circuit’s state is entangled.
- Parameters:
circuit (Any) – A backend-native circuit (no measurements) or a 1-D state-vector array.
qubits (list[int] | None) – Subsystem defining the bipartition
qubits | rest. The assertion passes when the entanglement entropy across this cut exceeds tolerance. WhenNone, the state must be entangled somewhere — i.e. it is not a fully-product state (some single-qubit reduced state is mixed).tolerance (float) – Entropy threshold in bits. Entanglement entropy must be strictly greater than this to count as entangled.
backend (Backend | None) – Backend used to extract the state vector (defaults to the configured backend).
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
AssertionError – When the state is separable across the chosen cut (entropy ≤ tolerance).
- Return type:
None
- qtest.assertions.assert_max_depth(circuit, max_depth, backend=None, msg=None)[source]¶
Assert that circuit has depth at most max_depth.
- Parameters:
circuit (Any) – A circuit object native to the chosen backend.
max_depth (int) – Maximum permitted circuit depth (non-negative integer).
backend (Backend | None) – Backend used to analyse the circuit. Defaults to the configured one.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – If
max_depthis not a non-negative integer.AssertionError – If the circuit’s depth exceeds
max_depth.
- Return type:
None
- qtest.assertions.assert_max_gate_count(circuit, max_count, gate=None, backend=None, msg=None)[source]¶
Assert that circuit contains at most max_count gates.
- Parameters:
circuit (Any) – A circuit object native to the chosen backend.
max_count (int) – Maximum permitted gate count (non-negative integer).
gate (str | None) – If given, count only gates with this (lowercased) name, e.g.
"cx"or"h". IfNone(the default), count every operation.backend (Backend | None) – Backend used to analyse the circuit. Defaults to the configured one.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – If
max_countis not a non-negative integer, orgateis not a non-empty string /None.AssertionError – If the (optionally filtered) gate count exceeds
max_count.
- Return type:
None
- qtest.assertions.assert_max_t_count(circuit, max_count, backend=None, msg=None)[source]¶
Assert that circuit uses at most max_count T / T-dagger gates.
T-count is the dominant cost metric for fault-tolerant (surface-code) execution, where T gates require expensive magic-state distillation.
- Raises:
ValueError – If
max_countis not a non-negative integer.AssertionError – If the T-count exceeds
max_count.
- Parameters:
- Return type:
None
- qtest.assertions.assert_max_two_qubit_count(circuit, max_count, backend=None, msg=None)[source]¶
Assert that circuit contains at most max_count two-qubit gates.
Two-qubit gates dominate error rates on real hardware, so this is one of the most useful regression guards after a transpilation pass.
- Raises:
ValueError – If
max_countis not a non-negative integer.AssertionError – If the two-qubit-gate count exceeds
max_count.
- Parameters:
- Return type:
None
- qtest.assertions.assert_measurement_probabilities(circuit, expected, bit_positions, shots=None, tolerance=None, metric=None, backend=None, seed=None, noise_model=None, msg=None)[source]¶
Assert the marginal distribution over bit_positions matches expected.
- Parameters:
circuit (Any) – A backend-native circuit with measurements.
expected (dict[str, float]) – Reference marginal distribution
{bitstring: probability}whose keys have lengthlen(bit_positions).bit_positions (list[int]) – Positions (0-based, from the left) within the measured bitstring to keep. Order matters: it defines the order of characters in the marginal keys.
shots (int | None) – Per-call overrides for the corresponding global config defaults.
tolerance (float | None) – Per-call overrides for the corresponding global config defaults.
metric (str | None) – Per-call overrides for the corresponding global config defaults.
backend (Backend | None) – Per-call overrides for the corresponding global config defaults.
seed (int | None) – Per-call overrides for the corresponding global config defaults.
noise_model (Any | None) – Per-call overrides for the corresponding global config defaults.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed input (empty positions, out-of-range index, marginal-key width mismatch, unknown metric, …).
AssertionError – When the measured marginal diverges from expected beyond tolerance.
- Return type:
None
- qtest.assertions.assert_phase(circuit, index_a, index_b, expected_phase, tolerance=1e-6, backend=None, msg=None)[source]¶
Assert the relative phase
arg(amp_b / amp_a)equals expected_phase.- Parameters:
circuit (Any) – A backend-native circuit (no measurements) or a 1-D state-vector array.
index_a (int | str) – The two computational basis states, given either as integer indices (
0…2**n - 1) or as bitstrings (e.g."01").amp_ais the reference.index_b (int | str) – The two computational basis states, given either as integer indices (
0…2**n - 1) or as bitstrings (e.g."01").amp_ais the reference.expected_phase (float) – Target relative phase in radians. Compared modulo \(2\pi\).
tolerance (float) – Maximum permitted angular deviation in radians.
backend (Backend | None) – Backend used to extract the state vector.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed input, or when either reference amplitude is ~0 (phase undefined).
AssertionError – When the relative phase deviates from expected_phase beyond tolerance.
- Return type:
None
- qtest.assertions.assert_robust_to_noise(circuit, expected, noise_levels=(0.001, 0.01, 0.05), max_distance=0.15, noise_type='depolarizing', metric='tv', shots=None, backend=None, seed=None, msg=None)[source]¶
Assert circuit’s output stays within max_distance of expected under noise.
For each value
pin noise_levels a noise model of type noise_type and strengthpis applied, the circuit is sampled, and the distance between the measured and expected distributions is computed. The assertion fails if any level exceeds max_distance.- Parameters:
circuit (Any) – A backend-native circuit with at least one measurement instruction.
expected (dict[str, float]) – Reference distribution as
{bitstring: probability}(summing to 1).noise_levels (Sequence[float]) – Increasing noise strengths to sweep. Each is passed as the single probability argument of the chosen noise_type constructor.
max_distance (float) – Maximum permitted distance at every noise level, in
[0, 1].noise_type (str) – One of
"depolarizing","bit_flip","phase_flip","readout".metric (str) – Distance metric:
"tv"(default) or"hellinger".shots (int | None) – Per-call overrides for the corresponding global config defaults.
backend (Backend | None) – Per-call overrides for the corresponding global config defaults.
seed (int | None) – Per-call overrides for the corresponding global config defaults.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed input (bad noise_type, metric, empty noise_levels, out-of-range max_distance, circuit without measurements, …).
AssertionError – When the measured distribution exceeds max_distance at any level.
- Return type:
None
- qtest.assertions.assert_separable(circuit, qubits=None, tolerance=1e-9, backend=None, msg=None)[source]¶
Assert that circuit’s state is separable (no entanglement).
- Parameters:
circuit (Any) – A backend-native circuit (no measurements) or a 1-D state-vector array.
qubits (list[int] | None) – Subsystem defining the bipartition
qubits | rest. The assertion passes when the entanglement entropy across this cut is at most tolerance. WhenNone, every qubit must be unentangled (the state is a full product state).tolerance (float) – Entropy threshold in bits. Entanglement entropy must be ≤ this.
backend (Backend | None) – Backend used to extract the state vector.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
AssertionError – When the state is entangled across the chosen cut (entropy > tolerance).
- Return type:
None
- qtest.assertions.assert_state_close(circuit, expected_state, tolerance=1e-6, global_phase=True, backend=None, noise_model=None, msg=None)[source]¶
Assert that circuit’s state vector equals expected_state.
- Parameters:
circuit (Any) – Backend-native circuit object (e.g.
qiskit.QuantumCircuit). Should contain no measurement / reset / classical operations — otherwise the backend will reject it when extracting the state.expected_state (str | list[complex] | tuple[complex, ...] | ndarray) – Either a name from
qtest.assertions._state_library(e.g."bell","ghz_3"), or a 1-D complex array / list of amplitudes with unit Euclidean norm.tolerance (float) – Maximum permitted infidelity (when
global_phase=True) or L2 distance (whenglobal_phase=False). Defaults to1e-6.global_phase (bool) – Whether to ignore a global phase factor when comparing. Defaults to
True(recommended).backend (Backend | None) – Backend to extract the state vector with. Defaults to the configured default backend; must satisfy
Backend.supports_statevector.noise_model (NoiseModel | str | None) – Optional
qtest.noise.NoiseModel(or preset name). When given, the circuit is evolved into a (generally mixed) density matrix under the noise and compared to expected_state via fidelity;None(the default) keeps the exact state-vector comparison. Noisy comparison requiresglobal_phase=True(fidelity is the only sensible notion for mixed states).msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed input (unknown state name, wrong shape, non-unit norm, backend without state-vector support, etc.).
AssertionError – When the circuit’s state vector diverges from expected_state beyond
tolerance.
- Return type:
None
Examples
>>> from qiskit import QuantumCircuit >>> qc = QuantumCircuit(2); qc.h(0); qc.cx(0, 1) >>> assert_state_close(qc, "bell")
- qtest.assertions.assert_unitary(operation, tolerance=1e-9, backend=None, msg=None)[source]¶
Assert that operation represents a unitary operator.
- Parameters:
operation (Any) –
One of:
np.ndarray— used directly as the candidate matrix.Object with a
to_matrix()method (e.g.qiskit.circuit.Gate) — its matrix representation is used.Anything else — passed to
Backend.get_unitary()(treated as a circuit).
tolerance (float) – Maximum permitted entry-wise deviation \(\max_{ij} |(U^\dagger U)_{ij} - I_{ij}|\). Defaults to
1e-9.backend (Backend | None) – Backend used to extract a unitary from circuit-shaped inputs. Ignored for arrays and gate objects.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – If the matrix is not 2-D, not square, or has zero size.
AssertionError – If
operationdeviates from unitarity beyondtolerance.
- Return type:
None
Submodules¶
assert_distribution_close — qtest’s primary statistical assertion.
Compares the measurement distribution produced by a quantum circuit against
an expected probability distribution and raises AssertionError with
a human-readable diagnostic when they diverge beyond the configured
tolerance.
Three statistical metrics are supported:
"tv"— total variation distance. Tolerance is the maximum permitted distance. Lower tolerance = stricter test."hellinger"— Hellinger distance. Same semantics as"tv"."chi_square"— Pearson \(\chi^{2}\) goodness-of-fit test. Heretoleranceis interpreted as the significance level \(\alpha\): the assertion fails whenp_value < tolerance. Lower tolerance = stricter.
- qtest.assertions.distribution.assert_distribution_close(circuit, expected, shots=None, tolerance=None, metric=None, backend=None, seed=None, noise_model=None, msg=None)[source]¶
Assert that circuit’s measurement distribution is close to expected.
- Parameters:
circuit (Any) – A backend-native circuit object (e.g.
qiskit.QuantumCircuit). Must contain at least one measurement instruction.expected (dict[str, float]) – Reference probability distribution as
{bitstring: probability}. Must be non-empty, with values in[0, 1]summing to1. Bitstrings absent from expected are taken to have probability 0.shots (int | None) – Per-call overrides for the corresponding global config defaults.
Nonemeans “use config” — seeqtest.config.QtestConfig.tolerance (float | None) – Per-call overrides for the corresponding global config defaults.
Nonemeans “use config” — seeqtest.config.QtestConfig.metric (str | None) – Per-call overrides for the corresponding global config defaults.
Nonemeans “use config” — seeqtest.config.QtestConfig.backend (Backend | None) – Per-call overrides for the corresponding global config defaults.
Nonemeans “use config” — seeqtest.config.QtestConfig.seed (int | None) – Per-call overrides for the corresponding global config defaults.
Nonemeans “use config” — seeqtest.config.QtestConfig.noise_model (NoiseModel | str | None) – Optional
qtest.noise.NoiseModel(or the name of a built-in preset) applied during simulation.None(the default) uses thedefault_noiseconfig preset if set, otherwise runs noiseless.msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed input (empty distribution, inconsistent bitstring lengths, probabilities outside
[0, 1], no measurement in circuit, non-positive shots, etc.).AssertionError – When the measured distribution diverges from expected beyond the configured tolerance.
- Return type:
None
Examples
>>> from qiskit import QuantumCircuit >>> qc = QuantumCircuit(2, 2) >>> qc.h(0); qc.cx(0, 1); qc.measure([0, 1], [0, 1]) >>> assert_distribution_close( ... qc, {"00": 0.5, "11": 0.5}, shots=4000, seed=42 ... )
assert_state_close — state-vector level assertion.
Compares a circuit’s resulting state vector against an expected target
(either a complex array or a named state from
qtest.assertions._state_library).
Two comparison modes¶
global_phase=True(default) — compare via fidelity \(F = |\langle\psi|\varphi\rangle|^{2}\). The assertion succeeds when \(F \ge 1 - \text{tolerance}\). This is invariant under a global phase \(e^{i\theta}\) and is almost always the right notion of “the same state”.global_phase=False— compare via raw Euclidean distance \(\lVert\psi - \varphi\rVert_{2}\). The assertion succeeds when this distance is strictly less thantolerance. Phase-sensitive: two vectors differing only by an overall \(e^{i\theta}\) will fail.
- qtest.assertions.state.assert_state_close(circuit, expected_state, tolerance=1e-6, global_phase=True, backend=None, noise_model=None, msg=None)[source]¶
Assert that circuit’s state vector equals expected_state.
- Parameters:
circuit (Any) – Backend-native circuit object (e.g.
qiskit.QuantumCircuit). Should contain no measurement / reset / classical operations — otherwise the backend will reject it when extracting the state.expected_state (str | list[complex] | tuple[complex, ...] | ndarray) – Either a name from
qtest.assertions._state_library(e.g."bell","ghz_3"), or a 1-D complex array / list of amplitudes with unit Euclidean norm.tolerance (float) – Maximum permitted infidelity (when
global_phase=True) or L2 distance (whenglobal_phase=False). Defaults to1e-6.global_phase (bool) – Whether to ignore a global phase factor when comparing. Defaults to
True(recommended).backend (Backend | None) – Backend to extract the state vector with. Defaults to the configured default backend; must satisfy
Backend.supports_statevector.noise_model (NoiseModel | str | None) – Optional
qtest.noise.NoiseModel(or preset name). When given, the circuit is evolved into a (generally mixed) density matrix under the noise and compared to expected_state via fidelity;None(the default) keeps the exact state-vector comparison. Noisy comparison requiresglobal_phase=True(fidelity is the only sensible notion for mixed states).msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed input (unknown state name, wrong shape, non-unit norm, backend without state-vector support, etc.).
AssertionError – When the circuit’s state vector diverges from expected_state beyond
tolerance.
- Return type:
None
Examples
>>> from qiskit import QuantumCircuit >>> qc = QuantumCircuit(2); qc.h(0); qc.cx(0, 1) >>> assert_state_close(qc, "bell")
assert_unitary — verify that an operation is unitary.
Accepts a matrix (np.ndarray), a Qiskit Gate (anything exposing
to_matrix()), or a quantum circuit (anything the configured backend can
extract a unitary from). Checks both \(U^{\dagger} U \approx I\) and
\(U U^{\dagger} \approx I\), reporting the worst-case off-diagonal /
diagonal deviation.
- qtest.assertions.unitary.assert_unitary(operation, tolerance=1e-9, backend=None, msg=None)[source]¶
Assert that operation represents a unitary operator.
- Parameters:
operation (Any) –
One of:
np.ndarray— used directly as the candidate matrix.Object with a
to_matrix()method (e.g.qiskit.circuit.Gate) — its matrix representation is used.Anything else — passed to
Backend.get_unitary()(treated as a circuit).
tolerance (float) – Maximum permitted entry-wise deviation \(\max_{ij} |(U^\dagger U)_{ij} - I_{ij}|\). Defaults to
1e-9.backend (Backend | None) – Backend used to extract a unitary from circuit-shaped inputs. Ignored for arrays and gate objects.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – If the matrix is not 2-D, not square, or has zero size.
AssertionError – If
operationdeviates from unitarity beyondtolerance.
- Return type:
None
assert_circuit_equivalent — verify two circuits implement the same unitary.
Three comparison methods, with "auto" selecting one based on circuit size:
"unitary"(default for ≤ 8 qubits) — phase-insensitive. Computes the process fidelity \(F = |\mathrm{tr}(U_a^\dagger U_b)|^{2} / d^{2}\) and fails when \(1 - F > \text{tolerance}\). Insensitive to a global phase factor."hilbert_schmidt"(default for 9–15 qubits) — phase-sensitive. Computes \(\lVert U_a - U_b \rVert_{F}\) viaqtest.metrics.hilbert_schmidt_distance()and fails when the distance exceedstolerance."random_sampling"(default for > 15 qubits) — samplesn_samplesHaar-uniform pure states, computes per-state fidelity of the two evolved states, and fails when1 - mean(fidelity) > tolerance.
- qtest.assertions.equivalence.assert_circuit_equivalent(circuit_a, circuit_b, method='auto', tolerance=1e-6, n_samples=100, backend=None, seed=None, msg=None)[source]¶
Assert that circuit_a and circuit_b implement equivalent unitaries.
- Parameters:
circuit_a (Any) – Backend-native circuit objects with identical qubit counts. Must consist only of unitary operations (no measurements / resets).
circuit_b (Any) – Backend-native circuit objects with identical qubit counts. Must consist only of unitary operations (no measurements / resets).
method (str) – One of
"auto","unitary","hilbert_schmidt","random_sampling". See module docstring for semantics. With"auto"the method is chosen from the qubit count.tolerance (float) – Maximum permitted infidelity (
"unitary"/"random_sampling") or HS distance ("hilbert_schmidt"). Defaults to1e-6.n_samples (int) – Number of random Haar states for
"random_sampling". Ignored otherwise. Defaults to100.backend (Backend | None) – Backend used to extract unitaries. Defaults to the configured default backend.
seed (int | None) – Seed for the random state generator (
"random_sampling"only).msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For invalid
method, mismatched qubit counts, non-positiven_samples, etc.AssertionError – When the circuits diverge beyond
tolerance.
- Return type:
None
assert_robust_to_noise — noise-degradation regression assertion.
Where qtest.assert_distribution_close() checks a circuit at a single
(possibly noisy) operating point, assert_robust_to_noise() sweeps a
ladder of increasing noise strengths and asserts that the circuit’s output
distribution never drifts further than max_distance from expected. This
is the natural shape of an error-mitigation / error-correction regression
test: “as noise rises to level X, my mitigated circuit must still track the
ideal result to within Y”.
- qtest.assertions.robustness.assert_robust_to_noise(circuit, expected, noise_levels=(0.001, 0.01, 0.05), max_distance=0.15, noise_type='depolarizing', metric='tv', shots=None, backend=None, seed=None, msg=None)[source]¶
Assert circuit’s output stays within max_distance of expected under noise.
For each value
pin noise_levels a noise model of type noise_type and strengthpis applied, the circuit is sampled, and the distance between the measured and expected distributions is computed. The assertion fails if any level exceeds max_distance.- Parameters:
circuit (Any) – A backend-native circuit with at least one measurement instruction.
expected (dict[str, float]) – Reference distribution as
{bitstring: probability}(summing to 1).noise_levels (Sequence[float]) – Increasing noise strengths to sweep. Each is passed as the single probability argument of the chosen noise_type constructor.
max_distance (float) – Maximum permitted distance at every noise level, in
[0, 1].noise_type (str) – One of
"depolarizing","bit_flip","phase_flip","readout".metric (str) – Distance metric:
"tv"(default) or"hellinger".shots (int | None) – Per-call overrides for the corresponding global config defaults.
backend (Backend | None) – Per-call overrides for the corresponding global config defaults.
seed (int | None) – Per-call overrides for the corresponding global config defaults.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed input (bad noise_type, metric, empty noise_levels, out-of-range max_distance, circuit without measurements, …).
AssertionError – When the measured distribution exceeds max_distance at any level.
- Return type:
None
assert_entangled / assert_separable — entanglement-aware assertions.
Both operate on the pure state a circuit prepares (or a raw state vector).
Entanglement is judged via the entanglement entropy of a bipartition: the von
Neumann entropy of the reduced density matrix on a subsystem is 0 iff that
cut is a product state, and positive otherwise.
assert_entangled()— the state is entangled across the chosen cut (or, withqubits=None, is not a fully-product state).assert_separable()— the state is a product across the chosen cut (or, withqubits=None, is fully separable on every qubit).
- qtest.assertions.entanglement.assert_entangled(circuit, qubits=None, tolerance=_DEFAULT_TOL, backend=None, msg=None)[source]¶
Assert that circuit’s state is entangled.
- Parameters:
circuit (Any) – A backend-native circuit (no measurements) or a 1-D state-vector array.
qubits (list[int] | None) – Subsystem defining the bipartition
qubits | rest. The assertion passes when the entanglement entropy across this cut exceeds tolerance. WhenNone, the state must be entangled somewhere — i.e. it is not a fully-product state (some single-qubit reduced state is mixed).tolerance (float) – Entropy threshold in bits. Entanglement entropy must be strictly greater than this to count as entangled.
backend (Backend | None) – Backend used to extract the state vector (defaults to the configured backend).
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
AssertionError – When the state is separable across the chosen cut (entropy ≤ tolerance).
- Return type:
None
- qtest.assertions.entanglement.assert_separable(circuit, qubits=None, tolerance=1e-9, backend=None, msg=None)[source]¶
Assert that circuit’s state is separable (no entanglement).
- Parameters:
circuit (Any) – A backend-native circuit (no measurements) or a 1-D state-vector array.
qubits (list[int] | None) – Subsystem defining the bipartition
qubits | rest. The assertion passes when the entanglement entropy across this cut is at most tolerance. WhenNone, every qubit must be unentangled (the state is a full product state).tolerance (float) – Entropy threshold in bits. Entanglement entropy must be ≤ this.
backend (Backend | None) – Backend used to extract the state vector.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
AssertionError – When the state is entangled across the chosen cut (entropy > tolerance).
- Return type:
None
assert_measurement_probabilities — marginal-distribution assertion.
Tests the marginal measurement distribution over a subset of the measured bits, rather than the full joint distribution. Useful when only some qubits carry the result of interest (e.g. an ancilla-assisted computation where you only care about the data register).
Bit selection is by position in the measured bitstring as returned by the
backend (index 0 = leftmost character). This keeps the marginalisation
backend-agnostic and free of endianness guesswork — the positions line up with
the keys you already see from assert_distribution_close() diagnostics.
- qtest.assertions.marginals.assert_measurement_probabilities(circuit, expected, bit_positions, shots=None, tolerance=None, metric=None, backend=None, seed=None, noise_model=None, msg=None)[source]¶
Assert the marginal distribution over bit_positions matches expected.
- Parameters:
circuit (Any) – A backend-native circuit with measurements.
expected (dict[str, float]) – Reference marginal distribution
{bitstring: probability}whose keys have lengthlen(bit_positions).bit_positions (list[int]) – Positions (0-based, from the left) within the measured bitstring to keep. Order matters: it defines the order of characters in the marginal keys.
shots (int | None) – Per-call overrides for the corresponding global config defaults.
tolerance (float | None) – Per-call overrides for the corresponding global config defaults.
metric (str | None) – Per-call overrides for the corresponding global config defaults.
backend (Backend | None) – Per-call overrides for the corresponding global config defaults.
seed (int | None) – Per-call overrides for the corresponding global config defaults.
noise_model (Any | None) – Per-call overrides for the corresponding global config defaults.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed input (empty positions, out-of-range index, marginal-key width mismatch, unknown metric, …).
AssertionError – When the measured marginal diverges from expected beyond tolerance.
- Return type:
None
assert_phase — relative-phase assertion between two basis amplitudes.
Global phase is physically irrelevant, but relative phases between basis
states are the whole point of many circuits (a Z/S/T rotation, a
phase-kickback, a QFT). assert_phase() checks that the phase of one
computational-basis amplitude relative to another matches a target angle,
modulo \(2\pi\).
- qtest.assertions.phase.assert_phase(circuit, index_a, index_b, expected_phase, tolerance=1e-6, backend=None, msg=None)[source]¶
Assert the relative phase
arg(amp_b / amp_a)equals expected_phase.- Parameters:
circuit (Any) – A backend-native circuit (no measurements) or a 1-D state-vector array.
index_a (int | str) – The two computational basis states, given either as integer indices (
0…2**n - 1) or as bitstrings (e.g."01").amp_ais the reference.index_b (int | str) – The two computational basis states, given either as integer indices (
0…2**n - 1) or as bitstrings (e.g."01").amp_ais the reference.expected_phase (float) – Target relative phase in radians. Compared modulo \(2\pi\).
tolerance (float) – Maximum permitted angular deviation in radians.
backend (Backend | None) – Backend used to extract the state vector.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed input, or when either reference amplitude is ~0 (phase undefined).
AssertionError – When the relative phase deviates from expected_phase beyond tolerance.
- Return type:
None
assert_commutes — operator commutation / anticommutation assertion.
Checks whether two operators commute (AB == BA) or anticommute
(AB == -BA) by comparing the (anti)commutator to the zero matrix. Operands
may be raw matrices, gate objects (anything with to_matrix()), or circuits
(whose unitary is extracted via the backend) — the same coercion used by
qtest.assert_unitary().
- qtest.assertions.commutation.assert_commutes(a, b, tolerance=1e-9, anti=False, backend=None, msg=None)[source]¶
Assert that operators a and b commute (or anticommute).
- Parameters:
a (Any) – Operators as
np.ndarray, gate objects withto_matrix(), or circuits. Must have identical shape.b (Any) – Operators as
np.ndarray, gate objects withto_matrix(), or circuits. Must have identical shape.tolerance (float) – Maximum permitted entry-wise magnitude of the (anti)commutator \(\max_{ij}|C_{ij}|\), where
C = AB - BA(commutator) orC = AB + BA(anticommutator whenanti=True).anti (bool) – When
Truecheck anticommutation (AB + BA ≈ 0) instead of commutation.backend (Backend | None) – Backend used to extract unitaries from circuit-shaped operands.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – For malformed or mismatched operand shapes.
AssertionError – When a and b do not (anti)commute within tolerance.
- Return type:
None
Resource / cost assertions — guard a circuit’s structure, not its output.
Where qtest.assert_circuit_equivalent() answers “does the transpiled
circuit still compute the right thing?”, these assertions answer the
complementary question: “did it get cheaper?”. They check the quantities an
optimiser or transpiler is supposed to reduce — circuit depth, total gate
count, two-qubit-gate count, and T-count — and are the natural way to lock in
an optimisation and catch regressions.
All checks are pure static analysis (no simulation), so they are fast and work
on circuits of any width. Metrics are extracted via
Backend.get_resources(); backends that cannot introspect their native
circuit type raise NotImplementedError.
Gate-name-based checks (assert_max_gate_count() with a gate filter,
and assert_max_t_count()) rely on backend gate naming, which qtest
normalises to lowercase (e.g. "t", "cx", "h").
- qtest.assertions.resources.assert_max_depth(circuit, max_depth, backend=None, msg=None)[source]¶
Assert that circuit has depth at most max_depth.
- Parameters:
circuit (Any) – A circuit object native to the chosen backend.
max_depth (int) – Maximum permitted circuit depth (non-negative integer).
backend (Backend | None) – Backend used to analyse the circuit. Defaults to the configured one.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – If
max_depthis not a non-negative integer.AssertionError – If the circuit’s depth exceeds
max_depth.
- Return type:
None
- qtest.assertions.resources.assert_max_gate_count(circuit, max_count, gate=None, backend=None, msg=None)[source]¶
Assert that circuit contains at most max_count gates.
- Parameters:
circuit (Any) – A circuit object native to the chosen backend.
max_count (int) – Maximum permitted gate count (non-negative integer).
gate (str | None) – If given, count only gates with this (lowercased) name, e.g.
"cx"or"h". IfNone(the default), count every operation.backend (Backend | None) – Backend used to analyse the circuit. Defaults to the configured one.
msg (str | None) – Optional prefix prepended to the assertion failure message.
- Raises:
ValueError – If
max_countis not a non-negative integer, orgateis not a non-empty string /None.AssertionError – If the (optionally filtered) gate count exceeds
max_count.
- Return type:
None
- qtest.assertions.resources.assert_max_t_count(circuit, max_count, backend=None, msg=None)[source]¶
Assert that circuit uses at most max_count T / T-dagger gates.
T-count is the dominant cost metric for fault-tolerant (surface-code) execution, where T gates require expensive magic-state distillation.
- Raises:
ValueError – If
max_countis not a non-negative integer.AssertionError – If the T-count exceeds
max_count.
- Parameters:
- Return type:
None
- qtest.assertions.resources.assert_max_two_qubit_count(circuit, max_count, backend=None, msg=None)[source]¶
Assert that circuit contains at most max_count two-qubit gates.
Two-qubit gates dominate error rates on real hardware, so this is one of the most useful regression guards after a transpilation pass.
- Raises:
ValueError – If
max_countis not a non-negative integer.AssertionError – If the two-qubit-gate count exceeds
max_count.
- Parameters:
- Return type:
None