# Classes and Functions¶

## Quantities¶

class `quantiphy.``Quantity`[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). UnknownConversion(QuantiPhyError, KeyError) – A unit conversion was requested and there is no corresponding unit converter. InvalidRecognizer(QuantiPhyError, KeyError) – Assignment recognizer (assign_rec) does not match at least the value (val). UnknownScaleFactor(QuantiPhyError, ValueError) – Unknown scale factor. InvalidNumber(QuantiPhyError, ValueError, TypeError) – Not a valid number. IncompatiblePreferences(QuantiPhyError, ValueError) – radix and comma must differ.

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:

 `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, show_label, …]) 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, **kwargs) 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) – 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’. 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]:
>>> print(total)
\$13.68
```
classmethod `all_from_conv_fmt`(text, **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 ‘.’.

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. **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. A copy of text where all numbers that were formatted conventionally have been reformatted. 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. A copy of text where all numbers that were formatted with SI scale factors have been reformatted. 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. UnknownConversion(QuantiPhyError, KeyError) – A unit conversion was requested and there is no corresponding unit converter. UnknownFormatKey(QuantiPhyError, KeyError) – ‘label_fmt’ or ‘label_fmt_full’ contains an unknown format key.

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: ```[ [()] = ] [-- ] ``` where ‘=’ may be replaced by ‘:’ and ‘–’ may be replaced by ‘//’ or ‘#’. In addition, bracket 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, must be given if is given. : the name is used as a key for the value. : the name taken by the quantity. : A number with optional units (ex: 3 or 1pF or 1 kOhm), 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. 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. : 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 ``` 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. a dictionary of quantities for the values specified in the argument. dict

Example:

```>>> sagan_frequencies = r'''
...     -- Carl Sagan's SETI frequencies of high interest
...
...     f_hy = 1420.405751786 MHz -- Hydrogen line frequency
...     f_sagan1 = pi*f_hy "Hz" -- Sagan's first frequency
...     f_sagan2 = 2*pi*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’, 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). 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. UnknownConversion(QuantiPhyError, KeyError) – A unit conversion was requested and there is no corresponding unit converter. UnknownFormatKey(QuantiPhyError, KeyError) – ‘label_fmt’ or ‘label_fmt_full’ contains an unknown format key.

Example:

```>>> t = Quantity('Total = \$1000000 -- 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.000000000000
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. UnknownFormatKey(QuantiPhyError, KeyError) – ‘label_fmt’ or ‘label_fmt_full’ contains an unknown format key. UnknownConversion(QuantiPhyError, KeyError) – A unit conversion was requested and there is no corresponding unit converter.

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. 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 or real) – 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 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. 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
... )
True True False True False
```
`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')
600 kK
600M
```

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

Raises: UnknownPreference(QuantiPhyError, KeyError) – Unknown preference. UnknownScaleFactor(QuantiPhyError, ValueError) – Unknown scale factor.
`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. 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. UnknownConversion(QuantiPhyError, KeyError) – A unit conversion was requested and there is no corresponding unit converter. UnknownFormatKey(QuantiPhyError, KeyError) – ‘label_fmt’ or ‘label_fmt_full’ contains an unknown format key.

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
```
`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 and the units of the quantity and it 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. cls (class) – Class to use for return value. If not given, the class of self is used. 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' '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.*+) = (?P.*?) -- (?P.*?)', ``` 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' ``` 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’. Default is ‘si’. ‘sia’ (SI ASCII) is like ‘si’, but causes map_sf to be ignored. 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}' '{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 (real or dictionary) – 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`. nan (str) – The text to be used to represent a value that is not-a-number. By default its value is ‘NaN’. 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. 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 (‘YZEP’) and very small (‘zy’) scale factors that many people do not recognize. 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`. prec (int) – 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. 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) – When rendering, strip the radix (decimal point) if not needed from numbers even if they could then be mistaken for integers. If this setting is False, the radix is still striped if the number has a scale factor. By default this 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. 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. of strings tight_units (list) – 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’. UnknownPreference(QuantiPhyError, KeyError) – Unknown preference. UnknownScaleFactor(QuantiPhyError, ValueError) – Unknown scale factor.

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
```

## Unit Conversion¶

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

Creates a unit converter.

Just the creation of the converter is sufficient to make it available to `Quantity` (the `UnitConversion` object itself is normally discarded). Once created, it is automatically employed by `Quantity` when a conversion is requested with the given units. A forward conversion is performed if the from and to units match, and a reversion conversion is performed if they are swapped. A no-op conversion is performed when converting one from- unit to another or one to-unit to another.

Parameters: to_units (string or list of strings) – A collection of units. If given as a single string it is split. from_units (string or list of strings) – A collection of units. If given as a single string it is split. slope (float) – Scale factor for conversion. You may also pass a function as an argument, in which case it is used to perform forward conversions. In this case, intercept should also be passed a callable. intercept (float) – Conversion offset. You may also pass a function as an argument, in which case it is used to perform reverse conversions. In this case, slope should also be passed a callable.

Forward Conversion: The following conversion is applied if the given units are among the from_units and the desired units are among the to_units:

new_value = given_value * slope + intercept

Or, if slope is callable:

new_value = slope (given_value)

In this case the name slope is misleading.

Reverse Conversion: The following conversion is applied if the given units are among the to_units and the desired units are among the from_units:

new_value = (given_value - intercept)/slope

Or, if intercept is callable:

new_value = intercept (given_value)

In this case the name intercept is misleading.

No-Op Conversion: The following conversion is applied if the given and desired units are both found among the from-units or are both found among the to-units.

new_value = given_value

Example:

```>>> from quantiphy import Quantity, UnitConversion
>>> m2pc = UnitConversion('m', 'pc parsec', 3.0857e16)
```

Normally one simply discards the return value of UnitConversion, but if kept you can convert it to a string to get a summary of the conversion:

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

The act of creating this unit conversion establishes a conversion between meters (m) and parsecs (parsec, pc) that is accessible when creating or rendering quantities and can go both ways:

```>>> d_sol = Quantity('5 μpc', scale='m')  # forward conversion
>>> print(d_sol)
154.28 Gm

>>> d_ac = Quantity(1.339848, units='pc') # reverse conversion
>>> print(d_ac.render(scale='m'))
41.344e15 m

>>> d_ac = Quantity(1.339848, units='pc') # no-op conversion
>>> print(f'{d_ac:qparsec}')
1.3398 parsec
```

The conversion can employ both a slope and an intercept, and if you convert the converter object to a string, it summarizes the conversion, which can help you avoid mistakes:

```>>> conversion = UnitConversion('F', 'C', 1.8, 32)
>>> print(str(conversion))
F = 1.8*C + 32
```

You can also use functions to perform the conversions, which is appropriate when the conversion is nonlinear (cannot be described with a slope and intercept). For example:

```>>> from quantiphy import UnitConversion, Quantity
>>> from math import log10

>>> def from_dB(value):
...     return 10**(value/20)

>>> def to_dB(value):
...     return 20*log10(value)

>>> converter = UnitConversion('V', 'dBV', from_dB, to_dB)
>>> converter = UnitConversion('A', 'dBA', from_dB, to_dB)

>>> print('{:pdBV}, {:pdBV}'.format(Quantity('100mV'), Quantity('10V')))
-20 dBV, 20 dBV

>>> print('{:qV}, {:qV}'.format(Quantity('-20 dBV'), Quantity('20 dBV')))
100 mV, 10 V

>>> print('{:pdBA}, {:pdBA}'.format(Quantity('100mA'), Quantity('10A')))
-20 dBA, 20 dBA

>>> print('{:qA}, {:qA}'.format(Quantity('-20 dBA'), Quantity('20 dBA')))
100 mA, 10 A
```
`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:

```>>> 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')
```

## 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. ExpectedQuantity(QuantiPhyError, ValueError) – value must be an instance of `Quantity` or it must be a string that can be converted to a quantity. MissingName(QuantiPhyError, NameError) – alias was not specified and no name was available from value.

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. 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. This exception is raised if input_sf contains an unknown scale factor.

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

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