Skip to content

numpy_statevector

Execute a circuit program with a NumPy statevector.

Qubit 0 is the least significant bit of the statevector index. Each gate is applied by moving those qubit axes next to each other and multiplying, which keeps the update readable on a small register. This is the reference evolution for small programs. Correctness and readability come before performance.

Reset, a measurement followed by a gate, and Prepare after the register has left |0...0> are rejected.

statevector

statevector(program: Program) -> NDArray[complex128]

Return the statevector of program before its terminal measurement.

The register starts in |0...0>. Prepare writes its amplitudes only while the register is still in that state. Barrier is ignored. A Measure may appear only after every gate.

Parameters:

  • program (Program) –

    Operations to apply.

Returns:

  • NDArray[complex128] –

    Complex amplitudes. Qubit q is bit q of the index, so qubit 0 is

  • NDArray[complex128] –

    the least significant bit.

Raises:

  • NotImplementedError –

    program resets a qubit, measures a qubit and then applies a gate, or prepares a state after the register has left |0...0>.

Source code in shadowsim/backends/numpy_statevector.py
def statevector(program: Program) -> npt.NDArray[np.complex128]:
    """Return the statevector of ``program`` before its terminal measurement.

    The register starts in ``|0...0>``. ``Prepare`` writes its amplitudes only
    while the register is still in that state. ``Barrier`` is ignored. A
    ``Measure`` may appear only after every gate.

    Args:
        program: Operations to apply.

    Returns:
        Complex amplitudes. Qubit ``q`` is bit ``q`` of the index, so qubit 0 is
        the least significant bit.

    Raises:
        NotImplementedError: ``program`` resets a qubit, measures a qubit and
            then applies a gate, or prepares a state after the register has
            left ``|0...0>``.
    """
    state = np.zeros(2**program.num_qubits, dtype=np.complex128)
    state[0] = 1.0
    for operation in _before_measurement(program):
        state = _apply(state, operation)
    return state

expectations

expectations(
    program: Program, qubits: Sequence[int], pauli: _Pauli
) -> list[float]

Return the exact expectation of pauli on each qubit in qubits.

Parameters:

  • program (Program) –

    Circuit to evolve, before the computational-basis measurement.

  • qubits (Sequence[int]) –

    Qubit indexes. The result follows this order.

  • pauli (_Pauli) –

    "Z" or "X".

Returns:

  • list[float] –

    One expectation per entry of qubits.

Raises:

  • ValueError –

    pauli is not "X" or "Z", or an index is outside program.

  • NotImplementedError –

    program uses an operation :func:statevector cannot apply.

Source code in shadowsim/backends/numpy_statevector.py
def expectations(program: Program, qubits: Sequence[int], pauli: _Pauli) -> list[float]:
    """Return the exact expectation of ``pauli`` on each qubit in ``qubits``.

    Args:
        program: Circuit to evolve, before the computational-basis measurement.
        qubits: Qubit indexes. The result follows this order.
        pauli: ``"Z"`` or ``"X"``.

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

    Raises:
        ValueError: ``pauli`` is not ``"X"`` or ``"Z"``, or an index is outside
            ``program``.
        NotImplementedError: ``program`` uses an operation :func:`statevector`
            cannot apply.
    """
    if pauli not in ("X", "Z"):
        raise ValueError("pauli must be 'X' or 'Z'")
    state = statevector(program)
    indexes = _qubit_indexes(qubits, program.num_qubits, register="program")
    return [_expectation(state, index, pauli) for index in indexes]

sample_counts

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

Sample the computational-basis distribution of program.

A terminal Measure does not change that distribution. Keys use Qiskit order: the rightmost character is qubit 0. The same seed returns the same counts. None draws without a fixed seed.

Parameters:

  • program (Program) –

    Circuit to sample.

  • shots (int) –

    Number of shots. Must be a positive integer.

  • seed (int | None) –

    Seed for numpy.random.Generator, or None.

Returns:

  • dict[str, int] –

    Mapping from bitstring to shot count. Outcomes that never occurred are

  • dict[str, int] –

    omitted.

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 uses an operation :func:statevector cannot apply.

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

    A terminal ``Measure`` does not change that distribution. Keys use Qiskit
    order: the rightmost character is qubit 0. The same ``seed`` returns the
    same counts. ``None`` draws without a fixed seed.

    Args:
        program: Circuit to sample.
        shots: Number of shots. Must be a positive integer.
        seed: Seed for ``numpy.random.Generator``, or ``None``.

    Returns:
        Mapping from bitstring to shot count. Outcomes that never occurred are
        omitted.

    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`` uses an operation :func:`statevector`
            cannot apply.
    """
    shots = _require_shots(shots)
    seed = _require_seed(seed)
    probabilities = _probabilities(statevector(program))
    outcomes = np.random.default_rng(seed).choice(probabilities.shape[0], size=shots, p=probabilities)
    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