Skip to content

flixopt.components

This module contains the basic components of the flixopt framework.

Attributes

Classes

LinearConverter

LinearConverter(label: str, inputs: list[Flow], outputs: list[Flow], on_off_parameters: OnOffParameters | None = None, conversion_factors: list[dict[str, TemporalDataUser]] | None = None, piecewise_conversion: PiecewiseConversion | None = None, meta_data: dict | None = None)

Bases: Component

Converts input-Flows into output-Flows via linear conversion factors.

LinearConverter models equipment that transforms one or more input flows into one or more output flows through linear relationships. This includes heat exchangers, electrical converters, chemical reactors, and other equipment where the relationship between inputs and outputs can be expressed as linear equations.

The component supports two modeling approaches: simple conversion factors for straightforward linear relationships, or piecewise conversion for complex non-linear behavior approximated through piecewise linear segments.

Mathematical Formulation

See the complete mathematical model in the documentation: LinearConverter

Parameters:

Name Type Description Default
label str

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

required
inputs list[Flow]

list of input Flows that feed into the converter.

required
outputs list[Flow]

list of output Flows that are produced by the converter.

required
on_off_parameters OnOffParameters | None

Information about on and off state of LinearConverter. Component is On/Off if all connected Flows are On/Off. This induces an On-Variable (binary) in all Flows! If possible, use OnOffParameters in a single Flow instead to keep the number of binary variables low.

None
conversion_factors list[dict[str, TemporalDataUser]] | None

Linear relationships between flows expressed as a list of dictionaries. Each dictionary maps flow labels to their coefficients in one linear equation. The number of conversion factors must be less than the total number of flows to ensure degrees of freedom > 0. Either 'conversion_factors' OR 'piecewise_conversion' can be used, but not both. For examples also look into the linear_converters.py file.

None
piecewise_conversion PiecewiseConversion | None

Define piecewise linear relationships between flow rates of different flows. Enables modeling of non-linear conversion behavior through linear approximation. Either 'conversion_factors' or 'piecewise_conversion' can be used, but not both.

None
meta_data dict | None

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

None

Examples:

Simple 1:1 heat exchanger with 95% efficiency:

heat_exchanger = LinearConverter(
    label='primary_hx',
    inputs=[hot_water_in],
    outputs=[hot_water_out],
    conversion_factors=[{'hot_water_in': 0.95, 'hot_water_out': 1}],
)

Multi-input heat pump with COP=3:

heat_pump = LinearConverter(
    label='air_source_hp',
    inputs=[electricity_in],
    outputs=[heat_output],
    conversion_factors=[{'electricity_in': 3, 'heat_output': 1}],
)

Combined heat and power (CHP) unit with multiple outputs:

chp_unit = LinearConverter(
    label='gas_chp',
    inputs=[natural_gas],
    outputs=[electricity_out, heat_out],
    conversion_factors=[
        {'natural_gas': 0.35, 'electricity_out': 1},
        {'natural_gas': 0.45, 'heat_out': 1},
    ],
)

Electrolyzer with multiple conversion relationships:

electrolyzer = LinearConverter(
    label='pem_electrolyzer',
    inputs=[electricity_in, water_in],
    outputs=[hydrogen_out, oxygen_out],
    conversion_factors=[
        {'electricity_in': 1, 'hydrogen_out': 50},  # 50 kWh/kg H2
        {'water_in': 1, 'hydrogen_out': 9},  # 9 kg H2O/kg H2
        {'hydrogen_out': 8, 'oxygen_out': 1},  # Mass balance
    ],
)

Complex converter with piecewise efficiency:

variable_efficiency_converter = LinearConverter(
    label='variable_converter',
    inputs=[fuel_in],
    outputs=[power_out],
    piecewise_conversion=PiecewiseConversion(
        {
            'fuel_in': Piecewise(
                [
                    Piece(0, 10),  # Low load operation
                    Piece(10, 25),  # High load operation
                ]
            ),
            'power_out': Piecewise(
                [
                    Piece(0, 3.5),  # Lower efficiency at part load
                    Piece(3.5, 10),  # Higher efficiency at full load
                ]
            ),
        }
    ),
)
Note

Conversion factors define linear relationships where the sum of (coefficient × flow_rate) equals zero for each equation: factor1×flow1 + factor2×flow2 + ... = 0 Conversion factors define linear relationships: {flow1: a1, flow2: a2, ...} yields a1×flow_rate1 + a2×flow_rate2 + ... = 0. Note: The input format may be unintuitive. For example, {"electricity": 1, "H2": 50} implies 1×electricity = 50×H2, i.e., 50 units of electricity produce 1 unit of H2.

The system must have fewer conversion factors than total flows (degrees of freedom > 0) to avoid over-constraining the problem. For n total flows, use at most n-1 conversion factors.

When using piecewise_conversion, the converter operates on one piece at a time, with binary variables determining which piece is active.

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.

Storage

Storage(label: str, charging: Flow, discharging: Flow, capacity_in_flow_hours: PeriodicDataUser | InvestParameters, relative_minimum_charge_state: TemporalDataUser = 0, relative_maximum_charge_state: TemporalDataUser = 1, initial_charge_state: PeriodicDataUser | Literal['lastValueOfSim'] = 0, minimal_final_charge_state: PeriodicDataUser | None = None, maximal_final_charge_state: PeriodicDataUser | None = None, relative_minimum_final_charge_state: PeriodicDataUser | None = None, relative_maximum_final_charge_state: PeriodicDataUser | None = None, eta_charge: TemporalDataUser = 1, eta_discharge: TemporalDataUser = 1, relative_loss_per_hour: TemporalDataUser = 0, prevent_simultaneous_charge_and_discharge: bool = True, balanced: bool = False, meta_data: dict | None = None)

Bases: Component

A Storage models the temporary storage and release of energy or material.

Storages have one incoming and one outgoing Flow, each with configurable efficiency factors. They maintain a charge state variable that represents the stored amount, bounded by capacity limits and evolving over time based on charging, discharging, and self-discharge losses.

The storage model handles complex temporal dynamics including initial conditions, final state constraints, and time-varying parameters. It supports both fixed-size and investment-optimized storage systems with comprehensive techno-economic modeling.

Mathematical Formulation

See the complete mathematical model in the documentation: Storage

  • Equation (1): Charge state bounds
  • Equation (3): Storage balance (charge state evolution)

Variable Mapping: - capacity_in_flow_hours → C (storage capacity) - charge_state → c(t_i) (state of charge at time t_i) - relative_loss_per_hour → ċ_rel,loss (self-discharge rate) - eta_charge → η_in (charging efficiency) - eta_discharge → η_out (discharging efficiency)

Parameters:

Name Type Description Default
label str

Element identifier used in the FlowSystem.

required
charging Flow

Incoming flow for loading the storage.

required
discharging Flow

Outgoing flow for unloading the storage.

required
capacity_in_flow_hours PeriodicDataUser | InvestParameters

Storage capacity in flow-hours (kWh, m³, kg). Scalar for fixed size or InvestParameters for optimization.

required
relative_minimum_charge_state TemporalDataUser

Minimum charge state (0-1). Default: 0.

0
relative_maximum_charge_state TemporalDataUser

Maximum charge state (0-1). Default: 1.

1
initial_charge_state PeriodicDataUser | Literal['lastValueOfSim']

Charge at start. Numeric or 'lastValueOfSim'. Default: 0.

0
minimal_final_charge_state PeriodicDataUser | None

Minimum absolute charge required at end (optional).

None
maximal_final_charge_state PeriodicDataUser | None

Maximum absolute charge allowed at end (optional).

None
relative_minimum_final_charge_state PeriodicDataUser | None

Minimum relative charge at end. Defaults to last value of relative_minimum_charge_state.

None
relative_maximum_final_charge_state PeriodicDataUser | None

Maximum relative charge at end. Defaults to last value of relative_maximum_charge_state.

None
eta_charge TemporalDataUser

Charging efficiency (0-1). Default: 1.

1
eta_discharge TemporalDataUser

Discharging efficiency (0-1). Default: 1.

1
relative_loss_per_hour TemporalDataUser

Self-discharge per hour (0-0.1). Default: 0.

0
prevent_simultaneous_charge_and_discharge bool

Prevent charging and discharging simultaneously. Adds binary variables. Default: True.

True
meta_data dict | None

Additional information stored in results. Python native types only.

None

Examples:

Battery energy storage system:

battery = Storage(
    label='lithium_battery',
    charging=battery_charge_flow,
    discharging=battery_discharge_flow,
    capacity_in_flow_hours=100,  # 100 kWh capacity
    eta_charge=0.95,  # 95% charging efficiency
    eta_discharge=0.95,  # 95% discharging efficiency
    relative_loss_per_hour=0.001,  # 0.1% loss per hour
    relative_minimum_charge_state=0.1,  # Never below 10% SOC
    relative_maximum_charge_state=0.9,  # Never above 90% SOC
)

Thermal storage with cycling constraints:

thermal_storage = Storage(
    label='hot_water_tank',
    charging=heat_input,
    discharging=heat_output,
    capacity_in_flow_hours=500,  # 500 kWh thermal capacity
    initial_charge_state=250,  # Start half full
    # Impact of temperature on energy capacity
    relative_maximum_charge_state=water_temperature_spread / rated_temeprature_spread,
    eta_charge=0.90,  # Heat exchanger losses
    eta_discharge=0.85,  # Distribution losses
    relative_loss_per_hour=0.02,  # 2% thermal loss per hour
    prevent_simultaneous_charge_and_discharge=True,
)

Pumped hydro storage with investment optimization:

pumped_hydro = Storage(
    label='pumped_hydro',
    charging=pump_flow,
    discharging=turbine_flow,
    capacity_in_flow_hours=InvestParameters(
        minimum_size=1000,  # Minimum economic scale
        maximum_size=10000,  # Site constraints
        specific_effects={'cost': 150},  # €150/MWh capacity
        fix_effects={'cost': 50_000_000},  # €50M fixed costs
    ),
    eta_charge=0.85,  # Pumping efficiency
    eta_discharge=0.90,  # Turbine efficiency
    initial_charge_state='lastValueOfSim',  # Ensuring no deficit compared to start
    relative_loss_per_hour=0.0001,  # Minimal evaporation
)

Material storage with inventory management:

fuel_storage = Storage(
    label='natural_gas_storage',
    charging=gas_injection,
    discharging=gas_withdrawal,
    capacity_in_flow_hours=10000,  # 10,000 m³ storage volume
    initial_charge_state=3000,  # Start with 3,000 m³
    minimal_final_charge_state=1000,  # Strategic reserve
    maximal_final_charge_state=9000,  # Prevent overflow
    eta_charge=0.98,  # Compression losses
    eta_discharge=0.95,  # Pressure reduction losses
    relative_loss_per_hour=0.0005,  # 0.05% leakage per hour
    prevent_simultaneous_charge_and_discharge=False,  # Allow flow-through
)
Note

Mathematical formulation: See Storage for charge state evolution equations and balance constraints.

Efficiency parameters (eta_charge, eta_discharge) are dimensionless (0-1 range). The relative_loss_per_hour represents exponential decay per hour.

Binary variables: When prevent_simultaneous_charge_and_discharge is True, binary variables enforce mutual exclusivity, increasing solution time but preventing unrealistic simultaneous charging and discharging.

Units: Flow rates and charge states are related by the concept of 'flow hours' (=flow_rate * time). With flow rates in kW, the charge state is therefore (usually) kWh. With flow rates in m3/h, the charge state is therefore in m3.

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.

Transmission

Transmission(label: str, in1: Flow, out1: Flow, in2: Flow | None = None, out2: Flow | None = None, relative_losses: TemporalDataUser | None = None, absolute_losses: TemporalDataUser | None = None, on_off_parameters: OnOffParameters = None, prevent_simultaneous_flows_in_both_directions: bool = True, balanced: bool = False, meta_data: dict | None = None)

Bases: Component

Models transmission infrastructure that transports flows between two locations with losses.

Transmission components represent physical infrastructure like pipes, cables, transmission lines, or conveyor systems that transport energy or materials between two points. They can model both unidirectional and bidirectional flow with configurable loss mechanisms and operational constraints.

The component supports complex transmission scenarios including relative losses (proportional to flow), absolute losses (fixed when active), and bidirectional operation with flow direction constraints.

Parameters:

Name Type Description Default
label str

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

required
in1 Flow

The primary inflow (side A). Pass InvestParameters here for capacity optimization.

required
out1 Flow

The primary outflow (side B).

required
in2 Flow | None

Optional secondary inflow (side B) for bidirectional operation. If in1 has InvestParameters, in2 will automatically have matching capacity.

None
out2 Flow | None

Optional secondary outflow (side A) for bidirectional operation.

None
relative_losses TemporalDataUser | None

Proportional losses as fraction of throughput (e.g., 0.02 for 2% loss). Applied as: output = input × (1 - relative_losses)

None
absolute_losses TemporalDataUser | None

Fixed losses that occur when transmission is active. Automatically creates binary variables for on/off states.

None
on_off_parameters OnOffParameters

Parameters defining binary operation constraints and costs.

None
prevent_simultaneous_flows_in_both_directions bool

If True, prevents simultaneous flow in both directions. Increases binary variables but reflects physical reality for most transmission systems. Default is True.

True
balanced bool

Whether to equate the size of the in1 and in2 Flow. Needs InvestParameters in both Flows.

False
meta_data dict | None

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

None

Examples:

Simple electrical transmission line:

power_line = Transmission(
    label='110kv_line',
    in1=substation_a_out,
    out1=substation_b_in,
    relative_losses=0.03,  # 3% line losses
)

Bidirectional natural gas pipeline:

gas_pipeline = Transmission(
    label='interstate_pipeline',
    in1=compressor_station_a,
    out1=distribution_hub_b,
    in2=compressor_station_b,
    out2=distribution_hub_a,
    relative_losses=0.005,  # 0.5% friction losses
    absolute_losses=50,  # 50 kW compressor power when active
    prevent_simultaneous_flows_in_both_directions=True,
)

District heating network with investment optimization:

heating_network = Transmission(
    label='dh_main_line',
    in1=Flow(
        label='heat_supply',
        bus=central_plant_bus,
        size=InvestParameters(
            minimum_size=1000,  # Minimum 1 MW capacity
            maximum_size=10000,  # Maximum 10 MW capacity
            specific_effects={'cost': 200},  # €200/kW capacity
            fix_effects={'cost': 500000},  # €500k fixed installation
        ),
    ),
    out1=district_heat_demand,
    relative_losses=0.15,  # 15% thermal losses in distribution
)

Material conveyor with on/off operation:

conveyor_belt = Transmission(
    label='material_transport',
    in1=loading_station,
    out1=unloading_station,
    absolute_losses=25,  # 25 kW motor power when running
    on_off_parameters=OnOffParameters(
        effects_per_switch_on={'maintenance': 0.1},
        consecutive_on_hours_min=2,  # Minimum 2-hour operation
        switch_on_total_max=10,  # Maximum 10 starts per day
    ),
)
Note

The transmission equation balances flows with losses: output_flow = input_flow × (1 - relative_losses) - absolute_losses

For bidirectional transmission, each direction has independent loss calculations.

When using InvestParameters on in1, the capacity automatically applies to in2 to maintain consistent bidirectional capacity without additional investment variables.

Absolute losses force the creation of binary on/off variables, which increases computational complexity but enables realistic modeling of equipment with standby power consumption.

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.

TransmissionModel

TransmissionModel(model: FlowSystemModel, element: Transmission)

Bases: ComponentModel

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

previous_states property
previous_states: DataArray | None

Previous state of the component, derived from its flows

Functions

create_transmission_equation
create_transmission_equation(name: str, in_flow: Flow, out_flow: Flow) -> linopy.Constraint

Creates an Equation for the Transmission efficiency and adds it to the model

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

StorageModel

StorageModel(model: FlowSystemModel, element: Storage)

Bases: ComponentModel

Submodel of Storage

Attributes

investment property
investment: InvestmentModel | None

OnOff feature

charge_state property
charge_state: Variable

Charge state variable

netto_discharge property
netto_discharge: Variable

Netto discharge variable

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

previous_states property
previous_states: DataArray | None

Previous state of the component, derived from its flows

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

SourceAndSink

SourceAndSink(label: str, inputs: list[Flow] | None = None, outputs: list[Flow] | None = None, prevent_simultaneous_flow_rates: bool = True, meta_data: dict | None = None, **kwargs)

Bases: Component

A SourceAndSink combines both supply and demand capabilities in a single component.

SourceAndSink components can both consume AND provide energy or material flows from and to the system, making them ideal for modeling markets, (simple) storage facilities, or bidirectional grid connections where buying and selling occur at the same location.

Parameters:

Name Type Description Default
label str

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

required
inputs list[Flow] | None

Input-flows into the SourceAndSink representing consumption/demand side.

None
outputs list[Flow] | None

Output-flows from the SourceAndSink representing supply/generation side.

None
prevent_simultaneous_flow_rates bool

If True, prevents simultaneous input and output flows. This enforces that the component operates either as a source OR sink at any given time, but not both simultaneously. Default is True.

True
meta_data dict | None

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

None

Examples:

Electricity market connection (buy/sell to grid):

electricity_market = SourceAndSink(
    label='grid_connection',
    inputs=[electricity_purchase],  # Buy from grid
    outputs=[electricity_sale],  # Sell to grid
    prevent_simultaneous_flow_rates=True,  # Can't buy and sell simultaneously
)

Natural gas storage facility:

gas_storage_facility = SourceAndSink(
    label='underground_gas_storage',
    inputs=[gas_injection_flow],  # Inject gas into storage
    outputs=[gas_withdrawal_flow],  # Withdraw gas from storage
    prevent_simultaneous_flow_rates=True,  # Injection or withdrawal, not both
)

District heating network connection:

dh_connection = SourceAndSink(
    label='district_heating_tie',
    inputs=[heat_purchase_flow],  # Purchase heat from network
    outputs=[heat_sale_flow],  # Sell excess heat to network
    prevent_simultaneous_flow_rates=False,  # May allow simultaneous flows
)

Industrial waste heat exchange:

waste_heat_exchange = SourceAndSink(
    label='industrial_heat_hub',
    inputs=[
        waste_heat_input_a,  # Receive waste heat from process A
        waste_heat_input_b,  # Receive waste heat from process B
    ],
    outputs=[
        useful_heat_supply_c,  # Supply heat to process C
        useful_heat_supply_d,  # Supply heat to process D
    ],
    prevent_simultaneous_flow_rates=False,  # Multiple simultaneous flows allowed
)
Note

When prevent_simultaneous_flow_rates is True, binary variables are created to ensure mutually exclusive operation between input and output flows, which increases computational complexity but reflects realistic market or storage operation constraints.

SourceAndSink is particularly useful for modeling: - Energy markets with bidirectional trading - Storage facilities with injection/withdrawal operations - Grid tie points with import/export capabilities - Waste exchange networks with multiple participants

Deprecated

The deprecated sink and source kwargs are accepted for compatibility but will be removed in future releases.

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.

Source

Source(label: str, outputs: list[Flow] | None = None, meta_data: dict | None = None, prevent_simultaneous_flow_rates: bool = False, **kwargs)

Bases: Component

A Source generates or provides energy or material flows into the system.

Sources represent supply points like power plants, fuel suppliers, renewable energy sources, or any system boundary where flows originate. They provide unlimited supply capability subject to flow constraints, demand patterns and effects.

Parameters:

Name Type Description Default
label str

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

required
outputs list[Flow] | None

Output-flows from the source. Can be single flow or list of flows for sources providing multiple commodities or services.

None
meta_data dict | None

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

None
prevent_simultaneous_flow_rates bool

If True, only one output flow can be active at a time. Useful for modeling mutually exclusive supply options. Default is False.

False

Examples:

Simple electricity grid connection:

grid_source = Source(label='electrical_grid', outputs=[grid_electricity_flow])

Natural gas supply with cost and capacity constraints:

gas_supply = Source(
    label='gas_network',
    outputs=[
        Flow(
            label='natural_gas_flow',
            bus=gas_bus,
            size=1000,  # Maximum 1000 kW supply capacity
            effects_per_flow_hour={'cost': 0.04},  # €0.04/kWh gas cost
        )
    ],
)

Multi-fuel power plant with switching constraints:

multi_fuel_plant = Source(
    label='flexible_generator',
    outputs=[coal_electricity, gas_electricity, biomass_electricity],
    prevent_simultaneous_flow_rates=True,  # Can only use one fuel at a time
)

Renewable energy source with investment optimization:

solar_farm = Source(
    label='solar_pv',
    outputs=[
        Flow(
            label='solar_power',
            bus=electricity_bus,
            size=InvestParameters(
                minimum_size=0,
                maximum_size=50000,  # Up to 50 MW
                specific_effects={'cost': 800},  # €800/kW installed
                fix_effects={'cost': 100000},  # €100k development costs
            ),
            fixed_relative_profile=solar_profile,  # Hourly generation profile
        )
    ],
)
Deprecated

The deprecated source kwarg is accepted for compatibility but will be removed in future releases.

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.

Sink

Sink(label: str, inputs: list[Flow] | None = None, meta_data: dict | None = None, prevent_simultaneous_flow_rates: bool = False, **kwargs)

Bases: Component

A Sink consumes energy or material flows from the system.

Sinks represent demand points like electrical loads, heat demands, material consumption, or any system boundary where flows terminate. They provide unlimited consumption capability subject to flow constraints, demand patterns and effects.

Parameters:

Name Type Description Default
label str

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

required
inputs list[Flow] | None

Input-flows into the sink. Can be single flow or list of flows for sinks consuming multiple commodities or services.

None
meta_data dict | None

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

None
prevent_simultaneous_flow_rates bool

If True, only one input flow can be active at a time. Useful for modeling mutually exclusive consumption options. Default is False.

False

Examples:

Simple electrical demand:

electrical_load = Sink(label='building_load', inputs=[electricity_demand_flow])

Heat demand with time-varying profile:

heat_demand = Sink(
    label='district_heating_load',
    inputs=[
        Flow(
            label='heat_consumption',
            bus=heat_bus,
            fixed_relative_profile=hourly_heat_profile,  # Demand profile
            size=2000,  # Peak demand of 2000 kW
        )
    ],
)

Multi-energy building with switching capabilities:

flexible_building = Sink(
    label='smart_building',
    inputs=[electricity_heating, gas_heating, heat_pump_heating],
    prevent_simultaneous_flow_rates=True,  # Can only use one heating mode
)

Industrial process with variable demand:

factory_load = Sink(
    label='manufacturing_plant',
    inputs=[
        Flow(
            label='electricity_process',
            bus=electricity_bus,
            size=5000,  # Base electrical load
            effects_per_flow_hour={'cost': -0.1},  # Value of service (negative cost)
        ),
        Flow(
            label='steam_process',
            bus=steam_bus,
            size=3000,  # Process steam demand
            fixed_relative_profile=production_schedule,
        ),
    ],
)
Deprecated

The deprecated sink kwarg is accepted for compatibility but will be removed in future releases.

Initialize a Sink (consumes flow from the system).

Supports legacy sink= keyword for backward compatibility (deprecated): if sink is provided it is used as the single input flow and a DeprecationWarning is issued; specifying both inputs and sink raises ValueError.

Parameters:

Name Type Description Default
label str

Unique element label.

required
inputs list[Flow]

Input flows for the sink.

None
meta_data dict

Arbitrary metadata attached to the element.

None
prevent_simultaneous_flow_rates bool

If True, prevents simultaneous nonzero flow rates across the element's inputs by wiring that restriction into the base Component setup.

False
Note

The deprecated sink kwarg is accepted for compatibility but will be removed in future releases.

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.

Functions