flixopt.io ¶
Classes¶
CalculationResultsPaths dataclass ¶
Functions¶
remove_none_and_empty ¶
Recursively removes None and empty dicts and lists values from a dictionary or list.
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 and convert it to python native types.
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:
load_json ¶
Load data from a JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | Path | Path to the JSON file. | required |
Returns:
| Type | Description |
|---|---|
dict | list | Loaded data (typically dict or list). |
Raises:
| Type | Description |
|---|---|
FileNotFoundError | If the file does not exist. |
JSONDecodeError | If the file is not valid JSON. |
save_json ¶
save_json(data: dict | list, path: str | Path, indent: int = 4, ensure_ascii: bool = False, **kwargs) -> None
Save data to a JSON file with consistent formatting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | dict | list | Data to save (dict or list). | required |
path | str | Path | Path to save the JSON file. | required |
indent | int | Number of spaces for indentation (default: 4). | 4 |
ensure_ascii | bool | If False, allow Unicode characters (default: False). | False |
**kwargs | Additional arguments to pass to json.dump(). | {} |
load_yaml ¶
Load data from a YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | Path | Path to the YAML file. | required |
Returns:
| Type | Description |
|---|---|
dict | list | Loaded data (typically dict or list), or empty dict if file is empty. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError | If the file does not exist. |
YAMLError | If the file is not valid YAML. |
Note | Returns {} for empty YAML files instead of None. |
save_yaml ¶
save_yaml(data: dict | list, path: str | Path, indent: int = 4, width: int = 1000, allow_unicode: bool = True, sort_keys: bool = False, compact_numeric_lists: bool = False, **kwargs) -> None
Save data to a YAML file with consistent formatting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | dict | list | Data to save (dict or list). | required |
path | str | Path | Path to save the YAML file. | required |
indent | int | Number of spaces for indentation (default: 4). | 4 |
width | int | Maximum line width (default: 1000). | 1000 |
allow_unicode | bool | If True, allow Unicode characters (default: True). | True |
sort_keys | bool | If True, sort dictionary keys (default: False). | False |
compact_numeric_lists | bool | If True, format numeric lists inline for better readability (default: False). | False |
**kwargs | Additional arguments to pass to yaml.dump(). | {} |
format_yaml_string ¶
format_yaml_string(data: dict | list, indent: int = 4, width: int = 1000, allow_unicode: bool = True, sort_keys: bool = False, compact_numeric_lists: bool = False, **kwargs) -> str
Format data as a YAML string with consistent formatting.
This function provides the same formatting as save_yaml() but returns a string instead of writing to a file. Useful for logging or displaying YAML data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | dict | list | Data to format (dict or list). | required |
indent | int | Number of spaces for indentation (default: 4). | 4 |
width | int | Maximum line width (default: 1000). | 1000 |
allow_unicode | bool | If True, allow Unicode characters (default: True). | True |
sort_keys | bool | If True, sort dictionary keys (default: False). | False |
compact_numeric_lists | bool | If True, format numeric lists inline for better readability (default: False). | False |
**kwargs | Additional arguments to pass to yaml.dump(). | {} |
Returns:
| Type | Description |
|---|---|
str | Formatted YAML string. |
load_config_file ¶
Load a configuration file, automatically detecting JSON or YAML format.
This function intelligently tries to load the file based on its extension, with fallback support if the primary format fails.
Supported extensions: - .json: Tries JSON first, falls back to YAML - .yaml, .yml: Tries YAML first, falls back to JSON - Others: Tries YAML, then JSON
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | Path | Path to the configuration file. | required |
Returns:
| Type | Description |
|---|---|
dict | Loaded configuration as a dictionary. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError | If the file does not exist. |
ValueError | If neither JSON nor YAML parsing succeeds. |
document_linopy_model ¶
Convert all model variables and constraints to a structured string representation. This can take multiple seconds for large models. The output can be saved to a yaml file with readable formating applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | Path | Path to save the document. Defaults to None. | None |
save_dataset_to_netcdf ¶
Save a dataset to a netcdf file. Store all attrs as JSON strings in 'attrs' attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds | Dataset | Dataset to save. | required |
path | str | Path | Path to save the dataset to. | required |
compression | int | Compression level for the dataset (0-9). 0 means no compression. 5 is a good default. | 0 |
Raises:
| Type | Description |
|---|---|
ValueError | If the path has an invalid file extension. |
load_dataset_from_netcdf ¶
numeric_to_str_for_repr ¶
numeric_to_str_for_repr(value: int | float | integer | floating | ndarray | Series | DataFrame | DataArray, precision: int = 1, atol: float = 1e-10) -> str
Format value for display in repr methods.
For single values or uniform arrays, returns the formatted value. For arrays with variation, returns a range showing min-max.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value | int | float | integer | floating | ndarray | Series | DataFrame | DataArray | Numeric value or container (DataArray, array, Series, DataFrame) | required |
precision | int | Number of decimal places (default: 1) | 1 |
atol | float | Absolute tolerance for considering values equal (default: 1e-10) | 1e-10 |
Returns:
| Type | Description |
|---|---|
str | Formatted string representation: |
str |
|
str |
|
str |
|
Raises:
| Type | Description |
|---|---|
TypeError | If value cannot be converted to numeric format |
build_repr_from_init ¶
build_repr_from_init(obj: object, excluded_params: set[str] | None = None, label_as_positional: bool = True, skip_default_size: bool = False) -> str
Build a repr string from init signature, showing non-default parameter values.
This utility function extracts common repr logic used across flixopt classes. It introspects the init method to build a constructor-style repr showing only parameters that differ from their defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj | object | The object to create repr for | required |
excluded_params | set[str] | None | Set of parameter names to exclude (e.g., {'self', 'inputs', 'outputs'}) Default excludes 'self', 'label', and 'kwargs' | None |
label_as_positional | bool | If True and 'label' param exists, show it as first positional arg | True |
skip_default_size | bool | If True, skip 'size' parameter when it equals CONFIG.Modeling.big | False |
Returns:
| Type | Description |
|---|---|
str | Formatted repr string like: ClassName("label", param=value) |
format_flow_details ¶
Format inputs and outputs as indented bullet list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj | Object with 'inputs' and/or 'outputs' attributes | required | |
has_inputs | bool | Whether to check for inputs | True |
has_outputs | bool | Whether to check for outputs | True |
Returns:
| Type | Description |
|---|---|
str | Formatted string with flow details (including leading newline), or empty string if no flows |
format_title_with_underline ¶
format_sections_with_headers ¶
build_metadata_info ¶
suppress_output ¶
Suppress all console output including C-level output from solvers.
WARNING: Not thread-safe. Modifies global file descriptors. Use only with sequential execution or multiprocessing.