Skip to content

flixopt.effects

This module contains the effects of the flixopt framework. Furthermore, it contains the EffectCollection, which is used to collect all effects of a system. Different Datatypes are used to represent the effects with assigned values by the user, which are then transformed into the internal data structure.

Attributes

TemporalEffectsUser module-attribute

TemporalEffectsUser = TemporalDataUser | dict[str, TemporalDataUser]

This datatype is used to define a temporal share to an effect by a certain attribute.

PeriodicEffectsUser module-attribute

PeriodicEffectsUser = PeriodicDataUser | dict[str, PeriodicDataUser]

This datatype is used to define a scalar share to an effect by a certain attribute.

TemporalEffects module-attribute

TemporalEffects = dict[str, TemporalData]

This datatype is used internally to handle temporal shares to an effect.

PeriodicEffects module-attribute

PeriodicEffects = dict[str, Scalar]

This datatype is used internally to handle scalar shares to an effect.

Classes

Effect

Effect(label: str, unit: str, description: str, meta_data: dict | None = None, is_standard: bool = False, is_objective: bool = False, share_from_temporal: TemporalEffectsUser | None = None, share_from_periodic: PeriodicEffectsUser | None = None, minimum_temporal: PeriodicEffectsUser | None = None, maximum_temporal: PeriodicEffectsUser | None = None, minimum_periodic: PeriodicEffectsUser | None = None, maximum_periodic: PeriodicEffectsUser | None = None, minimum_per_hour: TemporalDataUser | None = None, maximum_per_hour: TemporalDataUser | None = None, minimum_total: Scalar | None = None, maximum_total: Scalar | None = None, **kwargs)

Bases: Element

Represents system-wide impacts like costs, emissions, resource consumption, or other effects.

Effects capture the broader impacts of system operation and investment decisions beyond the primary energy/material flows. Each Effect accumulates contributions from Components, Flows, and other system elements. One Effect is typically chosen as the optimization objective, while others can serve as constraints or tracking metrics.

Effects support comprehensive modeling including operational and investment contributions, cross-effect relationships (e.g., carbon pricing), and flexible constraint formulation.

Parameters:

Name Type Description Default
label str

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

required
unit str

The unit of the effect (e.g., '€', 'kg_CO2', 'kWh_primary', 'm²'). This is informative only and does not affect optimization calculations.

required
description str

Descriptive name explaining what this effect represents.

required
is_standard bool

If True, this is a standard effect allowing direct value input without effect dictionaries. Used for simplified effect specification (and less boilerplate code).

False
is_objective bool

If True, this effect serves as the optimization objective function. Only one effect can be marked as objective per optimization.

False
share_from_temporal TemporalEffectsUser | None

Temporal cross-effect contributions. Maps temporal contributions from other effects to this effect

None
share_from_periodic PeriodicEffectsUser | None

Periodic cross-effect contributions. Maps periodic contributions from other effects to this effect.

None
minimum_temporal PeriodicEffectsUser | None

Minimum allowed total contribution across all timesteps.

None
maximum_temporal PeriodicEffectsUser | None

Maximum allowed total contribution across all timesteps.

None
minimum_per_hour TemporalDataUser | None

Minimum allowed contribution per hour.

None
maximum_per_hour TemporalDataUser | None

Maximum allowed contribution per hour.

None
minimum_periodic PeriodicEffectsUser | None

Minimum allowed total periodic contribution.

None
maximum_periodic PeriodicEffectsUser | None

Maximum allowed total periodic contribution.

None
minimum_total Scalar | None

Minimum allowed total effect (temporal + periodic combined).

None
maximum_total Scalar | None

Maximum allowed total effect (temporal + periodic combined).

None
meta_data dict | None

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

None

Deprecated Parameters (for backwards compatibility): minimum_operation: Use minimum_temporal instead. maximum_operation: Use maximum_temporal instead. minimum_invest: Use minimum_periodic instead. maximum_invest: Use maximum_periodic instead. minimum_operation_per_hour: Use minimum_per_hour instead. maximum_operation_per_hour: Use maximum_per_hour instead.

Examples:

Basic cost objective:

cost_effect = Effect(
    label='system_costs',
    unit='€',
    description='Total system costs',
    is_objective=True,
)

CO2 emissions:

co2_effect = Effect(
    label='CO2',
    unit='kg_CO2',
    description='Carbon dioxide emissions',
    maximum_total=1_000_000,  # 1000 t CO2 annual limit
)

Land use constraint:

land_use = Effect(
    label='land_usage',
    unit='m²',
    description='Land area requirement',
    maximum_total=50_000,  # Maximum 5 hectares available
)

Primary energy tracking:

primary_energy = Effect(
    label='primary_energy',
    unit='kWh_primary',
    description='Primary energy consumption',
)

Cost objective with carbon and primary energy pricing:

```python
cost_effect = Effect(
    label='system_costs',
    unit='€',
    description='Total system costs',
    is_objective=True,
    share_from_temporal={
        'primary_energy': 0.08,  # 0.08 €/kWh_primary
        'CO2': 0.2,  # Carbon pricing: 0.2 €/kg_CO2 into costs if used on a cost effect
    },
)
```

Water consumption with tiered constraints:

```python
water_usage = Effect(
    label='water_consumption',
    unit='m³',
    description='Industrial water usage',
    minimum_per_hour=10,  # Minimum 10 m³/h for process stability
    maximum_per_hour=500,  # Maximum 500 m³/h capacity limit
    maximum_total=100_000,  # Annual permit limit: 100,000 m³
)
```
Note

Effect bounds can be None to indicate no constraint in that direction.

Cross-effect relationships enable sophisticated modeling like carbon pricing, resource valuation, or multi-criteria optimization with weighted objectives.

The unit field is purely informational - ensure dimensional consistency across all contributions to each effect manually.

Effects are accumulated as: - Total = Σ(temporal contributions) + Σ(periodic contributions)

Attributes

minimum_operation property writable
minimum_operation

DEPRECATED: Use 'minimum_temporal' property instead.

maximum_operation property writable
maximum_operation

DEPRECATED: Use 'maximum_temporal' property instead.

minimum_invest property writable
minimum_invest

DEPRECATED: Use 'minimum_periodic' property instead.

maximum_invest property writable
maximum_invest

DEPRECATED: Use 'maximum_periodic' property instead.

minimum_operation_per_hour property writable
minimum_operation_per_hour

DEPRECATED: Use 'minimum_per_hour' property instead.

maximum_operation_per_hour property writable
maximum_operation_per_hour

DEPRECATED: Use 'maximum_per_hour' property 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.

EffectCollection

EffectCollection(*effects: Effect)

Handling all Effects

Functions

create_effect_values_dict
create_effect_values_dict(effect_values_user: PeriodicEffectsUser | TemporalEffectsUser) -> dict[str, Scalar | TemporalDataUser] | None

Converts effect values into a dictionary. If a scalar is provided, it is associated with a default effect type.

Examples

effect_values_user = 20 -> {'': 20} effect_values_user = {None: 20} -> {'': 20} effect_values_user = None -> None effect_values_user = {'effect1': 20, 'effect2': 0.3} -> {'effect1': 20, 'effect2': 0.3}

Returns

dict or None A dictionary keyed by effect label, or None if input is None. Note: a standard effect must be defined when passing scalars or None labels.

EffectCollectionModel

EffectCollectionModel(model: FlowSystemModel, effects: EffectCollection)

Bases: Submodel

Handling all Effects

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

calculate_all_conversion_paths

calculate_all_conversion_paths(conversion_dict: dict[str, dict[str, Scalar | DataArray]]) -> dict[tuple[str, str], xr.DataArray]

Calculates all possible direct and indirect conversion factors between units/domains. This function uses Breadth-First Search (BFS) to find all possible conversion paths between different units or domains in a conversion graph. It computes both direct conversions (explicitly provided in the input) and indirect conversions (derived through intermediate units). Args: conversion_dict: A nested dictionary where: - Outer keys represent origin units/domains - Inner dictionaries map target units/domains to their conversion factors - Conversion factors can be integers, floats, or numpy arrays Returns: A dictionary mapping (origin, target) tuples to their respective conversion factors. Each key is a tuple of strings representing the origin and target units/domains. Each value is the conversion factor (int, float, or numpy array) from origin to target.

detect_cycles

detect_cycles(graph: dict[str, list[str]]) -> list[list[str]]

Detects cycles in a directed graph using DFS.

Parameters:

Name Type Description Default
graph dict[str, list[str]]

Adjacency list representation of the graph

required

Returns:

Type Description
list[list[str]]

List of cycles found, where each cycle is a list of nodes

tuples_to_adjacency_list

tuples_to_adjacency_list(edges: list[tuple[str, str]]) -> dict[str, list[str]]

Converts a list of edge tuples (source, target) to an adjacency list representation.

Parameters:

Name Type Description Default
edges list[tuple[str, str]]

List of (source, target) tuples representing directed edges

required

Returns:

Type Description
dict[str, list[str]]

Dictionary mapping each source node to a list of its target nodes