escope.units module

class escope.units.Units(value: float | ndarray | str, unit: str | None = None)

Bases: object

Class for unit conversion

Examples

Units(“4 lbs”).asunits(“kg”) → 1.814

Units(“3 V / 200 mA”).asunits(“Ohm”) → 15.0

Units(“psi”).definition() → “6894.7573 kg m^-1 s^-2”

Syntax

The full syntax for unit specification is:

BASEUNIT

m | s | g | A | mol

PREFIX

m | u | n | p | f | k | M | G | T

ALTUNIT

meter | meters | second | seconds | sec | secs | gram | grams | gm | amp | amps | ampere | amperes | Amp | Ampere | Amperes

ALTPREFIX

milli | micro | μ | nano | pico | femto | kilo | mega | Mega | giga | Giga | tera | Tera

DERIVEDUNIT

in | inch | Hz | Hertz | hertz | cyc | cycles | V | volt | Volt | volts | Volts | N | newton | Newton | newtons | Newtons | Pa | pascal | bar | atm | torr | J | joule | joules | Joule | Joules | barn | Ohm | Ohms | ohm | ohms | mho | Mho

UNIT

(PREFIX | ALTPREFIX)? (BASEUNIT | ALTUNIT | DERIVEDUNIT)

DIGITS

[0-9]

INTEGER

(‘-’ | ‘+’)? DIGIT+

NUMBER

(‘-’ | ‘+’)? DIGIT* (‘.’ DIGIT*)? (‘e’ (‘+’ | ‘-’) DIGIT*)?

POWFRAC

INTEGER (‘|’ INTEGER)?

POWERED

UNIT (‘^’ POWFRAC)?

FACTOR

POWERED | NUMBER

MULTI

FACTOR (’ ‘ MULTI)?

FRACTION

MULTI (‘/’ MULTI)?

Thus, the following would be understood:

‘kg m / s^2’

That’s a newton

‘J / Hz^1|2’

Joules per root-Hertz

Notes

Multiplication is implicit; do not attempt to write ‘*’.

Fractions in exponents must be written with ‘|’ rather than ‘/’, as ‘|’ binds more tightly than ‘^’.

Division marked by ‘/’ binds most loosely, e.g,

‘kg / m s’ – kilogram per meter per second

Syntax checking is not overly rigorous. Some invalid expressions may return meaningless values without a reported error.

definition(withoutvalue=False)

Definition of stored value in SI units

Parameters

withoutvalue

If given as True, only the base unit is returned, not the value-with-units

Returns

The definition of the stored unit in terms of SI base units.

Examples

Units(“2 lb”).definition() → “0.907 kg”

Units(“psi”).definition(True) → “kg m^-1 s^-2”

asunits(newunit: str, warn=False) float | ndarray

Convert to different units

Parameters

newunit

string representation of unit to convert to

Returns

The conversion result. The shape and data type of the result will match the original value passed into the Units constructor.

Notes

An exception is raised if the units are incompatible.

Optional argument WARN, if True, turns that into a warning.

See the class documentation for unit syntax and note that addition or subtraction is not supported.