Coverage for /opt/conda/envs/apienv/lib/python3.10/site-packages/daiquiri/core/transform/units.py: 63%

19 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-14 02:13 +0000

1from pint import UnitRegistry 

2 

3ureg = UnitRegistry() 

4 

5 

6def isquantity(x): 

7 return isinstance(x, ureg.Quantity) 

8 

9 

10def asquantity(value, units=None, convert=None): 

11 """ 

12 :param Quantity or num or array value: 

13 :param Unit or str units: dimensionless by default 

14 :pram bool convert: by default convert when units not None 

15 :returns Quantity: 

16 """ 

17 if isquantity(value): 

18 if convert is None: 

19 convert = units is not None 

20 elif convert: 

21 return value.to(units) 

22 else: 

23 return value 

24 else: 

25 return ureg.Quantity(value, units=units) 

26 

27 

28def asvalue(value, units): 

29 """ 

30 :param Quantity or num or array value: 

31 :param Unit or str units: 

32 :returns num or array: 

33 """ 

34 return asquantity(value, units, convert=True).magnitude 

35 

36 

37def get_exponent(unit, relative_to=ureg.m): 

38 """ 

39 :param Unit str units: 

40 :param Relative to SI unit: 

41 :returns float exponent: 

42 """ 

43 if not hasattr(ureg, unit): 

44 raise KeyError(f"No such unit {unit}") 

45 

46 unit_obj = getattr(ureg, unit) 

47 return (1 * unit_obj).to(relative_to).magnitude