Developers API#
This reference groups lower-level modules commonly used by contributors and advanced integrators.
Public API Modules#
Factory helpers for creating quantities and units.
- pyunitwizard.api.construction.quantity(value, unit=None, form=None, parser=None, standardized=False)[source]#
Returns a quantity.
- Parameters:
value (int, float or arraylike) – The value of the quantity. Can be a scalar or an array like type.
unit (UnitLike) – Unit in of the quantity in any of the accepted form.
form ({"unyt", "pint", "openmm.unit", "astropy.units", "string"}, optional) – Output form of the quantity.
parser ({"unyt", "pint", "openmm.unit", "astropy.units"}, optional) – The parser to use.
standardized (bool, optional) – Return a standardized quantity, default=False.
- Returns:
The quantity.
- Return type:
QuantityLike
- pyunitwizard.api.construction.unit(unit, form=None, parser=None)[source]#
Returns a unit.
- Parameters:
unit (str) – Name of the unit (i.e kcal/mol).
form ({"unyt", "pint", "openmm.unit", "astropy.units", "string"}, optional) – The form of the unit. This is the type that will be returned
parser ({"unyt", "pint", "openmm.unit", "astropy.units"}, optional) – The parser to use.
- Returns:
The unit.
- Return type:
Unitlike
Conversion helpers bridging between different quantity backends.
- pyunitwizard.api.conversion.conversion_factor(from_unit, to_unit, parser=None)[source]#
Return the multiplicative factor converting magnitudes between two units.
The returned factor
ssatisfiesvalue_in_to_unit = s * value_in_from_unit. It is computed once per(from_unit, to_unit, parser, default_form)and cached, so repeated calls in hot loops avoid constructing a quantity on every conversion. This is the fast path for converting bare magnitudes; for full quantities (or one-off conversions) useconvert().Only offset-free (purely multiplicative) unit pairs are supported. Affine pairs, such as
degC->kelvin, carry an additive offset that no single factor can express; those raiseBadCallErrorand must go throughconvert().- Parameters:
from_unit (str) – Source unit of the magnitude.
to_unit (str) – Target unit of the magnitude.
parser ({"pint", "openmm.unit", "astropy.units"}, optional) – Parser used to interpret the unit strings.
- Returns:
The multiplicative conversion factor.
- Return type:
float
- Raises:
BadCallError – If the unit pair is affine (offset-bearing).
Examples
>>> import pyunitwizard as puw >>> puw.conversion_factor('nm', 'angstroms') 10.0
- pyunitwizard.api.conversion.convert(quantity_or_unit, to_unit=None, to_form=None, parser=None, to_type='quantity')[source]#
Convert a quantity or unit across unit systems, forms, and output types.
- Parameters:
quantity_or_unit (Any) – Input quantity or unit to convert. It can be any supported runtime form, including strings when a compatible parser is configured.
to_unit (str, optional) – Target unit. When provided, the quantity is converted to this unit before returning.
to_form ({"unyt", "pint", "openmm.unit", "astropy.units", "string"}, optional) – Target backend form. If omitted, the input form is preserved.
parser ({"pint", "openmm.unit", "astropy.units"}, optional) – Parser used when quantity_or_unit or to_unit is provided as a string.
to_type ({"quantity", "unit", "value"}, optional, default="quantity") – Output type to return.
- Returns:
Converted object in the requested unit/form/type.
- Return type:
QuantityOrUnit or float or numpy.ndarray
- Raises:
BadCallError – If to_type is not one of
"quantity","unit", or"value".
Examples
>>> import pyunitwizard as puw >>> q = puw.quantity(1.0, "nanometer") >>> puw.convert(q, to_unit="angstrom")
- pyunitwizard.api.conversion.to_string(quantity_or_unit, to_unit=None, parser=None)[source]#
Return a quantity or unit converted to string form.
- Parameters:
quantity_or_unit (Any) – Input quantity or unit to convert.
to_unit (str, optional) – Target unit expressed as string.
parser ({"pint", "openmm.unit", "astropy.units"}, optional) – Parser used when string inputs require explicit parsing.
- Returns:
Quantity or unit represented in string form.
- Return type:
str
Examples
>>> import pyunitwizard as puw >>> q = puw.quantity(1.0, "nanometer") >>> puw.to_string(q, to_unit="angstrom")
Validation helpers for PyUnitWizard.
- pyunitwizard.api.validation.check(quantity_or_unit, dimensionality=None, value_type=None, shape=None, unit=None, dtype_name=None)[source]#
Check if a quantity or unit has the specified dimensionality, value_type, shape, unit or data type.
- Parameters:
quantity_or_unit (Any) – A quantity or unit object. If any other object is passed False will be returned.
dimensionality (dict) – A dictionary specifying the dimensionality of the quantity or unit.
value_type (Any) – The type of the quantity. Can be int, float, np.ndarray.
shape (tuple of int) – For non scalar quantities. A tuple with the shape of the array.
unit (str) – Name of the unit.
dtype_name (str) – For non scalar quantities. The dtype of the array (i.e float64).
- Returns:
True if the quantity or unit has the specified parameters.
- Return type:
bool
- pyunitwizard.api.validation.ensure_quantity(value, dimensionality=None, to_unit=None, standardized=True, parser=None, caller=None)[source]#
Return
valueas a validated quantity, or raise.This is the canonical “digest a length/mass/time/… argument” helper: it accepts any PyUnitWizard-recognized quantity form (a unit-bearing string, or a pint/openmm/astropy/unyt quantity), optionally checks its physical dimensionality, and returns it standardized (or in
to_unit). Bare numbers are rejected, so a value meant as one unit is never silently reinterpreted as another.- Parameters:
value (Any) – A quantity, or a unit-bearing string (e.g.
"3.5 angstroms"). Bare numbers (int/float/array/list) are rejected.dimensionality (dict, optional) – Required dimensionality, e.g.
{'[L]': 1}for a length. If given and the quantity does not match, anArgumentErroris raised.to_unit (str, optional) – If given, the quantity is returned in this unit instead of the configured standard unit.
standardized (bool, default True) – When True (and
to_unitis None) the quantity is returned in the configured standard units. When False (andto_unitis None) the quantity is returned unchanged (still validated).parser (str, optional) – Parser used for string quantities.
caller (str, optional) – Name of the calling function, used to enrich error messages.
- Returns:
The validated quantity, standardized or converted to
to_unit.- Return type:
Any
- Raises:
ArgumentError – If
valueis not a quantity, or its dimensionality does not match.
Comparison helpers for quantities and units.
- pyunitwizard.api.comparison.are_close(quantity_1, quantity_2, rtol=1e-05, atol=1e-08)[source]#
Compares whether two quantities are similiar within a specified tolerance.
- Parameters:
quantity_or_unit_1 (QuantityOrUnit) – A quantity or a unit
quantity_or_unit_2 (QuantityOrUnit) – A quantity or a unit
relative_tolerance (float) – The relative tolerance to compare the quantities.
quantity_1 (Any)
quantity_2 (Any)
rtol (float)
atol (float)
- Returns:
Whether the quantities or units are similar.
- Return type:
bool
- pyunitwizard.api.comparison.are_compatible(quantity_or_unit_1, quantity_or_unit_2)[source]#
Check whether two quantities or units are compatible. This means that they have the same dimensionalities.
- Parameters:
quantity_or_unit_1 (QuantityOrUnit) – A quantity or a unit
quantity_or_unit_2 (QuantityOrUnit) – A quantity or a unit
- Returns:
Whether the quantities or units are compatible.
- Return type:
bool
- pyunitwizard.api.comparison.are_equal(quantity_or_unit_1, quantity_or_unit_2, same_form=False)[source]#
Compares whether two quantities are similiar within a specified tolerance.
- Parameters:
quantity_or_unit_1 (QuantityOrUnit) – A quantity or a unit
quantity_or_unit_2 (QuantityOrUnit) – A quantity or a unit
relative_tolerance (float) – The relative tolerance to compare the quantities.
same_form (bool)
- Returns:
Whether the quantities or units are similar.
- Return type:
bool
- pyunitwizard.api.comparison.compatibility(quantity_or_unit_1, quantity_or_unit_2)[source]#
Check whether two quantities or units are dimensionally compatible.
- Parameters:
quantity_or_unit_1 (QuantityOrUnit) – First quantity or unit.
quantity_or_unit_2 (QuantityOrUnit) – Second quantity or unit.
- Returns:
Truewhen both inputs are compatible for conversion/comparison.- Return type:
bool
Examples
>>> import pyunitwizard as puw >>> puw.compatibility("1 nm", "10 angstrom")
- pyunitwizard.api.comparison.similarity(quantity_or_unit_1, quantity_or_unit_2, relative_tolerance=1e-08)[source]#
Compare two quantities using relative tolerance semantics.
- Parameters:
quantity_or_unit_1 (QuantityOrUnit) – First quantity or unit to compare.
quantity_or_unit_2 (QuantityOrUnit) – Second quantity or unit to compare.
relative_tolerance (float, default=1e-8) – Relative tolerance used internally as
rtolinare_close().
- Returns:
Truewhen values are close within tolerance and units are compatible.- Return type:
bool
Examples
>>> import pyunitwizard as puw >>> a = puw.quantity(1.0, "nanometer") >>> b = puw.quantity(10.0, "angstrom") >>> puw.similarity(a, b)
Introspection helpers for PyUnitWizard quantities and units.
- pyunitwizard.api.introspection.get_dimensionality(quantity_or_unit)[source]#
Return dimensional exponents for a quantity or unit.
- Parameters:
quantity_or_unit (QuantityOrUnit) – Quantity or unit to inspect. String values are parsed when possible.
- Returns:
Mapping of fundamental dimensions to integer exponents.
- Return type:
dict
- Raises:
NotImplementedFormError – If the input form is not supported by current runtime adapters.
Examples
>>> import pyunitwizard as puw >>> puw.get_dimensionality("1 nanometer")
- pyunitwizard.api.introspection.get_form(quantity_or_unit, raise_exception=True)[source]#
Returns the form of a quantity as a string.
- Parameters:
quantity_or_unit (QuantityOrUnit) – A quanitity or a unit
raise_exception (bool, default=True) – Whether to raise NotImplementedFormError if the form is not found.
- Returns:
The form of the quantity
- Return type:
{“string”, “pint”, “openmm.unit”, “unyt”, None}
- pyunitwizard.api.introspection.has_unit(quantity_or_unit, target_unit, parser=None)[source]#
Check whether an object already uses an exact target unit.
This predicate inspects only unit metadata and never extracts or converts the magnitude. String quantities return
Nonebecause answering for them requires parsing the input rather than inspecting existing metadata.- Parameters:
quantity_or_unit (QuantityOrUnit) – Quantity or unit whose current unit is inspected.
target_unit (str or UnitLike) – Exact unit expected on the input object.
parser (str, optional) – Parser used once when caching a string target unit.
- Returns:
Truefor an exact unit match,Falsefor a different unit, andNonewhen the input is textual and cannot be inspected cheaply.- Return type:
bool or None
Examples
>>> import pyunitwizard as puw >>> quantity = puw.quantity(1.0, "nanometer") >>> puw.has_unit(quantity, "nm") True
- pyunitwizard.api.introspection.is_dimensionless(quantity_or_unit)[source]#
Check wheter a quantity or unit is dimensionless.
- Parameters:
quantity_or_unit (QuantityOrUnit) – A quantity or a unit
- Returns:
Whether the quantity or unit is dimensionless.
- Return type:
bool
- pyunitwizard.api.introspection.is_quantity(quantity_or_unit, parser=None)[source]#
Check whether an object is a quantity
- Parameters:
quantity_or_unit (QuantityOrUnit) – A quanitity or a unit
parser ({"unyt", "pint", "openmm.unit", "astropy.units"}, optional) – The parser for string quantities
- Returns:
False if it’s not a quantity
- Return type:
bool
- pyunitwizard.api.introspection.is_unit(quantity_or_unit, parser=None)[source]#
Check whether an object is a unit
- Parameters:
quantity_or_unit (QuantityOrUnit) – A quantity or a unit
parser ({"unyt", "pint", "openmm.unit", "astropy.units"}, optional) – The parser for string quantities
- Returns:
False if it’s not a unit
- Return type:
bool
- pyunitwizard.api.introspection.unit_matches_target(source_unit, form, target_unit, parser=None)[source]#
Compare an already-extracted unit against a target unit.
This carries the whole tri-state contract of
has_unit(); that function is the public, instrumented entry point onto it. Callers that test one object against several targets extract the source unit once and come here directly, rather than re-extracting it per target.- Parameters:
source_unit (UnitLike) – Unit already extracted from the object under test.
form (str) – Form of source_unit.
target_unit (str or UnitLike) – Unit expected on the object.
parser (str, optional) – Parser used once when caching a string target unit.
- Returns:
Trueon an exact match,Falseon a different unit, andNonewhen the comparison cannot be made cheaply.- Return type:
bool or None
- pyunitwizard.api.introspection.unit_of(quantity_or_unit, form)[source]#
Return the unit of an object whose form is already known.
- Parameters:
quantity_or_unit (QuantityOrUnit) – Quantity or unit, in form.
form (str) – Form of quantity_or_unit, already resolved by the caller.
- Returns:
The object itself when it is a unit, otherwise its unit.
- Return type:
UnitLike
Value and unit extraction helpers.
- pyunitwizard.api.extraction.change_value(quantity, value)[source]#
Return a quantity with a replaced value while preserving unit and form.
- Parameters:
quantity (QuantityLike) – Input quantity.
value (numpy.ndarray or float or int) – New numeric value to assign.
- Returns:
Quantity with updated value and original unit.
- Return type:
QuantityLike
Examples
>>> import pyunitwizard as puw >>> q = puw.quantity(1.0, "nanometer") >>> puw.change_value(q, 2.0)
- pyunitwizard.api.extraction.get_unit(quantity, to_form=None, parser=None, standardized=False)[source]#
Returns the unit of a quantity.
- Parameters:
to_unit (str, optional) –
Name of the unit to which the quantity will be converted (i.e kcal/mol).
- form{“unyt”, “pint”, “openmm.unit”, “astropy.units”, “string”}, optional
If passed the unit will be converted to that form. This is the type that will be returned
parser ({"unyt", "pint", "openmm.unit", "astropy.units"}, optional) – The parser to use.
quantity (Any)
to_form (str | None)
standardized (bool | None)
- Returns:
The unit.
- Return type:
UnitLike
- pyunitwizard.api.extraction.get_value(quantity, to_unit=None, parser=None, standardized=False, value_type=None, dtype=None)[source]#
Returns the value of a quantity.
- Parameters:
to_unit (str, optional) – Name of the unit to which the quantity will be converted (i.e kcal/mol).
parser ({"unyt", "pint", "openmm.unit", "astropy.units"}, optional) – The parser to use.
quantity (Any)
standardized (bool | None)
value_type (Any | None)
dtype (Any | None)
- Returns:
An array with the quantity value or a a float or an int if it’s a scalar.
- Return type:
np.ndarray or float or int
- pyunitwizard.api.extraction.get_value_and_unit(quantity, to_unit=None, to_form=None, parser=None, standardized=False, value_type=None, dtype=None)[source]#
Returns the value and unit of a quantity.
- Parameters:
to_unit (str, optional) – Name of the unit to which the quantity will be converted (i.e kcal/mol).
parser ({"unyt", "pint", "openmm.unit", "astropy.units"}, optional) – The parser to use.
quantity (Any)
to_form (str | None)
standardized (bool | None)
value_type (Any | None)
dtype (Any | None)
- Returns:
np.ndarray or float or int
UnitLike – The value and unit of the input quantity.
- Return type:
Tuple[ndarray | float | int | list | tuple, Any]
Standardization helpers for canonical units.
- pyunitwizard.api.standardization.get_standard_units(quantity_or_unit=None, dimensionality=None, form=None, parser=None)[source]#
Returns standard unit of the quantity or unit passed.
- Parameters:
quantity_or_unit (Any) – A quantity or unit
dimensionality (dict | None)
form (str | None)
parser (str | None)
- Returns:
The standard unit.
- Return type:
str
- Raises:
NoStandardsError – If no standard units were defined.
- pyunitwizard.api.standardization.standardize(quantity_or_unit, to_form=None, to_unit=None)[source]#
Convert a quantity or unit to standard units.
- Parameters:
quantity_or_unit (QuantityOrUnit) – The quantity or a unit that will be converted.
to_form (str, optional.) – The form to transform to. When omitted the configured default form is used.
to_unit (str, optional.) – Target unit expressed as a string (e.g.
"ms","angstrom"). When provided the output is converted to this unit instead of the configured standard unit for the corresponding dimensionality. The form standardization controlled by to_form still applies.
- Returns:
The quantity or unit converted to standard (or requested) units.
- Return type:
QuantityOrUnit
- Raises:
NoStandardsError – If no standard units were defined and to_unit was not supplied.
Context manager for temporary PyUnitWizard configuration.
- pyunitwizard.api.context.context(default_form=None, default_parser=None, standard_units=None)[source]#
Context manager to temporarily change PyUnitWizard configuration.
- Parameters:
default_form (str, optional) – Temporary default form.
default_parser (str, optional) – Temporary default parser.
standard_units (list of str, optional) – Temporary standard units.
Examples
>>> with puw.context(default_form='pint', standard_units=['nm', 'ps']): >>> q = puw.standardize(input_q)
Configuration Module#
- pyunitwizard.configure.configure.add_constant(constant_name, value, unit)[source]#
Register a runtime constant.
- Parameters:
constant_name (str) – Constant identifier.
value (float or int) – Numeric constant value.
unit (str) – Unit associated with the constant value.
- Returns:
Constant mapping is updated in global constants registry.
- Return type:
None
- pyunitwizard.configure.configure.add_standard_units(standard_units, provenance=None)[source]#
Add or replace standard units without discarding the full existing set.
Each incoming unit is matched against the current standards by dimensionality. Any existing standard that shares its dimensionality with an incoming unit is replaced; all other existing standards are preserved. Calling this function is equivalent to calling
set_standard_unitswith a merged list, but avoids the need to enumerate the whole set when only one or a few standards need changing.- Parameters:
standard_units (list of str or str) – Standard unit name(s) to add or, if a unit with the same dimensionality is already registered, to replace.
provenance (str | None)
- Returns:
Runtime standard-unit maps are rebuilt in place.
- Return type:
None
- Raises:
ValueError – If standard_units is neither a string nor a list/tuple.
- pyunitwizard.configure.configure.get_default_form()[source]#
Return the configured default form for quantities and units.
- Returns:
Default runtime form.
- Return type:
str
Examples
>>> import pyunitwizard as puw >>> puw.configure.get_default_form()
- pyunitwizard.configure.configure.get_default_parser()[source]#
Return the configured default parser.
- Returns:
Default parser identifier.
- Return type:
str
Examples
>>> import pyunitwizard as puw >>> puw.configure.get_default_parser()
- pyunitwizard.configure.configure.get_libraries_loaded()[source]#
Return currently loaded backend libraries.
- Returns:
Loaded library identifiers.
- Return type:
list of str
Examples
>>> import pyunitwizard as puw >>> puw.configure.get_libraries_loaded()
- pyunitwizard.configure.configure.get_libraries_supported()[source]#
Return backend libraries supported by this installation.
- Returns:
Supported library identifiers.
- Return type:
list of str
Examples
>>> import pyunitwizard as puw >>> puw.configure.get_libraries_supported()
- pyunitwizard.configure.configure.get_parsers_loaded()[source]#
Return currently loaded parsers.
- Returns:
Loaded parser identifiers.
- Return type:
list of str
Examples
>>> import pyunitwizard as puw >>> puw.configure.get_parsers_loaded()
- pyunitwizard.configure.configure.get_parsers_supported()[source]#
Return parser backends supported by this installation.
- Returns:
Supported parser identifiers.
- Return type:
list of str
Examples
>>> import pyunitwizard as puw >>> puw.configure.get_parsers_supported()
- pyunitwizard.configure.configure.get_pint_registry_cache()[source]#
Return the folder pint will cache its parsed definitions in.
- Returns:
The resolved folder, pint’s
":auto:"sentinel, orNonewhen caching is disabled.- Return type:
str or None
- pyunitwizard.configure.configure.get_standard_units()[source]#
Return configured standard units mapped to dimensionality definitions.
- Returns:
Dictionary keyed by standard unit string with dimensionality mappings.
- Return type:
dict
Examples
>>> import pyunitwizard as puw >>> puw.configure.get_standard_units()
- pyunitwizard.configure.configure.has_active_policy()[source]#
Return whether a unit policy is already active in this session.
A library that configures PyUnitWizard on import should consult this first and stay out of the way when the answer is
True: another library, or the user, already decided. Without that check the last import wins, and with lazy imports “last” can mean a notebook cell run half an hour later.- Returns:
Truewhen standard units are configured.- Return type:
bool
Examples
>>> import pyunitwizard as puw >>> if not puw.configure.has_active_policy(): ... puw.configure.set_standard_units(["nm", "ps"], provenance="mylib")
- pyunitwizard.configure.configure.load_library(library_names)[source]#
Load one or more backend libraries into runtime configuration.
- Parameters:
library_names (str or list of str) – Library name or list of library names to load.
- Returns:
Loaded libraries are registered in global runtime state.
- Return type:
None
- Raises:
TypeError – If library_names is not a string or a list/tuple of strings.
- pyunitwizard.configure.configure.report()[source]#
Return the active unit policy and where it came from.
Answers “which units am I getting, and who decided that?” without reading any library’s import-time code.
- Returns:
Mapping with the active form, parser, standard units, provenance, loaded backends and parsers, and registered fast-track names.
- Return type:
dict
Examples
>>> import pyunitwizard as puw >>> puw.configure.report()["provenance"]
- pyunitwizard.configure.configure.reset()[source]#
Reset runtime configuration state to defaults.
- Returns:
This function mutates global runtime configuration in place.
- Return type:
None
Examples
>>> import pyunitwizard as puw >>> puw.configure.reset()
- pyunitwizard.configure.configure.resolve_config_module(config=None, root_package=None, env_var='PYUNITWIZARD_CONFIG')[source]#
Resolve configuration module using
runtime > env > fileprecedence.- Parameters:
config (str, optional) – Explicit runtime configuration module path.
root_package (str, optional) – Root package name used to probe
<root_package>._pyunitwizard.env_var (str, default="PYUNITWIZARD_CONFIG") – Environment variable name used for config-module discovery.
- Returns:
Resolved module path, or
Nonewhen no candidate is found.- Return type:
str or None
- pyunitwizard.configure.configure.set_default_form(form)[source]#
Set the default form for quantities and units.
- Parameters:
form (str) – New default form identifier.
- Returns:
Runtime default form is updated in place.
- Return type:
None
- pyunitwizard.configure.configure.set_default_parser(parser)[source]#
Set the default parser for string quantities.
- Parameters:
parser (str) – New default parser identifier.
- Returns:
Runtime default parser is updated in place.
- Return type:
None
- pyunitwizard.configure.configure.set_pint_registry_cache(cache)[source]#
Let pint cache its parsed unit definitions on disk.
Parsing pint’s definitions costs about 180 ms in every process that uses units; from a warm cache it costs about 17 ms. It is off by default because writing to a user’s filesystem is not something importing a units library should do uninvited.
Call this before anything loads the pint backend. Naming a form does not load it, so the usual place is a package’s configuration module, above the call that sets the standard units.
- Parameters:
cache (bool or str or None) –
Truefor pint’s own per-user cache location, a path to choose one,Falseto disable, andNoneto defer to thePYUNITWIZARD_PINT_CACHEenvironment variable.- Returns:
The setting is recorded for when the backend is built.
- Return type:
None
- Warns:
RuntimeWarning – If the pint backend has already been loaded, in which case the registry exists and this call cannot affect it.
Examples
>>> import pyunitwizard as puw >>> puw.configure.set_pint_registry_cache(True) >>> puw.configure.set_default_form('pint')
- pyunitwizard.configure.configure.set_standard_units(standard_units, provenance=None)[source]#
Configure project standard units used by standardization helpers.
- Parameters:
standard_units (list of str) – Standard unit names used as normalization references.
provenance (str, optional) – Who is setting this policy, recorded so that
report()can answer “why are my results in these units?”. Libraries should pass their own name; a user setting units interactively can leave it unset.
- Returns:
Runtime standard-unit maps are rebuilt in place.
- Return type:
None
- Raises:
ValueError – If standard_units is neither a string nor list/tuple.