Skip to content

shadow

Shadow Hamiltonian, shadow state, and shadow simulation helpers.

ChangeOfBasis dataclass

Factors and shadow matrices for a quadratic change of basis.

Attributes:

  • A (NDArray[complexfloating]) –

    Change-of-basis matrix A = B†. New operators are O = A Y.

  • B (NDArray[complexfloating]) –

    Factor with Γ = B B†.

  • H_S (NDArray[complexfloating]) –

    Shadow matrix i B† Ω B in the new basis.

  • quadrature_H_S (NDArray[complexfloating]) –

    Shadow matrix i Ω Γ before the change of basis.

  • omega (NDArray[floating]) –

    Commutator matrix used, with [Y_j, Y_k] = i Ω_jk.

Source code in shadowsim/shadow/change_of_basis.py
@dataclass(frozen=True)
class ChangeOfBasis:
    """Factors and shadow matrices for a quadratic change of basis.

    Attributes:
        A: Change-of-basis matrix ``A = B†``. New operators are ``O = A Y``.
        B: Factor with ``Γ = B B†``.
        H_S: Shadow matrix ``i B† Ω B`` in the new basis.
        quadrature_H_S: Shadow matrix ``i Ω Γ`` before the change of basis.
        omega: Commutator matrix used, with ``[Y_j, Y_k] = i Ω_jk``.
    """

    A: npt.NDArray[np.complexfloating]
    B: npt.NDArray[np.complexfloating]
    H_S: npt.NDArray[np.complexfloating]
    quadrature_H_S: npt.NDArray[np.complexfloating]
    omega: npt.NDArray[np.floating]

InvarianceReport dataclass

Diagnostic for whether H and an operator set satisfy the IP.

Attributes:

  • is_closed (bool) –

    Whether the original Pauli support of S already equals its closure under commutators with H.

  • original_size (int) –

    Number of Pauli labels in the original operator set.

  • closure_size (int) –

    Number of Pauli labels after ad_H closure.

  • growth (int) –

    closure_size - original_size.

  • original_paulis (frozenset[str]) –

    Pauli labels appearing in the original operator set.

  • closure_paulis (frozenset[str]) –

    Pauli labels after closure.

  • added_paulis (frozenset[str]) –

    Labels in the closure that were not in the original set.

  • h_s_is_hermitian (bool) –

    Whether H_S on the closed basis is Hermitian (needed for unitary shadow Schrödinger evolution).

  • num_qubits (int) –

    Qubit count used for the Pauli presentation.

  • used_sparse_pauli_path (bool) –

    Whether the sparse Pauli path was used.

Source code in shadowsim/shadow/invariance.py
@dataclass(frozen=True)
class InvarianceReport:
    """Diagnostic for whether ``H`` and an operator set satisfy the IP.

    Attributes:
        is_closed: Whether the original Pauli support of ``S`` already equals
            its closure under commutators with ``H``.
        original_size: Number of Pauli labels in the original operator set.
        closure_size: Number of Pauli labels after ad_H closure.
        growth: ``closure_size - original_size``.
        original_paulis: Pauli labels appearing in the original operator set.
        closure_paulis: Pauli labels after closure.
        added_paulis: Labels in the closure that were not in the original set.
        h_s_is_hermitian: Whether ``H_S`` on the closed basis is Hermitian
            (needed for unitary shadow Schrödinger evolution).
        num_qubits: Qubit count used for the Pauli presentation.
        used_sparse_pauli_path: Whether the sparse Pauli path was used.
    """

    is_closed: bool
    original_size: int
    closure_size: int
    growth: int
    original_paulis: frozenset[str]
    closure_paulis: frozenset[str]
    added_paulis: frozenset[str]
    h_s_is_hermitian: bool
    num_qubits: int
    used_sparse_pauli_path: bool

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()

ShadowHamiltonian

Store the input model H and the reduced shadow matrix H_S.

There are two objects:

  • self.H: the input model on the full qubit space. On the sparse Pauli path this is a PauliSum-backed Hamiltonian (no 2^n matrix until .matrix is accessed). On the dense fallback it is the summed (2^n, 2^n) matrix.
  • self.H_S (also .shadow / get_H_S()): the actual shadow object—commutator matrix in the closed Pauli label basis only, shape (m, m) with m = |closure|. That size does not have to equal 2^n; it is whatever the closure step produces.

When H and every observable already expose a pauli_sum, construction stays in label/coeff space (no 4^n tomography, no full-space matrix multiplies). Otherwise the dense path densifies once, expands via traces, then shares the same structure-constant assembly for H_S.

Source code in shadowsim/shadow/shadow_hamiltonian.py
class ShadowHamiltonian:
    """Store the input model ``H`` and the reduced shadow matrix ``H_S``.

    There are two objects:

    - ``self.H``: the **input** model on the full qubit space. On the sparse Pauli
      path this is a PauliSum-backed ``Hamiltonian`` (no ``2^n`` matrix until
      ``.matrix`` is accessed). On the dense fallback it is the summed
      ``(2^n, 2^n)`` matrix.
    - ``self.H_S`` (also ``.shadow`` / ``get_H_S()``): the **actual shadow
      object**—commutator matrix in the **closed Pauli label basis** only, shape
      **``(m, m)``** with **``m = |closure|``**. That size does **not** have to
      equal ``2^n``; it is whatever the closure step produces.

    When ``H`` and every observable already expose a ``pauli_sum``, construction
    stays in label/coeff space (no ``4^n`` tomography, no full-space matrix
    multiplies). Otherwise the dense path densifies once, expands via traces,
    then shares the same structure-constant assembly for ``H_S``.
    """

    def __init__(
        self,
        operator_set: OperatorSet,
        H: Hamiltonian | Sequence[Hamiltonian],
        *,
        num_qubits: int | None = None,
        tol: float = 1e-10,
        verbose: bool = False,
    ) -> None:
        """Build a shadow Hamiltonian from an operator set and Hamiltonian terms.

        ``H`` may be a single ``Hamiltonian`` or a non-empty sequence of terms.
        If every term and every observable is Pauli-backed, terms are merged as
        PauliSums without densifying. Otherwise terms are summed on the full
        ``num_qubits``-qubit space via ``combined_hamiltonian_matrix``.
        ``num_qubits`` is inferred when possible (required if every term is a
        ``LocalHamiltonian``). After closure, ``self.H_S`` is the reduced matrix.
        Set ``verbose=True`` to print Pauli-set and closure progress.
        """
        self.operator_set = operator_set
        self.tol = float(tol)
        self.verbose = verbose

        model = _pauli_model_from_inputs(
            operator_set,
            H,
            num_qubits=num_qubits,
            tol=self.tol,
        )
        self.H = model.H
        self.num_qubits = model.num_qubits
        self.used_sparse_pauli_path = model.used_sparse_pauli_path
        self.pauli_decomposition = model.pauli_decomposition
        self.pauli_set = set(model.pauli_set)
        self.operator_pauli_set = set(model.operator_pauli_set)

        if self.verbose:
            print(
                "Pauli counts -> "
                f"Hamiltonian set: {len(self.pauli_set)}, "
                f"Operator set union: {len(self.operator_pauli_set)}"
            )

        self.operator_pauli_closure = _close_operator_paulis(self.operator_pauli_set, self.pauli_set)
        if self.verbose:
            print(f"Operator closure size: {len(self.operator_pauli_closure)}")

        self.basis = sorted(self.operator_pauli_closure)
        self.H_S = _assemble_h_s(self.basis, self.pauli_decomposition)

    @property
    def shadow(self) -> npt.NDArray[np.complexfloating]:
        """The shadow Hamiltonian: ``(m, m)`` with ``m = |closure|``; not ``(2^n, 2^n)`` in general."""
        return self.H_S

    def get_H_S(self) -> npt.NDArray[np.complexfloating]:
        """Return the shadow Hamiltonian in the closed Pauli basis.

        Same as ``shadow``. Shape ``(m, m)`` with ``m = len(self.basis)``,
        independent of ``2^n`` (unless m happens to match by coincidence).
        """
        return self.H_S

    def is_unitary(self) -> bool:
        """Return whether the shadow Hamiltonian matrix is unitary."""
        return unitary(self.H_S)

    def is_hermitian(self) -> bool:
        """Return whether the shadow Hamiltonian matrix is Hermitian."""
        return hermitian(self.H_S)

    def __str__(self) -> str:
        """Return a string representation of the ShadowHamiltonian."""
        if self.used_sparse_pauli_path:
            h_part = f"pauli_terms={len(self.pauli_decomposition)}"
        else:
            h_part = f"full_H.shape={self.H.matrix.shape}"
        return f"ShadowHamiltonian({h_part}, shadow.shape={self.H_S.shape}, n_qubits={self.num_qubits})"

    def __repr__(self) -> str:
        """Return a string representation of the ShadowHamiltonian."""
        if self.used_sparse_pauli_path:
            h_part = f"pauli_terms={len(self.pauli_decomposition)}"
        else:
            h_part = f"H.shape={self.H.matrix.shape}"
        return (
            "ShadowHamiltonian("
            f"{h_part}, "
            f"H_S.shape={self.H_S.shape}, "
            f"basis_size={len(self.basis)}, "
            f"sparse={self.used_sparse_pauli_path!r}, "
            f"tol={self.tol!r}, "
            f"verbose={self.verbose!r})"
        )

shadow property

shadow: NDArray[complexfloating]

The shadow Hamiltonian: (m, m) with m = |closure|; not (2^n, 2^n) in general.

__init__

__init__(
    operator_set: OperatorSet,
    H: Hamiltonian | Sequence[Hamiltonian],
    *,
    num_qubits: int | None = None,
    tol: float = 1e-10,
    verbose: bool = False,
) -> None

Build a shadow Hamiltonian from an operator set and Hamiltonian terms.

H may be a single Hamiltonian or a non-empty sequence of terms. If every term and every observable is Pauli-backed, terms are merged as PauliSums without densifying. Otherwise terms are summed on the full num_qubits-qubit space via combined_hamiltonian_matrix. num_qubits is inferred when possible (required if every term is a LocalHamiltonian). After closure, self.H_S is the reduced matrix. Set verbose=True to print Pauli-set and closure progress.

Source code in shadowsim/shadow/shadow_hamiltonian.py
def __init__(
    self,
    operator_set: OperatorSet,
    H: Hamiltonian | Sequence[Hamiltonian],
    *,
    num_qubits: int | None = None,
    tol: float = 1e-10,
    verbose: bool = False,
) -> None:
    """Build a shadow Hamiltonian from an operator set and Hamiltonian terms.

    ``H`` may be a single ``Hamiltonian`` or a non-empty sequence of terms.
    If every term and every observable is Pauli-backed, terms are merged as
    PauliSums without densifying. Otherwise terms are summed on the full
    ``num_qubits``-qubit space via ``combined_hamiltonian_matrix``.
    ``num_qubits`` is inferred when possible (required if every term is a
    ``LocalHamiltonian``). After closure, ``self.H_S`` is the reduced matrix.
    Set ``verbose=True`` to print Pauli-set and closure progress.
    """
    self.operator_set = operator_set
    self.tol = float(tol)
    self.verbose = verbose

    model = _pauli_model_from_inputs(
        operator_set,
        H,
        num_qubits=num_qubits,
        tol=self.tol,
    )
    self.H = model.H
    self.num_qubits = model.num_qubits
    self.used_sparse_pauli_path = model.used_sparse_pauli_path
    self.pauli_decomposition = model.pauli_decomposition
    self.pauli_set = set(model.pauli_set)
    self.operator_pauli_set = set(model.operator_pauli_set)

    if self.verbose:
        print(
            "Pauli counts -> "
            f"Hamiltonian set: {len(self.pauli_set)}, "
            f"Operator set union: {len(self.operator_pauli_set)}"
        )

    self.operator_pauli_closure = _close_operator_paulis(self.operator_pauli_set, self.pauli_set)
    if self.verbose:
        print(f"Operator closure size: {len(self.operator_pauli_closure)}")

    self.basis = sorted(self.operator_pauli_closure)
    self.H_S = _assemble_h_s(self.basis, self.pauli_decomposition)

get_H_S

get_H_S() -> NDArray[complexfloating]

Return the shadow Hamiltonian in the closed Pauli basis.

Same as shadow. Shape (m, m) with m = len(self.basis), independent of 2^n (unless m happens to match by coincidence).

Source code in shadowsim/shadow/shadow_hamiltonian.py
def get_H_S(self) -> npt.NDArray[np.complexfloating]:
    """Return the shadow Hamiltonian in the closed Pauli basis.

    Same as ``shadow``. Shape ``(m, m)`` with ``m = len(self.basis)``,
    independent of ``2^n`` (unless m happens to match by coincidence).
    """
    return self.H_S

is_unitary

is_unitary() -> bool

Return whether the shadow Hamiltonian matrix is unitary.

Source code in shadowsim/shadow/shadow_hamiltonian.py
def is_unitary(self) -> bool:
    """Return whether the shadow Hamiltonian matrix is unitary."""
    return unitary(self.H_S)

is_hermitian

is_hermitian() -> bool

Return whether the shadow Hamiltonian matrix is Hermitian.

Source code in shadowsim/shadow/shadow_hamiltonian.py
def is_hermitian(self) -> bool:
    """Return whether the shadow Hamiltonian matrix is Hermitian."""
    return hermitian(self.H_S)

__str__

__str__() -> str

Return a string representation of the ShadowHamiltonian.

Source code in shadowsim/shadow/shadow_hamiltonian.py
def __str__(self) -> str:
    """Return a string representation of the ShadowHamiltonian."""
    if self.used_sparse_pauli_path:
        h_part = f"pauli_terms={len(self.pauli_decomposition)}"
    else:
        h_part = f"full_H.shape={self.H.matrix.shape}"
    return f"ShadowHamiltonian({h_part}, shadow.shape={self.H_S.shape}, n_qubits={self.num_qubits})"

__repr__

__repr__() -> str

Return a string representation of the ShadowHamiltonian.

Source code in shadowsim/shadow/shadow_hamiltonian.py
def __repr__(self) -> str:
    """Return a string representation of the ShadowHamiltonian."""
    if self.used_sparse_pauli_path:
        h_part = f"pauli_terms={len(self.pauli_decomposition)}"
    else:
        h_part = f"H.shape={self.H.matrix.shape}"
    return (
        "ShadowHamiltonian("
        f"{h_part}, "
        f"H_S.shape={self.H_S.shape}, "
        f"basis_size={len(self.basis)}, "
        f"sparse={self.used_sparse_pauli_path!r}, "
        f"tol={self.tol!r}, "
        f"verbose={self.verbose!r})"
    )

ShadowState

Bases: State

Shadow state whose amplitudes are normalized operator expectations.

For a state |ψ⟩ and operators O_m, the amplitude weight is A = Σ_m |⟨O_m⟩|². The shadow vector is ⟨O_m⟩ / √A, which has Euclidean norm 1 whenever A > 0, then zero-padded to the next power of two or to 2**num_qubits.

Source code in shadowsim/shadow/shadow_state.py
class ShadowState(State):
    """Shadow state whose amplitudes are normalized operator expectations.

    For a state ``|ψ⟩`` and operators ``O_m``, the amplitude weight is
    ``A = Σ_m |⟨O_m⟩|²``. The shadow vector is ``⟨O_m⟩ / √A``, which has
    Euclidean norm 1 whenever ``A > 0``, then zero-padded to the next power
    of two or to ``2**num_qubits``.
    """

    def __init__(
        self,
        state: State,
        operator_set: OperatorSet,
        *,
        num_qubits: int | None = None,
    ) -> None:
        """Initialize a ShadowState from a state and operator set.

        Raises:
            ValueError: If ``A = Σ|⟨O⟩|²`` is zero, so no unit shadow vector
                exists, or if ``num_qubits`` cannot hold the components.
        """
        self.A = 0.0
        exp_vals: list[complex] = []

        psi = state.get_state()
        for op in operator_set.operators:
            exp_Om = np.vdot(psi, op.matrix @ psi)
            self.A += float(np.abs(exp_Om) ** 2)
            exp_vals.append(exp_Om)

        shadow_state = np.asarray(exp_vals, dtype=np.complex128)
        if self.A == 0:
            raise ValueError(
                "cannot build a shadow state when A = Σ|⟨O⟩|² is zero; every operator expectation vanished"
            )
        shadow_state = shadow_state / np.sqrt(self.A)

        n = int(shadow_state.shape[0])
        if num_qubits is not None:
            nq = int(num_qubits)
            if nq < 0:
                raise ValueError("num_qubits must be non-negative")
            need = 2**nq
            if n > need:
                raise ValueError(f"not enough room in 2**num_qubits={need} for {n} shadow components")
            padded_len = need
        else:
            padded_len = next_power_of_two(n)
        num_qubits_out = padded_len.bit_length() - 1
        if int(shadow_state.shape[0]) < padded_len:
            out = np.zeros(padded_len, dtype=np.complex128)
            out[:n] = shadow_state
            shadow_state = out

        super().__init__(shadow_state, num_qubits_out, 2)

    def __str__(self) -> str:
        """Return a string representation of the ShadowState."""
        return f"ShadowState(num_qubits={self.get_num_qubits()}, A={self.A}, shape={self.state.shape})"

    def __repr__(self) -> str:
        """Return a string representation of the ShadowState."""
        return f"ShadowState(state={self.state!r}, A={self.A!r}, num_qubits={self.get_num_qubits()})"

__init__

__init__(
    state: State,
    operator_set: OperatorSet,
    *,
    num_qubits: int | None = None,
) -> None

Initialize a ShadowState from a state and operator set.

Raises:

  • ValueError –

    If A = Σ|⟨O⟩|² is zero, so no unit shadow vector exists, or if num_qubits cannot hold the components.

Source code in shadowsim/shadow/shadow_state.py
def __init__(
    self,
    state: State,
    operator_set: OperatorSet,
    *,
    num_qubits: int | None = None,
) -> None:
    """Initialize a ShadowState from a state and operator set.

    Raises:
        ValueError: If ``A = Σ|⟨O⟩|²`` is zero, so no unit shadow vector
            exists, or if ``num_qubits`` cannot hold the components.
    """
    self.A = 0.0
    exp_vals: list[complex] = []

    psi = state.get_state()
    for op in operator_set.operators:
        exp_Om = np.vdot(psi, op.matrix @ psi)
        self.A += float(np.abs(exp_Om) ** 2)
        exp_vals.append(exp_Om)

    shadow_state = np.asarray(exp_vals, dtype=np.complex128)
    if self.A == 0:
        raise ValueError(
            "cannot build a shadow state when A = Σ|⟨O⟩|² is zero; every operator expectation vanished"
        )
    shadow_state = shadow_state / np.sqrt(self.A)

    n = int(shadow_state.shape[0])
    if num_qubits is not None:
        nq = int(num_qubits)
        if nq < 0:
            raise ValueError("num_qubits must be non-negative")
        need = 2**nq
        if n > need:
            raise ValueError(f"not enough room in 2**num_qubits={need} for {n} shadow components")
        padded_len = need
    else:
        padded_len = next_power_of_two(n)
    num_qubits_out = padded_len.bit_length() - 1
    if int(shadow_state.shape[0]) < padded_len:
        out = np.zeros(padded_len, dtype=np.complex128)
        out[:n] = shadow_state
        shadow_state = out

    super().__init__(shadow_state, num_qubits_out, 2)

__str__

__str__() -> str

Return a string representation of the ShadowState.

Source code in shadowsim/shadow/shadow_state.py
def __str__(self) -> str:
    """Return a string representation of the ShadowState."""
    return f"ShadowState(num_qubits={self.get_num_qubits()}, A={self.A}, shape={self.state.shape})"

__repr__

__repr__() -> str

Return a string representation of the ShadowState.

Source code in shadowsim/shadow/shadow_state.py
def __repr__(self) -> str:
    """Return a string representation of the ShadowState."""
    return f"ShadowState(state={self.state!r}, A={self.A!r}, num_qubits={self.get_num_qubits()})"

check_invariance

check_invariance(
    operator_set: OperatorSet,
    H: Hamiltonian | Sequence[Hamiltonian],
    *,
    num_qubits: int | None = None,
    tol: float = 1e-10,
) -> InvarianceReport

Check whether H and operator_set satisfy the invariance property.

Uses the same sparse/dense Pauli presentation as ShadowHamiltonian. Reports whether the original Pauli support of S is already closed under commutators with H, and how many labels must be added to close it. Also reports whether the closed-basis H_S is Hermitian.

Parameters:

  • operator_set (OperatorSet) –

    Observables whose Pauli support defines S.

  • H (Hamiltonian | Sequence[Hamiltonian]) –

    A single Hamiltonian or a non-empty sequence of terms.

  • num_qubits (int | None, default: None ) –

    Qubit count; inferred when possible (required if every term is a LocalHamiltonian).

  • tol (float, default: 1e-10 ) –

    Magnitude threshold for keeping Pauli coefficients.

Returns:

Source code in shadowsim/shadow/invariance.py
def check_invariance(
    operator_set: OperatorSet,
    H: Hamiltonian | Sequence[Hamiltonian],
    *,
    num_qubits: int | None = None,
    tol: float = 1e-10,
) -> InvarianceReport:
    """Check whether ``H`` and ``operator_set`` satisfy the invariance property.

    Uses the same sparse/dense Pauli presentation as ``ShadowHamiltonian``.
    Reports whether the original Pauli support of ``S`` is already closed under
    commutators with ``H``, and how many labels must be added to close it.
    Also reports whether the closed-basis ``H_S`` is Hermitian.

    Args:
        operator_set: Observables whose Pauli support defines ``S``.
        H: A single ``Hamiltonian`` or a non-empty sequence of terms.
        num_qubits: Qubit count; inferred when possible (required if every term
            is a ``LocalHamiltonian``).
        tol: Magnitude threshold for keeping Pauli coefficients.

    Returns:
        An ``InvarianceReport`` summarizing closure and Hermiticity.
    """
    model = _pauli_model_from_inputs(
        operator_set,
        H,
        num_qubits=num_qubits,
        tol=tol,
    )
    original = set(model.operator_pauli_set)
    closure = _close_operator_paulis(original, set(model.pauli_set))
    added = closure - original
    basis = sorted(closure)
    h_s = _assemble_h_s(basis, model.pauli_decomposition)

    return InvarianceReport(
        is_closed=not added,
        original_size=len(original),
        closure_size=len(closure),
        growth=len(added),
        original_paulis=frozenset(original),
        closure_paulis=frozenset(closure),
        added_paulis=frozenset(added),
        h_s_is_hermitian=hermitian(h_s),
        num_qubits=model.num_qubits,
        used_sparse_pauli_path=model.used_sparse_pauli_path,
    )