Skip to content

result

Structured simulation result with metadata and serialize/reload.

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

package_version

package_version() -> str

Return the installed shadowsim version, or "unknown" if unavailable.

Source code in shadowsim/simulators/result.py
def package_version() -> str:
    """Return the installed ``shadowsim`` version, or ``"unknown"`` if unavailable."""
    try:
        return version("shadowsim")
    except PackageNotFoundError:
        return "unknown"

save_resource_metrics

save_resource_metrics(
    simulator: object,
    wall_time: float | None,
    *,
    path: Path | None = None,
    output_dir: str | Path = "results",
) -> Path

Write one simulator's runtime and shot budget as JSON.

When path is set, that file is written and output_dir is ignored. Otherwise a timestamped resource_metrics_*.json file is written under output_dir (default results/), which is created if it does not exist.

The payload is {"resources": [record]}. Shot fields are None when neither the circuit backend nor the simulator stores an integer shots count. Otherwise num_jobs is len(tlist) and total_shots is shots_per_job * num_jobs. depth, width, gate_count, t_count, and toffoli_count are integers when the backend can measure metrics_circuit. Each is "N/A" when it cannot.

Source code in shadowsim/simulators/result.py
def save_resource_metrics(
    simulator: object,
    wall_time: float | None,
    *,
    path: Path | None = None,
    output_dir: str | Path = "results",
) -> Path:
    """Write one simulator's runtime and shot budget as JSON.

    When ``path`` is set, that file is written and ``output_dir`` is ignored.
    Otherwise a timestamped ``resource_metrics_*.json`` file is written under
    ``output_dir`` (default ``results/``), which is created if it does not exist.

    The payload is ``{"resources": [record]}``. Shot fields are ``None`` when
    neither the circuit backend nor the simulator stores an integer ``shots``
    count. Otherwise ``num_jobs`` is ``len(tlist)`` and ``total_shots`` is
    ``shots_per_job * num_jobs``. ``depth``, ``width``, ``gate_count``,
    ``t_count``, and ``toffoli_count`` are integers when the backend can
    measure ``metrics_circuit``. Each is ``"N/A"`` when it cannot.
    """
    if path is None:
        stamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
        path = Path(output_dir) / f"resource_metrics_{stamp}.json"
    else:
        path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    payload = {"resources": [_resource_record(simulator, wall_time)]}
    path.write_text(json.dumps(payload, indent=2) + "\n")
    return path