Skip to content

flixopt.carrier

Carrier class for energy/material type definitions.

Carriers represent types of energy or materials that flow through buses, such as electricity, heat, gas, or water. They provide consistent styling and metadata across visualizations.

Classes

Carrier

Carrier(name: str, color: str = '', unit: str = '', description: str = '')

Bases: Interface

Definition of an energy or material carrier type.

Carriers represent the type of energy or material flowing through a Bus. They provide consistent color, unit, and description across all visualizations and can be shared between multiple buses of the same type.

Inherits from Interface to provide serialization capabilities.

Parameters:

Name Type Description Default
name str

Identifier for the carrier (e.g., 'electricity', 'heat', 'gas').

required
color str

Hex color string for visualizations (e.g., '#FFD700').

''
unit str

Unit string for display (e.g., 'kW', 'kW_th', 'm³/h').

''
description str

Optional human-readable description.

''

Examples:

Creating custom carriers:

import flixopt as fx

# Define custom carriers
electricity = fx.Carrier('electricity', '#FFD700', 'kW', 'Electrical power')
district_heat = fx.Carrier('district_heat', '#FF6B6B', 'kW_th', 'District heating')
hydrogen = fx.Carrier('hydrogen', '#00CED1', 'kg/h', 'Hydrogen fuel')

# Register with FlowSystem
flow_system.add_carrier(electricity)
flow_system.add_carrier(district_heat)

# Use with buses (just reference by name)
elec_bus = fx.Bus('MainGrid', carrier='electricity')
heat_bus = fx.Bus('HeatingNetwork', carrier='district_heat')

Using predefined carriers from CONFIG:

# Access built-in carriers
elec = fx.CONFIG.Carriers.electricity
heat = fx.CONFIG.Carriers.heat

# Use directly
bus = fx.Bus('Grid', carrier='electricity')

Adding custom carriers to CONFIG:

# Add a new carrier globally
fx.CONFIG.Carriers.add(fx.Carrier('biogas', '#228B22', 'kW', 'Biogas'))

# Now available as
fx.CONFIG.Carriers.biogas
Note

Carriers are compared by name for equality, allowing flexible usage patterns where the same carrier type can be referenced by name string or Carrier object interchangeably.

Initialize a Carrier.

Parameters:

Name Type Description Default
name str

Identifier for the carrier (normalized to lowercase).

required
color str

Hex color string for visualizations.

''
unit str

Unit string for display.

''
description str

Optional human-readable description.

''

Attributes

label property
label: str

Label for container keying (alias for name).

prefix property
prefix: str

The prefix used for naming transformed data (e.g., 'Boiler(Q_th)|status_parameters').

flow_system property
flow_system: FlowSystem

Access the FlowSystem this interface is linked to.

Returns:

Type Description
FlowSystem

The FlowSystem instance this interface belongs to.

Raises:

Type Description
RuntimeError

If interface has not been linked to a FlowSystem yet.

Note

For Elements, this is set during add_elements(). For parameter classes, this is set recursively when the parent Element is registered.

Functions

transform_data
transform_data(name_prefix: str = '') -> None

Transform data to match FlowSystem dimensions.

Carriers don't have time-series data, so this is a no-op.

Parameters:

Name Type Description Default
name_prefix str

Ignored for Carrier.

''
link_to_flow_system(flow_system: FlowSystem, prefix: str = '') -> None

Link this interface and all nested interfaces to a FlowSystem.

This method is called automatically during element registration to enable elements to access FlowSystem properties without passing the reference through every method call. It also sets the prefix used for naming transformed data.

Subclasses with nested Interface objects should override this method to propagate the link to their nested interfaces by calling super().link_to_flow_system(flow_system, prefix) first, then linking nested objects with appropriate prefixes.

Parameters:

Name Type Description Default
flow_system FlowSystem

The FlowSystem to link to

required
prefix str

The prefix for naming transformed data (e.g., 'Boiler(Q_th)')

''

Examples:

Override in a subclass with nested interfaces:

def link_to_flow_system(self, flow_system, prefix: str = '') -> None:
    super().link_to_flow_system(flow_system, prefix)
    if self.nested_interface is not None:
        self.nested_interface.link_to_flow_system(flow_system, f'{prefix}|nested' if prefix else 'nested')

Creating an Interface dynamically during modeling:

# In a Model class
if flow.status_parameters is None:
    flow.status_parameters = StatusParameters()
    flow.status_parameters.link_to_flow_system(self._model.flow_system, f'{flow.label_full}')
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 = 5, overwrite: bool = False)

Save the object to a NetCDF file.

Parameters:

Name Type Description Default
path str | Path

Path to save the NetCDF file. Parent directories are created if they don't exist.

required
compression int

Compression level (0-9)

5
overwrite bool

If True, overwrite existing file. If False, raise error if file exists.

False

Raises:

Type Description
FileExistsError

If overwrite=False and file already exists.

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.

CarrierContainer

CarrierContainer(carriers: list[Carrier] | dict[str, Carrier] | None = None)

Bases: ContainerMixin['Carrier']

Container for Carrier objects.

Uses carrier.name for keying. Provides dict-like access to carriers registered with a FlowSystem.

Examples:

# Access via FlowSystem
carriers = flow_system.carriers

# Dict-like access
elec = carriers['electricity']
'heat' in carriers  # True/False

# Iteration
for name in carriers:
    print(name)

Initialize a CarrierContainer.

Parameters:

Name Type Description Default
carriers list[Carrier] | dict[str, Carrier] | None

Initial carriers to add.

None

Functions

add
add(element: T) -> None

Add an element to the container.

Functions