Skip to content

ir

Axis

Bases: Sequence[float64], Expression

The Axis object parses and stores a vector containing 3 elements.

The input vector is always normalized before it is stored.

Source code in opensquirrel\ir.py
class Axis(Sequence[np.float64], Expression):
    """The ``Axis`` object parses and stores a vector containing 3 elements.

    The input vector is always normalized before it is stored.
    """

    _len = 3

    def __init__(self, *axis: AxisLike) -> None:
        """Init of the ``Axis`` object.

        axis: An ``AxisLike`` to create the axis from.
        """
        axis_to_parse = axis[0] if len(axis) == 1 else cast(AxisLike, axis)
        self._value = self._parse_and_validate_axislike(axis_to_parse)

    @property
    def value(self) -> NDArray[np.float64]:
        """The ``Axis`` data saved as a 1D-Array with 3 elements."""
        return self._value

    @value.setter
    def value(self, axis: AxisLike) -> None:
        """Parse and set a new axis.

        Args:
            axis: An ``AxisLike`` to create the axis from.
        """
        self._value = self._parse_and_validate_axislike(axis)

    @classmethod
    def _parse_and_validate_axislike(cls, axis: AxisLike) -> NDArray[np.float64]:
        """Parse and validate an ``AxisLike``.

        Check if the `axis` can be cast to a 1DArray of length 3, raise an error
        otherwise. After casting to an array, the axis is normalized.

        Args:
            axis: ``AxisLike`` to validate and parse.

        Returns:
            Parsed axis represented as a 1DArray of length 3.
        """
        if isinstance(axis, Axis):
            return axis.value

        try:
            axis = np.asarray(axis, dtype=float)
        except (ValueError, TypeError) as e:
            msg = "axis requires an ArrayLike"
            raise TypeError(msg) from e
        axis = axis.flatten()
        if len(axis) != 3:
            msg = f"axis requires an ArrayLike of length 3, but received an ArrayLike of length {len(axis)}"
            raise ValueError(msg)
        return cls._normalize_axis(axis)

    @staticmethod
    def _normalize_axis(axis: NDArray[np.float64]) -> NDArray[np.float64]:
        """Normalize a NDArray.

        Args:
            axis: NDArray to normalize.

        Returns:
            Normalized NDArray.
        """
        return axis / np.linalg.norm(axis)

    def __getitem__(self, index: int, /) -> np.float64:  # type:ignore[override]
        """Get the item at `index`."""
        return cast(np.float64, self.value[index])

    def __len__(self) -> int:
        """Length of the axis, which is always 3."""
        return self._len

    def __repr__(self) -> str:
        """String representation of the ``Axis``."""
        return f"Axis{self.value}"

    def __array__(self, dtype: DTypeLike = None, *, copy: bool = True) -> NDArray[Any]:
        """Convert the ``Axis`` data to an array."""
        return np.array(self.value, dtype=dtype, copy=copy)

    def accept(self, visitor: IRVisitor) -> Any:
        """Accept the ``Axis``."""
        return visitor.visit_axis(self)

    def __eq__(self, other: Any) -> bool:
        """Check if `self` is equal to other.

        Two ``Axis`` objects are considered equal if their axes are equal.
        """
        if not isinstance(other, Axis):
            return False
        return np.array_equal(self, other)

value: NDArray[np.float64] property writable

The Axis data saved as a 1D-Array with 3 elements.

__array__(dtype=None, *, copy=True)

Convert the Axis data to an array.

Source code in opensquirrel\ir.py
def __array__(self, dtype: DTypeLike = None, *, copy: bool = True) -> NDArray[Any]:
    """Convert the ``Axis`` data to an array."""
    return np.array(self.value, dtype=dtype, copy=copy)

__eq__(other)

Check if self is equal to other.

Two Axis objects are considered equal if their axes are equal.

Source code in opensquirrel\ir.py
def __eq__(self, other: Any) -> bool:
    """Check if `self` is equal to other.

    Two ``Axis`` objects are considered equal if their axes are equal.
    """
    if not isinstance(other, Axis):
        return False
    return np.array_equal(self, other)

__getitem__(index)

Get the item at index.

Source code in opensquirrel\ir.py
def __getitem__(self, index: int, /) -> np.float64:  # type:ignore[override]
    """Get the item at `index`."""
    return cast(np.float64, self.value[index])

__init__(*axis)

Init of the Axis object.

axis: An AxisLike to create the axis from.

Source code in opensquirrel\ir.py
def __init__(self, *axis: AxisLike) -> None:
    """Init of the ``Axis`` object.

    axis: An ``AxisLike`` to create the axis from.
    """
    axis_to_parse = axis[0] if len(axis) == 1 else cast(AxisLike, axis)
    self._value = self._parse_and_validate_axislike(axis_to_parse)

__len__()

Length of the axis, which is always 3.

Source code in opensquirrel\ir.py
def __len__(self) -> int:
    """Length of the axis, which is always 3."""
    return self._len

__repr__()

String representation of the Axis.

Source code in opensquirrel\ir.py
def __repr__(self) -> str:
    """String representation of the ``Axis``."""
    return f"Axis{self.value}"

accept(visitor)

Accept the Axis.

Source code in opensquirrel\ir.py
def accept(self, visitor: IRVisitor) -> Any:
    """Accept the ``Axis``."""
    return visitor.visit_axis(self)

Gate

Bases: Statement, ABC

Source code in opensquirrel\ir.py
class Gate(Statement, ABC):
    def __init__(
        self,
        generator: Callable[..., Gate] | None = None,
        arguments: tuple[Expression, ...] | None = None,
        *args: Any,
        **kwargs: Any,
    ) -> None:
        # Note: two gates are considered equal even when their generators/arguments are different.
        self.generator = generator
        self.arguments = arguments

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Gate):
            return False
        return compare_gates(self, other)

    @property
    def name(self) -> str:
        if self.generator:
            return self.generator.__name__
        return "Anonymous gate: " + self.__repr__()

    @property
    def is_anonymous(self) -> bool:
        return self.arguments is None

    @staticmethod
    def _check_repeated_qubit_operands(qubits: list[Qubit]) -> bool:
        """Check if qubit operands are repeated.

        Args:
            qubits: List of qubits.

        Returns:
            Whether qubit operands are repeated.
        """
        return len(qubits) != len(set(qubits))

    @abstractmethod
    def get_qubit_operands(self) -> list[Qubit]:
        """Get the qubit operands of the Gate.

        Returns:
            List of qubits on which the Gate operates.
        """

    @abstractmethod
    def is_identity(self) -> bool:
        """Check whether the Gate is an identity Gate.

        Returns:
            Boolean value stating whether the Gate is an identity Gate.
        """

get_qubit_operands() abstractmethod

Get the qubit operands of the Gate.

Returns:

Type Description
list[Qubit]

List of qubits on which the Gate operates.

Source code in opensquirrel\ir.py
@abstractmethod
def get_qubit_operands(self) -> list[Qubit]:
    """Get the qubit operands of the Gate.

    Returns:
        List of qubits on which the Gate operates.
    """

is_identity() abstractmethod

Check whether the Gate is an identity Gate.

Returns:

Type Description
bool

Boolean value stating whether the Gate is an identity Gate.

Source code in opensquirrel\ir.py
@abstractmethod
def is_identity(self) -> bool:
    """Check whether the Gate is an identity Gate.

    Returns:
        Boolean value stating whether the Gate is an identity Gate.
    """