Repository navigation
Expand file tree
/
Copy pathmodel.py
More file actions
419 lines (351 loc) · 12.4 KB
/
Copy pathmodel.py
File metadata and controls
419 lines (351 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# -*- coding: utf-8 -*-
"""
"""
import os
import toml
import pandas as pd
from pyomo.environ import (
ConcreteModel,
Set,
Var,
Objective,
Constraint,
minimize,
NonNegativeReals,
Expression,
Binary,
)
from pyomo.opt import SolverFactory
from plotting import create_plots
def run(scenario=os.path.join("scenarios", "example1")):
"""
"""
with open(os.path.join(scenario, "config.toml")) as config_data:
config = toml.load(config_data)
if (
config["constraints"]["eta_partial"]
and not config["constraints"]["pmin"]
):
raise ValueError(
"If you set `eta_partial`, you also need to set `p_min` in "
"the config.toml file."
)
# set input data file
input_data = os.path.join(scenario, config["model"]["input"], "input.xlsx")
# result dir
rdir = os.path.join(scenario, config["model"]["output"])
# write results
if not os.path.exists(rdir):
os.makedirs(rdir)
else:
user_input = (
input(
"Output directory {} exists. Continue and overwrite "
"(y/[n]):".format(rdir)
)
or "n"
)
if user_input != "y":
print("Stopping process!")
sys.exit()
print("Reading data from `{}`".format(input_data))
# %% DATA
conventional = pd.read_excel(
input_data, sheet_name="conventional", index_col=[0]
)
storage = pd.read_excel(input_data, sheet_name="storage", index_col=[0])
renewable = pd.read_excel(
input_data, sheet_name="renewable", index_col=[0]
)
demand = pd.read_excel(input_data, sheet_name="demand", index_col=[0])
carrier = pd.read_excel(input_data, sheet_name="carrier", index_col=[0])
profiles = pd.read_excel(
input_data, sheet_name="profiles", parse_dates=True
)
units = pd.concat([conventional, renewable, storage], sort=False)
dt = int(config["model"]["t_resolution"])
# %% MODEL
print("Building model...")
m = ConcreteModel(name=config["name"])
# %% SETS
m.TIMESTEPS = Set(
initialize=list(range(len(profiles)))[
config["model"]["t_start"] : config["model"]["t_end"]
][::dt],
ordered=True,
)
m.CONV = Set(initialize=conventional.index)
m.RENEW = Set(initialize=renewable.index)
m.STOR = Set(initialize=storage.index)
m.ALL = m.CONV | m.RENEW
# %% VARIABLES
def p_bounds(m, t, u):
""" Bound of supply variable p for conventional units
"""
return (0, units.at[u, "p_nom"])
# supply variable p of all units
m.p = Var(m.TIMESTEPS, m.ALL, bounds=p_bounds)
# fuel variable for convential power plants
m.h = Var(m.TIMESTEPS, m.CONV, within=NonNegativeReals)
def s_out_bounds(m, t, s):
""" Bounds of output variable for storage units
"""
return (0, storage.at[s, "p_nom_out"])
# storage output variable
m.s_out = Var(m.TIMESTEPS, m.STOR, bounds=s_out_bounds)
def s_in_bounds(m, t, s):
""" Bounds of input variable for storage units
"""
return (0, storage.at[s, "p_nom_in"])
# storage input variable
m.s_in = Var(m.TIMESTEPS, m.STOR, bounds=s_in_bounds)
def level_bounds(m, t, s):
""" Bounds of storage filling level variable
"""
if t == m.TIMESTEPS.first():
return (
storage.at[s, "e_nom"] * storage.at[s, "e_init"],
storage.at[s, "e_nom"] * storage.at[s, "e_init"],
)
else:
return (0, storage.at[s, "e_nom"])
# storage level variable
m.e = Var(m.TIMESTEPS, m.STOR, bounds=level_bounds)
# auxiliary variable for balance constraint
m.aux = Var(m.TIMESTEPS, ["excess", "shortage"], within=NonNegativeReals)
# fix supply (p variable) of renewable energies units of the set "RENEW"
for t in m.TIMESTEPS:
for r in m.RENEW:
m.p[t, r].value = (
renewable.at[r, "p_nom"]
* profiles.at[t, renewable.at[r, "profile"]]
)
m.p[t, r].fix()
# binary status variable to indicate whether unit is on / off for conv Units
m.y = Var(m.TIMESTEPS, m.CONV, within=Binary)
def fuel_consumption(m, t, u):
"""
"""
if config["constraints"]["eta_partial"]:
return (
m.h[t, u]
== (
m.y[t, u] * units.at[u, "a"] + m.p[t, u] * units.at[u, "b"]
)
* 0.2933
) # Mbtu -> MWh
else:
return m.h[t, u] == m.p[t, u] / units.at[u, "eta"]
m.fuel_consumption = Constraint(m.TIMESTEPS, m.CONV, rule=fuel_consumption)
def emissions(m, u):
""" Expression to collect emissions.
"""
emissions = sum(
m.h[t, u]
* dt
* carrier.at[units.at[u, "carrier"], "emission_factor"]
for t in m.TIMESTEPS
)
return emissions
m.emissions = Expression(m.CONV, rule=emissions)
def opex(m, u):
""" Expression to collect operational expenditures used in objective
function.
"""
if u in m.CONV:
opex = (
sum(
(m.h[t, u] * carrier.at[units.at[u, "carrier"], "cost"])
+ units.at[u, "vom"]
for t in m.TIMESTEPS
)
* dt
)
if u in m.STOR:
opex = (
sum(m.s_out[t, u] * storage.at[u, "vom"] for t in m.TIMESTEPS)
* dt
)
if u in m.RENEW:
opex = (
sum(
m.p[t, u]
* (
renewable.at[u, "vom"]
+ carrier.at[units.at[u, "carrier"], "cost"]
)
for t in m.TIMESTEPS
)
* dt
)
return opex
m.opex = Expression(m.ALL | m.STOR, rule=opex)
# %% OBJECTIVE
def obj_rule(m):
""" Objective function of total cost
"""
expr = 0
expr += sum(m.opex[u] for u in m.ALL | m.STOR)
expr += sum(m.aux[t, "shortage"] * 3000 * dt for t in m.TIMESTEPS)
return expr
m.objective = Objective(sense=minimize, rule=obj_rule)
# %% CONSTRAINTS
def electricity_balance(m, t):
""" Energy balance constraint
"""
lhs = 0
lhs += sum(m.p[t, c] for c in m.CONV)
lhs += sum(m.p[t, r] for r in m.RENEW)
lhs += m.aux[t, "shortage"]
lhs += -m.aux[t, "excess"]
lhs += sum(m.s_out[t, s] - m.s_in[t, s] for s in m.STOR)
rhs = (
demand.at["demand", "amount"]
* profiles.at[t, demand.at["demand", "profile"]]
)
return lhs == rhs
# constraint for electricity balance
m.electricity_balance = Constraint(m.TIMESTEPS, rule=electricity_balance)
def p_min_constraint(m, t, c):
""" Minimal supply constraint of unit
"""
expr = (
m.p[t, c]
>= units.at[c, "p_min"] * units.at[c, "p_nom"] * m.y[t, c]
)
return expr
def p_max_constraint(m, t, c):
""" Maximum supply constraint of unit (required for pmin to work)
"""
return (
m.p[t, c]
<= units.at[c, "p_max"] * units.at[c, "p_nom"] * m.y[t, c]
)
if config["constraints"]["pmin"]:
m.p_min_constraint = Constraint(
m.TIMESTEPS, m.CONV, rule=p_min_constraint
)
m.p_max_constraint = Constraint(
m.TIMESTEPS, m.CONV, rule=p_max_constraint
)
# storage balance
def storage_balance(m, t, s):
""" Storage balance, first and last timestep are linked
"""
if t == m.TIMESTEPS.first():
return m.e[t, s] == m.e[m.TIMESTEPS.last(), s]
else:
return (
m.e[t, s]
== m.e[t - 1 * dt, s] * (1 - storage.at[s, "loss"])
+ storage.at[s, "eta_in"] * m.s_in[t, s] * dt
- m.s_out[t, s] / storage.at[s, "eta_out"] * dt
)
m.storage_balance = Constraint(m.TIMESTEPS, m.STOR, rule=storage_balance)
if config["model"]["debug"]:
m.write(
os.path.join(rdir, config["name"] + ".lp"),
io_options={"symbolic_solver_labels": True},
)
# %% SOLVING
print("Solving model...")
# set solver (can use other solver e.g. 'gurobi' if gurobi is installed)
opt = SolverFactory(config["model"]["solver"])
# solve model
# tee=True streams solver standard output in console
meta_results = opt.solve(m, tee=config["model"]["tee"])
# %% POSTPROCESSING
print("Processing results...")
results_data = {i.name: i.get_values() for i in m.component_objects(Var)}
# store results in dataframe
supply_results = pd.DataFrame()
fuel_results = pd.DataFrame()
filling_levels = pd.DataFrame()
demand_results = pd.DataFrame()
for var, val in results_data.items():
if bool(val):
if var in ["p", "s_out"]:
supply_results = pd.concat(
[supply_results, pd.Series(results_data[var]).unstack()],
axis=1,
sort=False,
)
elif var in ["h"]:
fuel_results = pd.concat(
[fuel_results, pd.Series(results_data["h"]).unstack()],
axis=1,
sort=False,
)
elif var == "e":
filling_levels = pd.concat(
[filling_levels, pd.Series(results_data["e"]).unstack()],
axis=1,
sort=False,
)
elif var in ["s_in"]:
demand_results = pd.concat(
[
demand_results,
pd.Series(results_data["s_in"]).unstack(),
],
axis=1,
sort=False,
)
# add shortage and excess
aux_df = pd.Series(results_data["aux"]).unstack()
supply_results["shortage"] = aux_df["shortage"]
demand_results["excess"] = aux_df["excess"]
demand_results["demand"] = (
demand.at["demand", "amount"]
* profiles[demand.at["demand", "profile"]]
).values[config["model"]["t_start"] : config["model"]["t_end"]][::dt]
cost = pd.DataFrame.from_dict(
{k: v() for k, v in m.opex.items()}, orient="index"
)
cost.columns = ["Operational Cost"]
cost.index.name = "Unit"
emissions = pd.DataFrame.from_dict(
{k: v() for k, v in m.emissions.items()}, orient="index"
)
emissions.columns = ["Emissions (in t)"]
emissions.index.name = "Unit"
meta_results.write(
filename=os.path.join(rdir, "model-stats.json"), format="json"
)
demand_results = demand_results.rename(columns={"phs": "phs-in"})
summary = pd.concat([supply_results.sum(), demand_results.sum()])
summary.name = "Energy (in TWh)"
summary = summary.to_frame()
summary.index.name = "Unit"
summary = summary.divide(1e6) * dt
# store results in excel file
writer = pd.ExcelWriter(os.path.join(rdir, "output.xlsx"))
summary.to_excel(writer, "summary", merge_cells=False)
cost.to_excel(writer, "cost", merge_cells=False)
emissions.to_excel(writer, "emissions", merge_cells=False)
supply_results.to_excel(writer, "supply", merge_cells=False)
demand_results.to_excel(writer, "demand", merge_cells=False)
filling_levels.to_excel(writer, "filling_levels", merge_cells=False)
fuel_results.to_excel(writer, "fuel_consumption", merge_cells=False)
writer.save()
print("Success! Stored results in `{}`".format(rdir))
# generate auto plots based on results
plots_dir = create_plots(
rdir, config, supply_results, demand_results, scenario
)
print("Success! Generated plots in {}".format(plots_dir))
if __name__ == "__main__":
import sys
import traceback
try:
if len(sys.argv) < 2:
run()
else:
run(sys.argv[1])
input("Press Enter to exit.")
except:
traceback.print_exc()
print("Oops, something went wrong.")
print("To get help: Post the whole output above in a new issue at:")
print("https://github.com/znes/enwajo/issues")
input("Then press Enter to exit.")