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
factoris the conversion factor of the unit (e.g.1 calorie = 4.18400 Joule, so the factor is 4.18400), thebaseis the base of the exponent (e.g. 10 for the kilo prefix), thescaleis the exponent of the base (e.g. 3 for the kilo prefix), and thedimensionis the physical dimensions of the unit (e.g.joulefor 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 toDIMENSIONLESS.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 raiseValueError.factor (
int|float) – The conversion factor of the unit. Must be positive. Defaults to 1.is_fullname (
bool) – Whethernameis the canonical full name. Defaults toTrue.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 ** 2ismS * nA / cm^2andu.mV * u.msisms * mV. Terms are ordered canonically (numerator first, then by symbol), soa * bandb * adisplay 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 thatparse_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
Unitoperand differently. Comparing aQuantityagainst a bareUnitimplicitly reads the unit as “one of that unit” (1 * unit), soQuantity(1, mV) == mVisTrue. Addition/subtraction, by contrast, reject a bareUnitoperand outright (Quantity(1, mV) + mVraisesTypeError), 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
scalepower to produce the unit’s magnitude. For SI-prefixed units this is 10 (e.g.kilomeans10 ** 3).- Returns:
The base of the exponent.
- Return type:
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:
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 tocreate_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 raiseValueError.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 byto_string('unicode')and accepted by the parser. Defaults todispname.latex (
str|None) – LaTeX symbol (e.g.r'\Omega'). Defaults to\mathrm{dispname}.
- Returns:
u – The new unit.
- Return type:
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:
- Returns:
A unit equal to
baseunit ** nthat displays as'cm^2'and is registered under name.- Return type:
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 (
kohmrenderskΩ) and, except for theda,h,dandcprefixes, itsauto_simplifyflag.- Parameters:
- Returns:
u – The new unit.
- Return type:
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
Dimensioninstance describing the physical dimensions (e.g. length, mass, time, …).- Return type:
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 tostr(unit).- Returns:
The display name of the unit.
- Return type:
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:
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:
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
baseas another Unit.- Parameters:
other (
Unit) – The other Unit to compare with.- Returns:
Whether the two Units have the same base.
- Return type:
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:
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, andfactor. Note that the comparison is component-wise, not on the computed productfactor * base**scale: a unit encoded asscale=3and one encoded asfactor=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.mmisFalse(the conversion ratio is off by one ulp). For factor units, preferu.math.iscloseover==.- Parameters:
other (
Unit) – The other Unit to compare with.- Returns:
Whether the two Units have the same magnitude.
- Return type:
Examples
>>> import saiunit as u >>> u.mvolt.has_same_magnitude(u.mamp) True >>> u.mvolt.has_same_magnitude(u.volt) False
- 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:
Trueif the unit is unitless,Falseotherwise.- Return type:
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 ** scaleand 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:
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:
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()equalsuexactly.- Returns:
A new Unit representing the reciprocal of this unit.
- Return type:
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
baseto produce the unit’s magnitude relative to the base unit. For example,mvolthasscale == -3(i.e.10 ** -3).Examples
>>> import saiunit as u >>> u.mvolt.scale -3
- property should_display_unit: bool#
Whether the unit should be shown in formatted output.
Returns
Trueunless the unit renders as"1": dimensionless units that carry a meaningful name (e.g. radian, steradian) or a scale (mV / V) are shown.- Returns:
Trueif the unit should be displayed,Falseotherwise.- Return type:
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^2displays asN, butV * sstaysV * s).simplifycollapses onto any registered unit, e.g.V * s→Wbandmol / 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:
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:
Examples
>>> import saiunit as u >>> (u.uF / u.cm ** 2).to_string('unicode') 'µF / cm²' >>> u.kohm.to_string('latex') '\\mathrm{k}\\Omega'