Developer reference¶
All Modules¶
pint¶
Pint is Python module/package to define, operate and manipulate physical quantities: the product of a numerical value and a unit of measurement. It allows arithmetic operations between them and conversions from and to different units.
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.
Context
(name=None, aliases=(), defaults=None)[source]¶ A specialized container that defines transformation functions from one dimension to another. Each Dimension are specified using a UnitsContainer. Simple transformation are given with a function taking a single parameter.
Conversion functions may take optional keyword arguments and the context can have default values for these arguments.
Additionally, a context may host redefinitions:
A redefinition must be performed among units that already exist in the registry. It cannot change the dimensionality of a unit. The symbol and aliases are automatically inherited from the registry.
Parameters: Example
>>> from pint.util import UnitsContainer >>> from pint import Context, UnitRegistry >>> ureg = UnitRegistry() >>> timedim = UnitsContainer({'[time]': 1}) >>> spacedim = UnitsContainer({'[length]': 1}) >>> def time_to_len(ureg, time): ... 'Time to length converter' ... return 3. * time >>> c = Context() >>> c.add_transformation(timedim, spacedim, time_to_len) >>> c.transform(timedim, spacedim, ureg, 2) 6.0 >>> def time_to_len_indexed(ureg, time, n=1): ... 'Time to length converter, n is the index of refraction of the material' ... return 3. * time / n >>> c = Context(defaults={'n':3}) >>> c.add_transformation(timedim, spacedim, time_to_len_indexed) >>> c.transform(timedim, spacedim, ureg, 2) 2.0 >>> c.redefine("pound = 0.5 kg")
-
defaults
= None¶ Maps defaults variable names to values
-
classmethod
from_context
(context, **defaults)[source]¶ Creates a new context that shares the funcs dictionary with the original context. The default values are copied from the original context and updated with the new defaults.
If defaults is empty, return the same context.
Parameters: - context (pint.Context) – Original context.
- **defaults –
Returns: Return type:
-
funcs
= None¶ Maps (src, dst) -> transformation function
-
hashable
()[source]¶ Generate a unique hashable and comparable representation of self, which can be used as a key in a dict. This class cannot define
__hash__
because it is mutable, and the Python interpreter does cache the output of__hash__
.Returns: Return type: tuple
-
redefine
(definition: str) → None[source]¶ Override the definition of a unit in the registry.
Parameters: definition (str) – <unit> = <new definition>``, e.g. pound = 0.5 kg
-
relation_to_context
= None¶ Maps (src, dst) -> self Used as a convenience dictionary to be composed by ContextChain
-
-
class
pint.
Measurement
[source]¶ Implements a class to describe a quantity with uncertainty.
Parameters: - value (pint.Quantity or any numeric type) – The expected value of the measurement
- error (pint.Quantity or any numeric type) – The error or uncertainty of the measurement
-
class
pint.
Quantity
[source]¶ Implements a class to describe a physical quantity: the product of a numerical value and a unit of measurement.
Parameters: - value (str, pint.Quantity or any numeric type) – Value of the physical quantity to be created.
- units (UnitsContainer, str or pint.Quantity) – Units of the physical quantity to be created.
-
compute
(**kwargs)[source]¶ Compute the Dask array wrapped by pint.Quantity.
Parameters: **kwargs (dict) – Any keyword arguments to pass to dask.compute
.Returns: A pint.Quantity wrapped numpy array. Return type: pint.Quantity
-
default_format
= ''¶ Default formatting string.
-
dimensionality
¶ returns: Dimensionality of the Quantity, e.g.
{length: 1, time: -1}
:rtype: dict
-
dimensionless
¶
-
classmethod
from_list
(quant_list, units=None)[source]¶ Transforms a list of Quantities into an numpy.array quantity. If no units are specified, the unit of the first element will be used. Same as from_sequence.
If units is not specified and list is empty, the unit cannot be determined and a ValueError is raised.
Parameters: - quant_list (list of pint.Quantity) – list of pint.Quantity
- units (UnitsContainer, str or pint.Quantity) – units of the physical quantity to be created (Default value = None)
Returns: Return type:
-
classmethod
from_sequence
(seq, units=None)[source]¶ Transforms a sequence of Quantities into an numpy.array quantity. If no units are specified, the unit of the first element will be used.
If units is not specified and sequence is empty, the unit cannot be determined and a ValueError is raised.
Parameters: - seq (sequence of pint.Quantity) – sequence of pint.Quantity
- units (UnitsContainer, str or pint.Quantity) – units of the physical quantity to be created (Default value = None)
Returns: Return type:
-
is_compatible_with
(other, *contexts, **ctx_kwargs)[source]¶ check if the other object is compatible
Parameters: - other – The object to check. Treated as dimensionless if not a Quantity, Unit or str.
- *contexts (str or pint.Context) – Contexts to use in the transformation.
- **ctx_kwargs – Values for the Context/s
Returns: Return type:
-
ito
(other=None, *contexts, **ctx_kwargs)[source]¶ Inplace rescale to different units.
Parameters: - other (pint.Quantity, str or dict) – Destination units. (Default value = None)
- *contexts (str or pint.Context) – Contexts to use in the transformation.
- **ctx_kwargs – Values for the Context/s
-
ito_reduced_units
()[source]¶ Return Quantity scaled in place to reduced units, i.e. one unit per dimension. This will not reduce compound units (e.g., ‘J/kg’ will not be reduced to m**2/s**2), nor can it make use of contexts at this time.
-
m
¶ Quantity’s magnitude. Short form for magnitude
-
m_as
(units)[source]¶ Quantity’s magnitude expressed in particular units.
Parameters: units (pint.Quantity, str or dict) – destination units
-
magnitude
¶ Quantity’s magnitude. Long form for m
-
persist
(**kwargs)[source]¶ Persist the Dask Array wrapped by pint.Quantity.
Parameters: **kwargs (dict) – Any keyword arguments to pass to dask.persist
.Returns: A pint.Quantity wrapped Dask array. Return type: pint.Quantity
-
prod
(axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]¶ Return the product of quantity elements over a given axis
Wraps np.prod().
-
to
(other=None, *contexts, **ctx_kwargs)[source]¶ Return Quantity rescaled to different units.
Parameters: - other (pint.Quantity, str or dict) – destination units. (Default value = None)
- *contexts (str or pint.Context) – Contexts to use in the transformation.
- **ctx_kwargs – Values for the Context/s
Returns: Return type:
-
to_compact
(unit=None)[source]¶ “Return Quantity rescaled to compact, human-readable units.
To get output in terms of a different unit, use the unit parameter.
Example
>>> import pint >>> ureg = pint.UnitRegistry() >>> (200e-9*ureg.s).to_compact() <Quantity(200.0, 'nanosecond')> >>> (1e-2*ureg('kg m/s^2')).to_compact('N') <Quantity(10.0, 'millinewton')>
-
to_reduced_units
()[source]¶ Return Quantity scaled in place to reduced units, i.e. one unit per dimension. This will not reduce compound units (intentionally), nor can it make use of contexts at this time.
-
u
¶ Quantity’s units. Short form for units
-
unitless
¶
-
units
¶ Quantity’s units. Long form for u
-
class
pint.
Unit
(units)[source]¶ Implements a class to describe a unit supporting math operations.
-
default_format
= ''¶ Default formatting string.
-
dimensionality
¶ returns: Dimensionality of the Unit, e.g.
{length: 1, time: -1}
:rtype: dict
-
dimensionless
¶ Return True if the Unit is dimensionless; False otherwise.
-
from_
(value, strict=True, name='value')[source]¶ Converts a numerical value or quantity to this unit
Parameters: - value – a Quantity (or numerical value if strict=False) to convert
- strict – boolean to indicate that only quanities are accepted (Default value = True)
- name – descriptive name to use if an exception occurs (Default value = “value”)
Returns: The converted value as this unit
Return type:
-
is_compatible_with
(other, *contexts, **ctx_kwargs)[source]¶ check if the other object is compatible
Parameters: - other – The object to check. Treated as dimensionless if not a Quantity, Unit or str.
- *contexts (str or pint.Context) – Contexts to use in the transformation.
- **ctx_kwargs – Values for the Context/s
Returns: Return type:
-
m_from
(value, strict=True, name='value')[source]¶ Converts a numerical value or quantity to this unit, then returns the magnitude of the converted value
Parameters: - value – a Quantity (or numerical value if strict=False) to convert
- strict – boolean to indicate that only quanities are accepted (Default value = True)
- name – descriptive name to use if an exception occurs (Default value = “value”)
Returns: The magnitude of the converted value
Return type:
-
-
class
pint.
UnitRegistry
(filename='', force_ndarray=False, force_ndarray_like=False, default_as_delta=True, autoconvert_offset_to_baseunit=False, on_redefinition='warn', system=None, auto_reduce_dimensions=False, preprocessors=None, fmt_locale=None, non_int_type=<class 'float'>, case_sensitive=True)[source]¶ The unit registry stores the definitions and relationships between units.
Parameters: - filename – path of the units definition file to load or line-iterable object. Empty to load the default definition file. None to leave the UnitRegistry empty.
- force_ndarray (bool) – convert any input, scalar or not to a numpy.ndarray.
- force_ndarray_like (bool) – convert all inputs other than duck arrays to a numpy.ndarray.
- default_as_delta – In the context of a multiplication of units, interpret non-multiplicative units as their delta counterparts.
- autoconvert_offset_to_baseunit – If True converts offset units in quantities are converted to their base units in multiplicative context. If False no conversion happens.
- on_redefinition (str) – action to take in case a unit is redefined. ‘warn’, ‘raise’, ‘ignore’
- auto_reduce_dimensions – If True, reduce dimensionality on appropriate operations.
- preprocessors – list of callables which are iteratively ran on any input expression or unit string
- fmt_locale – locale identifier string, used in format_babel. Default to None
- case_sensitive (bool, optional) – Control default case sensitivity of unit parsing. (Default: True)
-
check
(*args)¶ Decorator to for quantity type checking for function inputs.
Use it to ensure that the decorated function input parameters match the expected dimension of pint quantity.
- The wrapper function raises:
- pint.DimensionalityError if an argument doesn’t match the required dimensions.
- ureg : UnitRegistry
- a UnitRegistry instance.
- args : str or UnitContainer or None
- Dimensions of each of the input arguments. Use None to skip argument conversion.
Returns: the wrapped function.
Return type: callable
Raises: TypeError
– If the number of given dimensions does not match the number of function parameters.ValueError
– If the any of the provided dimensions cannot be parsed as a dimension.
-
pi_theorem
(quantities)[source]¶ Builds dimensionless quantities using the Buckingham π theorem
Parameters: quantities (dict) – mapping between variable name and units Returns: a list of dimensionless quantities expressed as dicts Return type: list
-
setup_matplotlib
(enable=True)[source]¶ Set up handlers for matplotlib’s unit support.
Parameters: enable (bool) – whether support should be enabled or disabled (Default value = True)
-
wraps
(ret, args, strict=True)¶ Wraps a function to become pint-aware.
Use it when a function requires a numerical value but in some specific units. The wrapper function will take a pint quantity, convert to the units specified in args and then call the wrapped function with the resulting magnitude.
The value returned by the wrapped function will be converted to the units specified in ret.
Parameters: - ureg (pint.UnitRegistry) – a UnitRegistry instance.
- ret (str, pint.Unit, iterable of str, or iterable of pint.Unit) – Units of each of the return values. Use None to skip argument conversion.
- args (str, pint.Unit, iterable of str, or iterable of pint.Unit) – Units of each of the input arguments. Use None to skip argument conversion.
- strict (bool) – Indicates that only quantities are accepted. (Default value = True)
Returns: the wrapper function.
Return type: callable
Raises: TypeError
– if the number of given arguments does not match the number of function parameters. if the any of the provided arguments is not a unit a string or Quantity
-
exception
pint.
DefinitionSyntaxError
(msg, *, filename=None, lineno=None)[source]¶ Raised when a textual definition has a syntax error.
-
exception
pint.
DimensionalityError
(units1, units2, dim1='', dim2='', *, extra_msg='')[source]¶ Raised when trying to convert between incompatible units.
-
exception
pint.
RedefinitionError
(name, definition_type, *, filename=None, lineno=None)[source]¶ Raised when a unit or prefix is redefined.
-
exception
pint.
UndefinedUnitError
(*unit_names)[source]¶ Raised when the units are not defined in the unit registry.
-
pint.
formatter
(items, as_ratio=True, single_denominator=False, product_fmt=' * ', division_fmt=' / ', power_fmt='{} ** {}', parentheses_fmt='({0})', exp_call=<function <lambda>>, locale=None, babel_length='long', babel_plural_form='one', sort=True)[source]¶ Format a list of (name, exponent) pairs.
Parameters: - items (list) – a list of (name, exponent) pairs.
- as_ratio (bool, optional) – True to display as ratio, False as negative powers. (Default value = True)
- single_denominator (bool, optional) – all with terms with negative exponents are collected together. (Default value = False)
- product_fmt (str) – the format used for multiplication. (Default value = ” * “)
- division_fmt (str) – the format used for division. (Default value = ” / “)
- power_fmt (str) – the format used for exponentiation. (Default value = “{} ** {}”)
- parentheses_fmt (str) – the format used for parenthesis. (Default value = “({0})”)
- locale (str) – the locale object as defined in babel. (Default value = None)
- babel_length (str) – the length of the translated unit, as defined in babel cldr. (Default value = “long”)
- babel_plural_form (str) – the plural form, calculated as defined in babel. (Default value = “one”)
- exp_call (callable) – (Default value = lambda x: f”{x:n}”)
- sort (bool, optional) – True to sort the formatted units alphabetically (Default value = True)
Returns: the formula as a string.
Return type:
-
pint.
get_application_registry
()[source]¶ Return the application registry. If
set_application_registry()
was never invoked, return a registry built usingdefaults_en.txt
embedded in the pint package.Returns: Return type: pint.UnitRegistry
-
pint.
set_application_registry
(registry)[source]¶ Set the application registry, which is used for unpickling operations and when invoking pint.Quantity or pint.Unit directly.
Parameters: registry (pint.UnitRegistry) –
pint.babel¶
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
pint.compat¶
Compatibility layer.
copyright: | 2013 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
pint.compat.
eq
(lhs, rhs, check_all: bool)[source]¶ Comparison of scalars and arrays.
Parameters: Returns: Return type: bool or array_like of bool
-
pint.compat.
is_duck_array_type
(cls) → bool[source]¶ Check if the type object represents a (non-Quantity) duck array type.
Parameters: cls (class) – Returns: Return type: bool
-
pint.compat.
is_upcast_type
(other) → bool[source]¶ Check if the type object is a upcast type using preset list.
Parameters: other (object) – Returns: Return type: bool
-
pint.compat.
isnan
(obj, check_all: bool)[source]¶ Test for NaN or NaT
Parameters: Returns: - bool or array_like of bool.
- Always return False for non-numeric types.
pint.context¶
Functions and classes related to context definitions and application.
copyright: | 2016 by Pint Authors, see AUTHORS for more details.. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.context.
Context
(name=None, aliases=(), defaults=None)[source]¶ A specialized container that defines transformation functions from one dimension to another. Each Dimension are specified using a UnitsContainer. Simple transformation are given with a function taking a single parameter.
Conversion functions may take optional keyword arguments and the context can have default values for these arguments.
Additionally, a context may host redefinitions:
A redefinition must be performed among units that already exist in the registry. It cannot change the dimensionality of a unit. The symbol and aliases are automatically inherited from the registry.
Parameters: Example
>>> from pint.util import UnitsContainer >>> from pint import Context, UnitRegistry >>> ureg = UnitRegistry() >>> timedim = UnitsContainer({'[time]': 1}) >>> spacedim = UnitsContainer({'[length]': 1}) >>> def time_to_len(ureg, time): ... 'Time to length converter' ... return 3. * time >>> c = Context() >>> c.add_transformation(timedim, spacedim, time_to_len) >>> c.transform(timedim, spacedim, ureg, 2) 6.0 >>> def time_to_len_indexed(ureg, time, n=1): ... 'Time to length converter, n is the index of refraction of the material' ... return 3. * time / n >>> c = Context(defaults={'n':3}) >>> c.add_transformation(timedim, spacedim, time_to_len_indexed) >>> c.transform(timedim, spacedim, ureg, 2) 2.0 >>> c.redefine("pound = 0.5 kg")
-
defaults
= None¶ Maps defaults variable names to values
-
classmethod
from_context
(context, **defaults)[source]¶ Creates a new context that shares the funcs dictionary with the original context. The default values are copied from the original context and updated with the new defaults.
If defaults is empty, return the same context.
Parameters: - context (pint.Context) – Original context.
- **defaults –
Returns: Return type:
-
funcs
= None¶ Maps (src, dst) -> transformation function
-
hashable
()[source]¶ Generate a unique hashable and comparable representation of self, which can be used as a key in a dict. This class cannot define
__hash__
because it is mutable, and the Python interpreter does cache the output of__hash__
.Returns: Return type: tuple
-
redefine
(definition: str) → None[source]¶ Override the definition of a unit in the registry.
Parameters: definition (str) – <unit> = <new definition>``, e.g. pound = 0.5 kg
-
relation_to_context
= None¶ Maps (src, dst) -> self Used as a convenience dictionary to be composed by ContextChain
-
-
class
pint.context.
ContextChain
[source]¶ A specialized ChainMap for contexts that simplifies finding rules to transform from one dimension to another.
-
graph
¶ The graph relating
-
hashable
()[source]¶ Generate a unique hashable and comparable representation of self, which can be used as a key in a dict. This class cannot define
__hash__
because it is mutable, and the Python interpreter does cache the output of__hash__
.
-
insert_contexts
(*contexts)[source]¶ Insert one or more contexts in reversed order the chained map. (A rule in last context will take precedence)
To facilitate the identification of the context with the matching rule, the relation_to_context dictionary of the context is used.
-
pint.converters¶
Functions and classes related to unit conversions.
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.converters.
LogarithmicConverter
(scale, logbase, logfactor)[source]¶ Converts between linear units and logarithmic units, such as dB, octave, neper or pH. Q_log = logfactor * log( Q_lin / scale ) / log(log_base)
Parameters:
pint.definitions¶
Functions and classes related to unit definitions.
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.definitions.
AliasDefinition
(name, aliases)[source]¶ Additional alias(es) for an already existing unit:
@alias <canonical name or previous alias> = <alias> [ = <alias> ] [...]
Example:
@alias meter = my_meter
-
classmethod
from_string
(definition, non_int_type=<class 'float'>)[source]¶ Parse a definition.
Parameters: - definition (str or PreprocessedDefinition) –
- non_int_type (type) –
Returns: Return type: Definition or subclass of Definition
-
classmethod
-
class
pint.definitions.
Definition
(name, symbol, aliases, converter)[source]¶ Base class for definitions.
Parameters: -
classmethod
from_string
(definition, non_int_type=<class 'float'>)[source]¶ Parse a definition.
Parameters: - definition (str or PreprocessedDefinition) –
- non_int_type (type) –
Returns: Return type: Definition or subclass of Definition
-
classmethod
-
class
pint.definitions.
DimensionDefinition
(name, symbol, aliases, converter, reference=None, is_base=False)[source]¶ Definition of a dimension:
[dimension name] = <relation to other dimensions>
Example:
[density] = [mass] / [volume]
-
classmethod
from_string
(definition, non_int_type=<class 'float'>)[source]¶ Parse a definition.
Parameters: - definition (str or PreprocessedDefinition) –
- non_int_type (type) –
Returns: Return type: Definition or subclass of Definition
-
classmethod
-
class
pint.definitions.
PrefixDefinition
(name, symbol, aliases, converter)[source]¶ Definition of a prefix:
<prefix>- = <amount> [= <symbol>] [= <alias>] [ = <alias> ] [...]
Example:
deca- = 1e+1 = da- = deka-
-
classmethod
from_string
(definition, non_int_type=<class 'float'>)[source]¶ Parse a definition.
Parameters: - definition (str or PreprocessedDefinition) –
- non_int_type (type) –
Returns: Return type: Definition or subclass of Definition
-
classmethod
-
class
pint.definitions.
PreprocessedDefinition
[source]¶ Splits a definition into the constitutive parts.
A definition is given as a string with equalities in a single line:
---------------> rhs a = b = c = d = e | | | -------> aliases (optional) | | | | | -----------> symbol (use "_" for no symbol) | | | ---------------> value | -------------------> name
-
aliases
¶ Type: tuple of str
-
rhs
¶ Type: tuple of str
-
-
class
pint.definitions.
UnitDefinition
(name, symbol, aliases, converter, reference=None, is_base=False)[source]¶ Definition of a unit:
<canonical name> = <relation to another unit or dimension> [= <symbol>] [= <alias>] [ = <alias> ] [...]
Example:
millennium = 1e3 * year = _ = millennia
Parameters: - reference (UnitsContainer) – Reference units.
- is_base (bool) – Indicates if it is a base unit.
-
classmethod
from_string
(definition, non_int_type=<class 'float'>)[source]¶ Parse a definition.
Parameters: - definition (str or PreprocessedDefinition) –
- non_int_type (type) –
Returns: Return type: Definition or subclass of Definition
pint.errors¶
Functions and classes related to unit definitions and conversions.
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
exception
pint.errors.
DefinitionSyntaxError
(msg, *, filename=None, lineno=None)[source]¶ Raised when a textual definition has a syntax error.
-
exception
pint.errors.
DimensionalityError
(units1, units2, dim1='', dim2='', *, extra_msg='')[source]¶ Raised when trying to convert between incompatible units.
-
exception
pint.errors.
LogarithmicUnitCalculusError
[source]¶ Raised on inappropriate operations with logarithmic units.
-
exception
pint.errors.
OffsetUnitCalculusError
[source]¶ Raised on ambiguous operations with offset units.
-
exception
pint.errors.
RedefinitionError
(name, definition_type, *, filename=None, lineno=None)[source]¶ Raised when a unit or prefix is redefined.
pint.formatter¶
Format units for pint.
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
pint.formatting.
formatter
(items, as_ratio=True, single_denominator=False, product_fmt=' * ', division_fmt=' / ', power_fmt='{} ** {}', parentheses_fmt='({0})', exp_call=<function <lambda>>, locale=None, babel_length='long', babel_plural_form='one', sort=True)[source]¶ Format a list of (name, exponent) pairs.
Parameters: - items (list) – a list of (name, exponent) pairs.
- as_ratio (bool, optional) – True to display as ratio, False as negative powers. (Default value = True)
- single_denominator (bool, optional) – all with terms with negative exponents are collected together. (Default value = False)
- product_fmt (str) – the format used for multiplication. (Default value = ” * “)
- division_fmt (str) – the format used for division. (Default value = ” / “)
- power_fmt (str) – the format used for exponentiation. (Default value = “{} ** {}”)
- parentheses_fmt (str) – the format used for parenthesis. (Default value = “({0})”)
- locale (str) – the locale object as defined in babel. (Default value = None)
- babel_length (str) – the length of the translated unit, as defined in babel cldr. (Default value = “long”)
- babel_plural_form (str) – the plural form, calculated as defined in babel. (Default value = “one”)
- exp_call (callable) – (Default value = lambda x: f”{x:n}”)
- sort (bool, optional) – True to sort the formatted units alphabetically (Default value = True)
Returns: the formula as a string.
Return type:
pint.matplotlib¶
Functions and classes related to working with Matplotlib’s support for plotting with units.
copyright: | 2017 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.matplotlib.
PintAxisInfo
(units)[source]¶ Support default axis and tick labeling and default limits.
-
class
pint.matplotlib.
PintConverter
(registry)[source]¶ Implement support for pint within matplotlib’s unit conversion framework.
-
pint.matplotlib.
setup_matplotlib_handlers
(registry, enable)[source]¶ Set up matplotlib’s unit support to handle units from a registry.
Parameters: - registry (pint.UnitRegistry) – The registry that will be used.
- enable (bool) – Whether support should be enabled or disabled.
pint.measurement¶
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.measurement.
Measurement
[source]¶ Implements a class to describe a quantity with uncertainty.
Parameters: - value (pint.Quantity or any numeric type) – The expected value of the measurement
- error (pint.Quantity or any numeric type) – The error or uncertainty of the measurement
pint.pint_eval¶
An expression evaluator to be used as a safe replacement for builtin eval.
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.pint_eval.
EvalTreeNode
(left, operator=None, right=None)[source]¶ Single node within an evaluation tree
left + operator + right –> binary op left + operator –> unary op left + right –> implicit op left –> single value
-
pint.pint_eval.
build_eval_tree
(tokens, op_priority={'': 1, '*': 1, '**': 3, '+': 0, '-': 0, '/': 1, '^': 3, 'unary': 2}, index=0, depth=0, prev_op=None)[source]¶ Build an evaluation tree from a set of tokens.
Params: Index, depth, and prev_op used recursively, so don’t touch. Tokens is an iterable of tokens from an expression to be evaluated.
Transform the tokens from an expression into a recursive parse tree, following order of operations. Operations can include binary ops (3 + 4), implicit ops (3 kg), or unary ops (-1).
General Strategy: 1) Get left side of operator 2) If no tokens left, return final result 3) Get operator 4) Use recursion to create tree starting at token on right side of operator (start at step #1) 4.1) If recursive call encounters an operator with lower or equal priority to step #2, exit recursion 5) Combine left side, operator, and right side into a new left side 6) Go back to step #2
pint.quantity¶
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.quantity.
Quantity
[source]¶ Implements a class to describe a physical quantity: the product of a numerical value and a unit of measurement.
Parameters: - value (str, pint.Quantity or any numeric type) – Value of the physical quantity to be created.
- units (UnitsContainer, str or pint.Quantity) – Units of the physical quantity to be created.
-
compute
(**kwargs)[source]¶ Compute the Dask array wrapped by pint.Quantity.
Parameters: **kwargs (dict) – Any keyword arguments to pass to dask.compute
.Returns: A pint.Quantity wrapped numpy array. Return type: pint.Quantity
-
default_format
= ''¶ Default formatting string.
-
dimensionality
¶ returns: Dimensionality of the Quantity, e.g.
{length: 1, time: -1}
:rtype: dict
-
dimensionless
¶
-
classmethod
from_list
(quant_list, units=None)[source]¶ Transforms a list of Quantities into an numpy.array quantity. If no units are specified, the unit of the first element will be used. Same as from_sequence.
If units is not specified and list is empty, the unit cannot be determined and a ValueError is raised.
Parameters: - quant_list (list of pint.Quantity) – list of pint.Quantity
- units (UnitsContainer, str or pint.Quantity) – units of the physical quantity to be created (Default value = None)
Returns: Return type:
-
classmethod
from_sequence
(seq, units=None)[source]¶ Transforms a sequence of Quantities into an numpy.array quantity. If no units are specified, the unit of the first element will be used.
If units is not specified and sequence is empty, the unit cannot be determined and a ValueError is raised.
Parameters: - seq (sequence of pint.Quantity) – sequence of pint.Quantity
- units (UnitsContainer, str or pint.Quantity) – units of the physical quantity to be created (Default value = None)
Returns: Return type:
-
is_compatible_with
(other, *contexts, **ctx_kwargs)[source]¶ check if the other object is compatible
Parameters: - other – The object to check. Treated as dimensionless if not a Quantity, Unit or str.
- *contexts (str or pint.Context) – Contexts to use in the transformation.
- **ctx_kwargs – Values for the Context/s
Returns: Return type:
-
ito
(other=None, *contexts, **ctx_kwargs)[source]¶ Inplace rescale to different units.
Parameters: - other (pint.Quantity, str or dict) – Destination units. (Default value = None)
- *contexts (str or pint.Context) – Contexts to use in the transformation.
- **ctx_kwargs – Values for the Context/s
-
ito_reduced_units
()[source]¶ Return Quantity scaled in place to reduced units, i.e. one unit per dimension. This will not reduce compound units (e.g., ‘J/kg’ will not be reduced to m**2/s**2), nor can it make use of contexts at this time.
-
m
¶ Quantity’s magnitude. Short form for magnitude
-
m_as
(units)[source]¶ Quantity’s magnitude expressed in particular units.
Parameters: units (pint.Quantity, str or dict) – destination units
-
magnitude
¶ Quantity’s magnitude. Long form for m
-
persist
(**kwargs)[source]¶ Persist the Dask Array wrapped by pint.Quantity.
Parameters: **kwargs (dict) – Any keyword arguments to pass to dask.persist
.Returns: A pint.Quantity wrapped Dask array. Return type: pint.Quantity
-
prod
(axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]¶ Return the product of quantity elements over a given axis
Wraps np.prod().
-
to
(other=None, *contexts, **ctx_kwargs)[source]¶ Return Quantity rescaled to different units.
Parameters: - other (pint.Quantity, str or dict) – destination units. (Default value = None)
- *contexts (str or pint.Context) – Contexts to use in the transformation.
- **ctx_kwargs – Values for the Context/s
Returns: Return type:
-
to_compact
(unit=None)[source]¶ “Return Quantity rescaled to compact, human-readable units.
To get output in terms of a different unit, use the unit parameter.
Example
>>> import pint >>> ureg = pint.UnitRegistry() >>> (200e-9*ureg.s).to_compact() <Quantity(200.0, 'nanosecond')> >>> (1e-2*ureg('kg m/s^2')).to_compact('N') <Quantity(10.0, 'millinewton')>
-
to_reduced_units
()[source]¶ Return Quantity scaled in place to reduced units, i.e. one unit per dimension. This will not reduce compound units (intentionally), nor can it make use of contexts at this time.
-
u
¶ Quantity’s units. Short form for units
-
unitless
¶
-
units
¶ Quantity’s units. Long form for u
-
pint.quantity.
printoptions
(*args, **kwargs)[source]¶ Numpy printoptions context manager released with version 1.15.0 https://docs.scipy.org/doc/numpy/reference/generated/numpy.printoptions.html
pint.registry¶
Defines the Registry, a class to contain units and their relations.
The module actually defines 5 registries with different capabilities:
- BaseRegistry: Basic unit definition and querying.
Conversion between multiplicative units.
- NonMultiplicativeRegistry: Conversion between non multiplicative (offset) units.
(e.g. Temperature)
- Inherits from BaseRegistry
- ContextRegisty: Conversion between units with different dimensions according
to previously established relations (contexts) - e.g. in spectroscopy, conversion between frequency and energy is possible. May also override conversions between units on the same dimension - e.g. different rounding conventions.
- Inherits from BaseRegistry
- SystemRegistry: Group unit and changing of base units.
(e.g. in MKS, meter, kilogram and second are base units.)
- Inherits from BaseRegistry
UnitRegistry: Combine all previous capabilities, it is exposed by Pint.
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.registry.
BaseRegistry
(filename='', force_ndarray=False, force_ndarray_like=False, on_redefinition='warn', auto_reduce_dimensions=False, preprocessors=None, fmt_locale=None, non_int_type=<class 'float'>, case_sensitive=True)[source]¶ Base class for all registries.
Capabilities:
- Register units, prefixes, and dimensions, and their relations.
- Convert between units.
- Find dimensionality of a unit.
- Parse units with prefix and/or suffix.
- Parse expressions.
- Parse a definition file.
- Allow extending the definition file parser by registering @ directives.
Parameters: - filename (str or None) – path of the units definition file to load or line iterable object. Empty to load the default definition file. None to leave the UnitRegistry empty.
- force_ndarray (bool) – convert any input, scalar or not to a numpy.ndarray.
- force_ndarray_like (bool) – convert all inputs other than duck arrays to a numpy.ndarray.
- on_redefinition (str) – action to take in case a unit is redefined: ‘warn’, ‘raise’, ‘ignore’
- auto_reduce_dimensions – If True, reduce dimensionality on appropriate operations.
- preprocessors – list of callables which are iteratively ran on any input expression or unit string
- fmt_locale – locale identifier string, used in format_babel
- non_int_type (type) – numerical type used for non integer values. (Default: float)
- case_sensitive (bool, optional) – Control default case sensitivity of unit parsing. (Default: True)
-
auto_reduce_dimensions
= None¶ Determines if dimensionality should be reduced on appropriate operations.
-
case_sensitive
= None¶ Default unit case sensitivity
-
convert
(value, src, dst, inplace=False)[source]¶ Convert value from some source to destination units.
Parameters: - value – value
- src (pint.Quantity or str) – source units.
- dst (pint.Quantity or str) – destination units.
- inplace – (Default value = False)
Returns: converted value
Return type:
-
default_format
¶ Default formatting string for quantities.
-
define
(definition)[source]¶ Add unit to the registry.
Parameters: definition (str or Definition) – a dimension, unit or prefix definition.
-
fmt_locale
= None¶ Babel.Locale instance or None
-
get_base_units
(input_units, check_nonmult=True, system=None)[source]¶ Convert unit or dict of units to the base units.
If any unit is non multiplicative and check_converter is True, then None is returned as the multiplicative factor.
Parameters: - input_units (UnitsContainer or str) – units
- check_nonmult (bool) – If True, None will be returned as the multiplicative factor if non-multiplicative units are found in the final Units. (Default value = True)
- system – (Default value = None)
Returns: multiplicative factor, base units
Return type: Number, pint.Unit
-
get_dimensionality
(input_units)[source]¶ Convert unit or dict of units or dimensions to a dict of base dimensions dimensions
-
get_root_units
(input_units, check_nonmult=True)[source]¶ Convert unit or dict of units to the root units.
If any unit is non multiplicative and check_converter is True, then None is returned as the multiplicative factor.
Parameters: - input_units (UnitsContainer or str) – units
- check_nonmult (bool) – if True, None will be returned as the multiplicative factor if a non-multiplicative units is found in the final Units. (Default value = True)
Returns: multiplicative factor, base units
Return type: Number, pint.Unit
-
is_compatible_with
(obj1, obj2, *contexts, **ctx_kwargs)[source]¶ check if the other object is compatible
Parameters: - obj2 (obj1,) – The objects to check against each other. Treated as dimensionless if not a Quantity, Unit or str.
- *contexts (str or pint.Context) – Contexts to use in the transformation.
- **ctx_kwargs – Values for the Context/s
Returns: Return type:
-
load_definitions
(file, is_resource=False)[source]¶ Add units and prefixes defined in a definition text file.
Parameters: - file – can be a filename or a line iterable.
- is_resource – used to indicate that the file is a resource file and therefore should be loaded from the package. (Default value = False)
-
non_int_type
= None¶ Numerical type used for non integer values.
-
parse_expression
(input_string, case_sensitive=None, use_decimal=False, **values)[source]¶ Parse a mathematical expression including units and return a quantity object.
Numerical constants can be specified as keyword arguments and will take precedence over the names defined in the registry.
Parameters: - input_string –
- case_sensitive – (Default value = None, which uses registry setting)
- use_decimal – (Default value = False)
- **values –
-
parse_pattern
(input_string, pattern, case_sensitive=None, use_decimal=False, many=False)[source]¶ Parse a string with a given regex pattern and returns result.
Parameters: - input_string –
- pattern_string – The regex parse string
- case_sensitive – (Default value = None, which uses registry setting)
- use_decimal – (Default value = False)
- many – Match many results (Default value = False)
-
parse_unit_name
(unit_name, case_sensitive=None)[source]¶ Parse a unit to identify prefix, unit name and suffix by walking the list of prefix and suffix. In case of equivalent combinations (e.g. (‘kilo’, ‘gram’, ‘’) and (‘’, ‘kilogram’, ‘’), prefer those with prefix.
Parameters: Returns: all non-equivalent combinations of (prefix, unit name, suffix)
Return type:
-
parse_units
(input_string, as_delta=None, case_sensitive=None)[source]¶ Parse a units expression and returns a UnitContainer with the canonical names.
The expression can only contain products, ratios and powers of units.
Parameters: - input_string (str) –
- as_delta (bool or None) – if the expression has multiple units, the parser will interpret non multiplicative units as their delta_ counterparts. (Default value = None)
- case_sensitive (bool or None) – Control if unit parsing is case sensitive. Defaults to None, which uses the registry’s setting.
-
class
pint.registry.
ContextCacheOverlay
(registry_cache: pint.registry.RegistryCache)[source]¶ Layer on top of the base UnitRegistry cache, specific to a combination of active contexts which contain unit redefinitions.
-
class
pint.registry.
ContextRegistry
(**kwargs)[source]¶ Handle of Contexts.
Conversion between units with different dimensions according to previously established relations (contexts). (e.g. in the spectroscopy, conversion between frequency and energy is possible)
Capabilities:
- Register contexts.
- Enable and disable contexts.
- Parse @context directive.
-
add_context
(context: pint.context.Context) → None[source]¶ Add a context object to the registry.
The context will be accessible by its name and aliases.
Notice that this method will NOT enable the context; see
enable_contexts()
.
-
context
(*names, **kwargs)[source]¶ Used as a context manager, this function enables to activate a context which is removed after usage.
Parameters: - *names – name(s) of the context(s).
- **kwargs – keyword arguments for the contexts.
Examples
Context can be called by their name:
>>> import pint >>> ureg = pint.UnitRegistry() >>> ureg.add_context(pint.Context('one')) >>> ureg.add_context(pint.Context('two')) >>> with ureg.context('one'): ... pass
If a context has an argument, you can specify its value as a keyword argument:
>>> with ureg.context('one', n=1): ... pass
Multiple contexts can be entered in single call:
>>> with ureg.context('one', 'two', n=1): ... pass
Or nested allowing you to give different values to the same keyword argument:
>>> with ureg.context('one', n=1): ... with ureg.context('two', n=2): ... pass
A nested context inherits the defaults from the containing context:
>>> with ureg.context('one', n=1): ... # Here n takes the value of the outer context ... with ureg.context('two'): ... pass
-
disable_contexts
(n: int = None) → None[source]¶ Disable the last n enabled contexts.
Parameters: n (int) – Number of contexts to disable. Default: disable all contexts.
-
enable_contexts
(*names_or_contexts, **kwargs) → None[source]¶ Enable contexts provided by name or by object.
Parameters: - *names_or_contexts – one or more contexts or context names/aliases
- **kwargs – keyword arguments for the context(s)
Examples
See
context()
-
remove_context
(name_or_alias: str) → pint.context.Context[source]¶ Remove a context from the registry and return it.
Notice that this methods will not disable the context; see
disable_contexts()
.
-
with_context
(name, **kwargs)[source]¶ Decorator to wrap a function call in a Pint context.
Use it to ensure that a certain context is active when calling a function:
:param name: name of the context. :param \*\*kwargs: keyword arguments for the context
Returns: the wrapped function. Return type: callable Example
>>> @ureg.with_context('sp') ... def my_cool_fun(wavelength): ... print('This wavelength is equivalent to: %s', wavelength.to('terahertz'))
-
class
pint.registry.
NonMultiplicativeRegistry
(default_as_delta=True, autoconvert_offset_to_baseunit=False, **kwargs)[source]¶ Handle of non multiplicative units (e.g. Temperature).
Capabilities: - Register non-multiplicative units and their relations. - Convert between non-multiplicative units.
Parameters: -
default_as_delta
= None¶ When performing a multiplication of units, interpret non-multiplicative units as their delta counterparts.
-
-
class
pint.registry.
RegistryCache
[source]¶ Cache to speed up unit registries
-
dimensional_equivalents
= None¶ Maps dimensionality (UnitsContainer) to Units (str)
-
dimensionality
= None¶ Maps dimensionality (UnitsContainer) to Units (UnitsContainer)
-
parse_unit
= None¶ Cache the unit name associated to user input. (‘mV’ -> ‘millivolt’)
-
root_units
= None¶ Maps dimensionality (UnitsContainer) to Dimensionality (UnitsContainer)
-
-
class
pint.registry.
RegistryMeta
[source]¶ This is just to call after_init at the right time instead of asking the developer to do it when subclassing.
-
class
pint.registry.
SystemRegistry
(system=None, **kwargs)[source]¶ Handle of Systems and Groups.
Conversion between units with different dimenstions according to previously established relations (contexts). (e.g. in the spectroscopy, conversion between frequency and energy is possible)
Capabilities:
- Register systems and groups.
- List systems
- Get or get the default system.
- Parse @system and @group directive.
-
get_base_units
(input_units, check_nonmult=True, system=None)[source]¶ Convert unit or dict of units to the base units.
If any unit is non multiplicative and check_converter is True, then None is returned as the multiplicative factor.
Unlike BaseRegistry, in this registry root_units might be different from base_units
Parameters: - input_units (UnitsContainer or str) – units
- check_nonmult (bool) – if True, None will be returned as the multiplicative factor if a non-multiplicative units is found in the final Units. (Default value = True)
- system – (Default value = None)
Returns: multiplicative factor, base units
Return type:
-
class
pint.registry.
UnitRegistry
(filename='', force_ndarray=False, force_ndarray_like=False, default_as_delta=True, autoconvert_offset_to_baseunit=False, on_redefinition='warn', system=None, auto_reduce_dimensions=False, preprocessors=None, fmt_locale=None, non_int_type=<class 'float'>, case_sensitive=True)[source]¶ The unit registry stores the definitions and relationships between units.
Parameters: - filename – path of the units definition file to load or line-iterable object. Empty to load the default definition file. None to leave the UnitRegistry empty.
- force_ndarray (bool) – convert any input, scalar or not to a numpy.ndarray.
- force_ndarray_like (bool) – convert all inputs other than duck arrays to a numpy.ndarray.
- default_as_delta – In the context of a multiplication of units, interpret non-multiplicative units as their delta counterparts.
- autoconvert_offset_to_baseunit – If True converts offset units in quantities are converted to their base units in multiplicative context. If False no conversion happens.
- on_redefinition (str) – action to take in case a unit is redefined. ‘warn’, ‘raise’, ‘ignore’
- auto_reduce_dimensions – If True, reduce dimensionality on appropriate operations.
- preprocessors – list of callables which are iteratively ran on any input expression or unit string
- fmt_locale – locale identifier string, used in format_babel. Default to None
- case_sensitive (bool, optional) – Control default case sensitivity of unit parsing. (Default: True)
-
check
(*args)¶ Decorator to for quantity type checking for function inputs.
Use it to ensure that the decorated function input parameters match the expected dimension of pint quantity.
- The wrapper function raises:
- pint.DimensionalityError if an argument doesn’t match the required dimensions.
- ureg : UnitRegistry
- a UnitRegistry instance.
- args : str or UnitContainer or None
- Dimensions of each of the input arguments. Use None to skip argument conversion.
Returns: the wrapped function.
Return type: callable
Raises: TypeError
– If the number of given dimensions does not match the number of function parameters.ValueError
– If the any of the provided dimensions cannot be parsed as a dimension.
-
pi_theorem
(quantities)[source]¶ Builds dimensionless quantities using the Buckingham π theorem
Parameters: quantities (dict) – mapping between variable name and units Returns: a list of dimensionless quantities expressed as dicts Return type: list
-
setup_matplotlib
(enable=True)[source]¶ Set up handlers for matplotlib’s unit support.
Parameters: enable (bool) – whether support should be enabled or disabled (Default value = True)
-
wraps
(ret, args, strict=True)¶ Wraps a function to become pint-aware.
Use it when a function requires a numerical value but in some specific units. The wrapper function will take a pint quantity, convert to the units specified in args and then call the wrapped function with the resulting magnitude.
The value returned by the wrapped function will be converted to the units specified in ret.
Parameters: - ureg (pint.UnitRegistry) – a UnitRegistry instance.
- ret (str, pint.Unit, iterable of str, or iterable of pint.Unit) – Units of each of the return values. Use None to skip argument conversion.
- args (str, pint.Unit, iterable of str, or iterable of pint.Unit) – Units of each of the input arguments. Use None to skip argument conversion.
- strict (bool) – Indicates that only quantities are accepted. (Default value = True)
Returns: the wrapper function.
Return type: callable
Raises: TypeError
– if the number of given arguments does not match the number of function parameters. if the any of the provided arguments is not a unit a string or Quantity
pint.registry_helpers¶
Miscellaneous methods of the registry writen as separate functions.
copyright: | 2016 by Pint Authors, see AUTHORS for more details.. |
---|---|
license: | BSD, see LICENSE for more details. |
-
pint.registry_helpers.
check
(ureg, *args)[source]¶ Decorator to for quantity type checking for function inputs.
Use it to ensure that the decorated function input parameters match the expected dimension of pint quantity.
- The wrapper function raises:
- pint.DimensionalityError if an argument doesn’t match the required dimensions.
- ureg : UnitRegistry
- a UnitRegistry instance.
- args : str or UnitContainer or None
- Dimensions of each of the input arguments. Use None to skip argument conversion.
Returns: the wrapped function.
Return type: callable
Raises: TypeError
– If the number of given dimensions does not match the number of function parameters.ValueError
– If the any of the provided dimensions cannot be parsed as a dimension.
-
pint.registry_helpers.
wraps
(ureg, ret, args, strict=True)[source]¶ Wraps a function to become pint-aware.
Use it when a function requires a numerical value but in some specific units. The wrapper function will take a pint quantity, convert to the units specified in args and then call the wrapped function with the resulting magnitude.
The value returned by the wrapped function will be converted to the units specified in ret.
Parameters: - ureg (pint.UnitRegistry) – a UnitRegistry instance.
- ret (str, pint.Unit, iterable of str, or iterable of pint.Unit) – Units of each of the return values. Use None to skip argument conversion.
- args (str, pint.Unit, iterable of str, or iterable of pint.Unit) – Units of each of the input arguments. Use None to skip argument conversion.
- strict (bool) – Indicates that only quantities are accepted. (Default value = True)
Returns: the wrapper function.
Return type: callable
Raises: TypeError
– if the number of given arguments does not match the number of function parameters. if the any of the provided arguments is not a unit a string or Quantity
pint.systems¶
Functions and classes related to system definitions and conversions.
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.systems.
Group
(name)[source]¶ A group is a set of units.
Units can be added directly or by including other groups.
Members are computed dynamically, that is if a unit is added to a group X all groups that include X are affected.
The group belongs to one Registry.
It can be specified in the definition file as:
@group <name> [using <group 1>, ..., <group N>] <definition 1> ... <definition N> @end
-
classmethod
from_lines
(lines, define_func, non_int_type=<class 'float'>)[source]¶ Return a Group object parsing an iterable of lines.
Parameters:
-
members
¶ Names of the units that are members of the group.
Calculated to include to all units in all included _used_groups.
-
classmethod
-
class
pint.systems.
System
(name)[source]¶ A system is a Group plus a set of base units.
Members are computed dynamically, that is if a unit is added to a group X all groups that include X are affected.
The System belongs to one Registry.
It can be specified in the definition file as:
@system <name> [using <group 1>, ..., <group N>] <rule 1> ... <rule N> @end
The syntax for the rule is:
new_unit_name : old_unit_name- where:
- old_unit_name: a root unit part which is going to be removed from the system.
- new_unit_name: a non root unit which is going to replace the old_unit.
If the new_unit_name and the old_unit_name, the later and the colon can be omitted.
-
base_units
= None¶ Maps root unit names to a dict indicating the new unit and its exponent. :type: dict[str, dict[str, number]]]
-
derived_units
= None¶ Derived unit names. :type: set(str)
-
name
= None¶ Name of the system :type: str
pint.unit¶
Functions and classes related to unit definitions and conversions.
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.unit.
Unit
(units)[source]¶ Implements a class to describe a unit supporting math operations.
-
default_format
= ''¶ Default formatting string.
-
dimensionality
¶ returns: Dimensionality of the Unit, e.g.
{length: 1, time: -1}
:rtype: dict
-
dimensionless
¶ Return True if the Unit is dimensionless; False otherwise.
-
from_
(value, strict=True, name='value')[source]¶ Converts a numerical value or quantity to this unit
Parameters: - value – a Quantity (or numerical value if strict=False) to convert
- strict – boolean to indicate that only quanities are accepted (Default value = True)
- name – descriptive name to use if an exception occurs (Default value = “value”)
Returns: The converted value as this unit
Return type:
-
is_compatible_with
(other, *contexts, **ctx_kwargs)[source]¶ check if the other object is compatible
Parameters: - other – The object to check. Treated as dimensionless if not a Quantity, Unit or str.
- *contexts (str or pint.Context) – Contexts to use in the transformation.
- **ctx_kwargs – Values for the Context/s
Returns: Return type:
-
m_from
(value, strict=True, name='value')[source]¶ Converts a numerical value or quantity to this unit, then returns the magnitude of the converted value
Parameters: - value – a Quantity (or numerical value if strict=False) to convert
- strict – boolean to indicate that only quanities are accepted (Default value = True)
- name – descriptive name to use if an exception occurs (Default value = “value”)
Returns: The magnitude of the converted value
Return type:
-
pint.util¶
Miscellaneous functions for pint.
copyright: | 2016 by Pint Authors, see AUTHORS for more details. |
---|---|
license: | BSD, see LICENSE for more details. |
-
class
pint.util.
BlockIterator
[source]¶ Like SourceIterator but stops when it finds ‘@end’ It also raises an error if another ‘@’ directive is found inside.
-
class
pint.util.
ParserHelper
(scale=1, *args, **kwargs)[source]¶ The ParserHelper stores in place the product of variables and their respective exponent and implements the corresponding operations.
ParserHelper is a read-only mapping. All operations (even in place ones)
Returns: WARNING : The hash value used does not take into account the scale attribute so be careful if you use it as a dict key and then two unequal object can have the same hash. Return type: type
Base class for object keeping a reference to the registree.
Such object are for now Quantity and Unit, in a number of places it is that an object from this class has a ‘_units’ attribute.
-
class
pint.util.
SourceIterator
[source]¶ Iterator to facilitate reading the definition files.
Accepts any sequence (like a list of lines, a file or another SourceIterator)
The iterator yields the line number and line (skipping comments and empty lines) and stripping white spaces.
- for lineno, line in SourceIterator(sequence):
- # do something here
-
class
pint.util.
UnitsContainer
(*args, **kwargs)[source]¶ The UnitsContainer stores the product of units and their respective exponent and implements the corresponding operations.
UnitsContainer is a read-only mapping. All operations (even in place ones)
Returns: Return type: type
-
pint.util.
column_echelon_form
(matrix, ntype=<class 'fractions.Fraction'>, transpose_result=False)[source]¶ Calculates the column echelon form using Gaussian elimination.
Parameters: - matrix – a 2D matrix as nested list.
- ntype – the numerical type to use in the calculation. (Default value = Fraction)
- transpose_result – indicates if the returned matrix should be transposed. (Default value = False)
Returns: column echelon form, transformed identity matrix, swapped rows
Return type:
-
pint.util.
getattr_maybe_raise
(self, item)[source]¶ Helper function invoked at start of all overridden
__getattr__
.Raise AttributeError if the user tries to ask for a _ or __ attribute, unless it is immediately followed by a number, to enable units encompassing constants, such as
L / _100km
.Parameters: item (string) – Item to be found.
-
pint.util.
iterable
(y)[source]¶ Check whether or not an object can be iterated over.
Vendored from numpy under the terms of the BSD 3-Clause License. (Copyright (c) 2005-2019, NumPy Developers.)
Parameters: - value – Input object.
- type – object
- y –
-
pint.util.
matrix_to_string
(matrix, row_headers=None, col_headers=None, fmtfun=<function <lambda>>)[source]¶ Takes a 2D matrix (as nested list) and returns a string.
Parameters: - matrix –
- row_headers – (Default value = None)
- col_headers – (Default value = None)
- fmtfun – (Default value = lambda x: str(int(x)))
-
pint.util.
pi_theorem
(quantities, registry=None)[source]¶ Builds dimensionless quantities using the Buckingham π theorem
Parameters: - quantities (dict) – mapping between variable name and units
- registry – (Default value = None)
Returns: a list of dimensionless quantities expressed as dicts
Return type:
-
pint.util.
sized
(y)[source]¶ Check whether or not an object has a defined length.
Parameters: - value – Input object.
- type – object
- y –
-
pint.util.
solve_dependencies
(dependencies)[source]¶ Solve a dependency graph.
Parameters: dependencies – dependency dictionary. For each key, the value is an iterable indicating its dependencies. Returns: iterator of sets, each containing keys of independents tasks dependent only of the previous tasks in the list. Return type: type
-
pint.util.
to_units_container
(unit_like, registry=None)[source]¶ Convert a unit compatible type to a UnitsContainer.
Parameters: - unit_like –
- registry – (Default value = None)