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.
Pint follows Numpy’s recommendation (NEP29) for minimal Numpy/Python versions support across the Scientific Python ecosystem. This ensures compatibility with other third party libraries (matplotlib, pandas, scipy).
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)
Cell In [1], line 5
2 import numpy as np
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)
Cell In [2], line 1
----> 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)
Cell In [3], line 1
----> 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)
Cell In [4], line 1
----> 1 print(legs1.to('kilometer'))
NameError: name 'legs1' is not defined
[5]:
print(legs1.dimensionality)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In [5], line 1
----> 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)
Cell In [6], line 2
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)
Cell In [6], line 3
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)
Cell In [7], line 1
----> 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)
Cell In [8], line 1
----> 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)
Cell In [9], line 1
----> 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)
Cell In [10], line 1
----> 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)
Cell In [11], line 2
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)
Cell In [11], line 3
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
,sign
,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)
Cell In [12], line 1
----> 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
, andVariable
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-pandasSeries
, as defined by PandasDataArray
,Dataset
, andVariable
, 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)
Cell In [13], line 1
----> 1 from graphviz import Digraph
3 g = Digraph(graph_attr={'size': '8,5'}, node_attr={'fontname': 'courier'})
4 g.edge('Dask array', 'NumPy 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)
Cell In [14], line 1
----> 1 import xarray as xr
3 # Load tutorial data
4 air = xr.tutorial.load_dataset('air_temperature')['air'][0]
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)
Cell In [15], line 1
----> 1 from sparse import COO
3 np.random.seed(80243963)
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)
Cell In [16], line 4
1 m = np.ma.masked_array([2, 3, 5, 7], mask=[False, True, False, True])
3 # Must create using Quantity class
----> 4 print(repr(ureg.Quantity(m, 'm')))
5 print()
7 # DO NOT create using multiplication until
8 # https://github.com/numpy/numpy/issues/15200 is resolved, as
9 # unexpected behavior may result
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)
Cell In [17], line 1
----> 1 import dask.array as da
3 d = da.arange(500, chunks=50)
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)
Cell In [18], line 1
----> 1 import dask.array as da
3 x = da.random.random((100, 100, 100), chunks=(100, 1, 1))
4 x[x < 0.95] = 0
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.