otaf.common package

Module contents

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]
otaf.common.bidirectional_string_to_array_conversion(x)[source]
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, optionally scaled by a multiplier.

Parameters:
  • se3_indices (List[Union[str, int]]) – List of indices representing SE(3) base matrices.

  • multiplier (Union[float, 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[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 the execution environment.

Returns:

trange_notebook if running in a Jupyter notebook, otherwise trange.

Return type:

function

Notes

  • This function checks the execution environment using is_running_in_notebook.

  • trange_notebook is used for better rendering in notebook environments.

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 the code is 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 get_ipython() function, which is available only in 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. The function also handles specific rules and patterns associated with each type.

Parameters:

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

Returns:

A dictionary containing the parsed components of the matrix. The keys depend on the type of matrix but typically include: - ‘type’: The matrix type (‘T’, ‘D’, or ‘G’). - ‘part’, ‘surface1’, ‘point1’, ‘surface2’, ‘point2’: Components specific to

Transformation or Gap matrices.

  • ’inverse’: Boolean indicating if the matrix is an inverse (for Deviation and Gap types).

  • ’mstring’: The reconstructed matrix string based on parsed components.

Return type:

Dict[str, Union[str, bool]]

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.round_floats_in_expression(ex, rnd=6)[source]

Round floating-point numbers in a SymPy expression to a specified number of decimal places.

Parameters:
  • ex (sympy.Expr) – SymPy expression containing floating-point numbers to be rounded.

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

Returns:

A new SymPy expression with all floating-point numbers rounded to the specified decimal places.

Return type:

sympy.Expr

otaf.common.threshold_for_percentile_positive_values_below(arr, percentile)[source]

Compute the threshold value such that the given percentage of positive values in the input array are below this threshold.

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.validate_dict_keys(dictionary, keys, dictionary_name, value_checks=None)[source]

Validate the presence of specific keys in a dictionary and optionally check their values.

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

  • keys (List[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 are the dictionary keys to validate and values are functions that take the dictionary’s value as input and return a boolean indicating whether the value is valid. If None, value validation is skipped (default is None).

Raises:
  • otaf.exceptions.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

  • value_checks is an optional mechanism to enforce additional constraints on dictionary values.

  • This function is designed for use cases where strict key and value validation is required.