Skip to content

circuit

Circuit backend protocol and Qiskit program translation.

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.
    """
    ...

backend_samples

backend_samples(backend: object) -> bool

Return whether backend stores a shot budget.

Parameters:

  • backend (object) –

    Circuit backend. Sampling backends store shots.

Returns:

  • bool –

    True when backend has a shots attribute.

Source code in shadowsim/backends/circuit.py
def backend_samples(backend: object) -> bool:
    """Return whether ``backend`` stores a shot budget.

    Args:
        backend: Circuit backend. Sampling backends store ``shots``.

    Returns:
        True when ``backend`` has a ``shots`` attribute.
    """
    return hasattr(backend, "shots")

backend_shots

backend_shots(backend: object) -> int

Return the positive shot count stored on backend.

Parameters:

  • backend (object) –

    Sampling backend. It must store shots as a positive integer.

Returns:

  • int –

    That shot count.

Raises:

  • ValueError –

    shots is missing or not a positive integer.

Source code in shadowsim/backends/circuit.py
def backend_shots(backend: object) -> int:
    """Return the positive shot count stored on ``backend``.

    Args:
        backend: Sampling backend. It must store ``shots`` as a positive integer.

    Returns:
        That shot count.

    Raises:
        ValueError: ``shots`` is missing or not a positive integer.
    """
    return _require_shots(getattr(backend, "shots", None))

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