Skip to content

flixopt.structure

This module contains the core structure of the flixopt framework. These classes are not directly used by the end user, but are used by other modules.

Classes

SubmodelsMixin

Mixin that provides submodel functionality for both FlowSystemModel and Submodel.

Attributes

all_submodels property
all_submodels: list[Submodel]

Get all submodels including nested ones recursively.

Functions

add_submodels
add_submodels(submodel: Submodel, short_name: str = None) -> Submodel

Register a sub-model with the model

FlowSystemModel

FlowSystemModel(flow_system: FlowSystem, normalize_weights: bool)

Bases: Model, SubmodelsMixin

The FlowSystemModel is the linopy Model that is used to create the mathematical model of the flow_system. It is used to create and store the variables and constraints for the flow_system.

Parameters:

Name Type Description Default
flow_system FlowSystem

The flow_system that is used to create the model.

required
normalize_weights bool

Whether to automatically normalize the weights to sum up to 1 when solving.

required

Attributes

weights property
weights: int | DataArray

Returns the weights of the FlowSystem. Normalizes to 1 if normalize_weights is True

all_submodels property
all_submodels: list[Submodel]

Get all submodels including nested ones recursively.

Functions

get_coords
get_coords(dims: Collection[str] | None = None, extra_timestep: bool = False) -> xr.Coordinates | None

Returns the coordinates of the model

Parameters:

Name Type Description Default
dims Collection[str] | None

The dimensions to include in the coordinates. If None, includes all dimensions

None
extra_timestep bool

If True, uses extra timesteps instead of regular timesteps

False

Returns:

Type Description
Coordinates | None

The coordinates of the model, or None if no coordinates are available

Raises:

Type Description
ValueError

If extra_timestep=True but 'time' is not in dims

add_submodels
add_submodels(submodel: Submodel, short_name: str = None) -> Submodel

Register a sub-model with the model

Interface

Base class for all Elements and Models in flixopt that provides serialization capabilities.

This class enables automatic serialization/deserialization of objects containing xarray DataArrays and nested Interface objects to/from xarray Datasets and NetCDF files. It uses introspection of constructor parameters to automatically handle most serialization scenarios.

Key Features
  • Automatic extraction and restoration of xarray DataArrays
  • Support for nested Interface objects
  • NetCDF and JSON export/import
  • Recursive handling of complex nested structures
Subclasses must implement

transform_data(flow_system): Transform data to match FlowSystem dimensions

Functions

transform_data
transform_data(flow_system: FlowSystem, name_prefix: str = '') -> None

Transform the data of the interface to match the FlowSystem's dimensions.

Parameters:

Name Type Description Default
flow_system FlowSystem

The FlowSystem containing timing and dimensional information

required
name_prefix str

The prefix to use for the names of the variables. Defaults to '', which results in no prefix.

''

Raises:

Type Description
NotImplementedError

Must be implemented by subclasses

to_dataset
to_dataset() -> xr.Dataset

Convert the object to an xarray Dataset representation. All DataArrays become dataset variables, everything else goes to attrs.

Its recommended to only call this method on Interfaces with all numeric data stored as xr.DataArrays. Interfaces inside a FlowSystem are automatically converted this form after connecting and transforming the FlowSystem.

Returns:

Type Description
Dataset

xr.Dataset: Dataset containing all DataArrays with basic objects only in attributes

Raises:

Type Description
ValueError

If serialization fails due to naming conflicts or invalid data

to_netcdf
to_netcdf(path: str | Path, compression: int = 0)

Save the object to a NetCDF file.

Parameters:

Name Type Description Default
path str | Path

Path to save the NetCDF file

required
compression int

Compression level (0-9)

0

Raises:

Type Description
ValueError

If serialization fails

IOError

If file cannot be written

from_dataset classmethod
from_dataset(ds: Dataset) -> Interface

Create an instance from an xarray Dataset.

Parameters:

Name Type Description Default
ds Dataset

Dataset containing the object data

required

Returns:

Type Description
Interface

Interface instance

Raises:

Type Description
ValueError

If dataset format is invalid or class mismatch

from_netcdf classmethod
from_netcdf(path: str | Path) -> Interface

Load an instance from a NetCDF file.

Parameters:

Name Type Description Default
path str | Path

Path to the NetCDF file

required

Returns:

Type Description
Interface

Interface instance

Raises:

Type Description
IOError

If file cannot be read

ValueError

If file format is invalid

get_structure
get_structure(clean: bool = False, stats: bool = False) -> dict

Get object structure as a dictionary.

Parameters:

Name Type Description Default
clean bool

If True, remove None and empty dicts and lists.

False
stats bool

If True, replace DataArray references with statistics

False

Returns:

Type Description
dict

Dictionary representation of the object structure

to_json
to_json(path: str | Path)

Save the object to a JSON file. This is meant for documentation and comparison, not for reloading.

Parameters:

Name Type Description Default
path str | Path

The path to the JSON file.

required

Raises:

Type Description
IOError

If file cannot be written

copy
copy() -> Interface

Create a copy of the Interface object.

Uses the existing serialization infrastructure to ensure proper copying of all DataArrays and nested objects.

Returns:

Type Description
Interface

A new instance of the same class with copied data.

Element

Element(label: str, meta_data: dict | None = None)

Bases: Interface

This class is the basic Element of flixopt. Every Element has a label

Parameters:

Name Type Description Default
label str

The label of the element

required
meta_data dict | None

used to store more information about the Element. Is not used internally, but saved in the results. Only use python native types.

None

Functions

transform_data
transform_data(flow_system: FlowSystem, name_prefix: str = '') -> None

Transform the data of the interface to match the FlowSystem's dimensions.

Parameters:

Name Type Description Default
flow_system FlowSystem

The FlowSystem containing timing and dimensional information

required
name_prefix str

The prefix to use for the names of the variables. Defaults to '', which results in no prefix.

''

Raises:

Type Description
NotImplementedError

Must be implemented by subclasses

to_dataset
to_dataset() -> xr.Dataset

Convert the object to an xarray Dataset representation. All DataArrays become dataset variables, everything else goes to attrs.

Its recommended to only call this method on Interfaces with all numeric data stored as xr.DataArrays. Interfaces inside a FlowSystem are automatically converted this form after connecting and transforming the FlowSystem.

Returns:

Type Description
Dataset

xr.Dataset: Dataset containing all DataArrays with basic objects only in attributes

Raises:

Type Description
ValueError

If serialization fails due to naming conflicts or invalid data

to_netcdf
to_netcdf(path: str | Path, compression: int = 0)

Save the object to a NetCDF file.

Parameters:

Name Type Description Default
path str | Path

Path to save the NetCDF file

required
compression int

Compression level (0-9)

0

Raises:

Type Description
ValueError

If serialization fails

IOError

If file cannot be written

from_dataset classmethod
from_dataset(ds: Dataset) -> Interface

Create an instance from an xarray Dataset.

Parameters:

Name Type Description Default
ds Dataset

Dataset containing the object data

required

Returns:

Type Description
Interface

Interface instance

Raises:

Type Description
ValueError

If dataset format is invalid or class mismatch

from_netcdf classmethod
from_netcdf(path: str | Path) -> Interface

Load an instance from a NetCDF file.

Parameters:

Name Type Description Default
path str | Path

Path to the NetCDF file

required

Returns:

Type Description
Interface

Interface instance

Raises:

Type Description
IOError

If file cannot be read

ValueError

If file format is invalid

get_structure
get_structure(clean: bool = False, stats: bool = False) -> dict

Get object structure as a dictionary.

Parameters:

Name Type Description Default
clean bool

If True, remove None and empty dicts and lists.

False
stats bool

If True, replace DataArray references with statistics

False

Returns:

Type Description
dict

Dictionary representation of the object structure

to_json
to_json(path: str | Path)

Save the object to a JSON file. This is meant for documentation and comparison, not for reloading.

Parameters:

Name Type Description Default
path str | Path

The path to the JSON file.

required

Raises:

Type Description
IOError

If file cannot be written

copy
copy() -> Interface

Create a copy of the Interface object.

Uses the existing serialization infrastructure to ensure proper copying of all DataArrays and nested objects.

Returns:

Type Description
Interface

A new instance of the same class with copied data.

Submodel

Submodel(model: FlowSystemModel, label_of_element: str, label_of_model: str | None = None)

Bases: SubmodelsMixin

Stores Variables and Constraints. Its a subset of a FlowSystemModel. Variables and constraints are stored in the main FlowSystemModel, and are referenced here. Can have other Submodels assigned, and can be a Submodel of another Submodel.

Parameters:

Name Type Description Default
model FlowSystemModel

The FlowSystemModel that is used to create the model.

required
label_of_element str

The label of the parent (Element). Used to construct the full label of the model.

required
label_of_model str | None

The label of the model. Used as a prefix in all variables and constraints.

None

Attributes

variables_direct property
variables_direct: Variables

Variables of the model, excluding those of sub-models

constraints_direct property
constraints_direct: Constraints

Constraints of the model, excluding those of sub-models

constraints property
constraints: Constraints

All constraints of the model, including those of all sub-models

variables property
variables: Variables

All variables of the model, including those of all sub-models

all_submodels property
all_submodels: list[Submodel]

Get all submodels including nested ones recursively.

Functions

add_variables
add_variables(short_name: str = None, **kwargs) -> linopy.Variable

Create and register a variable in one step

add_constraints
add_constraints(expression, short_name: str = None, **kwargs) -> linopy.Constraint

Create and register a constraint in one step

register_variable
register_variable(variable: Variable, short_name: str = None) -> linopy.Variable

Register a variable with the model

register_constraint
register_constraint(constraint: Constraint, short_name: str = None) -> linopy.Constraint

Register a constraint with the model

get
get(name: str, default=None)

Get variable by short name, returning default if not found

add_submodels
add_submodels(submodel: Submodel, short_name: str = None) -> Submodel

Register a sub-model with the model

Submodels dataclass

Submodels(data: dict[str, Submodel])

A simple collection for storing submodels with easy access and representation.

Functions

add
add(submodel: Submodel, name: str) -> None

Add a submodel to the collection.

get
get(name: str, default=None)

Get submodel by name, returning default if not found.

ElementModel

ElementModel(model: FlowSystemModel, element: Element)

Bases: Submodel

Stores the mathematical Variables and Constraints for Elements. ElementModels are directly registered in the main FlowSystemModel

Parameters:

Name Type Description Default
model FlowSystemModel

The FlowSystemModel that is used to create the model.

required
element Element

The element this model is created for.

required

Attributes

all_submodels property
all_submodels: list[Submodel]

Get all submodels including nested ones recursively.

variables_direct property
variables_direct: Variables

Variables of the model, excluding those of sub-models

constraints_direct property
constraints_direct: Constraints

Constraints of the model, excluding those of sub-models

constraints property
constraints: Constraints

All constraints of the model, including those of all sub-models

variables property
variables: Variables

All variables of the model, including those of all sub-models

Functions

add_submodels
add_submodels(submodel: Submodel, short_name: str = None) -> Submodel

Register a sub-model with the model

add_variables
add_variables(short_name: str = None, **kwargs) -> linopy.Variable

Create and register a variable in one step

add_constraints
add_constraints(expression, short_name: str = None, **kwargs) -> linopy.Constraint

Create and register a constraint in one step

register_variable
register_variable(variable: Variable, short_name: str = None) -> linopy.Variable

Register a variable with the model

register_constraint
register_constraint(constraint: Constraint, short_name: str = None) -> linopy.Constraint

Register a constraint with the model

get
get(name: str, default=None)

Get variable by short name, returning default if not found

Functions

register_class_for_io

register_class_for_io(cls)

Register a class for serialization/deserialization.