Skip to content

encoding

Prepare a normalized quantum state from classical data.

encode returns a State that any simulator accepts as initial_state. load_encoding_data reads a 1D vector from a .npy, .txt, or .csv file.

AmplitudeEncoding

Bases: StateEncoder

Prepare a state whose amplitudes are a normalized classical vector.

Let \(a\) be a non-zero vector of length \(m\). It is zero-padded to length

\[ d = \max\left(2, 2^{\lceil \log_2 m \rceil}\right) \]

and then divided by its Euclidean norm. That norm is real and non-negative, so the global phase of \(a\) is unchanged. The prepared state uses \(n = \log_2 d\) qubits, and index \(k\) of the padded vector is the amplitude of computational-basis state \(\lvert k\rangle\).

Examples:

A length-3 vector is padded to four amplitudes:

import numpy as np
from shadowsim.encoding import AmplitudeEncoding

state = AmplitudeEncoding().encode([1.0, 1.0, 0.0])
print(state.get_num_qubits())
print(np.round(state.to_numpy(), decimals=8))
2
[0.70710678+0.j 0.70710678+0.j 0.        +0.j 0.        +0.j]
Source code in shadowsim/encoding/amplitude.py
class AmplitudeEncoding(StateEncoder):
    r"""Prepare a state whose amplitudes are a normalized classical vector.

    Let \(a\) be a non-zero vector of length \(m\). It is zero-padded to length

    \[
        d = \max\left(2, 2^{\lceil \log_2 m \rceil}\right)
    \]

    and then divided by its Euclidean norm. That norm is real and non-negative,
    so the global phase of \(a\) is unchanged. The prepared state uses
    \(n = \log_2 d\) qubits, and index \(k\) of the padded vector is the
    amplitude of computational-basis state \(\lvert k\rangle\).

    Examples:
        A length-3 vector is padded to four amplitudes:

        ```python exec="1" source="above" result="text"
        import numpy as np
        from shadowsim.encoding import AmplitudeEncoding

        state = AmplitudeEncoding().encode([1.0, 1.0, 0.0])
        print(state.get_num_qubits())
        print(np.round(state.to_numpy(), decimals=8))
        ```

    """

    def encode(self, data: npt.ArrayLike) -> State:
        r"""Return the normalized, zero-padded amplitude state.

        Args:
            data: Non-zero 1D vector of finite real or complex amplitudes.

        Returns:
            Normalized state on \(\log_2 d\) qubits.

        Raises:
            ValueError: If ``data`` is empty, not 1D, non-finite, or all zeros.
        """
        amplitudes = _finite_amplitudes(data)
        # Scale by the largest magnitude first. A direct L2 norm underflows when
        # every amplitude is far below 1, and the result is then not normalized.
        scale = float(np.max(np.abs(amplitudes)))
        if scale == 0.0:
            raise ValueError("amplitude vector must be non-zero")
        scaled = amplitudes / scale

        padded_length = max(2, next_power_of_two(int(amplitudes.shape[0])))
        padded = np.zeros(padded_length, dtype=np.complex128)
        padded[: scaled.shape[0]] = scaled
        padded /= np.linalg.norm(scaled)
        return State(padded, padded_length.bit_length() - 1)

encode

encode(data: ArrayLike) -> State

Return the normalized, zero-padded amplitude state.

Parameters:

  • data (ArrayLike) –

    Non-zero 1D vector of finite real or complex amplitudes.

Returns:

  • State –

    Normalized state on \(\log_2 d\) qubits.

Raises:

  • ValueError –

    If data is empty, not 1D, non-finite, or all zeros.

Source code in shadowsim/encoding/amplitude.py
def encode(self, data: npt.ArrayLike) -> State:
    r"""Return the normalized, zero-padded amplitude state.

    Args:
        data: Non-zero 1D vector of finite real or complex amplitudes.

    Returns:
        Normalized state on \(\log_2 d\) qubits.

    Raises:
        ValueError: If ``data`` is empty, not 1D, non-finite, or all zeros.
    """
    amplitudes = _finite_amplitudes(data)
    # Scale by the largest magnitude first. A direct L2 norm underflows when
    # every amplitude is far below 1, and the result is then not normalized.
    scale = float(np.max(np.abs(amplitudes)))
    if scale == 0.0:
        raise ValueError("amplitude vector must be non-zero")
    scaled = amplitudes / scale

    padded_length = max(2, next_power_of_two(int(amplitudes.shape[0])))
    padded = np.zeros(padded_length, dtype=np.complex128)
    padded[: scaled.shape[0]] = scaled
    padded /= np.linalg.norm(scaled)
    return State(padded, padded_length.bit_length() - 1)

AngleEncoding

Bases: StateEncoder

Prepare \(\bigotimes_i R_y(\theta_i)\lvert 0\rangle\) from one angle per qubit.

Each angle is a rotation in radians. On a single qubit,

\[ R_y(\theta)\lvert 0\rangle = \cos(\theta/2)\lvert 0\rangle + \sin(\theta/2)\lvert 1\rangle. \]

Angles are not amplitudes: they are not normalized. The first angle is the first factor of tensor, so it is the most significant qubit. The number of qubits is the length of data.

Examples:

A \(\pi/2\) rotation prepares the equal superposition:

import numpy as np
from shadowsim.encoding import AngleEncoding

state = AngleEncoding().encode([np.pi / 2])
print(np.round(state.to_numpy(), decimals=8))
[0.70710678+0.j 0.70710678+0.j]
Source code in shadowsim/encoding/angle.py
class AngleEncoding(StateEncoder):
    r"""Prepare \(\bigotimes_i R_y(\theta_i)\lvert 0\rangle\) from one angle per qubit.

    Each angle is a rotation in radians. On a single qubit,

    \[
        R_y(\theta)\lvert 0\rangle = \cos(\theta/2)\lvert 0\rangle + \sin(\theta/2)\lvert 1\rangle.
    \]

    Angles are not amplitudes: they are not normalized. The first angle is the
    first factor of ``tensor``, so it is the most
    significant qubit. The number of qubits is the length of ``data``.

    Examples:
        A \(\pi/2\) rotation prepares the equal superposition:

        ```python exec="1" source="above" result="text"
        import numpy as np
        from shadowsim.encoding import AngleEncoding

        state = AngleEncoding().encode([np.pi / 2])
        print(np.round(state.to_numpy(), decimals=8))
        ```

    """

    def encode(self, data: npt.ArrayLike) -> State:
        """Return the product state for one Y rotation per qubit.

        Args:
            data: One finite real angle, in radians, per qubit.

        Returns:
            Normalized product state on ``len(data)`` qubits.

        Raises:
            ValueError: If ``data`` is not a non-empty 1D array of finite real numbers.
        """
        angles = _real_angles(data)
        kets = [np.array([np.cos(0.5 * theta), np.sin(0.5 * theta)], dtype=np.complex128) for theta in angles]
        vector = tensor(kets)
        vector = vector / np.linalg.norm(vector)
        return State(vector, int(angles.shape[0]))

encode

encode(data: ArrayLike) -> State

Return the product state for one Y rotation per qubit.

Parameters:

  • data (ArrayLike) –

    One finite real angle, in radians, per qubit.

Returns:

  • State –

    Normalized product state on len(data) qubits.

Raises:

  • ValueError –

    If data is not a non-empty 1D array of finite real numbers.

Source code in shadowsim/encoding/angle.py
def encode(self, data: npt.ArrayLike) -> State:
    """Return the product state for one Y rotation per qubit.

    Args:
        data: One finite real angle, in radians, per qubit.

    Returns:
        Normalized product state on ``len(data)`` qubits.

    Raises:
        ValueError: If ``data`` is not a non-empty 1D array of finite real numbers.
    """
    angles = _real_angles(data)
    kets = [np.array([np.cos(0.5 * theta), np.sin(0.5 * theta)], dtype=np.complex128) for theta in angles]
    vector = tensor(kets)
    vector = vector / np.linalg.norm(vector)
    return State(vector, int(angles.shape[0]))

ComputationalBasisEncoding

Bases: StateEncoder

Prepare a computational-basis state \(\lvert k\rangle\).

An integer \(k\) in \(0 .. 2^n - 1\) becomes the one-hot vector with a 1 at index \(k\). A length-\(n\) sequence of bits \(b_0, b_1, \ldots, b_{n-1}\) uses the same layout as tensor: \(b_0\) is the most significant qubit, and

\[ k = \sum_{i=0}^{n-1} b_i \, 2^{n-1-i}. \]

So [1, 0] on two qubits is \(\lvert 10\rangle\), index 2.

Parameters:

  • num_qubits (int) –

    Number of qubits \(n\). Must be a non-negative integer.

Examples:

from shadowsim.encoding import ComputationalBasisEncoding

encoder = ComputationalBasisEncoding(2)
print(encoder.encode(2).to_numpy())
print(encoder.encode([1, 0]).to_numpy())
[0.+0.j 0.+0.j 1.+0.j 0.+0.j]
[0.+0.j 0.+0.j 1.+0.j 0.+0.j]
Source code in shadowsim/encoding/computational_basis.py
class ComputationalBasisEncoding(StateEncoder):
    r"""Prepare a computational-basis state \(\lvert k\rangle\).

    An integer \(k\) in \(0 .. 2^n - 1\) becomes the one-hot vector with a 1
    at index \(k\). A length-\(n\) sequence of bits \(b_0, b_1, \ldots, b_{n-1}\)
    uses the same layout as ``tensor``: \(b_0\) is
    the most significant qubit, and

    \[
        k = \sum_{i=0}^{n-1} b_i \, 2^{n-1-i}.
    \]

    So ``[1, 0]`` on two qubits is \(\lvert 10\rangle\), index 2.

    Args:
        num_qubits: Number of qubits \(n\). Must be a non-negative integer.

    Examples:
        ```python exec="1" source="above" result="text"
        from shadowsim.encoding import ComputationalBasisEncoding

        encoder = ComputationalBasisEncoding(2)
        print(encoder.encode(2).to_numpy())
        print(encoder.encode([1, 0]).to_numpy())
        ```

    """

    def __init__(self, num_qubits: int) -> None:
        """Store the number of qubits this encoding prepares."""
        assert num_qubits >= 0, "num_qubits must be non-negative"
        assert isinstance(num_qubits, int), "num_qubits must be an integer"
        self._num_qubits = num_qubits

    def encode(self, data: npt.ArrayLike) -> State:
        r"""Return the computational-basis state for an index or a bit string.

        Args:
            data: Integer index \(k\), or a length-``num_qubits`` sequence of
                bits 0 and 1. The first bit is the most significant qubit.

        Returns:
            One-hot state \(\lvert k\rangle\).

        Raises:
            ValueError: If ``data`` is not an in-range index or a valid bit string.
        """
        index = _basis_index(self._num_qubits, data)
        vector = np.zeros(2**self._num_qubits, dtype=np.complex128)
        vector[index] = 1.0
        return State(vector, self._num_qubits)

__init__

__init__(num_qubits: int) -> None

Store the number of qubits this encoding prepares.

Source code in shadowsim/encoding/computational_basis.py
def __init__(self, num_qubits: int) -> None:
    """Store the number of qubits this encoding prepares."""
    assert num_qubits >= 0, "num_qubits must be non-negative"
    assert isinstance(num_qubits, int), "num_qubits must be an integer"
    self._num_qubits = num_qubits

encode

encode(data: ArrayLike) -> State

Return the computational-basis state for an index or a bit string.

Parameters:

  • data (ArrayLike) –

    Integer index \(k\), or a length-num_qubits sequence of bits 0 and 1. The first bit is the most significant qubit.

Returns:

  • State –

    One-hot state \(\lvert k\rangle\).

Raises:

  • ValueError –

    If data is not an in-range index or a valid bit string.

Source code in shadowsim/encoding/computational_basis.py
def encode(self, data: npt.ArrayLike) -> State:
    r"""Return the computational-basis state for an index or a bit string.

    Args:
        data: Integer index \(k\), or a length-``num_qubits`` sequence of
            bits 0 and 1. The first bit is the most significant qubit.

    Returns:
        One-hot state \(\lvert k\rangle\).

    Raises:
        ValueError: If ``data`` is not an in-range index or a valid bit string.
    """
    index = _basis_index(self._num_qubits, data)
    vector = np.zeros(2**self._num_qubits, dtype=np.complex128)
    vector[index] = 1.0
    return State(vector, self._num_qubits)

GrayEncoding

Bases: StateEncoder

Prepare the computational-basis state at the Gray code of \(k\).

An integer \(k\) in \(0 .. 2^n - 1\), or a length-\(n\) bit string read as that integer with the first bit most significant, is mapped by the binary-reflected Gray code

\[ g(k) = k \oplus (k \gg 1). \]

The prepared state is the one-hot vector with a 1 at index \(g(k)\). Consecutive integers therefore land on basis states at Hamming distance 1.

On two qubits, \(k = 0, 1, 2, 3\) prepares \(\lvert 00\rangle, \lvert 01\rangle, \lvert 11\rangle, \lvert 10\rangle\). So [1, 0] is the binary integer 2 and prepares \(\lvert 11\rangle\).

Parameters:

  • num_qubits (int) –

    Number of qubits \(n\). Must be a non-negative integer.

Examples:

from shadowsim.encoding import GrayEncoding

encoder = GrayEncoding(2)
print(encoder.encode(2).to_numpy())
print(encoder.encode([1, 0]).to_numpy())
[0.+0.j 0.+0.j 0.+0.j 1.+0.j]
[0.+0.j 0.+0.j 0.+0.j 1.+0.j]
Source code in shadowsim/encoding/gray.py
class GrayEncoding(StateEncoder):
    r"""Prepare the computational-basis state at the Gray code of \(k\).

    An integer \(k\) in \(0 .. 2^n - 1\), or a length-\(n\) bit string read as
    that integer with the first bit most significant, is mapped by the
    binary-reflected Gray code

    \[
        g(k) = k \oplus (k \gg 1).
    \]

    The prepared state is the one-hot vector with a 1 at index \(g(k)\).
    Consecutive integers therefore land on basis states at Hamming distance 1.

    On two qubits, \(k = 0, 1, 2, 3\) prepares
    \(\lvert 00\rangle, \lvert 01\rangle, \lvert 11\rangle, \lvert 10\rangle\).
    So ``[1, 0]`` is the binary integer 2 and prepares \(\lvert 11\rangle\).

    Args:
        num_qubits: Number of qubits \(n\). Must be a non-negative integer.

    Examples:
        ```python exec="1" source="above" result="text"
        from shadowsim.encoding import GrayEncoding

        encoder = GrayEncoding(2)
        print(encoder.encode(2).to_numpy())
        print(encoder.encode([1, 0]).to_numpy())
        ```

    """

    def __init__(self, num_qubits: int) -> None:
        """Store the number of qubits this encoding prepares."""
        assert num_qubits >= 0, "num_qubits must be non-negative"
        assert isinstance(num_qubits, int), "num_qubits must be an integer"
        self._num_qubits = num_qubits

    def encode(self, data: npt.ArrayLike) -> State:
        r"""Return the Gray-labeled computational-basis state for an index or a bit string.

        Args:
            data: Integer index \(k\), or a length-``num_qubits`` sequence of
                bits 0 and 1. The first bit is the most significant qubit, and
                the sequence is read as a standard binary integer.

        Returns:
            One-hot state \(\lvert g(k)\rangle\), where \(g(k) = k \oplus (k \gg 1)\).

        Raises:
            ValueError: If ``data`` is not an in-range index or a valid bit string.
        """
        index = _basis_index(self._num_qubits, data)
        gray = index ^ (index >> 1)
        vector = np.zeros(2**self._num_qubits, dtype=np.complex128)
        vector[gray] = 1.0
        return State(vector, self._num_qubits)

__init__

__init__(num_qubits: int) -> None

Store the number of qubits this encoding prepares.

Source code in shadowsim/encoding/gray.py
def __init__(self, num_qubits: int) -> None:
    """Store the number of qubits this encoding prepares."""
    assert num_qubits >= 0, "num_qubits must be non-negative"
    assert isinstance(num_qubits, int), "num_qubits must be an integer"
    self._num_qubits = num_qubits

encode

encode(data: ArrayLike) -> State

Return the Gray-labeled computational-basis state for an index or a bit string.

Parameters:

  • data (ArrayLike) –

    Integer index \(k\), or a length-num_qubits sequence of bits 0 and 1. The first bit is the most significant qubit, and the sequence is read as a standard binary integer.

Returns:

  • State –

    One-hot state \(\lvert g(k)\rangle\), where \(g(k) = k \oplus (k \gg 1)\).

Raises:

  • ValueError –

    If data is not an in-range index or a valid bit string.

Source code in shadowsim/encoding/gray.py
def encode(self, data: npt.ArrayLike) -> State:
    r"""Return the Gray-labeled computational-basis state for an index or a bit string.

    Args:
        data: Integer index \(k\), or a length-``num_qubits`` sequence of
            bits 0 and 1. The first bit is the most significant qubit, and
            the sequence is read as a standard binary integer.

    Returns:
        One-hot state \(\lvert g(k)\rangle\), where \(g(k) = k \oplus (k \gg 1)\).

    Raises:
        ValueError: If ``data`` is not an in-range index or a valid bit string.
    """
    index = _basis_index(self._num_qubits, data)
    gray = index ^ (index >> 1)
    vector = np.zeros(2**self._num_qubits, dtype=np.complex128)
    vector[gray] = 1.0
    return State(vector, self._num_qubits)

StateEncoder

Bases: ABC

Prepare a normalized State from classical data.

Subclasses define which classical inputs they accept. Every encoding returns a state vector that simulators can take as initial_state.

Source code in shadowsim/encoding/state_encoder.py
class StateEncoder(ABC):
    """Prepare a normalized ``State`` from classical data.

    Subclasses define which classical inputs they accept. Every encoding returns
    a state vector that simulators can take as ``initial_state``.
    """

    @abstractmethod
    def encode(self, data: npt.ArrayLike) -> State:
        """Return the quantum state prepared from ``data``.

        Args:
            data: Classical input for this encoding.

        Returns:
            A normalized state on the qubits this encoding uses.
        """
        raise NotImplementedError

encode abstractmethod

encode(data: ArrayLike) -> State

Return the quantum state prepared from data.

Parameters:

  • data (ArrayLike) –

    Classical input for this encoding.

Returns:

  • State –

    A normalized state on the qubits this encoding uses.

Source code in shadowsim/encoding/state_encoder.py
@abstractmethod
def encode(self, data: npt.ArrayLike) -> State:
    """Return the quantum state prepared from ``data``.

    Args:
        data: Classical input for this encoding.

    Returns:
        A normalized state on the qubits this encoding uses.
    """
    raise NotImplementedError

load_encoding_data

load_encoding_data(
    path: str | PathLike[str],
) -> NDArray[number[Any]]

Load a non-empty 1D vector from an encoding data file.

.npy files are read with allow_pickle=False and may contain finite real or complex numbers. .txt and .csv files are one column of finite real numbers. Complex values belong in .npy. The returned array is passed to an encoder such as AmplitudeEncoding, AngleEncoding, or ComputationalBasisEncoding.

Parameters:

  • path (str | PathLike[str]) –

    Path to a .npy, .txt, or .csv file. The suffix match is case-insensitive.

Returns:

  • NDArray[number[Any]] –

    The file's vector. A .npy array keeps its dtype. Text files are

  • NDArray[number[Any]] –

    returned as float64.

Raises:

  • ValueError –

    If the suffix is not supported, the path is missing, is a directory, or is empty, or the contents are not a non-empty 1D array of finite numbers. Pickle payloads are rejected and not executed.

Examples:

import tempfile
from pathlib import Path

import numpy as np

from shadowsim.encoding import AmplitudeEncoding, load_encoding_data

amplitudes = np.array([1.0, 1.0j, 0.0])
with tempfile.TemporaryDirectory() as directory:
    path = Path(directory) / "amplitudes.npy"
    np.save(path, amplitudes)
    state = AmplitudeEncoding().encode(load_encoding_data(path))
print(state.get_num_qubits())
2
Source code in shadowsim/encoding/load.py
def load_encoding_data(path: str | os.PathLike[str]) -> npt.NDArray[np.number[Any]]:
    """Load a non-empty 1D vector from an encoding data file.

    ``.npy`` files are read with ``allow_pickle=False`` and may contain finite
    real or complex numbers. ``.txt`` and ``.csv`` files are one column of
    finite real numbers. Complex values belong in ``.npy``. The returned array
    is passed to an encoder such as ``AmplitudeEncoding``, ``AngleEncoding``,
    or ``ComputationalBasisEncoding``.

    Args:
        path: Path to a ``.npy``, ``.txt``, or ``.csv`` file. The suffix match
            is case-insensitive.

    Returns:
        The file's vector. A ``.npy`` array keeps its dtype. Text files are
        returned as ``float64``.

    Raises:
        ValueError: If the suffix is not supported, the path is missing, is a
            directory, or is empty, or the contents are not a non-empty 1D
            array of finite numbers. Pickle payloads are rejected and not
            executed.

    Examples:
        ```python exec="1" source="above" result="text"
        import tempfile
        from pathlib import Path

        import numpy as np

        from shadowsim.encoding import AmplitudeEncoding, load_encoding_data

        amplitudes = np.array([1.0, 1.0j, 0.0])
        with tempfile.TemporaryDirectory() as directory:
            path = Path(directory) / "amplitudes.npy"
            np.save(path, amplitudes)
            state = AmplitudeEncoding().encode(load_encoding_data(path))
        print(state.get_num_qubits())
        ```

    """
    file_path = Path(path)
    suffix = file_path.suffix.lower()
    if suffix not in {".npy", ".txt", ".csv"}:
        raise ValueError(f"encoding data path must end in .npy, .txt, or .csv, got suffix {file_path.suffix!r}")
    if not file_path.exists():
        raise ValueError(f"encoding data file does not exist: {file_path}")
    if not file_path.is_file():
        raise ValueError(f"encoding data path must be a file: {file_path}")
    if file_path.stat().st_size == 0:
        raise ValueError(f"encoding data file is empty: {file_path}")

    if suffix == ".npy":
        return _require_vector(_read_npy(file_path), allow_complex=True)
    delimiter = "," if suffix == ".csv" else None
    return _require_vector(_read_text(file_path, delimiter), allow_complex=False)