Utility functions#

exception barotropy.utilities.DictionaryValidationError(message, key=None, value=None)[source]#

Bases: Exception

Exception raised for errors in the expected options.

barotropy.utilities.compare_contents_or_files(file_or_content_1, file_or_content_2)[source]#

Compare the content of two inputs, which can be either file paths or strings.

This function accepts two arguments. Each argument can be: 1. A file path pointing to a file containing text content. 2. A string containing text content directly.

If the argument is a file path that exists, the function reads its content. If the argument is a string, it’s directly used for comparison.

Parameters:
file_or_content1str

First input which can be a file path or string content.

file_or_content2str

Second input which can be a file path or string content.

Returns:
bool

True if the contents of the two inputs are identical, False otherwise.

Examples

>>> content_same("path/to/file1.txt", "path/to/file2.txt")
True
>>> content_same("Hello, world!", "path/to/file_with_hello_world_content.txt")
True
>>> content_same("Hello, world!", "Goodbye, world!")
False
barotropy.utilities.convert_configuration_options(config)[source]#

Processes configuration data by evaluating string expressions as numerical values and converting lists to numpy arrays.

This function iteratively goes through the configuration dictionary and converts string representations of numbers (e.g., “1+2”, “2*np.pi”) into actual numerical values using Python’s eval function. It also ensures that all numerical values are represented as Numpy types for consistency across the application.

Parameters:
configdict

The configuration data loaded from a YAML file, typically containing a mix of strings, numbers, and lists.

Returns:
dict

The postprocessed configuration data where string expressions are evaluated as numbers, and all numerical values are cast to corresponding NumPy types.

Raises:
ConfigurationError

If a list contains elements of different types after conversion, indicating an inconsistency in the expected data types.

barotropy.utilities.convert_numpy_to_python(data, precision=10)[source]#

Recursively converts numpy arrays, scalars, and other numpy types to their Python counterparts and rounds numerical values to the specified precision.

Parameters: - data: The numpy data to convert. - precision: The decimal precision to which float values should be rounded.

Returns: - The converted data with all numpy types replaced by native Python types and float values rounded.

barotropy.utilities.ensure_iterable(obj)[source]#

Ensure that an object is iterable. If the object is already an iterable (except for strings, which are not treated as iterables in this context), it will be returned as is. If the object is not an iterable, or if it is a string, it will be placed into a list to make it iterable.

Parameters:
objany type

The object to be checked and possibly converted into an iterable.

Returns:
Iterable

The original object if it is an iterable (and not a string), or a new list containing the object if it was not iterable or was a string.

Examples

>>> ensure_iterable([1, 2, 3])
[1, 2, 3]
>>> ensure_iterable('abc')
['abc']
>>> ensure_iterable(42)
[42]
>>> ensure_iterable(np.array([1, 2, 3]))
array([1, 2, 3])
barotropy.utilities.evaluate_constraints(data, constraints)[source]#

Evaluates the constraints based on the provided data and constraint definitions.

Parameters:
datadict

A dictionary containing performance data against which the constraints will be evaluated.

constraintslist of dicts

A list of constraint definitions, where each constraint is defined as a dictionary. Each dictionary must have ‘variable’ (str), ‘type’ (str, one of ‘=’, ‘>’, ‘<’), and ‘value’ (numeric).

Returns:
tuple of numpy.ndarray

Returns two numpy arrays: the first is an array of equality constraints, and the second is an array of inequality constraints. These arrays are flattened and concatenated from the evaluated constraint values.

Raises:
ValueError

If an unknown constraint type is specified in the constraints list.

barotropy.utilities.evaluate_objective_function(data, objective_function)[source]#

Evaluates the objective function based on the provided data and configuration.

Parameters:
datadict

A dictionary containing performance data against which the objective function will be evaluated.

objective_functiondict

A dictionary defining the objective function. It must have ‘variable’ (str) and ‘type’ (str, either ‘minimize’ or ‘maximize’).

Returns:
float

The value of the objective function, adjusted for optimization. Positive for minimization and negative for maximization.

Raises:
ValueError

If an unknown objective function type is specified in the configuration.

barotropy.utilities.is_float(element: any) bool[source]#

Check if the given element can be converted to a float.

Parameters:
elementany

The element to be checked.

Returns:
bool

True if the element can be converted to a float, False otherwise.

barotropy.utilities.is_numeric(value)[source]#

Check if a value is a numeric type, including both Python and NumPy numeric types.

This function checks if the given value is a numeric type (int, float, complex) in the Python standard library or NumPy, while explicitly excluding boolean types.

Parameters:
valueany type

The value to be checked for being a numeric type.

Returns:
bool

Returns True if the value is a numeric type (excluding booleans), otherwise False.

barotropy.utilities.postprocess_ode(t, y, ode_handle)[source]#

Post-processes the output of an ordinary differential equation (ODE) solver.

This function takes the time points and corresponding ODE solution matrix, and for each time point, it calls a user-defined ODE handling function to process the state of the ODE system. It collects the results into a dictionary where each key corresponds to a state variable and the values are numpy arrays of that state variable at each integration step

Parameters:
tarray_like

Integration points at which the ODE was solved, as a 1D numpy array.

yarray_like

The solution of the ODE system, as a 2D numpy array with shape (n,m) where n is the number of points and m is the number of state variables.

ode_handlecallable

A function that takes in a integration point and state vector and returns a tuple, where the first element is ignored (can be None) and the second element is a dictionary representing the processed state of the system.

Returns:
ode_outdict

A dictionary where each key corresponds to a state variable and each value is a numpy array containing the values of that state variable at each integration step.

barotropy.utilities.print_dict(data, indent=0)[source]#

Recursively prints nested dictionaries with indentation.

Parameters:
datadict

The dictionary to print. It can contain nested dictionaries as values.

indentint, optional

The initial level of indentation for the keys of the dictionary, by default 0. It controls the number of spaces before each key.

Returns:
None

Examples

>>> data = {"a": 1, "b": {"c": 2, "d": {"e": 3}}}
>>> print_dict(data)
a: 1
b:
    c: 2
    d:
        e: 3
barotropy.utilities.print_object(obj)[source]#

Prints all attributes and methods of an object, sorted alphabetically.

  • Methods are identified as callable and printed with the prefix ‘Method: ‘.

  • Attributes are identified as non-callable and printed with the prefix ‘Attribute: ‘.

Parameters:
objobject

The object whose attributes and methods are to be printed.

Returns:
None

This function does not return any value. It prints the attributes and methods of the given object.

barotropy.utilities.read_configuration_file(filename)[source]#

Reads and validates a YAML configuration file (return multiple outputs)

barotropy.utilities.render_and_evaluate(expression, data)[source]#

Render variables prefixed with ‘$’ in an expression and evaluate the resulting expression.

This function processes an input string expr, identifying all occurrences of variables indicated by a leading ‘$’ symbol. Each such variable is resolved to its value from the provided context dictionary. The expression with all variables resolved is then evaluated and the result is returned.

This function is useful to render strings defined in a YAML configuration file to values that are calculated within the code and stored in a dicitonary.

Parameters:
exprstr

The expression string containing variables to be rendered. Variables in the expression are expected to be prefixed with a ‘$’ symbol.

datadict

A dictionary containing variables and their corresponding values. These variables are used to render values in the expression.

Returns:
The result of evaluating the rendered expression. The type of the result depends on the
expression.

Notes

  • pattern: A regular expression pattern used to identify variables within the expression. Variables are expected to be in the format $variableName, potentially with dot-separated sub-properties (e.g., $variable.property).

  • replace_with_value: An inner function that takes a regex match object and returns the value of the variable from context. match.group(1) returns the first captured group from the matched text, which in this case is the variable name excluding the leading ‘$’ symbol. For example, in $variableName, match.group(1) would return variableName.

  • The function uses Python’s eval for evaluation, which should be used cautiously as it can execute arbitrary code. Ensure that the context and expressions are from a trusted source.

barotropy.utilities.render_nested_value(nested_key, data)[source]#

Retrieves a value from a nested structure (dictionaries or objects with attributes) using a dot-separated key.

This function is designed to navigate through a combination of dictionaries and objects. For an object to be compatible with this function, it must implement a keys() method that returns its attribute names.

This function is intended as a subroutine of the more genera render_expression

Parameters:
nested_keystr

A dot-separated key string that specifies the path in the structure. For example, ‘level1.level2.key’ will retrieve data[‘level1’][‘level2’][‘key’] if data is a dictionary, or data.level1.level2.key if data is an object or a combination of dictionaries and objects.

datadict or object

The starting dictionary or object from which to retrieve the value. This can be a nested structure of dictionaries and objects.

Returns:
value

The value retrieved from the nested structure using the specified key. The type of the value depends on what is stored at the specified key in the structure.

Raises:
KeyError

If the specified nested key is not found in the data structure. The error message includes the part of the path that was successfully traversed and the available keys or attributes at the last valid level.

barotropy.utilities.savefig_in_formats(fig, path_without_extension, formats=['.png', '.svg', '.eps'])[source]#

Save a given matplotlib figure in multiple file formats.

Parameters:
figmatplotlib.figure.Figure

The figure object to be saved.

path_without_extensionstr

The full path to save the figure excluding the file extension.

formatslist of str, optional

A list of string file extensions to specify which formats the figure should be saved in. Default is [‘.png’, ‘.svg’, ‘.pdf’].

Examples

>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> ax.plot([0, 1], [0, 1])
>>> save_fig_in_formats(fig, "/path/to/figure/filename")

This will save the figure as “filename.png”, “filename.svg”, and “filename.pdf” in the “/path/to/figure/” directory.

barotropy.utilities.validate_keys(checked_dict, required_keys, allowed_keys=None)[source]#

Validate the presence of required keys and check for any unexpected keys in a dictionary.

Give required keys and allowed keys to have complete control Give required keys twice to check that the list of keys is necessary and sufficient Give only required keys to allow all extra additional key

Parameters:
checked_dictdict

The dictionary to be checked.

required_keysset

A set of keys that are required in the dictionary.

allowed_keysset

A set of keys that are allowed in the dictionary.

Raises:
ConfigurationError

If either required keys are missing or unexpected keys are found.

barotropy.utilities.wait_for_file(file_path, timeout=None, poll_interval=0.1)[source]#

Wait until the specified file is created.

This function is used to wait until a Fluent transcript file is created.

Parameters:
file_pathstr

Path to the file to wait for.

timeoutfloat, optional

Maximum time to wait in seconds. If None, waits indefinitely.

poll_intervalint, optional

Time interval between checks in seconds.

Returns:
bool

True if the file was found, False otherwise (only if timeout is set).