Working With Units#
Early in our scientific careers we all learn about the importance of paying attention to units in our calculations. Unit conversions can still get the best of us and have caused more than one major technical disaster, including the crash and complete loss of the $327 million Mars Climate Orbiter.
In MetPy, we use the
pint library and a custom unit registry to help prevent
unit mistakes in calculations. That means that every quantity you pass to MetPy
should have units attached, just like if you were doing the calculation on
paper! This simplifies the MetPy API by eliminating the need to specify units
various functions. Instead, only the final results need to be converted to desired units. For
more information on unit support, see the documentation for
Pint. Particular attention should be paid to the support
for temperature units.
In this tutorial we’ll show some examples of working with units and get you on your way to utilizing the computation functions in MetPy.
To use units, the first step is to import the default MetPy units registry from the
import numpy as np import metpy.calc as mpcalc from metpy.units import units
The unit registry encapsulates all of the available units, as well as any pertinent settings.
The registry also understands unit prefixes and suffixes; this allows the registry to
'meters' in addition to the base
In general, using units is only a small step on top of using the
Adding Units to Data#
The easiest way to attach units to an array (or integer, float, etc.) is to multiply by the units:
It is also possible to directly construct a
pint.Quantity, with a full units string:
Compound units can be constructed by the direct mathematical operations necessary:
This verbose syntax can be reduced by using the unit registry’s support for parsing units:
9.81 * units('m/s^2')
Operations With Units#
With units attached, it is possible to perform mathematical operations, resulting in the proper units:
[0.5 0.5 0.5 0.5] meter / second
For multiplication and division, units can combine and cancel. For addition and subtraction, instead the operands must have compatible units. For instance, this works:
[2 4 6 8] meter
But for instance, distance + time would not work; instead it gives an error:
DimensionalityError: Cannot convert from ‘meter’ ([length]) to ‘second’ ([time])
Even if the units are not identical, as long as they are dimensionally equivalent, the operation can be performed:
There is also the
ito() method which performs the same operation
[0.0 3.2808398950131235 6.561679790026247 9.84251968503937 13.123359580052494] foot
To simplify units, there is also the
which converts a quantity to SI units, performing any needed cancellation:
3340000.0 joule / kilogram 3340000.0 meter ** 2 / second ** 2
By default Pint does not do any more than simple unit simplification, so when you perform operations you could get some seemingly odd results:
52.0 centimeter * inch
This is another place where
to() comes in handy:
0.013208 meter ** 2
Temperature units are actually relatively tricky (more like absolutely tricky as you’ll see). Temperature is a non-multiplicative unit - they are in a system with a reference point. That means that not only is there a scaling factor, but also an offset. This makes the math and unit book-keeping a little more complex. Imagine adding 10 degrees Celsius to 100 degrees Celsius. Is the answer 110 degrees Celsius or 383.15 degrees Celsius (283.15 K + 373.15 K)? That’s why there are delta degrees units in the unit registry for offset units. For more examples and explanation you can watch MetPy Monday #13: https://www.youtube.com/watch?v=iveJCqxe3Z4.
Let’s take a look at how this works and fails:
We would expect this to fail because we cannot add two offset units (and it does fail as an “Ambiguous operation with offset unit”).
10 * units.degC + 5 * units.degC
On the other hand, we can subtract two offset quantities and get a delta. A delta unit is pint’s way of representing a relative change in two offset units, indicating that this is not an absolute value of 5 degrees Celsius, but a relative change of 5 degrees Celsius.
We can add a delta to an offset unit as well since it is a relative change.
Absolute temperature scales like Kelvin and Rankine do not have an offset and therefore can be used in addition/subtraction without the need for a delta version of the unit.
All MetPy calculations are unit-aware and rely on this information to ensure that the calculations operate correctly. For example, we can use units to take an observation in whatever units are most convenient and let MetPy handle everything under the hood. Below we calculate dewpoint from the temperature and relative humidity:
or back to Fahrenheit:
While units are part of the MetPy ecosystem, they can be a headache after we have computed the desired quantities with MetPy and would like to move on. For example, we might have computed the dewpoint temperature for two points, say A and B, and would like to compute the average:
Per our previous discussion on temperature units, adding two temperatures together
won’t work. In this case, the easiest way to add two quantities and compute
an average is by dropping the units attached to the values via
There are a few common mistakes the new users often make. Be sure to check these when you’re having issues.
Pressure units are mbar or hPa for common atmospheric measurements. The unit mb is actually millibarns–a unit used in particle physics.
When using masked arrays, units must be multiplied on the left side. This will be addressed in the future, but is a current limitation in the ecosystem. The expected error will be AttributeError: ‘MaskedArray’ object has no attribute ‘units’ or calculation functions complaining about expecting a units and getting “dimensionless”.
Total running time of the script: ( 0 minutes 0.022 seconds)