Skip to content

flixopt.elements

This module contains the basic elements of the flixopt framework.

Attributes

Classes

Component

Component(label: str, inputs: list[Flow] | None = None, outputs: list[Flow] | None = None, on_off_parameters: OnOffParameters | None = None, prevent_simultaneous_flows: list[Flow] | None = None, meta_data: dict | None = None)

Bases: Element

Base class for all system components that transform, convert, or process flows.

Components are the active elements in energy systems that define how input and output Flows interact with each other. They represent equipment, processes, or logical operations that transform energy or materials between different states, carriers, or locations.

Components serve as connection points between Buses through their associated Flows, enabling the modeling of complex energy system topologies and operational constraints.

Parameters:

Name Type Description Default
label str

The label of the Element. Used to identify it in the FlowSystem.

required
inputs list[Flow] | None

list of input Flows feeding into the component. These represent energy/material consumption by the component.

None
outputs list[Flow] | None

list of output Flows leaving the component. These represent energy/material production by the component.

None
on_off_parameters OnOffParameters | None

Defines binary operation constraints and costs when the component has discrete on/off states. Creates binary variables for all connected Flows. For better performance, prefer defining OnOffParameters on individual Flows when possible.

None
prevent_simultaneous_flows list[Flow] | None

list of Flows that cannot be active simultaneously. Creates binary variables to enforce mutual exclusivity. Use sparingly as it increases computational complexity.

None
meta_data dict | None

Used to store additional information. Not used internally but saved in results. Only use Python native types.

None
Note

Component operational state is determined by its connected Flows: - Component is "on" if ANY of its Flows is active (flow_rate > 0) - Component is "off" only when ALL Flows are inactive (flow_rate = 0)

Binary variables and constraints: - on_off_parameters creates binary variables for ALL connected Flows - prevent_simultaneous_flows creates binary variables for specified Flows - For better computational performance, prefer Flow-level OnOffParameters

Component is an abstract base class. In practice, use specialized subclasses: - LinearConverter: Linear input/output relationships - Storage: Temporal energy/material storage - Transmission: Transport between locations - Source/Sink: System boundaries

Functions

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.

Bus

Bus(label: str, excess_penalty_per_flow_hour: TemporalDataUser | None = 100000.0, meta_data: dict | None = None)

Bases: Element

Buses represent nodal balances between flow rates, serving as connection points.

A Bus enforces energy or material balance constraints where the sum of all incoming flows must equal the sum of all outgoing flows at each time step. Buses represent physical or logical connection points for energy carriers (electricity, heat, gas) or material flows between different Components.

Mathematical Formulation

See the complete mathematical model in the documentation: Bus

Parameters:

Name Type Description Default
label str

The label of the Element. Used to identify it in the FlowSystem.

required
excess_penalty_per_flow_hour TemporalDataUser | None

Penalty costs for bus balance violations. When None, no excess/deficit is allowed (hard constraint). When set to a value > 0, allows bus imbalances at penalty cost. Default is 1e5 (high penalty).

100000.0
meta_data dict | None

Used to store additional information. Not used internally but saved in results. Only use Python native types.

None

Examples:

Electrical bus with strict balance:

electricity_bus = Bus(
    label='main_electrical_bus',
    excess_penalty_per_flow_hour=None,  # No imbalance allowed
)

Heat network with penalty for imbalances:

heat_network = Bus(
    label='district_heating_network',
    excess_penalty_per_flow_hour=1000,  # €1000/MWh penalty for imbalance
)

Material flow with time-varying penalties:

material_hub = Bus(
    label='material_processing_hub',
    excess_penalty_per_flow_hour=waste_disposal_costs,  # Time series
)
Note

The bus balance equation enforced is: Σ(inflows) = Σ(outflows) + excess - deficit

When excess_penalty_per_flow_hour is None, excess and deficit are forced to zero. When a penalty cost is specified, the optimization can choose to violate the balance if economically beneficial, paying the penalty. The penalty is added to the objective directly.

Empty inputs and outputs lists are initialized and populated automatically by the FlowSystem during system setup.

Functions

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.

Connection

Connection()

This class is not yet implemented!

Functions

Flow

Flow(label: str, bus: str, size: Scalar | InvestParameters = None, fixed_relative_profile: TemporalDataUser | None = None, relative_minimum: TemporalDataUser = 0, relative_maximum: TemporalDataUser = 1, effects_per_flow_hour: TemporalEffectsUser | None = None, on_off_parameters: OnOffParameters | None = None, flow_hours_total_max: Scalar | None = None, flow_hours_total_min: Scalar | None = None, load_factor_min: Scalar | None = None, load_factor_max: Scalar | None = None, previous_flow_rate: Scalar | list[Scalar] | None = None, meta_data: dict | None = None)

Bases: Element

Define a directed flow of energy or material between bus and component.

A Flow represents the transfer of energy (electricity, heat, fuel) or material between a Bus and a Component in a specific direction. The flow rate is the primary optimization variable, with constraints and costs defined through various parameters. Flows can have fixed or variable sizes, operational constraints, and complex on/off behavior.

Key Concepts

Flow Rate: The instantaneous rate of energy/material transfer (optimization variable) [kW, m³/h, kg/h] Flow Hours: Amount of energy/material transferred per timestep. [kWh, m³, kg] Flow Size: The maximum capacity or nominal rating of the flow [kW, m³/h, kg/h] Relative Bounds: Flow rate limits expressed as fractions of flow size

Integration with Parameter Classes
  • InvestParameters: Used for size when flow Size is an investment decision
  • OnOffParameters: Used for on_off_parameters when flow has discrete states
Mathematical Formulation

See the complete mathematical model in the documentation: Flow

Parameters:

Name Type Description Default
label str

Unique flow identifier within its component.

required
bus str

Bus label this flow connects to.

required
size Scalar | InvestParameters

Flow capacity. Scalar, InvestParameters, or None (uses CONFIG.Modeling.big).

None
relative_minimum TemporalDataUser

Minimum flow rate as fraction of size (0-1). Default: 0.

0
relative_maximum TemporalDataUser

Maximum flow rate as fraction of size. Default: 1.

1
load_factor_min Scalar | None

Minimum average utilization (0-1). Default: 0.

None
load_factor_max Scalar | None

Maximum average utilization (0-1). Default: 1.

None
effects_per_flow_hour TemporalEffectsUser | None

Operational costs/impacts per flow-hour. Dict mapping effect names to values (e.g., {'cost': 45, 'CO2': 0.8}).

None
on_off_parameters OnOffParameters | None

Binary operation constraints (OnOffParameters). Default: None.

None
flow_hours_total_max Scalar | None

Maximum cumulative flow-hours. Alternative to load_factor_max.

None
flow_hours_total_min Scalar | None

Minimum cumulative flow-hours. Alternative to load_factor_min.

None
fixed_relative_profile TemporalDataUser | None

Predetermined pattern as fraction of size. Flow rate = size × fixed_relative_profile(t).

None
previous_flow_rate Scalar | list[Scalar] | None

Initial flow state for on/off dynamics. Default: None (off).

None
meta_data dict | None

Additional info stored in results. Python native types only.

None

Examples:

Basic power flow with fixed capacity:

generator_output = Flow(
    label='electricity_out',
    bus='electricity_grid',
    size=100,  # 100 MW capacity
    relative_minimum=0.4,  # Cannot operate below 40 MW
    effects_per_flow_hour={'fuel_cost': 45, 'co2_emissions': 0.8},
)

Investment decision for battery capacity:

battery_flow = Flow(
    label='electricity_storage',
    bus='electricity_grid',
    size=InvestParameters(
        minimum_size=10,  # Minimum 10 MWh
        maximum_size=100,  # Maximum 100 MWh
        specific_effects={'cost': 150_000},  # €150k/MWh annualized
    ),
)

Heat pump with startup costs and minimum run times:

heat_pump = Flow(
    label='heat_output',
    bus='heating_network',
    size=50,  # 50 kW thermal
    relative_minimum=0.3,  # Minimum 15 kW output when on
    effects_per_flow_hour={'electricity_cost': 25, 'maintenance': 2},
    on_off_parameters=OnOffParameters(
        effects_per_switch_on={'startup_cost': 100, 'wear': 0.1},
        consecutive_on_hours_min=2,  # Must run at least 2 hours
        consecutive_off_hours_min=1,  # Must stay off at least 1 hour
        switch_on_total_max=200,  # Maximum 200 starts per period
    ),
)

Fixed renewable generation profile:

solar_generation = Flow(
    label='solar_power',
    bus='electricity_grid',
    size=25,  # 25 MW installed capacity
    fixed_relative_profile=np.array([0, 0.1, 0.4, 0.8, 0.9, 0.7, 0.3, 0.1, 0]),
    effects_per_flow_hour={'maintenance_costs': 5},  # €5/MWh maintenance
)

Industrial process with annual utilization limits:

production_line = Flow(
    label='product_output',
    bus='product_market',
    size=1000,  # 1000 units/hour capacity
    load_factor_min=0.6,  # Must achieve 60% annual utilization
    load_factor_max=0.85,  # Cannot exceed 85% for maintenance
    effects_per_flow_hour={'variable_cost': 12, 'quality_control': 0.5},
)
Design Considerations

Size vs Load Factors: Use flow_hours_total_min/max for absolute limits, load_factor_min/max for utilization-based constraints.

Relative Bounds: Set relative_minimum > 0 only when equipment cannot operate below that level. Use on_off_parameters for discrete on/off behavior.

Fixed Profiles: Use fixed_relative_profile for known exact patterns, relative_maximum for upper bounds on optimization variables.

Notes
  • Default size (CONFIG.Modeling.big) is used when size=None
  • list inputs for previous_flow_rate are converted to NumPy arrays
  • Flow direction is determined by component input/output designation
Deprecated

Passing Bus objects to bus parameter. Use bus label strings instead.

Functions

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.

FlowModel

FlowModel(model: FlowSystemModel, element: Flow)

Bases: ElementModel

Attributes

flow_rate property
flow_rate: Variable

Main flow rate variable

total_flow_hours property
total_flow_hours: Variable

Total flow hours variable

absolute_flow_rate_bounds property
absolute_flow_rate_bounds: tuple[TemporalData, TemporalData]

Returns the absolute bounds the flow_rate can reach. Further constraining might be needed

on_off property
on_off: OnOffModel | None

OnOff feature

investment property
investment: InvestmentModel | None

OnOff feature

previous_states property
previous_states: TemporalData | None

Previous states of the flow rate

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

ComponentModel

ComponentModel(model: FlowSystemModel, element: Component)

Bases: ElementModel

Attributes

previous_states property
previous_states: DataArray | None

Previous state of the component, derived from its flows

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