sasdata.data_util.nxsunit module

Define unit conversion support for NeXus style units.

The unit format is somewhat complicated. There are variant spellings and incorrect capitalization to worry about, as well as forms such as “mili*metre” and “1e-7 seconds”.

This is a minimal implementation of units including only what I happen to need now. It does not support the complete dimensional analysis provided by the package udunits on which NeXus is based, or even the units used in the NeXus definition files.

Unlike other units packages, this package does not carry the units along with the value but merely provides a conversion function for transforming values.

Usage example:

import nxsunit
u = nxsunit.Converter('mili*metre')  # Units stored in mm
v = u(3000,'m')  # Convert the value 3000 mm into meters

NeXus example:

# Load sample orientation in radians regardless of how it is stored.
# 1. Open the path
file.openpath('/entry1/sample/sample_orientation')
# 2. scan the attributes, retrieving 'units'
units = [for attr,value in file.attrs() if attr == 'units']
# 3. set up the converter (assumes that units actually exists)
u = nxsunit.Converter(units[0])
# 4. read the data and convert to the correct units
v = u(file.read(),'radians')

This is a standalone module, not relying on either DANSE or NeXus, and can be used for other unit conversion tasks.

Note: minutes are used for angle and seconds are used for time. We cannot tell what the correct interpretation is without knowing something about the fields themselves. If this becomes an issue, we will need to allow the application to set the dimension for the unit rather than inferring the dimension from an example unit.

class sasdata.data_util.nxsunit.Converter(units: str | None = None, dimension: List[str] | None = None)

Bases: object

Unit converter for NeXus style units.

The converter is initialized with the units of the source value. Various source values can then be converted to target values based on target value name.

__call__(value: T, units: str | None = '') List[float] | T

Call self as a function.

__dict__ = mappingproxy({'__module__': 'sasdata.data_util.nxsunit', '__doc__': '\n    Unit converter for NeXus style units.\n\n    The converter is initialized with the units of the source value.  Various\n    source values can then be converted to target values based on target\n    value name.\n    ', '_units': None, 'dimension': None, 'scalemap': None, 'scalebase': None, 'scaleoffset': None, 'units': <property object>, '__init__': <function Converter.__init__>, 'scale': <function Converter.scale>, '_scale_with_offset': <function Converter._scale_with_offset>, '_get_scale_for_units': <function Converter._get_scale_for_units>, 'get_compatible_units': <function Converter.get_compatible_units>, '__call__': <function Converter.__call__>, '__dict__': <attribute '__dict__' of 'Converter' objects>, '__weakref__': <attribute '__weakref__' of 'Converter' objects>, '__annotations__': {'_units': 'List[str]', 'dimension': 'List[str]', 'scalemap': 'List[Dict[str, ConversionType]]', 'scalebase': 'float', 'scaleoffset': 'float', 'units': 'str'}})
__doc__ = '\n    Unit converter for NeXus style units.\n\n    The converter is initialized with the units of the source value.  Various\n    source values can then be converted to target values based on target\n    value name.\n    '
__init__(units: str | None = None, dimension: List[str] | None = None)
__module__ = 'sasdata.data_util.nxsunit'
__weakref__

list of weak references to the object

_get_scale_for_units(units: List[str])

Protected method to get scale factor and scale offset as a combined value

_scale_with_offset(value: float, scale_base: Tuple[float, float]) float

Scale the given value and add the offset using the units string supplied

_units: List[str] = None

Name of the source units (km, Ang, us, …)

dimension: List[str] = None

Type of the source units (distance, time, frequency, …)

get_compatible_units() List[str]

Return a list of compatible units for the current Convertor object

scale(units: str = '', value: T = None) List[float] | T

Scale the given value using the units string supplied

scalebase: float = None

Scale base for the source units

scalemap: List[Dict[str, float | Tuple[float, float]]] = None

Scale converter, mapping unit name to scale factor or (scale, offset) for temperature units.

scaleoffset: float = None
property units: str
class sasdata.data_util.nxsunit.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False)

Bases: _Final, _Immutable, _BoundVarianceMixin, _PickleUsingNameMixin

Type variable.

Usage:

T = TypeVar('T')  # Can be anything
A = TypeVar('A', str, bytes)  # Must be str or bytes

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows:

def repeat(x: T, n: int) -> List[T]:

‘’’Return a list containing n references to x.’’’ return [x]*n

def longest(x: A, y: A) -> A:

‘’’Return the longest of two strings.’’’ return x if len(x) >= len(y) else y

The latter example’s signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str.

At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.

Type variables defined with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. See PEP 484 for more details. By default generic types are invariant in all type variables.

Type variables can be introspected. e.g.:

T.__name__ == ‘T’ T.__constraints__ == () T.__covariant__ == False T.__contravariant__ = False A.__constraints__ == (str, bytes)

Note that only type variables defined in global scope can be pickled.

__dict__ = mappingproxy({'__module__': 'typing', '__doc__': "Type variable.\n\n    Usage::\n\n      T = TypeVar('T')  # Can be anything\n      A = TypeVar('A', str, bytes)  # Must be str or bytes\n\n    Type variables exist primarily for the benefit of static type\n    checkers.  They serve as the parameters for generic types as well\n    as for generic function definitions.  See class Generic for more\n    information on generic types.  Generic functions work as follows:\n\n      def repeat(x: T, n: int) -> List[T]:\n          '''Return a list containing n references to x.'''\n          return [x]*n\n\n      def longest(x: A, y: A) -> A:\n          '''Return the longest of two strings.'''\n          return x if len(x) >= len(y) else y\n\n    The latter example's signature is essentially the overloading\n    of (str, str) -> str and (bytes, bytes) -> bytes.  Also note\n    that if the arguments are instances of some subclass of str,\n    the return type is still plain str.\n\n    At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.\n\n    Type variables defined with covariant=True or contravariant=True\n    can be used to declare covariant or contravariant generic types.\n    See PEP 484 for more details. By default generic types are invariant\n    in all type variables.\n\n    Type variables can be introspected. e.g.:\n\n      T.__name__ == 'T'\n      T.__constraints__ == ()\n      T.__covariant__ == False\n      T.__contravariant__ = False\n      A.__constraints__ == (str, bytes)\n\n    Note that only type variables defined in global scope can be pickled.\n    ", '__init__': <function TypeVar.__init__>, '__typing_subst__': <function TypeVar.__typing_subst__>, '__dict__': <attribute '__dict__' of 'TypeVar' objects>, '__annotations__': {}})
__doc__ = "Type variable.\n\n    Usage::\n\n      T = TypeVar('T')  # Can be anything\n      A = TypeVar('A', str, bytes)  # Must be str or bytes\n\n    Type variables exist primarily for the benefit of static type\n    checkers.  They serve as the parameters for generic types as well\n    as for generic function definitions.  See class Generic for more\n    information on generic types.  Generic functions work as follows:\n\n      def repeat(x: T, n: int) -> List[T]:\n          '''Return a list containing n references to x.'''\n          return [x]*n\n\n      def longest(x: A, y: A) -> A:\n          '''Return the longest of two strings.'''\n          return x if len(x) >= len(y) else y\n\n    The latter example's signature is essentially the overloading\n    of (str, str) -> str and (bytes, bytes) -> bytes.  Also note\n    that if the arguments are instances of some subclass of str,\n    the return type is still plain str.\n\n    At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.\n\n    Type variables defined with covariant=True or contravariant=True\n    can be used to declare covariant or contravariant generic types.\n    See PEP 484 for more details. By default generic types are invariant\n    in all type variables.\n\n    Type variables can be introspected. e.g.:\n\n      T.__name__ == 'T'\n      T.__constraints__ == ()\n      T.__covariant__ == False\n      T.__contravariant__ = False\n      A.__constraints__ == (str, bytes)\n\n    Note that only type variables defined in global scope can be pickled.\n    "
__init__(name, *constraints, bound=None, covariant=False, contravariant=False)
__module__ = 'typing'
__typing_subst__(arg)
__weakref__
sasdata.data_util.nxsunit._build_all_units()

Fill in the global variables DIMENSIONS and AMBIGUITIES for all available dimensions.

sasdata.data_util.nxsunit._build_degree_units(name: str, symbol: str, conversion: float | Tuple[float, float]) Dict[str, float | Tuple[float, float]]

Builds variations on the temperature unit name, including the degree symbol or the word degree.

sasdata.data_util.nxsunit._build_inv_n_metric_units(unit: str, abbr: str, n: int = 2) Dict[str, float | Tuple[float, float]]

Using the return from _build_metric_units, build inverse to the nth power variations on all units (1/x^n, invx^n, x^{-n} and x^-n)

sasdata.data_util.nxsunit._build_inv_n_units(names: Sequence[str], conversion: float | Tuple[float, float], n: int = 2) Dict[str, float | Tuple[float, float]]

Builds variations on inverse x to the nth power units, including 1/x^n, invx^n, x^-n and x^{-n}.

sasdata.data_util.nxsunit._build_metric_units(unit: str, abbr: str) Dict[str, float]

Construct standard SI names for the given unit. Builds e.g.,

s, ns, n*s, n_s second, nanosecond, nano*second, nano_second seconds, nanoseconds, nano*seconds, nano_seconds

Includes prefixes for femto through peta.

Ack! Allows, e.g., Coulomb and coulomb even though Coulomb is not a unit because some NeXus files store it that way!

Returns a dictionary of names and scales.

sasdata.data_util.nxsunit._build_plural_units(**kw: Dict[str, float | Tuple[float, float]]) Dict[str, float | Tuple[float, float]]

Construct names for the given units. Builds singular and plural form.

sasdata.data_util.nxsunit._format_unit_structure(unit: str | None = None) List[str]

Format units a common way :param unit: Unit string to be formatted :return: Formatted unit string

sasdata.data_util.nxsunit.standardize_units(unit: str | None) List[str]

Convert supplied units to a standard format for maintainability :param unit: Raw unit as supplied :return: Unit with known, reduced values