test_numpy_array.py
Go to the documentation of this file.
1 from __future__ import annotations
2 
3 import pytest
4 
5 import env # noqa: F401
6 from pybind11_tests import numpy_array as m
7 
8 np = pytest.importorskip("numpy")
9 
10 
12  # See issue #1328.
13  # - Platform-dependent sizes.
14  for size_check in m.get_platform_dtype_size_checks():
15  print(size_check)
16  assert size_check.size_cpp == size_check.size_numpy, size_check
17  # - Concrete sizes.
18  for check in m.get_concrete_dtype_checks():
19  print(check)
20  assert check.numpy == check.pybind11, check
21  if check.numpy.num != check.pybind11.num:
22  print(
23  f"NOTE: typenum mismatch for {check}: {check.numpy.num} != {check.pybind11.num}"
24  )
25 
26 
27 @pytest.fixture()
28 def arr():
29  return np.array([[1, 2, 3], [4, 5, 6]], "=u2")
30 
31 
33  a = np.array(0, "f8")
34  assert m.ndim(a) == 0
35  assert all(m.shape(a) == [])
36  assert all(m.strides(a) == [])
37  with pytest.raises(IndexError) as excinfo:
38  m.shape(a, 0)
39  assert str(excinfo.value) == "invalid axis: 0 (ndim = 0)"
40  with pytest.raises(IndexError) as excinfo:
41  m.strides(a, 0)
42  assert str(excinfo.value) == "invalid axis: 0 (ndim = 0)"
43  assert m.writeable(a)
44  assert m.size(a) == 1
45  assert m.itemsize(a) == 8
46  assert m.nbytes(a) == 8
47  assert m.owndata(a)
48 
49  a = np.array([[1, 2, 3], [4, 5, 6]], "u2").view()
50  a.flags.writeable = False
51  assert m.ndim(a) == 2
52  assert all(m.shape(a) == [2, 3])
53  assert m.shape(a, 0) == 2
54  assert m.shape(a, 1) == 3
55  assert all(m.strides(a) == [6, 2])
56  assert m.strides(a, 0) == 6
57  assert m.strides(a, 1) == 2
58  with pytest.raises(IndexError) as excinfo:
59  m.shape(a, 2)
60  assert str(excinfo.value) == "invalid axis: 2 (ndim = 2)"
61  with pytest.raises(IndexError) as excinfo:
62  m.strides(a, 2)
63  assert str(excinfo.value) == "invalid axis: 2 (ndim = 2)"
64  assert not m.writeable(a)
65  assert m.size(a) == 6
66  assert m.itemsize(a) == 2
67  assert m.nbytes(a) == 12
68  assert not m.owndata(a)
69 
70 
71 @pytest.mark.parametrize(
72  ("args", "ret"), [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)]
73 )
74 def test_index_offset(arr, args, ret):
75  assert m.index_at(arr, *args) == ret
76  assert m.index_at_t(arr, *args) == ret
77  assert m.offset_at(arr, *args) == ret * arr.dtype.itemsize
78  assert m.offset_at_t(arr, *args) == ret * arr.dtype.itemsize
79 
80 
82  for func in (
83  m.index_at,
84  m.index_at_t,
85  m.offset_at,
86  m.offset_at_t,
87  m.data,
88  m.data_t,
89  m.mutate_data,
90  m.mutate_data_t,
91  ):
92  with pytest.raises(IndexError) as excinfo:
93  func(arr, 1, 2, 3)
94  assert str(excinfo.value) == "too many indices for an array: 3 (ndim = 2)"
95 
96 
97 @pytest.mark.parametrize(
98  ("args", "ret"),
99  [
100  ([], [1, 2, 3, 4, 5, 6]),
101  ([1], [4, 5, 6]),
102  ([0, 1], [2, 3, 4, 5, 6]),
103  ([1, 2], [6]),
104  ],
105 )
106 def test_data(arr, args, ret):
107  from sys import byteorder
108 
109  assert all(m.data_t(arr, *args) == ret)
110  assert all(m.data(arr, *args)[(0 if byteorder == "little" else 1) :: 2] == ret)
111  assert all(m.data(arr, *args)[(1 if byteorder == "little" else 0) :: 2] == 0)
112 
113 
114 @pytest.mark.parametrize("dim", [0, 1, 3])
115 def test_at_fail(arr, dim):
116  for func in m.at_t, m.mutate_at_t:
117  with pytest.raises(IndexError) as excinfo:
118  func(arr, *([0] * dim))
119  assert str(excinfo.value) == f"index dimension mismatch: {dim} (ndim = 2)"
120 
121 
122 def test_at(arr):
123  assert m.at_t(arr, 0, 2) == 3
124  assert m.at_t(arr, 1, 0) == 4
125 
126  assert all(m.mutate_at_t(arr, 0, 2).ravel() == [1, 2, 4, 4, 5, 6])
127  assert all(m.mutate_at_t(arr, 1, 0).ravel() == [1, 2, 4, 5, 5, 6])
128 
129 
131  arr.flags.writeable = False
132  for func, args in (
133  (m.mutate_data, ()),
134  (m.mutate_data_t, ()),
135  (m.mutate_at_t, (0, 0)),
136  ):
137  with pytest.raises(ValueError) as excinfo:
138  func(arr, *args)
139  assert str(excinfo.value) == "array is not writeable"
140 
141 
143  assert all(m.mutate_data(arr).ravel() == [2, 4, 6, 8, 10, 12])
144  assert all(m.mutate_data(arr).ravel() == [4, 8, 12, 16, 20, 24])
145  assert all(m.mutate_data(arr, 1).ravel() == [4, 8, 12, 32, 40, 48])
146  assert all(m.mutate_data(arr, 0, 1).ravel() == [4, 16, 24, 64, 80, 96])
147  assert all(m.mutate_data(arr, 1, 2).ravel() == [4, 16, 24, 64, 80, 192])
148 
149  assert all(m.mutate_data_t(arr).ravel() == [5, 17, 25, 65, 81, 193])
150  assert all(m.mutate_data_t(arr).ravel() == [6, 18, 26, 66, 82, 194])
151  assert all(m.mutate_data_t(arr, 1).ravel() == [6, 18, 26, 67, 83, 195])
152  assert all(m.mutate_data_t(arr, 0, 1).ravel() == [6, 19, 27, 68, 84, 196])
153  assert all(m.mutate_data_t(arr, 1, 2).ravel() == [6, 19, 27, 68, 84, 197])
154 
155 
157  for func in (
158  m.index_at,
159  m.index_at_t,
160  m.data,
161  m.data_t,
162  m.mutate_data,
163  m.mutate_data_t,
164  m.at_t,
165  m.mutate_at_t,
166  ):
167  with pytest.raises(IndexError) as excinfo:
168  func(arr, 2, 0)
169  assert str(excinfo.value) == "index 2 is out of bounds for axis 0 with size 2"
170  with pytest.raises(IndexError) as excinfo:
171  func(arr, 0, 4)
172  assert str(excinfo.value) == "index 4 is out of bounds for axis 1 with size 3"
173 
174 
176  assert m.make_c_array().flags.c_contiguous
177  assert not m.make_c_array().flags.f_contiguous
178  assert m.make_f_array().flags.f_contiguous
179  assert not m.make_f_array().flags.c_contiguous
180 
181 
183  m.make_empty_shaped_array()
184 
185  # empty shape means numpy scalar, PEP 3118
186  assert m.scalar_int().ndim == 0
187  assert m.scalar_int().shape == ()
188  assert m.scalar_int() == 42
189 
190 
191 def test_wrap():
192  def assert_references(a, b, base=None):
193  if base is None:
194  base = a
195  assert a is not b
196  assert a.__array_interface__["data"][0] == b.__array_interface__["data"][0]
197  assert a.shape == b.shape
198  assert a.strides == b.strides
199  assert a.flags.c_contiguous == b.flags.c_contiguous
200  assert a.flags.f_contiguous == b.flags.f_contiguous
201  assert a.flags.writeable == b.flags.writeable
202  assert a.flags.aligned == b.flags.aligned
203  assert a.flags.writebackifcopy == b.flags.writebackifcopy
204  assert np.all(a == b)
205  assert not b.flags.owndata
206  assert b.base is base
207  if a.flags.writeable and a.ndim == 2:
208  a[0, 0] = 1234
209  assert b[0, 0] == 1234
210 
211  a1 = np.array([1, 2], dtype=np.int16)
212  assert a1.flags.owndata
213  assert a1.base is None
214  a2 = m.wrap(a1)
215  assert_references(a1, a2)
216 
217  a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order="F")
218  assert a1.flags.owndata
219  assert a1.base is None
220  a2 = m.wrap(a1)
221  assert_references(a1, a2)
222 
223  a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order="C")
224  a1.flags.writeable = False
225  a2 = m.wrap(a1)
226  assert_references(a1, a2)
227 
228  a1 = np.random.random((4, 4, 4))
229  a2 = m.wrap(a1)
230  assert_references(a1, a2)
231 
232  a1t = a1.transpose()
233  a2 = m.wrap(a1t)
234  assert_references(a1t, a2, a1)
235 
236  a1d = a1.diagonal()
237  a2 = m.wrap(a1d)
238  assert_references(a1d, a2, a1)
239 
240  a1m = a1[::-1, ::-1, ::-1]
241  a2 = m.wrap(a1m)
242  assert_references(a1m, a2, a1)
243 
244 
245 def test_numpy_view(capture):
246  with capture:
247  ac = m.ArrayClass()
248  ac_view_1 = ac.numpy_view()
249  ac_view_2 = ac.numpy_view()
250  assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32))
251  del ac
252  pytest.gc_collect()
253  assert (
254  capture
255  == """
256  ArrayClass()
257  ArrayClass::numpy_view()
258  ArrayClass::numpy_view()
259  """
260  )
261  ac_view_1[0] = 4
262  ac_view_1[1] = 3
263  assert ac_view_2[0] == 4
264  assert ac_view_2[1] == 3
265  with capture:
266  del ac_view_1
267  del ac_view_2
268  pytest.gc_collect()
269  pytest.gc_collect()
270  assert (
271  capture
272  == """
273  ~ArrayClass()
274  """
275  )
276 
277 
279  m.function_taking_uint64(123)
280  m.function_taking_uint64(np.uint64(123))
281 
282 
284  assert m.isinstance_untyped(np.array([1, 2, 3]), "not an array")
285  assert m.isinstance_typed(np.array([1.0, 2.0, 3.0]))
286 
287 
289  defaults = m.default_constructors()
290  for a in defaults.values():
291  assert a.size == 0
292  assert defaults["array"].dtype == np.array([]).dtype
293  assert defaults["array_t<int32>"].dtype == np.int32
294  assert defaults["array_t<double>"].dtype == np.float64
295 
296  results = m.converting_constructors([1, 2, 3])
297  for a in results.values():
298  np.testing.assert_array_equal(a, [1, 2, 3])
299  assert results["array"].dtype == np.dtype(int)
300  assert results["array_t<int32>"].dtype == np.int32
301  assert results["array_t<double>"].dtype == np.float64
302 
303 
305  # Exact overload matches:
306  assert m.overloaded(np.array([1], dtype="float64")) == "double"
307  assert m.overloaded(np.array([1], dtype="float32")) == "float"
308  assert m.overloaded(np.array([1], dtype="ushort")) == "unsigned short"
309  assert m.overloaded(np.array([1], dtype="intc")) == "int"
310  assert m.overloaded(np.array([1], dtype="longlong")) == "long long"
311  assert m.overloaded(np.array([1], dtype="complex")) == "double complex"
312  assert m.overloaded(np.array([1], dtype="csingle")) == "float complex"
313 
314  # No exact match, should call first convertible version:
315  assert m.overloaded(np.array([1], dtype="uint8")) == "double"
316 
317  with pytest.raises(TypeError) as excinfo:
318  m.overloaded("not an array")
319  assert (
320  msg(excinfo.value)
321  == """
322  overloaded(): incompatible function arguments. The following argument types are supported:
323  1. (arg0: numpy.ndarray[numpy.float64]) -> str
324  2. (arg0: numpy.ndarray[numpy.float32]) -> str
325  3. (arg0: numpy.ndarray[numpy.int32]) -> str
326  4. (arg0: numpy.ndarray[numpy.uint16]) -> str
327  5. (arg0: numpy.ndarray[numpy.int64]) -> str
328  6. (arg0: numpy.ndarray[numpy.complex128]) -> str
329  7. (arg0: numpy.ndarray[numpy.complex64]) -> str
330 
331  Invoked with: 'not an array'
332  """
333  )
334 
335  assert m.overloaded2(np.array([1], dtype="float64")) == "double"
336  assert m.overloaded2(np.array([1], dtype="float32")) == "float"
337  assert m.overloaded2(np.array([1], dtype="complex64")) == "float complex"
338  assert m.overloaded2(np.array([1], dtype="complex128")) == "double complex"
339  assert m.overloaded2(np.array([1], dtype="float32")) == "float"
340 
341  assert m.overloaded3(np.array([1], dtype="float64")) == "double"
342  assert m.overloaded3(np.array([1], dtype="intc")) == "int"
343  expected_exc = """
344  overloaded3(): incompatible function arguments. The following argument types are supported:
345  1. (arg0: numpy.ndarray[numpy.int32]) -> str
346  2. (arg0: numpy.ndarray[numpy.float64]) -> str
347 
348  Invoked with: """
349 
350  with pytest.raises(TypeError) as excinfo:
351  m.overloaded3(np.array([1], dtype="uintc"))
352  assert msg(excinfo.value) == expected_exc + repr(np.array([1], dtype="uint32"))
353  with pytest.raises(TypeError) as excinfo:
354  m.overloaded3(np.array([1], dtype="float32"))
355  assert msg(excinfo.value) == expected_exc + repr(np.array([1.0], dtype="float32"))
356  with pytest.raises(TypeError) as excinfo:
357  m.overloaded3(np.array([1], dtype="complex"))
358  assert msg(excinfo.value) == expected_exc + repr(np.array([1.0 + 0.0j]))
359 
360  # Exact matches:
361  assert m.overloaded4(np.array([1], dtype="double")) == "double"
362  assert m.overloaded4(np.array([1], dtype="longlong")) == "long long"
363  # Non-exact matches requiring conversion. Since float to integer isn't a
364  # save conversion, it should go to the double overload, but short can go to
365  # either (and so should end up on the first-registered, the long long).
366  assert m.overloaded4(np.array([1], dtype="float32")) == "double"
367  assert m.overloaded4(np.array([1], dtype="short")) == "long long"
368 
369  assert m.overloaded5(np.array([1], dtype="double")) == "double"
370  assert m.overloaded5(np.array([1], dtype="uintc")) == "unsigned int"
371  assert m.overloaded5(np.array([1], dtype="float32")) == "unsigned int"
372 
373 
375  """Tests fix for #685 - ndarray shouldn't go to std::string overload"""
376 
377  assert m.issue685("abc") == "string"
378  assert m.issue685(np.array([97, 98, 99], dtype="b")) == "array"
379  assert m.issue685(123) == "other"
380 
381 
383  z1 = np.array([[1, 2], [3, 4]], dtype="float64")
384  m.proxy_add2(z1, 10)
385  assert np.all(z1 == [[11, 12], [13, 14]])
386 
387  with pytest.raises(ValueError) as excinfo:
388  m.proxy_add2(np.array([1.0, 2, 3]), 5.0)
389  assert (
390  msg(excinfo.value) == "array has incorrect number of dimensions: 1; expected 2"
391  )
392 
393  expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype="int")
394  assert np.all(m.proxy_init3(3.0) == expect_c)
395  expect_f = np.transpose(expect_c)
396  assert np.all(m.proxy_init3F(3.0) == expect_f)
397 
398  assert m.proxy_squared_L2_norm(np.array(range(6))) == 55
399  assert m.proxy_squared_L2_norm(np.array(range(6), dtype="float64")) == 55
400 
401  assert m.proxy_auxiliaries2(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
402  assert m.proxy_auxiliaries2(z1) == m.array_auxiliaries2(z1)
403 
404  assert m.proxy_auxiliaries1_const_ref(z1[0, :])
405  assert m.proxy_auxiliaries2_const_ref(z1)
406 
407 
409  z1 = np.array([[1, 2], [3, 4]], dtype="float64")
410  m.proxy_add2_dyn(z1, 10)
411  assert np.all(z1 == [[11, 12], [13, 14]])
412 
413  expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype="int")
414  assert np.all(m.proxy_init3_dyn(3.0) == expect_c)
415 
416  assert m.proxy_auxiliaries2_dyn(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
417  assert m.proxy_auxiliaries2_dyn(z1) == m.array_auxiliaries2(z1)
418 
419 
421  with pytest.raises(ValueError) as excinfo:
422  m.array_fail_test()
423  assert str(excinfo.value) == "cannot create a pybind11::array from a nullptr"
424 
425  with pytest.raises(ValueError) as excinfo:
426  m.array_t_fail_test()
427  assert str(excinfo.value) == "cannot create a pybind11::array_t from a nullptr"
428 
429  with pytest.raises(ValueError) as excinfo:
430  m.array_fail_test_negative_size()
431  assert str(excinfo.value) == "negative dimensions are not allowed"
432 
433 
435  assert m.array_initializer_list1().shape == (1,)
436  assert m.array_initializer_list2().shape == (1, 2)
437  assert m.array_initializer_list3().shape == (1, 2, 3)
438  assert m.array_initializer_list4().shape == (1, 2, 3, 4)
439 
440 
442  a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype="float64")
443  m.array_reshape2(a)
444  assert a.size == 9
445  assert np.all(a == [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
446 
447  # total size change should succced with refcheck off
448  m.array_resize3(a, 4, False)
449  assert a.size == 64
450  # ... and fail with refcheck on
451  try:
452  m.array_resize3(a, 3, True)
453  except ValueError as e:
454  assert str(e).startswith("cannot resize an array") # noqa: PT017
455  # transposed array doesn't own data
456  b = a.transpose()
457  try:
458  m.array_resize3(b, 3, False)
459  except ValueError as e:
460  assert str(e).startswith( # noqa: PT017
461  "cannot resize this array: it does not own its data"
462  )
463  # ... but reshape should be fine
464  m.array_reshape2(b)
465  assert b.shape == (8, 8)
466 
467 
468 @pytest.mark.xfail("env.PYPY")
470  a = m.create_and_resize(2)
471  assert a.size == 4
472  assert np.all(a == 42.0)
473 
474 
476  a = np.ones(100 * 4).astype("uint8")
477  a_float_view = m.array_view(a, "float32")
478  assert a_float_view.shape == (100 * 1,) # 1 / 4 bytes = 8 / 32
479 
480  a_int16_view = m.array_view(a, "int16") # 1 / 2 bytes = 16 / 32
481  assert a_int16_view.shape == (100 * 2,)
482 
483 
485  a = np.ones(100 * 4).astype("uint8")
486  with pytest.raises(TypeError):
487  m.array_view(a, "deadly_dtype")
488 
489 
491  a = np.arange(2 * 7 * 3) + 1
492  x = m.reshape_initializer_list(a, 2, 7, 3)
493  assert x.shape == (2, 7, 3)
494  assert list(x[1][4]) == [34, 35, 36]
495  with pytest.raises(ValueError) as excinfo:
496  m.reshape_initializer_list(a, 1, 7, 3)
497  assert str(excinfo.value) == "cannot reshape array of size 42 into shape (1,7,3)"
498 
499 
501  a = np.arange(3 * 7 * 2) + 1
502  x = m.reshape_tuple(a, (3, 7, 2))
503  assert x.shape == (3, 7, 2)
504  assert list(x[1][4]) == [23, 24]
505  y = m.reshape_tuple(x, (x.size,))
506  assert y.shape == (42,)
507  with pytest.raises(ValueError) as excinfo:
508  m.reshape_tuple(a, (3, 7, 1))
509  assert str(excinfo.value) == "cannot reshape array of size 42 into shape (3,7,1)"
510  with pytest.raises(ValueError) as excinfo:
511  m.reshape_tuple(a, ())
512  assert str(excinfo.value) == "cannot reshape array of size 42 into shape ()"
513 
514 
516  a = m.index_using_ellipsis(np.zeros((5, 6, 7)))
517  assert a.shape == (6,)
518 
519 
520 @pytest.mark.parametrize(
521  "test_func",
522  [
523  m.test_fmt_desc_float,
524  m.test_fmt_desc_double,
525  m.test_fmt_desc_const_float,
526  m.test_fmt_desc_const_double,
527  ],
528 )
530  assert "numpy.ndarray[numpy.float" in test_func.__doc__
531 
532 
533 @pytest.mark.parametrize("forcecast", [False, True])
534 @pytest.mark.parametrize("contiguity", [None, "C", "F"])
535 @pytest.mark.parametrize("noconvert", [False, True])
536 @pytest.mark.filterwarnings(
537  "ignore:Casting complex values to real discards the imaginary part:"
538  + (
539  "numpy.exceptions.ComplexWarning"
540  if hasattr(np, "exceptions")
541  else "numpy.ComplexWarning"
542  )
543 )
544 def test_argument_conversions(forcecast, contiguity, noconvert):
545  function_name = "accept_double"
546  if contiguity == "C":
547  function_name += "_c_style"
548  elif contiguity == "F":
549  function_name += "_f_style"
550  if forcecast:
551  function_name += "_forcecast"
552  if noconvert:
553  function_name += "_noconvert"
554  function = getattr(m, function_name)
555 
556  for dtype in [np.dtype("float32"), np.dtype("float64"), np.dtype("complex128")]:
557  for order in ["C", "F"]:
558  for shape in [(2, 2), (1, 3, 1, 1), (1, 1, 1), (0,)]:
559  if not noconvert:
560  # If noconvert is not passed, only complex128 needs to be truncated and
561  # "cannot be safely obtained". So without `forcecast`, the argument shouldn't
562  # be accepted.
563  should_raise = dtype.name == "complex128" and not forcecast
564  else:
565  # If noconvert is passed, only float64 and the matching order is accepted.
566  # If at most one dimension has a size greater than 1, the array is also
567  # trivially contiguous.
568  trivially_contiguous = sum(1 for d in shape if d > 1) <= 1
569  should_raise = dtype.name != "float64" or (
570  contiguity is not None
571  and contiguity != order
572  and not trivially_contiguous
573  )
574 
575  array = np.zeros(shape, dtype=dtype, order=order)
576  if not should_raise:
577  function(array)
578  else:
579  with pytest.raises(
580  TypeError, match="incompatible function arguments"
581  ):
582  function(array)
583 
584 
585 @pytest.mark.xfail("env.PYPY")
587  from sys import getrefcount
588 
589  # Was np.float_ but that alias for float64 was removed in NumPy 2.
590  dtype = np.dtype(np.float64)
591  a = np.array([1], dtype=dtype)
592  before = getrefcount(dtype)
593  m.ndim(a)
594  after = getrefcount(dtype)
595  assert after == before
596 
597 
599  arr = np.zeros((), np.float64)
600  arr[()] = 37.2
601  assert m.round_trip_float(arr) == 37.2
602 
603 
604 # HINT: An easy and robust way (although only manual unfortunately) to check for
605 # ref-count leaks in the test_.*pyobject_ptr.* functions below is to
606 # * temporarily insert `while True:` (one-by-one),
607 # * run this test, and
608 # * run the Linux `top` command in another shell to visually monitor
609 # `RES` for a minute or two.
610 # If there is a leak, it is usually evident in seconds because the `RES`
611 # value increases without bounds. (Don't forget to Ctrl-C the test!)
612 
613 
614 # For use as a temporary user-defined object, to maximize sensitivity of the tests below:
615 # * Ref-count leaks will be immediately evident.
616 # * Sanitizers are much more likely to detect heap-use-after-free due to
617 # other ref-count bugs.
619  def __init__(self, value):
620  self.value = value
621 
622 
624  return [PyValueHolder(v) for v in values]
625 
626 
628  return [vh.value for vh in vhs]
629 
630 
632  # Intentionally all temporaries, do not change.
633  assert (
634  m.pass_array_pyobject_ptr_return_sum_str_values(
635  np.array(WrapWithPyValueHolder(-3, "four", 5.0), dtype=object)
636  )
637  == "-3four5.0"
638  )
639 
640 
642  # Intentionally all temporaries, do not change.
643  assert (
644  m.pass_array_pyobject_ptr_return_sum_str_values(
645  WrapWithPyValueHolder(2, "three", -4.0)
646  )
647  == "2three-4.0"
648  )
649 
650 
652  # Intentionally all temporaries, do not change.
653  assert UnwrapPyValueHolder(
654  m.pass_array_pyobject_ptr_return_as_list(
655  np.array(WrapWithPyValueHolder(-1, "two", 3.0), dtype=object)
656  )
657  ) == [-1, "two", 3.0]
658 
659 
660 @pytest.mark.parametrize(
661  ("return_array_pyobject_ptr", "unwrap"),
662  [
663  (m.return_array_pyobject_ptr_cpp_loop, list),
664  (m.return_array_pyobject_ptr_from_list, UnwrapPyValueHolder),
665  ],
666 )
667 def test_return_array_pyobject_ptr_cpp_loop(return_array_pyobject_ptr, unwrap):
668  # Intentionally all temporaries, do not change.
669  arr_from_list = return_array_pyobject_ptr(WrapWithPyValueHolder(6, "seven", -8.0))
670  assert isinstance(arr_from_list, np.ndarray)
671  assert arr_from_list.dtype == np.dtype("O")
672  assert unwrap(arr_from_list) == [6, "seven", -8.0]
test_numpy_array.test_index_offset
def test_index_offset(arr, args, ret)
Definition: test_numpy_array.py:74
Eigen::internal::print
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
Definition: NEON/PacketMath.h:3115
test_numpy_array.test_make_c_f_array
def test_make_c_f_array()
Definition: test_numpy_array.py:175
test_numpy_array.test_array_attributes
def test_array_attributes()
Definition: test_numpy_array.py:32
test_numpy_array.test_array_view
def test_array_view()
Definition: test_numpy_array.py:475
test_numpy_array.test_index_using_ellipsis
def test_index_using_ellipsis()
Definition: test_numpy_array.py:515
test_numpy_array.test_mutate_data
def test_mutate_data(arr)
Definition: test_numpy_array.py:142
test_numpy_array.test_wrap
def test_wrap()
Definition: test_numpy_array.py:191
test_numpy_array.test_dtypes
def test_dtypes()
Definition: test_numpy_array.py:11
test_numpy_array.test_array_failure
def test_array_failure()
Definition: test_numpy_array.py:420
list
Definition: pytypes.h:2166
test_numpy_array.test_numpy_view
def test_numpy_view(capture)
Definition: test_numpy_array.py:245
test_numpy_array.test_pass_array_pyobject_ptr_return_sum_str_values_ndarray
def test_pass_array_pyobject_ptr_return_sum_str_values_ndarray()
Definition: test_numpy_array.py:631
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:870
test_numpy_array.test_dim_check_fail
def test_dim_check_fail(arr)
Definition: test_numpy_array.py:81
getattr
object getattr(handle obj, handle name)
Definition: pytypes.h:890
unwrap
T unwrap(const mxArray *array)
Definition: matlab.h:256
test_numpy_array.PyValueHolder.__init__
def __init__(self, value)
Definition: test_numpy_array.py:619
test_numpy_array.test_initializer_list
def test_initializer_list()
Definition: test_numpy_array.py:434
test_numpy_array.test_mutate_readonly
def test_mutate_readonly(arr)
Definition: test_numpy_array.py:130
test_numpy_array.test_array_resize
def test_array_resize()
Definition: test_numpy_array.py:441
test_numpy_array.test_round_trip_float
def test_round_trip_float()
Definition: test_numpy_array.py:598
gtsam::range
Double_ range(const Point2_ &p, const Point2_ &q)
Definition: slam/expressions.h:30
test_numpy_array.test_reshape_tuple
def test_reshape_tuple()
Definition: test_numpy_array.py:500
view
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy y set format x g set format y g set format x2 g set format y2 g set format z g set angles radians set nogrid set key title set key left top Right noreverse box linetype linewidth samplen spacing width set nolabel set noarrow set nologscale set logscale x set set pointsize set encoding default set nopolar set noparametric set view
Definition: gnuplot_common_settings.hh:27
test_numpy_array.test_array_view_invalid
def test_array_view_invalid()
Definition: test_numpy_array.py:484
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:842
test_numpy_array.test_at
def test_at(arr)
Definition: test_numpy_array.py:122
test_numpy_array.test_pass_array_pyobject_ptr_return_as_list
def test_pass_array_pyobject_ptr_return_as_list()
Definition: test_numpy_array.py:651
Eigen::all
static const Eigen::internal::all_t all
Definition: IndexedViewHelper.h:171
test_numpy_array.test_constructors
def test_constructors()
Definition: test_numpy_array.py:288
test_numpy_array.test_array_unchecked_dyn_dims
def test_array_unchecked_dyn_dims()
Definition: test_numpy_array.py:408
test_numpy_array.test_format_descriptors_for_floating_point_types
def test_format_descriptors_for_floating_point_types(test_func)
Definition: test_numpy_array.py:529
test_numpy_array.test_bounds_check
def test_bounds_check(arr)
Definition: test_numpy_array.py:156
test_numpy_array.test_isinstance
def test_isinstance()
Definition: test_numpy_array.py:283
test_numpy_array.test_greedy_string_overload
def test_greedy_string_overload()
Definition: test_numpy_array.py:374
str
Definition: pytypes.h:1558
test_numpy_array.test_make_empty_shaped_array
def test_make_empty_shaped_array()
Definition: test_numpy_array.py:182
test_numpy_array.test_cast_numpy_int64_to_uint64
def test_cast_numpy_int64_to_uint64()
Definition: test_numpy_array.py:278
test_numpy_array.test_pass_array_pyobject_ptr_return_sum_str_values_list
def test_pass_array_pyobject_ptr_return_sum_str_values_list()
Definition: test_numpy_array.py:641
test_numpy_array.test_at_fail
def test_at_fail(arr, dim)
Definition: test_numpy_array.py:115
test_numpy_array.PyValueHolder
Definition: test_numpy_array.py:618
test_numpy_array.test_overload_resolution
def test_overload_resolution(msg)
Definition: test_numpy_array.py:304
test_numpy_array.test_data
def test_data(arr, args, ret)
Definition: test_numpy_array.py:106
test_numpy_array.test_reshape_initializer_list
def test_reshape_initializer_list()
Definition: test_numpy_array.py:490
test_numpy_array.test_array_create_and_resize
def test_array_create_and_resize()
Definition: test_numpy_array.py:469
test_numpy_array.PyValueHolder.value
value
Definition: test_numpy_array.py:620
test_numpy_array.UnwrapPyValueHolder
def UnwrapPyValueHolder(vhs)
Definition: test_numpy_array.py:627
function
Definition: pytypes.h:2252
test_numpy_array.WrapWithPyValueHolder
def WrapWithPyValueHolder(*values)
Definition: test_numpy_array.py:623
test_numpy_array.test_argument_conversions
def test_argument_conversions(forcecast, contiguity, noconvert)
Definition: test_numpy_array.py:544
test_numpy_array.test_dtype_refcount_leak
def test_dtype_refcount_leak()
Definition: test_numpy_array.py:586
test_numpy_array.test_array_unchecked_fixed_dims
def test_array_unchecked_fixed_dims(msg)
Definition: test_numpy_array.py:382
func
Definition: benchGeometry.cpp:23
test_numpy_array.arr
def arr()
Definition: test_numpy_array.py:28
test_numpy_array.test_return_array_pyobject_ptr_cpp_loop
def test_return_array_pyobject_ptr_cpp_loop(return_array_pyobject_ptr, unwrap)
Definition: test_numpy_array.py:667
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:6
repr
str repr(handle h)
Definition: pytypes.h:2467


gtsam
Author(s):
autogenerated on Sat Nov 16 2024 04:07:05