Skip to content

flixopt.utils

This module contains several utility functions used throughout the flixopt framework.

Functions

round_nested_floats

round_nested_floats(obj: dict | list | float | int | Any, decimals: int = 2) -> dict | list | float | int | Any

Recursively round floating point numbers in nested data structures.

This function traverses nested data structures (dictionaries, lists) and rounds any floating point numbers to the specified number of decimal places. It handles various data types including NumPy arrays and xarray DataArrays by converting them to lists with rounded values.

Parameters:

Name Type Description Default
obj dict | list | float | int | Any

The object to process. Can be a dict, list, float, int, numpy.ndarray, xarray.DataArray, or any other type.

required
decimals int

Number of decimal places to round to. Defaults to 2.

2

Returns:

Type Description
dict | list | float | int | Any

The processed object with the same structure as the input, but with all floating point numbers rounded to the specified precision. NumPy arrays and xarray DataArrays are converted to lists.

Examples:

>>> data = {'a': 3.14159, 'b': [1.234, 2.678]}
>>> round_nested_floats(data, decimals=2)
{'a': 3.14, 'b': [1.23, 2.68]}
>>> import numpy as np
>>> arr = np.array([1.234, 5.678])
>>> round_nested_floats(arr, decimals=1)
[1.2, 5.7]

convert_dataarray

convert_dataarray(data: DataArray, mode: Literal['py', 'numpy', 'xarray', 'structure']) -> list | np.ndarray | xr.DataArray | str

Convert a DataArray to a different format.

Parameters:

Name Type Description Default
data DataArray

The DataArray to convert.

required
mode Literal['py', 'numpy', 'xarray', 'structure']

The mode to convert to. - 'py': Convert to python native types (for json) - 'numpy': Convert to numpy array - 'xarray': Convert to xarray.DataArray - 'structure': Convert to strings (for structure, storing variable names)

required

Returns:

Type Description
list | ndarray | DataArray | str

The converted data.

Raises:

Type Description
ValueError

If the mode is unknown.