Custom units
This tutorial shows how to define your own units. A Unit
is defined by its scale relative to the SI unit of its dimension, its exponent map, its dimension and its context.
The exponent map is a frozenset of (symbol, exponent) pairs. It identifies the unit and is how the unit is printed.
Custom units can be combined with the units of the registry u like any other unit.
import numpy as np import scipy.constants as sc from qunits import Unit, u from qunits.dimension import Dimensionless, Energy, Length from qunits.prefix import Context inch = Unit(0.0254, frozenset({("in", 1)}), Length, Context.I) kcal = Unit(4184.0, frozenset({("kcal", 1)}), Energy, Context.I) x = 10 * inch # >>> 10.0 in x = x.to(u.mm) # >>> 254.0 mm E = (2 * kcal).to(u.kJ) # >>> 8.368 kJ P = E / (1 * u.s) # >>> 8.368 kJ/s
The dimension of a unit does not have to be one of the predefined dimensions in
qunits.dimension.
Any dimension can be obtained from the dimension d of a composite unit.
luminance = (u.cd / u.m**2).d name = luminance.name # >>> LuminousIntensity__DIV__Area nit = Unit(1.0, frozenset({("nit", 1)}), luminance, Context.I) L = 300 * nit # >>> 300.0 nit L = L.to(u.cd / u.m**2) # >>> 300.0 cd/m^2
Angles are dimensionless units with the context Context.ANGLE.
The trigonometric functions np.sin, np.cos and np.tan only accept angles,
and quantities with different contexts cannot be added or subtracted.
deg = Unit(sc.pi / 180, frozenset({("deg", 1)}), Dimensionless, Context.ANGLE) phi = 90 * deg + 0.25 * u.pi # >>> 135.0 deg y = np.sin(phi) # >>> 0.707106781186548 1 try: phi + 10 * u.percent except ValueError as error: print(error) # >>> Context mismatch in addition. Cannot add Dimensionless with context ANGLE and ...
There is exactly one unit per exponent map. Defining a unit again returns the existing unit,
and defining a different unit with an existing exponent map raises a ValueError.
same = Unit(0.0254, frozenset({("in", 1)}), Length, Context.I) print(same is inch) # >>> True try: Unit(0.025, frozenset({("in", 1)}), Length, Context.I) except ValueError as error: print(error) # >>> The unit in is already defined with scale 0.0254, dimension Length and context I.