Skip to content
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

Replace Register.rotate() with Register.rotated() #639

Merged
merged 2 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
42 changes: 41 additions & 1 deletion pulser-core/pulser/register/register.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from __future__ import annotations

import json
import warnings
from collections.abc import Mapping
from typing import Any, Optional, Union, cast

Expand Down Expand Up @@ -283,10 +284,22 @@ def max_connectivity(
def rotate(self, degrees: float) -> None:
"""Rotates the array around the origin by the given angle.

Warning:
Deprecated in v0.17 in favour of `Register.rotated()`. To be
removed in v0.18.

Args:
degrees: The angle of rotation in degrees.
"""
# TODO: Deprecate
with warnings.catch_warnings():
warnings.simplefilter("always")
warnings.warn(
"'Register.rotate()' has been deprecated and will be "
"removed in v0.18. Consider using `Register.rotated()` "
"instead.",
category=DeprecationWarning,
stacklevel=2,
)
if self.layout is not None:
raise TypeError(
"A register defined from a RegisterLayout cannot be rotated."
Expand All @@ -297,6 +310,33 @@ def rotate(self, degrees: float) -> None:
)
object.__setattr__(self, "_coords", [rot @ v for v in self._coords])

def rotated(self, degrees: float) -> Register:
"""Makes a new rotated register.

All coordinates are rotated counter-clockwise around the origin.

Args:
degrees: The angle of rotation in degrees.

Returns:
Register: A new register rotated around the origin by the given
angle.
"""
theta = np.deg2rad(degrees)
rot = np.array(
[[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]
)
if self.layout is not None:
warnings.warn(
"The rotated register won't have an associated "
"'RegisterLayout'.",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps specify the category ? It's a Userwarning by default and it might never change

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also feel like there is a way to define the rotation for both layout and register, by defining a method get_rotated_coords(self, angle) in CoordsCollection (that would only work for 2D coords/rotate around phi=0 in 3D). But I guess it's not very interesting to rotate a register layout since it is obtained from calibration ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I doubt warnings.warn() will ever change the default warning category in Python 3.x, but I can still specify it.
As you suggested, register layouts should give a notion of being static so having an easy option to rotate them is not something we want to be giving the user imo

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes let's go with this PR !

stacklevel=2,
)

return Register(
dict(zip(self.qubit_ids, [rot @ v for v in self._coords]))
)

def draw(
self,
with_labels: bool = True,
Expand Down
7 changes: 5 additions & 2 deletions tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,11 @@ def test_rare_cases(patch_plt_show):
var_._assign(10)
assert wf_.build() == BlackmanWaveform(100, 10)

rotated_reg = parametrize(Register.rotate)(reg, var)
with pytest.raises(NotImplementedError):
rotated_reg = parametrize(Register.rotated)(reg, var)
with pytest.raises(
NotImplementedError,
match="Instance or static method serialization is not supported.",
):
encode(rotated_reg)


Expand Down
20 changes: 16 additions & 4 deletions tests/test_register.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
from unittest.mock import patch

import numpy as np
import pytest

import pulser
from pulser import Register, Register3D
from pulser.devices import DigitalAnalogDevice, MockDevice

Expand Down Expand Up @@ -273,9 +274,20 @@ def test_max_connectivity():

def test_rotation():
reg = Register.square(2, spacing=np.sqrt(2))
reg.rotate(45)
coords_ = np.array([(0, -1), (1, 0), (-1, 0), (0, 1)], dtype=float)
assert np.all(np.isclose(reg._coords, coords_))
rot_reg = reg.rotated(45)
new_coords_ = np.array([(0, -1), (1, 0), (-1, 0), (0, 1)], dtype=float)
np.testing.assert_allclose(rot_reg._coords, new_coords_, atol=1e-15)

assert rot_reg != reg

assert pulser.__version__ <= "0.18", "Remove 'Register.rotate()'."
with pytest.warns(
DeprecationWarning,
match=re.escape("'Register.rotate()' has been deprecated"),
):
reg.rotate(45)
assert np.all(np.isclose(reg._coords, new_coords_))
assert reg == rot_reg


draw_params = [
Expand Down
12 changes: 11 additions & 1 deletion tests/test_register_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,17 @@ def test_register_definition(layout, layout3d):
reg2d._validate_layout(layout, (0, 1))

with pytest.raises(TypeError, match="cannot be rotated"):
reg2d.rotate(30)
with pytest.warns(
DeprecationWarning,
match=re.escape("'Register.rotate()' has been deprecated"),
):
reg2d.rotate(30)

with pytest.warns(
UserWarning, match="won't have an associated 'RegisterLayout'"
):
rot_reg2d = reg2d.rotated(90)
assert rot_reg2d.layout is None


def test_draw(layout, layout3d, patch_plt_show):
Expand Down
7 changes: 3 additions & 4 deletions tutorials/creating_sequences.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"The `Register` class provides some useful features, like the ability to visualise the array and to rotate it."
"The `Register` class provides some useful features, like the ability to visualise the array and to make a rotated copy."
]
},
{
Expand All @@ -63,10 +63,9 @@
"metadata": {},
"outputs": [],
"source": [
"reg1 = Register(qubits) # Copy of 'reg' to keep the original intact\n",
"print(\"The original array:\")\n",
"reg1.draw()\n",
"reg1.rotate(45) # Rotate by 45 degrees\n",
"reg.draw()\n",
"reg1 = reg.rotated(45) # Rotate by 45 degrees\n",
"print(\"The rotated array:\")\n",
"reg1.draw()"
]
Expand Down
Loading