Skip to content

simulator

Base simulator interface and plotting helpers.

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}"
        ")"
    )