Introduction

From v2.8.0, pymatgen comes with a fairly robust system of managing units. In essence, subclasses of float and numpy array is provided to attach units to any quantity, as well as provide for conversions. These are loaded at the root level of pymatgen and some properties (e.g., atomic masses, final energies) are returned with attached units. This demo provides an outline of some of the capabilities.

Let's start with some common units, like Energy.

In [1]:
import pymatgen as mg
#The constructor is simply the value + a string unit.
e = mg.Energy(1000, "Ha")
#Let's perform a conversion. Note that when printing, the units are printed as well.
print "{} = {}".format(e, e.to("eV"))
#To check what units are supported
print "Supported energy units are {}".format(e.supported_units)
1000.0 Ha = 27211.383859999998 eV
Supported energy units are ('kJ', 'J', 'eV', 'Ha', 'Ry')

Units support all functionality that is supported by floats. Unit combinations are automatically taken care of.

In [2]:
dist = mg.Length(65, "mile")
time = mg.Time(30, "min")
speed = dist / time
print "The speed is {}".format(speed)
#Let's do a more sensible unit.
print "The speed is {}".format(speed.to("mile h^-1"))
The speed is 2.1666666666666665 mile min^-1
The speed is 130.0 mile h^-1

Note that complex units are specified as space-separated powers of units. Powers are specified using "^". E.g., "kg m s^-1". Only integer powers are supported.

Now, let's do some basic science.

In [3]:
g = mg.FloatWithUnit(9.81, "m s^-2") #Acceleration due to gravity
m = mg.Mass(2, "kg")
h = mg.Length(10, "m")
print "The force is {}".format(m * g)
print "The potential energy is force is {}".format((m * g * h).to("J"))
The force is 19.62 N
The potential energy is force is 196.20000000000002 J

Some highly complex conversions are possible with this system. Let's do some made up units. We will also demonstrate pymatgen's internal unit consistency checks.

In [4]:
made_up = mg.FloatWithUnit(100, "Ha^3 bohr^-2")
print made_up.to("J^3 ang^-2")
2.959243823351516e-50 J^3 ang^-2
In [5]:
try:
    made_up.to("J^2")
except mg.UnitError as ex:
    print ex
Units are not compatible!

For arrays, we have the equivalent EnergyArray, ... and ArrayWithUnit classes. All other functionality remain the same.

In [6]:
dists = mg.LengthArray([1, 2, 3], "mile")
times = mg.TimeArray([0.11, 0.12, 0.23], "h")
print "Speeds are {}".format(dists / times)
Speeds are [  9.09090909  16.66666667  13.04347826] mile h^-1

This concludes the tutorial on units in pymatgen.