Skip to content

flixopt.io

Classes

CalculationResultsPaths dataclass

Python
CalculationResultsPaths(folder: Path, name: str)

Container for all paths related to saving CalculationResults.

Functions

all_paths
Python
all_paths() -> dict[str, pathlib.Path]

Return a dictionary of all paths.

create_folders
Python
create_folders(parents: bool = False) -> None

Ensure the folder exists. Args: parents: Whether to create the parent folders if they do not exist.

update
Python
update(new_name: str | None = None, new_folder: Path | None = None) -> None

Update name and/or folder and refresh all paths.

Functions

remove_none_and_empty

Python
remove_none_and_empty(obj)

Recursively removes None and empty dicts and lists values from a dictionary or list.

round_nested_floats

Python
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:

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

load_json

Python
load_json(path: str | Path) -> dict | list

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

Python
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

Python
load_yaml(path: str | Path) -> dict | list

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

Python
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

Python
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

Python
load_config_file(path: str | Path) -> dict

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

Python
document_linopy_model(model: Model, path: Path | None = None) -> dict[str, str]

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

Python
save_dataset_to_netcdf(ds: Dataset, path: str | Path, compression: int = 0) -> None

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

Python
load_dataset_from_netcdf(path: str | Path) -> xr.Dataset

Load a dataset from a netcdf file. Load all attrs from 'attrs' attributes.

Parameters:

Name Type Description Default
path str | Path

Path to load the dataset from.

required

Returns:

Name Type Description
Dataset Dataset

Loaded dataset with restored attrs.

numeric_to_str_for_repr

Python
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
  • Single/uniform values: "100.0"
str
  • Nearly uniform values: "~100.0" (values differ slightly but display similarly)
str
  • Varying values: "50.0-150.0" (shows range from min to max)

Raises:

Type Description
TypeError

If value cannot be converted to numeric format

build_repr_from_init

Python
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

Python
format_flow_details(obj, has_inputs: bool = True, has_outputs: bool = True) -> str

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

Python
format_title_with_underline(title: str, underline_char: str = '-') -> str

Format a title with underline of matching length.

Parameters:

Name Type Description Default
title str

The title text

required
underline_char str

Character to use for underline (default: '-')

'-'

Returns:

Type Description
str

Formatted string: "Title\n-----\n"

format_sections_with_headers

Python
format_sections_with_headers(sections: dict[str, str], underline_char: str = '-') -> list[str]

Format sections with underlined headers.

Parameters:

Name Type Description Default
sections dict[str, str]

Dict mapping section headers to content

required
underline_char str

Character for underlining headers

'-'

Returns:

Type Description
list[str]

List of formatted section strings

build_metadata_info

Python
build_metadata_info(parts: list[str], prefix: str = ' | ') -> str

Build metadata info string from parts.

Parameters:

Name Type Description Default
parts list[str]

List of metadata strings (empty strings are filtered out)

required
prefix str

Prefix to add if parts is non-empty

' | '

Returns:

Type Description
str

Formatted info string or empty string

suppress_output

Python
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.