Skip to content

run_shadow_simulation

Helpers and result type for running shadow dynamics.

ShadowSimulationResult dataclass

Outputs from a shadow-space dynamics run.

save writes times.npy, expectations.npy, and meta.json. load restores times, curves, labels, basis, and padding, and leaves shadow_hamiltonian, shadow_state, and H_S_padded as None. The shadow-observable curves are not saved, so load leaves them empty. plot_results draws one expectation curve per label.

Attributes:

  • times (NDArray[float64]) –

    Simulation time grid.

  • expectations (list[NDArray[float64]]) –

    Signed ⟨O_k⟩(t) for each closure-basis operator, in basis order.

  • labels (list[str]) –

    Names for each trajectory in expectations. A fresh run uses basis.

  • basis (list[str]) –

    Closure basis order (Pauli labels).

  • shadow_num_qubits (int) –

    Qubit count of the padded shadow Hilbert space.

  • h_s_dimension (int) –

    Unpadded H_S dimension, len(basis).

  • shadow_hamiltonian (ShadowHamiltonian | None) –

    Constructed shadow Hamiltonian (includes unpadded H_S). None when this result was not produced by a fresh run.

  • shadow_state (ShadowState | None) –

    Shadow state aligned to the closure basis order. None when this result was not produced by a fresh run.

  • H_S_padded (NDArray[complexfloating] | None) –

    H_S embedded in the top-left of a 2**shadow_num_qubits matrix. None when this result was not produced by a fresh run.

  • shadow_observable_expectations (list[NDArray[float64]]) –

    ⟨ψ_S(t)|M|ψ_S(t)⟩ for each M passed as shadow_observables, in that order. Empty when none were passed.

  • shadow_observable_labels (list[str]) –

    Names for each trajectory in shadow_observable_expectations.

Source code in shadowsim/shadow/run_shadow_simulation.py
@dataclass(frozen=True)
class ShadowSimulationResult:
    """Outputs from a shadow-space dynamics run.

    ``save`` writes ``times.npy``, ``expectations.npy``, and ``meta.json``.
    ``load`` restores times, curves, labels, basis, and padding, and leaves
    ``shadow_hamiltonian``, ``shadow_state``, and ``H_S_padded`` as ``None``.
    The shadow-observable curves are not saved, so ``load`` leaves them empty.
    ``plot_results`` draws one expectation curve per label.

    Attributes:
        times: Simulation time grid.
        expectations: Signed ``⟨O_k⟩(t)`` for each closure-basis operator, in ``basis`` order.
        labels: Names for each trajectory in ``expectations``. A fresh run uses ``basis``.
        basis: Closure basis order (Pauli labels).
        shadow_num_qubits: Qubit count of the padded shadow Hilbert space.
        h_s_dimension: Unpadded ``H_S`` dimension, ``len(basis)``.
        shadow_hamiltonian: Constructed shadow Hamiltonian (includes unpadded ``H_S``).
            ``None`` when this result was not produced by a fresh run.
        shadow_state: Shadow state aligned to the closure basis order.
            ``None`` when this result was not produced by a fresh run.
        H_S_padded: ``H_S`` embedded in the top-left of a ``2**shadow_num_qubits`` matrix.
            ``None`` when this result was not produced by a fresh run.
        shadow_observable_expectations: ``⟨ψ_S(t)|M|ψ_S(t)⟩`` for each ``M`` passed as
            ``shadow_observables``, in that order. Empty when none were passed.
        shadow_observable_labels: Names for each trajectory in
            ``shadow_observable_expectations``.
    """

    times: npt.NDArray[np.float64]
    expectations: list[npt.NDArray[np.float64]]
    labels: list[str]
    basis: list[str]
    shadow_num_qubits: int
    h_s_dimension: int
    shadow_hamiltonian: ShadowHamiltonian | None = None
    shadow_state: ShadowState | None = None
    H_S_padded: npt.NDArray[np.complexfloating] | None = None
    shadow_observable_expectations: list[npt.NDArray[np.float64]] = field(default_factory=list)
    shadow_observable_labels: list[str] = field(default_factory=list)

    def save(self, path: str | Path) -> Path:
        """Write times, expectation curves, and metadata to a directory.

        Layout::

            path/
              times.npy
              expectations.npy
              meta.json

        ``expectations.npy`` is a float64 array of shape
        ``(len(labels), len(times))``, one curve per row. ``meta.json`` records
        ``labels``, ``basis``, ``shadow_num_qubits``, and ``h_s_dimension``.
        The shadow Hamiltonian, shadow state, padded ``H_S``, and shadow-observable
        curves are not written.
        Arrays are saved with ``allow_pickle=False``.
        """
        out = Path(path)
        out.mkdir(parents=True, exist_ok=True)
        times = _as_time_grid(self.times)
        expectations = _as_expectation_matrix(times, self.labels, self.expectations)
        np.save(out / "times.npy", times, allow_pickle=False)
        np.save(out / "expectations.npy", expectations, allow_pickle=False)
        meta = {
            "basis": list(self.basis),
            "h_s_dimension": int(self.h_s_dimension),
            "labels": list(self.labels),
            "shadow_num_qubits": int(self.shadow_num_qubits),
        }
        (out / "meta.json").write_text(json.dumps(meta, indent=2, sort_keys=True) + "\n", encoding="utf-8")
        return out

    @classmethod
    def load(cls, path: str | Path) -> "ShadowSimulationResult":
        """Reload a result previously written by ``save``.

        Restores times, expectation curves, labels, basis, and padding.
        ``shadow_hamiltonian``, ``shadow_state``, and ``H_S_padded`` are
        ``None``. Array files are read with ``allow_pickle=False``. A pickle
        payload is rejected and not executed.
        """
        root = Path(path)
        if not root.is_dir():
            raise FileNotFoundError(f"ShadowSimulationResult directory not found: {root}")
        labels, basis, shadow_num_qubits, h_s_dimension = _load_meta(root)
        times = _as_time_grid(_read_npy(root / "times.npy"))
        expectations = _expectations_from_array(_read_npy(root / "expectations.npy"), times, labels)
        if len(basis) != h_s_dimension:
            raise ValueError(
                f"basis length disagrees with h_s_dimension; got {len(basis)} labels and h_s_dimension={h_s_dimension}"
            )
        if next_power_of_two(h_s_dimension) != 1 << shadow_num_qubits:
            raise ValueError(
                "shadow padding disagrees with h_s_dimension; "
                f"got h_s_dimension={h_s_dimension}, shadow_num_qubits={shadow_num_qubits}"
            )
        return cls(
            times=times,
            expectations=expectations,
            labels=labels,
            basis=basis,
            shadow_num_qubits=shadow_num_qubits,
            h_s_dimension=h_s_dimension,
        )

    def plot_results(self, *, title: str | None = None) -> None:
        """Plot expectation traces against time in an interactive window.

        One curve is drawn per entry of ``labels``. Axis labels are ``Time`` and
        ``Expectation``. Matplotlib is imported through the ``viz`` extra.
        """
        plt = import_optional("matplotlib.pyplot", extra="viz")
        for label, trace in zip(self.labels, self.expectations, strict=True):
            plt.plot(self.times, trace, label=label)
        if title:
            plt.title(title)
        plt.xlabel("Time")
        plt.ylabel("Expectation")
        plt.legend()
        plt.show()

save

save(path: str | Path) -> Path

Write times, expectation curves, and metadata to a directory.

Layout::

path/
  times.npy
  expectations.npy
  meta.json

expectations.npy is a float64 array of shape (len(labels), len(times)), one curve per row. meta.json records labels, basis, shadow_num_qubits, and h_s_dimension. The shadow Hamiltonian, shadow state, padded H_S, and shadow-observable curves are not written. Arrays are saved with allow_pickle=False.

Source code in shadowsim/shadow/run_shadow_simulation.py
def save(self, path: str | Path) -> Path:
    """Write times, expectation curves, and metadata to a directory.

    Layout::

        path/
          times.npy
          expectations.npy
          meta.json

    ``expectations.npy`` is a float64 array of shape
    ``(len(labels), len(times))``, one curve per row. ``meta.json`` records
    ``labels``, ``basis``, ``shadow_num_qubits``, and ``h_s_dimension``.
    The shadow Hamiltonian, shadow state, padded ``H_S``, and shadow-observable
    curves are not written.
    Arrays are saved with ``allow_pickle=False``.
    """
    out = Path(path)
    out.mkdir(parents=True, exist_ok=True)
    times = _as_time_grid(self.times)
    expectations = _as_expectation_matrix(times, self.labels, self.expectations)
    np.save(out / "times.npy", times, allow_pickle=False)
    np.save(out / "expectations.npy", expectations, allow_pickle=False)
    meta = {
        "basis": list(self.basis),
        "h_s_dimension": int(self.h_s_dimension),
        "labels": list(self.labels),
        "shadow_num_qubits": int(self.shadow_num_qubits),
    }
    (out / "meta.json").write_text(json.dumps(meta, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    return out

load classmethod

load(path: str | Path) -> ShadowSimulationResult

Reload a result previously written by save.

Restores times, expectation curves, labels, basis, and padding. shadow_hamiltonian, shadow_state, and H_S_padded are None. Array files are read with allow_pickle=False. A pickle payload is rejected and not executed.

Source code in shadowsim/shadow/run_shadow_simulation.py
@classmethod
def load(cls, path: str | Path) -> "ShadowSimulationResult":
    """Reload a result previously written by ``save``.

    Restores times, expectation curves, labels, basis, and padding.
    ``shadow_hamiltonian``, ``shadow_state``, and ``H_S_padded`` are
    ``None``. Array files are read with ``allow_pickle=False``. A pickle
    payload is rejected and not executed.
    """
    root = Path(path)
    if not root.is_dir():
        raise FileNotFoundError(f"ShadowSimulationResult directory not found: {root}")
    labels, basis, shadow_num_qubits, h_s_dimension = _load_meta(root)
    times = _as_time_grid(_read_npy(root / "times.npy"))
    expectations = _expectations_from_array(_read_npy(root / "expectations.npy"), times, labels)
    if len(basis) != h_s_dimension:
        raise ValueError(
            f"basis length disagrees with h_s_dimension; got {len(basis)} labels and h_s_dimension={h_s_dimension}"
        )
    if next_power_of_two(h_s_dimension) != 1 << shadow_num_qubits:
        raise ValueError(
            "shadow padding disagrees with h_s_dimension; "
            f"got h_s_dimension={h_s_dimension}, shadow_num_qubits={shadow_num_qubits}"
        )
    return cls(
        times=times,
        expectations=expectations,
        labels=labels,
        basis=basis,
        shadow_num_qubits=shadow_num_qubits,
        h_s_dimension=h_s_dimension,
    )

plot_results

plot_results(*, title: str | None = None) -> None

Plot expectation traces against time in an interactive window.

One curve is drawn per entry of labels. Axis labels are Time and Expectation. Matplotlib is imported through the viz extra.

Source code in shadowsim/shadow/run_shadow_simulation.py
def plot_results(self, *, title: str | None = None) -> None:
    """Plot expectation traces against time in an interactive window.

    One curve is drawn per entry of ``labels``. Axis labels are ``Time`` and
    ``Expectation``. Matplotlib is imported through the ``viz`` extra.
    """
    plt = import_optional("matplotlib.pyplot", extra="viz")
    for label, trace in zip(self.labels, self.expectations, strict=True):
        plt.plot(self.times, trace, label=label)
    if title:
        plt.title(title)
    plt.xlabel("Time")
    plt.ylabel("Expectation")
    plt.legend()
    plt.show()

computational_basis_projectors

computational_basis_projectors(
    num_qubits: int,
) -> OperatorSet

Return computational-basis projectors on a num_qubits-qubit space.

For n qubits this yields 2**n rank-1 projectors |k⟩⟨k| labeled P_{bits} (e.g. P_00, P_01, …).

Source code in shadowsim/shadow/run_shadow_simulation.py
def computational_basis_projectors(num_qubits: int) -> OperatorSet:
    """Return computational-basis projectors on a ``num_qubits``-qubit space.

    For ``n`` qubits this yields ``2**n`` rank-1 projectors ``|k⟩⟨k|`` labeled
    ``P_{bits}`` (e.g. ``P_00``, ``P_01``, …).
    """
    if num_qubits < 0:
        raise ValueError(f"num_qubits must be non-negative, got {num_qubits}")
    dim = 1 << num_qubits
    ops: list[Operator] = []
    for i in range(dim):
        bits = format(i, f"0{num_qubits}b") if num_qubits > 0 else ""
        p = np.zeros((dim, dim), dtype=np.complex128)
        p[i, i] = 1.0
        ops.append(Operator(p, name=f"P_{bits}" if num_qubits > 0 else "P_"))
    return OperatorSet(ops)

pad_h_s

pad_h_s(
    H_S: NDArray[complexfloating],
) -> tuple[NDArray[complexfloating], int]

Embed H_S in the top-left of the next power-of-two square matrix.

Returns:

  • NDArray[complexfloating] –

    (H_S_padded, shadow_num_qubits) where H_S_padded has shape

  • int –

    (D, D) with D = next_power_of_two(m) for an m×m input, and

  • tuple[NDArray[complexfloating], int] –

    shadow_num_qubits = log2(D) (0 when D == 1).

Source code in shadowsim/shadow/run_shadow_simulation.py
def pad_h_s(H_S: npt.NDArray[np.complexfloating]) -> tuple[npt.NDArray[np.complexfloating], int]:
    """Embed ``H_S`` in the top-left of the next power-of-two square matrix.

    Returns:
        ``(H_S_padded, shadow_num_qubits)`` where ``H_S_padded`` has shape
        ``(D, D)`` with ``D = next_power_of_two(m)`` for an ``m×m`` input, and
        ``shadow_num_qubits = log2(D)`` (``0`` when ``D == 1``).
    """
    matrix = np.asarray(H_S, dtype=np.complex128)
    if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:
        raise ValueError(f"H_S must be a square matrix, got shape {matrix.shape}")
    m = int(matrix.shape[0])
    d = next_power_of_two(m)
    if d == m:
        padded = matrix.copy()
    else:
        padded = np.zeros((d, d), dtype=np.complex128)
        padded[:m, :m] = matrix
    shadow_num_qubits = d.bit_length() - 1
    return padded, shadow_num_qubits

run_shadow_simulation

run_shadow_simulation(
    hamiltonians: Hamiltonian | Sequence[Hamiltonian],
    observables: OperatorSet | Sequence[Operator | str],
    initial_state: State,
    *,
    total_time: float,
    time_steps: int,
    circuit_backend: CircuitBackend,
    num_qubits: int | None = None,
    shadow_observables: OperatorSet | None = None,
    seed: int | None = None,
    tol: float = 1e-10,
    verbose: bool = False,
) -> ShadowSimulationResult

Build the shadow model and evolve it on circuit_backend.

Constructs ShadowHamiltonian on the physical system, builds a ShadowState ordered to match the closure basis of H_S, and pads H_S to a power-of-two Hilbert space. Component k of the evolved shadow state is ⟨O_k⟩(t) / √A, so it is read with a Hadamard test: an ancilla interferes exp(-i H_S t)|ψ_S(0)⟩ with |k⟩, and its ⟨X⟩ is that component. expectations holds √A times each reading, the signed ⟨O_k⟩(t) in basis order, labeled by basis.

One circuit runs per closure-basis operator per time point. A backend with a shots budget estimates each reading from that many shots, so each point carries an error of about √(A / shots). A backend without one, such as NumpyCircuitBackend, returns exact readings. The circuits use initialize and dense unitaries, so the backend must accept both.

shadow_observables are optional quadratic diagnostics on the shadow register, such as computational_basis_projectors(shadow_num_qubits). Each curve is ⟨ψ_S(t)|M|ψ_S(t)⟩, computed from the signed readings without extra circuits, so it carries their shot noise. The curves fill shadow_observable_expectations and do not change expectations.

Example
import numpy as np
from shadowsim.backends.numpy import NumpyCircuitBackend
from shadowsim.core import Hamiltonian, OperatorSet, State
from shadowsim.shadow import run_shadow_simulation

result = run_shadow_simulation(
    Hamiltonian("X"),
    OperatorSet(["Z"]),
    State(np.array([1.0, 0.0], dtype=np.complex128), 1),
    total_time=1.0,
    time_steps=11,
    circuit_backend=NumpyCircuitBackend(),
)
print(result.labels)  # ['Y', 'Z']: ⟨Y⟩ = -sin(2t), ⟨Z⟩ = cos(2t)
Source code in shadowsim/shadow/run_shadow_simulation.py
def run_shadow_simulation(
    hamiltonians: Hamiltonian | Sequence[Hamiltonian],
    observables: OperatorSet | Sequence[Operator | str],
    initial_state: State,
    *,
    total_time: float,
    time_steps: int,
    circuit_backend: CircuitBackend,
    num_qubits: int | None = None,
    shadow_observables: OperatorSet | None = None,
    seed: int | None = None,
    tol: float = 1e-10,
    verbose: bool = False,
) -> ShadowSimulationResult:
    """Build the shadow model and evolve it on ``circuit_backend``.

    Constructs ``ShadowHamiltonian`` on the physical system, builds a
    ``ShadowState`` ordered to match the closure basis of ``H_S``, and pads
    ``H_S`` to a power-of-two Hilbert space. Component ``k`` of the evolved
    shadow state is ``⟨O_k⟩(t) / √A``, so it is read with a Hadamard test: an
    ancilla interferes ``exp(-i H_S t)|ψ_S(0)⟩`` with ``|k⟩``, and its ``⟨X⟩``
    is that component. ``expectations`` holds ``√A`` times each reading, the
    signed ``⟨O_k⟩(t)`` in ``basis`` order, labeled by ``basis``.

    One circuit runs per closure-basis operator per time point. A backend with
    a ``shots`` budget estimates each reading from that many shots, so each
    point carries an error of about ``√(A / shots)``. A backend without one,
    such as ``NumpyCircuitBackend``, returns exact readings. The circuits use
    ``initialize`` and dense unitaries, so the backend must accept both.

    ``shadow_observables`` are optional quadratic diagnostics on the shadow
    register, such as ``computational_basis_projectors(shadow_num_qubits)``.
    Each curve is ``⟨ψ_S(t)|M|ψ_S(t)⟩``, computed from the signed readings
    without extra circuits, so it carries their shot noise. The curves fill
    ``shadow_observable_expectations`` and do not change ``expectations``.

    Example:
        ```python
        import numpy as np
        from shadowsim.backends.numpy import NumpyCircuitBackend
        from shadowsim.core import Hamiltonian, OperatorSet, State
        from shadowsim.shadow import run_shadow_simulation

        result = run_shadow_simulation(
            Hamiltonian("X"),
            OperatorSet(["Z"]),
            State(np.array([1.0, 0.0], dtype=np.complex128), 1),
            total_time=1.0,
            time_steps=11,
            circuit_backend=NumpyCircuitBackend(),
        )
        print(result.labels)  # ['Y', 'Z']: ⟨Y⟩ = -sin(2t), ⟨Z⟩ = cos(2t)
        ```
    """
    terms = _as_hamiltonian_list(hamiltonians)
    operator_set = _as_operator_set(observables)
    nq = num_qubits if num_qubits is not None else _infer_num_qubits(terms)
    if nq < 0:
        raise ValueError(f"shadow simulation: num_qubits must be non-negative, got {nq}")
    _validate_physical_dims(terms, operator_set, initial_state, nq)

    shadow_h = ShadowHamiltonian(
        operator_set,
        terms,
        num_qubits=nq,
        tol=tol,
        verbose=verbose,
    )
    H_S_padded, shadow_nq = pad_h_s(shadow_h.H_S)
    closure_ops = OperatorSet(list(shadow_h.basis))
    shadow_state = ShadowState(initial_state, closure_ops, num_qubits=shadow_nq)

    if shadow_state.get_num_qubits() != shadow_nq:
        raise ValueError(
            "shadow simulation: padded shadow state qubit count disagrees with padded H_S; "
            f"got state num_qubits={shadow_state.get_num_qubits()}, expected {shadow_nq}"
        )
    if shadow_state.state.shape[0] != H_S_padded.shape[0]:
        raise ValueError(
            "shadow simulation: padded shadow state dimension disagrees with padded H_S; "
            f"got state length {shadow_state.state.shape[0]}, H_S shape {H_S_padded.shape}"
        )

    if shadow_observables is not None:
        _validate_shadow_observables(shadow_observables, shadow_nq)

    times = np.linspace(0, total_time, time_steps)
    expectations = _signed_expectations(
        H_S_padded,
        shadow_state,
        int(shadow_h.H_S.shape[0]),
        times,
        circuit_backend,
        seed=seed,
    )
    observable_curves: list[npt.NDArray[np.float64]] = []
    observable_labels: list[str] = []
    if shadow_observables is not None:
        observable_curves = _shadow_observable_curves(expectations, shadow_state, shadow_observables)
        observable_labels = [op.name if op.name is not None else str(i) for i, op in enumerate(shadow_observables)]

    return ShadowSimulationResult(
        times=np.asarray(times, dtype=np.float64),
        expectations=expectations,
        labels=list(shadow_h.basis),
        basis=list(shadow_h.basis),
        shadow_num_qubits=shadow_nq,
        h_s_dimension=int(shadow_h.H_S.shape[0]),
        shadow_hamiltonian=shadow_h,
        shadow_state=shadow_state,
        H_S_padded=H_S_padded,
        shadow_observable_expectations=observable_curves,
        shadow_observable_labels=observable_labels,
    )