Pint: a Python units library

Pint: **physical quantities**

Pint is Python package to define, operate and manipulate physical quantities: the product of a numerical value and a unit of measurement. It allows arithmetic operations between them and conversions from and to different units.

It is distributed with a comprehensive list of physical units, prefixes and constants. Due to it’s modular design, you can extend (or even rewrite!) the complete list without changing the source code.

It has a complete test coverage. It runs in Python 2.7 and 3.X with no other dependency. It licensed under BSD.

Design principles

Although there are already a few very good Python packages to handle physical quantities, no one was really fitting my needs. Like most developers, I programed Pint to scratch my own itches.

Unit parsing: prefixed and pluralized forms of units are recognized without explicitly defining them. In other words: as the prefix kilo and the unit meter are defined, Pint understands kilometers. This results in a much shorter and maintainable unit definition list as compared to other packages.

Standalone unit definitions: units definitions are loaded from a text file which is simple and easy to edit. Adding and changing units and their definitions does not involve changing the code.

Advanced string formatting: a quantity can be formatted into string using PEP 3101 syntax. Extended conversion flags are given to provide symbolic, latex and pretty formatting.

Free to choose the numerical type: You can use any numerical type (fraction, float, decimal, numpy.ndarray, etc). NumPy is not required but supported.

NumPy integration: When you choose to use a NumPy ndarray, its methods and ufuncs are supported including automatic conversion of units. For example numpy.arccos(q) will require a dimensionless q and the units of the output quantity will be radian.

Handle temperature: conversion between units with different reference points, like positions on a map or absolute temperature scales.

Small codebase: easy to maintain codebase with a flat hierarchy.

Dependency free: it depends only on Python and it’s standard library.

Python 2 and 3: a single codebase that runs unchanged in Python 2.7+ and Python 3.0+.

User Guide

Installation

Pint has no dependencies except Python itself. In runs on Python 2.7 and 3.0+.

You can install it using pip:

$ pip install pint

or using easy_install:

$ easy_install pint

That’s all! You can check that Pint is correctly installed by starting up python, and importing pint:

>>> import pint

Note

If you have an old system installation of Python and you don’t want to mess with it, you can try Anaconda CE. It is a free Python distribution by Continuum Analytics that includes many scientific packages.

Getting the code

You can also get the code from PyPI or GitHub. You can either clone the public repository:

$ git clone git://github.com/hgrecco/pint.git

Download the tarball:

$ curl -OL https://github.com/hgrecco/pint/tarball/master

Or, download the zipball:

$ curl -OL https://github.com/hgrecco/pint/zipball/master

Once you have a copy of the source, you can embed it in your Python package, or install it into your site-packages easily:

$ python setup.py install

Tutorial

Converting Quantities

Pint has the concept of Unit Registry, an object within which units are defined and handled. You start by creating your registry:

>>> from pint import UnitRegistry
>>> ureg = UnitRegistry()

If no parameter is given to the constructor, the unit registry is populated with the default list of units and prefixes. You can now simply use the registry in the following way:

>>> distance = 24.0 * ureg.meter
>>> print(distance)
24.0 meter
>>> time = 8.0 * ureg.second
>>> print(time)
8.0 second
>>> print(repr(time))
<Quantity(8.0, 'second')>

In this code distance and time are physical quantities objects (Quantity). Physical quantities can be queried for the magnitude and units:

>>> print(distance.magnitude)
24.0
>>> print(distance.units)
meter

and can handle mathematical operations between:

>>> speed = distance / time
>>> print(speed)
3.0 meter / second

As unit registry knows about the relationship between different units, you can convert quantities to the unit of choice:

>>> speed.to(ureg.inch / ureg.minute )
<Quantity(7086.61417323, 'inch / minute')>

This method returns a new object leaving the original intact as can be seen by:

>>> print(speed)
3.0 meter / second

If you want to convert in-place (i.e. without creating another object), you can use the ito method:

>>> speed.ito(ureg.inch / ureg.minute )
<Quantity(7086.61417323, 'inch / minute')>
>>> print(speed)
7086.61417323 inch / minute

If you ask Pint to perform and invalid conversion:

>>> speed.to(ureg.joule)
Traceback (most recent call last):
...
pint.pint.DimensionalityError: Cannot convert from 'inch / minute' (length / time) to 'joule' (length ** 2 * mass / time ** 2)

In some cases it is useful to define physical quantities objects using the class constructor:

>>> Q_ = ureg.Quantity
>>> Q_(1.78, ureg.meter) == 1.78 * ureg.meter
True

(I tend to abbreviate Quantity as Q_) The in-built parse allows to recognize prefixed and pluralized units even though they are not in the definition list:

>>> distance = 42 * ureg.kilometers
>>> print(distance)
42 kilometer
>>> print(distance.to(ureg.meter))
42000.0 meter

If you try to use a unit which is not in the registry:

>>> speed = 23 * ureg.snail_speed
Traceback (most recent call last):
...
pint.pint.UndefinedUnitError: 'snail_speed' is not defined in the unit registry

You can add your own units to the registry or build your own list. More info on that Defining units

String parsing

Pint can also handle units provided as strings:

>>> 2.54 * ureg['centimeter']
<Quantity(2.54, 'centimeter')>

or via de Quantity constructor:

>>> Q_(2.54, 'centimeter')
<Quantity(2.54, 'centimeter')>

Numbers are also parsed:

>>> Q_('2.54 * centimeter')
<Quantity(2.54, 'centimeter')>

This enables you to build a simple unit converter in 3 lines:

Take a look at qconvert.py within the examples folder for a full script.

String formatting

Pint’s physical quantities can be easily printed:

>>> accel = 1.3 * ureg['meter/second**2']
>>> # The standard string formatting code
>>> print('The str is {:!s}'.format(accel))
The str is 1.3 meter / second ** 2
>>> # The standard representation formatting code
>>> print('The repr is {:!r}'.format(accel))
The repr is <Quantity(1.3, 'meter / second ** 2')>
>>> # Accessing useful attributes
>>> print('The magnitude is {0.magnitude} with units {0.units}'.format(accel))
The magnitude is 1.3 with units meter / second ** 2

But Pint also extends the standard formatting capabilities for unicode and latex representations:

>>> accel = 1.3 * ureg['meter/second**2']
>>> # Pretty print
>>> 'The pretty representation is {:!p}'.format(accel)
'The pretty representation is 1.3 meter/second²'
>>> # Latex print
>>> 'The latex representation is {:!l}'.format(accel)
'The latex representation is 1.3 \\frac{meter}{second^{2}}'

If you want to use abbreviated unit names, suffix the specification with ~:

>>> 'The str is {:!s~}'.format(accel)
'The str is 1.3 m / s ** 2'

The same is true for repr (r), latex (l) and pretty (p) specs.

Using Pint in your projects

If you use Pint in multiple modules within you Python package, you normally want to avoid creating multiple instances of the unit registry. The best way to do this is by instantiating the registry in a single place. For example, you can add the following code to your package __init__.py:

from pint import UnitRegistry
ureg = UnitRegistry()
Q_ = ureg.Quantity

Then in yourmodule.py the code would be:

from . import ureg, Q_

length = 10 * ureg.meter
my_speed = Quantity(20, 'm/s')

NumPy support

The magnitude of a Pint quantity can be of any numerical type and you are free to choose it according to your needs. In numerical applications, it is quite convenient to use NumPy ndarray and therefore they are supported by Pint.

First, we import the relevant packages:

>>> import numpy as np
>>> from pint import UnitRegistry
>>> ureg = UnitRegistry()
>>> Q_ = ureg.Quantity

and then we create a quantity the standard way

>>> legs1 = Q_(np.asarray([3., 4.]), 'meter')
>>> print(legs1)
[ 3.  4.] meter

or we use the property that Pint converts iterables into NumPy ndarrays to simply write:

>>> legs1 = [3., 4.] * ureg.meter
>>> print(legs1)
[ 3.  4.] meter

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

>>> print(legs1.to('kilometer'))
[ 0.003  0.004] kilometer
>>> print(legs1.dimensionality)
[length]
>>> legs1.to('joule')
Traceback (most recent call last):
...
DimensionalityError: Cannot convert from 'meter' ([length]) to 'joule' ([length] ** 2 * [mass] / [time] ** 2)

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

>>> legs2 = [400., 300.] * ureg.centimeter
>>> print(legs2)
[ 400.  300.] centimeter

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

>>> hyps = np.hypot(legs1, legs2)
>>> print(hyps)
[ 5.  5.] meter

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:

>>> angles = np.arccos(legs2/hyps)
>>> print(angles)
[ 0.64350111  0.92729522] radian

You can convert the result to degrees using the corresponding NumPy function:

>>> print(np.rad2deg(angles))
[ 36.86989765  53.13010235] degree

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

>>> np.arccos(legs2)
Traceback (most recent call last):
...
DimensionalityError: Cannot convert from 'centimeter' ([length]) to 'dimensionless' (dimensionless)

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, reciprocal
  • Trigonometric functions: sin, cos, tan, arcsin, arccos, arctan, arctan2, hypot, sinh, cosh, tanh, arcsinh, arccosh, arctanh, deg2rad, rad2deg
  • 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 ndarrays methods and functions:

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

Quantity is not a subclass of ndarray. This might change in the future, but for this reason functions that call numpy.asanyarray are currently not supported. These functions are:

  • unwrap, trapz, diff, ediff1d, fix, gradient, cross, ones_like

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.

This behaviour introduces some performance penalties and increased memory usage. Quantities that must be converted to other units require additional memory and cpu cycles. On top of this, all ufuncs are implemented in the Quantity class by overriding __array_wrap__, a NumPy hook that is executed after the calculation and before returning the value. To our knowledge, there is no way to signal back to NumPy that our code will take care of the calculation. For this reason the calculation is actually done twice: first in the original ndarray and then in then in the one that has been converted to the right units. Therefore, for numerically intensive code, you might want to convert the objects first and then use directly the magnitude.

Temperature conversion

Unlike meters and seconds, fahrenheits, celsius and kelvin are not multiplicative units. Temperature is expressed in a system with a reference point, and relations between temperature units include not only an scaling factor but also an offset. Pint supports these type of units and conversions between them. The default definition file includes fahrenheits, celsius, kelvin and rankine abbreviated as degF, degC, degK, and degR.

For example, to convert from celsius to fahrenheit:

>>> from pint import UnitRegistry
>>> ureg = UnitRegistry()
>>> home = 25.4 * ureg.degC
>>> print(home.to('degF'))
77.7200004 degF

or to other kelvin or rankine:

>>> print(home.to('degK'))
298.55 degK
>>> print(home.to('degR'))
537.39 degR

Additionally, for every temperature unit in the registry, there is also a delta counterpart to specify differences. For example, the change in celsius is equal to the change in kelvin, but not in fahrenheit (as the scaling factor is different).

>>> increase = 12.3 * ureg.delta_degC
>>> print(increase.to(ureg.delta_degK))
12.3 delta_degK
>>> print(increase.to(ureg.delta_degF))
6.83333333333 delta_degF

Differences in temperature are multiplicative:

>>> speed = 60. * ureg.delta_degC / ureg.min
>>> print(speed.to('delta_degC/second'))
1.0 delta_degC / second

The parser knows about delta units and use them when a temperature unit is found in a multiplicative context. For example, here:

>>> print(ureg.parse_units('degC/meter'))
delta_degC / meter

but not here:

>>> print(ureg.parse_units('degC'))
degC

You can override this behaviour:

>>> print(ureg.parse_units('degC/meter', to_delta=False))
degC / meter

To define a new temperature, you need to specify the offset. For example, this is the definition of the celsius and fahrenheit:

degC = degK; offset: 273.15 = celsius
degF = 9 / 5 * degK; offset: 255.372222 = fahrenheit

You do not need to define delta units, as they are defined automatically.

Buckingham Pi Theorem

Buckingham π theorem states that an equation involving n number of physical variables which are expressible in terms of k independent fundamental physical quantities can be expressed in terms of p = n - k dimensionless parameters.

To start with a very simple case, consider that you want to find a dimensionless quantity involving the magnitudes V, T and L with dimensions [length]/[time], [time] and [length] respectively.

>>> from pint import pi_theorem
>>> pi_theorem({'V': '[length]/[time]', 'T': '[time]', 'L': '[length]'})
[{'V': 1, 'T': 1, 'L': -1}]

The result indicates that a dimensionless quantity can be obtained by multiplying V by T and the inverse of L.

Which can be pretty printed using the Pint formatter:

>>> from pint import formatter
>>> result = pi_theorem({'V': '[length]/[time]', 'T': '[time]', 'L': '[length]'})
>>> print(formatter(result[0].items()))
T * V / L

You can also apply the Buckingham π theorem associated to a Registry. In this case, you can use derived dimensions such as speed:

>>> from pint import UnitRegistry
>>> ureg = UnitRegistry()
>>> ureg.pi_theorem({'V': '[speed]', 'T': '[time]', 'L': '[length]'})
[{'V': 1, 'T': 1, 'L': -1}]

or unit names:

>>> ureg.pi_theorem({'V': 'meter/second', 'T': 'second', 'L': 'meter'})
[{'V': 1, 'T': 1, 'L': -1}]

or quantities:

>>> Q_ = ureg.Quantity
>>> ureg.pi_theorem({'V': Q_(1, 'meter/second'),
...                  'T': Q_(1, 'second'),
...                  'L': Q_(1, 'meter')})
[{'V': 1, 'T': 1, 'L': -1}]

Application to the pendulum

There are 3 fundamental physical units in this equation: time, mass, and length, and 4 dimensional variables, T (oscillation period), M (mass), L (the length of the string), and g (earth gravity). Thus we need only 4 − 3 = 1 dimensionless parameter.

>>> ureg.pi_theorem({'T': '[time]',
...                  'M': '[mass]',
...                  'L': '[length]',
...                  'g': '[acceleration]'})
[{'T': 2, 'g': 1, 'L': -1}]

which means that the dimensionless quantity is:

\[\Pi = \frac{g T^2}{L}\]

and therefore:

\[T = constant \sqrt{\frac{L}{g}}\]

(In case you wonder, the constant is equal to 2 π, but this is outside the scope of this help)

Pressure loss in a pipe

What is the pressure loss p in a pipe with length L and diameter D for a fluid with density d, and viscosity m travelling with speed v? As pressure, mass, volume, viscosity and speed are defined as derived dimensions in the registry, we only need to explicitly write the density dimensions.

>>> ureg.pi_theorem({'p': '[pressure]',
...                  'L': '[length]',
...                  'D': '[length]',
...                  'd': '[mass]/[volume]',
...                  'm': '[viscosity]',
...                  'v': '[speed]'
...                  })
[{'p': 1, 'm': -2, 'd': 1, 'L': 2}, {'v': 1, 'm': -1, 'd': 1, 'L': 1}, {'L': -1, 'D': 1}]

The second dimensionless quantity is the Reynolds Number

Using Measurements

Measurements are the combination of two quantities: the mean value and the error (or uncertainty). The easiest ways to generate a measurement object is from a quantity using the plus_minus operator.

>>> import numpy as np
>>> from pint import UnitRegistry
>>> ureg = UnitRegistry()
>>> book_length = (20. * ureg.centimeter).plus_minus(2.)
>>> print(book_length)
(20.0 +/- 2.0) centimeter

You can inspect the mean value, the absolute error and the relative error:

>>> print(book_length.value)
20.0 centimeter
>>> print(book_length.error)
2.0 centimeter
>>> print(book_length.rel)
0.1

You can also create a Measurement object giving the relative error:

>>> book_length = (20. * ureg.centimeter).plus_minus(.1, relative=True)
>>> print(book_length)
(20.0 +/- 2.0) centimeter

Measurements support the same formatting codes as Quantity. For example, to pretty print a measurement with 2 decimal positions:

>>> print('{:.02f!p}'.format(book_length))
(2.00 ± 0.20) meter

Mathematical operations with Measurements, return new measurements following the Propagation of uncertainty rules.

>>> print(2 * book_length)
(40.0 +/- 4.0) centimeter
>>> width = (10 * ureg.centimeter).plus_minus(1)
>>> print('{:.02f}'.format(book_length + width))
(30.00 +/- 2.24) centimeter

Note

only linear combinations are currently supported.

Defining units

In a definition file

To define units in a persistent way you need to create a unit definition file. Such files are simple text files in which the units are defined as function of other units. For example this is how the minute and the hour are defined in default_en.txt:

hour = 60 * minute = h = hr
minute = 60 * second = min

It is quite straightforward, isn’t it? We are saying that minute is 60 seconds and is also known as min. The first word is always the canonical name. Next comes the definition (based on other units). Finally, a list of aliases, separated by equal signs.

The order in which units are defined does not matter, Pint will resolve the dependencies to define them in the right order. What is important is that if you transverse all definitions, a reference unit is reached. A reference unit is not defined as a function of another units but of a dimension. For the time in default_en.txt, this is the second:

second = [time] = s = sec

By defining second as equal to a string time in square brackets we indicate that:

  • time is a physical dimension.
  • second is a reference unit.

The ability to define basic physical dimensions as well as reference units allows to construct arbitrary units systems.

Pint is shipped with a default definition file named default_en.txt where en stands for english. You can add your own definitions to the end of this file but you will have to be careful to merge when you update Pint. An easier way is to create a new file (e.g. mydef.txt) with your definitions:

dog_year = 52 * day = dy

and then in Python, you can load it as:

>>> from pint import UnitRegistry
>>> # First we create the registry.
>>> ureg = UnitRegistry()
>>> # Then we append the new definitions
>>> ureg.load_definitions('/your/path/to/my_def.txt') 

If you make a translation of the default units or define a completely new set, you don’t want to append the translated definitions so you just give the filename to the constructor:

>>> from pint import UnitRegistry
>>> ureg = UnitRegistry('/your/path/to/default_es.txt')

In the definition file, prefixes are identified by a trailing dash:

yocto- = 10.0**-24 = y-

It is important to note that prefixed defined in this way can be used with any unit, including non-metric ones (e.g. kiloinch is valid for Pint). This simplifies definitions files enormously without introducing major problems. Pint, like Python, believes that we are all consenting adults.

Programmatically

You can easily add units to the registry programmatically. Let’s add a dog_year (sometimes writen as dy) equivalent to 52 (human) days:

>>> from pint import UnitRegistry
>>> # We first instantiate the registry.
>>> # If we do not provide any parameter, the default unit definitions are used.
>>> ureg = UnitRegistry()
>>> Q_ = ureg.Quantity

# Here we add the unit
>>> ureg.define('dog_year = 52 * day = dy')

# We create a quantity based on that unit and we convert to years.
>>> lassie_lifespan = Q_(10, 'year')
>>> print(lassie_lifespan.to('dog_years'))
70.238884381 dog_year

Note that we have used the name dog_years even though we have not defined the plural form as an alias. Pint takes care of that, so you don’t have to.

You can also add prefixes programmatically:

>>> ureg.define('myprefix- = 30 = my-')

where the number indicates the multiplication factor.

Warning

Units and prefixes added programmatically are forgotten when the program ends.

More information

Contributing to Pint

You can contribute in different ways:

Report issues

You can report any issues with the package, the documentation to the Pint issue tracker. Also feel free to submit feature requests, comments or questions.

Contribute code

To contribute fixes, code or documentation to Pint, send us a patch, or fork Pint in github and submit the changes using a pull request.

Frequently asked questions

Why the name Pint?

Pint is a unit and sounds like Python in the first syllable. Most important, it is a good unit for beer.

You mention other similar Python libraries. Can you point me to those?

Buckingham

Magnitude

SciMath

Python-quantities

Unum

Units

If your are aware of another one, please let me know.

One last thing

The MCO MIB has determined that the root cause for the loss of the MCO spacecraft was the failure to use metric units in the coding of a ground software file, “Small Forces,” used in trajectory models. Specifically, thruster performance data in English units instead of metric units was used in the software application code titled SM_FORCES (small forces). The output from the SM_FORCES application code as required by a MSOP Project Software Interface Specification (SIS) was to be in metric units of Newtonseconds (N-s). Instead, the data was reported in English units of pound-seconds (lbf-s). The Angular Momentum Desaturation (AMD) file contained the output data from the SM_FORCES software. The SIS, which was not followed, defines both the format and units of the AMD file generated by ground-based computers. Subsequent processing of the data from AMD file by the navigation software algorithm therefore, underestimated the effect on the spacecraft trajectory by a factor of 4.45, which is the required conversion factor from force in pounds to Newtons. An erroneous trajectory was computed using this incorrect data.

Mars Climate Orbiter Mishap Investigation Phase I Report PDF

About Pint

Units in Python. You are currently looking at the documentation of version 0.2.1.

Other Formats

You can download the documentation in other formats as well:

Useful Links

Fork me on GitHub