Skip to content

backends

Circuit execution backends for shot-based simulators.

AerCircuitBackend

Run a program on Qiskit Aer and return shot counts.

The program is translated to a Qiskit circuit and transpiled for AerSimulator. A set seed is passed as seed_simulator. basis_gates is passed the same way when it is set. z_expectations and x_expectations estimate Pauli expectations from those counts. depth, width, gate_count, t_count, and toffoli_count read that transpiled circuit. A unitary stays one instruction, so t and ccx counts stay zero unless transpilation emits those names.

Attributes:

  • name –

    "aer". Stored on simulation result metadata.

  • shots –

    Shot budget passed to each run_counts call by a simulator.

  • basis_gates –

    Gate names passed to AerSimulator, or None for Aer's own basis.

  • BASIS_GATE_NAMES –

    Gate names basis_gates may contain.

Source code in shadowsim/backends/aer.py
class AerCircuitBackend:
    """Run a program on Qiskit Aer and return shot counts.

    The program is translated to a Qiskit circuit and transpiled for
    ``AerSimulator``. A set ``seed`` is passed as ``seed_simulator``.
    ``basis_gates`` is passed the same way when it is set. ``z_expectations``
    and ``x_expectations`` estimate Pauli expectations from those counts.
    ``depth``, ``width``, ``gate_count``, ``t_count``, and ``toffoli_count``
    read that transpiled circuit. A unitary stays one instruction, so ``t``
    and ``ccx`` counts stay zero unless transpilation emits those names.

    Attributes:
        name: ``"aer"``. Stored on simulation result metadata.
        shots: Shot budget passed to each ``run_counts`` call by a simulator.
        basis_gates: Gate names passed to ``AerSimulator``, or ``None`` for
            Aer's own basis.
        BASIS_GATE_NAMES: Gate names ``basis_gates`` may contain.
    """

    BASIS_GATE_NAMES = _BASIS_GATE_NAMES

    def __init__(self, shots: int = 10000, basis_gates: Sequence[str] | None = None) -> None:
        """Store the shot budget and optional compilation basis.

        Args:
            shots: Number of shots for each circuit. Must be a positive integer.
            basis_gates: Gate names ``transpile`` may use. ``None`` keeps Aer's
                own basis. Names are stripped, lowercased, and de-duplicated.
                Each name must be in ``BASIS_GATE_NAMES``.

        Raises:
            ValueError: ``shots`` is not a positive integer, ``basis_gates`` is
                not a sequence of gate names, the sequence is empty, or a name
                is not a gate Aer can compile into.
        """
        self.name = "aer"
        self.shots = _require_shots(shots)
        self.basis_gates = _basis_gates(basis_gates)

    def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
        """Translate ``program`` to Qiskit, transpile that for Aer, and return counts.

        Args:
            program: Program to execute.
            shots: Number of shots.
            seed: Passed as ``seed_simulator`` when set. Omitted when ``None``.

        Returns:
            Mapping from bitstring to shot count.

        Raises:
            ValueError: ``program`` cannot be compiled into ``basis_gates``.
        """
        return self._run_counts(to_qiskit(program), shots=shots, seed=seed)

    def z_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Estimate ``⟨Z⟩`` on ``qubits`` from computational-basis shots.

        Args:
            program: Program to execute, before the computational-basis measurement.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Number of shots.
            seed: Passed as ``seed_simulator`` when set. Omitted when ``None``.

        Returns:
            One estimate per entry of ``qubits``, each ``(n0 - n1) / shots``.

        Raises:
            ValueError: An index is outside ``program``, or ``program`` cannot be
                compiled into ``basis_gates``.
        """
        return _expectations(self, program, qubits, shots=shots, seed=seed, basis="z")

    def x_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Estimate ``⟨X⟩`` on ``qubits`` by applying Hadamard and then measuring.

        Args:
            program: Program to execute, before the X-basis measurement.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Number of shots.
            seed: Passed as ``seed_simulator`` when set. Omitted when ``None``.

        Returns:
            One estimate per entry of ``qubits``, each ``(n0 - n1) / shots``.

        Raises:
            ValueError: An index is outside ``program``, or ``program`` cannot be
                compiled into ``basis_gates``.
        """
        return _expectations(self, program, qubits, shots=shots, seed=seed, basis="x")

    def depth(self, program: Program) -> int:
        """Return the depth of ``program`` after transpilation for Aer.

        Args:
            program: Program to measure. It is translated and transpiled for this basis.

        Returns:
            Length of the critical path on the transpiled circuit.

        Raises:
            ValueError: ``program`` cannot be compiled into ``basis_gates``.
        """
        return int(self._compiled(program).depth())

    def width(self, program: Program) -> int:
        """Return the qubit count of ``program`` after transpilation for Aer.

        Args:
            program: Program to measure. It is translated and transpiled for this basis.

        Returns:
            Number of qubits on the transpiled circuit. Classical bits are not included.

        Raises:
            ValueError: ``program`` cannot be compiled into ``basis_gates``.
        """
        return int(self._compiled(program).num_qubits)

    def gate_count(self, program: Program) -> int:
        """Return the instruction count of ``program`` after transpilation for Aer.

        Args:
            program: Program to measure. It is translated and transpiled for this basis.

        Returns:
            Total number of instructions on the transpiled circuit, including
            measurements when ``program`` contains them.

        Raises:
            ValueError: ``program`` cannot be compiled into ``basis_gates``.
        """
        return int(self._compiled(program).size())

    def t_count(self, program: Program) -> int:
        """Return the number of ``t`` gates after transpilation for Aer.

        ``tdg`` is not included. A multi-qubit unitary stays one instruction, so
        a program built only from unitaries reports zero.

        Args:
            program: Program to measure. It is translated and transpiled for this basis.

        Returns:
            Count of instructions named ``t``.

        Raises:
            ValueError: ``program`` cannot be compiled into ``basis_gates``.
        """
        return int(self._compiled(program).count_ops().get("t", 0))

    def toffoli_count(self, program: Program) -> int:
        """Return the number of ``ccx`` and ``ccz`` gates after transpilation for Aer.

        A multi-qubit unitary stays one instruction, so a program built only
        from unitaries reports zero.

        Args:
            program: Program to measure. It is translated and transpiled for this basis.

        Returns:
            Sum of ``ccx`` and ``ccz`` instructions.

        Raises:
            ValueError: ``program`` cannot be compiled into ``basis_gates``.
        """
        counts = self._compiled(program).count_ops()
        return int(counts.get("ccx", 0)) + int(counts.get("ccz", 0))

    def _simulator(self, seed: int | None) -> AerSimulator:
        """Return an Aer simulator for this basis and, when set, ``seed``."""
        options: dict[str, object] = {}
        if seed is not None:
            options["seed_simulator"] = seed
        if self.basis_gates is not None:
            options["basis_gates"] = list(self.basis_gates)
        return AerSimulator(**options)

    def _run_counts(self, circuit: QuantumCircuit, *, shots: int, seed: int | None) -> dict[str, int]:
        """Transpile ``circuit`` for Aer and return counts."""
        backend = self._simulator(seed)
        compiled = _transpile(circuit, backend, self.basis_gates)
        job = backend.run(compiled, shots=shots)
        return job.result().get_counts()

    def _compiled(self, program: Program) -> QuantumCircuit:
        """Translate ``program`` and transpile it for this backend's basis."""
        return _transpile(to_qiskit(program), self._simulator(None), self.basis_gates)

__init__

__init__(
    shots: int = 10000,
    basis_gates: Sequence[str] | None = None,
) -> None

Store the shot budget and optional compilation basis.

Parameters:

  • shots (int, default: 10000 ) –

    Number of shots for each circuit. Must be a positive integer.

  • basis_gates (Sequence[str] | None, default: None ) –

    Gate names transpile may use. None keeps Aer's own basis. Names are stripped, lowercased, and de-duplicated. Each name must be in BASIS_GATE_NAMES.

Raises:

  • ValueError –

    shots is not a positive integer, basis_gates is not a sequence of gate names, the sequence is empty, or a name is not a gate Aer can compile into.

Source code in shadowsim/backends/aer.py
def __init__(self, shots: int = 10000, basis_gates: Sequence[str] | None = None) -> None:
    """Store the shot budget and optional compilation basis.

    Args:
        shots: Number of shots for each circuit. Must be a positive integer.
        basis_gates: Gate names ``transpile`` may use. ``None`` keeps Aer's
            own basis. Names are stripped, lowercased, and de-duplicated.
            Each name must be in ``BASIS_GATE_NAMES``.

    Raises:
        ValueError: ``shots`` is not a positive integer, ``basis_gates`` is
            not a sequence of gate names, the sequence is empty, or a name
            is not a gate Aer can compile into.
    """
    self.name = "aer"
    self.shots = _require_shots(shots)
    self.basis_gates = _basis_gates(basis_gates)

run_counts

run_counts(
    program: Program, *, shots: int, seed: int | None
) -> dict[str, int]

Translate program to Qiskit, transpile that for Aer, and return counts.

Parameters:

  • program (Program) –

    Program to execute.

  • shots (int) –

    Number of shots.

  • seed (int | None) –

    Passed as seed_simulator when set. Omitted when None.

Returns:

  • dict[str, int] –

    Mapping from bitstring to shot count.

Raises:

  • ValueError –

    program cannot be compiled into basis_gates.

Source code in shadowsim/backends/aer.py
def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
    """Translate ``program`` to Qiskit, transpile that for Aer, and return counts.

    Args:
        program: Program to execute.
        shots: Number of shots.
        seed: Passed as ``seed_simulator`` when set. Omitted when ``None``.

    Returns:
        Mapping from bitstring to shot count.

    Raises:
        ValueError: ``program`` cannot be compiled into ``basis_gates``.
    """
    return self._run_counts(to_qiskit(program), shots=shots, seed=seed)

z_expectations

z_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Estimate ⟨Z⟩ on qubits from computational-basis shots.

Parameters:

  • program (Program) –

    Program to execute, before the computational-basis measurement.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Number of shots.

  • seed (int | None) –

    Passed as seed_simulator when set. Omitted when None.

Returns:

  • list[float] –

    One estimate per entry of qubits, each (n0 - n1) / shots.

Raises:

  • ValueError –

    An index is outside program, or program cannot be compiled into basis_gates.

Source code in shadowsim/backends/aer.py
def z_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Estimate ``⟨Z⟩`` on ``qubits`` from computational-basis shots.

    Args:
        program: Program to execute, before the computational-basis measurement.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Number of shots.
        seed: Passed as ``seed_simulator`` when set. Omitted when ``None``.

    Returns:
        One estimate per entry of ``qubits``, each ``(n0 - n1) / shots``.

    Raises:
        ValueError: An index is outside ``program``, or ``program`` cannot be
            compiled into ``basis_gates``.
    """
    return _expectations(self, program, qubits, shots=shots, seed=seed, basis="z")

x_expectations

x_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Estimate ⟨X⟩ on qubits by applying Hadamard and then measuring.

Parameters:

  • program (Program) –

    Program to execute, before the X-basis measurement.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Number of shots.

  • seed (int | None) –

    Passed as seed_simulator when set. Omitted when None.

Returns:

  • list[float] –

    One estimate per entry of qubits, each (n0 - n1) / shots.

Raises:

  • ValueError –

    An index is outside program, or program cannot be compiled into basis_gates.

Source code in shadowsim/backends/aer.py
def x_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Estimate ``⟨X⟩`` on ``qubits`` by applying Hadamard and then measuring.

    Args:
        program: Program to execute, before the X-basis measurement.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Number of shots.
        seed: Passed as ``seed_simulator`` when set. Omitted when ``None``.

    Returns:
        One estimate per entry of ``qubits``, each ``(n0 - n1) / shots``.

    Raises:
        ValueError: An index is outside ``program``, or ``program`` cannot be
            compiled into ``basis_gates``.
    """
    return _expectations(self, program, qubits, shots=shots, seed=seed, basis="x")

depth

depth(program: Program) -> int

Return the depth of program after transpilation for Aer.

Parameters:

  • program (Program) –

    Program to measure. It is translated and transpiled for this basis.

Returns:

  • int –

    Length of the critical path on the transpiled circuit.

Raises:

  • ValueError –

    program cannot be compiled into basis_gates.

Source code in shadowsim/backends/aer.py
def depth(self, program: Program) -> int:
    """Return the depth of ``program`` after transpilation for Aer.

    Args:
        program: Program to measure. It is translated and transpiled for this basis.

    Returns:
        Length of the critical path on the transpiled circuit.

    Raises:
        ValueError: ``program`` cannot be compiled into ``basis_gates``.
    """
    return int(self._compiled(program).depth())

width

width(program: Program) -> int

Return the qubit count of program after transpilation for Aer.

Parameters:

  • program (Program) –

    Program to measure. It is translated and transpiled for this basis.

Returns:

  • int –

    Number of qubits on the transpiled circuit. Classical bits are not included.

Raises:

  • ValueError –

    program cannot be compiled into basis_gates.

Source code in shadowsim/backends/aer.py
def width(self, program: Program) -> int:
    """Return the qubit count of ``program`` after transpilation for Aer.

    Args:
        program: Program to measure. It is translated and transpiled for this basis.

    Returns:
        Number of qubits on the transpiled circuit. Classical bits are not included.

    Raises:
        ValueError: ``program`` cannot be compiled into ``basis_gates``.
    """
    return int(self._compiled(program).num_qubits)

gate_count

gate_count(program: Program) -> int

Return the instruction count of program after transpilation for Aer.

Parameters:

  • program (Program) –

    Program to measure. It is translated and transpiled for this basis.

Returns:

  • int –

    Total number of instructions on the transpiled circuit, including

  • int –

    measurements when program contains them.

Raises:

  • ValueError –

    program cannot be compiled into basis_gates.

Source code in shadowsim/backends/aer.py
def gate_count(self, program: Program) -> int:
    """Return the instruction count of ``program`` after transpilation for Aer.

    Args:
        program: Program to measure. It is translated and transpiled for this basis.

    Returns:
        Total number of instructions on the transpiled circuit, including
        measurements when ``program`` contains them.

    Raises:
        ValueError: ``program`` cannot be compiled into ``basis_gates``.
    """
    return int(self._compiled(program).size())

t_count

t_count(program: Program) -> int

Return the number of t gates after transpilation for Aer.

tdg is not included. A multi-qubit unitary stays one instruction, so a program built only from unitaries reports zero.

Parameters:

  • program (Program) –

    Program to measure. It is translated and transpiled for this basis.

Returns:

  • int –

    Count of instructions named t.

Raises:

  • ValueError –

    program cannot be compiled into basis_gates.

Source code in shadowsim/backends/aer.py
def t_count(self, program: Program) -> int:
    """Return the number of ``t`` gates after transpilation for Aer.

    ``tdg`` is not included. A multi-qubit unitary stays one instruction, so
    a program built only from unitaries reports zero.

    Args:
        program: Program to measure. It is translated and transpiled for this basis.

    Returns:
        Count of instructions named ``t``.

    Raises:
        ValueError: ``program`` cannot be compiled into ``basis_gates``.
    """
    return int(self._compiled(program).count_ops().get("t", 0))

toffoli_count

toffoli_count(program: Program) -> int

Return the number of ccx and ccz gates after transpilation for Aer.

A multi-qubit unitary stays one instruction, so a program built only from unitaries reports zero.

Parameters:

  • program (Program) –

    Program to measure. It is translated and transpiled for this basis.

Returns:

  • int –

    Sum of ccx and ccz instructions.

Raises:

  • ValueError –

    program cannot be compiled into basis_gates.

Source code in shadowsim/backends/aer.py
def toffoli_count(self, program: Program) -> int:
    """Return the number of ``ccx`` and ``ccz`` gates after transpilation for Aer.

    A multi-qubit unitary stays one instruction, so a program built only
    from unitaries reports zero.

    Args:
        program: Program to measure. It is translated and transpiled for this basis.

    Returns:
        Sum of ``ccx`` and ``ccz`` instructions.

    Raises:
        ValueError: ``program`` cannot be compiled into ``basis_gates``.
    """
    counts = self._compiled(program).count_ops()
    return int(counts.get("ccx", 0)) + int(counts.get("ccz", 0))

CircuitBackend

Bases: Protocol

Execute one program and return shot counts or Pauli expectations.

Attributes:

  • name (str) –

    Identifier stored on simulation result metadata.

Source code in shadowsim/backends/circuit.py
class CircuitBackend(Protocol):
    """Execute one program and return shot counts or Pauli expectations.

    Attributes:
        name: Identifier stored on simulation result metadata.
    """

    name: str

    def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
        """Run ``program`` for ``shots`` and return bitstring counts.

        Args:
            program: Program to execute. Implementations compile it for their target.
            shots: Number of shots.
            seed: Optional seed. Implementations use it only when the target accepts one.

        Returns:
            Mapping from bitstring to shot count.
        """
        ...

    def z_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Return ``⟨Z⟩`` for each qubit in ``qubits``.

        Args:
            program: Program to execute, before the computational-basis measurement.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Number of shots used when the backend estimates from counts.
            seed: Optional seed. Implementations use it only when the target accepts one.

        Returns:
            One expectation per entry of ``qubits``.

        Raises:
            ValueError: An index is outside ``program``.
        """
        ...

    def x_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Return ``⟨X⟩`` for each qubit in ``qubits``.

        Args:
            program: Program to execute, before the X-basis measurement.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Number of shots used when the backend estimates from counts.
            seed: Optional seed. Implementations use it only when the target accepts one.

        Returns:
            One expectation per entry of ``qubits``.

        Raises:
            ValueError: An index is outside ``program``.
        """
        ...

    def depth(self, program: Program) -> int:
        """Return the depth of ``program`` after compilation for this backend.

        Args:
            program: Program to measure. Implementations compile it for their target.

        Returns:
            Length of the critical path on the compiled circuit.

        Raises:
            NotImplementedError: This backend does not expose gate counts.
        """
        ...

    def width(self, program: Program) -> int:
        """Return the number of qubits on ``program`` after compilation.

        Args:
            program: Program to measure. Implementations compile it for their target.

        Returns:
            Qubit count of the compiled circuit. Classical bits are not included.

        Raises:
            NotImplementedError: This backend does not expose gate counts.
        """
        ...

    def gate_count(self, program: Program) -> int:
        """Return the instruction count of ``program`` after compilation.

        Args:
            program: Program to measure. Implementations compile it for their target.

        Returns:
            Total number of instructions on the compiled circuit, including
            measurements when ``program`` contains them.

        Raises:
            NotImplementedError: This backend does not expose gate counts.
        """
        ...

    def t_count(self, program: Program) -> int:
        """Return the number of ``t`` gates on ``program`` after compilation.

        ``tdg`` is not included.

        Args:
            program: Program to measure. Implementations compile it for their target.

        Returns:
            Count of instructions named ``t``.

        Raises:
            NotImplementedError: This backend does not expose gate counts.
        """
        ...

    def toffoli_count(self, program: Program) -> int:
        """Return the number of Toffoli gates on ``program`` after compilation.

        A Toffoli is ``ccx`` or ``ccz``.

        Args:
            program: Program to measure. Implementations compile it for their target.

        Returns:
            Sum of ``ccx`` and ``ccz`` instructions.

        Raises:
            NotImplementedError: This backend does not expose gate counts.
        """
        ...

run_counts

run_counts(
    program: Program, *, shots: int, seed: int | None
) -> dict[str, int]

Run program for shots and return bitstring counts.

Parameters:

  • program (Program) –

    Program to execute. Implementations compile it for their target.

  • shots (int) –

    Number of shots.

  • seed (int | None) –

    Optional seed. Implementations use it only when the target accepts one.

Returns:

  • dict[str, int] –

    Mapping from bitstring to shot count.

Source code in shadowsim/backends/circuit.py
def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
    """Run ``program`` for ``shots`` and return bitstring counts.

    Args:
        program: Program to execute. Implementations compile it for their target.
        shots: Number of shots.
        seed: Optional seed. Implementations use it only when the target accepts one.

    Returns:
        Mapping from bitstring to shot count.
    """
    ...

z_expectations

z_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Return ⟨Z⟩ for each qubit in qubits.

Parameters:

  • program (Program) –

    Program to execute, before the computational-basis measurement.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Number of shots used when the backend estimates from counts.

  • seed (int | None) –

    Optional seed. Implementations use it only when the target accepts one.

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    An index is outside program.

Source code in shadowsim/backends/circuit.py
def z_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Return ``⟨Z⟩`` for each qubit in ``qubits``.

    Args:
        program: Program to execute, before the computational-basis measurement.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Number of shots used when the backend estimates from counts.
        seed: Optional seed. Implementations use it only when the target accepts one.

    Returns:
        One expectation per entry of ``qubits``.

    Raises:
        ValueError: An index is outside ``program``.
    """
    ...

x_expectations

x_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Return ⟨X⟩ for each qubit in qubits.

Parameters:

  • program (Program) –

    Program to execute, before the X-basis measurement.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Number of shots used when the backend estimates from counts.

  • seed (int | None) –

    Optional seed. Implementations use it only when the target accepts one.

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    An index is outside program.

Source code in shadowsim/backends/circuit.py
def x_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Return ``⟨X⟩`` for each qubit in ``qubits``.

    Args:
        program: Program to execute, before the X-basis measurement.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Number of shots used when the backend estimates from counts.
        seed: Optional seed. Implementations use it only when the target accepts one.

    Returns:
        One expectation per entry of ``qubits``.

    Raises:
        ValueError: An index is outside ``program``.
    """
    ...

depth

depth(program: Program) -> int

Return the depth of program after compilation for this backend.

Parameters:

  • program (Program) –

    Program to measure. Implementations compile it for their target.

Returns:

  • int –

    Length of the critical path on the compiled circuit.

Raises:

  • NotImplementedError –

    This backend does not expose gate counts.

Source code in shadowsim/backends/circuit.py
def depth(self, program: Program) -> int:
    """Return the depth of ``program`` after compilation for this backend.

    Args:
        program: Program to measure. Implementations compile it for their target.

    Returns:
        Length of the critical path on the compiled circuit.

    Raises:
        NotImplementedError: This backend does not expose gate counts.
    """
    ...

width

width(program: Program) -> int

Return the number of qubits on program after compilation.

Parameters:

  • program (Program) –

    Program to measure. Implementations compile it for their target.

Returns:

  • int –

    Qubit count of the compiled circuit. Classical bits are not included.

Raises:

  • NotImplementedError –

    This backend does not expose gate counts.

Source code in shadowsim/backends/circuit.py
def width(self, program: Program) -> int:
    """Return the number of qubits on ``program`` after compilation.

    Args:
        program: Program to measure. Implementations compile it for their target.

    Returns:
        Qubit count of the compiled circuit. Classical bits are not included.

    Raises:
        NotImplementedError: This backend does not expose gate counts.
    """
    ...

gate_count

gate_count(program: Program) -> int

Return the instruction count of program after compilation.

Parameters:

  • program (Program) –

    Program to measure. Implementations compile it for their target.

Returns:

  • int –

    Total number of instructions on the compiled circuit, including

  • int –

    measurements when program contains them.

Raises:

  • NotImplementedError –

    This backend does not expose gate counts.

Source code in shadowsim/backends/circuit.py
def gate_count(self, program: Program) -> int:
    """Return the instruction count of ``program`` after compilation.

    Args:
        program: Program to measure. Implementations compile it for their target.

    Returns:
        Total number of instructions on the compiled circuit, including
        measurements when ``program`` contains them.

    Raises:
        NotImplementedError: This backend does not expose gate counts.
    """
    ...

t_count

t_count(program: Program) -> int

Return the number of t gates on program after compilation.

tdg is not included.

Parameters:

  • program (Program) –

    Program to measure. Implementations compile it for their target.

Returns:

  • int –

    Count of instructions named t.

Raises:

  • NotImplementedError –

    This backend does not expose gate counts.

Source code in shadowsim/backends/circuit.py
def t_count(self, program: Program) -> int:
    """Return the number of ``t`` gates on ``program`` after compilation.

    ``tdg`` is not included.

    Args:
        program: Program to measure. Implementations compile it for their target.

    Returns:
        Count of instructions named ``t``.

    Raises:
        NotImplementedError: This backend does not expose gate counts.
    """
    ...

toffoli_count

toffoli_count(program: Program) -> int

Return the number of Toffoli gates on program after compilation.

A Toffoli is ccx or ccz.

Parameters:

  • program (Program) –

    Program to measure. Implementations compile it for their target.

Returns:

  • int –

    Sum of ccx and ccz instructions.

Raises:

  • NotImplementedError –

    This backend does not expose gate counts.

Source code in shadowsim/backends/circuit.py
def toffoli_count(self, program: Program) -> int:
    """Return the number of Toffoli gates on ``program`` after compilation.

    A Toffoli is ``ccx`` or ``ccz``.

    Args:
        program: Program to measure. Implementations compile it for their target.

    Returns:
        Sum of ``ccx`` and ``ccz`` instructions.

    Raises:
        NotImplementedError: This backend does not expose gate counts.
    """
    ...

CirqCircuitBackend

Bases: _UnsupportedCircuitMetrics

Evolve one program with the Cirq statevector simulator.

z_expectations and x_expectations are exact, so shots and seed are accepted and ignored there. run_counts samples the computational-basis distribution, and the same seed repeats those counts. The backend stores no shots attribute, so Trotterization reads the exact expectations.

Reset, a measurement followed by a gate, and state preparation after the register has left |0...0> are rejected. depth, width, gate_count, t_count, and toffoli_count are not available.

Statevectors agree with the NumPy backend to an absolute tolerance of 1e-8. One local Hamiltonian makes the Trotter product exact: that ⟨Z⟩ curve matches cos(2t) to 1e-8. A seeded Hadamard of 4000 shots stays within 0.05 of the NumPy frequencies.

Attributes:

  • name –

    "cirq". Stored on simulation result metadata.

Source code in shadowsim/backends/cirq.py
class CirqCircuitBackend(_UnsupportedCircuitMetrics):
    """Evolve one program with the Cirq statevector simulator.

    ``z_expectations`` and ``x_expectations`` are exact, so ``shots`` and
    ``seed`` are accepted and ignored there. ``run_counts`` samples the
    computational-basis distribution, and the same ``seed`` repeats those
    counts. The backend stores no ``shots`` attribute, so Trotterization reads
    the exact expectations.

    ``Reset``, a measurement followed by a gate, and state preparation after
    the register has left ``|0...0>`` are rejected. ``depth``, ``width``,
    ``gate_count``, ``t_count``, and ``toffoli_count`` are not available.

    Statevectors agree with the NumPy backend to an absolute tolerance of
    ``1e-8``. One local Hamiltonian makes the Trotter product exact: that
    ``⟨Z⟩`` curve matches ``cos(2t)`` to ``1e-8``. A seeded Hadamard of 4000
    shots stays within ``0.05`` of the NumPy frequencies.

    Attributes:
        name: ``"cirq"``. Stored on simulation result metadata.
    """

    def __init__(self) -> None:
        """Record the Cirq backend name."""
        self.name = "cirq"

    def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
        """Sample ``program`` in the computational basis.

        Args:
            program: Program to execute.
            shots: Number of shots.
            seed: Seed for Cirq sampling. ``None`` draws without a fixed seed.

        Returns:
            Mapping from bitstring to shot count. The rightmost character is qubit 0.

        Raises:
            ValueError: ``shots`` is not a positive integer, or the statevector
                probabilities do not sum to 1.
            TypeError: ``seed`` is not an ``int`` or ``None``.
            NotImplementedError: ``program`` resets a qubit, measures a qubit
                and then applies a gate, or prepares a state after leaving
                ``|0...0>``.
            ImportError: The ``cirq`` extra is not installed.
        """
        _require_shots(shots)
        _require_seed(seed)
        state = _state(program)
        return _sample(_cirq(), state, shots=shots, seed=seed)

    def z_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Return exact ``⟨Z⟩`` for each qubit in ``qubits``.

        Args:
            program: Program to execute, before the computational-basis measurement.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Unused. The value is not estimated from shots.
            seed: Unused.

        Returns:
            One expectation per entry of ``qubits``.

        Raises:
            ValueError: An index is outside ``program``.
            NotImplementedError: ``program`` resets a qubit, measures a qubit and
                then applies a gate, or prepares a state after leaving ``|0...0>``.
            ImportError: The ``cirq`` extra is not installed.
        """
        del shots, seed
        return _expectations(program, qubits, "Z")

    def x_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Return exact ``⟨X⟩`` for each qubit in ``qubits``.

        Args:
            program: Program to execute, before the X-basis measurement.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Unused. The value is not estimated from shots.
            seed: Unused.

        Returns:
            One expectation per entry of ``qubits``.

        Raises:
            ValueError: An index is outside ``program``.
            NotImplementedError: ``program`` resets a qubit, measures a qubit and
                then applies a gate, or prepares a state after leaving ``|0...0>``.
            ImportError: The ``cirq`` extra is not installed.
        """
        del shots, seed
        return _expectations(program, qubits, "X")

__init__

__init__() -> None

Record the Cirq backend name.

Source code in shadowsim/backends/cirq.py
def __init__(self) -> None:
    """Record the Cirq backend name."""
    self.name = "cirq"

run_counts

run_counts(
    program: Program, *, shots: int, seed: int | None
) -> dict[str, int]

Sample program in the computational basis.

Parameters:

  • program (Program) –

    Program to execute.

  • shots (int) –

    Number of shots.

  • seed (int | None) –

    Seed for Cirq sampling. None draws without a fixed seed.

Returns:

  • dict[str, int] –

    Mapping from bitstring to shot count. The rightmost character is qubit 0.

Raises:

  • ValueError –

    shots is not a positive integer, or the statevector probabilities do not sum to 1.

  • TypeError –

    seed is not an int or None.

  • NotImplementedError –

    program resets a qubit, measures a qubit and then applies a gate, or prepares a state after leaving |0...0>.

  • ImportError –

    The cirq extra is not installed.

Source code in shadowsim/backends/cirq.py
def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
    """Sample ``program`` in the computational basis.

    Args:
        program: Program to execute.
        shots: Number of shots.
        seed: Seed for Cirq sampling. ``None`` draws without a fixed seed.

    Returns:
        Mapping from bitstring to shot count. The rightmost character is qubit 0.

    Raises:
        ValueError: ``shots`` is not a positive integer, or the statevector
            probabilities do not sum to 1.
        TypeError: ``seed`` is not an ``int`` or ``None``.
        NotImplementedError: ``program`` resets a qubit, measures a qubit
            and then applies a gate, or prepares a state after leaving
            ``|0...0>``.
        ImportError: The ``cirq`` extra is not installed.
    """
    _require_shots(shots)
    _require_seed(seed)
    state = _state(program)
    return _sample(_cirq(), state, shots=shots, seed=seed)

z_expectations

z_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Return exact ⟨Z⟩ for each qubit in qubits.

Parameters:

  • program (Program) –

    Program to execute, before the computational-basis measurement.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Unused. The value is not estimated from shots.

  • seed (int | None) –

    Unused.

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    An index is outside program.

  • NotImplementedError –

    program resets a qubit, measures a qubit and then applies a gate, or prepares a state after leaving |0...0>.

  • ImportError –

    The cirq extra is not installed.

Source code in shadowsim/backends/cirq.py
def z_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Return exact ``⟨Z⟩`` for each qubit in ``qubits``.

    Args:
        program: Program to execute, before the computational-basis measurement.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Unused. The value is not estimated from shots.
        seed: Unused.

    Returns:
        One expectation per entry of ``qubits``.

    Raises:
        ValueError: An index is outside ``program``.
        NotImplementedError: ``program`` resets a qubit, measures a qubit and
            then applies a gate, or prepares a state after leaving ``|0...0>``.
        ImportError: The ``cirq`` extra is not installed.
    """
    del shots, seed
    return _expectations(program, qubits, "Z")

x_expectations

x_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Return exact ⟨X⟩ for each qubit in qubits.

Parameters:

  • program (Program) –

    Program to execute, before the X-basis measurement.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Unused. The value is not estimated from shots.

  • seed (int | None) –

    Unused.

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    An index is outside program.

  • NotImplementedError –

    program resets a qubit, measures a qubit and then applies a gate, or prepares a state after leaving |0...0>.

  • ImportError –

    The cirq extra is not installed.

Source code in shadowsim/backends/cirq.py
def x_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Return exact ``⟨X⟩`` for each qubit in ``qubits``.

    Args:
        program: Program to execute, before the X-basis measurement.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Unused. The value is not estimated from shots.
        seed: Unused.

    Returns:
        One expectation per entry of ``qubits``.

    Raises:
        ValueError: An index is outside ``program``.
        NotImplementedError: ``program`` resets a qubit, measures a qubit and
            then applies a gate, or prepares a state after leaving ``|0...0>``.
        ImportError: The ``cirq`` extra is not installed.
    """
    del shots, seed
    return _expectations(program, qubits, "X")

NumpyCircuitBackend

Bases: _UnsupportedCircuitMetrics

Evolve one program with a NumPy statevector.

This is the reference for small programs. Correctness and readability come before performance. z_expectations and x_expectations are exact, so shots and seed are accepted and ignored there. run_counts samples the computational-basis distribution, and the same seed repeats those counts. The backend stores no shots attribute, so Trotterization reads the exact expectations.

Reset, a measurement followed by a gate, and Prepare after the register has left |0...0> are rejected. depth, width, gate_count, t_count, and toffoli_count are not available.

Checked programs agree with Aer statevector probabilities to an absolute tolerance of 1e-8. One local Hamiltonian makes the Trotter product exact: that ⟨Z⟩ curve matches cos(2t) to 1e-8 and QuTiP to 1e-6. A seeded Hadamard of 4000 shots stays within 0.05 of Aer and of 1/2.

Attributes:

  • name –

    "numpy". Stored on simulation result metadata.

Source code in shadowsim/backends/numpy.py
class NumpyCircuitBackend(_UnsupportedCircuitMetrics):
    """Evolve one program with a NumPy statevector.

    This is the reference for small programs. Correctness and readability come
    before performance. ``z_expectations`` and ``x_expectations`` are exact, so
    ``shots`` and ``seed`` are accepted and ignored there. ``run_counts`` samples
    the computational-basis distribution, and the same ``seed`` repeats those
    counts. The backend stores no ``shots`` attribute, so Trotterization reads
    the exact expectations.

    ``Reset``, a measurement followed by a gate, and ``Prepare`` after the
    register has left ``|0...0>`` are rejected. ``depth``, ``width``,
    ``gate_count``, ``t_count``, and ``toffoli_count`` are not available.

    Checked programs agree with Aer statevector probabilities to an absolute
    tolerance of ``1e-8``. One local Hamiltonian makes the Trotter product
    exact: that ``⟨Z⟩`` curve matches ``cos(2t)`` to ``1e-8`` and QuTiP to
    ``1e-6``. A seeded Hadamard of 4000 shots stays within ``0.05`` of Aer and
    of ``1/2``.

    Attributes:
        name: ``"numpy"``. Stored on simulation result metadata.
    """

    def __init__(self) -> None:
        """Record the NumPy backend name."""
        self.name = "numpy"

    def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
        """Sample ``program`` in the computational basis.

        Args:
            program: Program to execute.
            shots: Number of shots.
            seed: Seed for the NumPy generator. ``None`` draws without a fixed seed.

        Returns:
            Mapping from bitstring to shot count. The rightmost character is qubit 0.

        Raises:
            ValueError: ``shots`` is not a positive integer, or the statevector
                probabilities do not sum to 1.
            TypeError: ``seed`` is not an ``int`` or ``None``.
            NotImplementedError: ``program`` resets a qubit, or measures a qubit
                and then applies a gate.
        """
        return sample_counts(program, shots=shots, seed=seed)

    def z_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Return exact ``⟨Z⟩`` for each qubit in ``qubits``.

        Args:
            program: Program to execute, before the computational-basis measurement.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Unused. The value is not estimated from shots.
            seed: Unused.

        Returns:
            One expectation per entry of ``qubits``.

        Raises:
            ValueError: An index is outside ``program``.
            NotImplementedError: ``program`` resets a qubit, measures a qubit and
                then applies a gate, or prepares a state after leaving ``|0...0>``.
        """
        del shots, seed
        return _expectations(program, qubits, "Z")

    def x_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Return exact ``⟨X⟩`` for each qubit in ``qubits``.

        Args:
            program: Program to execute, before the X-basis measurement.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Unused. The value is not estimated from shots.
            seed: Unused.

        Returns:
            One expectation per entry of ``qubits``.

        Raises:
            ValueError: An index is outside ``program``.
            NotImplementedError: ``program`` resets a qubit, measures a qubit and
                then applies a gate, or prepares a state after leaving ``|0...0>``.
        """
        del shots, seed
        return _expectations(program, qubits, "X")

__init__

__init__() -> None

Record the NumPy backend name.

Source code in shadowsim/backends/numpy.py
def __init__(self) -> None:
    """Record the NumPy backend name."""
    self.name = "numpy"

run_counts

run_counts(
    program: Program, *, shots: int, seed: int | None
) -> dict[str, int]

Sample program in the computational basis.

Parameters:

  • program (Program) –

    Program to execute.

  • shots (int) –

    Number of shots.

  • seed (int | None) –

    Seed for the NumPy generator. None draws without a fixed seed.

Returns:

  • dict[str, int] –

    Mapping from bitstring to shot count. The rightmost character is qubit 0.

Raises:

  • ValueError –

    shots is not a positive integer, or the statevector probabilities do not sum to 1.

  • TypeError –

    seed is not an int or None.

  • NotImplementedError –

    program resets a qubit, or measures a qubit and then applies a gate.

Source code in shadowsim/backends/numpy.py
def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
    """Sample ``program`` in the computational basis.

    Args:
        program: Program to execute.
        shots: Number of shots.
        seed: Seed for the NumPy generator. ``None`` draws without a fixed seed.

    Returns:
        Mapping from bitstring to shot count. The rightmost character is qubit 0.

    Raises:
        ValueError: ``shots`` is not a positive integer, or the statevector
            probabilities do not sum to 1.
        TypeError: ``seed`` is not an ``int`` or ``None``.
        NotImplementedError: ``program`` resets a qubit, or measures a qubit
            and then applies a gate.
    """
    return sample_counts(program, shots=shots, seed=seed)

z_expectations

z_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Return exact ⟨Z⟩ for each qubit in qubits.

Parameters:

  • program (Program) –

    Program to execute, before the computational-basis measurement.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Unused. The value is not estimated from shots.

  • seed (int | None) –

    Unused.

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    An index is outside program.

  • NotImplementedError –

    program resets a qubit, measures a qubit and then applies a gate, or prepares a state after leaving |0...0>.

Source code in shadowsim/backends/numpy.py
def z_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Return exact ``⟨Z⟩`` for each qubit in ``qubits``.

    Args:
        program: Program to execute, before the computational-basis measurement.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Unused. The value is not estimated from shots.
        seed: Unused.

    Returns:
        One expectation per entry of ``qubits``.

    Raises:
        ValueError: An index is outside ``program``.
        NotImplementedError: ``program`` resets a qubit, measures a qubit and
            then applies a gate, or prepares a state after leaving ``|0...0>``.
    """
    del shots, seed
    return _expectations(program, qubits, "Z")

x_expectations

x_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Return exact ⟨X⟩ for each qubit in qubits.

Parameters:

  • program (Program) –

    Program to execute, before the X-basis measurement.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Unused. The value is not estimated from shots.

  • seed (int | None) –

    Unused.

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    An index is outside program.

  • NotImplementedError –

    program resets a qubit, measures a qubit and then applies a gate, or prepares a state after leaving |0...0>.

Source code in shadowsim/backends/numpy.py
def x_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Return exact ``⟨X⟩`` for each qubit in ``qubits``.

    Args:
        program: Program to execute, before the X-basis measurement.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Unused. The value is not estimated from shots.
        seed: Unused.

    Returns:
        One expectation per entry of ``qubits``.

    Raises:
        ValueError: An index is outside ``program``.
        NotImplementedError: ``program`` resets a qubit, measures a qubit and
            then applies a gate, or prepares a state after leaving ``|0...0>``.
    """
    del shots, seed
    return _expectations(program, qubits, "X")

PauliPropagationBackend

Bases: _UnsupportedCircuitMetrics

Propagate one Pauli observable per requested qubit [@rudolph2025pauli].

The program is translated to Qiskit and written as OpenQASM 2 for PauliPropagation.OpenQASMInterface.readqasm. z_expectations and x_expectations return the expectation of Z or X on |0...0> after that circuit. Shot counts are not available.

Attributes:

  • name –

    "pauli_propagation". Stored on simulation result metadata.

  • max_weight –

    Largest Pauli weight kept during propagation. inf keeps every weight.

  • min_abs_coeff –

    Smallest coefficient magnitude kept during propagation.

Source code in shadowsim/backends/pauli_propagation.py
class PauliPropagationBackend(_UnsupportedCircuitMetrics):
    """Propagate one Pauli observable per requested qubit [@rudolph2025pauli].

    The program is translated to Qiskit and written as OpenQASM 2 for
    ``PauliPropagation.OpenQASMInterface.readqasm``. ``z_expectations`` and
    ``x_expectations`` return the expectation of Z or X on ``|0...0>`` after
    that circuit. Shot counts are not available.

    Attributes:
        name: ``"pauli_propagation"``. Stored on simulation result metadata.
        max_weight: Largest Pauli weight kept during propagation. ``inf`` keeps every weight.
        min_abs_coeff: Smallest coefficient magnitude kept during propagation.
    """

    def __init__(self, *, max_weight: float = _MAX_WEIGHT, min_abs_coeff: float = _MIN_ABS_COEFF) -> None:
        """Record the PauliPropagation backend name and truncation settings.

        Args:
            max_weight: Largest Pauli weight kept during propagation. ``inf`` keeps every weight.
            min_abs_coeff: Smallest coefficient magnitude kept during propagation.

        Raises:
            TypeError: A setting is not a real number.
            ValueError: A setting is negative, or ``min_abs_coeff`` is not finite.
        """
        self.name = "pauli_propagation"
        self.max_weight = _nonnegative_real(max_weight, "max_weight", allow_inf=True)
        self.min_abs_coeff = _nonnegative_real(min_abs_coeff, "min_abs_coeff", allow_inf=False)

    def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
        """Reject a request for shot counts.

        Args:
            program: Unused. PauliPropagation does not sample a program.
            shots: Unused.
            seed: Unused.

        Raises:
            NotImplementedError: PauliPropagation does not support shot counts.
        """
        del program, shots, seed
        raise NotImplementedError("PauliPropagation does not support shot counts")

    def z_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Return ``⟨Z⟩`` for each qubit in ``qubits``.

        Truncation uses ``max_weight`` and ``min_abs_coeff`` stored on this backend.

        Args:
            program: Program to propagate, without measurements or resets.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Unused. The value is not estimated from shots.
            seed: Unused.

        Returns:
            One expectation per entry of ``qubits``.

        Raises:
            ValueError: An index is outside ``program``, the Julia package is missing,
                or the program cannot be read.
            ImportError: The ``pauli_propagation`` extra is not installed.
        """
        del shots, seed
        return _expectations(self, program, qubits, "Z")

    def x_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Return ``⟨X⟩`` for each qubit in ``qubits``.

        Truncation uses ``max_weight`` and ``min_abs_coeff`` stored on this backend.

        Args:
            program: Program to propagate, without measurements or resets.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Unused. The value is not estimated from shots.
            seed: Unused.

        Returns:
            One expectation per entry of ``qubits``.

        Raises:
            ValueError: An index is outside ``program``, the Julia package is missing,
                or the program cannot be read.
            ImportError: The ``pauli_propagation`` extra is not installed.
        """
        del shots, seed
        return _expectations(self, program, qubits, "X")

__init__

__init__(
    *,
    max_weight: float = _MAX_WEIGHT,
    min_abs_coeff: float = _MIN_ABS_COEFF,
) -> None

Record the PauliPropagation backend name and truncation settings.

Parameters:

  • max_weight (float, default: _MAX_WEIGHT ) –

    Largest Pauli weight kept during propagation. inf keeps every weight.

  • min_abs_coeff (float, default: _MIN_ABS_COEFF ) –

    Smallest coefficient magnitude kept during propagation.

Raises:

  • TypeError –

    A setting is not a real number.

  • ValueError –

    A setting is negative, or min_abs_coeff is not finite.

Source code in shadowsim/backends/pauli_propagation.py
def __init__(self, *, max_weight: float = _MAX_WEIGHT, min_abs_coeff: float = _MIN_ABS_COEFF) -> None:
    """Record the PauliPropagation backend name and truncation settings.

    Args:
        max_weight: Largest Pauli weight kept during propagation. ``inf`` keeps every weight.
        min_abs_coeff: Smallest coefficient magnitude kept during propagation.

    Raises:
        TypeError: A setting is not a real number.
        ValueError: A setting is negative, or ``min_abs_coeff`` is not finite.
    """
    self.name = "pauli_propagation"
    self.max_weight = _nonnegative_real(max_weight, "max_weight", allow_inf=True)
    self.min_abs_coeff = _nonnegative_real(min_abs_coeff, "min_abs_coeff", allow_inf=False)

run_counts

run_counts(
    program: Program, *, shots: int, seed: int | None
) -> dict[str, int]

Reject a request for shot counts.

Parameters:

  • program (Program) –

    Unused. PauliPropagation does not sample a program.

  • shots (int) –

    Unused.

  • seed (int | None) –

    Unused.

Raises:

  • NotImplementedError –

    PauliPropagation does not support shot counts.

Source code in shadowsim/backends/pauli_propagation.py
def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
    """Reject a request for shot counts.

    Args:
        program: Unused. PauliPropagation does not sample a program.
        shots: Unused.
        seed: Unused.

    Raises:
        NotImplementedError: PauliPropagation does not support shot counts.
    """
    del program, shots, seed
    raise NotImplementedError("PauliPropagation does not support shot counts")

z_expectations

z_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Return ⟨Z⟩ for each qubit in qubits.

Truncation uses max_weight and min_abs_coeff stored on this backend.

Parameters:

  • program (Program) –

    Program to propagate, without measurements or resets.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Unused. The value is not estimated from shots.

  • seed (int | None) –

    Unused.

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    An index is outside program, the Julia package is missing, or the program cannot be read.

  • ImportError –

    The pauli_propagation extra is not installed.

Source code in shadowsim/backends/pauli_propagation.py
def z_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Return ``⟨Z⟩`` for each qubit in ``qubits``.

    Truncation uses ``max_weight`` and ``min_abs_coeff`` stored on this backend.

    Args:
        program: Program to propagate, without measurements or resets.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Unused. The value is not estimated from shots.
        seed: Unused.

    Returns:
        One expectation per entry of ``qubits``.

    Raises:
        ValueError: An index is outside ``program``, the Julia package is missing,
            or the program cannot be read.
        ImportError: The ``pauli_propagation`` extra is not installed.
    """
    del shots, seed
    return _expectations(self, program, qubits, "Z")

x_expectations

x_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Return ⟨X⟩ for each qubit in qubits.

Truncation uses max_weight and min_abs_coeff stored on this backend.

Parameters:

  • program (Program) –

    Program to propagate, without measurements or resets.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Unused. The value is not estimated from shots.

  • seed (int | None) –

    Unused.

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    An index is outside program, the Julia package is missing, or the program cannot be read.

  • ImportError –

    The pauli_propagation extra is not installed.

Source code in shadowsim/backends/pauli_propagation.py
def x_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Return ``⟨X⟩`` for each qubit in ``qubits``.

    Truncation uses ``max_weight`` and ``min_abs_coeff`` stored on this backend.

    Args:
        program: Program to propagate, without measurements or resets.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Unused. The value is not estimated from shots.
        seed: Unused.

    Returns:
        One expectation per entry of ``qubits``.

    Raises:
        ValueError: An index is outside ``program``, the Julia package is missing,
            or the program cannot be read.
        ImportError: The ``pauli_propagation`` extra is not installed.
    """
    del shots, seed
    return _expectations(self, program, qubits, "X")

QulacsCircuitBackend

Bases: _UnsupportedCircuitMetrics

Evolve one program with the Qulacs statevector simulator.

z_expectations and x_expectations are exact, so shots and seed are accepted and ignored there. run_counts samples the computational-basis distribution, and the same seed repeats those counts. The backend stores no shots attribute, so Trotterization reads the exact expectations.

Reset, a measurement followed by a gate, and state preparation after the register has left |0...0> are rejected. depth, width, gate_count, t_count, and toffoli_count are not available.

Statevectors agree with the NumPy backend to an absolute tolerance of 1e-8. One local Hamiltonian makes the Trotter product exact: that ⟨Z⟩ curve matches cos(2t) to 1e-8. A seeded Hadamard of 4000 shots stays within 0.05 of the NumPy frequencies.

Attributes:

  • name –

    "qulacs". Stored on simulation result metadata.

Source code in shadowsim/backends/qulacs.py
class QulacsCircuitBackend(_UnsupportedCircuitMetrics):
    """Evolve one program with the Qulacs statevector simulator.

    ``z_expectations`` and ``x_expectations`` are exact, so ``shots`` and
    ``seed`` are accepted and ignored there. ``run_counts`` samples the
    computational-basis distribution, and the same ``seed`` repeats those
    counts. The backend stores no ``shots`` attribute, so Trotterization reads
    the exact expectations.

    ``Reset``, a measurement followed by a gate, and state preparation after
    the register has left ``|0...0>`` are rejected. ``depth``, ``width``,
    ``gate_count``, ``t_count``, and ``toffoli_count`` are not available.

    Statevectors agree with the NumPy backend to an absolute tolerance of
    ``1e-8``. One local Hamiltonian makes the Trotter product exact: that
    ``⟨Z⟩`` curve matches ``cos(2t)`` to ``1e-8``. A seeded Hadamard of 4000
    shots stays within ``0.05`` of the NumPy frequencies.

    Attributes:
        name: ``"qulacs"``. Stored on simulation result metadata.
    """

    def __init__(self) -> None:
        """Record the Qulacs backend name."""
        self.name = "qulacs"

    def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
        """Sample ``program`` in the computational basis.

        Args:
            program: Program to execute.
            shots: Number of shots.
            seed: Seed for Qulacs sampling. ``None`` draws without a fixed seed.

        Returns:
            Mapping from bitstring to shot count. The rightmost character is qubit 0.

        Raises:
            ValueError: ``shots`` is not a positive integer, or the statevector
                probabilities do not sum to 1.
            TypeError: ``seed`` is not an ``int`` or ``None``.
            NotImplementedError: ``program`` resets a qubit, measures a qubit
                and then applies a gate, or prepares a state after leaving
                ``|0...0>``.
            ImportError: The ``qulacs`` extra is not installed.
        """
        _require_shots(shots)
        _require_seed(seed)
        state = _state(program)
        _check_normalized(state)
        if seed is None:
            outcomes = state.sampling(shots)
        else:
            outcomes = state.sampling(shots, seed)
        counts: dict[str, int] = {}
        width = program.num_qubits
        for outcome in outcomes:
            key = format(int(outcome), f"0{width}b")
            counts[key] = counts.get(key, 0) + 1
        return counts

    def z_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Return exact ``⟨Z⟩`` for each qubit in ``qubits``.

        Args:
            program: Program to execute, before the computational-basis measurement.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Unused. The value is not estimated from shots.
            seed: Unused.

        Returns:
            One expectation per entry of ``qubits``.

        Raises:
            ValueError: An index is outside ``program``.
            NotImplementedError: ``program`` resets a qubit, measures a qubit and
                then applies a gate, or prepares a state after leaving ``|0...0>``.
            ImportError: The ``qulacs`` extra is not installed.
        """
        del shots, seed
        return _expectations(program, qubits, "Z")

    def x_expectations(
        self,
        program: Program,
        qubits: Sequence[int],
        *,
        shots: int,
        seed: int | None,
    ) -> list[float]:
        """Return exact ``⟨X⟩`` for each qubit in ``qubits``.

        Args:
            program: Program to execute, before the X-basis measurement.
            qubits: 0-based indexes in ``program``. The result follows this order.
            shots: Unused. The value is not estimated from shots.
            seed: Unused.

        Returns:
            One expectation per entry of ``qubits``.

        Raises:
            ValueError: An index is outside ``program``.
            NotImplementedError: ``program`` resets a qubit, measures a qubit and
                then applies a gate, or prepares a state after leaving ``|0...0>``.
            ImportError: The ``qulacs`` extra is not installed.
        """
        del shots, seed
        return _expectations(program, qubits, "X")

__init__

__init__() -> None

Record the Qulacs backend name.

Source code in shadowsim/backends/qulacs.py
def __init__(self) -> None:
    """Record the Qulacs backend name."""
    self.name = "qulacs"

run_counts

run_counts(
    program: Program, *, shots: int, seed: int | None
) -> dict[str, int]

Sample program in the computational basis.

Parameters:

  • program (Program) –

    Program to execute.

  • shots (int) –

    Number of shots.

  • seed (int | None) –

    Seed for Qulacs sampling. None draws without a fixed seed.

Returns:

  • dict[str, int] –

    Mapping from bitstring to shot count. The rightmost character is qubit 0.

Raises:

  • ValueError –

    shots is not a positive integer, or the statevector probabilities do not sum to 1.

  • TypeError –

    seed is not an int or None.

  • NotImplementedError –

    program resets a qubit, measures a qubit and then applies a gate, or prepares a state after leaving |0...0>.

  • ImportError –

    The qulacs extra is not installed.

Source code in shadowsim/backends/qulacs.py
def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
    """Sample ``program`` in the computational basis.

    Args:
        program: Program to execute.
        shots: Number of shots.
        seed: Seed for Qulacs sampling. ``None`` draws without a fixed seed.

    Returns:
        Mapping from bitstring to shot count. The rightmost character is qubit 0.

    Raises:
        ValueError: ``shots`` is not a positive integer, or the statevector
            probabilities do not sum to 1.
        TypeError: ``seed`` is not an ``int`` or ``None``.
        NotImplementedError: ``program`` resets a qubit, measures a qubit
            and then applies a gate, or prepares a state after leaving
            ``|0...0>``.
        ImportError: The ``qulacs`` extra is not installed.
    """
    _require_shots(shots)
    _require_seed(seed)
    state = _state(program)
    _check_normalized(state)
    if seed is None:
        outcomes = state.sampling(shots)
    else:
        outcomes = state.sampling(shots, seed)
    counts: dict[str, int] = {}
    width = program.num_qubits
    for outcome in outcomes:
        key = format(int(outcome), f"0{width}b")
        counts[key] = counts.get(key, 0) + 1
    return counts

z_expectations

z_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Return exact ⟨Z⟩ for each qubit in qubits.

Parameters:

  • program (Program) –

    Program to execute, before the computational-basis measurement.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Unused. The value is not estimated from shots.

  • seed (int | None) –

    Unused.

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    An index is outside program.

  • NotImplementedError –

    program resets a qubit, measures a qubit and then applies a gate, or prepares a state after leaving |0...0>.

  • ImportError –

    The qulacs extra is not installed.

Source code in shadowsim/backends/qulacs.py
def z_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Return exact ``⟨Z⟩`` for each qubit in ``qubits``.

    Args:
        program: Program to execute, before the computational-basis measurement.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Unused. The value is not estimated from shots.
        seed: Unused.

    Returns:
        One expectation per entry of ``qubits``.

    Raises:
        ValueError: An index is outside ``program``.
        NotImplementedError: ``program`` resets a qubit, measures a qubit and
            then applies a gate, or prepares a state after leaving ``|0...0>``.
        ImportError: The ``qulacs`` extra is not installed.
    """
    del shots, seed
    return _expectations(program, qubits, "Z")

x_expectations

x_expectations(
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]

Return exact ⟨X⟩ for each qubit in qubits.

Parameters:

  • program (Program) –

    Program to execute, before the X-basis measurement.

  • qubits (Sequence[int]) –

    0-based indexes in program. The result follows this order.

  • shots (int) –

    Unused. The value is not estimated from shots.

  • seed (int | None) –

    Unused.

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    An index is outside program.

  • NotImplementedError –

    program resets a qubit, measures a qubit and then applies a gate, or prepares a state after leaving |0...0>.

  • ImportError –

    The qulacs extra is not installed.

Source code in shadowsim/backends/qulacs.py
def x_expectations(
    self,
    program: Program,
    qubits: Sequence[int],
    *,
    shots: int,
    seed: int | None,
) -> list[float]:
    """Return exact ``⟨X⟩`` for each qubit in ``qubits``.

    Args:
        program: Program to execute, before the X-basis measurement.
        qubits: 0-based indexes in ``program``. The result follows this order.
        shots: Unused. The value is not estimated from shots.
        seed: Unused.

    Returns:
        One expectation per entry of ``qubits``.

    Raises:
        ValueError: An index is outside ``program``.
        NotImplementedError: ``program`` resets a qubit, measures a qubit and
            then applies a gate, or prepares a state after leaving ``|0...0>``.
        ImportError: The ``qulacs`` extra is not installed.
    """
    del shots, seed
    return _expectations(program, qubits, "X")

ListedBackend

Bases: TypedDict

Display record for one concrete circuit backend.

Source code in shadowsim/backends/catalog.py
class ListedBackend(TypedDict):
    """Display record for one concrete circuit backend."""

    id: str
    title: str
    detail: str
    phrase: str
    setup: str
    shots: bool
    fields: list[ListedField]

from_qiskit

from_qiskit(circuit: QuantumCircuit) -> Program

Record the instructions of circuit as a :class:Program.

Qubit indexes are positions in circuit.qubits. Initialize, Hadamard, reset, barrier, and measure are recorded as those operations. Any other instruction that provides a matrix, including rx and a custom unitary, is recorded as that matrix on the instruction's qubits.

Parameters:

  • circuit (QuantumCircuit) –

    Circuit to record.

Returns:

  • Program –

    The operations on circuit, in order.

Raises:

  • ImportError –

    Qiskit is not installed.

  • ValueError –

    An instruction has no matrix and is not initialize, reset, barrier, or measure.

Source code in shadowsim/backends/circuit.py
def from_qiskit(circuit: QuantumCircuit) -> Program:
    """Record the instructions of ``circuit`` as a :class:`Program`.

    Qubit indexes are positions in ``circuit.qubits``. Initialize, Hadamard,
    reset, barrier, and measure are recorded as those operations. Any other
    instruction that provides a matrix, including ``rx`` and a custom unitary,
    is recorded as that matrix on the instruction's qubits.

    Args:
        circuit: Circuit to record.

    Returns:
        The operations on ``circuit``, in order.

    Raises:
        ImportError: Qiskit is not installed.
        ValueError: An instruction has no matrix and is not initialize, reset,
            barrier, or measure.
    """
    import_optional("qiskit", extra="qiskit")
    operations: list[Operation] = []
    for instruction in circuit.data:
        qubits = tuple(int(circuit.find_bit(qubit).index) for qubit in instruction.qubits)
        clbits = tuple(int(circuit.find_bit(clbit).index) for clbit in instruction.clbits)
        operations.append(_operation(instruction.operation, qubits, clbits))
    return Program(circuit.num_qubits, circuit.num_clbits, operations)

to_qiskit

to_qiskit(program: Program) -> QuantumCircuit

Build a Qiskit circuit from program.

The circuit has one quantum register and, when program has classical bits, one classical register. A measurement writes the same qubit onto the same classical bit recorded in program.

Parameters:

  • program (Program) –

    Operations to append.

Returns:

  • QuantumCircuit –

    A circuit with those operations.

Raises:

  • ImportError –

    Qiskit is not installed.

Source code in shadowsim/backends/circuit.py
def to_qiskit(program: Program) -> QuantumCircuit:
    """Build a Qiskit circuit from ``program``.

    The circuit has one quantum register and, when ``program`` has classical
    bits, one classical register. A measurement writes the same qubit onto the
    same classical bit recorded in ``program``.

    Args:
        program: Operations to append.

    Returns:
        A circuit with those operations.

    Raises:
        ImportError: Qiskit is not installed.
    """
    qiskit = import_optional("qiskit", extra="qiskit")
    circuit = qiskit.QuantumCircuit(program.num_qubits, program.num_clbits)
    for operation in program.operations:
        _append(circuit, operation)
    return circuit

listed_backends

listed_backends() -> list[ListedBackend]

Return the concrete circuit backends in export order.

Each exported backend module is imported on its own. A missing extra skips that module. CircuitBackend is a protocol, so it is omitted. Each record uses the class name and the first line of its docstring. Required constructor arguments appear in setup. A shots parameter is written as {shots} so the page can fill the shot budget. basis_gates, when its default is None, is a gate list written as {basis_gates}. Its choices are the class attribute BASIS_GATE_NAMES. Any other parameter with a default is a numeric field the page can edit, written as {name}.

Returns:

Raises:

  • ImportError –

    No circuit backend module could be imported. The first failure is re-raised.

Source code in shadowsim/backends/catalog.py
def listed_backends() -> list[ListedBackend]:
    """Return the concrete circuit backends in export order.

    Each exported backend module is imported on its own. A missing extra skips
    that module. ``CircuitBackend`` is a protocol, so it is omitted. Each
    record uses the class name and the first line of its docstring. Required
    constructor arguments appear in ``setup``. A ``shots`` parameter is written
    as ``{shots}`` so the page can fill the shot budget. ``basis_gates``, when
    its default is ``None``, is a gate list written as ``{basis_gates}``. Its
    choices are the class attribute ``BASIS_GATE_NAMES``. Any other parameter
    with a default is a numeric field the page can edit, written as ``{name}``.

    Returns:
        Backends the builder page can offer.

    Raises:
        ImportError: No circuit backend module could be imported. The first
            failure is re-raised.
    """
    listed: list[ListedBackend] = []
    first_error: ImportError | None = None
    seen: set[str] = set()
    for module_name, extra in _EXPORTS.values():
        if module_name in seen:
            continue
        seen.add(module_name)
        try:
            if extra is None:
                module = importlib.import_module(module_name)
            else:
                module = import_optional(module_name, extra=extra)
        except ImportError as exc:
            if first_error is None:
                first_error = exc
            continue
        listed.extend(_describe_backends(module))
    if listed:
        return listed
    if first_error is not None:
        raise first_error
    raise ImportError("no circuit backends could be imported")

__getattr__

__getattr__(name: str) -> Any

Import a circuit backend the first time it is accessed.

Source code in shadowsim/backends/__init__.py
def __getattr__(name: str) -> Any:
    """Import a circuit backend 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 name in _QISKIT_TRANSLATION:
        import_optional("qiskit", extra="qiskit")
    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 backends that have not been imported yet.

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