Classes and Functions

Quantities

class quantiphy.Quantity(value, model=None, *, units=None, scale=None, binary=None, name=None, desc=None, ignore_sf=None, params=None)[source]

Create a physical quantity.

A quantity is a number paired with a unit of measure.

Parameters
  • value (real, string or quantity) – The value of the quantity. If a string, it may be the name of a pre-defined constant or it may be a number that may be specified with SI scale factors and/or units. For example, the following are all valid: ‘2.5ns’, ‘1.7 MHz’, ‘1e6Ω’, ‘2.8_V’, ‘1e4 m/s’, ‘$10_000’, ‘42’, ‘ħ’, etc. The string may also have name and description if they are provided in a way recognizable by assign_rec. For example, ‘trise: 10ns — rise time’ or ‘trise = 10ns # rise time’ would work with the default recognizer.

  • model (quantity or string) – Used to pick up any missing attibutes (units, name, desc). May be a quantity or a string. If model is a quantity, only its units would be taken. If model is a string, it is split. Then, if there is one item, it is taken to be units. If there are two, they are taken to be name and units. And if there are three or more, the first two are taken to the be name and units, and the remainder is taken to be description.

  • units (str) – Overrides the units taken from value or model.

  • scale (float, tuple, func, string, or quantity) –

    • If a float or quantity, it multiplies by the given value to compute the value of the quantity. If a quantity, the units are ignored.

    • If a tuple, the first value, a float, is treated as a scale factor and the second value, a string, is take to be the units of the quantity.

    • If a function, it takes two arguments, the given value and the units and it returns two values, the value and units of the quantity.

    • If a string, it is taken to the be desired units. This value along with the units of the given value are used to select a known unit conversion, which is applied to create the quantity.

  • name (str) – Overrides the name taken from value or model.

  • desc (str) – Overrides the desc taken from value or model.

  • ignore_sf (bool) – Assume the value given within a string does not employ a scale factors. In this way, ‘1m’ is interpreted as 1 meter rather than 1 milli.

  • binary (bool) – Allow use of binary scale factors (Ki, Mi, Gi, Ti, Pi, Ei, Zi, Yi).

  • params – Parameters to be used in scaling. May be scalar, tuple, or dictionary.

Raises

You can use Quantity to create quantities from floats, strings, or other You can use Quantity to create quantities from floats, strings, or other quantities. If a float is given, model or units would be used to specify the units.

Examples:

>>> from quantiphy import Quantity
>>> from math import pi, tau
>>> newline = '''
... '''

>>> fhy = Quantity('1420.405751786 MHz')
>>> sagan = Quantity(pi*fhy, 'Hz')
>>> sagan2 = Quantity(tau*fhy, fhy)
>>> print(fhy, sagan, sagan2, sep=newline)
1.4204 GHz
4.4623 GHz
8.9247 GHz

You can use scale to scale the number or convert to different units when creating the quantity.

Examples:

>>> Tfreeze = Quantity('273.15 K', ignore_sf=True, scale='°C')
>>> print(Tfreeze)
0 °C

>>> Tboil = Quantity('212 °F', scale='°C')
>>> print(Tboil)
100 °C

Public Methods:

reset_prefs()

Reset preferences

set_prefs(**kwargs)

Set class preferences.

get_pref(name)

Get class preference.

prefs(**kwargs)

Set class preferences.

is_infinite()

Test value to determine if quantity is infinite.

is_nan()

Test value to determine if quantity is not a number.

as_tuple()

Return a tuple that contains the value as a float along with its units.

scale(scale[, cls])

Scale a quantity to create a new quantity.

add(addend[, check_units])

Create a new quantity that is the sum of the original and a contribution.

render(*[, form, show_units, prec, ...])

Convert quantity to a string.

fixed(*[, show_units, prec, show_label, ...])

Convert quantity to fixed-point string.

binary(*[, show_units, prec, show_label, ...])

Convert quantity to string using binary scale factors.

is_close(other[, reltol, abstol, check_units])

Are values equivalent?

format([template])

Convert quantity to string under the guidance of a template.

extract(text[, predefined])

Extract quantities.

map_sf_to_sci_notation(sf)

Render scale factors in scientific notation.

map_sf_to_greek(sf)

Render scale factors in Greek alphabet if appropriate.

all_from_conv_fmt(text[, only_e_notation])

Convert all numbers and quantities from conventional notation.

all_from_si_fmt(text, **kwargs)

Convert all numbers and quantities from SI notation.


add(addend, check_units=False)[source]

Create a new quantity that is the sum of the original and a contribution.

Parameters
  • addend (real, quantity, string) – The amount to add to the quantity.

  • check_units (boolean or 'strict') – If True, raise an exception if the units of the addend are not compatible with the underlying quantity. If the addend does not have units, then it is considered compatible unless check_units is ‘strict’.

Raises

IncompatibleUnits(QuantiPhyError, TypeError) – Units of contribution do not match those of underlying quantity.

Example:

>>> total = Quantity(0, '$')
>>> for contribution in [1.23, 4.56, 7.89]:
...     total = total.add(contribution)
>>> print(total)
$13.68
classmethod all_from_conv_fmt(text, only_e_notation=False, **kwargs)[source]

Convert all numbers and quantities from conventional notation.

Only supports a subset of the conventional formats that QuantiPhy normally accepts. For example, leading units (ex. $1M) and embedded commas are not supported, and the radix is always ‘.’.

There may be a space between the number an units, but it cannot be a normal space. Only non-breaking, thin-non-breaking and thin spaces are allowed.

Parameters
  • text (str) – A search and replace is performed on this text. The search looks for numbers and quantities in floating point or e-notation. They are replaced with the same number rendered as a quantity. To be recognized any units must be simple (only letters or underscores, no digits or symbols) and the units must be immediately adjacent to the number.

  • only_e_notation (bool) – If true, only numbers that explicitly have exponents are converted (1e6Hz is converted, but not 1.6 or 2009). If False, numbers with or without exponents are converted ( 1e6Hz, 1.6 and 2009 are all converted.

  • **kwargs – By default the numbers are rendered using the currently active preferences, but any valid argument to Quantity.render() can be passed in to control the rendering.

Returns

A copy of text where all numbers that were formatted conventionally have been reformatted.

Return type

str

Example:

>>> text = 'Applying stimulus @ 2.05000e-05s: V(in) = 5.00000e-01V.'
>>> with Quantity.prefs(spacer=''):
...     xlated = Quantity.all_from_conv_fmt(text)
...     print(xlated)
Applying stimulus @ 20.5us: V(in) = 500mV.
classmethod all_from_si_fmt(text, **kwargs)[source]

Convert all numbers and quantities from SI notation.

Only supports a subset of the SI formats that QuantiPhy normally accepts. For example, leading units (ex. $1M) and embedded commas are not supported, and the radix is always ‘.’.

Parameters
  • text (str) – A search and replace is performed on this text. The search looks for numbers and quantities formatted in SI notation (must have either a scale factor or units or both). They are replaced with the same number rendered as a quantity. To be recognized any units must be simple (only letters or underscores, no digits or symbols) and the units must be immediately adjacent to the number.

  • **kwargs – By default the numbers are rendered using the currently active preferences, but any valid argument to Quantity.render() can be passed in to control the rendering.

Returns

A copy of text where all numbers that were formatted with SI scale factors have been reformatted.

Return type

str

Example:

>>> print(Quantity.all_from_si_fmt(xlated))
Applying stimulus @ 20.5 us: V(in) = 500 mV.

>>> print(Quantity.all_from_si_fmt(xlated, form='eng'))
Applying stimulus @ 20.5e-6 s: V(in) = 500e-3 V.
as_tuple()[source]

Return a tuple that contains the value as a float along with its units.

Example:

>>> period = Quantity('10ns')
>>> period.as_tuple()
(1e-08, 's')
binary(*, show_units=None, prec=None, show_label=None, strip_zeros=None, strip_radix=None, scale=None)[source]

Convert quantity to string using binary scale factors.

When in range the number is divided by some integer power of 1024 and the appropriate scale factor is added to the quotient, where the scale factors are ‘’ for 0 powers of 1024, ‘Ki’ for 1, ‘Mi’ for 2, ‘Gi’ for 3, ‘Ti’ for 4, ‘Pi’ for 5, ‘Ei’ for 6, ‘Zi’ for 7 and ‘Yi for 8. Outside this range, the number is converted to a string using a simple floating point format.

Within the range the number of significant figures used is equal to prec+1. Outside the range, prec give the number of figures to the right of the decimal point.

Parameters
  • show_units (bool) – Whether the units should be included in the string.

  • prec (integer or 'full') – The desired precision (number of digits to the right of the radix when normalized). If specified as ‘full’, full_prec is used as the number of digits (and not the originally specified precision as with render).

  • show_label ('f', 'a', or boolean) –

    Add the name and possibly the description when rendering a quantity to a string. Either label_fmt or label_fmt_full is used to label the quantity.

    • neither is used if show_label is False,

    • otherwise label_fmt is used if quantity does not have a description or if show_label is ‘a’ (short for abbreviated),

    • otherwise label_fmt_full is used if show_desc is True or show_label is ‘f’ (short for full).

  • strip_zeros (boolean) – Remove contiguous zeros from end of fractional part. If not specified, the global strip_zeros setting is used.

  • strip_radix (boolean) – Remove radix if there is nothing to the right of it. If not specified, the global strip_radix setting is used.

  • scale (real, pair, function, or string) –

    • If a float, it scales the displayed value (the quantity is multiplied by scale before being converted to the string).

    • If a tuple, the first value, a float, is treated as a scale factor and the second value, a string, is take to be the units of the displayed value.

    • If a function, it takes two arguments, the value and the units of the quantity and it returns two values, the value and units of the displayed value.

    • If a string, it is taken to the be desired units. This value along with the units of the quantity are used to select a known unit conversion, which is applied to create the displayed value.

Raises

Example:

>>> t = Quantity('mem = 16 GiB — amount of physical memory', binary=True)
>>> print(
...     t.binary(),
...     t.binary(prec=3, strip_zeros=False),
...     t.binary(show_label=True, scale='b'), sep=newline)
16 GiB
16.00 GiB
mem = 128 Gib
classmethod extract(text, predefined=None, **kwargs)[source]

Extract quantities.

Takes a string that contains quantity definitions, one per line, and returns those quantities in a dictionary.

Parameters
  • text (str) –

    The string that contains the quantities, one definition per line. Each is parsed by assign_rec. By default, the lines are assumed to be of the form:

    [<name> [(<qname>)] = <value>] [— <description>]
    

    where ‘=’ may be replaced by ‘:’ and ‘—’ (the em-dash) may be replaced by ‘–’, ‘//’ or ‘#’. In addition, brackets delimit optional fields and parentheses represent literal parentheses. Each of the fields are allowed be largely arbitrary strings.

    The brackets indicate that the name/value pair and the description is optional. However, <name> must be given if <value> is given.

    <name>:

    the name is used as a key for the value.

    <qname>:

    the name taken by the quantity.

    <value>:

    A number with optional units (ex: 3 or 1pF or 1 kΩ); the units need not be a simple identifier (ex: 9.07 GHz/V).

    The value may also be an expression. When giving an expression, you may follow it with a string surrounded by double quotes, which is taken as the units. For example: Tstop = 5/Fin “s”. The expressions may only contain value defined previously in the same set of definitions, values contained in predefined, physical constants, the mathematical constants pi and tau (2*pi), which may be named π or τ, or number literals without scale factors or units. The units should not include a scale factor.

    When processing the value, it is passed as an argument to Quantity, if cannot be converted to a quantity, then it is treated as a Python expression.

    <description>:

    Optional textual description (ex: Frequency of hydrogen line).

    Blank lines and any line that does not contain a value are ignored. So with the default assign_rec, lines with the following form are ignored:

    — comment
    -- comment
    # comment
    // comment
    

  • predefined (dict) –

    A dictionary of predefined values. When specified, these values become available to be used in the expressions that give values to the values being defined. You can use locals() as this argument to make all local variables available.

    You can specify both values and functions. For example, predefined=dict(sqrt=sqrt) allows sqrt to be used in expressions.

  • **kwargs – Any argument that can be passed to Quantity can be passed to this function, and are in turn passed to Quantity as the quantities are created. This can be used, for example, to allow the binary scale factors.

Returns

a dictionary of quantities for the values specified in the argument.

Return type

dict

Example:

>>> sagan_frequencies = r'''
...     — Carl Sagan's SETI frequencies of high interest
...
...     f_hy = 1420.405751786 MHz — Hydrogen line frequency
...     f_sagan1 = π*f_hy "Hz" — Sagan's first frequency
...     f_sagan2 = τ*f_hy "Hz" — Sagan's second frequency
... '''
>>> freqs = Quantity.extract(sagan_frequencies)
>>> for f in freqs.values():
...     print(f.render(show_label='f'))
f_hy = 1.4204 GHz — Hydrogen line frequency
f_sagan1 = 4.4623 GHz — Sagan's first frequency
f_sagan2 = 8.9247 GHz — Sagan's second frequency

>>> globals().update(freqs)
>>> print(f_hy, f_sagan1, f_sagan2, sep=newline)
1.4204 GHz
4.4623 GHz
8.9247 GHz
fixed(*, show_units=None, prec=None, show_label=None, show_commas=None, strip_zeros=None, strip_radix=None, scale=None)[source]

Convert quantity to fixed-point string.

Parameters
  • show_units (bool) – Whether the units should be included in the string.

  • prec (integer or 'full') – The desired precision (one plus this value is the desired number of digits). If specified as ‘full’, the full original precision is used.

  • show_label ('f', 'a', or boolean) –

    Add the name and possibly the description when rendering a quantity to a string. Either label_fmt or label_fmt_full is used to label the quantity.

    • neither is used if show_label is False,

    • otherwise label_fmt is used if quantity does not have a description or if show_label is ‘a’ (short for abbreviated),

    • otherwise label_fmt_full is used if show_desc is True or show_label is ‘f’ (short for full).

  • show_commas – Add commas to whole part of mantissa, every three digits. If not specified, the global strip_zeros setting is used.

  • strip_zeros (boolean) – Remove contiguous zeros from end of fractional part. If not specified, the global strip_zeros setting is used.

  • strip_radix (boolean) – Remove radix if there is nothing to the right of it. If not specified, the global strip_radix setting is used.

  • scale (real, pair, function, or string) –

    • If a float, it scales the displayed value (the quantity is multiplied by scale before being converted to the string).

    • If a tuple, the first value, a float, is treated as a scale factor and the second value, a string, is take to be the units of the displayed value.

    • If a function, it takes two arguments, the value and the units of the quantity and it returns two values, the value and units of the displayed value.

    • If a string, it is taken to the be desired units. This value along with the units of the quantity are used to select a known unit conversion, which is applied to create the displayed value.

Raises

Example:

>>> t = Quantity('Total = $1000000.00 — the total')
>>> print(
...     t.fixed(),
...     t.fixed(show_commas=True),
...     t.fixed(show_units=False), sep=newline)
$1000000
$1,000,000
1000000

>>> print(
...     t.fixed(prec=2, strip_zeros=False, show_commas=True),
...     t.fixed(prec=6),
...     t.fixed(strip_zeros=False, prec=6), sep=newline)
$1,000,000.00
$1000000
$1000000.000000

>>> print(
...     t.fixed(strip_zeros=False, prec='full'),
...     t.fixed(show_label=True),
...     t.fixed(show_label='f'), sep=newline)
$1000000.00
Total = $1000000
Total = $1000000 — the total

>>> print(
...     t.fixed(scale=(1/10000, 'BTC')),
...     t.fixed(scale=(1/1000, 'ETH')),
...     t.fixed(scale=(1/1000, 'ETH'), show_units=False), sep=newline)
100 BTC
1000 ETH
1000
format(template='')[source]

Convert quantity to string under the guidance of a template.

Supports the normal floating point and string format types as well some new ones. If the format code is given in upper case, label_fmt is used to add the name and perhaps description to the result.

Parameters

template (str) – the format string.

Raises

The format is specified using A#W,.PTU where:

A   is a character and gives the alignment: either '', '>', '<', or '^'
#   is a literal hash that if present indicates that
    trailing zeros and radix should not be suppressed from fractional part.
W   is an integer and gives the width of the final string
,   is a literal comma, it indicates that the whole part of the
    mantissa should be partitioned into groups of three digits
    separated by commas
.P  is a literal period followed by an integer that gives the precision
T   is a character and gives the type: choose from p, q, r, s, e, f, g, u, n, d, ...
U   is a string that must match a known unit, it invokes scaling

Each of these component pieces is optional.

If:

q = Quantity('f = 1420.405751786 MHz — hydrogen line')

then:

q: quantity [si=y, units=y, label=n] (ex: 1.4204 GHz)
Q: quantity [si=y, units=y, label=y] (ex: f = 1.4204 GHz)
r: real [si=y, units=n, label=n] (ex: 1.4204G)
R: real [si=y, units=n, label=y] (ex: f = 1.4204G)
 : [label=n] (ex: 1.4204 GHz)
p: fixed-point [fixed=y, units=y, label=n] (ex: 1420405751.7860 Hz)
P: fixed-point [fixed=y, units=y, label=y] (ex: f = 1420405751.7860 Hz)
s: string [label=n] (ex: 1.4204 GHz)
S: string [label=y] (ex: f = 1.4204 GHz)
e: exponential form [si=n, units=n, label=n] (ex: 1.4204e9)
E: exponential form [si=n, units=n, label=y] (ex: f = 1.4204e9)
f: float [label=n] (ex: 1420400000.0000)
F: float [label=y] (ex: f = 1420400000.0000)
g: generalized float [label=n] (ex: 1.4204e+09)
G: generalized float [label=y] (ex: f = 1.4204e+09)
u: units only (ex: Hz)
n: name only (ex: f)
d: description only (ex: hydrogen line)
classmethod get_pref(name)[source]

Get class preference.

Returns the value of given preference.

Parameters

name (str) – Name of the desired preference. See Quantity.set_prefs() for list of preferences.

Raises

UnknownPreference(QuantiPhyError, KeyError) – unknown preference.

Example:

>>> Quantity.set_prefs(known_units='au')
>>> known_units = Quantity.get_pref('known_units')
>>> known_units.append('pc')
>>> Quantity.set_prefs(known_units=known_units)
>>> print(Quantity.get_pref('known_units'))
['au', 'pc']
is_close(other, reltol=None, abstol=None, check_units=True)[source]

Are values equivalent?

Indicates whether the value of a quantity or real number is equivalent to that of a quantity. The two values need not be identical, they just need to be close to be deemed equivalent.

Parameters
  • other (quantity, real, or string) – The value to compare against.

  • reltol (float) – The relative tolerance. If not specified. the reltol preference is used, which defaults to 1u.

  • abstol (float) – The absolute tolerance. If not specified. the abstol preference is used, which defaults to 1p.

  • check_units (bool) – If True (the default), and if other is a quantity, compare the units of the two values, if they differ return False. Otherwise only compare the numeric values, ignoring the units.

Returns

Returns true if abs(a - b) <= max(reltol * max(abs(a), abs(b)), abstol) where a and b represent other and the numeric value of the underlying quantity.

Return type

bool

Example:

>>> print(
...     c.is_close(c),                     # should pass, is identical
...     c.is_close(c+1),                   # should pass, is close
...     c.is_close(c+1e4),                 # should fail, not close
...     c.is_close(Quantity(c+1, 'm/s')),  # should pass, is close
...     c.is_close(Quantity(c+1, 'Hz')),   # should fail, wrong units
...     c.is_close('299.7925 Mm/s'),       # should pass, is close
... )
True True False True False True
is_infinite()[source]

Test value to determine if quantity is infinite. Returns a representation of the number (sign combined with self.inf) if value is infinite and None otherwise.

Example:

>>> inf = Quantity('inf Hz')
>>> inf.is_infinite()
'inf'
is_nan()[source]

Test value to determine if quantity is not a number. Returns a representation of the number (sign combined with self.nan) if value is not a number and None otherwise.

Example:

>>> nan = Quantity('-nan Hz')
>>> nan.is_nan()
'NaN'
static map_sf_to_greek(sf)[source]

Render scale factors in Greek alphabet if appropriate.

Pass this dictionary to map_sf preference if you prefer µ rather than u.

Example:

>>> with Quantity.prefs(map_sf=Quantity.map_sf_to_greek):
...     print(Quantity('mu0').render(show_label='f'))
µ₀ = 1.2566 µH/m — permeability of free space
static map_sf_to_sci_notation(sf)[source]

Render scale factors in scientific notation.

Pass this function to map_sf preference if you prefer your large and small numbers in classic scientific notation. It also causes ‘u’ to be converted to ‘µ’. Set form to ‘eng’ to format all numbers in scientific notation.

Example:

>>> with Quantity.prefs(map_sf=Quantity.map_sf_to_sci_notation, show_label='f'):
...     print(
...         Quantity('k').render(),
...         Quantity('mu0').render(),
...         Quantity('mu0').render(form='eng'),
...         sep=newline,
...     )
k = 13.806×10⁻²⁴ J/K — Boltzmann's constant
µ₀ = 1.2566 µH/m — permeability of free space
µ₀ = 1.2566×10⁻⁶ H/m — permeability of free space
classmethod prefs(**kwargs)[source]

Set class preferences.

This is just like Quantity.set_prefs(), except it is designed to work as a context manager, meaning that it is meant to be used with Python’s with statement. It allows preferences to be set to new values temporarily. They are reset upon exiting the with statement. For example:

>>> with Quantity.prefs(ignore_sf=True):
...     t = Quantity('600_000 K')
>>> t_bad = Quantity('600_000 K')
>>> print(t, t_bad, sep=newline)
600 kK
600M

See Quantity.set_prefs() for list of available arguments.

Raises
render(*, form=None, show_units=None, prec=None, show_label=None, strip_zeros=None, strip_radix=None, scale=None, negligible=None)[source]

Convert quantity to a string.

Parameters
  • form (str) – Specifies the form to use for representing numbers by default. Choose from ‘si’, ‘sia’, ‘eng’, ‘fixed’, and ‘binary’. As an example 0.25 A is represented with 250 mA when form is ‘si’, as 250e-3 A when form is ‘eng’, and with 0.25 A when from is ‘fixed’. ‘sia’ (SI ASCII) is like ‘si’, but causes map_sf preference to be ignored. ‘binary’ is like ‘sia’, but specifies that binary scale factors be used. Default is ‘si’.

  • show_units (bool) – Whether the units should be included in the string.

  • prec (integer or 'full') – The desired precision (one plus this value is the desired number of digits). If specified as ‘full’, the full original precision is used.

  • show_label ('f', 'a', or boolean) –

    Add the name and possibly the description when rendering a quantity to a string. Either label_fmt or label_fmt_full is used to label the quantity.

    • neither is used if show_label is False,

    • otherwise label_fmt is used if quantity does not have a description or if show_label is ‘a’ (short for abbreviated),

    • otherwise label_fmt_full is used if show_desc is True or show_label is ‘f’ (short for full).

  • strip_zeros (boolean) – Remove contiguous zeros from end of fractional part. If not specified, the global strip_zeros setting is used.

  • strip_radix (boolean) – Remove radix if there is nothing to the right of it. If not specified, the global strip_radix setting is used.

  • scale (real or dict) –

    • If a float or a quantity, it scales the displayed value (the quantity is multiplied by scale before being converted to the string). If a quantity, the units are ignored.

    • If a tuple, the first value, a float, is treated as a scale factor and the second value, a string, is take to be the units of the displayed value.

    • If a function, it takes two arguments, the value and the units of the quantity and it returns two values, the value and units of the displayed value.

    • If a string, it is taken to the be desired units. This value along with the units of the quantity are used to select a known unit conversion, which is applied to create the displayed value.

  • negligible – If the absolute value of the quantity is equal to or smaller than negligible, it is rendered as 0. To make negligible a function of the units of the quantity, pass a dictionary where the keys are the units and the values are the value to use for negligible. A key of ‘’ is used for quantities with no units and a key of None provides a default value for negligible that is used if the units of the quantity are not found in the dictionary.

Raises

Example:

>>> c = Quantity('c')
>>> print(
...     c.render(),
...     c.render(form='si'),
...     c.render(form='eng'),
...     c.render(form='fixed'),
...     c.render(show_units=False),
...     c.render(prec=6),
...     c.render(prec='full'),
...     c.render(show_label=True),
...     c.render(show_label='f'),
...     sep=newline
... )
299.79 Mm/s
299.79 Mm/s
299.79e6 m/s
299792458 m/s
299.79M
299.7925 Mm/s
299.792458 Mm/s
c = 299.79 Mm/s
c = 299.79 Mm/s — speed of light

>>> print(
...     Tfreeze.render(scale='°F'),
...     Tboil.render(scale='°F'),
...     sep=newline
... )
32 °F
212 °F
classmethod reset_prefs()[source]

Reset preferences

Resets all preferences to the current preferences of the parent class. If there is no parent class, they are reset to their defaults.

scale(scale, cls=None)[source]

Scale a quantity to create a new quantity.

Parameters
  • scale (real, pair, function, string, or quantity) –

    • If a float, it scales the existing value (a new quantity is returned whose value equals the existing quantity multiplied by scale. In this case the scale is assumed unitless and so the units of the new quantity are the same as those of the existing quantity).

    • If a tuple, the first value, a float, is treated as a scale factor and the second value, a string, is taken to be the units of the new quantity.

    • If a function, it takes two arguments, the value to be scaled and its units. The value is guaranteed to be a Quantity that includes the units, so the second argument is redundant and will eventually be deprecated. The function returns two values, the value and units of the new value.

    • If a string, it is taken to the be desired units. This value along with the units of the quantity are used to select a known unit conversion, which is applied to create the new value.

    • If a quantity, the units are ignored and the scale is treated as if were specified as a unitless float.

    • If a subclass of Quantity that includes units, the units are taken to the be desired units and the behavior is the same as if a string were given, except that cls defaults to the given subclass.

  • cls (class) – Class to use for return value. If not given, the class of self is used it the units do not change, in which case Quantity is used.

Raises

UnknownConversion(QuantiPhyError, KeyError) – A unit conversion was requested and there is no corresponding unit converter.

Example:

>>> Tf = Tfreeze.scale('°F')
>>> Tb = Tboil.scale('°F')
>>> print(Tf, Tb, sep=newline)
32 °F
212 °F
classmethod set_prefs(**kwargs)[source]

Set class preferences.

Any values not passed in are left alone. Pass in None to reset a preference to its default value.

Parameters
  • abstol (float) – Absolute tolerance, used by Quantity.is_close() when determining equivalence. Default is 10⁻¹².

  • accept_binary (bool) – Allow use of binary scale factors (Ki, Mi, Gi, Ti, Pi, Ei, Zi, Yi). Default is False.

  • assign_rec (str) –

    Regular expression used to recognize an assignment. Used in constructor and extract(). By default an ‘=’ or ‘:’ separates the name from the value and a ‘—’, ‘–’, ‘#’, or ‘//’ separates the value from the description, if a description is given. So the default recognizes the following forms:

    'vel = 60 m/s'
    'vel = 60 m/s — velocity'
    'vel = 60 m/s -- velocity'
    'vel = 60 m/s # velocity'
    'vel = 60 m/s // velocity'
    'vel: 60 m/s'
    'vel: 60 m/s — velocity'
    'vel: 60 m/s -- velocity'
    'vel: 60 m/s # velocity'
    'vel: 60 m/s // velocity'
    

    The name, value, and description are identified in the regular expression using named groups the names name, val and desc. For example:

    assign_req = r'(?P<name>.*+) = (?P<val>.*?) — (?P<desc>.*?)',
    

    The regular expression is interpreted using the re.VERBOSE flag.

    When used with Quantity.extract() there are a few more features.

    First, you may also introduce comments using ‘—’, ‘–’, ‘#’, or ‘//’:

    '— comment'
    '-- comment'
    '# comment'
    '// comment'
    

    Second, you can specify an alternate name using by placing in within parentheses following the name:

    'wavelength (λ) = 21 cm — wavelength of hydrogen line'
    

    In this case, the name attribute for the quantity will be ‘λ’ and the quantity will be filed in the output dictionary using ‘wavelength’ as the key. If the alternate name is not given, then ‘wavelength’ is used for the quantity name and dictionary key.

    Third, the value may be an expression involving the previously specified values. When doing so, you can specify the units by following the value expression with a double-quoted string. The expressions may contain numeric literals, previously defined quantities, and the constants pi and tau. For example:

    parameters = Quantity.extract(r'''
        Fin = 250MHz — frequency of input stimulus
        Tstop = 10/Fin "s" — simulation stop time
    ''')
    

    In this example, the value for Tstop is given as an expression involving Fin.

  • comma (str) – The character to be used as the thousands separator. It is very common to use a comma, but using a space, period, or an underscore can be used. For your convenience, you can access a non-breaking space using Quantity.non_breaking_space, Quantity.narrow_non_breaking_space, or Quantity.thin_space.

  • form (str) – Specifies the form to use for representing numbers by default. Choose from ‘si’, ‘sia’, ‘eng’, ‘fixed’, and ‘binary’. As an example, 0.25 A is represented with 250 mA when form is ‘si’, as 250e-3 A when form is ‘eng’, and with 0.25 A when from is ‘fixed’. ‘sia’ (SI ASCII) is like ‘si’, but causes map_sf to be ignored. ‘binary’ is like ‘sia’, but specifies that binary scale factors be used. Default is ‘si’.

  • full_prec (int) – Default full precision in digits where 0 corresponds to 1 digit. Must be nonnegative. This precision is used when the full precision is requested and the precision is not otherwise known. Default is 12.

  • ignore_sf (bool) – Whether all scale factors should be ignored by default when recognizing numbers. Default is False.

  • inf (str) – The text to be used to represent infinity. By default its value is ‘inf’, but is often set to ‘∞’ (the unicode infinity symbol). You can access the Unicode infinity symbol using Quantity.infinity_symbol.

  • input_sf (str) – Which scale factors to recognize when reading numbers. The default is ‘YZEPTGMKk_cmuµμnpfazy’. You can use this to ignore the scale factors you never expect to reduce the chance of a scale factor/unit ambiguity. For example, if you expect to encounter temperatures in Kelvin and can do without ‘K’ as a scale factor, you might use ‘TGMK_munpfa’. This also gets rid of the unusual scale factors.

  • keep_components (bool) – Indicate whether components should be kept if quantity value was given as string. Doing so takes a bit of space, but allows the original precision of the number to be recreated when full precision is requested. Default is True.

  • known_units (list or string) – List of units that are expected to be used in preference to a scale factor when the leading character could be mistaken as a scale factor. If a string is given, it is split at white space to form the list. When set, any previous known units are overridden. Default is empty.

  • label_fmt (str) –

    Format string used when label is requested if the quantity does not have a description or if the description was not requested (if show_desc is False). Is passed through string .format() method. Format string takes two possible arguments named n and v for the name and value. A typical values include:

    '{n} = {v}'    (default)
    '{n}: {v}'
    

  • label_fmt_full (str) –

    Format string used when label is requested if the quantity has a description and the description was requested (if show_desc is True). Is passed through string .format() method. Format string takes four possible arguments named n, v, d and V for the name, value, description, and value as formatted by label_fmt. Typical value include:

    '{n} = {v}{d}'    (default)
    '{n} = {v} -- {d}'
    '{n} = {v} # {d}'
    '{n} = {v} // {d}'
    '{n}: {v}{d}'
    '{n}: {v} -- {d}'
    '{V}{d}'
    '{V} -- {d}'
    '{V:<20}  # {d}'
    

    The last example shows the V argument with alignment and width modifiers. In this case the modifiers apply to the name and value after being they are combined with the label_fmt. This is typically done when printing several quantities, one per line, because it allows you to line up the descriptions.

  • map_sf (dictionary or function) – Use this to change the way individual scale factors are rendered, ex: map_sf={‘u’: ‘μ’} to render micro using mu. If a function is given, it takes a single string argument, the nominal scale factor (which would be the exponent if no scale factor fits), and returns either a string or a tuple. The string is the desired scale factor. The tuple consists of the string and a flag. If the flag is True the string is treated as an exponent, otherwise it is treated as a scale factors. The difference between an exponent and a scale factor is that the spacer goes after an exponent and before a scale factor. QuantiPhy provides two predefined functions intended for use with maps_sf: Quantity.map_sf_to_greek() and Quantity.map_sf_to_sci_notation(). Default is empty.

  • minus (str) –

    The text to be used as the minus sign. By default its value is ‘-‘, but is sometimes ‘−’ (the unicode minus sign). You can access the Unicode minus sign using Quantity.minus_sign.

    This preference only affects how numbers are rendered. Both - and the unicode − are always accepted as a minus sign when interpreting strings as numbers.

  • nan (str) – The text to be used to represent a value that is not-a-number. By default its value is ‘NaN’.

  • negligible (real or dictionary) – If the absolute value of the quantity is equal to or smaller than negligible, it is rendered as 0. To make negligible a function of the units of the quantity, pass a dictionary where the keys are the units and the values are the value to use for negligible. A key of ‘’ is used for quantities with no units and a key of None provides a default value for negligible that is used if the units of the quantity are not found in the dictionary.

  • number_fmt (dictionary or function) –

    Format string used to convert the components of the number into the number itself. Normally this is not necessary. However, it can be used to perform special formatting that is helpful when aligning numbers in tables. It allows you to specify the widths and alignments of the individual components. There are three named components: whole, frac, and units. whole contains the portion of the mantissa to the left of the radix (decimal point). It is the whole mantissa if there is no radix. It also includes the sign and the leading units (currency symbols), if any. frac contains the radix and the fractional part. It also contains the exponent if the number has one. units contains the scale factor and units. The following value can be used to align both the radix and the units, and give the number a fixed width:

    number_fmt = '{whole:>3s}{frac:<4s} {units:<3s}'
    

    The various widths and alignments could be adjusted to fit a variety of needs.

    It is also possible to specify a function as number_fmt, in which case it is passed the three values in order (whole, frac and units) and is expected to return the number as a string.

  • output_sf (str) – Which scale factors to output, generally one would only use familiar scale factors. The default is ‘TGMkmunpfa’, which gets rid or the very large (‘QRYZEP’) and very small (‘zyrq’) scale factors that many people do not recognize. You can set this to Quantity.all_sf to configure Quantity to use all available output scale factors.

  • radix (str) – The character to be used as the radix. By default it is ‘.’.

  • plus (str) –

    The text to be used as the plus sign. By default it is ‘+’, but is sometimes ‘+’ (the unicode full width plus sign) or ‘’ to simply eliminate plus signs from numbers. You can access the Unicode full width plus sign using Quantity.plus_sign.

    This preference only affects how numbers are rendered. Both + and the unicode + are always accepted as a plus sign when interpreting strings as numbers.

    QuantiPhy currently does not add leading plus signs to either mantissa or exponent, so this setting is ignored.

  • prec (int or str) – Default precision in digits where 0 corresponds to 1 digit. Must be nonnegative. This precision is used when the full precision is not required. Default is 4.

  • preferred_units (dict) – A dictionary that is used when looking up the preferred units when rendering. For example, if preferred_units contains the entry: {“Ω”: “Ohms Ohm ohms ohm”}, then when rendering a quantity with units “Ohms”, “Ohm”, “ohms”, or “ohm”, the units are rendered as “Ω”.

  • reltol (float) – Relative tolerance, used by Quantity.is_close() when determining equivalence. Default is 10⁻⁶.

  • show_commas (bool) – When rendering to fixed-point string, add commas to the whole part of the mantissa, every three digits. By default this is False.

  • show_desc (bool) –

    Whether the description should be shown if it is available when showing the label. By default show_desc is False.

    Deprecated since version 2.1: Use show_label='f' instead.

  • show_label ('f', 'a', or bool) –

    Add the name and possibly the description when rendering a quantity to a string. Either label_fmt or label_fmt_full is used to label the quantity.

    • Neither is used if show_label is False,

    • otherwise label_fmt is used if quantity does not have a description or if show_label is ‘a’ (short for abbreviated),

    • otherwise label_fmt_full is used if show_desc is True or show_label is ‘f’ (short for full).

  • spacer (str) –

    The spacer text to be inserted in a string between the numeric value and the scale factor when units are present. Is generally specified to be ‘’ or ‘ ‘; use the latter if you prefer a space between the number and the units. Generally using ‘ ‘ makes numbers easier to read, particularly with complex units, and using ‘’ is easier to parse. You could also use a Unicode non-breaking space ‘ ’. For your convenience, you can access a non-breaking space using Quantity.non_breaking_space, Quantity.narrow_non_breaking_space, or Quantity.thin_space.

    Certain units, as defined using the tight_units preference, cause the spacer to be suppressed.

  • strip_radix (bool or str) –

    When rendering, strip the radix (decimal point) if not needed from numbers even if they could then be mistaken for integers.

    There are three valid values: True, False, and “cover”. If True, the radix is removed if it is the last character in the mantissa, so 1 is rendered as “1”. If False, it is not removed, so 1 is rendered as “1.”. If “cover”, the radix is replaced by “.0”, so 1 is rendered as “1.0”. Thus, “cover” is a variant of False; it also retains the radix but adds a 0 to avoid a ‘hanging’ radix.

    If this setting is False, the radix is still stripped if the number has a scale factor. The default value is True.

    Set strip_radix to False when generating output that will be read by a parser that distinguishes between integers and reals based on the presence of a decimal point or scale factor.

    Be aware that use of “cover” can give the impression of more precision than is intended. For example, 1.4 if rendered with prec=0 would be “1.0”, which suggests a precision of 1 rather than 0. This true only if prec is less than 3.

  • strip_zeros (bool) –

    When rendering, strip off any unneeded zeros from the number. By default this is True.

    Set strip_zeros to False when you would like to indicated the precision of your numbers based on the number of digits shown.

  • tight_units (list of strings) – The spacer is suppressed with these units. By default, this is done for: % ° ‘ ” ′ ″. Some add °F and °C as well.

  • unity_sf (str) – The output scale factor for unity, generally ‘’ or ‘_’. The default is ‘’, but use ‘_’ if you want there to be no ambiguity between units and scale factors. For example, 0.3 would be rendered as ‘300m’, and 300 m would be rendered as ‘300_m’.

Raises

Example:

>>> mu0 = Quantity('mu0')
>>> print(mu0)
1.2566 uH/m

>>> Quantity.set_prefs(prec=6, map_sf={'u': 'μ'})
>>> print(mu0)
1.256637 μH/m

>>> Quantity.set_prefs(prec=None, map_sf=None)
>>> print(mu0)
1.2566 uH/m

Quantity Functions

These functions are provided for those that prefer use QuantiPhy to convert numbers in strings directly to floats, rather than keep the values around as Quantity objects.

quantiphy.as_real(*args, **kwargs)[source]

Convert to real.

Takes the same arguments as Quantity, but returns a float rather than a Quantity. Takes one additional optional keyword argument …

Parameters

cls (class) – Quantity subclass used to do the conversion. If not given, Quantity is used.

Examples:

>>> from quantiphy import as_real
>>> print(as_real('1 uL'))
1e-06

>>> print(as_real('1.2 mg/L', scale='M', params=74.55))
1.6096579476861166e-05
quantiphy.as_tuple(*args, **kwargs)[source]

Convert to tuple (value, units).

Takes the same arguments as Quantity, but returns a tuple consisting of the value and units. Takes one additional optional keyword argument …

Parameters

cls (class) – Quantity subclass used to do the conversion. If not given, Quantity is used.

Examples:

>>> from quantiphy import as_tuple
>>> print(as_tuple('1 uL'))
(1e-06, 'L')

>>> print(as_tuple('1.2 mg/L', scale='M', params=74.55))
(1.6096579476861166e-05, 'M')
quantiphy.render(value, units, params=None, *args, **kwargs)[source]

Render value and units to string (SI scale factors format).

The first two arguments are the value and the units and are required. The remaining arguments are the same as those of Quantity.render().

Examples:

>>> from quantiphy import render
>>> print(render(1e-6, 'L'))
1 uL

>>> print(render(16.097e-6, 'M', scale='g/L', params=74.55))
1.2 mg/L
quantiphy.fixed(value, units, params=None, *args, **kwargs)[source]

Render value and units to string (fixed-point format).

The first two arguments are the value and the units and are required. The remaining arguments are the same as those of Quantity.fixed().

Example:

>>> from quantiphy import fixed
>>> print(fixed(1e7, '$', show_commas=True, strip_zeros=False, prec=2))
$10,000,000.00
quantiphy.binary(value, units, params=None, *args, **kwargs)[source]

Render value and units to string (binary scale factors format)

The first two arguments are the value and the units and are required. The remaining arguments are the same as those of Quantity.binary().

Example:

>>> from quantiphy import binary
>>> print(binary(2**32, 'B'))
4 GiB

Unit Conversion

class quantiphy.UnitConversion(to_units, from_units, slope=1, intercept=0)[source]

Public Methods:

activate()

Re-activate a unit conversion.

convert([value, from_units, to_units])

Convert value to quantity with new units.

clear_all()

Remove all previously defined unit conversions.

fixture(converter_func)

A decorator fixture for unit conversion functions that can be used when creating parametrized unit conversions.


activate()[source]

Re-activate a unit conversion.

Normally it is not necessary to call this method, however it can be used re-activate a previously created unit conversion that has since been overridden by a different unit conversion with the same to and from units.

classmethod clear_all()[source]

Remove all previously defined unit conversions.

convert(value=1, from_units=None, to_units=None)[source]

Convert value to quantity with new units.

A convenience method. Normally it is not needed because once created, a unit conversion becomes directly accessible to quantities and can be used both when creating or rendering the quantity.

Parameters
  • value – The value to convert. May be a real number or a quantity. Alternately, may simply be a string, in which case it is taken to be the from_units. If the value is not given it is taken to be 1.

  • from_units (str) – The units to convert from. If not given, the class’s first from_units are used.

  • to_units (str) – The units to convert to. If not given, the class’s first to_units are used.

If the from_units were found among the class’s from_units, and the to_units were found among the class’s to_units, then a forward conversion is performed.

If the from_units were found among the class’s to_units, and the to_units were found among the class’s from_units, then a reverse conversion is performed.

Raises

UnknownConversion(QuantiPhyError, KeyError) – The given units are not supported by the underlying class.

Example:

>>> print(str(m2pc))
m ← 3.0857e+16*pc

>>> m = m2pc.convert()
>>> print(str(m))
30.857e15 m

>>> pc = m2pc.convert(m)
>>> print(str(pc))
1 pc

>>> m = m2pc.convert(pc)
>>> print(str(m))
30.857e15 m

>>> m2pc.convert(30.857e15, 'm')
Quantity('1 pc')

>>> m2pc.convert(1000, 'pc')
Quantity('30.857e18 m')

>>> m2pc.convert('pc')
Quantity('30.857e15 m')
static fixture(converter_func)[source]

A decorator fixture for unit conversion functions that can be used when creating parametrized unit conversions.

Creates an argument list for the decorated function based on the type of value given for the params argument to Quantity.

If params is a dictionary or mapping, its values are passed as named parameters.

If params is a tuple or list, its values are passed as positional arguments.

Otherwise, the value of params is passed as the second argument.

In all cases, the value being converted (an instance of Quantity) is passed as the first argument to the decorated converter function.

For example, when performing conversions between the molarity of a solution and its concentration in terms of g/L, the molecular weight of the compound used to make the solution is needed:

>>> from quantiphy import Quantity, UnitConversion

>>> @UnitConversion.fixture
... def from_molarity(M, mw):
...     return M * mw

>>> @UnitConversion.fixture
... def to_molarity(g_L, mw):
...     return g_L / mw

>>> conv = UnitConversion('g/L', 'M', from_molarity, to_molarity)

>>> KCl_M = Quantity('1.2 mg/L', scale='M', params=74.55)
>>> print(KCl_M)
16.097 uM
>>> print(f"{KCl_M:qg/L}")
1.2 mg/L

>>> NaCl_M = Quantity('5.0 mg/L', scale='M', params=58.44277)
>>> print(NaCl_M)
85.554 uM
>>> print(f"{NaCl_M:qg/L}")
5 mg/L

However, if you want to convert between mass and molarity where the mass is the amount of a compound needed to create a solution of a particular volume with a particular concentration, both the molecular weight and the volume are required parameters:

>>> @UnitConversion.fixture
... def to_molarity(mass, vol, mw):
...     moles = mass/mw
...     return moles/vol

>>> @UnitConversion.fixture
... def to_grams(molarity, vol, mw):
...     return molarity*vol*mw

>>> conv = UnitConversion('g', 'M', to_grams, to_molarity)

>>> KCl_M = Quantity('1.2 g', scale='M', params=dict(mw=74.55, vol=0.250))
>>> print(KCl_M)
64.386 mM
>>> print(f"{KCl_M:pg}")
1.2 g

>>> NaCl_M = Quantity('5.0 g', scale='M', params=dict(mw=58.44277, vol=0.250))
>>> print(NaCl_M)
342.22 mM
>>> print(f"{NaCl_M:pg}")
5 g

Constants and Unit Systems

quantiphy.add_constant(value, alias=None, unit_systems=None)[source]

Create a new constant.

Save a quantity in such a way that it can later be recalled by name when creating new quantities.

Parameters
  • value (quantity) – The value of the constant. Must be a quantity or a string that can be directly converted to a quantity.

  • alias (str) – An alias for the constant. Can be used to access the constant from as an alternative to the name given in the value, which itself is optional. If the value has a name, specifying this name is optional. If both are given, the constant is accessible using either name. alias may also be a list of aliases.

  • unit_systems (list or str) – Name or names of the unit systems to which the constant should be added. If given as a string, string will be split at white space to create the list. If a constant is associated with a unit system, it is only available when that unit system is active. You need not limit yourself to the predefined ‘mks’ and ‘cgs’ unit systems. Giving a name creates the corresponding unit system if it does not already exist. If unit_systems is not given, the constant is not associated with a unit system, meaning that it is always available regardless of which unit system is active.

Raises

The constant is saved under name if given, and under the name contained within value if available. It is not necessary to supply both names, one is sufficient.

Example:

>>> from quantiphy import Quantity, add_constant
>>> add_constant('f_hy = 1420.405751786 MHz — Frequency of hydrogen line')
>>> print(Quantity('f_hy').render(show_label='f'))
f_hy = 1.4204 GHz — Frequency of hydrogen line
quantiphy.set_unit_system(unit_system)[source]

Activates a unit system.

The default unit system is ‘mks’. Calling this function changes the active unit system to the one with the specified name. Only constants associated with the active unit system or not associated with a unit system are available for use.

Parameters

unit_system (str) – Name of the desired unit system.

Raises

UnknownUnitSystem(QuantiPhyError, KeyError)unit_system does not correspond to a known unit system.

Example:

>>> from quantiphy import Quantity, set_unit_system
>>> set_unit_system('cgs')
>>> print(Quantity('h').render(show_label='f'))
h = 6.6261e-27 erg-s — Plank's constant

>>> set_unit_system('mks')
>>> print(Quantity('h').render(show_label='f'))
h = 662.61e-36 J-s — Plank's constant

Exceptions

exception quantiphy.QuantiPhyError(*args, **kwargs)[source]

QuantiPhy base exception.

All of the specific QuantiPhy exceptions subclass this exception.

render(template=None)[source]

Convert exception to a string under guidance of format string.

Parameters

template (str) – This string, along with the positional and keyword arguments of the exception are passed to the Python format() function and the result is returned. template may also be a list of strings. In this case the first string found that renders without error is used. If template is not given, the exception is rendered with the built-in template.

exception quantiphy.ExpectedQuantity(*args, **kwargs)[source]

The value is required to be a Quantity or a string that can be converted to a Quantity.

exception quantiphy.IncompatiblePreferences(*args, **kwargs)[source]

Two preferences are not compatible

exception quantiphy.IncompatibleUnits(*args, **kwargs)[source]

The units of the contribution do not match those of the underlying quantity.

exception quantiphy.InvalidNumber(*args, **kwargs)[source]

The value given could not be converted to a number.

exception quantiphy.InvalidRecognizer(*args, **kwargs)[source]

The assign_rec preference is expected to be a regular expression that defines one or more named fields, one of which must be val. This exception is raised when the current value of assign_rec does not satisfy this requirement.

exception quantiphy.MissingName(*args, **kwargs)[source]

alias was not specified and no name was available from value.

exception quantiphy.UnknownConversion(*args, **kwargs)[source]

The given units are not supported by the underlying class, or a unit conversion was requested and there is no corresponding unit converter.

exception quantiphy.UnknownFormatKey(*args, **kwargs)[source]

The label_fmt and label_fmt_full are expected to be format strings that may interpolate certain named arguments. The valid named arguments are n for name, v for value, and d for description. This exception is raised when some other name is used for an interpolated argument.

exception quantiphy.UnknownPreference(*args, **kwargs)[source]

The name given for a preference is unknown.

exception quantiphy.UnknownScaleFactor(*args, **kwargs)[source]

The input_sf preference gives the list of scale factors that should be accepted on a number. The output_sf preference gives the list of scale factors that should be used when rendering numbers. This exception is raised if input_sf or output_sf contains an unknown scale factor.

exception quantiphy.UnknownUnitSystem(*args, **kwargs)[source]

The name given does not correspond to a known unit system.