Using units

Third party quantities module is extended to the irfpy.util.unitq module. Usually you may start with

from irfpy.util import unitq as u

See how to use the quantities module https://github.com/python-quantities/python-quantities

Below, extended use of irfpy.util.unitq is explained. Also refer to irfpy.util.unitq.

Getting used to

A simple use flow is as follows.

> from irfpy.util import unitq as u
> vel = 50 * u.au / (200 * u.hour)
> print(vel)     # Gives (internal expression of) quantities
0.25 au/h
> print(vel.n)   # Gives a value with unit of internal expression
0.25
> print(vel.s)    # With ``.s``, reference unit (default: MKSA) is returned.
10388741.020208333 m/s
> print(vel.ns)   # ``.ns``, value in reference unit is returned.
10388741.020208333
> print(vel.us)   # ``.us`` returns the unit of the reference
m/s
> u.use('cgs')   # ``.use`` can change the refernce unit system.
> print(vel.s)
1038874102.0208334 cm/s
> print(vel.r(u.km / u.s))    # ``.r`` rescales the unit.
10388.741020208332 km/s
> print(vel.r(u.c))     # In this case speed-of-light is a unit :)
0.034653109986537194 c
> print(vel.nr(u.c))     # ``.nr`` will return the rescaled number.
0.034653109986537194

Extended usage

u.nit

Sometimes it is usuful if you just instance quantities from string. u.nit will provide this functionality.

> from irfpy.util import unitq as u
> w = u.nit('3 kg')
> print w
3.0 kg
> g = u.nit('9.8 kg m/s^2')
> print g
9.8 kg*m/s**2

Further, the u.nit will identify the undefined unit in a form of SI-prefixed known units. Take an example of “pC”, pico-coulomb.

> 'pC' in u.known_unit    # Pico-Coulomb is not defined.
False
> print u.nit('pC')     # But using u.nit "pC" is guessed as "p"+"C"
1e-12 C
> 'pC' in u.known_unit    # Now it is found in the definition list
True
> print u.pC              # And even access with a usual way!!
1 pC

The ‘pC’ will be forgotten after the exit of the python interpreter. It may be a good idea to call u.nit(‘pC’) just after the import statement if you use ‘pC’ frequently.

make_unitful_function

Sometimes, it is useful if formula can handle the unit. This will help dimension check during the step-by-step calculation. It is supported with a simple way in irfpy.util.unitq.make_unitful_function(). See the above link.