From 0461c404f77fe32ccdd3febe4229da3df89804bd Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Mon, 22 Feb 2021 18:52:06 +0100 Subject: [PATCH] numpy uses __array__ for casting avoids infinite loop of __init__, __getitem__, and shape. Found on https://github.com/scikit-hep/awkward-0.x/pull/26/commits/8cf07f6113aa9f78bbfa4d84fbec10135878500e --- python/damask/_configmaterial.py | 2 +- python/damask/_rotation.py | 11 ++++++++++- python/tests/test_Rotation.py | 10 +++++++++- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/python/damask/_configmaterial.py b/python/damask/_configmaterial.py index 70019e26e..1cda2e46b 100644 --- a/python/damask/_configmaterial.py +++ b/python/damask/_configmaterial.py @@ -248,7 +248,7 @@ class ConfigMaterial(Config): Examples -------- >>> import damask - >>> O = damask.Rotation.from_random(3).as_quaternion() + >>> O = damask.Rotation.from_random(3) >>> phase = ['Aluminum','Steel','Aluminum'] >>> m = damask.ConfigMaterial().material_add(constituents={'phase':phase,'O':O}, ... homogenization='SX') diff --git a/python/damask/_rotation.py b/python/damask/_rotation.py index 4109c181e..86311546e 100644 --- a/python/damask/_rotation.py +++ b/python/damask/_rotation.py @@ -125,9 +125,18 @@ class Rotation: return np.logical_not(self==other) + def __array__(self): + """Initializer for numpy.""" + return self.quaternion + + + @property + def size(self): + return self.quaternion[...,0].size + @property def shape(self): - return self.quaternion.shape[:-1] + return self.quaternion[...,0].shape def __len__(self): diff --git a/python/tests/test_Rotation.py b/python/tests/test_Rotation.py index 6bee44e7f..b28a849c5 100644 --- a/python/tests/test_Rotation.py +++ b/python/tests/test_Rotation.py @@ -689,6 +689,10 @@ class TestRotation: with pytest.raises(TypeError): Rotation(np.ones(3)) + def test_to_numpy(self): + r = Rotation.from_random(np.random.randint(0,10,4)) + assert np.all(r.as_quaternion() == np.array(r)) + @pytest.mark.parametrize('degrees',[True,False]) def test_Eulers(self,set_of_rotations,degrees): for rot in set_of_rotations: @@ -804,7 +808,11 @@ class TestRotation: r = Rotation.from_random() assert r == ~~r - @pytest.mark.parametrize('shape',[None,1,(1,),(4,2),(1,1,1)]) + @pytest.mark.parametrize('shape',[1,(1,),(4,2),(1,1,1),tuple(np.random.randint(0,10,4))]) + def test_size(self,shape): + assert Rotation.from_random(shape).size == np.prod(shape) + + @pytest.mark.parametrize('shape',[None,1,(1,),(4,2),(1,1,1),tuple(np.random.randint(0,10,4))]) def test_shape(self,shape): r = Rotation.from_random(shape=shape) assert r.shape == (shape if isinstance(shape,tuple) else (shape,) if shape else ())