Unit registry#
- class ansys.units.unit_registry.UnitRegistry(config: str = 'cfg.yaml', other: Mapping[str, Mapping[str, Any]] = {}, custom_units: Sequence[Mapping[str, Any]] | None = None, custom_units_file: str | None = None)#
Bases:
objectA representation of valid
Unitinstances.All base and derived units loaded from the configuration file, cfg.yaml, on package initialization are provided by default.
- Parameters:
- config: str, optional
Path of a
YAMLconfiguration file, which can be a custom file, and defaults to the provided file,cfg.yaml. Custom configuration files must match the format of the default configuration file.- other: dict, optional
Dictionary for additional units (uses config file format).
- custom_units
listofdict,optional List of custom units to register during construction. Each dict must have keys
"unit","composition", and"factor"matching theregister_unit()signature. An optional"aliases"key (a list of strings) is also supported.- custom_units_file
str,optional Path to a
YAMLfile previously produced byexport_custom_units(). Entries are loaded and registered the same way ascustom_units, and the two can be combined.
Examples
>>> from ansys.units import UnitRegistry, Unit >>> ureg = UnitRegistry() >>> assert ureg.kg == Unit(units="kg") >>> fps = Unit("ft s^-1") >>> ureg.foot_per_sec = fps
Register custom units at construction:
>>> ur = UnitRegistry(custom_units=[ ... {"unit": "micron", "composition": "m", "factor": 1e-6}, ... {"unit": "inch", "composition": "m", "factor": 0.0254}, ... {"unit": "furlong", "composition": "m", "factor": 201.168, ... "aliases": ["furlongs"]}, ... ]) >>> q = ur.Quantity(10, "micron")
- Quantity(value: float | _ArrayInput, units: str | Unit) Quantity#
Create a Quantity using this registry’s units.
This method allows creating quantities with instance-registered units using string names.
- Parameters:
- Returns:
QuantityThe created quantity.
Examples
>>> ur = UnitRegistry() >>> ur.register_unit(unit="micron", composition="m", factor=1e-6) >>> q = ur.Quantity(1, "micron") >>> print(q) 1.0 micron
- export_custom_units(path: str, *, overwrite: bool = False) None#
Export this registry’s runtime-registered custom units to a YAML file.
Only units registered via
register_unit()(directly, or through thecustom_units/custom_units_fileconstructor parameters) are exported. Built-in units are never included. The resulting file can be reloaded withload_custom_units()or passed directly ascustom_units_fileto a newUnitRegistry.- Parameters:
- Raises:
ValueErrorIf this registry has no custom registered units to export.
FileExistsErrorIf
pathalready exists andoverwriteisFalse.
Examples
>>> from ansys.units.common import m >>> ur = UnitRegistry() >>> ur.register_unit("furlong", 201.168 * m, aliases=["furlongs"]) >>> ur.export_custom_units("units.yaml") >>> ur2 = UnitRegistry(custom_units_file="units.yaml") >>> ur2.furlong is ur2.furlongs True
- get_unit(name: str) Unit#
Look up a unit by name from this registry.
Checks instance-registered units first, then falls back to built-in units and compound unit strings. This allows string-based lookup of custom registered units as well as standard unit expressions.
- Parameters:
- name
str The unit name or compound unit string to look up (e.g., “micron”, “m”, “kg mol^-1”).
- name
- Returns:
UnitThe unit object.
- Raises:
AttributeErrorIf the unit is not found in this registry or cannot be parsed.
- register_alias(alias: str, canonical: str) None#
Register a new alias for an existing unit.
The alias is added to the global alias table so that it can be used anywhere a unit string is accepted (
Unit(),Quantity(), etc.).- Parameters:
- Raises:
AliasAlreadyRegisteredIf
aliasis already registered as a unit or alias.ValueErrorIf
canonicalis not a known unit or alias.
- register_unit(unit: str, definition: Unit | Quantity[Any], *, aliases: Sequence[str] | None = None) Unit#
- register_unit(*, unit: str, composition: str, factor: float, aliases: Sequence[str] | None = None) Unit
Register a new derived unit on this
UnitRegistryinstance.This is instance-scoped: it affects only this registry and does not mutate global state or other registries. The registered unit can be accessed as an attribute (e.g.,
ur.micron) or viaget_unit()for string-based lookup.This method supports two equivalent calling conventions: an object-based form that accepts a
UnitorQuantitydefinition, and acomposition/factorform.- Parameters:
- unit: str
The symbol/name of the new unit (e.g., “micron”).
- definition: Unit or Quantity, optional
An object-based definition of the new unit, for example
201.168 * m(aQuantity) or a bareUnitinstance (treated as a factor of1). Mutually exclusive withcomposition/factor.- composition: str, optional
A valid unit composition using existing configured units (e.g., “m”). Must be provided together with
factor. Mutually exclusive withdefinition.- factor: float, optional
Scale factor that relates the composition to this unit. Must be provided together with
composition. Mutually exclusive withdefinition.- aliases: sequence of str, optional
Additional names that resolve to the same registered unit on this instance (e.g.,
["furlongs"]).
- Returns:
UnitThe registered unit attached on this instance.
- Raises:
UnitNameAlreadyRegisteredIf
unit(or one ofaliases) is a built-in unit name, or already exists on this instance with a different effective definition (dimensions, SI scaling factor, or SI offset). Re-registering the same name with an equivalent definition is a no-op that returns the existing unit.ValueErrorIf
unitor an alias is empty,factoris not finite, or both/neither ofdefinitionandcomposition/factorare given.
Notes
The duplicate-name check compares effective definitions (dimensions, SI scaling factor, and SI offset). Re-registering the same name with an equivalent definition is idempotent. Built-in unit names can never be overridden, even with an equivalent definition. The check does not detect equivalent definitions registered under a different name.
Examples
>>> ur = UnitRegistry() >>> ur.register_unit(unit="micron", composition="m", factor=1e-6) >>> q = ur.Quantity(1, "micron") # Use registry's Quantity method
Object-based form, with an alias:
>>> from ansys.units.common import m >>> ur.register_unit("furlong", 201.168 * m, aliases=["furlongs"]) >>> ur.furlong == ur.furlongs True
- ansys.units.unit_registry.load_custom_units(path: str) list[dict[str, Any]]#
Load custom unit definitions from a file written by
export_custom_units.- Parameters:
- path
str Path to a
YAMLfile previously produced byUnitRegistry.export_custom_units().
- path
- Returns:
Examples
>>> ur.export_custom_units("units.yaml") >>> custom_units = load_custom_units("units.yaml") >>> ur2 = UnitRegistry(custom_units=custom_units)
- exception ansys.units.unit_registry.UnitNameAlreadyRegistered(name: str)#
Bases:
ValueErrorRaised when a unit name conflicts with an existing name.
This is raised when
unit(or an alias) is a built-in unit name, or when it is already registered on the instance with a different effective definition (dimensions, SI scaling factor, or SI offset). Re-registering the same name with an equivalent definition is a no-op and does not raise. Units with different names but equivalent definitions (same composition and factor) are also not detected as conflicts.
- exception ansys.units.unit_registry.AliasAlreadyRegistered(name: str)#
Bases:
ValueErrorRaised when an alias conflicts with an existing unit or alias.