Completed
Push — dev ( 4c120a...a4ab15 )
by Uwe
18s queued 14s
created

lopf   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 208
Duplicated Lines 32.69 %

Importance

Changes 0
Metric Value
wmc 7
eloc 97
dl 68
loc 208
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
B draw_graph() 68 68 5
B main() 0 88 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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