Skip to content

simulators

Quantum simulator implementations.

SimulationJob

Handle for a simulate() call running on a worker thread.

completed_steps and total_steps stay None until the backend reports time points. QuTiP does not report them.

Attributes:

  • status (SimulationStatus) –

    pending, running, succeeded, or failed.

  • completed_steps (int | None) –

    Finished time points, or None if this backend does not report them.

  • total_steps (int | None) –

    Time points this run will report, or None.

Source code in shadowsim/simulators/job.py
class SimulationJob:
    """Handle for a ``simulate()`` call running on a worker thread.

    ``completed_steps`` and ``total_steps`` stay ``None`` until the backend
    reports time points. QuTiP does not report them.

    Attributes:
        status: ``pending``, ``running``, ``succeeded``, or ``failed``.
        completed_steps: Finished time points, or ``None`` if this backend
            does not report them.
        total_steps: Time points this run will report, or ``None``.
    """

    def __init__(self, simulator: "Simulator") -> None:
        """Bind a job to ``simulator`` without starting it."""
        self._simulator = simulator
        self._status = SimulationStatus.PENDING
        self._result: SimulationResult | None = None
        self._error: Exception | None = None
        self._completed_steps: int | None = None
        self._total_steps: int | None = None
        self._thread: threading.Thread | None = None
        self._lock = threading.Lock()

    @property
    def status(self) -> SimulationStatus:
        """Return ``pending``, ``running``, ``succeeded``, or ``failed``."""
        with self._lock:
            return self._status

    @property
    def completed_steps(self) -> int | None:
        """Return how many time points have finished, or ``None``."""
        with self._lock:
            return self._completed_steps

    @property
    def total_steps(self) -> int | None:
        """Return how many time points this run reports, or ``None``."""
        with self._lock:
            return self._total_steps

    def result(self, timeout: float | None = None) -> SimulationResult:
        """Return the simulation result, waiting up to ``timeout`` seconds.

        ``timeout=None`` waits until the job finishes. A finished successful
        job returns its ``SimulationResult``. A failed job raises the
        exception from ``simulate()``.

        Args:
            timeout: Seconds to wait. ``None`` waits until the job finishes.

        Returns:
            The ``SimulationResult`` from ``simulate()``.

        Raises:
            TimeoutError: The job is still pending or running when the wait ends.
            Exception: Whatever ``simulate()`` raised.
        """
        if self.status in _UNFINISHED:
            thread = self._thread
            if thread is not None:
                thread.join(timeout)
        with self._lock:
            if self._status is SimulationStatus.SUCCEEDED:
                result = self._result
                if result is None:
                    raise RuntimeError("simulation succeeded without a result")
                return result
            if self._status is SimulationStatus.FAILED:
                error = self._error
                if error is None:
                    raise RuntimeError("simulation failed without an exception")
                raise error
            raise TimeoutError("simulation is still running")

    def _launch(self) -> None:
        """Start the worker thread."""
        thread = threading.Thread(target=self._run, name="shadowsim-simulation", daemon=False)
        self._thread = thread
        thread.start()

    def _run(self) -> None:
        """Mark the job running and call ``simulate()``."""
        with self._lock:
            self._status = SimulationStatus.RUNNING
        try:
            result = self._simulator.simulate()
        except Exception as exc:
            with self._lock:
                self._error = exc
                self._status = SimulationStatus.FAILED
        else:
            with self._lock:
                self._result = result
                self._status = SimulationStatus.SUCCEEDED

    def _begin_steps(self, total: int) -> None:
        """Record that this run will report ``total`` time points, none finished yet."""
        with self._lock:
            self._completed_steps = 0
            self._total_steps = total

    def _note_completed_step(self, total: int) -> None:
        """Count one finished time point and record ``total``."""
        with self._lock:
            completed = self._completed_steps
            self._completed_steps = 1 if completed is None else completed + 1
            self._total_steps = total

status property

Return pending, running, succeeded, or failed.

completed_steps property

completed_steps: int | None

Return how many time points have finished, or None.

total_steps property

total_steps: int | None

Return how many time points this run reports, or None.

__init__

__init__(simulator: Simulator) -> None

Bind a job to simulator without starting it.

Source code in shadowsim/simulators/job.py
def __init__(self, simulator: "Simulator") -> None:
    """Bind a job to ``simulator`` without starting it."""
    self._simulator = simulator
    self._status = SimulationStatus.PENDING
    self._result: SimulationResult | None = None
    self._error: Exception | None = None
    self._completed_steps: int | None = None
    self._total_steps: int | None = None
    self._thread: threading.Thread | None = None
    self._lock = threading.Lock()

result

result(timeout: float | None = None) -> SimulationResult

Return the simulation result, waiting up to timeout seconds.

timeout=None waits until the job finishes. A finished successful job returns its SimulationResult. A failed job raises the exception from simulate().

Parameters:

  • timeout (float | None, default: None ) –

    Seconds to wait. None waits until the job finishes.

Returns:

Raises:

  • TimeoutError –

    The job is still pending or running when the wait ends.

  • Exception –

    Whatever simulate() raised.

Source code in shadowsim/simulators/job.py
def result(self, timeout: float | None = None) -> SimulationResult:
    """Return the simulation result, waiting up to ``timeout`` seconds.

    ``timeout=None`` waits until the job finishes. A finished successful
    job returns its ``SimulationResult``. A failed job raises the
    exception from ``simulate()``.

    Args:
        timeout: Seconds to wait. ``None`` waits until the job finishes.

    Returns:
        The ``SimulationResult`` from ``simulate()``.

    Raises:
        TimeoutError: The job is still pending or running when the wait ends.
        Exception: Whatever ``simulate()`` raised.
    """
    if self.status in _UNFINISHED:
        thread = self._thread
        if thread is not None:
            thread.join(timeout)
    with self._lock:
        if self._status is SimulationStatus.SUCCEEDED:
            result = self._result
            if result is None:
                raise RuntimeError("simulation succeeded without a result")
            return result
        if self._status is SimulationStatus.FAILED:
            error = self._error
            if error is None:
                raise RuntimeError("simulation failed without an exception")
            raise error
        raise TimeoutError("simulation is still running")

SimulationStatus

Bases: StrEnum

Lifecycle of a :class:SimulationJob.

Source code in shadowsim/simulators/job.py
class SimulationStatus(StrEnum):
    """Lifecycle of a :class:`SimulationJob`."""

    PENDING = "pending"
    RUNNING = "running"
    SUCCEEDED = "succeeded"
    FAILED = "failed"

Measurement dataclass

One number per time point, computed from the shot counts of chosen qubits.

expression may use numbers, parentheses, unary + and -, + - * / **, shots, and counts["01"]. A counts key has one character per entry of qubits, in that order, so with qubits=(2, 0) counts["10"] is the number of shots where qubit 2 read 1 and qubit 0 read 0. A bitstring that was never observed is 0. shots is the total number of shots at that time point. Values are floats, so ** cannot build an unbounded integer.

The counts must come from a run in the basis this expression assumes. A Measurement does not change or check that basis.

An expectation backend has no counts. :func:apply_measurements then reads a one-qubit expression from that qubit's distribution: counts["0"] is (1 + expectation) / 2, counts["1"] is (1 - expectation) / 2, and shots is 1. Dividing by shots gives the infinite-shot value. An expression that uses raw counts without shots reads those probabilities.

Attributes:

  • qubits (tuple[int, ...]) –

    System qubit indexes, in the order a counts key lists them.

  • expression (str) –

    Arithmetic on counts and shots.

  • label (str) –

    Name of the resulting curve. Defaults to expression.

Examples:

Probability that qubits 0 and 1 agree:

from shadowsim.simulators import Measurement

same = Measurement((0, 1), '(counts["00"] + counts["11"]) / shots')
print(same.evaluate({"000": 6, "110": 2, "011": 2}))
0.8
Source code in shadowsim/simulators/reducers.py
@dataclass(frozen=True)
class Measurement:
    """One number per time point, computed from the shot counts of chosen qubits.

    ``expression`` may use numbers, parentheses, unary ``+`` and ``-``,
    ``+ - * / **``, ``shots``, and ``counts["01"]``. A ``counts`` key has one
    character per entry of ``qubits``, in that order, so with ``qubits=(2, 0)``
    ``counts["10"]`` is the number of shots where qubit 2 read 1 and qubit 0 read 0.
    A bitstring that was never observed is 0. ``shots`` is the total number of
    shots at that time point. Values are floats, so ``**`` cannot build an
    unbounded integer.

    The counts must come from a run in the basis this expression assumes. A
    Measurement does not change or check that basis.

    An expectation backend has no counts. :func:`apply_measurements` then reads
    a one-qubit expression from that qubit's distribution: ``counts["0"]`` is
    ``(1 + expectation) / 2``, ``counts["1"]`` is ``(1 - expectation) / 2``, and
    ``shots`` is 1. Dividing by ``shots`` gives the infinite-shot value. An
    expression that uses raw counts without ``shots`` reads those probabilities.

    Attributes:
        qubits: System qubit indexes, in the order a ``counts`` key lists them.
        expression: Arithmetic on ``counts`` and ``shots``.
        label: Name of the resulting curve. Defaults to ``expression``.

    Examples:
        Probability that qubits 0 and 1 agree:

        ```python exec="1" source="above" result="text"
        from shadowsim.simulators import Measurement

        same = Measurement((0, 1), '(counts["00"] + counts["11"]) / shots')
        print(same.evaluate({"000": 6, "110": 2, "011": 2}))
        ```
    """

    qubits: tuple[int, ...]
    expression: str
    label: str = ""
    _tree: ast.expr = field(init=False, repr=False, compare=False)

    def __post_init__(self) -> None:
        """Check ``qubits`` and parse ``expression``.

        Raises:
            ValueError: ``qubits`` is empty, repeats an index, or holds something
                other than non-negative integers, or ``expression`` is not allowed.
        """
        if isinstance(self.qubits, (str, bytes)) or not isinstance(self.qubits, Sequence):
            raise ValueError("qubits must be a non-empty list of qubit indexes")
        qubits = tuple(self.qubits)
        if not qubits:
            raise ValueError("qubits must be a non-empty list of qubit indexes")
        for qubit in qubits:
            if isinstance(qubit, bool) or not isinstance(qubit, int) or qubit < 0:
                raise ValueError("qubits must be non-negative integer indexes")
        if len(set(qubits)) != len(qubits):
            raise ValueError("qubits must not repeat an index")
        object.__setattr__(self, "qubits", qubits)
        object.__setattr__(self, "_tree", _parse(self.expression, len(qubits)))
        if not self.label:
            object.__setattr__(self, "label", self.expression.strip())

    def evaluate(self, counts: dict[str, int]) -> float:
        """Return this measurement on one time point's counts.

        Args:
            counts: Bitstring to shot count, where bit ``i`` of a key is system qubit ``i``.

        Raises:
            ValueError: A key is too short for ``qubits``, the expression divides
                by zero or overflows, or the result is not a finite real number.
        """
        last = max(self.qubits)
        marginal: dict[str, int] = {}
        for bitstring, shot_count in counts.items():
            if len(bitstring) <= last:
                raise ValueError(f"counts have {len(bitstring)} qubits, but this measurement reads qubit {last}")
            key = "".join(bitstring[qubit] for qubit in self.qubits)
            marginal[key] = marginal.get(key, 0) + shot_count
        try:
            value: object = _value(self._tree, marginal, sum(counts.values()))
        except ZeroDivisionError:
            raise ValueError(f"{self.label} divides by zero") from None
        except OverflowError:
            raise ValueError(f"{self.label} is too large") from None
        if not isinstance(value, float) or not math.isfinite(value):
            raise ValueError(f"{self.label} must be a finite real number")
        return value

__post_init__

__post_init__() -> None

Check qubits and parse expression.

Raises:

  • ValueError –

    qubits is empty, repeats an index, or holds something other than non-negative integers, or expression is not allowed.

Source code in shadowsim/simulators/reducers.py
def __post_init__(self) -> None:
    """Check ``qubits`` and parse ``expression``.

    Raises:
        ValueError: ``qubits`` is empty, repeats an index, or holds something
            other than non-negative integers, or ``expression`` is not allowed.
    """
    if isinstance(self.qubits, (str, bytes)) or not isinstance(self.qubits, Sequence):
        raise ValueError("qubits must be a non-empty list of qubit indexes")
    qubits = tuple(self.qubits)
    if not qubits:
        raise ValueError("qubits must be a non-empty list of qubit indexes")
    for qubit in qubits:
        if isinstance(qubit, bool) or not isinstance(qubit, int) or qubit < 0:
            raise ValueError("qubits must be non-negative integer indexes")
    if len(set(qubits)) != len(qubits):
        raise ValueError("qubits must not repeat an index")
    object.__setattr__(self, "qubits", qubits)
    object.__setattr__(self, "_tree", _parse(self.expression, len(qubits)))
    if not self.label:
        object.__setattr__(self, "label", self.expression.strip())

evaluate

evaluate(counts: dict[str, int]) -> float

Return this measurement on one time point's counts.

Parameters:

  • counts (dict[str, int]) –

    Bitstring to shot count, where bit i of a key is system qubit i.

Raises:

  • ValueError –

    A key is too short for qubits, the expression divides by zero or overflows, or the result is not a finite real number.

Source code in shadowsim/simulators/reducers.py
def evaluate(self, counts: dict[str, int]) -> float:
    """Return this measurement on one time point's counts.

    Args:
        counts: Bitstring to shot count, where bit ``i`` of a key is system qubit ``i``.

    Raises:
        ValueError: A key is too short for ``qubits``, the expression divides
            by zero or overflows, or the result is not a finite real number.
    """
    last = max(self.qubits)
    marginal: dict[str, int] = {}
    for bitstring, shot_count in counts.items():
        if len(bitstring) <= last:
            raise ValueError(f"counts have {len(bitstring)} qubits, but this measurement reads qubit {last}")
        key = "".join(bitstring[qubit] for qubit in self.qubits)
        marginal[key] = marginal.get(key, 0) + shot_count
    try:
        value: object = _value(self._tree, marginal, sum(counts.values()))
    except ZeroDivisionError:
        raise ValueError(f"{self.label} divides by zero") from None
    except OverflowError:
        raise ValueError(f"{self.label} is too large") from None
    if not isinstance(value, float) or not math.isfinite(value):
        raise ValueError(f"{self.label} must be a finite real number")
    return value

SimulationResult dataclass

Outputs from a simulator simulate() / run() call.

Attributes:

  • times (NDArray[float64]) –

    Simulation time grid.

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

    One expectation trajectory per measured observable / group.

  • states (list[ndarray] | None) –

    Optional state trajectory (None when the backend does not store states).

  • seed (int | None) –

    Random seed used for the run, if any.

  • algorithm (str) –

    Backend identifier (typically the simulator id).

  • runtime (float | None) –

    Wall-clock seconds for the simulate() call, if recorded.

  • metadata (dict[str, Any]) –

    Reproducibility and parameter metadata (version, params, …).

  • counts (list[dict[str, int]] | None) –

    One shot-count dict per entry of times (None when the backend does not sample). Bit i of a key is system qubit i.

Source code in shadowsim/simulators/result.py
@dataclass(frozen=True)
class SimulationResult:
    """Outputs from a simulator ``simulate()`` / ``run()`` call.

    Attributes:
        times: Simulation time grid.
        observables: One expectation trajectory per measured observable / group.
        states: Optional state trajectory (``None`` when the backend does not store states).
        seed: Random seed used for the run, if any.
        algorithm: Backend identifier (typically the simulator ``id``).
        runtime: Wall-clock seconds for the ``simulate()`` call, if recorded.
        metadata: Reproducibility and parameter metadata (version, params, …).
        counts: One shot-count dict per entry of ``times`` (``None`` when the
            backend does not sample). Bit ``i`` of a key is system qubit ``i``.
    """

    times: npt.NDArray[np.float64]
    observables: list[npt.NDArray[np.float64]]
    states: list[np.ndarray] | None = None
    seed: int | None = None
    algorithm: str = ""
    runtime: float | None = None
    metadata: dict[str, Any] = field(default_factory=dict)
    counts: list[dict[str, int]] | None = None

    def save(self, path: str | Path) -> Path:
        """Write this result to a directory as numeric arrays plus ``meta.json``.

        Layout::

            path/
              times.npy
              observables.npz
              states.npz   # only when ``states`` is not None
              counts.json  # only when ``counts`` is not None
              meta.json

        Traces and states keep their shapes, including jagged traces. Archives
        contain only numeric arrays, so ``load`` can read them with
        ``allow_pickle=False``.
        """
        out = Path(path)
        out.mkdir(parents=True, exist_ok=True)
        np.save(out / "times.npy", np.asarray(self.times))
        _write_archive(out / "observables.npz", [_as_float_array(obs) for obs in self.observables])
        states_path = out / "states.npz"
        if self.states is None:
            states_path.unlink(missing_ok=True)
        else:
            _write_archive(states_path, self.states)
        counts_path = out / "counts.json"
        if self.counts is None:
            counts_path.unlink(missing_ok=True)
        else:
            counts_path.write_text(json.dumps(self.counts, sort_keys=True) + "\n", encoding="utf-8")
        # Drop the previous object-array files so a re-save cannot be loaded as a pickle.
        (out / "observables.npy").unlink(missing_ok=True)
        (out / "states.npy").unlink(missing_ok=True)
        meta = {
            "seed": self.seed,
            "algorithm": self.algorithm,
            "runtime": self.runtime,
            "metadata": self.metadata,
            "has_states": self.states is not None,
            "has_counts": self.counts is not None,
        }
        (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) -> "SimulationResult":
        """Reload a result previously written by ``save``.

        Array files are read with ``allow_pickle=False``. A numeric
        ``observables.npy`` from an older save still loads. Object-dtype arrays
        and other pickle payloads are rejected and not executed. ``states.npy``
        from an older save is refused, because that file was an object array.
        """
        root = Path(path)
        if not root.is_dir():
            raise FileNotFoundError(f"SimulationResult directory not found: {root}")
        meta_path = root / "meta.json"
        if not meta_path.is_file():
            raise FileNotFoundError(f"missing meta.json in {root}")
        meta = json.loads(meta_path.read_text(encoding="utf-8"))
        times = _read_npy(root / "times.npy")
        observables = _load_observables(root)
        states: list[np.ndarray] | None = None
        if meta.get("has_states", False):
            states = _load_states(root)
        counts: list[dict[str, int]] | None = None
        if meta.get("has_counts", False):
            counts = _load_counts(root)
        return cls(
            times=times,
            observables=observables,
            states=states,
            seed=meta.get("seed"),
            algorithm=str(meta.get("algorithm", "")),
            runtime=meta.get("runtime"),
            metadata=dict(meta.get("metadata") or {}),
            counts=counts,
        )

save

save(path: str | Path) -> Path

Write this result to a directory as numeric arrays plus meta.json.

Layout::

path/
  times.npy
  observables.npz
  states.npz   # only when ``states`` is not None
  counts.json  # only when ``counts`` is not None
  meta.json

Traces and states keep their shapes, including jagged traces. Archives contain only numeric arrays, so load can read them with allow_pickle=False.

Source code in shadowsim/simulators/result.py
def save(self, path: str | Path) -> Path:
    """Write this result to a directory as numeric arrays plus ``meta.json``.

    Layout::

        path/
          times.npy
          observables.npz
          states.npz   # only when ``states`` is not None
          counts.json  # only when ``counts`` is not None
          meta.json

    Traces and states keep their shapes, including jagged traces. Archives
    contain only numeric arrays, so ``load`` can read them with
    ``allow_pickle=False``.
    """
    out = Path(path)
    out.mkdir(parents=True, exist_ok=True)
    np.save(out / "times.npy", np.asarray(self.times))
    _write_archive(out / "observables.npz", [_as_float_array(obs) for obs in self.observables])
    states_path = out / "states.npz"
    if self.states is None:
        states_path.unlink(missing_ok=True)
    else:
        _write_archive(states_path, self.states)
    counts_path = out / "counts.json"
    if self.counts is None:
        counts_path.unlink(missing_ok=True)
    else:
        counts_path.write_text(json.dumps(self.counts, sort_keys=True) + "\n", encoding="utf-8")
    # Drop the previous object-array files so a re-save cannot be loaded as a pickle.
    (out / "observables.npy").unlink(missing_ok=True)
    (out / "states.npy").unlink(missing_ok=True)
    meta = {
        "seed": self.seed,
        "algorithm": self.algorithm,
        "runtime": self.runtime,
        "metadata": self.metadata,
        "has_states": self.states is not None,
        "has_counts": self.counts is not None,
    }
    (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) -> SimulationResult

Reload a result previously written by save.

Array files are read with allow_pickle=False. A numeric observables.npy from an older save still loads. Object-dtype arrays and other pickle payloads are rejected and not executed. states.npy from an older save is refused, because that file was an object array.

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

    Array files are read with ``allow_pickle=False``. A numeric
    ``observables.npy`` from an older save still loads. Object-dtype arrays
    and other pickle payloads are rejected and not executed. ``states.npy``
    from an older save is refused, because that file was an object array.
    """
    root = Path(path)
    if not root.is_dir():
        raise FileNotFoundError(f"SimulationResult directory not found: {root}")
    meta_path = root / "meta.json"
    if not meta_path.is_file():
        raise FileNotFoundError(f"missing meta.json in {root}")
    meta = json.loads(meta_path.read_text(encoding="utf-8"))
    times = _read_npy(root / "times.npy")
    observables = _load_observables(root)
    states: list[np.ndarray] | None = None
    if meta.get("has_states", False):
        states = _load_states(root)
    counts: list[dict[str, int]] | None = None
    if meta.get("has_counts", False):
        counts = _load_counts(root)
    return cls(
        times=times,
        observables=observables,
        states=states,
        seed=meta.get("seed"),
        algorithm=str(meta.get("algorithm", "")),
        runtime=meta.get("runtime"),
        metadata=dict(meta.get("metadata") or {}),
        counts=counts,
    )

Simulator

Base class for quantum simulation backends.

Source code in shadowsim/simulators/simulator.py
class Simulator:
    """Base class for quantum simulation backends."""

    def __init__(
        self,
        hamiltonians: Sequence[Hamiltonian],
        lindblads: Sequence[Operator],
        initial_state: State,
        *,
        num_qubits: int,
        total_time: float,
        time_steps: int,
        id: str,
    ) -> None:
        """Initialize the shared simulator fields and time grid."""
        if not hamiltonians:
            raise ValueError("hamiltonians must be a non-empty list")
        self.hamiltonians = list(hamiltonians)
        self.lindblads = list(lindblads)
        self.initial_state = initial_state
        self.num_qubits = num_qubits
        self.total_time = total_time
        self.time_steps = time_steps
        self.id = id
        self.results: _Traces | None = None
        self.last_result: SimulationResult | None = None
        self._simulated: SimulationResult | None = None
        self.tlist = np.linspace(0, self.total_time, self.time_steps)
        self._active_job: SimulationJob | None = None
        self._job_lock = threading.Lock()

    def run(self) -> SimulationResult:
        """Run the simulation and return its results."""
        return self.simulate()

    def simulate(self) -> SimulationResult:
        """Run the backend-specific simulation."""
        raise NotImplementedError("Subclasses must implement simulate()")

    def start(self) -> SimulationJob:
        """Run ``simulate()`` on a worker thread and return a job handle.

        The handle comes back while that call is still in progress. ``simulate()``
        and ``run()`` stay synchronous and keep their current return values.
        Split J and Trotter record finished time points on ``completed_steps``
        and ``total_steps``. QuTiP leaves both ``None``.

        Returns:
            A job that moves from pending to running, then to succeeded or failed.

        Raises:
            RuntimeError: This simulator already has a pending or running job.
        """
        with self._job_lock:
            active = self._active_job
            if active is not None and active.status in {SimulationStatus.PENDING, SimulationStatus.RUNNING}:
                raise RuntimeError("a simulation is already running")
            job = SimulationJob(self)
            self._active_job = job
            job._launch()
            return job

    def _running_job(self) -> SimulationJob | None:
        """Return the job executing ``simulate()`` right now, if any."""
        job = self._active_job
        if job is not None and job.status is SimulationStatus.RUNNING:
            return job
        return None

    def _begin_step_progress(self, total: int) -> None:
        """Set the running job to zero completed steps out of ``total``.

        No-op when this ``simulate()`` call was not launched by ``start()``.
        """
        job = self._running_job()
        if job is not None:
            job._begin_steps(total)

    def _report_completed_step(self, total: int) -> None:
        """Count one finished time point on the running job.

        No-op when this ``simulate()`` call was not launched by ``start()``,
        so a direct ``simulate()`` leaves any user progress callback unchanged.
        """
        job = self._running_job()
        if job is not None:
            job._note_completed_step(total)

    def _make_result(
        self,
        observables: Sequence[Sequence[float] | np.ndarray],
        *,
        runtime: float | None = None,
        seed: int | None = None,
        states: list[np.ndarray] | None = None,
        counts: list[dict[str, int]] | None = None,
        **extra_meta: Any,
    ) -> SimulationResult:
        """Build a ``SimulationResult``, store it on ``self.last_result``, and return it.

        ``self.results`` remains the low-level list of expectation traces; callers that
        need metadata should use the returned object or ``self.last_result``.
        """
        traces = [np.asarray(curve, dtype=np.float64) for curve in observables]
        metadata: dict[str, Any] = {
            "software_version": package_version(),
            "num_qubits": self.num_qubits,
            "total_time": self.total_time,
            "time_steps": self.time_steps,
            "simulator_id": self.id,
        }
        metadata.update(extra_meta)
        result = SimulationResult(
            times=np.asarray(self.tlist, dtype=np.float64).copy(),
            observables=traces,
            states=states,
            seed=seed,
            algorithm=self.id,
            runtime=runtime,
            metadata=metadata,
            counts=counts,
        )
        self.last_result = result
        self._simulated = result
        return result

    def measure(self, measurements: Sequence[Measurement]) -> SimulationResult:
        """Read ``measurements`` from the last ``simulate()`` and make them the results.

        ``results``, ``last_result``, plots, and benchmarks then show one curve
        per measurement. Each call reads the simulated result again, so a second
        call replaces the first.

        Raises:
            ValueError: Nothing has been simulated yet, or a measurement cannot
                be read from the result (see :func:`apply_measurements`).
        """
        if self._simulated is None:
            raise ValueError("Results are not available. Please run the simulation first.")
        result = apply_measurements(self._simulated, measurements)
        self.results = [curve.copy() for curve in result.observables]
        self.last_result = result
        return result

    @overload
    def get_results(self, index: None = None) -> _Traces: ...

    @overload
    def get_results(self, index: int) -> _Trace: ...

    def get_results(self, index: int | None = None) -> _Traces | _Trace:
        """Return simulation results, optionally for one observable index."""
        if self.results is None:
            raise ValueError("Results are not available. Please run the simulation first.")
        if index is None:
            return self.results
        return self.results[index]

    def plot_results(
        self,
        indices: list[int] | None = None,
        *,
        labels: list[str] | None = None,
        title: str | None = None,
    ) -> None:
        """Plot expectation traces vs time in an interactive window."""
        results = self.results
        if results is None:
            raise ValueError("Results are not available. Please run the simulation first.")
        plt = import_optional("matplotlib.pyplot", extra="viz")
        if indices is None:
            indices = list(range(len(results)))
        for plot_i, index in enumerate(indices):
            curve_label = labels[plot_i] if labels is not None and plot_i < len(labels) else str(index)
            plt.plot(self.tlist, self.get_results(index), label=curve_label)
        if title:
            plt.title(title)
        plt.xlabel("Time")
        plt.ylabel("Expectation")
        plt.legend()
        plt.show()

    def save_result_plot(
        self,
        indices: list[int] | None = None,
        *,
        dpi: float = 150,
        labels: list[str] | None = None,
        title: str | None = None,
        output_dir: str | Path = "results",
    ) -> Path:
        """Plot expectation traces vs `tlist` and save under ``output_dir``.

        Saves as ``{id}_{timestamp}.png`` (``id`` is set per simulator subclass).
        ``output_dir`` defaults to ``results/`` and is created if it does not exist.
        Does not open an interactive window.
        """
        results = self.results
        if results is None:
            raise ValueError("Results are not available. Please run the simulation first.")
        plt = import_optional("matplotlib.pyplot", extra="viz")
        if indices is None:
            indices = list(range(len(results)))
        stamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
        path = Path(output_dir) / f"{self.id}_{stamp}.png"
        path.parent.mkdir(parents=True, exist_ok=True)

        fig, ax = plt.subplots()
        try:
            for plot_i, index in enumerate(indices):
                curve_label = labels[plot_i] if labels is not None and plot_i < len(labels) else str(index)
                ax.plot(
                    self.tlist,
                    self.get_results(index),
                    label=curve_label,
                )
            ax.set_xlabel("Time")
            ax.set_ylabel("Expectation")
            if title:
                ax.set_title(title)
            ax.legend()
            fig.savefig(path, dpi=dpi, bbox_inches="tight")
        finally:
            plt.close(fig)
        return path

    def __str__(self) -> str:
        """Return a string representation of the simulator."""
        return f"{self.__class__.__name__}(id={self.id}, num_qubits={self.num_qubits}, time_steps={self.time_steps})"

    def __repr__(self) -> str:
        """Return a string representation of the simulator."""
        return (
            f"{self.__class__.__name__}("
            f"hamiltonians={self.hamiltonians!r}, "
            f"lindblads={self.lindblads!r}, "
            f"initial_state={self.initial_state!r}, "
            f"num_qubits={self.num_qubits}, "
            f"total_time={self.total_time}, "
            f"time_steps={self.time_steps}, "
            f"id={self.id!r}"
            ")"
        )

__init__

__init__(
    hamiltonians: Sequence[Hamiltonian],
    lindblads: Sequence[Operator],
    initial_state: State,
    *,
    num_qubits: int,
    total_time: float,
    time_steps: int,
    id: str,
) -> None

Initialize the shared simulator fields and time grid.

Source code in shadowsim/simulators/simulator.py
def __init__(
    self,
    hamiltonians: Sequence[Hamiltonian],
    lindblads: Sequence[Operator],
    initial_state: State,
    *,
    num_qubits: int,
    total_time: float,
    time_steps: int,
    id: str,
) -> None:
    """Initialize the shared simulator fields and time grid."""
    if not hamiltonians:
        raise ValueError("hamiltonians must be a non-empty list")
    self.hamiltonians = list(hamiltonians)
    self.lindblads = list(lindblads)
    self.initial_state = initial_state
    self.num_qubits = num_qubits
    self.total_time = total_time
    self.time_steps = time_steps
    self.id = id
    self.results: _Traces | None = None
    self.last_result: SimulationResult | None = None
    self._simulated: SimulationResult | None = None
    self.tlist = np.linspace(0, self.total_time, self.time_steps)
    self._active_job: SimulationJob | None = None
    self._job_lock = threading.Lock()

run

Run the simulation and return its results.

Source code in shadowsim/simulators/simulator.py
def run(self) -> SimulationResult:
    """Run the simulation and return its results."""
    return self.simulate()

simulate

simulate() -> SimulationResult

Run the backend-specific simulation.

Source code in shadowsim/simulators/simulator.py
def simulate(self) -> SimulationResult:
    """Run the backend-specific simulation."""
    raise NotImplementedError("Subclasses must implement simulate()")

start

start() -> SimulationJob

Run simulate() on a worker thread and return a job handle.

The handle comes back while that call is still in progress. simulate() and run() stay synchronous and keep their current return values. Split J and Trotter record finished time points on completed_steps and total_steps. QuTiP leaves both None.

Returns:

  • SimulationJob –

    A job that moves from pending to running, then to succeeded or failed.

Raises:

  • RuntimeError –

    This simulator already has a pending or running job.

Source code in shadowsim/simulators/simulator.py
def start(self) -> SimulationJob:
    """Run ``simulate()`` on a worker thread and return a job handle.

    The handle comes back while that call is still in progress. ``simulate()``
    and ``run()`` stay synchronous and keep their current return values.
    Split J and Trotter record finished time points on ``completed_steps``
    and ``total_steps``. QuTiP leaves both ``None``.

    Returns:
        A job that moves from pending to running, then to succeeded or failed.

    Raises:
        RuntimeError: This simulator already has a pending or running job.
    """
    with self._job_lock:
        active = self._active_job
        if active is not None and active.status in {SimulationStatus.PENDING, SimulationStatus.RUNNING}:
            raise RuntimeError("a simulation is already running")
        job = SimulationJob(self)
        self._active_job = job
        job._launch()
        return job

measure

measure(
    measurements: Sequence[Measurement],
) -> SimulationResult

Read measurements from the last simulate() and make them the results.

results, last_result, plots, and benchmarks then show one curve per measurement. Each call reads the simulated result again, so a second call replaces the first.

Raises:

  • ValueError –

    Nothing has been simulated yet, or a measurement cannot be read from the result (see :func:apply_measurements).

Source code in shadowsim/simulators/simulator.py
def measure(self, measurements: Sequence[Measurement]) -> SimulationResult:
    """Read ``measurements`` from the last ``simulate()`` and make them the results.

    ``results``, ``last_result``, plots, and benchmarks then show one curve
    per measurement. Each call reads the simulated result again, so a second
    call replaces the first.

    Raises:
        ValueError: Nothing has been simulated yet, or a measurement cannot
            be read from the result (see :func:`apply_measurements`).
    """
    if self._simulated is None:
        raise ValueError("Results are not available. Please run the simulation first.")
    result = apply_measurements(self._simulated, measurements)
    self.results = [curve.copy() for curve in result.observables]
    self.last_result = result
    return result

get_results

get_results(index: None = None) -> _Traces
get_results(index: int) -> _Trace
get_results(index: int | None = None) -> _Traces | _Trace

Return simulation results, optionally for one observable index.

Source code in shadowsim/simulators/simulator.py
def get_results(self, index: int | None = None) -> _Traces | _Trace:
    """Return simulation results, optionally for one observable index."""
    if self.results is None:
        raise ValueError("Results are not available. Please run the simulation first.")
    if index is None:
        return self.results
    return self.results[index]

plot_results

plot_results(
    indices: list[int] | None = None,
    *,
    labels: list[str] | None = None,
    title: str | None = None,
) -> None

Plot expectation traces vs time in an interactive window.

Source code in shadowsim/simulators/simulator.py
def plot_results(
    self,
    indices: list[int] | None = None,
    *,
    labels: list[str] | None = None,
    title: str | None = None,
) -> None:
    """Plot expectation traces vs time in an interactive window."""
    results = self.results
    if results is None:
        raise ValueError("Results are not available. Please run the simulation first.")
    plt = import_optional("matplotlib.pyplot", extra="viz")
    if indices is None:
        indices = list(range(len(results)))
    for plot_i, index in enumerate(indices):
        curve_label = labels[plot_i] if labels is not None and plot_i < len(labels) else str(index)
        plt.plot(self.tlist, self.get_results(index), label=curve_label)
    if title:
        plt.title(title)
    plt.xlabel("Time")
    plt.ylabel("Expectation")
    plt.legend()
    plt.show()

save_result_plot

save_result_plot(
    indices: list[int] | None = None,
    *,
    dpi: float = 150,
    labels: list[str] | None = None,
    title: str | None = None,
    output_dir: str | Path = "results",
) -> Path

Plot expectation traces vs tlist and save under output_dir.

Saves as {id}_{timestamp}.png (id is set per simulator subclass). output_dir defaults to results/ and is created if it does not exist. Does not open an interactive window.

Source code in shadowsim/simulators/simulator.py
def save_result_plot(
    self,
    indices: list[int] | None = None,
    *,
    dpi: float = 150,
    labels: list[str] | None = None,
    title: str | None = None,
    output_dir: str | Path = "results",
) -> Path:
    """Plot expectation traces vs `tlist` and save under ``output_dir``.

    Saves as ``{id}_{timestamp}.png`` (``id`` is set per simulator subclass).
    ``output_dir`` defaults to ``results/`` and is created if it does not exist.
    Does not open an interactive window.
    """
    results = self.results
    if results is None:
        raise ValueError("Results are not available. Please run the simulation first.")
    plt = import_optional("matplotlib.pyplot", extra="viz")
    if indices is None:
        indices = list(range(len(results)))
    stamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
    path = Path(output_dir) / f"{self.id}_{stamp}.png"
    path.parent.mkdir(parents=True, exist_ok=True)

    fig, ax = plt.subplots()
    try:
        for plot_i, index in enumerate(indices):
            curve_label = labels[plot_i] if labels is not None and plot_i < len(labels) else str(index)
            ax.plot(
                self.tlist,
                self.get_results(index),
                label=curve_label,
            )
        ax.set_xlabel("Time")
        ax.set_ylabel("Expectation")
        if title:
            ax.set_title(title)
        ax.legend()
        fig.savefig(path, dpi=dpi, bbox_inches="tight")
    finally:
        plt.close(fig)
    return path

__str__

__str__() -> str

Return a string representation of the simulator.

Source code in shadowsim/simulators/simulator.py
def __str__(self) -> str:
    """Return a string representation of the simulator."""
    return f"{self.__class__.__name__}(id={self.id}, num_qubits={self.num_qubits}, time_steps={self.time_steps})"

__repr__

__repr__() -> str

Return a string representation of the simulator.

Source code in shadowsim/simulators/simulator.py
def __repr__(self) -> str:
    """Return a string representation of the simulator."""
    return (
        f"{self.__class__.__name__}("
        f"hamiltonians={self.hamiltonians!r}, "
        f"lindblads={self.lindblads!r}, "
        f"initial_state={self.initial_state!r}, "
        f"num_qubits={self.num_qubits}, "
        f"total_time={self.total_time}, "
        f"time_steps={self.time_steps}, "
        f"id={self.id!r}"
        ")"
    )

HybridWMLSimulator

Bases: ProductFormulaSimulator

Simulate open-system dynamics with hybrid wave-matrix Lindbladization.

Each of the num_steps samples one term. The weight of a Hamiltonian eigenvalue λ is |λ|, and the weight of a Lindblad L is ||L||_F^2. Their sum is c. A sampled eigenvalue prepares its eigenvector on a program register and applies exp(-i sgn(λ) SWAP Δ) on that register and the term's qubits, with Δ = c t / num_steps, then resets the program register. A sampled Lindblad applies exp(-i J_L sqrt(τ)) on one ancilla and the Lindblad's qubits, with τ = c t / (num_steps ||L||_F^2), then resets the ancilla. One seeded sequence is frozen into the circuit and reused for every shot.

Counts come from circuit_backend. Omitting it uses Aer. The shot count is that backend's shots attribute. Before the measurement, each system qubit is rotated into its letter of basis (default all Z). The ancilla and the program register are not measured. Bit i of a counts key is system qubit i. Read those counts with :meth:measure. With workers greater than 1, that backend is pickled into each worker process.

Each time point starts from initial_state. The term sequence and the shot sampler are a pure function of seed and the time index, so workers=1 and a larger pool return the same counts. workers=1 (the default) runs the points serially, in tlist order. progress(index, total) may run in completion order when workers is greater than 1. A job from start() counts each finished time point in completed_steps.

Source code in shadowsim/simulators/hybrid_wml_simulator.py
class HybridWMLSimulator(ProductFormulaSimulator):
    """Simulate open-system dynamics with hybrid wave-matrix Lindbladization.

    Each of the ``num_steps`` samples one term. The weight of a Hamiltonian
    eigenvalue ``λ`` is ``|λ|``, and the weight of a Lindblad ``L`` is
    ``||L||_F^2``. Their sum is ``c``. A sampled eigenvalue prepares its
    eigenvector on a program register and applies ``exp(-i sgn(λ) SWAP Δ)`` on
    that register and the term's qubits, with ``Δ = c t / num_steps``, then
    resets the program register. A sampled Lindblad applies
    ``exp(-i J_L sqrt(τ))`` on one ancilla and the Lindblad's qubits, with
    ``τ = c t / (num_steps ||L||_F^2)``, then resets the ancilla. One seeded
    sequence is frozen into the circuit and reused for every shot.

    Counts come from ``circuit_backend``. Omitting it uses Aer.
    The shot count is that backend's ``shots`` attribute. Before the measurement,
    each system qubit is rotated into its letter of ``basis`` (default all ``Z``).
    The ancilla and the program register are not measured. Bit ``i`` of a counts
    key is system qubit ``i``. Read those counts with :meth:`measure`.
    With ``workers`` greater than 1, that backend is pickled into each worker process.

    Each time point starts from ``initial_state``. The term sequence and the shot
    sampler are a pure function of ``seed`` and the time index, so ``workers=1``
    and a larger pool return the same counts. ``workers=1`` (the default) runs
    the points serially, in ``tlist`` order. ``progress(index, total)`` may run
    in completion order when ``workers`` is greater than 1. A job from ``start()``
    counts each finished time point in ``completed_steps``.
    """

    title: str = "Hybrid WML"
    requires_sampling_backend: bool = True
    sampling_backend_error: str = "Hybrid WML samples a circuit and needs a backend with a shot budget"

    def __init__(
        self,
        hamiltonians: list[LocalHamiltonian],
        lindblads: list[LocalOperator],
        initial_state: State,
        *,
        num_qubits: int,
        total_time: float,
        time_steps: int,
        num_steps: int,
        verbose: bool = False,
        seed: int | None = None,
        progress: ProgressCallback | None = None,
        workers: int = 1,
        circuit_backend: CircuitBackend | None = None,
        basis: str | None = None,
    ) -> None:
        """Initialize a hybrid WML simulator for the given model.

        Raises:
            TypeError: An operator has the wrong type, or ``seed`` or ``workers``
                has the wrong type.
            ValueError: ``workers`` or ``num_steps`` is not positive, ``total_time``
                is negative, ``basis`` is malformed, the backend has no shot budget,
                an operator does not act on the register, or every sampling weight
                is zero.
        """
        super().__init__(
            hamiltonians,
            lindblads,
            initial_state,
            num_qubits=num_qubits,
            total_time=total_time,
            time_steps=time_steps,
            id="hybrid_wml_simulator",
        )
        if self.total_time < 0.0:
            raise ValueError("total_time must be non-negative")
        self._configure_run(
            num_steps=_positive_int("num_steps", num_steps),
            verbose=verbose,
            seed=seed,
            progress=progress,
            workers=workers,
            circuit_backend=circuit_backend,
            basis=basis,
        )
        _prepare(self.hamiltonians, self.lindblads, self.num_qubits)

    def _time_point_call(self, t: float, index: int) -> TimeCall:
        """Return the hybrid WML counts call for time ``t`` at ``index``."""
        hamiltonians = cast(list[LocalHamiltonian], self.hamiltonians)
        lindblads = cast(list[LocalOperator], self.lindblads)
        return (
            _hybrid_wml,
            (
                hamiltonians,
                lindblads,
                self.initial_state,
                self.num_qubits,
                t,
                self.num_steps,
            ),
            {
                "verbose": self.verbose,
                "shots": backend_shots(self.circuit_backend),
                "seed": self.seed,
                "time_index": index,
                "circuit_backend": self.circuit_backend,
                "basis": self.basis,
            },
        )

    def _extra_metadata(self) -> dict[str, Any]:
        """Return the Lindblad count stored on the result."""
        return {"lindblad_count": len(self.lindblads)}

    def metrics_circuit(self) -> Program:
        """Return the program executed at the final time, including measurement."""
        return _hybrid_wml_circuit(
            cast(list[LocalHamiltonian], self.hamiltonians),
            cast(list[LocalOperator], self.lindblads),
            self.initial_state,
            self.num_qubits,
            float(self.tlist[-1]),
            self.num_steps,
            verbose=False,
            seed=self.seed,
            time_index=len(self.tlist) - 1,
            basis=self.basis,
        )

__init__

__init__(
    hamiltonians: list[LocalHamiltonian],
    lindblads: list[LocalOperator],
    initial_state: State,
    *,
    num_qubits: int,
    total_time: float,
    time_steps: int,
    num_steps: int,
    verbose: bool = False,
    seed: int | None = None,
    progress: ProgressCallback | None = None,
    workers: int = 1,
    circuit_backend: CircuitBackend | None = None,
    basis: str | None = None,
) -> None

Initialize a hybrid WML simulator for the given model.

Raises:

  • TypeError –

    An operator has the wrong type, or seed or workers has the wrong type.

  • ValueError –

    workers or num_steps is not positive, total_time is negative, basis is malformed, the backend has no shot budget, an operator does not act on the register, or every sampling weight is zero.

Source code in shadowsim/simulators/hybrid_wml_simulator.py
def __init__(
    self,
    hamiltonians: list[LocalHamiltonian],
    lindblads: list[LocalOperator],
    initial_state: State,
    *,
    num_qubits: int,
    total_time: float,
    time_steps: int,
    num_steps: int,
    verbose: bool = False,
    seed: int | None = None,
    progress: ProgressCallback | None = None,
    workers: int = 1,
    circuit_backend: CircuitBackend | None = None,
    basis: str | None = None,
) -> None:
    """Initialize a hybrid WML simulator for the given model.

    Raises:
        TypeError: An operator has the wrong type, or ``seed`` or ``workers``
            has the wrong type.
        ValueError: ``workers`` or ``num_steps`` is not positive, ``total_time``
            is negative, ``basis`` is malformed, the backend has no shot budget,
            an operator does not act on the register, or every sampling weight
            is zero.
    """
    super().__init__(
        hamiltonians,
        lindblads,
        initial_state,
        num_qubits=num_qubits,
        total_time=total_time,
        time_steps=time_steps,
        id="hybrid_wml_simulator",
    )
    if self.total_time < 0.0:
        raise ValueError("total_time must be non-negative")
    self._configure_run(
        num_steps=_positive_int("num_steps", num_steps),
        verbose=verbose,
        seed=seed,
        progress=progress,
        workers=workers,
        circuit_backend=circuit_backend,
        basis=basis,
    )
    _prepare(self.hamiltonians, self.lindblads, self.num_qubits)

metrics_circuit

metrics_circuit() -> Program

Return the program executed at the final time, including measurement.

Source code in shadowsim/simulators/hybrid_wml_simulator.py
def metrics_circuit(self) -> Program:
    """Return the program executed at the final time, including measurement."""
    return _hybrid_wml_circuit(
        cast(list[LocalHamiltonian], self.hamiltonians),
        cast(list[LocalOperator], self.lindblads),
        self.initial_state,
        self.num_qubits,
        float(self.tlist[-1]),
        self.num_steps,
        verbose=False,
        seed=self.seed,
        time_index=len(self.tlist) - 1,
        basis=self.basis,
    )

QutipSimulator

Bases: Simulator

Simulate open or closed quantum dynamics with QuTiP.

Source code in shadowsim/simulators/qutip_simulator.py
class QutipSimulator(Simulator):
    """Simulate open or closed quantum dynamics with QuTiP."""

    title: str = "QuTiP"

    def __init__(
        self,
        hamiltonians: Sequence[Hamiltonian],
        lindblads: Sequence[Operator],
        initial_state: State,
        observables: OperatorSet | Sequence[Operator],
        *,
        num_qubits: int,
        total_time: float,
        time_steps: int,
    ) -> None:
        """Initialize a QuTiP simulator for the given model."""
        super().__init__(
            hamiltonians,
            lindblads,
            initial_state,
            num_qubits=num_qubits,
            total_time=total_time,
            time_steps=time_steps,
            id="qutip_simulator",
        )
        self.observables = observables

    def simulate(self) -> SimulationResult:
        """Evolve the system with QuTiP and store expectation traces."""
        tlist = self.tlist
        H_q = Qobj(combined_hamiltonian_matrix(self.hamiltonians, self.num_qubits))
        psi0 = to_qutip(self.initial_state)
        e_ops = [to_qutip(op) for op in self.observables]
        c_ops = [to_qutip(op) for op in self.lindblads]
        started = perf_counter()
        # Large energy scales can require more internal integration steps.
        # QuTiP stubs may type ``mesolve`` as ``NoReturn``; avoid marking callers unreachable.
        result = cast(
            Any,
            mesolve(
                H_q,
                psi0,
                tlist,
                c_ops=c_ops,
                e_ops=e_ops,
                options={"nsteps": 100000},
            ),
        )
        runtime = perf_counter() - started
        traces = cast(list[np.ndarray], list(result.expect))
        self.results = traces
        return self._make_result(
            traces,
            runtime=runtime,
            seed=None,
            observable_count=len(self.observables),
            lindblad_count=len(self.lindblads),
        )

    def __str__(self) -> str:
        """Return a string representation of the QutipSimulator."""
        return (
            "QutipSimulator("
            f"num_qubits={self.num_qubits}, "
            f"observable_count={len(self.observables)}, "
            f"time_steps={self.time_steps}"
            ")"
        )

    def __repr__(self) -> str:
        """Return a string representation of the QutipSimulator."""
        return (
            "QutipSimulator("
            f"hamiltonians={self.hamiltonians!r}, "
            f"lindblads={self.lindblads!r}, "
            f"initial_state={self.initial_state!r}, "
            f"observables={self.observables!r}, "
            f"num_qubits={self.num_qubits}, "
            f"total_time={self.total_time}, "
            f"time_steps={self.time_steps}"
            ")"
        )

__init__

__init__(
    hamiltonians: Sequence[Hamiltonian],
    lindblads: Sequence[Operator],
    initial_state: State,
    observables: OperatorSet | Sequence[Operator],
    *,
    num_qubits: int,
    total_time: float,
    time_steps: int,
) -> None

Initialize a QuTiP simulator for the given model.

Source code in shadowsim/simulators/qutip_simulator.py
def __init__(
    self,
    hamiltonians: Sequence[Hamiltonian],
    lindblads: Sequence[Operator],
    initial_state: State,
    observables: OperatorSet | Sequence[Operator],
    *,
    num_qubits: int,
    total_time: float,
    time_steps: int,
) -> None:
    """Initialize a QuTiP simulator for the given model."""
    super().__init__(
        hamiltonians,
        lindblads,
        initial_state,
        num_qubits=num_qubits,
        total_time=total_time,
        time_steps=time_steps,
        id="qutip_simulator",
    )
    self.observables = observables

simulate

simulate() -> SimulationResult

Evolve the system with QuTiP and store expectation traces.

Source code in shadowsim/simulators/qutip_simulator.py
def simulate(self) -> SimulationResult:
    """Evolve the system with QuTiP and store expectation traces."""
    tlist = self.tlist
    H_q = Qobj(combined_hamiltonian_matrix(self.hamiltonians, self.num_qubits))
    psi0 = to_qutip(self.initial_state)
    e_ops = [to_qutip(op) for op in self.observables]
    c_ops = [to_qutip(op) for op in self.lindblads]
    started = perf_counter()
    # Large energy scales can require more internal integration steps.
    # QuTiP stubs may type ``mesolve`` as ``NoReturn``; avoid marking callers unreachable.
    result = cast(
        Any,
        mesolve(
            H_q,
            psi0,
            tlist,
            c_ops=c_ops,
            e_ops=e_ops,
            options={"nsteps": 100000},
        ),
    )
    runtime = perf_counter() - started
    traces = cast(list[np.ndarray], list(result.expect))
    self.results = traces
    return self._make_result(
        traces,
        runtime=runtime,
        seed=None,
        observable_count=len(self.observables),
        lindblad_count=len(self.lindblads),
    )

__str__

__str__() -> str

Return a string representation of the QutipSimulator.

Source code in shadowsim/simulators/qutip_simulator.py
def __str__(self) -> str:
    """Return a string representation of the QutipSimulator."""
    return (
        "QutipSimulator("
        f"num_qubits={self.num_qubits}, "
        f"observable_count={len(self.observables)}, "
        f"time_steps={self.time_steps}"
        ")"
    )

__repr__

__repr__() -> str

Return a string representation of the QutipSimulator.

Source code in shadowsim/simulators/qutip_simulator.py
def __repr__(self) -> str:
    """Return a string representation of the QutipSimulator."""
    return (
        "QutipSimulator("
        f"hamiltonians={self.hamiltonians!r}, "
        f"lindblads={self.lindblads!r}, "
        f"initial_state={self.initial_state!r}, "
        f"observables={self.observables!r}, "
        f"num_qubits={self.num_qubits}, "
        f"total_time={self.total_time}, "
        f"time_steps={self.time_steps}"
        ")"
    )

SplitJMatrixSimulator

Bases: ProductFormulaSimulator

Simulate open-system dynamics with the Split JMatrix method.

Each of the num_steps applies every Lindblad jump once, then trotter_depth Hamiltonian slices. order=1 (the default) applies each local term once per slice of width t / (num_steps * trotter_depth), in list order. order=2 uses one Strang step per slice: half-steps forward, a full step on the last term, then half-steps in reverse. Either order covers coherent time t.

Counts come from circuit_backend. Omitting it uses Aer. The shot count is that backend's shots attribute. Before the measurement, each system qubit is rotated into its letter of basis (default all Z). The result keeps one counts dict per time point, where bit i of a key is system qubit i and the ancilla bit is dropped. Read those counts with :meth:measure. With workers greater than 1, that backend is pickled into each worker process.

Each time point starts from initial_state and uses the same seed. workers=1 (the default) runs those points serially, in tlist order. workers greater than 1 runs one process-pool task per time point. Traces are still returned in tlist order, and progress(index, total) may run in completion order. A job from start() counts each finished time point in completed_steps.

Source code in shadowsim/simulators/splitjmatrix_simulator.py
class SplitJMatrixSimulator(ProductFormulaSimulator):
    """Simulate open-system dynamics with the Split JMatrix method.

    Each of the ``num_steps`` applies every Lindblad jump once, then
    ``trotter_depth`` Hamiltonian slices. ``order=1`` (the default) applies each
    local term once per slice of width ``t / (num_steps * trotter_depth)``, in
    list order. ``order=2`` uses one Strang step per slice: half-steps forward,
    a full step on the last term, then half-steps in reverse. Either order
    covers coherent time ``t``.

    Counts come from ``circuit_backend``. Omitting it uses Aer.
    The shot count is that backend's ``shots`` attribute. Before the measurement,
    each system qubit is rotated into its letter of ``basis`` (default all ``Z``).
    The result keeps one counts dict per time point, where bit ``i`` of a key is
    system qubit ``i`` and the ancilla bit is dropped.
    Read those counts with :meth:`measure`.
    With ``workers`` greater than 1, that backend is pickled into each worker process.

    Each time point starts from ``initial_state`` and uses the same ``seed``.
    ``workers=1`` (the default) runs those points serially, in ``tlist`` order.
    ``workers`` greater than 1 runs one process-pool task per time point.
    Traces are still returned in ``tlist`` order, and ``progress(index, total)``
    may run in completion order. A job from ``start()`` counts each finished
    time point in ``completed_steps``.
    """

    title: str = "Split J"
    requires_sampling_backend: bool = True
    sampling_backend_error: str = "Split JMatrix samples an ancilla circuit and needs a backend with a shot budget"
    counts_skip: int = 1

    def __init__(
        self,
        hamiltonians: List[LocalHamiltonian],
        lindblads: List[LocalOperator],
        initial_state: State,
        *,
        num_qubits: int,
        total_time: float,
        time_steps: int,
        num_steps: int,
        trotter_depth: int = 1,
        order: Literal[1, 2] = 1,
        verbose: bool = False,
        seed: int | None = None,
        progress: ProgressCallback | None = None,
        workers: int = 1,
        circuit_backend: CircuitBackend | None = None,
        basis: str | None = None,
    ) -> None:
        """Initialize a Split JMatrix simulator for the given model."""
        super().__init__(
            hamiltonians,
            lindblads,
            initial_state,
            num_qubits=num_qubits,
            total_time=total_time,
            time_steps=time_steps,
            id="split_jmatrix_simulator",
        )
        for L in self.lindblads:
            if not isinstance(L, LocalOperator):
                raise TypeError(
                    "SplitJMatrixSimulator `lindblads` must be LocalOperator (with "
                    f"`sites` on the register); got {type(L).__name__}."
                )
        self._configure_run(
            num_steps=num_steps,
            trotter_depth=trotter_depth,
            order=order,
            verbose=verbose,
            seed=seed,
            progress=progress,
            workers=workers,
            circuit_backend=circuit_backend,
            basis=basis,
        )

    def _time_point_call(self, t: float, _index: int) -> TimeCall:
        """Return the ancilla-circuit counts call for time ``t``."""
        hamiltonians = cast(list[LocalHamiltonian], self.hamiltonians)
        lindblads = cast(list[LocalOperator], self.lindblads)
        return (
            _split_jmatrix,
            (
                hamiltonians,
                lindblads,
                self.initial_state,
                self.num_qubits,
                t,
                self.num_steps,
                self.trotter_depth,
            ),
            {
                "order": self.order,
                "verbose": self.verbose,
                "shots": backend_shots(self.circuit_backend),
                # Same seed the serial loop passes for this circuit.
                "seed": self.seed,
                "circuit_backend": self.circuit_backend,
                "basis": self.basis,
            },
        )

    def _extra_metadata(self) -> dict[str, Any]:
        """Return the Lindblad count stored on the result."""
        return {"lindblad_count": len(self.lindblads)}

    def metrics_circuit(self) -> Program:
        """Return the program executed at the final time, including measurement."""
        return _split_jmatrix_circuit(
            cast(list[LocalHamiltonian], self.hamiltonians),
            cast(list[LocalOperator], self.lindblads),
            self.initial_state,
            self.num_qubits,
            float(self.tlist[-1]),
            self.num_steps,
            self.trotter_depth,
            order=self.order,
            verbose=False,
            basis=self.basis,
        )

__init__

__init__(
    hamiltonians: List[LocalHamiltonian],
    lindblads: List[LocalOperator],
    initial_state: State,
    *,
    num_qubits: int,
    total_time: float,
    time_steps: int,
    num_steps: int,
    trotter_depth: int = 1,
    order: Literal[1, 2] = 1,
    verbose: bool = False,
    seed: int | None = None,
    progress: ProgressCallback | None = None,
    workers: int = 1,
    circuit_backend: CircuitBackend | None = None,
    basis: str | None = None,
) -> None

Initialize a Split JMatrix simulator for the given model.

Source code in shadowsim/simulators/splitjmatrix_simulator.py
def __init__(
    self,
    hamiltonians: List[LocalHamiltonian],
    lindblads: List[LocalOperator],
    initial_state: State,
    *,
    num_qubits: int,
    total_time: float,
    time_steps: int,
    num_steps: int,
    trotter_depth: int = 1,
    order: Literal[1, 2] = 1,
    verbose: bool = False,
    seed: int | None = None,
    progress: ProgressCallback | None = None,
    workers: int = 1,
    circuit_backend: CircuitBackend | None = None,
    basis: str | None = None,
) -> None:
    """Initialize a Split JMatrix simulator for the given model."""
    super().__init__(
        hamiltonians,
        lindblads,
        initial_state,
        num_qubits=num_qubits,
        total_time=total_time,
        time_steps=time_steps,
        id="split_jmatrix_simulator",
    )
    for L in self.lindblads:
        if not isinstance(L, LocalOperator):
            raise TypeError(
                "SplitJMatrixSimulator `lindblads` must be LocalOperator (with "
                f"`sites` on the register); got {type(L).__name__}."
            )
    self._configure_run(
        num_steps=num_steps,
        trotter_depth=trotter_depth,
        order=order,
        verbose=verbose,
        seed=seed,
        progress=progress,
        workers=workers,
        circuit_backend=circuit_backend,
        basis=basis,
    )

metrics_circuit

metrics_circuit() -> Program

Return the program executed at the final time, including measurement.

Source code in shadowsim/simulators/splitjmatrix_simulator.py
def metrics_circuit(self) -> Program:
    """Return the program executed at the final time, including measurement."""
    return _split_jmatrix_circuit(
        cast(list[LocalHamiltonian], self.hamiltonians),
        cast(list[LocalOperator], self.lindblads),
        self.initial_state,
        self.num_qubits,
        float(self.tlist[-1]),
        self.num_steps,
        self.trotter_depth,
        order=self.order,
        verbose=False,
        basis=self.basis,
    )

TrotterizationSimulator

Bases: ProductFormulaSimulator

Simulate closed-system dynamics with a Trotter product formula.

closed_system is true, so Lindblad operators are rejected. Counts come from circuit_backend when that backend stores shots. Omitting it uses Aer. Before the measurement, each qubit is rotated into its letter of basis (default all Z). The result keeps one counts dict per time point, where bit i of a key is qubit i. Read them with :meth:measure. A backend without a shot budget, such as PauliPropagation, returns the expectation of each qubit's basis letter from the same circuit with the measurement removed, and the result has no counts. :meth:measure reads a one-qubit measurement from that distribution: counts["0"] is (1 + expectation) / 2, counts["1"] is (1 - expectation) / 2, and shots is 1. Dividing by shots gives the infinite-shot value, and an expression that uses raw counts without shots reads those probabilities. Two or more qubits need a sampling backend. The shot count is that backend's shots attribute when it has one. With workers greater than 1, that backend is pickled into each worker process.

order=1 (the default) applies each local term once per slice of width t / (num_steps * trotter_depth), in list order. order=2 uses one Strang step per slice: half-steps forward, a full step on the last term, then half-steps in reverse. trotter_depth is how many slices fit in one time sample, for both orders.

Each time point starts from initial_state and uses the same seed. workers=1 (the default) runs those points serially, in tlist order. workers greater than 1 runs one process-pool task per time point. Traces are still returned in tlist order, and progress(index, total) may run in completion order. A job from start() counts each finished time point in completed_steps.

Source code in shadowsim/simulators/trotterization_simulator.py
class TrotterizationSimulator(ProductFormulaSimulator):
    """Simulate closed-system dynamics with a Trotter product formula.

    ``closed_system`` is true, so Lindblad operators are rejected.
    Counts come from ``circuit_backend`` when that backend stores ``shots``.
    Omitting it uses Aer. Before the measurement, each
    qubit is rotated into its letter of ``basis`` (default all ``Z``). The result
    keeps one counts dict per time point, where bit ``i`` of a key is qubit ``i``.
    Read them with :meth:`measure`. A backend without a shot budget, such as
    PauliPropagation, returns the expectation of each qubit's ``basis`` letter
    from the same circuit with the measurement removed, and the result has no
    counts. :meth:`measure` reads a one-qubit measurement from that distribution:
    ``counts["0"]`` is ``(1 + expectation) / 2``, ``counts["1"]`` is
    ``(1 - expectation) / 2``, and ``shots`` is 1. Dividing by ``shots`` gives
    the infinite-shot value, and an expression that uses raw counts without
    ``shots`` reads those probabilities. Two or more qubits need a sampling backend.
    The shot count is that backend's ``shots`` attribute when it has one.
    With ``workers`` greater than 1, that backend is pickled into each worker process.

    ``order=1`` (the default) applies each local term once per slice of width
    ``t / (num_steps * trotter_depth)``, in list order. ``order=2`` uses one Strang
    step per slice: half-steps forward, a full step on the last term, then half-steps
    in reverse. ``trotter_depth`` is how many slices fit in one time sample, for both
    orders.

    Each time point starts from ``initial_state`` and uses the same ``seed``.
    ``workers=1`` (the default) runs those points serially, in ``tlist`` order.
    ``workers`` greater than 1 runs one process-pool task per time point.
    Traces are still returned in ``tlist`` order, and ``progress(index, total)``
    may run in completion order. A job from ``start()`` counts each finished
    time point in ``completed_steps``.
    """

    title: str = "Trotter"
    closed_system: bool = True

    def __init__(
        self,
        hamiltonians: list[LocalHamiltonian],
        lindblads: Sequence[Operator],
        initial_state: State,
        *,
        num_qubits: int,
        total_time: float,
        time_steps: int,
        num_steps: int,
        trotter_depth: int = 1,
        order: Literal[1, 2] = 1,
        verbose: bool = False,
        seed: int | None = None,
        progress: ProgressCallback | None = None,
        workers: int = 1,
        circuit_backend: CircuitBackend | None = None,
        basis: str | None = None,
    ) -> None:
        """Initialize a closed-system Trotterization simulator for the given model."""
        super().__init__(
            hamiltonians,
            lindblads,
            initial_state,
            num_qubits=num_qubits,
            total_time=total_time,
            time_steps=time_steps,
            id="trotterization_simulator",
        )
        if self.lindblads:
            raise ValueError("TrotterizationSimulator is closed-system only; lindblads must be empty")
        for h in self.hamiltonians:
            if not isinstance(h, LocalHamiltonian):
                raise TypeError(
                    "TrotterizationSimulator `hamiltonians` must be LocalHamiltonian "
                    f"(with `sites` on the register); got {type(h).__name__}."
                )
        if num_steps <= 0:
            raise ValueError("num_steps must be a positive integer")
        self._configure_run(
            num_steps=num_steps,
            trotter_depth=trotter_depth,
            order=order,
            verbose=verbose,
            seed=seed,
            progress=progress,
            workers=workers,
            circuit_backend=circuit_backend,
            basis=basis,
        )

    def _time_point_call(self, t: float, _index: int) -> TimeCall:
        """Return the closed-system counts call for time ``t``."""
        hamiltonians = cast(list[LocalHamiltonian], self.hamiltonians)
        return (
            _trotter_circuit_counts,
            (
                hamiltonians,
                self.initial_state,
                self.num_qubits,
                t,
                self.num_steps,
                self.trotter_depth,
            ),
            {
                "order": self.order,
                "verbose": self.verbose,
                "shots": backend_shots(self.circuit_backend),
                # Same seed the serial loop passes for this circuit.
                "seed": self.seed,
                "circuit_backend": self.circuit_backend,
                "basis": self.basis,
            },
        )

    def _expectation_samples(self, t: float) -> list[float]:
        """Return each qubit's ``basis`` expectation at time ``t`` from a backend without shots."""
        circuit = _trotter_circuit(
            cast(list[LocalHamiltonian], self.hamiltonians),
            self.initial_state,
            self.num_qubits,
            t,
            self.num_steps,
            self.trotter_depth,
            order=self.order,
            verbose=self.verbose,
            basis=self.basis,
        )
        qubits = list(range(self.num_qubits))
        values = self.circuit_backend.z_expectations(circuit, qubits, shots=1, seed=self.seed)
        return [float(value) for value in values]

    def metrics_circuit(self) -> Program:
        """Return the program executed at the final time.

        A sampling backend includes the computational-basis measurement.
        """
        program = _trotter_circuit(
            cast(list[LocalHamiltonian], self.hamiltonians),
            self.initial_state,
            self.num_qubits,
            float(self.tlist[-1]),
            self.num_steps,
            self.trotter_depth,
            order=self.order,
            verbose=False,
            basis=self.basis,
        )
        if not backend_samples(self.circuit_backend):
            return program
        return Program(program.num_qubits, program.num_qubits, (*program.operations, *_measure_all(program.num_qubits)))

__init__

__init__(
    hamiltonians: list[LocalHamiltonian],
    lindblads: Sequence[Operator],
    initial_state: State,
    *,
    num_qubits: int,
    total_time: float,
    time_steps: int,
    num_steps: int,
    trotter_depth: int = 1,
    order: Literal[1, 2] = 1,
    verbose: bool = False,
    seed: int | None = None,
    progress: ProgressCallback | None = None,
    workers: int = 1,
    circuit_backend: CircuitBackend | None = None,
    basis: str | None = None,
) -> None

Initialize a closed-system Trotterization simulator for the given model.

Source code in shadowsim/simulators/trotterization_simulator.py
def __init__(
    self,
    hamiltonians: list[LocalHamiltonian],
    lindblads: Sequence[Operator],
    initial_state: State,
    *,
    num_qubits: int,
    total_time: float,
    time_steps: int,
    num_steps: int,
    trotter_depth: int = 1,
    order: Literal[1, 2] = 1,
    verbose: bool = False,
    seed: int | None = None,
    progress: ProgressCallback | None = None,
    workers: int = 1,
    circuit_backend: CircuitBackend | None = None,
    basis: str | None = None,
) -> None:
    """Initialize a closed-system Trotterization simulator for the given model."""
    super().__init__(
        hamiltonians,
        lindblads,
        initial_state,
        num_qubits=num_qubits,
        total_time=total_time,
        time_steps=time_steps,
        id="trotterization_simulator",
    )
    if self.lindblads:
        raise ValueError("TrotterizationSimulator is closed-system only; lindblads must be empty")
    for h in self.hamiltonians:
        if not isinstance(h, LocalHamiltonian):
            raise TypeError(
                "TrotterizationSimulator `hamiltonians` must be LocalHamiltonian "
                f"(with `sites` on the register); got {type(h).__name__}."
            )
    if num_steps <= 0:
        raise ValueError("num_steps must be a positive integer")
    self._configure_run(
        num_steps=num_steps,
        trotter_depth=trotter_depth,
        order=order,
        verbose=verbose,
        seed=seed,
        progress=progress,
        workers=workers,
        circuit_backend=circuit_backend,
        basis=basis,
    )

metrics_circuit

metrics_circuit() -> Program

Return the program executed at the final time.

A sampling backend includes the computational-basis measurement.

Source code in shadowsim/simulators/trotterization_simulator.py
def metrics_circuit(self) -> Program:
    """Return the program executed at the final time.

    A sampling backend includes the computational-basis measurement.
    """
    program = _trotter_circuit(
        cast(list[LocalHamiltonian], self.hamiltonians),
        self.initial_state,
        self.num_qubits,
        float(self.tlist[-1]),
        self.num_steps,
        self.trotter_depth,
        order=self.order,
        verbose=False,
        basis=self.basis,
    )
    if not backend_samples(self.circuit_backend):
        return program
    return Program(program.num_qubits, program.num_qubits, (*program.operations, *_measure_all(program.num_qubits)))

apply_measurements

apply_measurements(
    result: SimulationResult,
    measurements: Sequence[Measurement],
) -> SimulationResult

Return result with one curve per measurement in place of its observables.

Each curve has one value per entry of result.counts. The metadata gains measurements: the qubits, expression, and label of each one, in order.

Only a sampling backend, such as Aer, records counts. An expectation backend, such as PauliPropagation, returns one Pauli expectation per qubit instead (observable_kind is "qubit_expectations"). A one-qubit measurement is evaluated on that distribution: counts["0"] is (1 + expectation) / 2, counts["1"] is (1 - expectation) / 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.

Raises:

  • ValueError –

    measurements is empty, or a measurement cannot be evaluated on result.

Source code in shadowsim/simulators/reducers.py
def apply_measurements(result: SimulationResult, measurements: Sequence[Measurement]) -> SimulationResult:
    """Return ``result`` with one curve per measurement in place of its observables.

    Each curve has one value per entry of ``result.counts``. The metadata gains
    ``measurements``: the qubits, expression, and label of each one, in order.

    Only a sampling backend, such as Aer, records counts. An expectation backend,
    such as PauliPropagation, returns one Pauli expectation per qubit instead
    (``observable_kind`` is ``"qubit_expectations"``). A one-qubit measurement is
    evaluated on that distribution: ``counts["0"]`` is ``(1 + expectation) / 2``,
    ``counts["1"]`` is ``(1 - expectation) / 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.

    Raises:
        ValueError: ``measurements`` is empty, or a measurement cannot be
            evaluated on ``result``.
    """
    if not measurements:
        raise ValueError("at least one measurement is required")
    if result.counts is None:
        curves = [_from_expectations(result, item) for item in measurements]
    else:
        curves = [
            np.array([item.evaluate(counts) for counts in result.counts], dtype=np.float64) for item in measurements
        ]
    recorded = [
        {"qubits": list(item.qubits), "expression": item.expression, "label": item.label} for item in measurements
    ]
    metadata = {key: value for key, value in result.metadata.items() if key != "observable_kind"}
    return replace(result, observables=curves, metadata={**metadata, "measurements": recorded})

__getattr__

__getattr__(name: str) -> Any

Import an optional simulator the first time it is accessed.

Source code in shadowsim/simulators/__init__.py
def __getattr__(name: str) -> Any:
    """Import an optional simulator the first time it is accessed."""
    try:
        module_name, extra = _EXPORTS[name]
    except KeyError:
        raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None
    if extra is None:
        module = importlib.import_module(module_name)
    else:
        module = import_optional(module_name, extra=extra)
    value = getattr(module, name)
    globals()[name] = value
    return value

__dir__

__dir__() -> list[str]

Return module attributes, including simulators that have not been imported yet.

Source code in shadowsim/simulators/__init__.py
def __dir__() -> list[str]:
    """Return module attributes, including simulators that have not been imported yet."""
    return sorted(set(globals()) | set(_EXPORTS))