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

Removing ParamObj.__getattr__() #523

Merged
merged 3 commits into from
May 22, 2023
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
15 changes: 2 additions & 13 deletions pulser-core/pulser/parametrized/paramobj.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,13 +235,13 @@ def class_to_dict(cls: Callable) -> dict[str, Any]:
return obj_to_dict(self, cls_dict, *args, **self.kwargs)

def _to_abstract_repr(self) -> dict[str, Any]:
op_name = self.cls.__name__
if isinstance(self.cls, Parametrized):
raise ValueError(
"Serialization of calls to parametrized objects is not "
"supported."
)
elif (
op_name = self.cls.__name__
if (
self.args # If it is a classmethod the first arg will be the class
and hasattr(self.args[0], op_name)
and inspect.isfunction(self.cls)
Expand Down Expand Up @@ -344,17 +344,6 @@ def __call__(self, *args: Any, **kwargs: Any) -> ParamObj:
)
return obj

def __getattr__(self, name: str) -> ParamObj:
if hasattr(self.cls, name):
warnings.warn(
"Serialization of 'getattr' calls to parametrized objects "
"is not supported, so this object can't be serialized.",
stacklevel=2,
)
return ParamObj(getattr, self, name)
else:
raise AttributeError(f"No attribute named '{name}' in {self}.")

def __str__(self) -> str:
args = [str(a) for a in self.args]
kwargs = [f"{key}={str(value)}" for key, value in self.kwargs.items()]
Expand Down
10 changes: 2 additions & 8 deletions tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,11 +137,11 @@ def test_rare_cases(patch_plt_show):

wf = BlackmanWaveform(var * 100 // 10, var)
with pytest.warns(
UserWarning, match="Serialization of 'getattr'"
UserWarning, match="Calls to methods of parametrized objects"
), pytest.raises(
ValueError, match="Serialization of calls to parametrized objects"
):
s = encode(wf.draw())
s = encode(wf())
s = encode(wf)

with pytest.raises(ValueError, match="not encode a Sequence"):
Expand All @@ -155,12 +155,6 @@ def test_rare_cases(patch_plt_show):
var_ = wf_._variables["var"]
var_._assign(10)
assert wf_.build() == BlackmanWaveform(100, 10)
with pytest.warns(UserWarning, match="Serialization of 'getattr'"):
draw_func = wf_.draw
with pytest.warns(
UserWarning, match="Calls to methods of parametrized objects"
):
draw_func().build()

rotated_reg = parametrize(Register.rotate)(reg, var)
with pytest.raises(NotImplementedError):
Expand Down
71 changes: 49 additions & 22 deletions tests/test_parametrized.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,44 @@

import numpy as np
import pytest
from numpy.polynomial import Polynomial

from pulser import Pulse
from pulser.json.coders import PulserDecoder, PulserEncoder
from pulser.parametrized import Variable
from pulser.parametrized import ParamObj, Variable
from pulser.waveforms import BlackmanWaveform, CompositeWaveform

a = Variable("a", float)
b = Variable("b", int, size=2)
b._assign([-1.5, 1.5])
d = Variable("d", float, size=1)
d._assign([0.5])
t = Variable("t", int)
bwf = BlackmanWaveform(t, a)
pulse = Pulse.ConstantDetuning(bwf, b[0], b[1])
pulse2 = Pulse(bwf, bwf, 1)

@pytest.fixture
def a():
return Variable("a", float)

def test_var():

@pytest.fixture
def b():
b = Variable("b", int, size=2)
b._assign([-1.5, 1.5])
return b


@pytest.fixture
def d():
d = Variable("d", float, size=1)
d._assign([0.5])
return d


@pytest.fixture
def t():
return Variable("t", int)


@pytest.fixture
def bwf(t, a):
return BlackmanWaveform(t, a)


def test_var(a, b):
with pytest.raises(TypeError, match="'name' has to be of type 'str'"):
Variable(1, dtype=int)
with pytest.raises(TypeError, match="Invalid data type"):
Expand Down Expand Up @@ -62,17 +82,17 @@ def test_var():
with pytest.raises(ValueError, match="No value"):
a.build()

d = Variable("d", int, size=2)
d._assign([1, 2])
assert np.all(d.build() == np.array([1, 2]))
var_ = Variable("var_", int, size=2)
var_._assign([1, 2])
assert np.all(var_.build() == np.array([1, 2]))

with pytest.raises(TypeError, match="Invalid key type"):
b[[0, 1]]
with pytest.raises(IndexError):
b[2]


def test_varitem():
def test_varitem(a, b, d):
a0 = a[0]
b1 = b[1]
b01 = b[100::-1]
Expand All @@ -89,25 +109,32 @@ def test_varitem():
b1.key = 0


def test_paramobj():
def test_paramobj(bwf, t, a, b):
assert set(bwf.variables.keys()) == {"t", "a"}
pulse = Pulse.ConstantDetuning(bwf, b[0], b[1])
assert set(pulse.variables.keys()) == {"t", "a", "b"}
assert str(bwf) == "BlackmanWaveform(t, a)"
assert str(pulse) == f"Pulse.ConstantDetuning({str(bwf)}, b[0], b[1])"
pulse2 = Pulse(bwf, bwf, 1)
assert str(pulse2) == f"Pulse({str(bwf)}, {str(bwf)}, 1)"
with pytest.raises(AttributeError):
bwf._duration
with pytest.warns(UserWarning, match="Serialization of 'getattr'"):
time = bwf.duration
samps = bwf.samples
cwf = CompositeWaveform(bwf, bwf)
t._assign(1000)
a._assign(np.pi)
assert len(cwf.build().samples) == len(samps.build()) * 2
assert time.build() == 1000
assert len(cwf.build().samples) == len(bwf.build().samples) * 2
assert bwf.build().duration == 1000

param_poly = ParamObj(Polynomial, b)
with pytest.warns(
UserWarning, match="Calls to methods of parametrized objects"
):
origin = param_poly(0)
b._assign((0, 1))
assert origin.build() == 0.0


def test_opsupport():
def test_opsupport(a, b):
a._assign(-2.0)
u = 5 + a
u = b - u # u = [-4, -2]
Expand Down