PhysicalQuantity
Connects a value with a unit.
>>> from PhysicalQuantities.quantity import PhysicalQuantity
>>> g = PhysicalQuantity(9.81, 'm/s**2')
The value is stored in the attribute .value. It can acutally be any Python object, however when working with units, especially converting between different unit scalings, there can be multiplications with float values to take that into account.
For Numpy arrays, it is better to use PhysicalQuantityArray instead, as it subclasses a ndarray.
Reference
PhysicalQuantity class definition
- class PhysicalQuantities.quantity.PhysicalQuantity(value: int | float | complex, unit: str | PhysicalUnit, annotation: str = '')[source]
Represents a physical quantity with a value and a unit.
Supports arithmetic operations (+, -, , /, //, *), comparisons, conversions between compatible units, and some mathematical functions.
Attributes
- valueint | float | complex
The numerical value of the quantity.
- unitPhysicalUnit
The unit associated with the value.
- formatstr, optional
A format string used for converting the value to a string. Defaults to ‘’.
- annotationstr, optional
An optional annotation or description for the quantity. Defaults to ‘’.
- __array_priority__int
Ensures NumPy ufuncs are handled correctly (set to 1000).
- __abs__()[source]
Returns the quantity with the absolute value.
Applies abs() to the numerical value.
Returns
- PhysicalQuantity
A new quantity with the absolute value.
- __array_ufunc__(ufunc, method, *inputs, **kwargs)[source]
Implements NumPy Universal Function (ufunc) support.
- __bool__() bool[source]
Tests if the quantity’s value is non-zero (Python 3 boolean context).
This method provides the standard boolean interpretation used in contexts like if quantity:.
Returns
- bool
True if the value is non-zero, False otherwise. For array values, tests if any element is non-zero using numpy.any().
- __complex__()[source]
Converts the quantity to a complex number after converting to base units.
Returns
- complex
The numerical value of the quantity in base units as a complex number.
- __deepcopy__(memo: dict) PhysicalQuantity[source]
Creates a deep copy of the PhysicalQuantity instance.
Ensures that the numerical value is also deep-copied, crucial for mutable types like numpy arrays.
Parameters
- memodict
The memo dictionary used by copy.deepcopy.
Returns
- PhysicalQuantity
A new, independent copy of the quantity.
- __dir__() list[str][source]
Lists available attributes, including units for conversion via attribute access.
Extends the default dir() list with names of units from unit_table that share the same base unit dimension as the current quantity. This allows tab completion for unit conversions like quantity.mV.
Returns
- list[str]
A list of attribute names, including compatible unit names.
- __eq__(other)[source]
Tests if two quantities are equal (self == other).
Compares values after converting both quantities to base units. Returns False if other is not a PhysicalQuantity or if units are dimensionally incompatible.
Parameters
- otherobject
The object to compare against.
Returns
- bool
True if self is equal to other.
- __float__()[source]
Converts the quantity to a float after converting to base units.
Returns
- float
The numerical value of the quantity in base units as a float.
- __floordiv__(other)[source]
Performs floor division (self // other).
self // scalar: Floor divides value, keeps the unit.
self // other_quantity: Floor divides values, divides units. If the resulting unit is dimensionless, returns a scaled scalar.
Parameters
- othernumber | PhysicalQuantity
The divisor.
Returns
- PhysicalQuantity | number
The result of the floor division.
- __format__(*args, **kw)[source]
Formats the quantity using a standard format specifier applied to the value.
- __ge__(other)[source]
Tests if this quantity is greater than or equal to another (self >= other).
Compares values after converting both quantities to base units.
Parameters
- otherPhysicalQuantity
The quantity to compare against.
Returns
- bool
True if self is greater than or equal to other.
Raises
- TypeError
If other is not a PhysicalQuantity.
- UnitError
If units are incompatible.
- __getattr__(attr) int | float | complex | PhysicalQuantity[source]
Converts to a different scaling prefix of the same unit via attribute access.
Allows retrieving the quantity expressed in a unit with a different scaling prefix (e.g., quantity.mV). If the attribute name ends with an underscore (_), the numerical value (in the specified unit) is returned without the unit (e.g., quantity.mV_). Accessing just _ returns the original numerical value.
This method is called only if standard attribute lookup fails.
Parameters
- attrstr
The attribute name, expected to be a unit name (optionally with a trailing _) or just _.
Returns
- int | float | complex | PhysicalQuantity
The quantity converted to the specified unit scaling, or the numerical value if the attribute ends with _.
Raises
- AttributeError
If attr is not a unit name found in unit_table, if the found unit is incompatible with the quantity’s unit, or if the attribute syntax is otherwise invalid.
Examples
>>> from PhysicalQuantities import q >>> a = 2 * q.mm >>> a._ 2 >>> a.mm_ 2 >>> a.m_ # Converts mm to m and returns the value 0.002 >>> a.m # Converts mm to m and returns the PhysicalQuantity 0.002 m >>> a.base # Accesses the .base property, does not go through __getattr__ 0.002 m >>> a.kg Traceback (most recent call last): ... AttributeError: Unit 'kg' is not compatible with unit 'mm'
- __getitem__(key)[source]
Allows indexing if the underlying value is an array or list.
Parameters
- keyslice | int
The index or slice.
Returns
- PhysicalQuantity
A new PhysicalQuantity containing the indexed/sliced value.
Raises
- AttributeError
If the underlying value does not support indexing.
Examples
>>> from PhysicalQuantities import PhysicalQuantity >>> import numpy as np >>> q_array = PhysicalQuantity(np.array([1, 2, 3]), 'm') >>> q_array[1] 2 m >>> q_array[0:2] [1 2] m
- __gt__(other)[source]
Tests if this quantity is greater than another (self > other).
Compares values after converting both quantities to base units.
Parameters
- otherPhysicalQuantity
The quantity to compare against.
Returns
- bool
True if self is strictly greater than other.
Raises
- TypeError
If other is not a PhysicalQuantity.
- UnitError
If units are incompatible.
- __hash__ = None
- __init__(value: int | float | complex, unit: str | PhysicalUnit, annotation: str = '')[source]
Initializes a PhysicalQuantity.
Parameters
- valueint | float | complex
The numerical value of the quantity.
- unitstr | PhysicalUnit
The unit of the quantity, either as a string name or a PhysicalUnit object.
- annotationstr, optional
An optional annotation for the quantity. Defaults to ‘’.
Examples
>>> from PhysicalQuantities import PhysicalQuantity >>> v = PhysicalQuantity(1, 'V') >>> v 1 V
- __le__(other)[source]
Tests if this quantity is less than or equal to another (self <= other).
Compares values after converting both quantities to base units.
Parameters
- otherPhysicalQuantity
The quantity to compare against.
Returns
- bool
True if self is less than or equal to other.
Raises
- TypeError
If other is not a PhysicalQuantity.
- UnitError
If units are incompatible.
- __len__()[source]
Returns the length if the underlying value is an array or list.
Returns
- int
The length of the underlying value array/list.
Raises
- TypeError
If the underlying value does not have a defined length.
Examples
>>> from PhysicalQuantities import PhysicalQuantity >>> import numpy as np >>> q_list = PhysicalQuantity([1, 2, 3], 's') >>> len(q_list) 3
- __lt__(other)[source]
Tests if this quantity is less than another (self < other).
Compares values after converting both quantities to base units.
Parameters
- otherPhysicalQuantity
The quantity to compare against.
Returns
- bool
True if self is strictly less than other.
Raises
- TypeError
If other is not a PhysicalQuantity.
- UnitError
If units are incompatible.
- __mul__(other)[source]
Multiplies by a scalar or another PhysicalQuantity.
self * scalar: Scales the value, keeps the unit.
self * other_quantity: Multiplies values and units. If the resulting unit is dimensionless, returns a scaled scalar.
- __ne__(other)[source]
Tests if two quantities are not equal (self != other).
Parameters
- otherobject
The object to compare against.
Returns
- bool
True if self is not equal to other.
- __neg__()[source]
Returns the quantity with the negated value (unary minus).
Returns
- PhysicalQuantity
A new quantity with the negated value (-self).
- __pos__()[source]
Returns the quantity itself (unary plus).
Returns
- PhysicalQuantity
The quantity itself (+self).
- __pow__(other)[source]
Raises the quantity to a power (self ** other).
The exponent other must be a dimensionless scalar.
Parameters
- othernumber
The exponent (must be dimensionless).
Returns
- PhysicalQuantity
The quantity raised to the power other.
Raises
- UnitError
If other is a PhysicalQuantity (exponent must be scalar).
- __radd__(other)
Adds another PhysicalQuantity. Units must be compatible.
- __rdiv__(other)[source]
Performs reverse true division (other / self) (Python 2 style).
See __rtruediv__.
- __rfloordiv__(other)[source]
Performs reverse floor division (other // self).
other must be a scalar. The resulting unit is the reciprocal of self.unit.
Parameters
- othernumber
The dividend (must be a scalar).
Returns
- PhysicalQuantity
The result with reciprocal units.
Raises
- TypeError
If other is a PhysicalQuantity.
- __rmul__(other)
Multiplies by a scalar or another PhysicalQuantity.
self * scalar: Scales the value, keeps the unit.
self * other_quantity: Multiplies values and units. If the resulting unit is dimensionless, returns a scaled scalar.
- __round__(ndigits=0)[source]
Rounds the numerical value to a given number of decimal places.
Applies round() or numpy.round() to the value.
Parameters
- ndigitsint, optional
Number of decimal places to round to (default is 0).
Returns
- PhysicalQuantity
A new quantity with the rounded value.
- __rpow__(other)[source]
Raises a scalar base to the power of this quantity (other ** self).
This operation is only valid if self is dimensionless.
Parameters
- othernumber
The base.
Raises
- UnitError
If self is not dimensionless.
- __rsub__(other)[source]
Subtracts this quantity from another (other - self). Units must be compatible.
- __rtruediv__(other)
Performs reverse true division (other / self) (Python 2 style).
See __rtruediv__.
- __setitem__(key, value)[source]
Allows item assignment if the underlying value is an array or list.
The assigned value must be a PhysicalQuantity and will be converted to the unit of this quantity before assignment.
Parameters
- keyslice | int
The index or slice where the value should be assigned.
- valuePhysicalQuantity
The PhysicalQuantity instance to assign.
Raises
- AttributeError
If the underlying value does not support item assignment, or if value is not a PhysicalQuantity.
- UnitError
If the unit of value is not compatible with this quantity’s unit.
Examples
>>> from PhysicalQuantities import PhysicalQuantity, q >>> import numpy as np >>> q_array = PhysicalQuantity(np.array([1.0, 2.0, 3.0]), 'm') >>> q_array[0] = 50 * q.cm >>> q_array [0.5 2. 3. ] m
- __str__()[source]
Returns the string representation ‘value unit’.
Uses IPython’s float precision settings if available via self.ptformatter and no specific self.format is set.
Returns
- str
The string representation of the quantity.
- __truediv__(other)
Performs true division (self / other) (Python 2 style).
See __truediv__.
- __weakref__
list of weak references to the object (if defined)
- property autoscale: PhysicalQuantity
Rescales the quantity to a unit with a ‘reasonable’ prefix.
Attempts to find a unit prefix (like k, m, n, etc.) such that the numerical value falls roughly between 1 and 1000 (or 0.001 and 1 for scales < 1). Works best for simple units with standard SI prefixes defined. Returns the original quantity if no suitable rescaling is found.
Returns
- PhysicalQuantity
A new quantity object, possibly rescaled.
Examples
>>> from PhysicalQuantities import PhysicalQuantity, q >>> (4e-9 * q.F).autoscale 4.0 nF >>> (0.005 * q.V).autoscale 5.0 mV >>> (12345 * q.m).autoscale 12.345 km
- property base: PhysicalQuantity
Converts the quantity to its equivalent representation in SI base units.
Calculates the value in terms of the fundamental SI base units (kg, m, s, A, K, mol, cd) and constructs the corresponding unit string. Handles units with offsets (like temperature scales) correctly during value conversion.
Returns
- PhysicalQuantity
A new quantity object expressed in SI base units.
Examples
>>> from PhysicalQuantities import PhysicalQuantity, q >>> (1 * q.km).base 1000.0 m >>> (1 * q.V).base 1.0 kg*m**2*s**-3*A**-1 >>> q.PhysicalQuantity(0, 'degC').base # 0 degC -> 273.15 K 273.15 K >>> q.PhysicalQuantity(32, 'degF').base # 32 degF -> 273.15 K 273.15 K
- convert(unit)[source]
Converts the quantity in-place to a different unit.
Adjusts the value and updates the unit attribute. The new unit must be compatible with the original unit.
Parameters
- unitstr | PhysicalUnit
The target unit to convert to.
Raises
- UnitError
If the target unit is not compatible.
- cos() float[source]
Calculates the cosine of the quantity, assuming it is an angle.
Converts the value to radians before applying numpy.cos.
Returns
- float
The cosine of the angle value in radians.
Raises
- UnitError
If the quantity’s unit is not an angle type.
- property dB: dBQuantity
Converts the quantity to a dB representation (if applicable).
Uses heuristics to determine whether to use 10*log10 (for power-like units containing ‘W’) or 20*log10 (for amplitude-like units).
Returns
- dBQuantity
The quantity expressed in decibels relative to its unit (e.g., dBV, dBW).
Examples
>>> from PhysicalQuantities import q >>> (10 * q.V).dB 20.0 dBV >>> (10 * q.W).dB 10.0 dBW
- static from_dict(quantity_dict: dict) PhysicalQuantity[source]
Creates a PhysicalQuantity instance from a dictionary representation.
Parameters
- quantity_dictdict
A dictionary containing ‘value’ and ‘PhysicalUnit’ keys. The ‘PhysicalUnit’ value should be a dictionary suitable for PhysicalUnit.from_dict. Can optionally be nested under a ‘PhysicalQuantity’ key.
Returns
- PhysicalQuantity
The reconstructed PhysicalQuantity instance.
Raises
- ValueError
If the dictionary structure is incorrect.
Notes
This relies on PhysicalUnit.from_dict to reconstruct the unit. The unit must typically be predefined or definable from the dictionary content.
- static from_json(json_quantity: str) PhysicalQuantity[source]
Creates a PhysicalQuantity instance from a JSON string.
Parameters
- json_quantitystr
A JSON string, typically generated by to_json, containing a ‘PhysicalQuantity’ key whose value is the dictionary representation.
Returns
- PhysicalQuantity
The reconstructed PhysicalQuantity instance.
Raises
- ValueError
If the JSON string does not contain the expected structure.
- property imag: PhysicalQuantity
Returns the imaginary part of the quantity’s value, keeping the unit.
Returns
- PhysicalQuantity
A new quantity with the imaginary part of the original value.
Examples
>>> from PhysicalQuantities import PhysicalQuantity >>> b = PhysicalQuantity(2 + 1j, 'V') >>> b.imag 1.0 V
- property np: ndarray
Return a numpy array with the unit as metadata attribute
Returns
- np.ndarray
dtype.metadata = dict(unit=PhysicalUnit)
- pow(exponent: float) PhysicalQuantity[source]
Raises the quantity to the power of an exponent (alias for __pow__).
Parameters
- exponentfloat
The exponent (must be dimensionless scalar).
Returns
- PhysicalQuantity
The quantity raised to the specified power.
- property real: PhysicalQuantity
Returns the real part of the quantity’s value, keeping the unit.
Returns
- PhysicalQuantity
A new quantity with the real part of the original value.
Examples
>>> from PhysicalQuantities import PhysicalQuantity >>> b = PhysicalQuantity(2 + 1j, 'V') >>> b.real 2.0 V
- rint()[source]
Rounds the numerical value(s) to the nearest integer.
Applies numpy.rint to the underlying value.
Returns
- PhysicalQuantity
A new quantity with the value(s) rounded to the nearest integer.
- sin() float[source]
Calculates the sine of the quantity, assuming it is an angle.
Converts the value to radians before applying numpy.sin.
Returns
- float
The sine of the angle value in radians.
Raises
- UnitError
If the quantity’s unit is not an angle type (e.g., rad, deg).
- sqrt() PhysicalQuantity[source]
Calculates the positive square root of the quantity.
Returns
- PhysicalQuantity
The square root (self ** 0.5).
- tan() float[source]
Calculates the tangent of the quantity, assuming it is an angle.
Converts the value to radians before applying numpy.tan.
Returns
- float
The tangent of the angle value in radians.
Raises
- UnitError
If the quantity’s unit is not an angle type.
- to(*units)[source]
Converts the quantity to the specified unit(s).
Parameters
- *unitsstr | PhysicalUnit
One or more target units (names or PhysicalUnit objects).
Returns
- PhysicalQuantity | tuple[PhysicalQuantity, …]
If one unit is specified: A new PhysicalQuantity object representing the value in that unit.
If multiple units are specified: A tuple of PhysicalQuantity objects, one for each specified unit. The values are calculated such that their sum equals the original quantity, and intermediate values (except the last) are integers (using _round). This is useful for irregular unit systems like hours/minutes/seconds.
Raises
- UnitError
If any target unit is incompatible with the quantity’s current unit.
Examples
>>> from PhysicalQuantities import PhysicalQuantity, q >>> b = PhysicalQuantity(4, 'J/s') >>> b.to('W') 4.0 W >>> t = PhysicalQuantity(3661, 's') >>> h, m, s = t.to('h', 'min', 's') # Note the order matters for tuple unpacking >>> h, m, s (1 h, 1 min, 1.0 s) >>> t = PhysicalQuantity(1000, 's') >>> t.to('h', 'min', 's') (0 h, 16 min, 40.0 s)
Notes
When multiple units are provided, they are processed in order of magnitude (largest first, based on sorting internally). The internal _round method (truncation) is used to determine integer parts for intermediate units. Floating point inaccuracies might occur.