{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "NumPy Support\n", "=============\n", "\n", "The magnitude of a Pint quantity can be of any numerical scalar type, and you are free\n", "to choose it according to your needs. For numerical applications requiring arrays, it is\n", "quite convenient to use [NumPy ndarray](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html) (or [ndarray-like types supporting NEP-18](https://numpy.org/neps/nep-0018-array-function-protocol.html)),\n", "and therefore these are the array types supported by Pint.\n", "\n", "First, we import the relevant packages:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Import NumPy\n", "import numpy as np\n", "\n", "# Disable Pint's old fallback behavior (must come before importing Pint)\n", "import os\n", "os.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = \"0\"\n", "\n", "# Import Pint\n", "import pint\n", "ureg = pint.UnitRegistry()\n", "Q_ = ureg.Quantity\n", "\n", "# Silence NEP 18 warning\n", "import warnings\n", "with warnings.catch_warnings():\n", " warnings.simplefilter(\"ignore\")\n", " Q_([])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and then we create a quantity the standard way" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3.0 4.0] meter\n" ] } ], "source": [ "legs1 = Q_(np.asarray([3., 4.]), 'meter')\n", "print(legs1)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3.0 4.0] meter\n" ] } ], "source": [ "legs1 = [3., 4.] * ureg.meter\n", "print(legs1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All usual Pint methods can be used with this quantity. For example:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.003 0.004] kilometer\n" ] } ], "source": [ "print(legs1.to('kilometer'))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[length]\n" ] } ], "source": [ "print(legs1.dimensionality)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Cannot convert from 'meter' ([length]) to 'joule' ([length] ** 2 * [mass] / [time] ** 2)\n" ] } ], "source": [ "try:\n", " legs1.to('joule')\n", "except pint.DimensionalityError as exc:\n", " print(exc)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "NumPy functions are supported by Pint. For example if we define:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[400.0 300.0] centimeter\n" ] } ], "source": [ "legs2 = [400., 300.] * ureg.centimeter\n", "print(legs2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we can calculate the hypotenuse of the right triangles with legs1 and legs2." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[5.0 5.0] meter\n" ] } ], "source": [ "hyps = np.hypot(legs1, legs2)\n", "print(hyps)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that before the `np.hypot` was used, the numerical value of legs2 was\n", "internally converted to the units of legs1 as expected.\n", "\n", "Similarly, when you apply a function that expects angles in radians, a conversion\n", "is applied before the requested calculation:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.6435011087932843 0.9272952180016123] radian\n" ] } ], "source": [ "angles = np.arccos(legs2/hyps)\n", "print(angles)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can convert the result to degrees using usual unit conversion:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[36.86989764584401 53.13010235415599] degree\n" ] } ], "source": [ "print(angles.to('degree'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Applying a function that expects angles to a quantity with a different dimensionality\n", "results in an error:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Cannot convert from 'centimeter' ([length]) to 'dimensionless' (dimensionless)\n" ] } ], "source": [ "try:\n", " np.arccos(legs2)\n", "except pint.DimensionalityError as exc:\n", " print(exc)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Function/Method Support\n", "-----------------------\n", "\n", "The following [ufuncs](http://docs.scipy.org/doc/numpy/reference/ufuncs.html) can be applied to a Quantity object:\n", "\n", "- **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`\n", "- **Trigonometric functions**: `sin`, `cos`, `tan`, `arcsin`, `arccos`, `arctan`, `arctan2`, `hypot`, `sinh`, `cosh`, `tanh`, `arcsinh`, `arccosh`, `arctanh`\n", "- **Comparison functions**: `greater`, `greater_equal`, `less`, `less_equal`, `not_equal`, `equal`\n", "- **Floating functions**: `isreal`, `iscomplex`, `isfinite`, `isinf`, `isnan`, `signbit`, `copysign`, `nextafter`, `modf`, `ldexp`, `frexp`, `fmod`, `floor`, `ceil`, `trunc`\n", "\n", "And the following NumPy functions:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['alen', 'all', 'amax', 'amin', 'any', 'append', 'argmax', 'argmin', 'argsort', 'around', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'block', 'broadcast_to', 'clip', 'column_stack', 'compress', 'concatenate', 'copy', 'copyto', 'count_nonzero', 'cross', 'cumprod', 'cumproduct', 'cumsum', 'diagonal', 'diff', 'dot', 'dstack', 'ediff1d', 'einsum', 'empty_like', 'expand_dims', 'fix', 'flip', 'full_like', 'gradient', 'hstack', 'insert', 'interp', 'isclose', 'iscomplex', 'isin', 'isreal', 'linalg.solve', 'linspace', 'mean', 'median', 'meshgrid', 'moveaxis', 'nan_to_num', 'nanargmax', 'nanargmin', 'nancumprod', 'nancumsum', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanstd', 'nansum', 'nanvar', 'ndim', 'nonzero', 'ones_like', 'pad', 'percentile', 'ptp', 'ravel', 'reshape', 'resize', 'result_type', 'rollaxis', 'rot90', 'round_', 'searchsorted', 'shape', 'size', 'sort', 'squeeze', 'stack', 'std', 'sum', 'swapaxes', 'tile', 'transpose', 'trapz', 'trim_zeros', 'unwrap', 'var', 'vstack', 'where', 'zeros_like']\n" ] } ], "source": [ "from pint.numpy_func import HANDLED_FUNCTIONS\n", "print(sorted(list(HANDLED_FUNCTIONS)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And the following [NumPy ndarray methods](http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#array-methods):\n", "\n", "- `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`\n", "\n", "Pull requests are welcome for any NumPy function, ufunc, or method that is not currently\n", "supported.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Array Type Support\n", "------------------\n", "\n", "### Overview\n", "\n", "When not wrapping a scalar type, a Pint `Quantity` can be considered a [\"duck array\"](https://numpy.org/neps/nep-0022-ndarray-duck-typing-overview.html), 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:\n", "\n", "- xarray: `DataArray`, `Dataset`, and `Variable`\n", "- Sparse: `COO`\n", "\n", "and the following have partial support, with full integration planned:\n", "\n", "- 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)\n", "- Dask arrays\n", "- CuPy arrays\n", "\n", "### Technical Commentary\n", "\n", "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](https://numpy.org/neps/nep-0018-array-function-protocol.html) 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.\n", "\n", "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:\n", "\n", "- `PintArray`, as defined by pint-pandas\n", "- `Series`, as defined by Pandas\n", "- `DataArray`, `Dataset`, and `Variable`, as defined by xarray\n", "\n", "(Note: if your application requires extension of this collection of types, it is available in Pint's API at `pint.compat.upcast_types`.)\n", "\n", "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](https://numpy.org/neps/nep-0030-duck-array-protocol.html) 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.\n", "\n", "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:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "image/svg+xml": [ "\n", "\n", "\n", "\n", "\n", "\n", "%3\n", "\n", "\n", "Dask array\n", "\n", "Dask array\n", "\n", "\n", "NumPy ndarray\n", "\n", "NumPy ndarray\n", "\n", "\n", "Dask array->NumPy ndarray\n", "\n", "\n", "\n", "\n", "CuPy ndarray\n", "\n", "CuPy ndarray\n", "\n", "\n", "Dask array->CuPy ndarray\n", "\n", "\n", "\n", "\n", "Sparse COO\n", "\n", "Sparse COO\n", "\n", "\n", "Dask array->Sparse COO\n", "\n", "\n", "\n", "\n", "NumPy masked array\n", "\n", "NumPy masked array\n", "\n", "\n", "Dask array->NumPy masked array\n", "\n", "\n", "\n", "\n", "CuPy ndarray->NumPy ndarray\n", "\n", "\n", "\n", "\n", "Sparse COO->NumPy ndarray\n", "\n", "\n", "\n", "\n", "NumPy masked array->NumPy ndarray\n", "\n", "\n", "\n", "\n", "Jax array\n", "\n", "Jax array\n", "\n", "\n", "Jax array->NumPy ndarray\n", "\n", "\n", "\n", "\n", "Pint Quantity\n", "\n", "Pint Quantity\n", "\n", "\n", "Pint Quantity->Dask array\n", "\n", "\n", "\n", "\n", "Pint Quantity->NumPy ndarray\n", "\n", "\n", "\n", "\n", "Pint Quantity->CuPy ndarray\n", "\n", "\n", "\n", "\n", "Pint Quantity->Sparse COO\n", "\n", "\n", "\n", "\n", "Pint Quantity->NumPy masked array\n", "\n", "\n", "\n", "\n", "xarray Dataset/DataArray/Variable\n", "\n", "xarray Dataset/DataArray/Variable\n", "\n", "\n", "xarray Dataset/DataArray/Variable->Dask array\n", "\n", "\n", "\n", "\n", "xarray Dataset/DataArray/Variable->NumPy ndarray\n", "\n", "\n", "\n", "\n", "xarray Dataset/DataArray/Variable->CuPy ndarray\n", "\n", "\n", "\n", "\n", "xarray Dataset/DataArray/Variable->Sparse COO\n", "\n", "\n", "\n", "\n", "xarray Dataset/DataArray/Variable->NumPy masked array\n", "\n", "\n", "\n", "\n", "xarray Dataset/DataArray/Variable->Jax array\n", "\n", "\n", "\n", "\n", "xarray Dataset/DataArray/Variable->Pint Quantity\n", "\n", "\n", "\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from graphviz import Digraph\n", "\n", "g = Digraph(graph_attr={'size': '8,5'}, node_attr={'fontname': 'courier'})\n", "g.edge('Dask array', 'NumPy ndarray')\n", "g.edge('Dask array', 'CuPy ndarray')\n", "g.edge('Dask array', 'Sparse COO')\n", "g.edge('Dask array', 'NumPy masked array', style='dashed')\n", "g.edge('CuPy ndarray', 'NumPy ndarray')\n", "g.edge('Sparse COO', 'NumPy ndarray')\n", "g.edge('NumPy masked array', 'NumPy ndarray')\n", "g.edge('Jax array', 'NumPy ndarray')\n", "g.edge('Pint Quantity', 'Dask array', style='dashed')\n", "g.edge('Pint Quantity', 'NumPy ndarray')\n", "g.edge('Pint Quantity', 'CuPy ndarray', style='dashed')\n", "g.edge('Pint Quantity', 'Sparse COO')\n", "g.edge('Pint Quantity', 'NumPy masked array', style='dashed')\n", "g.edge('xarray Dataset/DataArray/Variable', 'Dask array')\n", "g.edge('xarray Dataset/DataArray/Variable', 'CuPy ndarray', style='dashed')\n", "g.edge('xarray Dataset/DataArray/Variable', 'Sparse COO')\n", "g.edge('xarray Dataset/DataArray/Variable', 'NumPy ndarray')\n", "g.edge('xarray Dataset/DataArray/Variable', 'NumPy masked array', style='dashed')\n", "g.edge('xarray Dataset/DataArray/Variable', 'Pint Quantity')\n", "g.edge('xarray Dataset/DataArray/Variable', 'Jax array', style='dashed')\n", "g" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Examples\n", "\n", "**xarray wrapping Pint Quantity**" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "Coordinates:\n", " * lat (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0\n", " * lon (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0\n", " time datetime64[ns] 2013-01-01\n", "Attributes:\n", " long_name: 4xDaily Air temperature at sigma level 995\n", " precision: 2\n", " GRIB_id: 11\n", " GRIB_name: TMP\n", " var_desc: Air temperature\n", " dataset: NMC Reanalysis\n", " level_desc: Surface\n", " statistic: Individual Obs\n", " parent_stat: Other\n", " actual_range: [185.16 322.1 ]\n", "\n", "\n", "\n", "Coordinates:\n", " time datetime64[ns] 2013-01-01\n" ] } ], "source": [ "import xarray as xr\n", "\n", "# Load tutorial data\n", "air = xr.tutorial.load_dataset('air_temperature')['air'][0]\n", "\n", "# Convert to Quantity\n", "air.data = Q_(air.data, air.attrs.pop('units', ''))\n", "\n", "print(air)\n", "print()\n", "print(air.max())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Pint Quantity wrapping Sparse COO**" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " meter\n", "\n", "0.09488747484058625 meter\n" ] } ], "source": [ "from sparse import COO\n", "\n", "x = np.random.random((100, 100, 100))\n", "x[x < 0.9] = 0 # fill most of the array with zeros\n", "s = COO(x)\n", "\n", "q = s * ureg.m\n", "\n", "print(q)\n", "print()\n", "print(np.mean(q))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Pint Quantity wrapping NumPy Masked Array**" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "masked_array(data=[, --, , --],\n", " mask=[False, True, False, True],\n", " fill_value='?',\n", " dtype=object)\n" ] } ], "source": [ "m = np.ma.masked_array([2, 3, 5, 7], mask=[False, True, False, True])\n", "\n", "# Must create using Quantity class\n", "print(repr(ureg.Quantity(m, 'm')))\n", "print()\n", "\n", "# DO NOT create using multiplication until\n", "# https://github.com/numpy/numpy/issues/15200 is resolved, as\n", "# unexpected behavior may result\n", "print(repr(m * ureg.m))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**xarray wrapping Pint Quantity wrapping Dask array wrapping Sparse COO**" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", ", 'meter')>\n", "Coordinates:\n", " * z (z) int64 0 1 2 3 4 5 6 7 8 9 10 ... 90 91 92 93 94 95 96 97 98 99\n", " * y (y) int64 -50 -49 -48 -47 -46 -45 -44 -43 ... 43 44 45 46 47 48 49\n", " * x (x) float64 -20.0 -18.5 -17.0 -15.5 ... 124.0 125.5 127.0 128.5\n", "\n", "\n", ", 'meter')>\n", "Coordinates:\n", " y int64 -46\n", " x float64 125.5\n" ] } ], "source": [ "import dask.array as da\n", "\n", "x = da.random.random((100, 100, 100), chunks=(100, 1, 1))\n", "x[x < 0.95] = 0\n", "\n", "data = xr.DataArray(\n", " Q_(x.map_blocks(COO), 'm'),\n", " dims=('z', 'y', 'x'),\n", " coords={\n", " 'z': np.arange(100),\n", " 'y': np.arange(100) - 50,\n", " 'x': np.arange(100) * 1.5 - 20\n", " },\n", " name='test'\n", ")\n", "\n", "print(data)\n", "print()\n", "print(data.sel(x=125.5, y=-46).mean())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Compatibility Packages\n", "\n", "To aid in integration between various array types and Pint (such as by providing convenience methods), the following compatibility packages are available:\n", "\n", "- [pint-pandas](https://github.com/hgrecco/pint-pandas)\n", "- pint-xarray ([in development](https://github.com/hgrecco/pint/issues/849), initial alpha release planned for January 2020)\n", "\n", "(Note: if you have developed a compatibility package for Pint, please submit a pull request to add it to this list!)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Additional Comments\n", "\n", "What follows is a short discussion about how NumPy support is implemented in Pint's `Quantity` Object.\n", "\n", "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.\n", "\n", "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).\n", "\n", "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\n", "information on these protocols, see .\n", "\n", "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](wrapping.html)).\n", "\n", "Array interface protocol attributes (such as `__array_struct__` and\n", "`__array_interface__`) are available on Pint Quantities by deferring to the corresponding `__array_*` attribute on the magnitude as casted to an ndarray. This has been found to be potentially incorrect and to cause unexpected behavior, and has therefore been deprecated. As of the next minor version of Pint (or when the `PINT_ARRAY_PROTOCOL_FALLBACK` environment variable is set to 0 prior to importing Pint as done at the beginning of this page), attempting to access these attributes will instead raise an AttributeError." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.7" } }, "nbformat": 4, "nbformat_minor": 4 }