Metadata-Version: 2.4
Name: shadowsim
Version: 1.0.0
Summary: Tools for shadow Hamiltonian research and quantum simulation benchmarking.
Author-email: Aidan Sims <simsaidan@gmail.com>
License-Expression: MIT
Project-URL: Repository, https://github.com/simsaidan/ShadowSim.py
Project-URL: Documentation, https://simsaidan.github.io/ShadowSim.py/
Project-URL: Changelog, https://github.com/simsaidan/ShadowSim.py/blob/main/CHANGELOG.md
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Topic :: Scientific/Engineering :: Quantum Computing
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=2.0
Provides-Extra: qutip
Requires-Dist: qutip; extra == "qutip"
Provides-Extra: qiskit
Requires-Dist: qiskit; extra == "qiskit"
Requires-Dist: qiskit-aer; extra == "qiskit"
Requires-Dist: scipy>=1.14; extra == "qiskit"
Provides-Extra: viz
Requires-Dist: matplotlib; extra == "viz"
Provides-Extra: pauli-propagation
Requires-Dist: juliacall==0.9.36; extra == "pauli-propagation"
Provides-Extra: qulacs
Requires-Dist: qulacs; extra == "qulacs"
Provides-Extra: cirq
Requires-Dist: cirq; extra == "cirq"
Provides-Extra: circuits
Requires-Dist: scipy>=1.14; extra == "circuits"
Provides-Extra: yaml
Requires-Dist: pyyaml; extra == "yaml"
Provides-Extra: all
Requires-Dist: shadowsim[qutip]; extra == "all"
Requires-Dist: shadowsim[qiskit]; extra == "all"
Requires-Dist: shadowsim[viz]; extra == "all"
Requires-Dist: shadowsim[qulacs]; extra == "all"
Requires-Dist: shadowsim[cirq]; extra == "all"
Requires-Dist: shadowsim[circuits]; extra == "all"
Requires-Dist: shadowsim[yaml]; extra == "all"
Dynamic: license-file

# ShadowSim.py

[![Test and coverage](https://github.com/simsaidan/ShadowSim.py/actions/workflows/test-coverage.yml/badge.svg)](https://github.com/simsaidan/ShadowSim.py/actions/workflows/test-coverage.yml)
[![codecov](https://codecov.io/gh/simsaidan/ShadowSim.py/branch/main/graph/badge.svg)](https://app.codecov.io/gh/simsaidan/ShadowSim.py)

## Overview

ShadowSim.py is an open-source Python library with two main purposes:

1. **Shadow Hamiltonian research**: support analysis and further research on shadow Hamiltonian simulation.
2. **Algorithm comparison**: make it easy to compare quantum simulation algorithms for **open** and **closed** systems.

**Note:** “Shadow” here means *shadow Hamiltonian simulation* ([Somma et al., arXiv:2407.21775](https://arxiv.org/abs/2407.21775)), **not** classical shadow tomography / randomized measurement protocols.

**When to use:** Use ShadowSim to build and inspect shadow Hamiltonians for small qubit systems, and to benchmark open- or closed-system simulation algorithms against a classical reference (e.g. QuTiP). The [simulation builder](#simulation-builder) is the local page for that work.

## Installation

The core package depends only on NumPy. Product-formula simulators need the `circuits` extra (SciPy). QuTiP, Qiskit, Matplotlib, Julia's PauliPropagation, Qulacs, and Cirq are optional:

```bash
python -m pip install shadowsim
python -m pip install "shadowsim[qutip]"
python -m pip install "shadowsim[qiskit]"
python -m pip install "shadowsim[circuits]"
python -m pip install "shadowsim[viz]"
python -m pip install "shadowsim[pauli_propagation]"
python -m pip install "shadowsim[qulacs]"
python -m pip install "shadowsim[cirq]"
python -m pip install "shadowsim[yaml]"
python -m pip install "shadowsim[all]"
```

| Extra | Provides |
| --- | --- |
| `qutip` | `QutipSimulator` and QuTiP interop (`from_qutip` / `to_qutip`) |
| `qiskit` | `AerCircuitBackend` and the Qiskit translation used by `PauliPropagationBackend` (`qiskit`, `qiskit-aer`, and `scipy`) |
| `circuits` | Trotterization, Split JMatrix, Hybrid WML, and `run_shadow_simulation` (`scipy`) |
| `viz` | Matplotlib plots (`plot_results` and benchmark figures) |
| `pauli_propagation` | `PauliPropagationBackend` (`juliacall` 0.9.36). Julia 1.10+ and the Julia package are a separate install; see [PauliPropagation](#paulipropagation) |
| `qulacs` | `QulacsCircuitBackend` |
| `cirq` | `CirqCircuitBackend` |
| `yaml` | Load YAML experiment files with `shadowsim run` (`pyyaml`) |
| `all` | `qutip`, `qiskit`, `circuits`, `viz`, `qulacs`, `cirq`, and `yaml` |

The package can then be imported as `shadowsim`. Importing a backend or plot helper without its extra raises an `ImportError` that names the extra to install.

For a local development install (`uv sync --all-extras`, tests, lint, scaffolding a simulator),
see [CONTRIBUTING.md](CONTRIBUTING.md).

## Usage

### Simulation builder

`shadowsim serve` opens the simulation builder, a local page for assembling and running a simulation. Cards come from the same catalogs as the research commands. Drag a card into a lane, or tap it to place it. Lanes run left to right.

| Lane | What you set |
| --- | --- |
| Initial state | Basis, Gray, angle, or amplitude |
| Model | A preexisting model, or operators you add |
| Method | One or more simulators. Circuit methods take a backend; a classical reference such as QuTiP does not. The first row is the reference when several methods are compared |
| Measure | Pauli expectations, counts, or the measurements the model defines |
| Then | Plot the curves, save arrays and metadata, or export runtime and shot budget as JSON |

The page checks the run as you edit it and shows the version 1 document in a code preview. **Run simulation** runs that document, and the curves appear in the results panel. Save and export paths stay under `results/` (change the root with `--output-dir`). **Export board** downloads the layout as JSON, and **Import board** loads one back. The page is laid out for a desktop window.

```bash
shadowsim serve
shadowsim serve --host 127.0.0.1 --port 8000 --output-dir results --no-browser
```

The server binds `127.0.0.1:8000`, prints a one-time URL that carries a startup token, and opens that URL in the default browser. A non-loopback address requires `--allow-remote` together with `--tls-cert` and `--tls-key`. Anyone who has the startup token can submit a run. A method or backend whose extra is not installed is left off the page. `shadowsim serve --help` lists every flag, and the run-document schema is in the [CLI docs](https://simsaidan.github.io/ShadowSim.py/cli/).

### Command-line interface

Research commands (`model`, `simulate`, `compare`, `run`) build and run the same version 1 documents as the [simulation builder](#simulation-builder). Examples and the document schema are in the [CLI docs](https://simsaidan.github.io/ShadowSim.py/cli/).

```bash
shadowsim model ising --qubits 4 --J 1.0
shadowsim simulate --model ising --qubits 2 --simulator trotterization --time-steps 2 --num-steps 1 --backend numpy
shadowsim compare --model ising --qubits 2 --simulator trotterization --time-steps 2 --num-steps 1 --backends numpy,aer
shadowsim run experiment.json
```

### Python API

Public objects are imported from their domain subpackages:
```python
from shadowsim.core import DensityOperator, Hamiltonian, Operator, State
from shadowsim.encoding import AmplitudeEncoding, AngleEncoding, ComputationalBasisEncoding, GrayEncoding
from shadowsim.shadow import ShadowHamiltonian, check_invariance
from shadowsim.simulators import QutipSimulator, SimulationResult
```

### State encoding

`shadowsim.encoding` turns classical data into a normalized `State`. Simulators take that state as `initial_state`.

```python
import numpy as np
from shadowsim.encoding import AmplitudeEncoding, AngleEncoding, ComputationalBasisEncoding, GrayEncoding

basis = ComputationalBasisEncoding(2).encode([1, 0])  # |10>
gray = GrayEncoding(2).encode([1, 0])  # |11>, Gray code of binary 2
angle = AngleEncoding().encode([np.pi / 2, 0.0])
amplitude = AmplitudeEncoding().encode([1.0, 1.0, 0.0])  # zero-padded to 2 qubits
```

`load_encoding_data` reads a 1D vector from a `.npy`, `.txt`, or `.csv` file for an encoder, as in `AmplitudeEncoding().encode(load_encoding_data("amplitudes.npy"))`.

[`examples/state_encoding.py`](examples/state_encoding.py) passes an encoded state to `QutipSimulator`.

### QuTiP interop

With the `qutip` extra, convert between QuTiP `Qobj` values and ShadowSim core types:

```python
from shadowsim.interop.qutip import from_qutip, to_qutip

H = from_qutip(qutip_H)  # → Hamiltonian
ops = [from_qutip(c) for c in c_ops]  # → Operator
psi = from_qutip(psi0)  # → State (ket)
rho = from_qutip(qutip_rho)  # → DensityOperator (Hermitian, PSD, tr≈1)
qobj = to_qutip(H)
```

Override with `kind=` when needed (e.g. `kind="hamiltonian"` for a unit-trace projector).

### PauliPropagation

`PauliPropagationBackend` returns ⟨Z⟩ and ⟨X⟩ for selected qubits of one program, following [Rudolph et al., arXiv:2505.21606](https://arxiv.org/abs/2505.21606). It translates that program to OpenQASM 2, so the `qiskit` extra is required as well. The `pauli_propagation` extra installs `juliacall` 0.9.36. Julia 1.10 or newer has to be available already. That juliacall release is the one that resolves next to the PauliPropagation revision below.

In the Julia project juliacall uses for this Python environment, install the OpenQASM reader:

```python
import juliacall
from juliacall import Main as jl

jl.seval("using Pkg")
jl.seval('Pkg.add(url="https://github.com/SparqleSim/PauliPropagation.jl", rev="6e8c1ae")')
```

`readqasm` on that revision accepts OpenQASM 2 / `qelib1` gates, skips `barrier` and `id`, and rejects `measure`, `reset`, and unknown gates. Qubit indexes are 0-based, and each method returns one float per index in that order. `shots` and `seed` are accepted and ignored. `max_weight` defaults to `inf`, so every Pauli weight is kept, and `min_abs_coeff` defaults to `1e-10`. The [simulation builder](#simulation-builder) card edits both before a run.

```python
import numpy as np

from shadowsim.backends import PauliPropagationBackend
from shadowsim.backends.program import Program, Unitary

half = 0.2
rx = np.array([[np.cos(half), -1j * np.sin(half)], [-1j * np.sin(half), np.cos(half)]])
program = Program(1, 0, [Unitary(rx, (0,))])
backend = PauliPropagationBackend()
backend.z_expectations(program, [0], shots=1, seed=None)  # [cos(0.4)]
backend.x_expectations(program, [0], shots=1, seed=None)  # [0.0]
```

`RX(0.4)` applied to `|0⟩` stays in the YZ plane, so ⟨X⟩ is 0. `run_counts` raises `NotImplementedError`. `TrotterizationSimulator` and the [simulation builder](#simulation-builder) can run a closed Trotter program on this backend: product states are prepared with single-qubit gates, the program is translated to Qiskit and transpiled into gates the reader accepts, and every qubit returns the expectation of its `basis` letter. It is an expectation backend, so it has no shot counts (see [Measurements](#measurements)). Split JMatrix and Hybrid WML sample an ancilla and stay on Aer.

### Simulation results

Each backend’s `simulate()` / `run()` returns a `SimulationResult` with:

- `times`, `observables` (one curve per measurement), optional `states` (usually `None`)
- `counts`: one bitstring-to-shots dict per time point from a sampling backend, otherwise `None`
- `seed`, `algorithm`, `runtime`, and `metadata` (software version, grid params, backend params)

Serialize and reload with `result.save(path)` / `SimulationResult.load(path)` (directory of
`times.npy`, numeric `.npz` archives, `counts.json` when there are counts, and `meta.json`).
Loading does not unpickle array files. Low-level curves remain on `simulator.results`
for plotting and benchmarking.

### Measurements

Circuit simulators stop at the measurement. Before measuring, they rotate each
qubit into its letter of `basis` (default all `Z`; `X` adds a Hadamard, `Y` adds
S†, stored as a 2×2 unitary, then a Hadamard). What comes back depends on the circuit backend:

- **Sampling backends** such as `AerCircuitBackend` have a `shots` budget and
  return counts. `result.counts` holds one dict per time point, and `observables`
  stays empty until you measure. Any `Measurement` can read them.
- **Expectation backends** such as `PauliPropagationBackend`,
  `NumpyCircuitBackend`, `QulacsCircuitBackend`, and `CirqCircuitBackend` have
  no shot budget.
  Trotterization fills `observables` with each qubit's ⟨P⟩ for its `basis`
  letter and leaves `counts` empty. A one-qubit measurement is read from that
  distribution: `counts["0"]` is `(1 + ⟨P⟩) / 2`, `counts["1"]` is
  `(1 - ⟨P⟩) / 2`, and `shots` is 1. Dividing by `shots` gives the infinite-shot
  value. An expression that uses raw counts without `shots` reads those
  probabilities. Two or more qubits need a sampling backend, because the result
  has no correlations between qubits.

In every counts key, bit `i` is system qubit `i` (Qiskit's order is reversed
before the counts are stored). Split JMatrix drops its ancilla bit, so its keys
cover the system qubits only.

A `Measurement` names some qubits and an arithmetic expression on their counts.
Keys list those qubits in the order given, and `shots` is the total for that time
point. Expressions may use numbers, parentheses, `+ - * / **`, `shots`, and
`counts["01"]`; a bitstring that never appeared is 0. `simulator.measure(...)`
evaluates a list of measurements at every time point and returns a result with one
curve per measurement. `apply_measurements(result, ...)` does the same for a
result you already have.

```python
from shadowsim.backends import AerCircuitBackend
from shadowsim.models import ising
from shadowsim.simulators import Measurement, TrotterizationSimulator

model = ising(n_qubits=3)
simulator = TrotterizationSimulator(
    model.local_hamiltonians,
    [],
    model.psi0,
    num_qubits=model.num_qubits,
    total_time=1.0,
    time_steps=11,
    num_steps=4,
    basis="ZZX",
    circuit_backend=AerCircuitBackend(shots=1000),
)
simulator.simulate()
result = simulator.measure(
    [
        Measurement((2,), '(counts["0"] - counts["1"]) / shots', "expectation on 2"),  # ⟨X⟩ on qubit 2
        Measurement((0, 1), '(counts["00"] + counts["11"]) / shots', "qubits 0 and 1 agree"),
    ]
)
```

`counts["1"] / shots` is the fraction of shots where that qubit read 1. A
Tavis–Cummings cavity stored on two qubits uses
`(3 * counts["11"] + 2 * counts["10"] + counts["01"]) / shots`
for its mean photon number.

`start()` runs that same `simulate()` call on a worker thread and returns a `SimulationJob`
immediately. Poll `status` (`pending`, `running`, `succeeded`, or `failed`). `result()` waits
for the `SimulationResult`; pass `timeout` to stop waiting while the job is still running,
which raises `TimeoutError`. If `simulate()` raised, `result()` raises that exception. Split J
and Trotter jobs count finished time points in `completed_steps` and `total_steps`. A QuTiP
job leaves both as `None`.

The following simulators are supported by the package:

| Name | Type | Can handle open systems |
| --- | --- | --- |
| Qutip simulator | classical reference | true |
| Split JMatrix | quantum-inspired | true |
| Trotterization | quantum-inspired | false |
| Hybrid wave-matrix Lindbladization | quantum-inspired | true |

### Backends

The circuit simulators hand each time point's program to a circuit backend, passed
as `circuit_backend=`. QuTiP integrates the master equation itself and takes no
backend. The following backends are supported:

| Backend | Kind | Simulators | Extra |
| --- | --- | --- | --- |
| `AerCircuitBackend` | sampling: returns shot counts from a `shots` budget | Split JMatrix, Trotterization, Hybrid WML | `qiskit` |
| `NumpyCircuitBackend` | expectation: exact Pauli expectations from a NumPy statevector. `run_counts` can still sample | Trotterization (closed systems) | core |
| `PauliPropagationBackend` | expectation: returns exact Pauli expectations, no counts | Trotterization (closed systems) | `qiskit` and `pauli_propagation` |
| `QulacsCircuitBackend` | expectation: exact Pauli expectations from a Qulacs statevector. `run_counts` can still sample | Trotterization (closed systems) | `qulacs` |
| `CirqCircuitBackend` | expectation: exact Pauli expectations from a Cirq statevector. `run_counts` can still sample | Trotterization (closed systems) | `cirq` |

`AerCircuitBackend` is the default for the circuit simulators. Split JMatrix
and Hybrid WML sample an ancilla, so they need a sampling backend. See
[Measurements](#measurements) for what each kind returns and
[PauliPropagation](#paulipropagation) for the Julia setup.

`NumpyCircuitBackend` is the reference for small circuits. Correctness and
readability come before performance. It stores no `shots` attribute, so
Trotterization reads exact ⟨Z⟩ and ⟨X⟩. `run_counts` still samples the
computational basis, and the same `seed` repeats those counts. `Reset` and a
measurement followed by a gate are rejected. Split JMatrix and Hybrid WML sample
an ancilla with `Reset`, so they use Aer.

Checked circuits agree with Aer statevector probabilities to `1e-8`. One local
Hamiltonian makes the Trotter product exact: that ⟨Z⟩ curve matches `cos(2t)`
to `1e-8` and QuTiP to `1e-6`. A seeded Hadamard of 4000 shots stays within
`0.05` of Aer and of `1/2`.

```python
import numpy as np

from shadowsim.backends import NumpyCircuitBackend
from shadowsim.backends.program import Program, Unitary

half = 0.2
rx = np.array([[np.cos(half), -1j * np.sin(half)], [-1j * np.sin(half), np.cos(half)]])
program = Program(1, 0, [Unitary(rx, (0,))])
backend = NumpyCircuitBackend()
backend.z_expectations(program, [0], shots=1, seed=None)  # [cos(0.4)]
backend.x_expectations(program, [0], shots=1, seed=None)  # [0.0]
```

`QulacsCircuitBackend` is the same kind of expectation backend, with the
statevector evolved by Qulacs. It does not need Qiskit. It stores no `shots` attribute, so
Trotterization reads exact ⟨Z⟩ and ⟨X⟩. `run_counts` still samples the
computational basis, and the same `seed` repeats those counts. `Reset` and a
measurement followed by a gate are rejected. Split JMatrix and Hybrid WML sample
an ancilla with `Reset`, so they use Aer.

Statevectors agree with `NumpyCircuitBackend` to `1e-8`. One local Hamiltonian
makes the Trotter product exact: that ⟨Z⟩ curve matches `cos(2t)` to `1e-8`.
A seeded Hadamard of 4000 shots stays within `0.05` of NumPy and of `1/2`.
[`examples/qulacs_benchmark.py`](examples/qulacs_benchmark.py) times the two
backends on one closed Trotter circuit. That script is not part of the test run.

```python
import numpy as np

from shadowsim.backends import QulacsCircuitBackend
from shadowsim.backends.program import Program, Unitary

half = 0.2
rx = np.array([[np.cos(half), -1j * np.sin(half)], [-1j * np.sin(half), np.cos(half)]])
program = Program(1, 0, [Unitary(rx, (0,))])
backend = QulacsCircuitBackend()
backend.z_expectations(program, [0], shots=1, seed=None)  # [cos(0.4)]
backend.x_expectations(program, [0], shots=1, seed=None)  # [0.0]
```

`CirqCircuitBackend` is the same kind of expectation backend, with the
statevector evolved by Cirq. It does not need Qiskit. It stores no `shots` attribute, so
Trotterization reads exact ⟨Z⟩ and ⟨X⟩. `run_counts` still samples the
computational basis, and the same `seed` repeats those counts. `Reset`, a
measurement followed by a gate, and circuit metrics are rejected. Split
JMatrix and Hybrid WML sample an ancilla with `Reset`, so they use Aer.

Statevectors agree with `NumpyCircuitBackend` to `1e-8`. One local Hamiltonian
makes the Trotter product exact: that ⟨Z⟩ curve matches `cos(2t)` to `1e-8`.
A seeded Hadamard of 4000 shots stays within `0.05` of NumPy and of `1/2`.

```python
import numpy as np

from shadowsim.backends import CirqCircuitBackend
from shadowsim.backends.program import Program, Unitary

half = 0.2
rx = np.array([[np.cos(half), -1j * np.sin(half)], [-1j * np.sin(half), np.cos(half)]])
program = Program(1, 0, [Unitary(rx, (0,))])
backend = CirqCircuitBackend()
backend.z_expectations(program, [0], shots=1, seed=None)  # [cos(0.4)]
backend.x_expectations(program, [0], shots=1, seed=None)  # [0.0]
```

### Sparse / Pauli-label shadow construction

Pass Pauli labels (or `PauliSum`s) for both the Hamiltonian and the observables so
`ShadowHamiltonian` can build `H_S` in label space—no `4^n` tomography and no
full `2^n × 2^n` matrix multiplies during construction:

```python
from shadowsim.core import Hamiltonian, OperatorSet
from shadowsim.shadow import ShadowHamiltonian

shadow = ShadowHamiltonian(
    OperatorSet(["XII", "YII", "ZII", "IIX"]),
    [Hamiltonian("XII"), Hamiltonian("IIX")],
)
assert shadow.used_sparse_pauli_path
print(shadow.H_S.shape)  # (|closure|, |closure|)
```

Dense matrices and `LocalHamiltonian` terms still work; they take the densifying
fallback (`used_sparse_pauli_path` is `False`). See also
[`examples/simple_shadow.py`](examples/simple_shadow.py).

To check whether a given operator set already satisfies the invariance property
(closed under `[H, ·]`) without building a full shadow simulation, use
`check_invariance`. It reports whether the set is closed, how many Pauli labels
must be added to close it, and whether the closed-basis `H_S` is Hermitian:

```python
from shadowsim.core import Hamiltonian, OperatorSet
from shadowsim.shadow import check_invariance

report = check_invariance(
    OperatorSet(["Z"]),
    Hamiltonian("X"),
)
assert not report.is_closed
assert report.growth == 1
assert report.added_paulis == frozenset({"Y"})
```

For practical scale limits (sparse vs dense, closure size, simulators), see
[Scalability / practical limits](#scalability--practical-limits).

## Scalability / practical limits

### Shadow construction

- Prefer Pauli labels / `PauliSum` so `ShadowHamiltonian` takes the sparse path
  (`used_sparse_pauli_path`). Cost then tracks Hamiltonian Pauli terms × closure
  size `m`, not `4^n`.
- Dense fallback (dense matrices / `LocalHamiltonian`): practical for small `n`
  (roughly ≤3–4 as historically exercised). Bottleneck is `4^n` Pauli tomography
  plus dense `2^n` linear algebra.
- Closure size `m` can grow independently of Hilbert-space dimension; `H_S` is
  always `m×m` (not `2^n×2^n`).
- Inspect cost before a long run: `ShadowHamiltonian(..., verbose=True)` prints
  Hamiltonian Pauli count, operator-set union size, and closure size.

### What works today

| Path | Practical scale today | Bottleneck |
| --- | --- | --- |
| `ShadowHamiltonian` (Pauli labels) | few-term models; `n` past ~3–4 when closure stays small | Pauli terms × closure size `m` |
| `ShadowHamiltonian` (dense / local) | small `n` (~≤3–4) | `4^n` tomography + dense mats |
| QuTiP simulator | small truncated models | stiff ODEs / Hilbert dim |
| Split JMatrix + Aer | tiny time grids / shot budgets for smoke; set `seed` for reproducible Aer shots | circuit per timestep × shots |
| Trotterization + Aer | closed systems only; tiny time grids / shot budgets; set `seed` for reproducible Aer shots | circuit per timestep × shots |
| Trotterization + NumPy | small closed systems used as a reference | one statevector of length `2^n` per time point |

### Not yet / still heavy

For shadow construction, use the
[sparse / Pauli-label path](#sparse--pauli-label-shadow-construction) whenever
you already have a Pauli decomposition.

## Examples

### Example 1: Exploring a simple shadow simulation

The complete example is in [`examples/simple_shadow.py`](examples/simple_shadow.py)
and can be run after `uv sync --all-extras`:
```bash
uv run python examples/simple_shadow.py
```
That example uses Pauli labels (sparse construction path) and
`run_shadow_simulation` for the reduced shadow dynamics. Pass a circuit backend:
`NumpyCircuitBackend`, `QulacsCircuitBackend`, and `CirqCircuitBackend` give
exact curves, and a sampling backend such as `AerCircuitBackend` estimates
them from its `shots`.
```python
from shadowsim.backends.numpy import NumpyCircuitBackend

shadow = run_shadow_simulation(
    hamiltonians,
    observables,
    initial_state,
    total_time=5.0,
    time_steps=400,
    circuit_backend=NumpyCircuitBackend(),
)
```
`shadow.expectations` holds the signed `⟨O_k⟩(t)` for each operator in the
closure basis, labeled by `shadow.basis`, so the curves line up with a QuTiP
run on the physical system. Pass `shadow_observables` (for example
`computational_basis_projectors`) to also get quadratic shadow-space curves in
`shadow.shadow_observable_expectations`.
The returned result can `save` and `load` the shadow traces, and `plot_results` draws them.
Pass `verbose=True` to `run_shadow_simulation` if you want Pauli-set and
closure sizes printed.

### Example 2: Comparing a quantum algorithm against a classical solver

This is a paper-scale QuTiP vs Split JMatrix + Aer comparison (`301` time points
and a non-trivial shot budget)—expect long wall time and nontrivial Aer cost; it
is not a CI smoke test. The runnable script
[`examples/simple_algo_benchmark.py`](examples/simple_algo_benchmark.py) uses the
same scale; there is no reduced smoke grid yet. See
[Scalability / practical limits](#scalability--practical-limits).

Imagine a scenario in which you want to compare the results of a new quantum
simulation algorithm against a source of truth like QuTiP.

We build the open cavity–emitter (Tavis–Cummings–like) model with the shared
factory. Defaults match the historical Example 2 parameters; pass
`n_emitters`, `g`, `kappa`, and friends to change the physics without rewriting
operator embeddings.

```python
from shadowsim.backends import AerCircuitBackend
from shadowsim.benchmarking import Benchmark
from shadowsim.models import tavis_cummings
from shadowsim.simulators import QutipSimulator, SplitJMatrixSimulator

model = tavis_cummings()
```

Next, we create two simulators, one for the new algorithm and one for the
source of truth.

```python
# Qutip simulator
qutip_simulator = QutipSimulator(
    model.full_hamiltonians,
    model.c_ops_full,
    model.psi0,
    model.e_ops,
    num_qubits=model.num_qubits,
    total_time=0.25,
    time_steps=301,
)
# Split JMatrix simulator
splitjmatrix_simulator = SplitJMatrixSimulator(
    model.local_hamiltonians,
    model.c_ops_local,
    model.psi0,
    num_qubits=model.num_qubits,
    total_time=0.25,
    time_steps=301,
    num_steps=40,
    circuit_backend=AerCircuitBackend(shots=10000),
)
```

To easily compare results, we initialize a benchmark with a reference simulator
and one or more challengers. All simulators must share the same time grid.
We run the benchmark, which runs the underlying simulations. Split JMatrix only
records counts, so we then apply `model.measurements`, which estimate the same
quantities as the QuTiP `e_ops`: the cavity population on qubits 0 and 1, and the
emitter population on qubit 2. Every model lists measurements that match its
`e_ops` this way. Numeric L∞ / L2 /
MAE / RMSE error metrics vs the reference are available via `error_metrics`.
Wall-clock time, shot budget (when the circuit backend stores `shots`), and
circuit metrics are available via `resource_metrics`. Those metrics are the
depth, qubit width, gate count, T count, and Toffoli count of the final-time
circuit after the backend transpiles it. Each is `N/A` when the backend cannot
report it, including QuTiP and Pauli propagation. Error and resource rows are
exported together by `save_error_metrics` as `{"errors": ..., "resources": ...}`. `save_result_plot` saves a plot per
simulator and an absolute-difference plot vs the reference for each challenger.
The third figure below shows L∞, MAE, and RMSE from `error_metrics`. Those
three share a per-time-point scale.

QuTiP is deterministic. Split JMatrix estimates populations from the finite
`shots` budget on `AerCircuitBackend`, so the comparison moves run to run unless
you set `seed` (wired into Aer’s `seed_simulator`). Residual disagreement also
includes systematic split-J / Trotter bias that does not vanish with more shots.
Use a lower `shots` value on that backend for smoke checks and a higher budget
for publication figures; pass
`verbose=True` or a `progress(step, total)` callback for long-run feedback.
`workers=1` (the default) runs each time point serially. A larger `workers`
value runs those independent points on a process pool; traces stay in `tlist`
order.

```python
benchmark = Benchmark(qutip_simulator, splitjmatrix_simulator)
benchmark.run()
splitjmatrix_simulator.measure(model.measurements)
print(benchmark.error_metrics())
print(benchmark.resource_metrics())
metrics_path = benchmark.save_error_metrics()
paths = benchmark.save_result_plot(labels=["cavity population", "emitter population"])
for path in [metrics_path, *paths]:
    print(f"Saved: {path}")
```

**Output**

*QuTiP (reference):*

![QuTiP expectations](./images/example2_qutip.png)

*Split JMatrix:*

![Split JMatrix expectations](./images/example2_split_jmatrix.png)

*L∞, MAE, and RMSE vs QuTiP:*

![L∞, MAE, and RMSE versus QuTiP](./images/example2_error_metrics.png)

### Example 3: Classical and transverse-field Ising models

[`examples/ising_chain.py`](examples/ising_chain.py) builds Ising Hamiltonians with
the shared factory and evolves a small open transverse-field chain in QuTiP.

```bash
uv run python examples/ising_chain.py
```

```python
from shadowsim.models import ising
from shadowsim.simulators import QutipSimulator

# Transverse-field Ising: H = J Σ Z_i Z_j + h Σ X_i
model = ising(
    n_qubits=4,
    J=1.0,
    h=0.5,
    field="transverse",  # or "classical" for a Z field
    topology="chain",
    boundary="open",  # or "periodic"
)

# Custom connectivity (overrides chain presets)
custom = ising(
    n_qubits=4,
    J=1.0,
    h=0.5,
    field="classical",
    edges=[(0, 1), (1, 2), (2, 3), (0, 2)],
)

simulator = QutipSimulator(
    model.full_hamiltonians,
    model.c_ops_full,  # empty; closed system
    model.psi0,
    model.e_ops,
    num_qubits=model.num_qubits,
    total_time=2.0,
    time_steps=101,
)
result = simulator.simulate()
```

Use `model.hamiltonian` or `model.pauli_sum` when you only need the combined
Hamiltonian (for example with `run_shadow_simulation`). Every ZZ edge and
every single-site field is also available as `model.local_hamiltonians`. A
long-range edge, including the periodic wrap, is a two-site term on its
endpoints.

### Example 4: Encoding classical data as an initial state

[`examples/state_encoding.py`](examples/state_encoding.py) prepares computational-basis, angle, and amplitude states, then evolves the amplitude state with QuTiP.

```bash
uv run python examples/state_encoding.py
```

### Example 5: Coupled oscillators on a smaller register

[`examples/coupled_oscillators.py`](examples/coupled_oscillators.py) evolves a three-mass
spring network four ways. Newton's equations are the reference. The block
encoding of [Babbush et al.](https://arxiv.org/abs/2303.13012) and the shadow
Hamiltonian of [Somma et al.](https://arxiv.org/abs/2407.21775)
(`change_of_basis`) both have dimension 6 and pad to 3 qubits. The same means
from a truncated Fock-space QuTiP run use cutoff 8, which is 9 qubits. The
script prints the position, momentum, and first-mass kinetic-fraction
deviations, then plots that fraction. It needs the `qutip` and `viz` extras.

```bash
uv run python examples/coupled_oscillators.py
```

## Documentation

- [API / site docs](https://simsaidan.github.io/ShadowSim.py/) (`docs/`; preview with `uv sync --group docs --extra qutip --extra qiskit && uv run mkdocs serve`)
- [Command-line interface](https://simsaidan.github.io/ShadowSim.py/cli/)
- [Contributing](CONTRIBUTING.md)

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, tests, linting,
simulator scaffolding, and pull-request guidelines.

## License

This project is licensed under the MIT License. See `LICENSE` for details.

## Citing

Cite this software with the metadata in [`CITATION.cff`](CITATION.cff). The DOI is added there after the GitHub release mints it. See the [changelog](CHANGELOG.md) for what 1.0.0 keeps stable.

## References

See the [documentation bibliography](https://simsaidan.github.io/ShadowSim.py/references/).
