test_numpy_dtypes.py
Go to the documentation of this file.
1 import re
2 
3 import pytest
4 
5 import env # noqa: F401
6 from pybind11_tests import numpy_dtypes as m
7 
8 np = pytest.importorskip("numpy")
9 
10 
11 @pytest.fixture(scope="module")
13  ld = np.dtype("longdouble")
14  return np.dtype(
15  {
16  "names": ["bool_", "uint_", "float_", "ldbl_"],
17  "formats": ["?", "u4", "f4", f"f{ld.itemsize}"],
18  "offsets": [0, 4, 8, (16 if ld.alignment > 4 else 12)],
19  }
20  )
21 
22 
23 @pytest.fixture(scope="module")
25  return np.dtype([("bool_", "?"), ("uint_", "u4"), ("float_", "f4"), ("ldbl_", "g")])
26 
27 
28 def dt_fmt():
29  from sys import byteorder
30 
31  e = "<" if byteorder == "little" else ">"
32  return (
33  "{{'names':['bool_','uint_','float_','ldbl_'],"
34  "'formats':['?','" + e + "u4','" + e + "f4','" + e + "f{}'],"
35  "'offsets':[0,4,8,{}],'itemsize':{}}}"
36  )
37 
38 
40  ld = np.dtype("longdouble")
41  simple_ld_off = 12 + 4 * (ld.alignment > 4)
42  return dt_fmt().format(ld.itemsize, simple_ld_off, simple_ld_off + ld.itemsize)
43 
44 
46  from sys import byteorder
47 
48  return "[('bool_','?'),('uint_','{e}u4'),('float_','{e}f4'),('ldbl_','{e}f{}')]".format(
49  np.dtype("longdouble").itemsize, e="<" if byteorder == "little" else ">"
50  )
51 
52 
54  return (
55  12
56  + 4 * (np.dtype("uint64").alignment > 4)
57  + 8
58  + 8 * (np.dtype("longdouble").alignment > 8)
59  )
60 
61 
63  ld = np.dtype("longdouble")
64  partial_ld_off = partial_ld_offset()
65  partial_size = partial_ld_off + ld.itemsize
66  partial_end_padding = partial_size % np.dtype("uint64").alignment
67  return dt_fmt().format(
68  ld.itemsize, partial_ld_off, partial_size + partial_end_padding
69  )
70 
71 
73  ld = np.dtype("longdouble")
74  partial_nested_off = 8 + 8 * (ld.alignment > 8)
75  partial_ld_off = partial_ld_offset()
76  partial_size = partial_ld_off + ld.itemsize
77  partial_end_padding = partial_size % np.dtype("uint64").alignment
78  partial_nested_size = partial_nested_off * 2 + partial_size + partial_end_padding
79  return "{{'names':['a'],'formats':[{}],'offsets':[{}],'itemsize':{}}}".format(
80  partial_dtype_fmt(), partial_nested_off, partial_nested_size
81  )
82 
83 
84 def assert_equal(actual, expected_data, expected_dtype):
85  np.testing.assert_equal(actual, np.array(expected_data, dtype=expected_dtype))
86 
87 
89  with pytest.raises(RuntimeError) as excinfo:
90  m.get_format_unbound()
91  assert re.match(
92  "^NumPy type info missing for .*UnboundStruct.*$", str(excinfo.value)
93  )
94 
95  ld = np.dtype("longdouble")
96  ldbl_fmt = ("4x" if ld.alignment > 4 else "") + ld.char
97  ss_fmt = "^T{?:bool_:3xI:uint_:f:float_:" + ldbl_fmt + ":ldbl_:}"
98  dbl = np.dtype("double")
99  end_padding = ld.itemsize % np.dtype("uint64").alignment
100  partial_fmt = (
101  "^T{?:bool_:3xI:uint_:f:float_:"
102  + str(4 * (dbl.alignment > 4) + dbl.itemsize + 8 * (ld.alignment > 8))
103  + "xg:ldbl_:"
104  + (str(end_padding) + "x}" if end_padding > 0 else "}")
105  )
106  nested_extra = str(max(8, ld.alignment))
107  assert m.print_format_descriptors() == [
108  ss_fmt,
109  "^T{?:bool_:I:uint_:f:float_:g:ldbl_:}",
110  "^T{" + ss_fmt + ":a:^T{?:bool_:I:uint_:f:float_:g:ldbl_:}:b:}",
111  partial_fmt,
112  "^T{" + nested_extra + "x" + partial_fmt + ":a:" + nested_extra + "x}",
113  "^T{3s:a:3s:b:}",
114  "^T{(3)4s:a:(2)i:b:(3)B:c:1x(4, 2)f:d:}",
115  "^T{q:e1:B:e2:}",
116  "^T{Zf:cflt:Zd:cdbl:}",
117  ]
118 
119 
120 def test_dtype(simple_dtype):
121  from sys import byteorder
122 
123  e = "<" if byteorder == "little" else ">"
124 
125  assert [x.replace(" ", "") for x in m.print_dtypes()] == [
128  f"[('a',{simple_dtype_fmt()}),('b',{packed_dtype_fmt()})]",
131  "[('a','S3'),('b','S3')]",
132  (
133  "{'names':['a','b','c','d'],"
134  f"'formats':[('S4',(3,)),('{e}i4',(2,)),('u1',(3,)),('{e}f4',(4,2))],"
135  "'offsets':[0,12,20,24],'itemsize':56}"
136  ),
137  "[('e1','" + e + "i8'),('e2','u1')]",
138  "[('x','i1'),('y','" + e + "u8')]",
139  "[('cflt','" + e + "c8'),('cdbl','" + e + "c16')]",
140  ]
141 
142  d1 = np.dtype(
143  {
144  "names": ["a", "b"],
145  "formats": ["int32", "float64"],
146  "offsets": [1, 10],
147  "itemsize": 20,
148  }
149  )
150  d2 = np.dtype([("a", "i4"), ("b", "f4")])
151  assert m.test_dtype_ctors() == [
152  np.dtype("int32"),
153  np.dtype("float64"),
154  np.dtype("bool"),
155  d1,
156  d1,
157  np.dtype("uint32"),
158  d2,
159  np.dtype("d"),
160  ]
161 
162  assert m.test_dtype_methods() == [
163  np.dtype("int32"),
164  simple_dtype,
165  False,
166  True,
167  np.dtype("int32").itemsize,
168  simple_dtype.itemsize,
169  ]
170 
171  assert m.trailing_padding_dtype() == m.buffer_to_dtype(
172  np.zeros(1, m.trailing_padding_dtype())
173  )
174 
175  expected_chars = "bhilqBHILQefdgFDG?MmO"
176  assert m.test_dtype_kind() == list("iiiiiuuuuuffffcccbMmO")
177  assert m.test_dtype_char_() == list(expected_chars)
178  assert m.test_dtype_num() == [np.dtype(ch).num for ch in expected_chars]
179  assert m.test_dtype_byteorder() == [np.dtype(ch).byteorder for ch in expected_chars]
180  assert m.test_dtype_alignment() == [np.dtype(ch).alignment for ch in expected_chars]
181  assert m.test_dtype_flags() == [chr(np.dtype(ch).flags) for ch in expected_chars]
182 
183 
184 def test_recarray(simple_dtype, packed_dtype):
185  elements = [(False, 0, 0.0, -0.0), (True, 1, 1.5, -2.5), (False, 2, 3.0, -5.0)]
186 
187  for func, dtype in [
188  (m.create_rec_simple, simple_dtype),
189  (m.create_rec_packed, packed_dtype),
190  ]:
191  arr = func(0)
192  assert arr.dtype == dtype
193  assert_equal(arr, [], simple_dtype)
194  assert_equal(arr, [], packed_dtype)
195 
196  arr = func(3)
197  assert arr.dtype == dtype
198  assert_equal(arr, elements, simple_dtype)
199  assert_equal(arr, elements, packed_dtype)
200 
201  # Show what recarray's look like in NumPy.
202  assert type(arr[0]) == np.void
203  assert type(arr[0].item()) == tuple
204 
205  if dtype == simple_dtype:
206  assert m.print_rec_simple(arr) == [
207  "s:0,0,0,-0",
208  "s:1,1,1.5,-2.5",
209  "s:0,2,3,-5",
210  ]
211  else:
212  assert m.print_rec_packed(arr) == [
213  "p:0,0,0,-0",
214  "p:1,1,1.5,-2.5",
215  "p:0,2,3,-5",
216  ]
217 
218  nested_dtype = np.dtype([("a", simple_dtype), ("b", packed_dtype)])
219 
220  arr = m.create_rec_nested(0)
221  assert arr.dtype == nested_dtype
222  assert_equal(arr, [], nested_dtype)
223 
224  arr = m.create_rec_nested(3)
225  assert arr.dtype == nested_dtype
226  assert_equal(
227  arr,
228  [
229  ((False, 0, 0.0, -0.0), (True, 1, 1.5, -2.5)),
230  ((True, 1, 1.5, -2.5), (False, 2, 3.0, -5.0)),
231  ((False, 2, 3.0, -5.0), (True, 3, 4.5, -7.5)),
232  ],
233  nested_dtype,
234  )
235  assert m.print_rec_nested(arr) == [
236  "n:a=s:0,0,0,-0;b=p:1,1,1.5,-2.5",
237  "n:a=s:1,1,1.5,-2.5;b=p:0,2,3,-5",
238  "n:a=s:0,2,3,-5;b=p:1,3,4.5,-7.5",
239  ]
240 
241  arr = m.create_rec_partial(3)
242  assert str(arr.dtype).replace(" ", "") == partial_dtype_fmt()
243  partial_dtype = arr.dtype
244  assert "" not in arr.dtype.fields
245  assert partial_dtype.itemsize > simple_dtype.itemsize
246  assert_equal(arr, elements, simple_dtype)
247  assert_equal(arr, elements, packed_dtype)
248 
249  arr = m.create_rec_partial_nested(3)
250  assert str(arr.dtype).replace(" ", "") == partial_nested_fmt()
251  assert "" not in arr.dtype.fields
252  assert "" not in arr.dtype.fields["a"][0].fields
253  assert arr.dtype.itemsize > partial_dtype.itemsize
254  np.testing.assert_equal(arr["a"], m.create_rec_partial(3))
255 
256 
258  data = np.arange(1, 7, dtype="int32")
259  for i in range(8):
260  np.testing.assert_array_equal(m.test_array_ctors(10 + i), data.reshape((3, 2)))
261  np.testing.assert_array_equal(m.test_array_ctors(20 + i), data.reshape((3, 2)))
262  for i in range(5):
263  np.testing.assert_array_equal(m.test_array_ctors(30 + i), data)
264  np.testing.assert_array_equal(m.test_array_ctors(40 + i), data)
265 
266 
268  arr = m.create_string_array(True)
269  assert str(arr.dtype) == "[('a', 'S3'), ('b', 'S3')]"
270  assert m.print_string_array(arr) == [
271  "a='',b=''",
272  "a='a',b='a'",
273  "a='ab',b='ab'",
274  "a='abc',b='abc'",
275  ]
276  dtype = arr.dtype
277  assert arr["a"].tolist() == [b"", b"a", b"ab", b"abc"]
278  assert arr["b"].tolist() == [b"", b"a", b"ab", b"abc"]
279  arr = m.create_string_array(False)
280  assert dtype == arr.dtype
281 
282 
284  from sys import byteorder
285 
286  e = "<" if byteorder == "little" else ">"
287 
288  arr = m.create_array_array(3)
289  assert str(arr.dtype).replace(" ", "") == (
290  "{'names':['a','b','c','d'],"
291  f"'formats':[('S4',(3,)),('{e}i4',(2,)),('u1',(3,)),('{e}f4',(4,2))],"
292  "'offsets':[0,12,20,24],'itemsize':56}"
293  )
294  assert m.print_array_array(arr) == [
295  "a={{A,B,C,D},{K,L,M,N},{U,V,W,X}},b={0,1},"
296  "c={0,1,2},d={{0,1},{10,11},{20,21},{30,31}}",
297  "a={{W,X,Y,Z},{G,H,I,J},{Q,R,S,T}},b={1000,1001},"
298  "c={10,11,12},d={{100,101},{110,111},{120,121},{130,131}}",
299  "a={{S,T,U,V},{C,D,E,F},{M,N,O,P}},b={2000,2001},"
300  "c={20,21,22},d={{200,201},{210,211},{220,221},{230,231}}",
301  ]
302  assert arr["a"].tolist() == [
303  [b"ABCD", b"KLMN", b"UVWX"],
304  [b"WXYZ", b"GHIJ", b"QRST"],
305  [b"STUV", b"CDEF", b"MNOP"],
306  ]
307  assert arr["b"].tolist() == [[0, 1], [1000, 1001], [2000, 2001]]
308  assert m.create_array_array(0).dtype == arr.dtype
309 
310 
312  from sys import byteorder
313 
314  e = "<" if byteorder == "little" else ">"
315 
316  arr = m.create_enum_array(3)
317  dtype = arr.dtype
318  assert dtype == np.dtype([("e1", e + "i8"), ("e2", "u1")])
319  assert m.print_enum_array(arr) == ["e1=A,e2=X", "e1=B,e2=Y", "e1=A,e2=X"]
320  assert arr["e1"].tolist() == [-1, 1, -1]
321  assert arr["e2"].tolist() == [1, 2, 1]
322  assert m.create_enum_array(0).dtype == dtype
323 
324 
326  from sys import byteorder
327 
328  e = "<" if byteorder == "little" else ">"
329 
330  arr = m.create_complex_array(3)
331  dtype = arr.dtype
332  assert dtype == np.dtype([("cflt", e + "c8"), ("cdbl", e + "c16")])
333  assert m.print_complex_array(arr) == [
334  "c:(0,0.25),(0.5,0.75)",
335  "c:(1,1.25),(1.5,1.75)",
336  "c:(2,2.25),(2.5,2.75)",
337  ]
338  assert arr["cflt"].tolist() == [0.0 + 0.25j, 1.0 + 1.25j, 2.0 + 2.25j]
339  assert arr["cdbl"].tolist() == [0.5 + 0.75j, 1.5 + 1.75j, 2.5 + 2.75j]
340  assert m.create_complex_array(0).dtype == dtype
341 
342 
343 def test_signature(doc):
344  assert (
345  doc(m.create_rec_nested)
346  == "create_rec_nested(arg0: int) -> numpy.ndarray[NestedStruct]"
347  )
348 
349 
351  n = 3
352  arrays = [
353  m.create_rec_simple(n),
354  m.create_rec_packed(n),
355  m.create_rec_nested(n),
356  m.create_enum_array(n),
357  ]
358  funcs = [m.f_simple, m.f_packed, m.f_nested]
359 
360  for i, func in enumerate(funcs):
361  for j, arr in enumerate(arrays):
362  if i == j and i < 2:
363  assert [func(arr[k]) for k in range(n)] == [k * 10 for k in range(n)]
364  else:
365  with pytest.raises(TypeError) as excinfo:
366  func(arr[0])
367  assert "incompatible function arguments" in str(excinfo.value)
368 
369 
371  n = 3
372  array = m.create_rec_simple(n)
373  values = m.f_simple_vectorized(array)
374  np.testing.assert_array_equal(values, [0, 10, 20])
375  array_2 = m.f_simple_pass_thru_vectorized(array)
376  np.testing.assert_array_equal(array, array_2)
377 
378 
380  s = m.SimpleStruct()
381  assert s.astuple() == (False, 0, 0.0, 0.0)
382  assert m.SimpleStruct.fromtuple(s.astuple()).astuple() == s.astuple()
383 
384  s.uint_ = 2
385  assert m.f_simple(s) == 20
386 
387  # Try as recarray of shape==(1,).
388  s_recarray = np.array([(False, 2, 0.0, 0.0)], dtype=simple_dtype)
389  # Show that this will work for vectorized case.
390  np.testing.assert_array_equal(m.f_simple_vectorized(s_recarray), [20])
391 
392  # Show as a scalar that inherits from np.generic.
393  s_scalar = s_recarray[0]
394  assert isinstance(s_scalar, np.void)
395  assert m.f_simple(s_scalar) == 20
396 
397  # Show that an *array* scalar (np.ndarray.shape == ()) does not convert.
398  # More specifically, conversion to SimpleStruct is not implicit.
399  s_recarray_scalar = s_recarray.reshape(())
400  assert isinstance(s_recarray_scalar, np.ndarray)
401  assert s_recarray_scalar.dtype == simple_dtype
402  with pytest.raises(TypeError) as excinfo:
403  m.f_simple(s_recarray_scalar)
404  assert "incompatible function arguments" in str(excinfo.value)
405  # Explicitly convert to m.SimpleStruct.
406  assert m.f_simple(m.SimpleStruct.fromtuple(s_recarray_scalar.item())) == 20
407 
408  # Show that an array of dtype=object does *not* convert.
409  s_array_object = np.array([s])
410  assert s_array_object.dtype == object
411  with pytest.raises(TypeError) as excinfo:
412  m.f_simple_vectorized(s_array_object)
413  assert "incompatible function arguments" in str(excinfo.value)
414  # Explicitly convert to `np.array(..., dtype=simple_dtype)`
415  s_array = np.array([s.astuple()], dtype=simple_dtype)
416  np.testing.assert_array_equal(m.f_simple_vectorized(s_array), [20])
417 
418 
420  with pytest.raises(RuntimeError) as excinfo:
421  m.register_dtype()
422  assert "dtype is already registered" in str(excinfo.value)
423 
424 
425 @pytest.mark.xfail("env.PYPY")
427  from sys import getrefcount
428 
429  fmt = "f4"
430  pytest.gc_collect()
431  start = getrefcount(fmt)
432  d = m.dtype_wrapper(fmt)
433  assert d is np.dtype("f4")
434  del d
435  pytest.gc_collect()
436  assert getrefcount(fmt) == start
437 
438 
440  assert all(m.compare_buffer_info())
test_numpy_dtypes.test_complex_array
def test_complex_array()
Definition: test_numpy_dtypes.py:325
test_numpy_dtypes.test_recarray
def test_recarray(simple_dtype, packed_dtype)
Definition: test_numpy_dtypes.py:184
test_numpy_dtypes.test_vectorize
def test_vectorize()
Definition: test_numpy_dtypes.py:370
format
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
Definition: openglsupport.cpp:226
test_numpy_dtypes.simple_dtype_fmt
def simple_dtype_fmt()
Definition: test_numpy_dtypes.py:39
list
Definition: pytypes.h:2124
test_numpy_dtypes.packed_dtype
def packed_dtype()
Definition: test_numpy_dtypes.py:24
test_numpy_dtypes.simple_dtype
def simple_dtype()
Definition: test_numpy_dtypes.py:12
test_numpy_dtypes.test_array_array
def test_array_array()
Definition: test_numpy_dtypes.py:283
test_numpy_dtypes.test_cls_and_dtype_conversion
def test_cls_and_dtype_conversion(simple_dtype)
Definition: test_numpy_dtypes.py:379
type
Definition: pytypes.h:1491
test_numpy_dtypes.partial_nested_fmt
def partial_nested_fmt()
Definition: test_numpy_dtypes.py:72
test_numpy_dtypes.test_register_dtype
def test_register_dtype()
Definition: test_numpy_dtypes.py:419
test_numpy_dtypes.partial_dtype_fmt
def partial_dtype_fmt()
Definition: test_numpy_dtypes.py:62
test_numpy_dtypes.dt_fmt
def dt_fmt()
Definition: test_numpy_dtypes.py:28
gtsam::range
Double_ range(const Point2_ &p, const Point2_ &q)
Definition: slam/expressions.h:30
test_numpy_dtypes.test_str_leak
def test_str_leak()
Definition: test_numpy_dtypes.py:426
doc
Annotation for documentation.
Definition: attr.h:45
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:825
Eigen::all
static const Eigen::internal::all_t all
Definition: IndexedViewHelper.h:171
test_numpy_dtypes.test_signature
def test_signature(doc)
Definition: test_numpy_dtypes.py:343
test_numpy_dtypes.test_dtype
def test_dtype(simple_dtype)
Definition: test_numpy_dtypes.py:120
test_numpy_dtypes.test_array_constructors
def test_array_constructors()
Definition: test_numpy_dtypes.py:257
test_numpy_dtypes.test_string_array
def test_string_array()
Definition: test_numpy_dtypes.py:267
test_numpy_dtypes.test_enum_array
def test_enum_array()
Definition: test_numpy_dtypes.py:311
test_numpy_dtypes.test_format_descriptors
def test_format_descriptors()
Definition: test_numpy_dtypes.py:88
str
Definition: pytypes.h:1524
test_numpy_dtypes.assert_equal
def assert_equal(actual, expected_data, expected_dtype)
Definition: test_numpy_dtypes.py:84
test_numpy_dtypes.partial_ld_offset
def partial_ld_offset()
Definition: test_numpy_dtypes.py:53
test_numpy_dtypes.test_scalar_conversion
def test_scalar_conversion()
Definition: test_numpy_dtypes.py:350
func
Definition: benchGeometry.cpp:23
max
#define max(a, b)
Definition: datatypes.h:20
test_numpy_dtypes.packed_dtype_fmt
def packed_dtype_fmt()
Definition: test_numpy_dtypes.py:45
test_numpy_dtypes.test_compare_buffer_info
def test_compare_buffer_info()
Definition: test_numpy_dtypes.py:439


gtsam
Author(s):
autogenerated on Tue Jun 25 2024 03:05:29