Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add check method to EnergySystem class #51

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,5 @@ Changelog

0.5.1
-----

* Added EnergySystem.check() to check graph for sanity
14 changes: 14 additions & 0 deletions src/oemof/network/energy_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,20 @@ def flows(self):
for target in source.outputs
}

def check(self):
error_message = (
"Node {n} not part of EnergySystem "
+ "but Flow ({i}, {o}) exists."
)

for n in self.nodes:
for o in n.outputs.keys():
if o not in self.nodes:
raise RuntimeError(error_message.format(n=n, i=n, o=o))
for i in n.inputs.keys():
if i not in self.nodes:
raise RuntimeError(error_message.format(n=n, i=i, o=n))

def dump(self, dpath=None, filename=None):
r"""Dump an EnergySystem instance."""
if dpath is None:
Expand Down
32 changes: 32 additions & 0 deletions tests/test_energy_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,38 @@ def test_add_flow_assignment(self):
assert (node1, node2) in self.es.flows().keys()
assert (node2, node1) in self.es.flows().keys()

def test_check_method(self):
node0 = Node(label="node0")
node1 = Node(label="node1")
node2 = Node(label="node2")
node3 = Node(label="node3", inputs={node2: Edge()})
self.es.check() # empty, no problem

self.es.add(node0)
self.es.check() # single node, no problem

node0.outputs[node1] = Edge()
with pytest.raises(RuntimeError, match="not part of EnergySystem"):
self.es.check() # node1 needs to be added

self.es.add(node1)
self.es.check() # consistent graph added, no problem

# The check method is not needed for these cases.
# I still add them to the test for completeness.
with pytest.raises(KeyError):
node2.outputs[node1] # not allowed anyway
with pytest.raises(KeyError):
node1.inputs[node2] # also not allowed
self.es.check() # graph still consistent

self.es.add(node2)
with pytest.raises(RuntimeError, match="not part of EnergySystem"):
self.es.check() # if node 2 is present, node3 also needs to be

self.es.add(node3)
self.es.check() # Now, everything is fine.

def test_that_node_additions_are_signalled(self):
"""
When a node gets `add`ed, a corresponding signal should be emitted.
Expand Down
Loading