#!/usr/bin/env python # coding: utf-8 # ## 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) # 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")) # 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")) # 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") # In[5]: try: made_up.to("J^2") except mg.UnitError as ex: print ex # 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) # ## This concludes the tutorial on units in pymatgen.