Passed
Pull Request — dev (#1193)
by Patrik
01:53
created

nested_subnetwork_example.main()   B

Complexity

Conditions 3

Size

Total Lines 209
Code Lines 106

Duplication

Lines 209
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 106
dl 209
loc 209
rs 7
c 0
b 0
f 0
cc 3
nop 0

How to fix   Long Method   

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:

1
import logging
2
import os
3
4
import matplotlib.pyplot as plt
5
import pandas as pd
6
from oemof.tools import logger
7
from oemof.network import SubNetwork
8
from oemof import solph
9
10
from oemof.solph import EnergySystem
11
from oemof.solph import Model
12
from oemof.solph import buses
13
from oemof.solph import components
14
from oemof.solph import create_time_index
15
from oemof.solph import flows
16
from oemof.solph import helpers
17
from oemof.solph import Results
18
19
STORAGE_LABEL = "battery_storage"
20
21
22
def get_data_from_file_path(file_path: str) -> pd.DataFrame:
23
    file_dir = os.path.dirname(os.path.abspath(__file__))
24
    data = pd.read_csv(file_dir + "/" + file_path)
25
    return data
26
27
28 View Code Duplication
def plot_figures_for(element: dict) -> None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
29
    figure, axes = plt.subplots(figsize=(10, 5))
30
    element["sequences"].plot(ax=axes, kind="line", drawstyle="steps-post")
31
    plt.legend(
32
        loc="upper center",
33
        prop={"size": 8},
34
        bbox_to_anchor=(0.5, 1.25),
35
        ncol=2,
36
    )
37
    figure.subplots_adjust(top=0.8)
38
    plt.show()
39
40
41
class Volatile(SubNetwork):
42
43
    def __init__(
44
        self,
45
        label: str,
46
        output_bus: solph.Bus,
47
        timeseries: float | list[float],
48
        nominal_capacity: float,
49
        parent_node=None,
50
    ):
51
        self.output_bus = output_bus
52
        self.timeseries = timeseries
53
        self.nominal_capacity = nominal_capacity
54
55
        super().__init__(
56
            label=label, parent_node=parent_node,
57
        )
58
59
        self.subnode(
60
            solph.components.Source,
61
            local_name="source",
62
            outputs={
63
                self.output_bus: solph.Flow(
64
                    max=self.timeseries, nominal_capacity=self.nominal_capacity
65
                ),
66
            },
67
        )
68
69
70 View Code Duplication
def main():
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
71
    # For models that need a long time to optimise, saving and loading the
72
    # EnergySystem might be advised. By default, we do not do this here. Feel
73
    # free to experiment with this once you understood the rest of the code.
74
75
    # *************************************************************************
76
    # ********** PART 1 - Define and optimise the energy system ***************
77
    # *************************************************************************
78
79
    # Read data file
80
    file_name = "subnetwork_example.csv"
81
    data = get_data_from_file_path(file_name)
82
83
    solver = "cbc"  # 'glpk', 'gurobi',....
84
    debug = False  # Set number_of_timesteps to 3 to get a readable lp-file.
85
    number_of_time_steps = len(data)
86
    solver_verbose = False  # show/hide solver output
87
88
    # initiate the logger (see the API docs for more information)
89
    logger.define_logging(
90
        logfile="oemof_example.log",
91
        screen_level=logging.INFO,
92
        file_level=logging.INFO,
93
    )
94
95
    logging.info("Initialize the energy system")
96
    date_time_index = create_time_index(2012, number=number_of_time_steps)
97
98
    # create the energysystem and assign the time index
99
    energysystem = EnergySystem(
100
        timeindex=date_time_index, infer_last_interval=False
101
    )
102
103
    ##########################################################################
104
    # Create oemof objects
105
    ##########################################################################
106
107
    logging.info("Create oemof objects")
108
109
    # The bus objects were assigned to variables which makes it easier to
110
    # connect components to these buses (see below).
111
112
    # create natural gas bus
113
    bus_gas = buses.Bus(label="natural_gas")
114
115
    # create electricity bus
116
    bus_electricity = buses.Bus(label="electricity")
117
118
    # adding the buses to the energy system
119
    energysystem.add(bus_gas, bus_electricity)
120
121
    # create excess component for the electricity bus to allow overproduction
122
    energysystem.add(
123
        components.Sink(
124
            label="excess_bus_electricity",
125
            inputs={bus_electricity: flows.Flow()},
126
        )
127
    )
128
129
    # create source object representing the gas commodity
130
    energysystem.add(
131
        components.Source(
132
            label="rgas",
133
            outputs={bus_gas: flows.Flow()},
134
        )
135
    )
136
137
    # *** SUB-NETWORK ***************************
138
    # Add a subnetwork for Renewable Energies.
139
    renewables = SubNetwork("renewables")
140
    re_bus = renewables.subnode(buses.Bus, "re_elec")
141
142
    # create fixed source object representing wind power plants
143
    renewables.subnode(
144
        Volatile,
145
        local_name="wind",
146
        output_bus=re_bus,
147
        timeseries=data["wind"],
148
        nominal_capacity=1000000,
149
    )
150
    # create fixed source object representing pv power plants
151
    renewables.subnode(
152
        Volatile,
153
        local_name="pv",
154
        output_bus=re_bus,
155
        timeseries=data["pv"],
156
        nominal_capacity=582000,
157
    )
158
    renewables.subnode(
159
        components.Converter,
160
        local_name="connection",
161
        outputs={bus_electricity: flows.Flow()},
162
        inputs={re_bus: flows.Flow()},
163
    )
164
    energysystem.add(renewables)  # Subnetwork to Energysystem
165
    # *************************************************************
166
167
    # create simple sink object representing the electrical demand
168
    # nominal_value is set to 1 because demand_el is not a normalised series
169
    energysystem.add(
170
        components.Sink(
171
            label="demand",
172
            inputs={
173
                bus_electricity: flows.Flow(
174
                    fix=data["demand_el"], nominal_capacity=1
175
                )
176
            },
177
        )
178
    )
179
180
    # create simple converter object representing a gas power plant
181
    energysystem.add(
182
        components.Converter(
183
            label="pp_gas",
184
            inputs={bus_gas: flows.Flow()},
185
            outputs={
186
                bus_electricity: flows.Flow(
187
                    nominal_capacity=10e10, variable_costs=50
188
                )
189
            },
190
            conversion_factors={bus_electricity: 0.58},
191
        )
192
    )
193
194
    # create storage object representing a battery
195
    nominal_capacity = 10077997
196
    nominal_value = nominal_capacity / 6
197
198
    battery_storage = components.GenericStorage(
199
        nominal_capacity=nominal_capacity,
200
        label=STORAGE_LABEL,
201
        inputs={bus_electricity: flows.Flow(nominal_capacity=nominal_value)},
202
        outputs={
203
            bus_electricity: flows.Flow(
204
                nominal_capacity=nominal_value, variable_costs=0.001
205
            )
206
        },
207
        loss_rate=0.00,
208
        initial_storage_level=None,
209
        inflow_conversion_factor=1,
210
        outflow_conversion_factor=0.8,
211
    )
212
213
    energysystem.add(battery_storage)
214
215
    ##########################################################################
216
    # Optimise the energy system and plot the results
217
    ##########################################################################
218
219
    logging.info("Optimise the energy system")
220
221
    # initialise the operational model
222
    energysystem_model = Model(energysystem)
223
224
    # This is for debugging only. It is not(!) necessary to solve the problem
225
    # and should be set to False to save time and disc space in normal use. For
226
    # debugging the timesteps should be set to 3, to increase the readability
227
    # of the lp-file.
228
    if debug:
229
        file_path = os.path.join(
230
            helpers.extend_basic_path("lp_files"), "basic_example.lp"
231
        )
232
        logging.info(f"Store lp-file in {file_path}.")
233
        io_option = {"symbolic_solver_labels": True}
234
        energysystem_model.write(file_path, io_options=io_option)
235
236
    # if tee_switch is true solver messages will be displayed
237
    logging.info("Solve the optimization problem")
238
    energysystem_model.solve(
239
        solver=solver, solve_kwargs={"tee": solver_verbose}
240
    )
241
242
    results = Results(energysystem_model)
243
244
    # ToDO Implement a filter methode for the Result object to exclude
245
    #  subcomponents of a facade/sub-network
246
    # The following lines are meant to show how the result should look like
247
    # in case the subcomponents should be exclude. There should not be a
248
    # postprocessing it is better to filter the nodes directly
249
250
    # Filter columns that are internal only
251
    keep_columns = [
252
        c
253
        for c in results.flow.columns
254
        if getattr(c[1].label, "parent", None)
255
        != getattr(c[0].label, "parent", None)
256
        or (
257
            getattr(c[0].label, "parent", True) is True
258
            and getattr(c[1].label, "parent", True) is True
259
        )
260
    ]
261
    flow_results_filtered = results.flow[keep_columns].copy()
262
263
    # Replace subcomponent with facade object
264
    for level in [0, 1]:
265
        flow_results_filtered.rename(
266
            columns={
267
                c[level]: getattr(c[level].label, "parent", c[level])
268
                for c in flow_results_filtered.columns
269
            },
270
            level=level,
271
            inplace=True,
272
        )
273
274
    print("**** All results ****")
275
    print(results.flow.sum())
276
277
    print("**** Filtered results ****")
278
    print(flow_results_filtered.sum())
279
280
281
if __name__ == "__main__":
282
    main()
283