#!/usr/bin/env python # coding: utf-8 # # Units # # Testing a couple of different packages for handling units: `astropy.units`, `quantities`, and `pint`. # # ## `astropy.units` # # Replicating the handy [online tutorial](http://astropy.readthedocs.org/en/latest/units/). # In[1]: import astropy.units as u import numpy as np # In[16]: 42.0 * u.meter # In[17]: [1., 2., 3.] * u.m # In[18]: np.array([1., 2., 3.]) * u.m # In[19]: w = 42.0 * u.kilogram # In[20]: w.value # In[21]: w.unit # In[22]: dir(w) # Variables and attributes: # In[23]: d = 2300. * u.kg/u.m**3 # In[24]: d # In[25]: d.unit # In[26]: vp = 2500 * u.m/u.s # In[27]: z = vp * d # In[28]: z # In[29]: z.unit # In[30]: z.unit.compose() # Convert velocity to ft/s: # In[31]: from astropy.units import imperial # In[32]: vp.to(imperial.foot/u.s) # In[33]: # To put it another way: vp * 3.28084 * (imperial.foot/u.m) # In[34]: fps = imperial.foot/u.second # In[35]: vp_imperial = vp.to(fps) vp_imperial # In[36]: vp.cgs # In[37]: vp_imperial.si # I think we could define a unit system, `oilfield` or `oil` perhaps, that has feet, g/cm^3, seconds, degF, etc. # # We would also have to define various units like barrel, boe, cubic foot, etc. # In[38]: t = 245 * u.deg_C t # In[39]: u.equivalencies.temperature() # I do like how IPython plays so nicely with the formatting. # ## `quantities` # # Potentially nice because it can also handle uncertainties. Following [the tutorial](https://pythonhosted.org/quantities/user/tutorial.html)... # In[2]: import quantities as pq # In[3]: vel = 2.5 * pq.km/pq.s vel # In[4]: vel.units = pq.ft/pq.s vel # I think I prefer having a `to` method on the quantity object, rather than setting an attribute. # # Uncertainties are quite cool, though, if rather deterministic... # In[5]: den = pq.UncertainQuantity(2850., pq.kg/pq.m**3, 75.) den # In[6]: imp = vel * den imp # ## `pint` # In[7]: from pint import UnitRegistry # In[8]: ureg = UnitRegistry() # In[9]: vs = 1200. * ureg.meter/ureg.second # In[10]: vs # In[11]: vs.units # In[12]: vs.magnitude # In[13]: vs.dimensionality # In[40]: zs = vs * d zs # Not sure if this is good or bad, but `pint` knows about aliases and alternate spellings: # In[47]: vs.to(ureg.feet/ureg.s) # In[48]: vs.to(ureg.foot/ureg.s) # In[49]: 5.0 * ureg.metres # As with astropy, we can define units: # In[50]: ftps = ureg.foot/ureg.second vs.to(ftps) # In[51]: t = 2245.0 * ureg.rankine t # In[52]: t.to(ureg.degC) # In[53]: p = 4500. * ureg.psi # In[54]: p.to(ureg.MPa) # ## `pint` with `numpy` # Need to see how the units respond to being differenced, convolved, etc. # In[ ]: