Handling numpy Object Arrays

Creation

pytools.obj_array.make_obj_array(res_list)[source]

Create a one-dimensional object array from res_list. This differs from numpy.array(res_list, dtype=object) by whether it tries to determine its shape by descending into nested array-like objects. Consider the following example:

>>> import numpy as np
>>> a = np.array([np.arange(5), np.arange(5)], dtype=object)
>>> a
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]], dtype=object)
>>> a.shape
(2, 5)
>>> # meanwhile:
>>> from pytools.obj_array import make_obj_array
>>> b = make_obj_array([np.arange(5), np.arange(5)])
>>> b
array([array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4])], dtype=object)
>>> b.shape
(2,)

In some settings (such as when the sub-arrays are large and/or live on a GPU), the recursive behavior of numpy.array() can be undesirable.

pytools.obj_array.flat_obj_array(*args)[source]

Return a one-dimensional flattened object array consisting of elements obtained by ‘flattening’ args as follows:

  • The first axis of any non-subclassed object arrays will be flattened into the result.

  • Instances of list will be flattened into the result.

  • Any other type will appear in the list as-is.

Mapping

pytools.obj_array.obj_array_vectorize(f, ary)[source]

Apply the function f to all entries of the object array ary. Return an object array of the same shape consisting of the return values. If ary is not an object array, return f(ary).

Note

This function exists because numpy.vectorize suffers from the same issue described under make_obj_array().

pytools.obj_array.obj_array_vectorize_n_args(f, *args)[source]

Apply the function f elementwise to all entries of any object arrays in args. All such object arrays are expected to have the same shape (but this is not checked). Equivalent to an appropriately-looped execution of:

result[idx] = f(obj_array_arg1[idx], arg2, obj_array_arg3[idx])

Return an object array of the same shape as the arguments consisting of the return values of f.

Note

This function exists because numpy.vectorize suffers from the same issue described under make_obj_array().

Numpy workarounds

These functions work around a long-standing, annoying numpy issue.

pytools.obj_array.obj_array_real(ary)[source]
pytools.obj_array.obj_array_imag(ary)[source]
pytools.obj_array.obj_array_real_copy(ary)[source]
pytools.obj_array.obj_array_imag_copy(ary)[source]