NumPy Support

The magnitude of a Pint quantity can be of any numerical scalar type, and you are free to choose it according to your needs. For numerical applications requiring arrays, it is quite convenient to use NumPy ndarray (or ndarray-like types supporting NEP-18), and therefore these are the array types supported by Pint.

First, we import the relevant packages:

[1]:
# Import NumPy
import numpy as np

# Import Pint
import pint
ureg = pint.UnitRegistry()
Q_ = ureg.Quantity

# Silence NEP 18 warning
import warnings
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    Q_([])
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-1-6f98795b295e> in <module>
      3
      4 # Import Pint
----> 5 import pint
      6 ureg = pint.UnitRegistry()
      7 Q_ = ureg.Quantity

ModuleNotFoundError: No module named 'pint'

and then we create a quantity the standard way

[2]:
legs1 = Q_(np.asarray([3., 4.]), 'meter')
print(legs1)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-7363f342a04f> in <module>
----> 1 legs1 = Q_(np.asarray([3., 4.]), 'meter')
      2 print(legs1)

NameError: name 'Q_' is not defined
[3]:
legs1 = [3., 4.] * ureg.meter
print(legs1)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-16e0b9566547> in <module>
----> 1 legs1 = [3., 4.] * ureg.meter
      2 print(legs1)

NameError: name 'ureg' is not defined

All usual Pint methods can be used with this quantity. For example:

[4]:
print(legs1.to('kilometer'))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-d5f27d177bea> in <module>
----> 1 print(legs1.to('kilometer'))

NameError: name 'legs1' is not defined
[5]:
print(legs1.dimensionality)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-c3d2e77fa53d> in <module>
----> 1 print(legs1.dimensionality)

NameError: name 'legs1' is not defined
[6]:
try:
    legs1.to('joule')
except pint.DimensionalityError as exc:
    print(exc)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-e6dd88127d37> in <module>
      1 try:
----> 2     legs1.to('joule')
      3 except pint.DimensionalityError as exc:

NameError: name 'legs1' is not defined

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-6-e6dd88127d37> in <module>
      1 try:
      2     legs1.to('joule')
----> 3 except pint.DimensionalityError as exc:
      4     print(exc)

NameError: name 'pint' is not defined

NumPy functions are supported by Pint. For example if we define:

[7]:
legs2 = [400., 300.] * ureg.centimeter
print(legs2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-5f80f0cca684> in <module>
----> 1 legs2 = [400., 300.] * ureg.centimeter
      2 print(legs2)

NameError: name 'ureg' is not defined

we can calculate the hypotenuse of the right triangles with legs1 and legs2.

[8]:
hyps = np.hypot(legs1, legs2)
print(hyps)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-62aafc3845eb> in <module>
----> 1 hyps = np.hypot(legs1, legs2)
      2 print(hyps)

NameError: name 'legs1' is not defined

Notice that before the np.hypot was used, the numerical value of legs2 was internally converted to the units of legs1 as expected.

Similarly, when you apply a function that expects angles in radians, a conversion is applied before the requested calculation:

[9]:
angles = np.arccos(legs2/hyps)
print(angles)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-30aa25a9e4c7> in <module>
----> 1 angles = np.arccos(legs2/hyps)
      2 print(angles)

NameError: name 'legs2' is not defined

You can convert the result to degrees using usual unit conversion:

[10]:
print(angles.to('degree'))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-5f6a2e25b384> in <module>
----> 1 print(angles.to('degree'))

NameError: name 'angles' is not defined

Applying a function that expects angles to a quantity with a different dimensionality results in an error:

[11]:
try:
    np.arccos(legs2)
except pint.DimensionalityError as exc:
    print(exc)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-4271dba2c4d5> in <module>
      1 try:
----> 2     np.arccos(legs2)
      3 except pint.DimensionalityError as exc:

NameError: name 'legs2' is not defined

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-11-4271dba2c4d5> in <module>
      1 try:
      2     np.arccos(legs2)
----> 3 except pint.DimensionalityError as exc:
      4     print(exc)

NameError: name 'pint' is not defined

Function/Method Support

The following ufuncs can be applied to a Quantity object:

  • Math operations: add, subtract, multiply, divide, logaddexp, logaddexp2, true_divide, floor_divide, negative, remainder, mod, fmod, absolute, rint, sign, conj, exp, exp2, log, log2, log10, expm1, log1p, sqrt, square, cbrt, reciprocal

  • Trigonometric functions: sin, cos, tan, arcsin, arccos, arctan, arctan2, hypot, sinh, cosh, tanh, arcsinh, arccosh, arctanh

  • Comparison functions: greater, greater_equal, less, less_equal, not_equal, equal

  • Floating functions: isreal, iscomplex, isfinite, isinf, isnan, signbit, copysign, nextafter, modf, ldexp, frexp, fmod, floor, ceil, trunc

And the following NumPy functions:

[12]:
from pint.numpy_func import HANDLED_FUNCTIONS
print(sorted(list(HANDLED_FUNCTIONS)))
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-12-59ce015c0c55> in <module>
----> 1 from pint.numpy_func import HANDLED_FUNCTIONS
      2 print(sorted(list(HANDLED_FUNCTIONS)))

ModuleNotFoundError: No module named 'pint'

And the following NumPy ndarray methods:

  • argmax, argmin, argsort, astype, clip, compress, conj, conjugate, cumprod, cumsum, diagonal, dot, fill, flatten, flatten, item, max, mean, min, nonzero, prod, ptp, put, ravel, repeat, reshape, round, searchsorted, sort, squeeze, std, sum, take, trace, transpose, var

Pull requests are welcome for any NumPy function, ufunc, or method that is not currently supported.

Array Type Support

Overview

When not wrapping a scalar type, a Pint Quantity can be considered a “duck array”, that is, an array-like type that implements (all or most of) NumPy’s API for ndarray. Many other such duck arrays exist in the Python ecosystem, and Pint aims to work with as many of them as reasonably possible. To date, the following are specifically tested and known to work:

  • xarray: DataArray, Dataset, and Variable

  • Sparse: COO

and the following have partial support, with full integration planned:

  • NumPy masked arrays (NOTE: Masked Array compatibility has changed with Pint 0.10 and versions of NumPy up to at least 1.18, see the example below)

  • Dask arrays

  • CuPy arrays

Technical Commentary

Starting with version 0.10, Pint aims to interoperate with other duck arrays in a well-defined and well-supported fashion. Part of this support lies in implementing `__array_ufunc__ to support NumPy ufuncs <https://numpy.org/neps/nep-0013-ufunc-overrides.html>`__ and `__array_function__ to support NumPy functions <https://numpy.org/neps/nep-0018-array-function-protocol.html>`__. However, the central component to this interoperability is respecting a type casting hierarchy of duck arrays. When all types in the hierarchy properly defer to those above it (in wrapping, arithmetic, and NumPy operations), a well-defined nesting and operator precedence order exists. When they don’t, the graph of relations becomes cyclic, and the expected result of mixed-type operations becomes ambiguous.

For Pint, following this hierarchy means declaring a list of types that are above it in the hierarchy and to which it defers (“upcast types”) and assuming all others are below it and wrappable by it (“downcast types”). To date, Pint’s declared upcast types are:

  • PintArray, as defined by pint-pandas

  • Series, as defined by Pandas

  • DataArray, Dataset, and Variable, as defined by xarray

(Note: if your application requires extension of this collection of types, it is available in Pint’s API at pint.compat.upcast_types.)

While Pint assumes it can wrap any other duck array (meaning, for now, those that implement __array_function__, shape, ndim, and dtype, at least until NEP 30 is implemented), there are a few common types that Pint explicitly tests (or plans to test) for optimal interoperability. These are listed above in the overview section and included in the below chart.

This type casting hierarchy of ndarray-like types can be shown by the below acyclic graph, where solid lines represent declared support, and dashed lines represent planned support:

[13]:
from graphviz import Digraph

g = Digraph(graph_attr={'size': '8,5'}, node_attr={'fontname': 'courier'})
g.edge('Dask array', 'NumPy ndarray')
g.edge('Dask array', 'CuPy ndarray')
g.edge('Dask array', 'Sparse COO')
g.edge('Dask array', 'NumPy masked array', style='dashed')
g.edge('CuPy ndarray', 'NumPy ndarray')
g.edge('Sparse COO', 'NumPy ndarray')
g.edge('NumPy masked array', 'NumPy ndarray')
g.edge('Jax array', 'NumPy ndarray')
g.edge('Pint Quantity', 'Dask array', style='dashed')
g.edge('Pint Quantity', 'NumPy ndarray')
g.edge('Pint Quantity', 'CuPy ndarray', style='dashed')
g.edge('Pint Quantity', 'Sparse COO')
g.edge('Pint Quantity', 'NumPy masked array', style='dashed')
g.edge('xarray Dataset/DataArray/Variable', 'Dask array')
g.edge('xarray Dataset/DataArray/Variable', 'CuPy ndarray', style='dashed')
g.edge('xarray Dataset/DataArray/Variable', 'Sparse COO')
g.edge('xarray Dataset/DataArray/Variable', 'NumPy ndarray')
g.edge('xarray Dataset/DataArray/Variable', 'NumPy masked array', style='dashed')
g.edge('xarray Dataset/DataArray/Variable', 'Pint Quantity')
g.edge('xarray Dataset/DataArray/Variable', 'Jax array', style='dashed')
g
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-13-d9d5624d9e63> in <module>
----> 1 from graphviz import Digraph
      2
      3 g = Digraph(graph_attr={'size': '8,5'}, node_attr={'fontname': 'courier'})
      4 g.edge('Dask array', 'NumPy ndarray')
      5 g.edge('Dask array', 'CuPy ndarray')

ModuleNotFoundError: No module named 'graphviz'

Examples

xarray wrapping Pint Quantity

[14]:
import xarray as xr

# Load tutorial data
air = xr.tutorial.load_dataset('air_temperature')['air'][0]

# Convert to Quantity
air.data = Q_(air.data, air.attrs.pop('units', ''))

print(air)
print()
print(air.max())
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-14-a48ac4b8f0bf> in <module>
----> 1 import xarray as xr
      2
      3 # Load tutorial data
      4 air = xr.tutorial.load_dataset('air_temperature')['air'][0]
      5

ModuleNotFoundError: No module named 'xarray'

Pint Quantity wrapping Sparse COO

[15]:
from sparse import COO

np.random.seed(80243963)

x = np.random.random((100, 100, 100))
x[x < 0.9] = 0  # fill most of the array with zeros
s = COO(x)

q = s * ureg.m

print(q)
print()
print(np.mean(q))
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-15-0c71c397da63> in <module>
----> 1 from sparse import COO
      2
      3 np.random.seed(80243963)
      4
      5 x = np.random.random((100, 100, 100))

ModuleNotFoundError: No module named 'sparse'

Pint Quantity wrapping NumPy Masked Array

[16]:
m = np.ma.masked_array([2, 3, 5, 7], mask=[False, True, False, True])

# Must create using Quantity class
print(repr(ureg.Quantity(m, 'm')))
print()

# DO NOT create using multiplication until
# https://github.com/numpy/numpy/issues/15200 is resolved, as
# unexpected behavior may result
print(repr(m * ureg.m))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-16-2cecb13c1f57> in <module>
      2
      3 # Must create using Quantity class
----> 4 print(repr(ureg.Quantity(m, 'm')))
      5 print()
      6

NameError: name 'ureg' is not defined

Pint Quantity wrapping Dask Array

[17]:
import dask.array as da

d = da.arange(500, chunks=50)

# Must create using Quantity class, otherwise Dask will wrap Pint Quantity
q = ureg.Quantity(d, ureg.kelvin)

print(repr(q))
print()

# DO NOT create using multiplication on the right until
# https://github.com/dask/dask/issues/4583 is resolved, as
# unexpected behavior may result
print(repr(d * ureg.kelvin))
print(repr(ureg.kelvin * d))
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-17-6ec7e965f697> in <module>
----> 1 import dask.array as da
      2
      3 d = da.arange(500, chunks=50)
      4
      5 # Must create using Quantity class, otherwise Dask will wrap Pint Quantity

ModuleNotFoundError: No module named 'dask'

xarray wrapping Pint Quantity wrapping Dask array wrapping Sparse COO

[18]:
import dask.array as da

x = da.random.random((100, 100, 100), chunks=(100, 1, 1))
x[x < 0.95] = 0

data = xr.DataArray(
    Q_(x.map_blocks(COO), 'm'),
    dims=('z', 'y', 'x'),
    coords={
        'z': np.arange(100),
        'y': np.arange(100) - 50,
        'x': np.arange(100) * 1.5 - 20
    },
    name='test'
)

print(data)
print()
print(data.sel(x=125.5, y=-46).mean())
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-18-28ef792410dc> in <module>
----> 1 import dask.array as da
      2
      3 x = da.random.random((100, 100, 100), chunks=(100, 1, 1))
      4 x[x < 0.95] = 0
      5

ModuleNotFoundError: No module named 'dask'

Compatibility Packages

To aid in integration between various array types and Pint (such as by providing convenience methods), the following compatibility packages are available:

(Note: if you have developed a compatibility package for Pint, please submit a pull request to add it to this list!)

Additional Comments

What follows is a short discussion about how NumPy support is implemented in Pint’s Quantity Object.

For the supported functions, Pint expects certain units and attempts to convert the input (or inputs). For example, the argument of the exponential function (numpy.exp) must be dimensionless. Units will be simplified (converting the magnitude appropriately) and numpy.exp will be applied to the resulting magnitude. If the input is not dimensionless, a DimensionalityError exception will be raised.

In some functions that take 2 or more arguments (e.g. arctan2), the second argument is converted to the units of the first. Again, a DimensionalityError exception will be raised if this is not possible. ndarray or downcast type arguments are generally treated as if they were dimensionless quantities, whereas Pint defers to its declared upcast types by always returning NotImplemented when they are encountered (see above).

To achive these function and ufunc overrides, Pint uses the __array_function__ and __array_ufunc__ protocols respectively, as recommened by NumPy. This means that functions and ufuncs that Pint does not explicitly handle will error, rather than return a value with units stripped (in contrast to Pint’s behavior prior to v0.10). For more information on these protocols, see https://docs.scipy.org/doc/numpy-1.17.0/user/basics.dispatch.html.

This behaviour introduces some performance penalties and increased memory usage. Quantities that must be converted to other units require additional memory and CPU cycles. Therefore, for numerically intensive code, you might want to convert the objects first and then use directly the magnitude, such as by using Pint’s wraps utility (see wrapping).

Attempting to access array interface protocol attributes (such as __array_struct__ and __array_interface__) on Pint Quantities will raise an AttributeError, since a Quantity is meant to behave as a “duck array,” and not a pure ndarray.