Unit#

class brainunit.Unit(dim=None, scale=0, base=10.0, factor=1.0, name=None, dispname=None, is_fullname=True, display_parts=None)#

A physical unit.

Basically, a unit is just a number with given dimensions, e.g. mvolt = 0.001 with the dimensions of voltage. The units module defines a large number of standard units, and you can also define your own (see below).

Mathematically, a unit represents:

\[\text{{factor}} \times \text{{base}}^{\text{{scale}}} \times \text{{dimension}}\]

where the factor is the conversion factor of the unit (e.g. 1 calorie = 4.18400 Joule, so the factor is 4.18400), the base is the base of the exponent (e.g. 10 for the kilo prefix), the scale is the exponent of the base (e.g. 3 for the kilo prefix), and the dimension is the physical dimensions of the unit (e.g. joule for energy).

The unit class also keeps track of the named units it was composed from, to generate a readable string representation. See below.

Parameters:
  • dim (Dimension | str | None) – The physical dimensions of the unit. Defaults to DIMENSIONLESS.

  • scale (int | float) – The scale exponent, e.g. 3 for a “k” (kilo) prefix. Defaults to 0.

  • base (int | float) – The base of the exponent. Must be 10 (the only supported base); other values raise ValueError.

  • factor (int | float) – The conversion factor of the unit. Must be positive. Defaults to 1.

  • name (str | None) – The full name of the unit, e.g. 'volt'.

  • dispname (str | None) – The display name, e.g. 'V'.

  • is_fullname (bool) – Whether name is the canonical full name. Defaults to True.

  • display_parts (list of tuple, optional) – Legacy (name, dispname, exponent) display components, accepted for backward compatibility (old pickles).

Notes

When creating scaled units, you can use the following prefixes:

Factor

Name

Prefix

10^24

yotta

Y

10^21

zetta

Z

10^18

exa

E

10^15

peta

P

10^12

tera

T

10^9

giga

G

10^6

mega

M

10^3

kilo

k

10^2

hecto

h

10^1

deka

da

1

10^-1

deci

d

10^-2

centi

c

10^-3

milli

m

10^-6

micro

u (mu in SI)

10^-9

nano

n

10^-12

pico

p

10^-15

femto

f

10^-18

atto

a

10^-21

zepto

z

10^-24

yocto

y

Display

A unit keeps the named units it was composed from, so composites display the way they were written: u.mS * u.nA / u.cm ** 2 is mS * nA / cm^2 and u.mV * u.ms is ms * mV. Terms are ordered canonically (numerator first, then by symbol), so a * b and b * a display identically. A composite collapses automatically only onto a curated set of units (SI base units, N, Pa, J, W, C, V, F, ohm, S, Hz and their prefixed forms):

>>> import saiunit as u
>>> u.kilogram * u.metre / u.second ** 2
Unit("N")
>>> u.volt * u.second
Unit("s * V")
>>> (u.volt * u.second).simplify()
Unit("Wb")

str(unit) is canonical ASCII that parse_unit() reads back; to_string() also renders Unicode (µF / cm²) and LaTeX.

Defining your own

>>> import saiunit as u
>>> cal = u.Unit.create(u.joule.dim, 'calorie', 'cal', factor=4.184)
>>> cal / u.gram
Unit("cal / g")

Comparison and arithmetic treat a bare Unit operand differently. Comparing a Quantity against a bare Unit implicitly reads the unit as “one of that unit” (1 * unit), so Quantity(1, mV) == mV is True. Addition/subtraction, by contrast, reject a bare Unit operand outright (Quantity(1, mV) + mV raises TypeError), since there is no natural mantissa to add. Both behaviours are intentional; see __eq__ for the comparison side.

Examples

Create a simple unit:

>>> import saiunit as u
>>> u.volt
Unit("V")
>>> u.mvolt
Unit("mV")

Combine units:

>>> import saiunit as u
>>> u.volt / u.amp
Unit("V / A")
property base: float#

Return the base of the unit’s scale exponent.

The base is the number that is raised to the scale power to produce the unit’s magnitude. For SI-prefixed units this is 10 (e.g. kilo means 10 ** 3).

Returns:

The base of the exponent.

Return type:

float

Examples

>>> import saiunit as u
>>> u.kvolt.base
10.0
copy()[source]#

Return a copy of this Unit.

Returns:

A new Unit object with the same attributes.

Return type:

Unit

Examples

>>> import saiunit as u
>>> v = u.volt.copy()
>>> v == u.volt
True
>>> v is u.volt
False
static create(dim, name, dispname, scale=0, base=10.0, factor=1.0, *, auto_simplify=False, unicode=None, latex=None)[source]#

Create and register a new named unit.

Parameters:
  • dim (Dimension) – The dimensions of the unit.

  • name (str) – The full name of the unit, e.g. 'volt'

  • dispname (str) – The ASCII display symbol, e.g. 'V'. A symbol of the form '<registered symbol>^<int>' (e.g. 'cm^2') creates a power alias equivalent to create_power().

  • scale (int | float) – The scale of this unit as an exponent of 10, e.g. -3 for a unit that is 1/1000 of the base scale. Defaults to 0 (i.e. a base unit).

  • base (float) – The base for this unit (as the base of the exponent). Must be 10, the only supported base; other values raise ValueError.

  • factor (float) – The factor for this unit (as the conversion factor), e.g. a factor of 1 cal = 4.18400 J, where 4.18400 is the factor. Defaults to 1.

  • auto_simplify (bool) – Display arithmetic results with exactly this unit’s dimension and magnitude as this unit. Defaults to False.

  • unicode (str | None) – Unicode symbol (e.g. 'Ω'), used by to_string('unicode') and accepted by the parser. Defaults to dispname.

  • latex (str | None) – LaTeX symbol (e.g. r'\Omega'). Defaults to \mathrm{dispname}.

Returns:

u – The new unit.

Return type:

Unit

Examples

>>> import saiunit as u
>>> from saiunit import Dimension
>>> energy_dim = u.joule.dim
>>> cal = u.Unit.create(energy_dim, 'calorie', 'cal', factor=4.184)
>>> cal
Unit("cal")
static create_power(baseunit, n, name=None)[source]#

Create and register a power alias such as cmetre2 = cm^2.

Parameters:
  • baseunit (Unit) – The unit to raise to a power.

  • n (int) – The exponent.

  • name (str | None) – The full name; defaults to baseunit.name + str(n).

Returns:

A unit equal to baseunit ** n that displays as 'cm^2' and is registered under name.

Return type:

Unit

Examples

>>> import saiunit as u
>>> cm2 = u.Unit.create_power(u.cmetre, 2)
>>> cm2.name, str(cm2)
('cmetre2', 'cm^2')
static create_scaled_unit(baseunit, scalefactor)[source]#

Create a scaled unit from a base unit.

The scaled unit inherits the Unicode/LaTeX symbols of the base unit (kohm renders kΩ) and, except for the da, h, d and c prefixes, its auto_simplify flag.

Parameters:
  • baseunit (Unit) – The unit of which to create a scaled version, e.g. volt, amp.

  • scalefactor (str) – The scaling factor, e.g. "m" for mvolt, mamp

Returns:

u – The new unit.

Return type:

Unit

Examples

>>> import saiunit as u
>>> uvolt = u.Unit.create_scaled_unit(u.volt, 'u')
>>> uvolt.name
'uvolt'
>>> uvolt.scale
-6
property dim: Dimension#

Return the physical unit dimensions of this unit.

Returns:

The Dimension instance describing the physical dimensions (e.g. length, mass, time, …).

Return type:

Dimension

Examples

>>> import saiunit as u
>>> u.volt.dim
metre ** 2 * kilogram * second ** -3 * amp ** -1
property dispname#

Return the display name of the unit.

The display name is the canonical string used when rendering the unit (e.g. 'V' for volt, 'mV' for millivolt), identical to str(unit).

Returns:

The display name of the unit.

Return type:

str

Examples

>>> import saiunit as u
>>> u.volt.dispname
'V'
>>> u.mvolt.dispname
'mV'
property factor: float#

Return the conversion factor of the unit.

The factor represents a multiplicative constant that converts a quantity expressed in this unit to its base-unit equivalent. For example, 1 calorie = 4.184 joule, so calorie.factor == 4.184.

Returns:

The conversion factor.

Return type:

float

Examples

>>> import saiunit as u
>>> u.volt.factor
1.0
factorless()[source]#

Return an equivalent Unit with the factor set to 1.

If this unit already has factor == 1, the unit itself is returned unchanged. (Substituting a registry-preferred alias here would silently rename units, e.g. becquerel → hertz or steradian → radian.)

Returns:

This unit if its factor is already 1, otherwise a Unit with the factor set to 1 (the registered standard unit for the same dimension/scale when one exists).

Return type:

Unit

Notes

For a dimensionless unit, the result may carry an angular label (e.g. rad) even though the input was a plain ratio: saiunit does not distinguish angle from ratio in the dimensionless registry keyspace.

Examples

>>> import saiunit as u
>>> pound = u.Unit.create(
...     u.get_or_create_dimension(kg=1), 'pound', 'lb', factor=0.453592)
>>> pound.factor
0.453592
>>> pound.factorless().factor
1.0
has_same_base(other)[source]#

Whether this Unit has the same base as another Unit.

Parameters:

other (Unit) – The other Unit to compare with.

Returns:

Whether the two Units have the same base.

Return type:

bool

Examples

>>> import saiunit as u
>>> u.volt.has_same_base(u.amp)
True
>>> u.volt.has_same_base(u.mvolt)
True
has_same_dim(other)[source]#

Whether this Unit has the same unit dimensions as another Unit.

Parameters:

other (Unit) – The other Unit to compare with.

Returns:

Whether the two Units have the same unit dimensions.

Return type:

bool

Examples

>>> import saiunit as u
>>> u.volt.has_same_dim(u.mvolt)
True
>>> u.volt.has_same_dim(u.amp)
False
has_same_magnitude(other)[source]#

Whether this Unit has the same magnitude as another Unit.

Two units have the same magnitude when they share the same scale, base, and factor. Note that the comparison is component-wise, not on the computed product factor * base**scale: a unit encoded as scale=3 and one encoded as factor=1000. have equal magnitude products but compare unequal here.

Note also that comparing quantities across factor units after conversion is exact-float equality: e.g. 1*u.inch == 25.4*u.mm is False (the conversion ratio is off by one ulp). For factor units, prefer u.math.isclose over ==.

Parameters:

other (Unit) – The other Unit to compare with.

Returns:

Whether the two Units have the same magnitude.

Return type:

bool

Examples

>>> import saiunit as u
>>> u.mvolt.has_same_magnitude(u.mamp)
True
>>> u.mvolt.has_same_magnitude(u.volt)
False
property is_fullname: bool#

Whether this is a named unit (or power alias) rather than a composite.

property is_unitless: bool#

Whether the unit is dimensionless with no scaling.

A unit is considered unitless when its dimension is dimensionless, its scale exponent is 0, and its factor is 1.0.

Returns:

True if the unit is unitless, False otherwise.

Return type:

bool

Examples

>>> import saiunit as u
>>> u.UNITLESS.is_unitless
True
>>> u.volt.is_unitless
False
property magnitude: float#

Return the absolute magnitude of the unit.

The magnitude is computed as factor * base ** scale and represents the overall multiplicative factor that converts a value in this unit to the corresponding base-unit value.

Returns:

The absolute magnitude of the unit. Extreme scales whose magnitude exceeds the float range yield inf (IEEE-754 overflow semantics) rather than raising.

Return type:

float

Examples

>>> import saiunit as u
>>> u.mvolt.magnitude
0.001
>>> u.kvolt.magnitude
1000.0
property name#

Return the full name of the unit.

For composite units this is the canonical display string.

Returns:

The full name of the unit (e.g. 'volt', 'mvolt').

Return type:

str

Examples

>>> import saiunit as u
>>> u.volt.name
'volt'
>>> u.mvolt.name
'mvolt'
reverse()[source]#

Return the multiplicative inverse of this unit.

Computes 1 / self, producing a new unit with negated scale, inverted factor, and reciprocal dimensions. u.reverse().reverse() equals u exactly.

Returns:

A new Unit representing the reciprocal of this unit.

Return type:

Unit

Examples

>>> import saiunit as u
>>> u.second.reverse()
Unit("Hz")
>>> u.metre.reverse()
Unit("1 / m")
property scale: float | int#

Return the scale exponent of the unit.

The scale is the integer exponent applied to base to produce the unit’s magnitude relative to the base unit. For example, mvolt has scale == -3 (i.e. 10 ** -3).

Returns:

The scale exponent.

Return type:

float or int

Examples

>>> import saiunit as u
>>> u.mvolt.scale
-3
property should_display_unit: bool#

Whether the unit should be shown in formatted output.

Returns True unless the unit renders as "1": dimensionless units that carry a meaningful name (e.g. radian, steradian) or a scale (mV / V) are shown.

Returns:

True if the unit should be displayed, False otherwise.

Return type:

bool

Examples

>>> import saiunit as u
>>> u.volt.should_display_unit
True
>>> u.UNITLESS.should_display_unit
False
simplify()[source]#

Return the registered unit with exactly this unit’s value, if any.

Unit arithmetic only collapses onto a curated set of units (kg * m / s^2 displays as N, but V * s stays V * s). simplify collapses onto any registered unit, e.g. V * s → Wb and mol / l → M. Dimensionless units, and units with no registered match, become an anonymous unit (mV / V → 10^-3).

Returns:

A unit equal to this one.

Return type:

Unit

Examples

>>> import saiunit as u
>>> (u.volt * u.second).simplify()
Unit("Wb")
>>> (u.mvolt / u.volt).simplify()
Unit("10^-3")
to_string(format='ascii')[source]#

Render the unit as a string.

Parameters:

format (str) – One of 'ascii' (canonical, parseable: mS * nA / cm^2), 'ascii_inline' (mS * nA * cm^-2), 'unicode' (mS·nA / cm²), 'unicode_inline' (mS·nA·cm⁻²), 'latex' (\frac{\mathrm{mS}\,\mathrm{nA}}{\mathrm{cm}^{2}}) or 'latex_inline'.

Return type:

str

Examples

>>> import saiunit as u
>>> (u.uF / u.cm ** 2).to_string('unicode')
'µF / cm²'
>>> u.kohm.to_string('latex')
'\\mathrm{k}\\Omega'