otaf.common package

Module contents

Common utility functions and helpers for OTAF.

otaf.common.alphabet_generator()[source]

Generate infinite sequences of alphabetic strings, starting with single letters.

This generator produces all possible combinations of lowercase alphabetic characters (‘a’ to ‘z’), incrementing the sequence length after exhausting combinations of the current length.

Yields:

str – The next alphabetic string in the sequence.

Notes

  • The generator starts with single-letter combinations (‘a’, ‘b’, …, ‘z’) and continues with multi-letter combinations (e.g., ‘aa’, ‘ab’, …, ‘zz’, ‘aaa’, etc.).

  • It produces strings indefinitely, making it suitable for cases where infinite sequences are needed.

otaf.common.arrays_close_enough(arr1, arr2, tolerance=1e-06)[source]

Check if two arrays are element-wise equal within a tolerance.

Parameters:
  • arr1 (array_like) – The input arrays to compare.

  • arr2 (array_like) – The input arrays to compare.

  • tolerance (float, optional) – The absolute tolerance threshold for comparison. Default is 1e-06.

Returns:

True if the arrays are equal within the given tolerance, False otherwise.

Return type:

bool

Raises:

ValueError – If the input arrays do not have the same shape.

otaf.common.bidirectional_string_to_array_conversion(x)[source]

Convert input between a numeric array and its string representation.

Parameters:

x (str or array_like) – The input to transform. If a string is provided, it is parsed into a list of floats. Otherwise, it is formatted into a string.

Returns:

The converted representation.

Return type:

str or list of str

otaf.common.extract_expressions_with_variables(m)[source]

Extract matrix expressions containing free variables.

This function filters specific off-diagonal and last-column elements of a given symbolic matrix and returns only those expressions that contain free variables (i.e., symbols).

Parameters:

m (sympy.MatrixBase) – Sympy matrix from which expressions are to be extracted.

Returns:

A list of expressions from the matrix that contain free variables.

Return type:

List[sympy.Expr]

Notes

The indices for the filtered elements include: - Off-diagonal terms: (0, 1), (0, 2), (1, 2) - Last-column terms: (0, 3), (1, 3), (2, 3)

otaf.common.get_SE3_base(index)[source]

Retrieve the SE(3) base matrix corresponding to a given index.

Parameters:

index (str) – The index representing the SE(3) base matrix.

Returns:

The SE(3) base matrix associated with the given index.

Return type:

sympy.MatrixBase

Raises:

KeyError – If the specified index is not found in BASIS_DICT.

Notes

The SE(3) base matrix is retrieved from the predefined BASIS_DICT in the otaf.constants module.

otaf.common.get_SE3_matrices_from_indices(se3_indices, multiplier=1.0)[source]

Retrieve SE(3) matrices corresponding to a list of indices.

Parameters:
  • se3_indices (list of str or int) – List of indices representing SE(3) base matrices.

  • multiplier (float or int, optional) – A scalar multiplier applied to each matrix. Default is 1.0.

Returns:

A list of SE(3) base matrices, each scaled by the specified multiplier.

Return type:

list of sympy.MatrixBase

Notes

The indices are converted to strings and used to retrieve the corresponding SE(3) base matrices from the predefined BASIS_DICT in the otaf.constants module.

otaf.common.get_symbol_coef_map(expr, rnd=8)[source]

Extract coefficients of each variable in a first-order polynomial.

Parameters:
  • expr (sympy.Expr) – The polynomial expression to extract coefficients from.

  • rnd (int, optional) – Number of decimal places to round the coefficients to (default is 8).

Returns:

A dictionary mapping variable names (as strings) to their coefficients (as floats). Includes the constant term, represented by the key ‘CONST’.

Return type:

Dict[str, float]

Notes

  • The function assumes the input is a first-order polynomial.

  • If no constant term exists in the expression, ‘CONST’ is set to 0.0.

otaf.common.get_symbols_in_expressions(expr_list)[source]

Extract and sort unique symbols from a list of sympy expressions.

This function processes a list of sympy expressions, extracts the free symbols, and categorizes them into deviation symbols and gap symbols based on their naming patterns. The symbols in each category are sorted according to a predefined order.

Parameters:

expr_list (List[sp.Expr]) – A list of sympy expressions from which symbols will be extracted.

Returns:

  • The first list contains sorted deviation symbols (symbols with “_d_” in their names).

  • The second list contains sorted gap symbols (symbols with “_g_” in their names).

Return type:

Tuple[List[sp.Symbol], List[sp.Symbol]]

Raises:

ValueError – If a symbol’s name does not end with a number or cannot be categorized based on the predefined sort order.

Notes

  • Sorting prioritizes symbols with a specific prefix order (“u_”, “v_”, “w_”, “alpha_”, “beta_”, “gamma_”) followed by numerical suffixes.

  • The function assumes symbols are named consistently with the expected patterns.

Examples

>>> from sympy import symbols, Eq
>>> u_d_1, v_g_2, w_d_3 = symbols("u_d_1 v_g_2 w_d_3")
>>> expr_list = [u_d_1 + v_g_2, w_d_3]
>>> get_symbols_in_expressions(expr_list)
([u_d_1, w_d_3], [v_g_2])
otaf.common.get_tqdm_range()[source]

Retrieve the appropriate tqdm range function based on environment.

Returns:

trange_notebook if running in a Jupyter notebook, otherwise trange.

Return type:

callable

Notes

This function checks the execution environment using the utility is_running_in_notebook. The trange_notebook variant is selected for cleaner HTML progress bar rendering inside notebooks.

otaf.common.inverse_mstring(matrix_str)[source]

Generate the inverse of a matrix string representation.

This function processes a matrix string representation (either a Transformation matrix or a Gap matrix) and returns its inverse string representation. The inverse is computed by swapping certain elements in the input string based on predefined patterns.

Parameters:

matrix_str (str) – The string representation of the matrix. Must follow the expected format for either a Transformation matrix or a Gap matrix.

Returns:

The inverse string representation of the matrix. Returns an empty string if matrix_str is empty.

Return type:

str

Raises:

ValueError – If the matrix string does not match the expected format for a Transformation or Gap matrix, or if the matrix type is unsupported.

Examples

>>> inverse_mstring("TP123S1P456S2")
'TP123S2P456S1'
>>> inverse_mstring("GP1S1P1P2S2P2")
'GP2S2P2P1S1P1'
>>> inverse_mstring("")
''
otaf.common.is_running_in_notebook()[source]

Check if the current code is running in a Jupyter notebook environment.

This function detects the type of IPython shell to determine whether the code is executed in a Jupyter notebook, a terminal, or a standard Python interpreter.

Returns:

True if running in a Jupyter notebook or qtconsole, False otherwise.

Return type:

bool

Notes

If the IPython shell cannot be detected, it is assumed the code is running in a standard Python interpreter.

This function relies on the built-in get_ipython() function, which is available exclusively within IPython environments.

otaf.common.merge_with_checks(existing_points, new_points)[source]

Merge two dictionaries with value consistency checks.

This function merges new_points into existing_points. If a key in new_points already exists in existing_points, the function checks whether their corresponding values are numerically close. If not, a ValueError is raised. The existing_points dictionary is modified in place.

Parameters:
  • existing_points (dict) – The original dictionary of points to merge into. This dictionary is updated in place. Keys are typically strings, and values are numeric arrays or similar types.

  • new_points (dict) – The new points to merge. Keys should match those in existing_points if they overlap.

Returns:

The updated existing_points dictionary after merging.

Return type:

dict

Raises:

ValueError – If a key exists in both dictionaries and the corresponding values are not numerically close.

Examples

>>> existing_points = {'A': [1.0, 2.0], 'B': [3.0, 4.0]}
>>> new_points = {'B': [3.0, 4.0], 'C': [5.0, 6.0]}
>>> merge_with_checks(existing_points, new_points)
{'A': [1.0, 2.0], 'B': [3.0, 4.0], 'C': [5.0, 6.0]}
>>> new_points = {'B': [3.1, 4.1]}
>>> merge_with_checks(existing_points, new_points)
ValueError: Conflict for key B: existing value [3.0, 4.0], new value [3.1, 4.1]
otaf.common.parse_matrix_string(matrix_str)[source]

Parse a matrix string into its components.

This function processes a string representation of a matrix, identifying its type (Transformation, Deviation, or Gap) based on the first character. It extracts and returns the relevant components in a structured dictionary format.

Parameters:

matrix_str (str) – The string representation of the matrix to be parsed.

Returns:

A dictionary containing the parsed components of the matrix. Keys include type, part, surface1, point1, surface2, point2, inverse, and mstring.

Return type:

dict

Raises:

ValueError – If the matrix string does not conform to the expected pattern for its type or if an unsupported matrix type is encountered.

Examples

>>> parse_matrix_string('TP1kK0aA0')
{'type': 'T', 'part': '1', 'surface1': 'k', 'point1': 'K0',
 'surface2': 'a', 'point2': 'A0', 'mstring': 'TP1kK0aA0'}
>>> parse_matrix_string('D1k')
{'type': 'D', 'inverse': False, 'part': '1', 'surface': 'k',
 'point': 'K0', 'mstring': 'D1k'}
>>> parse_matrix_string('GP1kK0P2aA0')
{'type': 'G', 'inverse': False, 'part1': '1', 'surface1': 'k',
 'point1': 'K0', 'part2': '2', 'surface2': 'a', 'point2': 'A0',
 'mstring': 'GP1kK0P2aA0'}
otaf.common.scaling(scale_factor)[source]

A decorator factory that scales the output of a function by a constant factor.

This decorator safely handles scalar numeric types, nested iterables (lists, tuples, sets), and preserves the original iterable type where possible. It gracefully skips None, str, and bytes values without altering them or throwing errors.

Parameters:

scale_factor (float) – The numerical factor by which to multiply the output of the wrapped function.

Returns:

A decorator function capable of wrapping a target callable.

Return type:

callable

Examples

>>> @scaling(2.5)
... def get_prices():
...     return [10.0, None, 20.0]
>>> get_prices()
[25.0, None, 50.0]
otaf.common.threshold_for_percentile_positive_values_below(arr, percentile)[source]

Compute the threshold value for a given percentile of positive values.

This function extracts all positive values from the input array and calculates the threshold such that the specified percentage of these values fall below it.

Parameters:
  • arr (array-like) – Input array of floats. Must contain at least one positive value for meaningful output.

  • percentile (float) – The percentage (between 0 and 100) of positive values to consider.

Returns:

The threshold value such that the specified percentage of positive values are below it. Returns None if there are no positive values in the input array.

Return type:

float or None

Raises:

ValueError – If the percentile is not between 0 and 100, if the input array is empty, or if the input cannot be reduced to a one-dimensional array.

Notes

  • This function operates on the positive values in the input array, ignoring non-positive values.

  • The input array is squeezed to handle cases where the input is a higher-dimensional array that can be reduced to one dimension.

Examples

# Compute the 50th percentile threshold for positive values >>> threshold_for_percentile_positive_values_below([-1, 2, 3, 4, 5], 50) 3.0

# Handle arrays with no positive values >>> threshold_for_percentile_positive_values_below([-1, -2, -3], 50) None

otaf.common.tree()[source]

Create a recursive defaultdict that automatically creates nested dictionaries.

Returns:

A defaultdict that creates nested dictionaries on-the-fly.

Return type:

defaultdict

otaf.common.validate_dict_keys(dictionary, keys, dictionary_name, value_checks={})[source]

Validate presence of specific keys and optionally check their values.

Parameters:
  • dictionary (dict) – The dictionary to validate.

  • keys (list of str) – A list of keys that must be present in the dictionary.

  • dictionary_name (str) – The name of the dictionary used in error messages for clarity.

  • value_checks (dict, optional) – A dictionary where keys map to validation functions. Each function takes a value as input and returns a boolean indicating validity. Default is {}.

Raises:
  • MissingKeyError – If a required key is missing from the dictionary.

  • ValueError – If a value associated with a key fails the validation function provided in value_checks.

Return type:

None

Notes

The value_checks parameter acts as an optional mechanism to enforce additional constraints on nested dictionary values.