Quantum State Tomography in Python: Reconstruct, Visualize, and Validate Small Quantum States
quantum-tomographystate-reconstructiondensity-matrixmeasurementsQiskitquantum-hardware

Quantum State Tomography in Python: Reconstruct, Visualize, and Validate Small Quantum States

SSmartQubit Editorial Team
2026-11-18
7 min read

Learn a repeatable Python workflow to reconstruct, validate, and compare small quantum states from measurement results.

Quantum state tomography turns measurement results into an estimated density matrix, giving developers a practical way to inspect whether a small circuit prepared the state they intended. This guide presents a repeatable Python workflow: choose measurement bases, collect counts, reconstruct the state, check physicality, compare against a reference, and separate simulator behavior from hardware noise.

Overview

Quantum state tomography is the process of estimating an unknown quantum state from repeated measurements. A state is represented by a density matrix, usually written as ρ. For a pure state, the matrix is ρ = |ψ⟩⟨ψ|; for a mixed or noisy state, it describes a probabilistic combination of possible states.

A single measurement basis cannot reveal the complete state. Measuring a qubit in the computational basis tells you about probabilities associated with Z, but it does not directly expose phase information. Tomography therefore repeats the circuit with different basis rotations before measurement. For one qubit, the standard Pauli approach uses the X, Y, and Z bases. For n qubits, a full local-Pauli plan contains up to 3^n settings, so tomography is most practical for small states.

The workflow has six parts:

  1. Define the state-preparation circuit and the qubits to characterize.
  2. Choose an informationally complete set of measurement bases.
  3. Run each basis setting for a fixed number of shots.
  4. Convert counts into expectation values or probabilities.
  5. Reconstruct and validate the density matrix.
  6. Compare the result with an ideal simulation or a previous hardware run.

Tomography is diagnostic rather than automatically corrective. A reconstructed matrix can reveal population errors, phase errors, unwanted mixing, or correlations, but it does not by itself identify which gate caused them.

How to estimate

A useful starting point is Pauli-basis reconstruction. For one qubit, estimate the three expectation values ⟨X⟩, ⟨Y⟩, and ⟨Z⟩. The density matrix is then:

ρ = 1/2 (I + ⟨X⟩X + ⟨Y⟩Y + ⟨Z⟩Z)

If the computational-basis results are counts for 0 and 1, then ⟨Z⟩ = (N0 - N1) / (N0 + N1). The same difference-of-frequencies rule applies after rotating the measurement basis. To measure X, apply a Hadamard before the computational measurement. To measure Y, apply a basis change that maps the Y eigenstates to computational-basis states. Keep the convention consistent across your SDK, simulator, and hardware workflow.

For multiple qubits, expand the state in tensor products of Pauli operators:

ρ = 1 / 2^n  Σ_P  ⟨P⟩ P

Here, P ranges over strings made from I, X, Y, and Z. The identity expectation is one. Every non-identity Pauli expectation must be estimated from a compatible measurement setting. For example, the observable X⊗Z can be estimated by measuring the first qubit in the X basis and the second in the Z basis, then assigning each bitstring an eigenvalue of plus or minus one.

A compact Python helper for a binary observable is:

def expectation_from_counts(counts, eigenvalue_for_bitstring):
    total = sum(counts.values())
    if total == 0:
        raise ValueError("No shots were recorded")
    weighted = sum(
        eigenvalue_for_bitstring(bitstring) * count
        for bitstring, count in counts.items()
    )
    return weighted / total

Your Qiskit, Cirq, or other SDK code is responsible for preparing basis rotations, submitting jobs, and returning counts. Keeping the count-to-expectation calculation separate makes it easier to test the mathematics independently from provider APIs. For circuit inspection, pair tomography with a quantum circuit visualization workflow.

Inputs and assumptions

Before collecting data, record the assumptions that determine whether two tomography runs are comparable.

  • Target subsystem: State whether you reconstruct all qubits or a reduced subsystem. Tracing out unmeasured qubits changes the interpretation.
  • Measurement convention: Document bit order, endianness, basis-rotation gates, and the mapping from measured bits to eigenvalues.
  • Basis plan: List every setting, such as XX, XY, and ZZ. Do not infer missing correlators without stating an approximation.
  • Shot budget: Use the same shot count per setting when comparing runs, or record the difference explicitly. More shots reduce sampling uncertainty but do not remove systematic hardware error.
  • State model: Decide whether a raw linear inversion is sufficient for diagnosis or whether you need a physicality-constrained estimator.
  • Reference: Save the ideal state, simulator noise model, circuit version, backend identifier, transpilation settings, and execution date.

Raw linear inversion is easy to understand, but finite-shot noise can produce a matrix with a small negative eigenvalue or a trace that is slightly different from one. A density matrix should be Hermitian, have unit trace, and be positive semidefinite. These are not optional presentation checks: they determine whether quantities such as fidelity and purity are physically interpretable.

For a first validation pass in Python, use numerical checks similar to:

import numpy as np

def validate_density_matrix(rho, tolerance=1e-8):
    hermitian_error = np.linalg.norm(rho - rho.conj().T)
    trace_error = abs(np.trace(rho) - 1)
    eigenvalues = np.linalg.eigvalsh((rho + rho.conj().T) / 2)
    return {
        "hermitian": hermitian_error < tolerance,
        "trace_one": trace_error < tolerance,
        "positive_within_tolerance": eigenvalues.min() >= -tolerance,
        "minimum_eigenvalue": float(eigenvalues.min()),
    }

If the estimate is not physical, report that fact rather than silently clipping values. For production analysis, consider maximum-likelihood or another constrained reconstruction method, and record the estimator and stopping criteria alongside the result.

Worked examples

Consider a one-qubit circuit intended to prepare the state |+⟩ = (|0⟩ + |1⟩)/√2. Run three versions of the circuit, each followed by the appropriate basis rotation:

  1. Z setting: The expected result is approximately balanced between zero and one, so ⟨Z⟩ should be near zero.
  2. X setting: The state should produce a strong positive signal, so ⟨X⟩ should be near one.
  3. Y setting: The signal should be near zero for this ideal real-valued state, so ⟨Y⟩ should be near zero.

Suppose the measured estimates are ⟨X⟩ = 0.94, ⟨Y⟩ = 0.03, and ⟨Z⟩ = -0.06. Substituting them into the one-qubit formula produces a matrix close to the ideal |+⟩ density matrix. The reduced X signal may indicate gate or readout error, while the small Y and Z terms may be ordinary finite-shot variation or a systematic bias. Repeat the experiment with a larger shot budget before assigning a physical cause.

For a two-qubit Bell-state experiment, measure all required combinations of local bases and reconstruct the four-by-four matrix. Then compare three quantities:

  • Trace: It should be close to one.
  • Eigenvalues: Negative values beyond the chosen tolerance indicate that raw inversion produced a nonphysical estimate.
  • Fidelity: Compare the reconstructed matrix with the intended reference state using a documented fidelity definition.

Run the same tomography plan on an ideal simulator first. This tests basis rotations, bit ordering, Pauli signs, and matrix assembly without hardware noise. Next, use a noise-aware simulator if available, and finally run on hardware. If the ideal simulation fails, fix the implementation before interpreting device results. If only the hardware result changes, inspect readout mitigation, transpilation, calibration conditions, and circuit depth. A transpiler and pass-manager review can help explain why the executed circuit differs from the source circuit.

Tomography can be expensive in both shots and cloud runtime. Estimate the number of settings, shots per setting, batching limits, and expected queue overhead before submission. The cloud job planning guide provides a useful framework for recording those inputs. For uncertainty interpretation, also review shots and statistical validation guidance.

When to recalculate

Re-run or recalculate tomography whenever an input that affects the estimate changes. That includes the state-preparation circuit, qubit subset, basis-rotation convention, shot count, backend, noise model, measurement-mitigation method, transpiler settings, or reconstruction algorithm. A new SDK release can also change primitives, result formats, or circuit execution behavior, so keep a small regression test with a known state and review the project after API upgrades.

Use this checklist before publishing or comparing a result:

  • Confirm that every required basis setting was executed.
  • Verify bit ordering and basis-rotation signs with a simulator.
  • Store raw counts, not only the reconstructed matrix.
  • Report shots per setting and any discarded or failed jobs.
  • Check Hermiticity, trace, and eigenvalues.
  • Compare ideal, noise-model, and hardware results separately.
  • State whether the matrix came from linear inversion or a constrained estimator.
  • Record circuit, SDK, backend, transpilation, and measurement-mitigation versions.

For repeated experiments, put these fields in an experiment log and attach the reconstruction code. That makes a tomography result auditable and lets you distinguish a real change in the prepared state from a change in measurement settings or software. If tomography is part of a larger variational or hybrid workflow, connect the reconstructed-state metrics to the same run identifier used for training, optimization, and baseline tracking.

Related Topics

#quantum-tomography#state-reconstruction#density-matrix#measurements#Qiskit#quantum-hardware
S

SmartQubit Editorial Team

Quantum Computing Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.