Unit Conversion in Python

Chris Drackett picture Chris Drackett · Jan 24, 2010 · Viewed 47.3k times · Source

I'm working on a project that lets users track different data types over time. Part of the base idea is that a user should be able to enter data using any units that they need to. I've been looking at both units:

http://pypi.python.org/pypi/units/

and quantities:

http://pypi.python.org/pypi/quantities/

However I'm not sure the best way to go. From what I can tell, quantities is more complex, but includes a better initial list of units.

Answer

Christopher Bruns picture Christopher Bruns · Feb 5, 2010

I applaud use of explicit units in scientific computing applications. Using explicit units is analogous brushing your teeth. It adds some tedium up front, but the type safety you get can save a lot of trouble in the long run. Like, say, not crashing $125 million orbiters into planets.

You should also probably check out these two other python unit/quantity packages:

Unum

Scientific.Physics.PhysicalQuantity

I once investigated Scientific.Physics.PhysicalQuantity. It did not quite meet my needs, but might satisfy yours. It's hard to tell what features you need from your brief description.

I ended up writing my own python package for unit conversion and dimensional analysis, but it is not properly packaged for release yet. We are using my unit system in the python bindings for our OpenMM system for GPU accelerated molecular mechanics. You can browse the svn repository of my python units code at:

SimTK python units

Eventually I intend to package it for distribution. If you find it interesting, please let me know. That might motivate me to package it up sooner. The features I was looking for when I was designing the SimTK python units system included the following:

  1. Units are NOT necessarily stored in terms of SI units internally. This is very important for me, because one important application area for us is at the molecular scale. Using SI units internally can lead to exponent overflow in commonly used molecular force calculations. Internally, all unit systems are equally fundamental in SimTK.
  2. I wanted similar power and flexibility to the Boost.Units system in C++. Both because I am familiar with that system, and because it was designed under the scrutiny of a large group of brilliant engineers. Boost.Units is a well crafted second generation dimensional analysis system. Thus I might argue that the SimTK units system is a third generation system :). Be aware that while Boost.Units is a "zero overhead" system with no runtime cost, all python quantity implementations, including SimTK units, probably exact a runtime cost.
  3. I want dimensioned Quantities that are compatible with numpy arrays, but do not necessarily require the python numpy package. In other words, Quantities can be based on either numpy arrays or on built in python types.

What features are important to you?