Passed
Pull Request — dev (#850)
by Uwe
01:35
created

transshipment.draw_graph()   B

Complexity

Conditions 5

Size

Total Lines 68
Code Lines 26

Duplication

Lines 68
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 26
dl 68
loc 68
rs 8.7893
c 0
b 0
f 0
cc 5
nop 9

How to fix   Long Method    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
# -*- coding: utf-8 -*-
2
3
"""
4
General description:
5
---------------------
6
This script shows how use the custom component `solph.custom.Link` to build
7
a simple transshipment model.
8
9
10
Installation requirements
11
-------------------------
12
This example requires oemof.solph (v0.5.x), install by:
13
14
    pip install oemof.solph[examples]
15
16
To draw the graph pygraphviz is required, installed by:
17
18
    pip install pygraphviz
19
20
License
21
-------
22
Simon Hilpert - 12.12.2017 - [email protected]
23
24
`MIT license <https://github.com/oemof/oemof-solph/blob/dev/LICENSE>`_
25
"""
26
import networkx as nx
27
import pandas as pd
28
from matplotlib import pyplot as plt
29
from oemof.network.graph import create_nx_graph
30
31
# oemof imports
32
from oemof.solph import Bus
33
from oemof.solph import EnergySystem
34
from oemof.solph import Flow
35
from oemof.solph import Investment
36
from oemof.solph import Model
37
from oemof.solph import components as cmp
38
from oemof.solph import processing
39
from oemof.solph import views
40
from oemof.solph.components.experimental import Link
41
42
try:
43
    import pygraphviz as pygz
44
except ModuleNotFoundError:
45
    pygz = None
46
47
48 View Code Duplication
def draw_graph(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
49
    grph,
50
    edge_labels=True,
51
    node_color="#AFAFAF",
52
    edge_color="#CFCFCF",
53
    plot=True,
54
    node_size=2000,
55
    with_labels=True,
56
    arrows=True,
57
    layout="neato",
58
):
59
    """
60
    Draw a graph. This function will be removed in future versions.
61
62
    Parameters
63
    ----------
64
    grph : networkxGraph
65
        A graph to draw.
66
    edge_labels : boolean
67
        Use nominal values of flow as edge label
68
    node_color : dict or string
69
        Hex color code oder matplotlib color for each node. If string, all
70
        colors are the same.
71
72
    edge_color : string
73
        Hex color code oder matplotlib color for edge color.
74
75
    plot : boolean
76
        Show matplotlib plot.
77
78
    node_size : integer
79
        Size of nodes.
80
81
    with_labels : boolean
82
        Draw node labels.
83
84
    arrows : boolean
85
        Draw arrows on directed edges. Works only if an optimization_model has
86
        been passed.
87
    layout : string
88
        networkx graph layout, one of: neato, dot, twopi, circo, fdp, sfdp.
89
    """
90
    if isinstance(node_color, dict):
91
        node_color = [node_color.get(g, "#AFAFAF") for g in grph.nodes()]
92
93
    # set drawing options
94
    options = {
95
        "prog": "dot",
96
        "with_labels": with_labels,
97
        "node_color": node_color,
98
        "edge_color": edge_color,
99
        "node_size": node_size,
100
        "arrows": arrows,
101
    }
102
103
    # draw graph
104
    pos = nx.drawing.nx_agraph.graphviz_layout(grph, prog=layout)
105
106
    nx.draw(grph, pos=pos, **options)
107
108
    # add edge labels for all edges
109
    if edge_labels is True and plt:
110
        labels = nx.get_edge_attributes(grph, "weight")
111
        nx.draw_networkx_edge_labels(grph, pos=pos, edge_labels=labels)
112
113
    # show output
114
    if plot is True:
115
        plt.show()
116
117
118
datetimeindex = pd.date_range("1/1/2017", periods=3, freq="H")
119
120
es = EnergySystem(timeindex=datetimeindex, infer_last_interval=False)
121
122
b_0 = Bus(label="b_0")
123
124
b_1 = Bus(label="b_1")
125
126
es.add(b_0, b_1)
127
128
es.add(
129
    Link(
130
        label="line_0",
131
        inputs={b_0: Flow(), b_1: Flow()},
132
        outputs={
133
            b_1: Flow(investment=Investment()),
134
            b_0: Flow(investment=Investment()),
135
        },
136
        conversion_factors={(b_0, b_1): 0.95, (b_1, b_0): 0.9},
137
        limit_direction=False,
138
    )
139
)
140
141
142
es.add(
143
    cmp.Source(
144
        label="gen_0",
145
        outputs={b_0: Flow(nominal_value=100, variable_costs=50)},
146
    )
147
)
148
149
es.add(
150
    cmp.Source(
151
        label="gen_1",
152
        outputs={b_1: Flow(nominal_value=100, variable_costs=50)},
153
    )
154
)
155
156
es.add(
157
    cmp.Sink(label="load_0", inputs={b_0: Flow(nominal_value=150, fix=[0, 1])})
158
)
159
160
es.add(
161
    cmp.Sink(label="load_1", inputs={b_1: Flow(nominal_value=150, fix=[1, 0])})
162
)
163
164
m = Model(energysystem=es)
165
166
# m.write('transshipment.lp', io_options={'symbolic_solver_labels': True})
167
168
m.solve(solver="cbc", solve_kwargs={"tee": True, "keepfiles": False})
169
170
m.results()
171
172
graph = create_nx_graph(es, m)
173
174
if pygz is not None:
175
    draw_graph(
176
        graph,
177
        plot=True,
178
        layout="neato",
179
        node_size=3000,
180
        node_color={"b_0": "#cd3333", "b_1": "#7EC0EE", "b_2": "#eeac7e"},
181
    )
182
183
results = processing.results(m)
184
185
print(views.node(results, "gen_0"))
186
print(views.node(results, "gen_1"))
187
188
views.node(results, "line_0")["sequences"].plot(kind="bar")
189
190
# look at constraints of Links in the pyomo model LinkBlock
191
m.LinkBlock.pprint()
192