Skip to content

[CQT-289] Avoid creating an Axis (0, 0, 0) #406

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions opensquirrel/ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,8 @@ def __init__(self, *axis: AxisLike) -> None:
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)
self._value = self.parse(axis_to_parse)
self._value = self.normalize(self._value)

@property
def value(self) -> NDArray[np.float64]:
Expand All @@ -228,10 +229,11 @@ def value(self, axis: AxisLike) -> None:
Args:
axis: An ``AxisLike`` to create the axis from.
"""
self._value = self._parse_and_validate_axislike(axis)
self._value = self.parse(axis)
self._value = self.normalize(self._value)

@classmethod
def _parse_and_validate_axislike(cls, axis: AxisLike) -> NDArray[np.float64]:
def parse(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.
Expand All @@ -255,10 +257,13 @@ def _parse_and_validate_axislike(cls, axis: AxisLike) -> NDArray[np.float64]:
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)
if np.any(axis != 0).item():
return axis
msg = "axis requires at least one element to be non-zero"
raise ValueError(msg)

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

Args:
Expand Down
62 changes: 60 additions & 2 deletions test/test_ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@

import numpy as np
import pytest
from numpy.typing import ArrayLike
from numpy.typing import NDArray

from opensquirrel import I
from opensquirrel.common import ATOL
from opensquirrel.ir import (
Axis,
AxisLike,
Bit,
BlochSphereRotation,
ControlledGate,
Expand Down Expand Up @@ -44,7 +45,7 @@ def test_axis_getter(self, axis: Axis) -> None:
(Axis(0, 1, 0), [0, 1, 0]),
],
)
def test_axis_setter_no_error(self, axis: Axis, new_axis: ArrayLike, expected_axis: ArrayLike) -> None:
def test_axis_setter_no_error(self, axis: Axis, new_axis: AxisLike, expected_axis: list[float]) -> None:
axis.value = new_axis # type: ignore[assignment]
np.testing.assert_array_equal(axis, expected_axis)

Expand Down Expand Up @@ -93,6 +94,63 @@ def test_eq_true(self, axis: Axis, other: Any) -> None:
def test_eq_false(self, axis: Axis, other: Any) -> None:
assert axis != other

@pytest.mark.parametrize(
("axis", "expected"),
[
([1, 0, 0], np.array([1, 0, 0], dtype=np.float64)),
([0, 0, 0], ValueError),
([1, 2], ValueError),
([1, 2, 3, 4], ValueError),
([0, 1, 0], np.array([0, 1, 0], dtype=np.float64)),
(["a", "b", "c"], TypeError),
],
)
def test_constructor(self, axis: AxisLike, expected: Any) -> None:
if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(expected):
Axis(axis)
else:
assert isinstance(expected, np.ndarray)
obj = Axis(axis)
np.testing.assert_array_equal(obj.value, expected)

@pytest.mark.parametrize(
("axis", "expected"),
[
([1, 0, 0], np.array([1, 0, 0], dtype=np.float64)),
([0, 0, 0], ValueError),
([1, 2], ValueError),
([1, 2, 3, 4], ValueError),
([0, 1, 0], np.array([0, 1, 0], dtype=np.float64)),
(["a", "b", "c"], TypeError),
],
)
def test_parser(self, axis: AxisLike, expected: Any) -> None:
if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(expected):
Axis.parse(axis)
else:
assert isinstance(expected, np.ndarray)
obj = Axis.parse(axis)
np.testing.assert_array_equal(obj, expected)

@pytest.mark.parametrize(
("axis", "expected"),
[
(np.array([1, 0, 0], dtype=np.float64), np.array([1, 0, 0], dtype=np.float64)),
(np.array([0, 1, 0], dtype=np.float64), np.array([0, 1, 0], dtype=np.float64)),
(np.array([0, 0, 1], dtype=np.float64), np.array([0, 0, 1], dtype=np.float64)),
(
np.array([1, 1, 1], dtype=np.float64),
np.array([1 / np.sqrt(3), 1 / np.sqrt(3), 1 / np.sqrt(3)], dtype=np.float64),
),
],
)
def test_normalize(self, axis: AxisLike, expected: NDArray[np.float64]) -> None:
obj = Axis.normalize(np.array(axis, dtype=np.float64))
assert isinstance(expected, np.ndarray)
np.testing.assert_array_almost_equal(obj, expected)


class TestIR:
def test_cnot_equality(self) -> None:
Expand Down
Loading