Search code examples
pythonnumpyscalar

Instantiate scalar of custom structured dtype


I have defined a custom dtype. For example:

vec = np.dtype([('x', float), ('y', float), ('z', float)])
quat = np.dtype([('w', float), ('v', vec)])

Now I want to make a scalar quaternion:

quat((1.0, (0.0, 0.0, 0.0)))

I would expect that if anything, my tuple syntax is unacceptable. However, instead, I get the following error:

TypeError: 'numpy.dtype' object is not callable

The relevant portion of the documentation on scalars implies that it is possible to have a scalar of a structured type built like this in numpy.

How do instantiate a quat scalar? Is it even possible?

By the way, I've played with the following workaround:

np.array([(1.0, (0.0, 0.0, 0.0))], dtype=quat)

This does not produce an actual scalar (although it honestly works well enough for my purposes, making the question mostly theoretical). Calling item on the result returns a tuple, not a scalar quat object.


Solution

  • Calling item on your array produced a tuple because item is specifically designed to convert NumPy types to Python types. Indexing the array produces a NumPy scalar of type numpy.void:

    scalar = np.array([(1.0, (0.0, 0.0, 0.0))], dtype=quat)[0]