mpylab.tools.uconv module¶
Unit conversion helpers used by parser and devices.
This module is the canonical conversion backend in mpylab. The public API supports both directions:
unit/value -> Quantity (to_quantity)
Quantity -> target unit/value (from_quantity)
The mapping is case-insensitive for unit names.
- class mpylab.tools.uconv.AsymmetricDBValue(value: float, plus: float, minus: float, unit: str = 'dB', lower_bound_clipped: bool = False, clipped_lower_value: float | None = None)
Bases:
objectNominal dB value with separate positive and negative uncertainties.
Logarithmic conversion of a symmetric linear uncertainty is asymmetric.
plusis the upper dB uncertainty,minusis the lower dB uncertainty. If the lower linear bound is not positive, the lower dB value is clipped toclipped_lower_value,minusis infinite, andlower_bound_clippedis true.- Parameters:
value (float) – Nominal logarithmic value.
plus (float) – Positive logarithmic uncertainty relative to
value.minus (float) – Negative logarithmic uncertainty relative to
value.unit (str, optional) – Display label for the logarithmic unit.
lower_bound_clipped (bool, optional) – Whether the lower linear bound could not be represented logarithmically.
clipped_lower_value (float or None, optional) – Absolute logarithmic value substituted for the invalid lower bound.
Notes
If the lower linear bound is not positive, the lower dB value is clipped to
LOWEST_DBwhenclipped_lower_valueisNone.- as_tuple()
Return the value and uncertainties for simple formatting code.
- Returns:
(value, plus, minus, unit).- Return type:
tuple of (float, float, float, str)
- clipped_lower_value: float | None = None
- lower_bound_clipped: bool = False
- lower_value()
Return the absolute lower logarithmic bound.
- Returns:
value - minusor the configured clipped lower value.- Return type:
float
- minus: float
- plus: float
- unit: str = 'dB'
- upper_value()
Return the absolute upper logarithmic bound.
- Returns:
value + plus.- Return type:
float
- value: float
- class mpylab.tools.uconv.UConv
Bases:
objectCentral registry for unit conversion methods.
uconv maps input unit strings to tuples (target_scuq_unit, converter). uconv_from_quantity maps scuq unit-string representation to outbound converters keyed by destination unit string.
- classmethod available_output_units(obj)
Return target units available for a quantity.
- Parameters:
obj (scuq.quantities.Quantity) – Quantity whose unit selects the outbound conversion registry.
- Returns:
Sorted target unit names, or an empty tuple when no outbound mapping is registered.
- Return type:
tuple of str
- Raises:
TypeError – If
objdoes not expose a SCUQ unit.
- classmethod available_units()
Return all supported input units.
- Returns:
Sorted normalized input unit names.
- Return type:
tuple of str
- classmethod convert(unit, value)
Convert a numeric value to its canonical SCUQ representation.
- Parameters:
unit (str) – Unit of the input value.
value (scalar or array-like) – Numeric value expressed in
unit.
- Returns:
Canonical SCUQ unit followed by the converted value.
- Return type:
tuple of (scuq.units.Unit, object)
- Raises:
TypeError – If the unit name or numeric input type is unsupported.
ValueError – If the unit is unknown.
- classmethod from_quantity(tounit, obj)
Convert a SCUQ quantity to a numeric value in a target unit.
- Parameters:
tounit (str) – Requested output unit.
obj (scuq.quantities.Quantity) – Quantity whose expectation value is converted.
- Returns:
Expectation value expressed in
tounit.- Return type:
float
- Raises:
TypeError – If
tounitis not a string orobjdoes not expose a SCUQ unit.ValueError – If no outbound mapping exists for the quantity unit or target unit.
- classmethod get(unit)
Return the registered SCUQ unit and input converter.
- Parameters:
unit (str) – Input unit name, matched case-insensitively.
- Returns:
Canonical SCUQ unit and numeric converter.
- Return type:
tuple of (scuq.units.Unit, callable)
- Raises:
TypeError – If
unitis not a string.ValueError – If no input conversion is registered for
unit.
- classmethod logarithmic_error_bounds(unit, linear_value, error_db)
Return linear bounds for
linear_value +/- error_db.error_dbis interpreted as a difference on the logarithmic input scale, not as an absolute logarithmic level.- Parameters:
unit (str) – Registered logarithmic input unit determining factor 10 or 20.
linear_value (float) – Nominal value after conversion to the corresponding linear unit.
error_db (float) – Non-negative absolute error on the logarithmic input scale.
- Returns:
Lower and upper linear bounds.
- Return type:
tuple of (float, float)
- Raises:
TypeError – If
unitis not a string or an argument cannot participate in the numeric calculation.ValueError – If
unitis not logarithmic,error_dbis negative, or the resulting scale is not finite.
- classmethod logarithmic_input_factor(unit)
Return the dB factor for a logarithmic input unit, else
None.Power-like logarithmic units use factor 10 and amplitude-like units use factor 20. The factor is independent of the unit’s reference value and can therefore be used to apply a dB difference to an already converted linear value.
- Parameters:
unit (str) – Logarithmic input unit name.
- Returns:
Factor 10 or 20, or
Nonefor a non-logarithmic or unknown input unit.- Return type:
float or None
- Raises:
TypeError – If
unitis not a string.
- logarithmic_input_factors = {'db': 10.0, 'db((a/m)/v)': 20.0, 'db((v/m)/v)': 20.0, 'db/m': 20.0, 'db1/m': 20.0, 'dba/m': 20.0, 'dbd': 10.0, 'dbi': 10.0, 'dbm': 10.0, 'dbs/m': 20.0, 'dbuv': 20.0, 'dbuv/m': 20.0, 'dbv/m': 20.0, 'dbw/m2': 20.0, 'dbµv/m': 20.0, 'dbμv/m': 20.0}
- classmethod normalize_unit(unit)
Normalize a unit name to its registry key.
- Parameters:
unit (str) – Unit name, with arbitrary surrounding whitespace and letter case.
- Returns:
Stripped, lowercase unit key.
- Return type:
str
- Raises:
TypeError – If
unitis not a string.
- classmethod to_quantity(fromunit, value)
Create a SCUQ quantity from a unit string and value.
- Parameters:
fromunit (str) – Unit of
value.value (scalar or array-like) – Numeric input accepted by the registered converter.
- Returns:
Quantity in the canonical SCUQ unit.
- Return type:
scuq.quantities.Quantity
- Raises:
TypeError – If the unit name or numeric input type is unsupported.
ValueError – If
fromunitis unknown.
- uconv = {'(a/m)/v': (<scuq.units.AlternateUnit object>, <function _ident>), '(v/m)/v': (<scuq.units.AlternateUnit object>, <function _ident>), '1': (<scuq.units.ProductUnit object>, <function _ident>), '1/m': (<scuq.units.ProductUnit object>, <function _ident>), 'a/m': (<scuq.units.ProductUnit object>, <function _ident>), 'amplituderatio': (<scuq.units.AlternateUnit object>, <function _ident>), 'cm': (<scuq.units.BaseUnit object>, <function _mulfac.<locals>.new_m>), 'db': (<scuq.units.AlternateUnit object>, <function _from_dBfac.<locals>.lin>), 'db((a/m)/v)': (<scuq.units.AlternateUnit object>, <function _from_dBfac.<locals>.lin>), 'db((v/m)/v)': (<scuq.units.AlternateUnit object>, <function _from_dBfac.<locals>.lin>), 'db/m': (<scuq.units.AlternateUnit object>, <function _from_dBfac.<locals>.lin>), 'db1/m': (<scuq.units.ProductUnit object>, <function _from_dBfac.<locals>.lin>), 'dba/m': (<scuq.units.ProductUnit object>, <function _from_dBfac.<locals>.lin>), 'dbd': (<scuq.units.AlternateUnit object>, <function _mulfac.<locals>.new_m>), 'dbi': (<scuq.units.AlternateUnit object>, <function _from_dBfac.<locals>.lin>), 'dbm': (<scuq.units.AlternateUnit object>, <function _mulfac.<locals>.new_m>), 'dbs/m': (<scuq.units.ProductUnit object>, <function _from_dBfac.<locals>.lin>), 'dbuv': (<scuq.units.AlternateUnit object>, <function _mulfac.<locals>.new_m>), 'dbuv/m': (<scuq.units.ProductUnit object>, <function _mulfac.<locals>.new_m>), 'dbv/m': (<scuq.units.ProductUnit object>, <function _from_dBfac.<locals>.lin>), 'dbw/m2': (<scuq.units.ProductUnit object>, <function _from_dBfac.<locals>.lin>), 'dbµv/m': (<scuq.units.ProductUnit object>, <function _mulfac.<locals>.new_m>), 'dbμv/m': (<scuq.units.ProductUnit object>, <function _mulfac.<locals>.new_m>), 'deg': (<scuq.units.AlternateUnit object>, <function _mulfac.<locals>.new_m>), 'dimensionless': (<scuq.units.ProductUnit object>, <function _ident>), 'f': (<scuq.units.AlternateUnit object>, <function _ident>), 'ghz': (<scuq.units.AlternateUnit object>, <function _mulfac.<locals>.new_m>), 'h': (<scuq.units.AlternateUnit object>, <function _ident>), 'hz': (<scuq.units.AlternateUnit object>, <function _ident>), 'khz': (<scuq.units.AlternateUnit object>, <function _mulfac.<locals>.new_m>), 'm': (<scuq.units.BaseUnit object>, <function _ident>), 'mhz': (<scuq.units.AlternateUnit object>, <function _mulfac.<locals>.new_m>), 'mm': (<scuq.units.BaseUnit object>, <function _mulfac.<locals>.new_m>), 'powerratio': (<scuq.units.AlternateUnit object>, <function _ident>), 'rad': (<scuq.units.AlternateUnit object>, <function _ident>), 's/m': (<scuq.units.ProductUnit object>, <function _ident>), 'steps': (<scuq.units.ProductUnit object>, <function _ident>), 'v': (<scuq.units.AlternateUnit object>, <function _ident>), 'v/m': (<scuq.units.ProductUnit object>, <function _ident>), 'w': (<scuq.units.AlternateUnit object>, <function _ident>), 'w/m2': (<scuq.units.ProductUnit object>, <function _ident>)}
- uconv_from_quantity = {'(A/m)/V': {'(a/m)/v': <function _ident>, 'db((a/m)/v)': <function _to_dBfac.<locals>.db>}, '(V/V)': {'amplituderatio': <function _ident>}, '(V/m)/V': {'(v/m)/v': <function _ident>, 'db((v/m)/v)': <function _to_dBfac.<locals>.db>, 'db/m': <function _to_dBfac.<locals>.db>}, '(W/W)': {'db': <function _to_dBfac.<locals>.db>, 'dbd': <function _addsum.<locals>.new_m>, 'dbi': <function _to_dBfac.<locals>.db>, 'powerratio': <function _ident>, 'powerration': <function _ident>}, '1': {'1': <function _ident>, 'dimensionless': <function _ident>, 'steps': <function _ident>}, 'A*m^(-1)': {'a/m': <function _ident>, 'dba/m': <function _to_dBfac.<locals>.db>}, 'A*m^(-1)*V^(-1)': {'a/m': <function _ident>, 'dbs/m': <function _to_dBfac.<locals>.db>, 's/m': <function _ident>}, 'F': {'f': <function _ident>}, 'H': {'h': <function _ident>}, 'Hz': {'ghz': <function _mulfac.<locals>.new_m>, 'hz': <function _ident>, 'khz': <function _mulfac.<locals>.new_m>, 'mhz': <function _mulfac.<locals>.new_m>}, 'V': {'dbuv': <function _addsum.<locals>.new_m>, 'v': <function _ident>}, 'V*m^(-1)': {'dbuv/m': <function _addsum.<locals>.new_m>, 'dbv/m': <function _to_dBfac.<locals>.db>, 'v/m': <function _ident>}, 'V/m': {'dbuv/m': <function _addsum.<locals>.new_m>, 'dbv/m': <function _to_dBfac.<locals>.db>, 'v/m': <function _ident>}, 'W': {'dbm': <function _addsum.<locals>.new_m>, 'w': <function _ident>}, 'W*m^(-2)': {'dbw/m2': <function _to_dBfac.<locals>.db>, 'w/m2': <function _ident>}, 'm': {'cm': <function _mulfac.<locals>.new_m>, 'm': <function _ident>, 'mm': <function _mulfac.<locals>.new_m>}, 'm^(-1)': {'1/m': <function _ident>, 'db1/m': <function _to_dBfac.<locals>.db>}, 'rad': {'deg': <function _mulfac.<locals>.new_m>, 'rad': <function _ident>}}
- classmethod unit_exists(unit)
Return whether an input unit is registered.
- Parameters:
unit (str) – Unit name to test case-insensitively.
- Returns:
Truewhen an input converter is registered.- Return type:
bool
- Raises:
TypeError – If
unitis not a string.
- mpylab.tools.uconv.V2dBuV(inp)
- mpylab.tools.uconv.V_per_m_to_dBuV_per_m(inp)
- mpylab.tools.uconv.W2dBm(inp)
- mpylab.tools.uconv.amplitude_ratio_to_dB(inp)
- mpylab.tools.uconv.dB2lin(dBfac=None, sifac=None)
Create a converter from dB input to linear output.
- Parameters:
dBfac (float, optional) – Logarithmic factor. Use 10 for power quantities and 20 for amplitude quantities. The default is 10.
sifac (float, optional) – Linear scaling applied after exponentiation. For example,
1e-3converts the milliwatt reference of dBm to watts. The default is 1.
- Returns:
Converter accepting a real scalar, sequence, or NumPy array. Scalar input returns a Python or NumPy scalar; non-scalar input returns an array.
- Return type:
callable
- Raises:
TypeError – Raised by the returned converter for complex input.
Examples
dBm2W = dB2lin(10, 1e-3)creates a dBm-to-watt converter.
- mpylab.tools.uconv.dB_to_amplitude_ratio(inp)
- mpylab.tools.uconv.dB_to_power_ratio(inp)
- mpylab.tools.uconv.dBm2W(inp)
- mpylab.tools.uconv.dBm2mW(inp)
- mpylab.tools.uconv.dBm_to_dBuV(dbm, z0=50.0)
Convert an RF level from dBm to dBuV.
- Parameters:
dbm (float or array-like) – Power level in dBm.
z0 (float or scuq.quantities.Quantity, optional) – Positive resistive reference impedance. Numeric input is interpreted in ohms; a quantity must have an electrical-resistance dimension. The default is 50 ohms. For a quantity, its expectation value is used.
- Returns:
Corresponding RMS voltage level in dBuV.
- Return type:
float or numpy.ndarray
- Raises:
TypeError – If
z0is neither a real number nor an impedance quantity.ValueError – If
z0has the wrong dimension or is not positive and finite.
- mpylab.tools.uconv.dBuV2V(inp)
- mpylab.tools.uconv.dBuV2uV(inp)
- mpylab.tools.uconv.dBuV_per_m_to_V_per_m(inp)
- mpylab.tools.uconv.dBuV_to_dBm(dbuv, z0=50.0)
Convert an RF level from dBuV to dBm.
- Parameters:
dbuv (float or array-like) – RMS voltage level in dBuV.
z0 (float or scuq.quantities.Quantity, optional) – Positive resistive reference impedance. Numeric input is interpreted in ohms; a quantity must have an electrical-resistance dimension. The default is 50 ohms. For a quantity, its expectation value is used.
- Returns:
Corresponding power level in dBm.
- Return type:
float or numpy.ndarray
- Raises:
TypeError – If
z0is neither a real number nor an impedance quantity.ValueError – If
z0has the wrong dimension or is not positive and finite.
- mpylab.tools.uconv.from_quantity(tounit, obj)
Convert a SCUQ quantity through
UConv.from_quantity().- Parameters:
tounit (str) – Requested output unit.
obj (scuq.quantities.Quantity) – Quantity whose expectation value is converted.
- Returns:
Expectation value expressed in
tounit.- Return type:
float
- mpylab.tools.uconv.lin2dB(dBfac=None, sifac=None)
Create a converter from linear input to dB output.
- Parameters:
dBfac (float, optional) – Logarithmic factor. Use 10 for power quantities and 20 for amplitude quantities. The default is 10.
sifac (float, optional) – Linear scaling applied before the logarithm. For example,
1e3converts watts to the milliwatt reference used by dBm. The default is 1.
- Returns:
Converter accepting a real scalar, sequence, or NumPy array. Scalar input returns a Python or NumPy scalar; non-scalar input returns an array.
- Return type:
callable
- Raises:
TypeError – Raised by the returned converter for complex input.
Examples
W2dBm = lin2dB(10, 1e3)creates a watt-to-dBm converter.
- mpylab.tools.uconv.mW2dBm(inp)
- mpylab.tools.uconv.power_from_voltage(voltage_v, z0=50.0)
Convert RMS voltage to RF power for a resistive impedance.
- Parameters:
voltage_v (float or array-like) – RMS voltage in volts.
z0 (float or scuq.quantities.Quantity, optional) – Positive resistive reference impedance. Numeric input is interpreted in ohms; a quantity must have an electrical-resistance dimension. The default is 50 ohms. For a quantity, its expectation value is used.
- Returns:
RF power in watts.
- Return type:
float or numpy.ndarray
- Raises:
TypeError – If
z0is neither a real number nor an impedance quantity.ValueError – If
z0has the wrong dimension or is not positive and finite.
- mpylab.tools.uconv.power_ratio_to_dB(inp)
- mpylab.tools.uconv.quantity_to_dBm(quantity, context=None)
Convert a power quantity in watts to dBm.
- Parameters:
quantity (scuq.quantities.Quantity) – Power expressed in watts. The function does not perform a unit reduction before applying the 1 mW reference.
context (scuq.ucomponents.Context or scuq.cucomponents.Context, optional) – Context used to evaluate expectation value and uncertainty.
- Returns:
Nominal level in dBm with asymmetric uncertainty.
- Return type:
- Raises:
TypeError – If the evaluated quantity is genuinely complex.
ValueError – If the expectation value is not positive.
- mpylab.tools.uconv.quantity_to_db(quantity, reference=1.0, factor=10.0, unit='dB', context=None)
Convert a positive linear Quantity to a dB value with asymmetric uncertainty.
- Parameters:
quantity (scuq.quantities.Quantity) – Linear scuq quantity to convert. The expectation value and combined standard uncertainty are evaluated through the matching real or complex SCUQ context.
reference (float, optional) – Linear reference value for 0 dB. Use 1e-3 for dBm from watts.
factor (float, optional) – Logarithmic factor. Use 10 for power quantities and 20 for amplitudes.
unit (str, optional) – Label stored in the returned
AsymmetricDBValue.context (scuq.ucomponents.Context or scuq.cucomponents.Context, optional) – Optional scuq uncertainty context. If omitted, a fresh context is used.
- Returns:
Nominal dB value plus upper/lower dB standard uncertainties.
- Return type:
- Raises:
TypeError – If the evaluated quantity is genuinely complex. Apply a magnitude operation before logarithmic conversion.
ValueError – If
referenceorfactoris not positive, or if the quantity’s expectation value is not positive.
Notes
If the lower linear uncertainty bound is zero or negative, the returned lower bound is marked as clipped and represented by
LOWEST_DB.
- mpylab.tools.uconv.scuq_value_unit_to_unit(tounit, value, unit)
Convert a SCUQ value/unit pair to a registered output unit.
- Parameters:
tounit (str) – Requested output unit.
value (scalar) – Numeric value expressed in
unit.unit (scuq.units.Unit) – SCUQ unit associated with
value.
- Returns:
Converted numeric value.
- Return type:
float
- mpylab.tools.uconv.sparam_complex_to_db_phase_deg(value)
Convert complex S-parameters to magnitude in dB and phase in degrees.
- Parameters:
value (complex or array-like of complex) – Complex S-parameter value or values.
- Returns:
magnitude_db (float or numpy.ndarray) – Magnitude calculated as
20 * log10(abs(value)).phase_deg (float or numpy.ndarray) – Phase in degrees in the range
[-180, 180].
Notes
Scalar input returns two scalars; sequence or array input returns two NumPy arrays. A zero magnitude maps to
-infdB and phase0.
- mpylab.tools.uconv.sparam_complex_to_db_phase_rad(value)
Convert complex S-parameters to magnitude in dB and phase in radians.
- Parameters:
value (complex or array-like of complex) – Complex S-parameter value or values.
- Returns:
magnitude_db (float or numpy.ndarray) – Magnitude calculated as
20 * log10(abs(value)).phase_rad (float or numpy.ndarray) – Phase in radians in the range
[-pi, pi].
Notes
Scalar input returns two scalars; sequence or array input returns two NumPy arrays. A zero magnitude maps to
-infdB and phase0.
- mpylab.tools.uconv.sparam_db_phase_deg_to_complex(magnitude_db, phase_deg)
Convert S-parameter magnitude in dB and phase in degrees to complex form.
- Parameters:
magnitude_db (float or array-like of float) – S-parameter magnitude in decibels using factor 20.
phase_deg (float or array-like of float) – Phase in degrees. Inputs are broadcast against
magnitude_db.
- Returns:
Complex S-parameter value or broadcast array of values.
- Return type:
complex or numpy.ndarray
Notes
Scalar input returns a scalar; sequence or array input returns a NumPy array.
-infdB maps to0+0j.
- mpylab.tools.uconv.sparam_db_phase_rad_to_complex(magnitude_db, phase_rad)
Convert S-parameter magnitude in dB and phase in radians to complex form.
- Parameters:
magnitude_db (float or array-like of float) – S-parameter magnitude in decibels using factor 20.
phase_rad (float or array-like of float) – Phase in radians. Inputs are broadcast against
magnitude_db.
- Returns:
Complex S-parameter value or broadcast array of values.
- Return type:
complex or numpy.ndarray
Notes
The inverse calculation uses
abs(value) = 10 ** (magnitude_db / 20)andvalue = abs(value) * exp(1j * phase_rad). Scalar input returns a scalar; sequence or array input returns a NumPy array.-infdB maps to0+0j.
- mpylab.tools.uconv.to_quantity(fromunit, value)
Create a SCUQ quantity through
UConv.to_quantity().- Parameters:
fromunit (str) – Unit of
value.value (scalar or array-like) – Numeric input accepted by the registered converter.
- Returns:
Quantity in the canonical SCUQ unit.
- Return type:
scuq.quantities.Quantity
- mpylab.tools.uconv.to_scuq_value_unit(fromunit, value)
Return converted (value, unit) for driver code.
This helper returns the converted value first and the scuq unit second, matching the order expected by existing driver code.
- Parameters:
fromunit (str) – Unit of
value.value (scalar or array-like) – Numeric input accepted by the registered converter.
- Returns:
Converted value followed by its canonical SCUQ unit. This order is intentionally opposite to
UConv.convert().- Return type:
tuple of (object, scuq.units.Unit)
- mpylab.tools.uconv.uV2dBuV(inp)
- mpylab.tools.uconv.value_from_unit_to_unit(fromunit, tounit, value)
Convert a numeric value between two registered unit strings.
- Parameters:
fromunit (str) – Unit of
value.tounit (str) – Requested output unit.
value (scalar) – Numeric input value.
- Returns:
Converted numeric value.
- Return type:
float
- mpylab.tools.uconv.voltage_from_power(power_w, z0=50.0)
Convert RF power to RMS voltage for a resistive impedance.
- Parameters:
power_w (float or array-like) – RF power in watts.
z0 (float or scuq.quantities.Quantity, optional) – Positive resistive reference impedance. Numeric input is interpreted in ohms; a quantity must have an electrical-resistance dimension. The default is 50 ohms. For a quantity, its expectation value is used.
- Returns:
RMS voltage in volts.
- Return type:
float or numpy.ndarray
- Raises:
TypeError – If
z0is neither a real number nor an impedance quantity.ValueError – If
z0has the wrong dimension or is not positive and finite.