oemof.network¶
oemof.network.energy_system¶
Basic EnergySystem class
This file is part of project oemof (github.com/oemof/oemof). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location oemof/oemof/energy_system.py
SPDX-FileCopyrightText: Stephan Günther <> SPDX-FileCopyrightText: Uwe Krien <uwe.krien@ifam.fraunhofer.de> SPDX-FileCopyrightText: Simon Hilpert <> SPDX-FileCopyrightText: Cord Kaldemeyer <> SPDX-FileCopyrightText: Patrik Schönfeldt <patrik.schoenfeldt@dlr.de>
SPDX-License-Identifier: MIT
- class oemof.network.energy_system.EnergySystem(*, groupings=None, results=None, timeindex=None, timeincrement=None, temporal=None, nodes=None, entities=None)[source]¶
Bases:
objectDefining an energy supply system to use oemof’s solver libraries.
Note
The list of regions is not necessary to use the energy system with solph.
- Parameters:
entities (list of
Entity, optional) – A list containing the already existingEntitiesthat should be part of the energy system. Stored in theentitiesattribute. Defaults to [] if not supplied.timeindex (pandas.datetimeindex) – Defines the time range and, if equidistant, the timeindex for the energy system
timeincrement (numeric (sequence)) – Define the timeincrement for the energy system
groupings (list) – The elements of this list are used to construct
Groupingsor they are used directly if they are instances ofGrouping. These groupings are then used to aggregate the entities added to this energy system intogroups. By default, there’ll always be one group for eachuidcontaining exactly the entity with the givenuid. See the examples for more information.
- Variables:
entities (list of
Entity) – A list containing theEntitiesthat comprise the energy system.groups (dict) –
results (dictionary) – A dictionary holding the results produced by the energy system. Is None while no results are produced. Currently only set after a call to
optimize()after which it holds the return value ofom.results(). See the documentation of that method for a detailed description of the structure of the results dictionary.timeindex (pandas.index, optional) – Define the time range and increment for the energy system. This is an optional attribute but might be import for other functions/methods that use the EnergySystem class as an input parameter.
Examples
Regardles of additional groupings,
entitieswill always be grouped by theiruid:>>> from oemof.network.network import Node >>> es = EnergySystem() >>> bus = Node(label='electricity') >>> es.add(bus) >>> bus is es.groups['electricity'] True >>> es.dump() 'Attributes dumped to ... >>> es = EnergySystem() >>> es.restore() 'Attributes restored from ... >>> bus is es.groups['electricity'] False >>> es.groups['electricity'] "<oemof.network.network.nodes.Node: 'electricity'>"
For simple user defined groupings, you can just supply a function that computes a key from an
entityand the resulting groups will be sets ofentitiesstored under the returned keys, like in this example, whereentitiesare grouped by their type:>>> es = EnergySystem(groupings=[type]) >>> buses = set(Node(label="Node {}".format(i)) for i in range(9)) >>> es.add(*buses) >>> class Sink(Node): ... pass >>> components = set(Sink(label="Component {}".format(i)) ... for i in range(9)) >>> es.add(*components) >>> buses == es.groups[Node] True >>> components == es.groups[Sink] True
- dump(dpath=None, filename=None, consider_dpath=True)[source]¶
Dump an EnergySystem instance.
- Parameters:
dpath (str) – Path to write your dump in.
filename (str) – Filename to write your dump to.
consider_dpath (bool) – Use separate parameters for path (default: ~/.oemof/) and filename.
- property groups¶
- property node¶
- property nodes¶
- restore(dpath=None, filename=None, consider_dpath=True)[source]¶
Restore an EnergySystem instance.
- Parameters:
dpath (str) – Path to write your dump in.
filename (str) – Filename to write your dump to.
consider_dpath (bool) – Use separate parameters for path (defualt: ~/.oemof/) and filename.
- signals = {<function EnergySystem.add>: <blinker.base.NamedSignal object at 0x7792dada5340; <function EnergySystem.add>>}¶
A dictionary of blinker signals emitted by energy systems.
Currently only one signal is supported. This signal is emitted whenever a node <oemof.network.Node> is add`ed to an energy system. The signal’s `sender is set to the node <oemof.network.Node> that got added to the energy system so that node <oemof.network.Node> have an easy way to only receive signals for when they themselves get added to an energy system.
oemof.network.graph¶
Modules for creating and analysing energy system graphs.
This file is part of project oemof (github.com/oemof/oemof). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location oemof/oemof/graph.py
SPDX-FileCopyrightText: Simon Hilpert <> SPDX-FileCopyrightText: Uwe Krien <uwe.krien@ifam.fraunhofer.de>
SPDX-License-Identifier: MIT
- oemof.network.graph.create_nx_graph(energy_system=None, remove_nodes=None, filename=None, remove_nodes_with_substrings=None, remove_edges=None)[source]¶
Create a networkx.DiGraph for the passed energy system and plot it. See https://networkx.org/documentation/ for more information.
- Parameters:
energy_system (oemof.solph.network.EnergySystem)
filename (str or Path) – Absolute filename (with path) to write your graph in the graphml format. If no filename is given no file will be written.
remove_nodes (list of strings) – Nodes to be removed e.g. [‘node1’, node2’)]
remove_nodes_with_substrings (list of strings) – Nodes that contain substrings to be removed e.g. [‘elec’, ‘heat’)]
remove_edges (list of string tuples) – Edges to be removed e.g. [(‘resource_gas’, ‘gas_balance’)]
Examples
>>> import os >>> import pandas as pd >>> from oemof.network.network import Node >>> from oemof.network.energy_system import EnergySystem >>> import oemof.network.graph as graph >>> datetimeindex = pd.date_range('1/1/2017', periods=3, freq='h') >>> es = EnergySystem(timeindex=datetimeindex) >>> b_gas = Node(label='b_gas') >>> bel1 = Node(label='bel1') >>> bel2 = Node(label='bel2') >>> demand_el = Node(label='demand_el', inputs = [bel1]) >>> pp_gas = Node(label=('pp', 'gas'), ... inputs=[b_gas], ... outputs=[bel1]) >>> line_to2 = Node(label='line_to2', inputs=[bel1], outputs=[bel2]) >>> line_from2 = Node(label='line_from2', ... inputs=[bel2], outputs=[bel1]) >>> es.add(b_gas, bel1, demand_el, pp_gas, bel2, line_to2, line_from2) >>> my_graph = graph.create_nx_graph(es) >>> # export graph as .graphml for programs like Yed where it can be >>> # sorted and customized. this is especially helpful for large graphs >>> # grph.create_nx_graph(es, filename="my_graph.graphml") >>> [my_graph.has_node(nd) ... for nd in ['b_gas', 'bel1', "('pp', 'gas')", 'demand_el', 'tester']] [True, True, True, True, False] >>> list(nx.attracting_components(my_graph)) [{'demand_el'}] >>> sorted(list(nx.strongly_connected_components(my_graph))[1]) ['bel1', 'bel2', 'line_from2', 'line_to2'] >>> new_graph = graph.create_nx_graph(energy_system=es, ... remove_nodes_with_substrings=['b_'], ... remove_nodes=["('pp', 'gas')"], ... remove_edges=[('bel2', 'line_from2')], ... filename='test_graph') >>> [new_graph.has_node(nd) ... for nd in ['b_gas', 'bel1', "('pp', 'gas')", 'demand_el', 'tester']] [False, True, False, True, False] >>> my_graph.has_edge("('pp', 'gas')", 'bel1') True >>> new_graph.has_edge('bel2', 'line_from2') False >>> os.remove('test_graph.graphml')
Notes
Needs graphviz and networkx (>= v.1.11) to work properly. Tested on Ubuntu 16.04 x64 and solydxk (debian 9).
oemof.network.groupings¶
All you need to create groups of stuff in your energy system.
This file is part of project oemof (github.com/oemof/oemof). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location oemof/oemof/groupings.py
SPDX-FileCopyrightText: Stephan Günther <> SPDX-FileCopyrightText: Uwe Krien <uwe.krien@ifam.fraunhofer.de> SPDX-FileCopyrightText: Patrik Schönfeldt <patrik.schoenfeldt@dlr.de>
SPDX-License-Identifier: MIT
- oemof.network.groupings.DEFAULT = <oemof.network.groupings.Grouping object>¶
The default
Grouping.This one is always present in an
energy system. It stores everyentityunder itsuidand raises an error if anotherentitywith the sameuidget’s added to theenergy system.
- class oemof.network.groupings.Entities(key=None, constant_key=None, filter=None, **kwargs)[source]¶
Bases:
GroupingSpecialises
Groupingto groupentitiesintosets.
- class oemof.network.groupings.Flows(key=None, constant_key=None, filter=None, **kwargs)[source]¶
Bases:
EntitiesSpecialises
Groupingto group the flows connected tonodesintosets. Note that this specifically means that thekey, andvaluefunctions act on a set of flows.
- class oemof.network.groupings.FlowsWithNodes(key=None, constant_key=None, filter=None, **kwargs)[source]¶
Bases:
EntitiesSpecialises
Groupingto act on the flows connected tonodesand createsetsof(source, target, flow)tuples. Note that this specifically means that thekey, andvaluefunctions act on sets like these.
- class oemof.network.groupings.Grouping(key=None, constant_key=None, filter=None, **kwargs)[source]¶
Bases:
objectUsed to aggregate
entitiesin anenergy systemintogroups.The way
Groupingswork is that eachGroupinggof an energy system is called whenever anentityis added to the energy system (and for eachentityalready present, if the energy system is created with existing enties). The callg(e, groups), whereeis anentityandgroupsis a dictionary mapping group keys to groups, then uses the three functionskey,valueandmergein the following way:key(e)is called to obtain a keykunder which the group should be stored,value(e)is called to obtain a valuev(the actual group) to store underk,if you supplied a
filter()argument,visfilteredusing that function,otherwise, if there is not yet anything stored under
groups[k],groups[k]is set tov. Otherwisemergeis used to figure out how to mergevinto the old value ofgroups[k], i.e.groups[k]is set tomerge(v, groups[k]).
Instead of trying to use this class directly, have a look at its subclasses, like
Entities, which should cater for most use cases.Notes
When overriding methods using any of the constructor parameters, you don’t have access to
selfin the corresponding function. If you need access toself, subclassGroupingand override the methods in the subclass.A
Groupingmay be called more than once on the same objecte, so one should make sure that user definedGroupinggis idempotent, i.e.g(e, g(e, d)) == g(e, d).- Parameters:
key (callable or hashable) – Specifies (if not callable) or extracts (if callable) a
keyfor eachentityof theenergy system.constant_key (hashable (optional)) – Specifies a constant
key. Keys specified using this parameter are not called but taken as is.value (callable, optional) – Overrides the default behaviour of
value.filter (callable, optional) – If supplied, whatever is returned by
value()isfilteredthrough this. Mostly useful in conjunction with static (i.e. non-callable)keys. Seefilter()for more details.merge (callable, optional) – Overrides the default behaviour of
merge.
- filter(group)[source]¶
Filterthe group returned byvalue()before storing it.Should return a boolean value. If the
groupreturned byvalue()isiterable, this function is used (via Python’sbuiltin filter) to select the values which should be retained ingroup. Ifgroupis notiterable, it is simply called ongroupitself and the return value decides whethergroupis stored (True) or not (False).
- key(node)[source]¶
Obtain a key under which to store the group.
You have to supply this method yourself using the
keyparameter when creatingGroupinginstances.Called for every
nodeof the energy system. Expected to return the key (i.e. a validhashable) under which the groupvalue(node)will be stored. If it should be added to more than one group, return alist(or any other non-hashable,iterable) containing the group keys.Return
Noneif you don’t want to storeein a group.
- merge(new, old)[source]¶
Merge a known
oldgroup with anewone.This method is called if there is already a value stored under
group[key(e)]. In that case,merge(value(e), group[key(e)])is called and should return the new group to store underkey(e).The default behaviour is to raise an error if
newandoldare not identical.
- value(e)[source]¶
Generate the group obtained from
e.This methd returns the actual group obtained from
e. Likekey, it is called for everyein the energy system. If there is no group stored underkey(e),groups[key(e)]is set tovalue(e). Otherwisemerge(value(e), groups[key(e)])is called.The default returns the
entityitself.
oemof.network.network¶
- class oemof.network.network.Edge(input_node=None, output_node=None, flow=None, values=None, *, custom_properties=None)[source]¶
Bases:
EntityBus`es/:class:`Component`s are always connected by an :class:`Edge.Edge`s connect a single :class:`Nodewith another. They are directed and have a (sequence of) value(s) attached to them, so they can be used to represent a flow from a source/an input to a target/an output.- Parameters:
flow, values (object, optional) – The (list of) object(s) representing the values flowing from this edge’s input into its output. Note that these two names are aliases of each other, so flow and values are mutually exclusive.
Note that all of these parameters are also set as attributes with the same
name.
- Label¶
alias of
EdgeLabel
- property flow¶
- classmethod from_object(o)[source]¶
Creates an Edge instance from a single object.
This method inspects its argument and does something different depending on various cases:
If o is an instance of Edge, o is returned unchanged.
If o is a Mapping, the instance is created by calling cls(**o),
In all other cases, o will be used as the values keyword argument to Edge’s constructor.
- property input¶
- property output¶
- class oemof.network.network.Entity(label, *, custom_properties=None)[source]¶
Bases:
objectRepresents an Entity in an energy system graph.
Abstract superclass of the general types of entities of an energy system graph, collecting attributes and operations common to all types of nodes. Users should neither instantiate nor subclass this, but use
Component,Bus,Edgeor one of their subclasses instead.- Parameters:
label (hashable, optional) – Used as the string representation of this node. If this parameter is not an instance of
strit will be converted to a string and the result will be used as this node’slabel, which should be unique with respect to the other nodes in the energy system graph this node belongs to. If this parameter is not supplied, the string representation of this node will instead be generated based on this nodes class and id.custom_properties (dict) – This dictionary that can be used to store information that can be used to easily attach custom information to any Entity.
- property label¶
If this node was given a label on construction, this attribute holds the actual object passed as a parameter. Otherwise node.label is a synonym for str(node).
- class oemof.network.network.Node(label, *, inputs=None, outputs=None, parent_node=None, custom_properties=None)[source]¶
Bases:
EntityA Node of an energy system graph.
- Parameters:
label ((See documentation of class Entity))
inputs (list or dict, optional) – Either a list of this nodes’ input nodes or a dictionary mapping input nodes to corresponding inflows (i.e. input values). List will be converted to dictionary with values set to None.
outputs (list or dict, optional) – Either a list of this nodes’ output nodes or a dictionary mapping output nodes to corresponding outflows (i.e. output values). List will be converted to dictionary with values set to None.
- Variables:
inputs (dict) – A dictionary mapping input nodes to corresponding inflows.
outputs (dict) – A dictionary mapping output nodes to corresponding outflows.
- property depth: int¶
The
Nodeinstances have a depth defined as the depth of their parent (if any) + 1.
- property inputs¶
dict: Dictionary mapping input
EntitiesntoEdge`s from :obj:`nintoself. Ifselfis anEdge, returns a dict containing theEdge’s single input node as the key and the flow as the value.
- property outputs¶
dict: Dictionary mapping output
EntitiesntoEdgesfromselfinton. Ifselfis anEdge, returns a dict containing theEdge’s single output node as the key and the flow as the value.
- subnode(class_, local_name, *args, **kwargs)[source]¶
Create a subnode and add it to this Node.
Create a subnode by calling class_(label, *args, **kwargs) and append the result to self.__subnodes. The purpose of this wrapper is to make sure that subnodes are always label`led with a unique label. This is useful because this allows giving the same `local_name to distinct sub-Node`s in different `Node s.
- Parameters:
class_ (type) – The class of the subnode to create. This class must be a subclass of Node.
local_name (hashable) – The label to use for the subnode.
*args, **kwargs – Additional positional and keyword arguments that will be passed to the constructor of class_ when creating the subnode.
- Returns:
class: Node – The newly created subnode, which is also appended to self.subnodes.
Examples
Create a subnode of type Bus with a label based on the the given local_name, inputs and outputs and append it to the subnodes of this Node.
When >>> from oemof.network import Node, Edge >>> subnetwork = Node(“subnetwork”) >>> input = output = Node(“input”) >>> # Create a subnode of type Node using this convenience function >>> bus = subnetwork.subnode( … Node, “bus”, inputs={input: Edge()}, outputs={output: Edge()} … )
- property subnodes¶
Subnodes of the Node
It is deliberately provided as a tuple to prevent user to append subnodes other than with API methods.