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


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