Skip to content

trotterization_simulator

Closed-system Trotterization simulator.

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