Common utilities¶
The tool-module migration guide maps
imports from the historical mpylab.tools.util facade to the focused
modules used by new applications. The complete generated reference contains utilities that are intentionally omitted from this
curated selection.
Unit conversion¶
mpylab.tools.uconv is the canonical conversion backend. Keep SCUQ
quantities in measurement and evaluation code; convert at protocol and
presentation boundaries.
- class mpylab.tools.uconv.UConv¶
Central 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.
- 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.
- 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.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.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.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.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.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.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.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.
- 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)¶
Nominal 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)
- lower_value()¶
Return the absolute lower logarithmic bound.
- Returns:
value - minusor the configured clipped lower value.- Return type:
float
- upper_value()¶
Return the absolute upper logarithmic bound.
- Returns:
value + plus.- Return type:
float
S-parameter representation¶
The phase unit is explicit in each function name.
- 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_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_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.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.
Generated file names¶
- mpylab.tools.filenames.filename_token(value: Any, max_length: int = 64, default: str = 'item') str¶
Return a filesystem-safe token for use inside generated filenames.
The returned token is derived from value, lower-cased, ASCII-normalized, stripped of path separators and other unsafe characters, and limited to max_length characters. If sanitizing or truncating changes the original text, a short stable hash is appended to reduce accidental collisions while keeping the human-readable prefix.
- mpylab.tools.filenames.format_output_filename(pattern: str, *args: Any, max_token_length: int = 64) str¶
Format pattern with filename-safe versions of args.
Only the substitution arguments are sanitized. Directory components already present in pattern are preserved, so patterns such as
"output/out_raw_%s.dat"keep their target directory unchanged.
Script configuration¶
- class mpylab.env.script_cli.ConfigError¶
Raised when a command-line configuration cannot be loaded.
- mpylab.env.script_cli.update_conf(cdict, argv=None, script_name=None)¶
Update a configuration from defaults and ordered overrides.
Configuration arguments are applied from left to right. Nested dictionaries from
cdictare merged recursively; all other values are replaced. A configuration module may additionally or alternatively defineupdate_config(config)for targeted in-place updates. The hook runs after the module’scdictand must returnNone.This compatibility entry point intentionally returns
None. Useresolve_config_chain()when source provenance is required.- Parameters:
cdict (dict) – Configuration mapping to update in place.
argv (sequence of str or None, optional) – Command-line arguments.
Noneusessys.argv.script_name (str or None, optional) – Program name shown in command-line help.
- Raises:
ConfigError – If a configuration source or its update hook is invalid.
- mpylab.env.script_cli.resolve_autosave_resume(measurement, command, expected_measurement, expected_method)¶
Validate autosave restart metadata and return its description.
Structured
autosave_resumemetadata is preferred. Older pickles remain usable whenautosave_infoidentifies the measurement orascmdcalls the expected public measurement method.- Parameters:
measurement (object) – Restored measurement instance containing restart metadata.
command (str or None) – Legacy
ascmdrestart command.expected_measurement (str) – Expected measurement identifier.
expected_method (str) – Expected public measurement method name.
- Returns:
Measurement description stored in the autosave metadata.
- Return type:
str or None
- Raises:
ValueError – If restart metadata is inconsistent, unsupported, or does not match the expected measurement method.