I am trying to use pint in a situation where I need to do transformations between dimensions, eg. fluid ounces to grams.
The values I need for my transformation are in a database and change for various substances (eg. different densities for different liquids), so I'm using the Context.add_transformation() method to dynamically create my transformation. Here's my test program:
#!/opt/env/upgrade/bin/python
import pint
ureg = pint.UnitRegistry()
c = pint.Context('ab')
def vtom(ureg, x):
# here I print some output just to see if this function is ever called
# and what arguments are passed. It is not being called.
print "vtom(%s, %s)" % (ureg, x)
# right now I just return the input, so it's 1:1. I know this is
# not right, I am just trying to get pint to find the transform and use it.
return x
c.add_transformation('[volume]', '[mass]', vtom)
ureg.add_context(c)
PQ = ureg.Quantity
# this works fine
a = PQ(1 * ureg.oz)
print '%s = %s' % (a, a.to('gram'))
b = PQ(10 * ureg.floz)
c = PQ(10 * ureg.gram)
# both these fail, see exception output below
print '%s = %s' % (c, c.to('floz'))
print '%s = %s' % (b, b.to('gram'))
The output:
1 ounce = 28.349523125 gram
Traceback (most recent call last):
File "./p.py", line 26, in <module>
print '%s = %s' % (b, b.to('gram'))
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/quantity.py", line 332, in to
magnitude = self._convert_magnitude_not_inplace(other, *contexts, **ctx_kwargs)
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/quantity.py", line 300, in _convert_magnitude_not_inplace
return self._REGISTRY.convert(self._magnitude, self._units, other)
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/registry.py", line 686, in convert
return self._convert(value, src, dst, inplace)
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/registry.py", line 1214, in _convert
return super(ContextRegistry, self)._convert(value, src, dst, inplace)
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/registry.py", line 937, in _convert
return super(NonMultiplicativeRegistry, self)._convert(value, src, dst, inplace)
File "/opt/env/upgrade/local/lib/python2.7/site-packages/pint/registry.py", line 708, in _convert
raise DimensionalityError(src, dst, src_dim, dst_dim)
pint.errors.DimensionalityError: Cannot convert from 'fluid_ounce' ([length] ** 3) to 'gram' ([mass])
It seems that pint is not finding my tranformation. In the units text file (the default one that comes with pint), '[volume] = [length] ** 3' is defined, so it should be able to walk the graph and find '[mass]'.. or so I thought...
Thanks!