Quantum circuits can produce unexpected results for reasons that are difficult to see in a diagram alone. This practical quantum state debugging workflow shows how to move from circuit structure to statevectors, amplitudes, probabilities, Bloch-sphere coordinates, reduced states, entanglement checks, and measurement counts so you can isolate whether the problem is a gate, a phase, a qubit-ordering assumption, or noise.
Overview
A quantum circuit is not fully described by its final measurement counts. Measurements discard phase information and compress a state into sampled classical results. When debugging, inspect the circuit at several levels instead:
- Circuit structure: Confirm that gates, controls, targets, barriers, and measurements are where you expect them to be.
- Statevector: Inspect complex amplitudes before measurement when the simulator and circuit size permit it.
- Probabilities: Convert amplitudes into observable outcome probabilities and check normalization.
- Single-qubit views: Use Bloch-sphere coordinates or reduced density matrices to inspect individual qubits.
- Correlations: Check whether multi-qubit behavior indicates entanglement rather than independent superposition.
- Shot results: Compare sampled counts with ideal probabilities and, later, with noisy hardware results.
No single view answers every debugging question. A statevector can reveal a phase that measurement counts hide, while counts can reveal sampling and hardware effects that an ideal statevector cannot model. Treat these views as complementary diagnostics.
For simulator selection, see the Quantum Simulator Selection Guide. For repeatable tests around these checks, use the Quantum Circuit Unit Testing in Python guide.
How to compare state-inspection options
Before choosing a visualization or result format, define the question you are trying to answer. This prevents a common debugging mistake: using measurement counts to investigate a phase issue or using a full statevector when the real problem is a reversed bit label.
| Inspection method | Best question | What it can hide |
|---|---|---|
| Circuit diagram | Did I construct the intended sequence and connectivity? | State amplitudes, phase, and noise |
| Statevector | What are the exact complex amplitudes in an ideal simulation? | Hardware noise and finite-shot variation |
| Amplitude and probability table | Which basis states are present, and with what weight? | Global phase and some relative-phase effects |
| Bloch sphere | What is the reduced state of one qubit? | Some multi-qubit correlations and global state structure |
| Reduced density matrix | Is one qubit pure, mixed, or correlated with another? | Details of the full state outside the selected subsystem |
| Measurement counts | What outcomes appear after sampling and measurement? | Unobserved phase information |
A reliable order is to start with the circuit diagram, then inspect a small ideal statevector, then calculate probabilities and single-qubit reduced states. Only after those checks should you add measurements, shots, noise, or hardware execution. This narrows the search space and makes each result easier to interpret.
SDKs differ in register ordering, result objects, visualization APIs, and simulator configuration. Keep the mathematics independent from the SDK: document which logical qubit each index represents, convert results into your own clearly labeled arrays, and treat plotting code as a presentation layer. The SDK comparison and migration guide is useful when translating these checks between Qiskit, Cirq, PennyLane, and Braket.
Feature-by-feature debugging workflow
1. Confirm the circuit and qubit order
First draw or print the circuit. Verify that a controlled gate targets the intended qubit, that measurement operations map quantum bits to the expected classical bits, and that any layout or transpilation step has not changed your assumptions.
Write down an explicit convention such as “basis index bit 0 represents the least-significant qubit” rather than relying on visual order. Endianness is a frequent source of apparently reversed answers. Test the convention with simple basis states: prepare one qubit in the state corresponding to a known bit string, inspect the statevector index, and compare it with the SDK’s displayed count key.
2. Inspect amplitudes before measurement
For a pure state, the statevector contains one complex amplitude for every computational-basis state. The magnitude squared of an amplitude is its ideal measurement probability:
probability = abs(amplitude) ** 2
A version-tolerant inspection pattern is to obtain the simulator’s statevector using the SDK’s documented method, convert it to a complex array, and label each entry yourself:
import numpy as np
# Replace this with the statevector returned by your SDK.
state = np.asarray(statevector, dtype=complex)
n_qubits = int(np.log2(len(state)))
if 2 ** n_qubits != len(state):
raise ValueError("Statevector length must be a power of two")
for index, amplitude in enumerate(state):
probability = abs(amplitude) ** 2
if probability > 1e-10:
bitstring = format(index, f"0{n_qubits}b")
print(bitstring, amplitude, probability)
print("Normalization:", np.sum(np.abs(state) ** 2))
Near-zero values are normal in floating-point simulation. Use a tolerance instead of testing whether a value is exactly zero. Also distinguish a global phase, which does not change measurement probabilities, from a relative phase between basis states, which can change interference after later gates.
3. Calculate Bloch-sphere coordinates
A Bloch sphere is a complete description of a single qubit only when that qubit is in a pure state. In a multi-qubit circuit, the correct object is usually the qubit’s reduced state. Its coordinates can be calculated from the reduced density matrix rho:
import numpy as np
pauli_x = np.array([[0, 1], [1, 0]], dtype=complex)
pauli_y = np.array([[0, -1j], [1j, 0]], dtype=complex)
pauli_z = np.array([[1, 0], [0, -1]], dtype=complex)
x = np.trace(rho @ pauli_x).real
y = np.trace(rho @ pauli_y).real
z = np.trace(rho @ pauli_z).real
bloch_length = np.sqrt(x*x + y*y + z*z)
print("Bloch coordinates:", (x, y, z))
print("Bloch-vector length:", bloch_length)
For a pure single-qubit state, the vector length is approximately one. A shorter vector can indicate entanglement with other qubits, a mixed state, or noise. It does not automatically mean that a gate failed.
4. Check entanglement and correlations
For a two-qubit pure state, a quick diagnostic is to compare the full state with the product of its single-qubit reduced states. If the state cannot be factored into one state for each qubit, it is entangled. In practice, use a reduced density matrix and calculate a purity value:
def purity(rho):
return float(np.trace(rho @ rho).real)
print("Purity:", purity(rho_qubit_a))
A purity near one is consistent with a pure reduced state; a lower value indicates that the subsystem is mixed. For a pure global state, that often points to entanglement with the remaining qubits. For noisy simulations or hardware, noise can also reduce purity, so compare against an ideal run and inspect the noise model separately.
5. Compare probabilities with measurement counts
Run the same circuit with a modest number of shots and compare empirical frequencies with ideal probabilities. Counts will not exactly match probabilities because sampling is random. Large, systematic differences suggest a measurement mapping issue, a changed circuit, noise, or an incorrect result-format conversion.
Keep measurement debugging separate from state debugging. The Quantum Measurement Strategies guide covers shots, basis rotations, observables, and post-processing. For noise-specific comparisons, see Quantum Noise Models in Python.
6. Use controlled experiments
Reduce the circuit to the smallest example that reproduces the issue. Remove measurements, replace unknown inputs with basis states, and add gates one at a time. Save intermediate states after important operations. This turns “the final result is wrong” into a smaller assertion such as “the target qubit is not in the expected superposition after the Hadamard gate.”
Common symptoms and likely causes
| Symptom | Likely causes | Diagnostic check |
|---|---|---|
| Correct probabilities but wrong interference later | Incorrect relative phase or gate convention | Print complex amplitudes before and after the interference gate; compare signs and imaginary parts. |
| Bit strings appear reversed | Qubit, register, or classical-bit endianness mismatch | Test a one-hot basis state and document the index-to-qubit mapping. |
| Expected entanglement is missing | Control and target are swapped, or a later gate uncomputes the correlation | Inspect joint amplitudes and reduced-state purity after each controlled operation. |
| Small unexpected amplitudes appear | Floating-point residue, an unintended gate, or noise | Use a tolerance, rerun an ideal simulation, and compare circuit depth and operations. |
| Simulator and hardware disagree | Finite shots, readout errors, gate noise, drift, or transpilation changes | Compare ideal, noisy-simulator, and hardware results with the same measurement mapping. |
| Bloch sphere looks mixed after an entangling gate | The qubit may be entangled rather than incorrectly rotated | Calculate the reduced density matrix and its purity; inspect the full state as well. |
Best fit by scenario
- Learning a qubit tutorial: Start with circuit diagrams, amplitudes, and probabilities. Use a Bloch sphere for single-qubit rotations.
- Debugging a small algorithm: Save intermediate statevectors and compare them with hand-derived expected states. This is especially useful for Grover-style amplification, phase kickback, and small variational circuits.
- Investigating entanglement: Use joint amplitudes, reduced density matrices, purity, and correlation measurements. Do not rely on one qubit’s Bloch sphere alone.
- Working with larger circuits: Prefer targeted observables, snapshots, stabilizer or tensor-network methods where appropriate, and sampled checks rather than assuming a full statevector is practical.
- Preparing for hardware: Establish an ideal baseline first, then add a noise model and compare counts, expectation values, and calibration-sensitive behavior. Record seeds, shots, circuit metadata, and SDK versions as part of the experiment.
State inspection also supports hybrid workflows. If a variational circuit is producing an unstable objective value, inspect the prepared state and measured observables separately before changing the optimizer. A debugging checklist is often more useful than another optimizer setting.
When to revisit
Revisit this workflow whenever you change qubit ordering, add a controlled operation, introduce mid-circuit measurement, alter transpilation, move between SDKs, or compare an ideal simulator with noisy execution. These changes can affect statevector access, result formats, measurement mapping, and available visualization methods.
SDK inspection APIs and plotting helpers can change across releases, so verify snippets against the version used by your project. The underlying checks remain stable: validate normalization, label basis states explicitly, distinguish phase from probability, inspect reduced states for single-qubit claims, and compare ideal results with sampled results.
As a practical maintenance routine, keep a small diagnostic circuit in your repository. It should test basis-state preparation, a superposition, a relative-phase change, an entangling operation, and measurement mapping. Run it in continuous integration and repeat it after dependency upgrades. Record the expected state or probabilities rather than relying only on a plotted image. For a broader reproducibility checklist, see the Quantum Experiment Reproducibility guide.
When a real circuit fails, reduce it, inspect it, and compare one layer at a time: structure, amplitudes, probabilities, reduced states, entanglement, and counts. That sequence turns quantum state visualization from a presentation feature into a repeatable debugging tool.