pyphot.unit_adapters package

Contents

pyphot.unit_adapters package#

This module provides a framework for using different unit packages such as astropy, pint, and others. It provides a unified interface for working with units across different packages through adapters.

Registered Adapters#

We provide the following adapters:

  • AstropyAdapter: Adapter for the astropy unit system.

  • PintAdapter: Adapter for the pint unit system.

  • EzUnitsAdapter: Adapter for the legacy pyphot unit system based on pint (v0.1.0).

Note: The EzUnitsAdapter is provided as a fallback for older codes and in case other unit packages are missing.

API Overview#

All adapters must implement the UnitsAdapter interface, which defines the following methods:

  • U(): queries the unit registry.

  • Q(): make sure the returned object is a quantity, i.e. a value with unit (e.g. astropy differs between U(“kg”) and Q(“kg”) = 1. * U(“kg”))

For source typing reasons, adapters also override a few methods:

  • has_unit(): checks if the object has a unit.

  • val_in_unit(): returns the value of the quantity in the specified unit or forces a default unit if not specified.

Decorator to impose units on arguments and keyword arguments#

For convenience, adapters provide (by inheritance) a decorate decorator which can help defining functions with default units on arguments and keyword arguments.

For a more general decorator, use enforce_default_units() which will assumes the defined global adapter, if not a specific one provided.

Note

Both decoration methods will update the docstring of the decorated function to include information about the imposed units.

Typing#

Hint typing information is provided at the module level: UnitAdapterType, QuantityType, which is a union of UnitsAdapter and varied Quantity definitions. In addition, each adapter provides specific types in their typing.Quantity attribute.

Exceptions#

For convenience adapters also provide a list of potential exception types. At the module level UndefinedUnitError, and DimensionalityError which applies to any backend units.

When needed UndefinedUnitError and DimensionalityError can be used to catch specific errors related to unit conversion or registration by the unit package.

find_default_units_backend()[source]#

Set the default units adapter.

Return type:

astropy_adapter.ApUnitsAdapter | pint_adapter.PintUnitsAdapter | ezunits_adapter.EzUnitsAdapter | units_adapter.UnitsAdapter

get_adapter(name)[source]#

Get the units adapter for the given name.

Parameters:

name (str) – The name of the units adapter.

Returns:

The units adapter for the given name.

Return type:

UnitAdapter

Raises:

ValueError – If the given name is not a registered adapter.:

Subpackages#

Submodules#

pyphot.unit_adapters.astropy_adapter module#

Adapter to use transparently with the internal ezunits (frozen pint version 0.1; pyphot legacy)

class ApUnitsAdapter[source]#

Bases: UnitsAdapter

Adapter for ezunits

static Q(*args, **kwargs)[source]#

Force quantity from Unit Registry

Return type:

Quantity

static U(*args, **kwargs)[source]#

Quantity from Unit Registry

Return type:

Unit

static has_unit(val)[source]#

Check if val is a value with unit information

Parameters:

val (Any | Quantity)

Return type:

bool

typing: UnitTyping = UnitTyping(DimensionalityError=<class 'astropy.units.errors.UnitConversionError'>, UndefinedUnitError=<class 'ValueError'>, Quantity=<class 'astropy.units.quantity.Quantity'>)#
static val_in_unit(varname, value, defaultunit=None, warn=True)[source]#

check units and convert to defaultunit or create the unit information

Parameters:
  • varname (str) – name of the variable

  • value (object) – value of the variable, which may be unitless

  • defaultunit (str) – default units is unitless

  • warn (bool) – whether to warn if the variable does not have explicit units

Returns:

quantity – value with units

Return type:

ez_Quantity

Example

>>> r = 0.5
>>> print(val_in_unit('r', r, 'degree'))
# UserWarning: Variable r does not have explicit units. Assuming `degree`
<Quantity(0.5, 'degree')>
>>> r = 0.5 * unit['degree']
>>> print(val_in_unit('r', r, 'degree'))
<Quantity(0.5, 'degree')>

pyphot.unit_adapters.astropy_units module#

Declare missing photometric and spectral units for use with astropy.

class Quantity[source]#

Bases: ndarray

A ~astropy.units.Quantity represents a number with some associated unit.

See also: https://docs.astropy.org/en/stable/units/quantity.html

Parameters:
  • value (number, ~numpy.ndarray, ~astropy.units.Quantity (sequence), or str) – The numerical value of this quantity in the units given by unit. If a Quantity or sequence of them (or any other valid object with a unit attribute), creates a new Quantity object, converting to unit units as needed. If a string, it is converted to a number or Quantity, depending on whether a unit is present.

  • unit (unit-like) – An object that represents the unit associated with the input value. Must be an ~astropy.units.UnitBase object or a string parseable by the units package.

  • dtype (dtype, optional) – The dtype of the resulting Numpy array or scalar that will hold the value. If not provided, it is determined from the input, except that any integer and (non-Quantity) object inputs are converted to float by default. If None, the normal numpy.dtype introspection is used, e.g. preventing upcasting of integers.

  • copy (bool, optional) – If True (default), then the value is copied. Otherwise, a copy will only be made if __array__ returns a copy, if value is a nested sequence, or if a copy is needed to satisfy an explicitly given dtype. (The False option is intended mostly for internal use, to speed up initialization where a copy is known to have been made. Use with care.)

  • order ({'C', 'F', 'A'}, optional) – Specify the order of the array. As in ~numpy.array. This parameter is ignored if the input is a Quantity and copy=False.

  • subok (bool, optional) – If False (default), the returned array will be forced to be a Quantity. Otherwise, Quantity subclasses will be passed through, or a subclass appropriate for the unit will be used (such as ~astropy.units.Dex for u.dex(u.AA)).

  • ndmin (int, optional) – Specifies the minimum number of dimensions that the resulting array should have. Ones will be prepended to the shape as needed to meet this requirement. This parameter is ignored if the input is a Quantity and copy=False.

Raises:
  • TypeError – If the value provided is not a Python numeric type.

  • TypeError – If the unit provided is not either a Unit object or a parseable string unit.

Notes

Quantities can also be created by multiplying a number or array with a Unit. See https://docs.astropy.org/en/latest/units/

Unless the dtype argument is explicitly specified, integer or (non-Quantity) object inputs are converted to float by default.

static __new__(cls, value, unit=None, dtype=<class 'numpy.inexact'>, copy=True, order=None, subok=False, ndmin=0)[source]#
Parameters:
  • cls (type[Self])

  • value (astropy.units.Quantity | Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str])

Return type:

Self

all(axis=None, out=None)[source]#
any(axis=None, out=None)[source]#
argmax(axis=None, out=None, *, keepdims=False)[source]#
argmin(axis=None, out=None, *, keepdims=False)[source]#
argsort(axis=-1, kind=None, order=None, *, stable=None)[source]#
property cgs#

Returns a copy of the current Quantity instance with CGS units. The value of the resulting object will be scaled.

choose(choices, out=None, mode='raise')[source]#
decompose(bases=())[source]#

Generates a new Quantity with the units decomposed. Decomposed units have only irreducible units in them (see astropy.units.UnitBase.decompose).

Parameters:

bases (sequence of ~astropy.units.UnitBase, optional) – The bases to decompose into. When not provided, decomposes down to any irreducible units. When provided, the decomposed result will only contain the given units. This will raises a ~astropy.units.UnitsError if it’s not possible to do so.

Returns:

newq – A new object equal to this quantity with units decomposed.

Return type:

~astropy.units.Quantity

diff(n=1, axis=-1)[source]#
dot(b, out=None)[source]#
dump(file)[source]#

Not implemented, use .value.dump() instead.

dumps()[source]#

Not implemented, use .value.dumps() instead.

ediff1d(to_end=None, to_begin=None)[source]#
property equivalencies#

A list of equivalencies that will be applied by default during unit conversions.

fill(value)[source]#
property flat#

A 1-D iterator over the Quantity array.

This returns a QuantityIterator instance, which behaves the same as the ~numpy.flatiter instance returned by ~numpy.ndarray.flat, and is similar to, but not a subclass of, Python’s built-in iterator object.

info#

Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information.

insert(obj, values, axis=None)[source]#

Insert values along the given axis before the given indices and return a new ~astropy.units.Quantity object.

This is a thin wrapper around the numpy.insert function.

Parameters:
  • obj (int, slice or sequence of int) – Object that defines the index or indices before which values is inserted.

  • values (array-like) – Values to insert. If the type of values is different from that of quantity, values is converted to the matching type. values should be shaped so that it can be broadcast appropriately The unit of values must be consistent with this quantity.

  • axis (int, optional) – Axis along which to insert values. If axis is None then the quantity array is flattened before insertion.

Returns:

out – A copy of quantity with values inserted. Note that the insertion does not occur in-place: a new quantity array is returned.

Return type:

~astropy.units.Quantity

Examples

>>> import astropy.units as u
>>> q = [1, 2] * u.m
>>> q.insert(0, 50 * u.cm)
<Quantity [ 0.5,  1.,  2.] m>
>>> q = [[1, 2], [3, 4]] * u.m
>>> q.insert(1, [10, 20] * u.m, axis=0)
<Quantity [[  1.,  2.],
           [ 10., 20.],
           [  3.,  4.]] m>
>>> q.insert(1, 10 * u.m, axis=1)
<Quantity [[  1., 10.,  2.],
           [  3., 10.,  4.]] m>
property isscalar#

True if the value of this quantity is a scalar, or False if it is an array-like object.

Note

This is subtly different from numpy.isscalar in that numpy.isscalar returns False for a zero-dimensional array (e.g. np.array(1)), while this is True for quantities, since quantities cannot represent true numpy scalars.

item(*args)[source]#

Copy an element of an array to a scalar Quantity and return it.

Like item() except that it always returns a Quantity, not a Python scalar.

mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)[source]#
put(indices, values, mode='raise')[source]#
round(decimals=0, out=None)[source]#
searchsorted(v, *args, **kwargs)[source]#
property si#

Returns a copy of the current Quantity instance with SI units. The value of the resulting object will be scaled.

std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)[source]#
take(indices, axis=None, out=None, mode='raise')[source]#
to(unit, equivalencies=[], copy=True)[source]#

Return a new ~astropy.units.Quantity object with the specified unit.

Parameters:
  • unit (unit-like) – An object that represents the unit to convert to. Must be an ~astropy.units.UnitBase object or a string parseable by the ~astropy.units package.

  • equivalencies (list of tuple) – A list of equivalence pairs to try if the units are not directly convertible. See astropy:unit_equivalencies. If not provided or [], class default equivalencies will be used (none for ~astropy.units.Quantity, but may be set for subclasses) If None, no equivalencies will be applied at all, not even any set globally or within a context.

  • copy (bool, optional) – If True (default), then the value is copied. Otherwise, a copy will only be made if necessary.

See also

to_value

get the numerical value in a given unit.

to_string(unit=None, precision=None, format=None, subfmt=None, *, formatter=None)[source]#

Generate a string representation of the quantity and its unit.

The behavior of this function can be altered via the numpy.set_printoptions function and its various keywords. The exception to this is the threshold keyword, which is controlled via the [units.quantity] configuration item latex_array_threshold. This is treated separately because the numpy default of 1000 is too big for most browsers to handle.

Parameters:
  • unit (unit-like, optional) – Specifies the unit. If not provided, the unit used to initialize the quantity will be used.

  • precision (number, optional) – The level of decimal precision. If None, or not provided, it will be determined from NumPy print options.

  • format (str, optional) –

    The format of the result. If not provided, an unadorned string is returned. Supported values are:

    • ’latex’: Return a LaTeX-formatted string

    • ’latex_inline’: Return a LaTeX-formatted string that uses negative exponents instead of fractions

  • formatter (str, callable, dict, optional) – The formatter to use for the value. If a string, it should be a valid format specifier using Python’s mini-language. If a callable, it will be treated as the default formatter for all values and will overwrite default Latex formatting for exponential notation and complex numbers. If a dict, it should map a specific type to a callable to be directly passed into numpy.array2string. If not provided, the default formatter will be used.

  • subfmt (str, optional) –

    Subformat of the result. For the moment, only used for format='latex' and format='latex_inline'. Supported values are:

    • ’inline’: Use $ ... $ as delimiters.

    • ’display’: Use $\displaystyle ... $ as delimiters.

Returns:

A string with the contents of this Quantity

Return type:

str

to_value(unit=None, equivalencies=[])[source]#

The numerical value, possibly in a different unit.

Parameters:
  • unit (unit-like, optional) – The unit in which the value should be given. If not given or None, use the current unit.

  • equivalencies (list of tuple, optional) – A list of equivalence pairs to try if the units are not directly convertible (see astropy:unit_equivalencies). If not provided or [], class default equivalencies will be used (none for ~astropy.units.Quantity, but may be set for subclasses). If None, no equivalencies will be applied at all, not even any set globally or within a context.

Returns:

value – The value in the units specified. For arrays, this will be a view of the data if no unit conversion was necessary.

Return type:

ndarray or scalar

See also

to

Get a new instance in a different unit.

tobytes(order='C')[source]#

Not implemented, use .value.tobytes() instead.

tofile(fid, sep='', format='%s')[source]#

Not implemented, use .value.tofile() instead.

tolist()[source]#
tostring(order='C')[source]#

Not implemented, use .value.tostring() instead.

trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)[source]#
property unit#

A ~astropy.units.UnitBase object representing the unit of this quantity.

property value#

The numerical value of this instance.

See also

to_value

Get the numerical value in a given unit.

var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)[source]#
U#

alias of Unit

class Unit[source]#

Bases: NamedUnit

The main unit class.

There are a number of different ways to construct a Unit, but always returns a UnitBase instance. If the arguments refer to an already-existing unit, that existing unit instance is returned, rather than a new one.

  • From a string:

    Unit(s, format=None, parse_strict='silent')
    

    Construct from a string representing a (possibly compound) unit.

    The optional format keyword argument specifies the format the string is in, by default "generic". For a description of the available formats, see astropy.units.format.

    The optional parse_strict keyword argument controls what happens when the string does not comply with the specified format. It may be one of the following:

    • 'raise': (default) raise a ValueError exception.

    • 'warn': emit a UnitParserWarning, and return a unit.

    • 'silent': return a unit silently.

    With 'warn' or 'silent' the parser might be able to parse the string and return a normal unit, but if it fails then an UnrecognizedUnit instance is returned.

  • From a number:

    Unit(number)
    

    Creates a dimensionless unit.

  • From a UnitBase instance:

    Unit(unit)
    

    Returns the given unit unchanged.

  • From no arguments:

    Unit()
    

    Returns the dimensionless unit.

  • The last form, which creates a new Unit is described in detail below.

See also: https://docs.astropy.org/en/stable/units/

Parameters:
  • st (str or list of str) – The name of the unit. If a list, the first element is the canonical (short) name, and the rest of the elements are aliases.

  • represents (unit-like, optional) – The unit that this named unit represents.

  • doc (str, optional) – A docstring describing the unit.

  • format (dict, optional) –

    A mapping to format-specific representations of this unit. For example, for the Ohm unit, it might be nice to have it displayed as \Omega by the latex formatter. In that case, format argument should be set to:

    {'latex': r'\Omega'}
    

  • namespace (dict, optional) – When provided, inject the unit (and all of its aliases) into the given namespace.

Raises:
  • ValueError – If any of the given unit names are already in the registry.

  • ValueError – If any of the given unit names are not valid Python tokens.

  • ValueError – If represents cannot be parsed as a unit, e.g., because it is a malformed string or a |Quantity| that is not a scalar.

__init__(st, represents=None, doc=None, format=None, namespace=None)[source]#
decompose(bases=())[source]#
Parameters:

bases (Collection[UnitBase])

Return type:

UnitBase

is_unity()[source]#
Return type:

bool

property represents: UnitBase#

The unit that this named unit represents.

pyphot.unit_adapters.ezunits_adapter module#

Adapter to use transparently with the internal ezunits (frozen pint version 0.1; pyphot legacy)

class EzUnitsAdapter[source]#

Bases: UnitsAdapter

Adapter for ezunits

static Q(*args, **kwargs)[source]#

Quantity from Unit Registry

Return type:

ez_Quantity

static U(*args, **kwargs)[source]#

Quantity from Unit Registry

Return type:

ez_Quantity

static has_unit(val)[source]#

Check if val is a value with unit information

Parameters:

val (Any | ez_Quantity)

Return type:

bool

typing: UnitTyping = UnitTyping(DimensionalityError=<class 'pyphot.unit_adapters.ezunits.pint.DimensionalityError'>, UndefinedUnitError=<class 'pyphot.unit_adapters.ezunits.pint.UndefinedUnitError'>, Quantity=pyphot.unit_adapters.ezunits_adapter.ez_Quantity)#
static val_in_unit(varname, value, defaultunit=None, warn=True)[source]#

check units and convert to defaultunit or create the unit information

Parameters:
  • varname (str) – name of the variable

  • value (object) – value of the variable, which may be unitless

  • defaultunit (str) – default units is unitless

  • warn (bool) – whether to warn if the variable does not have explicit units

Returns:

quantity – value with units

Return type:

ez_Quantity

Example

>>> r = 0.5
>>> print(val_in_unit('r', r, 'degree'))
# UserWarning: Variable r does not have explicit units. Assuming `degree`
<Quantity(0.5, 'degree')>
>>> r = 0.5 * unit['degree']
>>> print(val_in_unit('r', r, 'degree'))
<Quantity(0.5, 'degree')>

pyphot.unit_adapters.pint_adapter module#

pyphot.unit_adapters.pint_units module#

pyphot.unit_adapters.typing module#

pyphot.unit_adapters.units_adapter module#

UnitsAdapter base class and decorator#

Provides the common interface for units adapters.

class UnitTyping[source]#

Bases: object

Collects exceptions related to the unit handling as standard exceptions

DimensionalityError: Any = <dataclasses._MISSING_TYPE object>#
Quantity: Any = <dataclasses._MISSING_TYPE object>#
UndefinedUnitError: Any = <dataclasses._MISSING_TYPE object>#
__init__(DimensionalityError, UndefinedUnitError, Quantity)#
Parameters:
  • DimensionalityError (Any)

  • UndefinedUnitError (Any)

  • Quantity (Any)

Return type:

None

class UnitsAdapter[source]#

Bases: object

Unifies unit handling

static Q(*args, **kwargs)[source]#

Returns an explicit quantity from a unit query (not always the default)

Return type:

Any

static U(*args, **kwargs)[source]#

Returns the resulting object from a unit query to the unit registry.

Note

Some registries make a distinction between units and quantities (i.e. value with unit information).

seealso: UnitsAdapter.Q

Return type:

Any

classmethod decorate(*args, output=None, warn=False, **kwargs)[source]#

Decorator to enforce default units for function arguments.

Parameters:
  • *args (str) – Default units for function arguments.

  • output (str, optional) – Default unit for the function output.

  • warn (bool, optional) – Whether to warn if a variable does not have explicit units.

  • _Adapter (UnitsAdapter, optional) – Units adapter to impose, defaulting to the global adapter.

  • **kwargs – Additional keyword arguments.

Returns:

Decorated function.

Return type:

Callable

static has_unit(val)[source]#

Check if val is a value with unit information

Parameters:

val (Any)

Return type:

bool

typing: UnitTyping#
static val_in_unit(varname, value, defaultunit=None, warn=True)[source]#
Parameters:
  • varname (str)

  • value (Any)

  • defaultunit (str | None)

  • warn (bool)

Return type:

Any