Skip to content

run

Build a simulator from a builder-page selection.

RetainedRun dataclass

A finished run the page can save or export without simulating again.

directory holds the measured results in the same layout as a save. document is the posted selection with actions removed. resources and errors are the chart payload records used for an export.

Source code in shadowsim/cli/run.py
@dataclass(frozen=True)
class RetainedRun:
    """A finished run the page can save or export without simulating again.

    ``directory`` holds the measured results in the same layout as a save.
    ``document`` is the posted selection with ``actions`` removed. ``resources``
    and ``errors`` are the chart payload records used for an export.
    """

    directory: Path
    document: dict[str, object]
    resources: list[object]
    errors: list[object] | None = None

RetainedRunMismatch

Bases: ValueError

The posted selection does not match the retained run.

Source code in shadowsim/cli/run.py
class RetainedRunMismatch(ValueError):
    """The posted selection does not match the retained run."""

build_simulator

build_simulator(
    selection: Mapping[str, object], *, simulator: int = 0
) -> Simulator

Build one simulator from a version 1 run document.

selection is the document :func:run_page reads. version must be 1. A missing version fails with version must be 1. Any other version fails with that value in the message. simulator selects an entry of simulators; the default is the first.

Parameters:

  • selection (Mapping[str, object]) –

    total is the shared evolution time. state has id and value. model is id plus arguments, or terms plus qubits. Each simulator has id, arguments, and backend (null, or id plus arguments). state.id is an id from :func:shadowsim.cli.catalog.listed_states. measure has id. model records the factory's e_ops on an observables simulator and applies its measurements on a circuit simulator. The chart names are those measurement labels. An added Hamiltonian also has sites, plus expression for counts. Its measure.id is an id from :func:shadowsim.cli.catalog.listed_measurements. A factory model rejects a catalog id, and an added Hamiltonian rejects model. actions is ignored. The simulator id is an id from :func:shadowsim.simulators.catalog.listed_simulators. A simulator that records observables ignores a missing backend. A circuit simulator's backend is an id from :func:shadowsim.backends.catalog.listed_backends, and one that samples needs a backend with a shot budget. An added Hamiltonian's measure of x, y, or z records that Pauli's expectation on each selected qubit for every simulator. counts evaluates expression (see :class:~shadowsim.simulators.Measurement) on the shot counts of the selected qubits, in sites order. It needs a backend with a shot budget, so an observables simulator and a backend without one reject it. A circuit simulator records counts only; :func:run_page reads them. model is a factory name from :func:shadowsim.models.catalog.listed_models. A non-empty terms list is the model instead: each item has id and matrix, and local terms also have sites. At least one Hamiltonian term is required. Factory arguments use the factory's parameter names. A posted name the factory does not take fails. n_qubits is at most 15. An integer field is an integer of at least the catalog minimum, and a missing field keeps the factory default. A factory that does not take n_qubits must report a qubit count, and that count is at most 15. The other arguments are finite reals or numeric text. A per-emitter value is a scalar or a sequence whose length is n_emitters, or length 1 when the factory has no emitter count. edges is empty, dash pairs such as 0-1, 1-2, or a list of pairs. state.value is the payload for state.id. A basis or Gray code is a string of 0 and 1 whose length is the qubit count, at most 15 characters. Angle is one finite real number per qubit. Amplitude is a non-zero list of finite real numbers, and the padded vector must use the model's qubit count. For an added Hamiltonian, measure.sites lists qubit indexes to measure. Missing sites measures every qubit. A factory measurement already names its qubits. Simulator arguments are the catalog fields for that constructor. time_steps is from 1 to 500. Missing it uses 101 when the constructor records observables and 11 otherwise. num_steps is from 1 to 100 and defaults to 4 when the constructor takes it. trotter_depth is from 1 to 100 and order is 1 or 2; both default to the constructor value. seed is an integer and defaults to 0. A missing field uses that default. A posted name the constructor does not take is ignored. A backend with a shot budget reads shots (1 to 100000) from the backend arguments. A posted time_steps value is checked before the simulator extra is imported. A posted shots value is checked then too when that backend has a shot budget, and also when no backend module can be imported. A gate-list field, such as Aer's basis_gates, is a comma-separated string or a sequence of names. A blank value keeps that backend's own basis. Any other backend field is a non-negative number, and a missing value keeps the catalog default. A simulator with closed_system set rejects Lindblad operators. A missing shot count uses the page budget.

  • simulator (int, default: 0 ) –

    Index of the simulators entry to build. Defaults to the first.

Returns:

  • Simulator –

    A simulator that has not been run.

Raises:

  • ValueError –

    The document cannot run in this slice.

  • ImportError –

    The extra required by the simulator or backend is not installed.

Source code in shadowsim/cli/run.py
def build_simulator(selection: Mapping[str, object], *, simulator: int = 0) -> Simulator:
    """Build one simulator from a version 1 run document.

    ``selection`` is the document :func:`run_page` reads. ``version`` must be 1.
    A missing version fails with ``version must be 1``. Any other version fails
    with that value in the message. ``simulator`` selects an entry of
    ``simulators``; the default is the first.

    Args:
        selection: ``total`` is the shared evolution time. ``state`` has ``id``
            and ``value``. ``model`` is ``id`` plus ``arguments``, or ``terms``
            plus ``qubits``. Each simulator has ``id``, ``arguments``, and
            ``backend`` (null, or ``id`` plus ``arguments``). ``state.id`` is an
            id from :func:`shadowsim.cli.catalog.listed_states`. ``measure`` has
            ``id``. ``model`` records the factory's ``e_ops`` on an observables
            simulator and applies its ``measurements`` on a circuit simulator.
            The chart names are those measurement labels. An added Hamiltonian
            also has ``sites``, plus ``expression`` for ``counts``. Its
            ``measure.id`` is an id from
            :func:`shadowsim.cli.catalog.listed_measurements`. A factory model
            rejects a catalog id, and an added Hamiltonian rejects ``model``.
            ``actions`` is ignored. The simulator ``id`` is
            an id from :func:`shadowsim.simulators.catalog.listed_simulators`.
            A simulator that records observables ignores a missing backend. A
            circuit simulator's ``backend`` is an id from
            :func:`shadowsim.backends.catalog.listed_backends`, and one that
            samples needs a backend with a shot budget. An added Hamiltonian's
            ``measure`` of ``x``, ``y``, or ``z`` records that Pauli's expectation
            on each selected qubit for every simulator. ``counts`` evaluates
            ``expression`` (see :class:`~shadowsim.simulators.Measurement`) on the
            shot counts of the selected qubits, in ``sites`` order. It needs a
            backend with a shot budget, so an observables simulator and a backend
            without one reject it. A circuit simulator records counts only;
            :func:`run_page` reads them.
            ``model`` is a factory name from :func:`shadowsim.models.catalog.listed_models`.
            A non-empty ``terms`` list is the model instead: each item has ``id``
            and ``matrix``, and local terms also have ``sites``. At least one
            Hamiltonian term is required.
            Factory ``arguments`` use the factory's parameter names. A posted
            name the factory does not take fails. ``n_qubits`` is at most 15.
            An integer field is an integer of at least the catalog minimum, and
            a missing field keeps the factory default. A factory that does not
            take ``n_qubits`` must report a qubit count, and that count is at
            most 15. The other arguments are finite reals or numeric text. A
            per-emitter value is a scalar or a sequence whose length is
            ``n_emitters``, or length 1 when the factory has no emitter count.
            ``edges`` is empty, dash pairs such as ``0-1, 1-2``, or a list of
            pairs.
            ``state.value`` is the payload for ``state.id``. A basis or Gray code
            is a string of 0 and 1 whose length is the qubit count, at most 15
            characters. Angle is one finite real number per qubit. Amplitude is
            a non-zero list of finite real numbers, and the padded vector must
            use the model's qubit count. For an added Hamiltonian,
            ``measure.sites`` lists qubit indexes to measure. Missing ``sites``
            measures every qubit. A factory measurement already names its qubits.
            Simulator ``arguments`` are the catalog fields for that constructor.
            ``time_steps`` is from 1 to 500. Missing it uses 101 when the
            constructor records observables and 11 otherwise. ``num_steps`` is
            from 1 to 100 and defaults to 4 when the constructor takes it.
            ``trotter_depth`` is from 1 to 100 and ``order`` is 1 or 2; both
            default to the constructor value. ``seed`` is an integer and
            defaults to 0. A missing field uses that default. A posted name the
            constructor does not take is ignored. A backend with a shot budget
            reads ``shots`` (1 to 100000) from the backend arguments. A posted
            ``time_steps`` value is checked before the simulator extra is
            imported. A posted ``shots`` value is checked then too when that
            backend has a shot budget, and also when no backend module can be
            imported. A gate-list field, such as Aer's ``basis_gates``, is a
            comma-separated string or a sequence of names. A blank value keeps
            that backend's own basis. Any other backend field is a non-negative
            number, and a missing value keeps the catalog default. A simulator
            with ``closed_system`` set rejects Lindblad operators. A missing
            shot count uses the page budget.
        simulator: Index of the ``simulators`` entry to build. Defaults to the first.

    Returns:
        A simulator that has not been run.

    Raises:
        ValueError: The document cannot run in this slice.
        ImportError: The extra required by the simulator or backend is not installed.
    """
    document = _read_document(selection)
    return _build_simulator(document, simulator)

check_page

check_page(
    selection: Mapping[str, object],
    *,
    output_root: Path | None = None,
) -> dict[str, object]

Build a version 1 document and return its qubit count. Do not simulate.

This is the build :func:run_page performs before it evolves the system. One entry builds that simulator. Two or more build every entry and reject a mismatched time grid. Nothing is written. qubits is the first simulator's num_qubits.

Parameters:

  • selection (Mapping[str, object]) –

    The version 1 document described on :func:build_simulator.

  • output_root (Path | None, default: None ) –

    Directory that save and export paths must stay under. None leaves those paths unchanged.

Returns:

  • dict[str, object] –

    qubits, the qubit count of the built model. A factory model also

  • dict[str, object] –

    returns measurements, one label and qubits entry for each

  • dict[str, object] –

    measurement the factory defines.

Raises:

  • ValueError –

    The document cannot run, including an integer field below its minimum, an edge list, or a qubit count above 15, an action id that is not listed, or a save or export path outside output_root.

  • ImportError –

    The extra required by a simulator or backend is not installed.

Source code in shadowsim/cli/run.py
def check_page(selection: Mapping[str, object], *, output_root: Path | None = None) -> dict[str, object]:
    """Build a version 1 document and return its qubit count. Do not simulate.

    This is the build :func:`run_page` performs before it evolves the system.
    One entry builds that simulator. Two or more build every entry and reject a
    mismatched time grid. Nothing is written. ``qubits`` is the first simulator's
    ``num_qubits``.

    Args:
        selection: The version 1 document described on :func:`build_simulator`.
        output_root: Directory that save and export paths must stay under.
            ``None`` leaves those paths unchanged.

    Returns:
        ``qubits``, the qubit count of the built model. A factory model also
        returns ``measurements``, one ``label`` and ``qubits`` entry for each
        measurement the factory defines.

    Raises:
        ValueError: The document cannot run, including an integer field below
            its minimum, an edge list, or a qubit count above 15, an action id
            that is not listed, or a save or export path outside ``output_root``.
        ImportError: The extra required by a simulator or backend is not installed.
    """
    prepared = _prepare_page(selection, output_root=output_root)
    payload: dict[str, object] = {"qubits": prepared.simulators[0].num_qubits}
    if _text(prepared.document.measure.get("id")) == "model":
        model = cast(_FactoryModel, _page_model(prepared.document.model))
        payload["measurements"] = [
            {"label": item.label, "qubits": list(item.qubits)} for item in _model_records(model)[1]
        ]
    return payload

simulation_body

simulation_body(
    selection: Mapping[str, object],
) -> dict[str, object]

Return the posted selection without actions.

Save and export paths do not change the curves. A retained run is matched against this body.

Source code in shadowsim/cli/run.py
def simulation_body(selection: Mapping[str, object]) -> dict[str, object]:
    """Return the posted selection without ``actions``.

    Save and export paths do not change the curves. A retained run is matched
    against this body.
    """
    return {key: value for key, value in selection.items() if key != "actions"}

run_page

run_page(
    selection: Mapping[str, object],
    *,
    output_root: Path | None = None,
    retain_to: Path | None = None,
) -> dict[str, object]

Run every simulator in a version 1 document.

The simulators are built by the same steps as :func:check_page. None of them runs until that build succeeds. One simulators entry is one simulation. Two or more is a benchmark. The first entry is the reference. Any exported simulator may be the reference or a challenger. Every entry must share total and time_steps, because :class:~shadowsim.benchmarking.benchmark.Benchmark compares one time grid. time_steps is read from that entry's arguments. actions lists the ids to run. An id that is not in :func:shadowsim.cli.catalog.listed_actions is an error. save writes each result under save_path, or that action's catalog default when the key is missing. One result is the directory itself. A benchmark writes sim_1, sim_2, and so on inside it. export writes metrics JSON under export_path, or that action's catalog default when the key is missing. A benchmark uses :meth:~shadowsim.benchmarking.benchmark.Benchmark.save_error_metrics. One simulator writes its runtime, shot budget, and circuit metrics with :func:~shadowsim.simulators.result.save_resource_metrics. plot is drawn by the page. The payload names each observable in labels and lists wall time, shot budget, and circuit metrics in resources. Circuit metrics are "N/A" when the backend cannot measure the final-time circuit. A benchmark fills resources from :meth:~shadowsim.benchmarking.benchmark.Benchmark.resource_metrics, and each series names its curves {simulator} · {label}. Save and export both run when both are selected. When output_root is set, save_path and export_path must resolve under that directory. A relative path is resolved from the working directory. When retain_to is set, the measured results are also written there so :func:write_page can save or export them later without simulating again.

Parameters:

  • selection (Mapping[str, object]) –

    The version 1 document described on :func:build_simulator.

  • output_root (Path | None, default: None ) –

    Directory that save and export paths must stay under. None leaves those paths unchanged.

  • retain_to (Path | None, default: None ) –

    Directory that receives a copy of the measured results. None skips that copy.

Source code in shadowsim/cli/run.py
def run_page(
    selection: Mapping[str, object],
    *,
    output_root: Path | None = None,
    retain_to: Path | None = None,
) -> dict[str, object]:
    """Run every simulator in a version 1 document.

    The simulators are built by the same steps as :func:`check_page`. None of
    them runs until that build succeeds. One ``simulators`` entry is one simulation.
    Two or more is a benchmark. The first entry is the reference. Any exported
    simulator may be the reference or a challenger. Every entry must share ``total``
    and ``time_steps``, because :class:`~shadowsim.benchmarking.benchmark.Benchmark`
    compares one time grid. ``time_steps`` is read from that entry's arguments.
    ``actions`` lists the ids to run. An id that is not in
    :func:`shadowsim.cli.catalog.listed_actions` is an error. ``save`` writes each
    result under ``save_path``, or that action's catalog default when the key is
    missing. One result is the directory itself.
    A benchmark writes ``sim_1``, ``sim_2``, and so on inside it. ``export`` writes
    metrics JSON under ``export_path``, or that action's catalog default when
    the key is missing.
    A benchmark uses :meth:`~shadowsim.benchmarking.benchmark.Benchmark.save_error_metrics`.
    One simulator writes its runtime, shot budget, and circuit metrics with
    :func:`~shadowsim.simulators.result.save_resource_metrics`. ``plot`` is drawn by the
    page. The payload names each observable in ``labels`` and lists wall time,
    shot budget, and circuit metrics in ``resources``. Circuit metrics are
    ``"N/A"`` when the backend cannot measure the final-time circuit. A benchmark
    fills ``resources`` from
    :meth:`~shadowsim.benchmarking.benchmark.Benchmark.resource_metrics`, and each
    series names its curves ``{simulator} · {label}``. Save and export both run
    when both are selected. When ``output_root`` is set, ``save_path`` and
    ``export_path`` must resolve under that directory.
    A relative path is resolved from the working directory. When ``retain_to`` is
    set, the measured results are also written there so :func:`write_page` can
    save or export them later without simulating again.

    Args:
        selection: The version 1 document described on :func:`build_simulator`.
        output_root: Directory that save and export paths must stay under.
            ``None`` leaves those paths unchanged.
        retain_to: Directory that receives a copy of the measured results.
            ``None`` skips that copy.
    """
    prepared = _prepare_page(selection, output_root=output_root)
    if prepared.benchmark is not None:
        return _run_benchmark(selection, prepared, prepared.benchmark, retain_to=retain_to)
    simulator = prepared.simulators[0]
    simulator.simulate()
    result = _measured_result(simulator, selection)
    payload = _result_payload(result, simulator, _page_model(prepared.document.model), prepared.document.measure)
    if retain_to is not None:
        _write_results(retain_to, [result])
    saved = _write_results(prepared.directory, [result])
    if saved:
        payload["saved"] = saved
    exported = _export_resources(prepared.export_to, simulator, result.runtime)
    if exported:
        payload["exported"] = exported
    return payload

write_page

write_page(
    selection: Mapping[str, object],
    retained: RetainedRun,
    *,
    output_root: Path | None = None,
) -> dict[str, object]

Write save and export for a retained run. Do not simulate.

selection is the version 1 document, including the Save and Export paths to write. Its simulation fields must match retained.document. The measured results are loaded from retained.directory. Export writes the retained resources and errors records.

Parameters:

  • selection (Mapping[str, object]) –

    The version 1 document described on :func:build_simulator.

  • retained (RetainedRun) –

    The finished run :func:run_page stored under retain_to.

  • output_root (Path | None, default: None ) –

    Directory that save and export paths must stay under. None leaves those paths unchanged.

Returns:

  • dict[str, object] –

    saved and exported paths in the same shape as :func:run_page.

Raises:

  • RetainedRunMismatch –

    The posted simulation does not match retained.

  • ValueError –

    The document cannot write, including an action id that is not listed or a save or export path outside output_root.

  • FileNotFoundError –

    A retained result directory is missing.

Source code in shadowsim/cli/run.py
def write_page(
    selection: Mapping[str, object],
    retained: RetainedRun,
    *,
    output_root: Path | None = None,
) -> dict[str, object]:
    """Write save and export for a retained run. Do not simulate.

    ``selection`` is the version 1 document, including the Save and Export paths
    to write. Its simulation fields must match ``retained.document``. The
    measured results are loaded from ``retained.directory``. Export writes the
    retained ``resources`` and ``errors`` records.

    Args:
        selection: The version 1 document described on :func:`build_simulator`.
        retained: The finished run :func:`run_page` stored under ``retain_to``.
        output_root: Directory that save and export paths must stay under.
            ``None`` leaves those paths unchanged.

    Returns:
        ``saved`` and ``exported`` paths in the same shape as :func:`run_page`.

    Raises:
        RetainedRunMismatch: The posted simulation does not match ``retained``.
        ValueError: The document cannot write, including an action id that is
            not listed or a save or export path outside ``output_root``.
        FileNotFoundError: A retained result directory is missing.
    """
    if simulation_body(selection) != retained.document:
        raise RetainedRunMismatch("the retained run does not match this selection")
    document = _read_document(selection)
    _require_actions(document.action_ids)
    directory = _save_directory(document, output_root)
    export_to = _export_location(document, output_root)
    results = _load_retained_results(retained.directory)
    payload: dict[str, object] = {}
    saved = _write_results(directory, results)
    if saved:
        payload["saved"] = saved
    exported = _export_retained_metrics(export_to, retained.resources, retained.errors)
    if exported:
        payload["exported"] = exported
    return payload