forked from tum-ens/urbs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunme.py
197 lines (157 loc) · 5.96 KB
/
runme.py
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
import os
import pandas as pd
import pyomo.environ
import shutil
import urbs
from datetime import datetime
from pyomo.opt.base import SolverFactory
# SCENARIOS
def scenario_base(data):
# do nothing
return data
def scenario_stock_prices(data):
# change stock commodity prices
co = data['commodity']
stock_commodities_only = (co.index.get_level_values('Type') == 'Stock')
co.loc[stock_commodities_only, 'price'] *= 1.5
return data
def scenario_co2_limit(data):
# change global CO2 limit
hacks = data['hacks']
hacks.loc['Global CO2 limit', 'Value'] *= 0.05
return data
def scenario_co2_tax_mid(data):
# change CO2 price in Mid
co = data['commodity']
co.loc[('Mid', 'CO2', 'Env'), 'price'] = 50
return data
def scenario_north_process_caps(data):
# change maximum installable capacity
pro = data['process']
pro.loc[('North', 'Hydro plant'), 'cap-up'] *= 0.5
pro.loc[('North', 'Biomass plant'), 'cap-up'] *= 0.25
return data
def scenario_no_dsm(data):
# empty the DSM dataframe completely
data['dsm'] = pd.DataFrame()
return data
def scenario_all_together(data):
# combine all other scenarios
data = scenario_stock_prices(data)
data = scenario_co2_limit(data)
data = scenario_north_process_caps(data)
return data
def prepare_result_directory(result_name):
""" create a time stamped directory within the result folder """
# timestamp for result directory
now = datetime.now().strftime('%Y%m%dT%H%M')
# create result directory if not existent
result_dir = os.path.join('result', '{}-{}'.format(result_name, now))
if not os.path.exists(result_dir):
os.makedirs(result_dir)
return result_dir
def setup_solver(optim, logfile='solver.log'):
""" """
if optim.name == 'gurobi':
# reference with list of option names
# http://www.gurobi.com/documentation/5.6/reference-manual/parameters
optim.set_options("logfile={}".format(logfile))
# optim.set_options("timelimit=7200") # seconds
# optim.set_options("mipgap=5e-4") # default = 1e-4
elif optim.name == 'glpk':
# reference with list of options
# execute 'glpsol --help'
optim.set_options("log={}".format(logfile))
# optim.set_options("tmlim=7200") # seconds
# optim.set_options("mipgap=.0005")
else:
print("Warning from setup_solver: no options set for solver "
"'{}'!".format(optim.name))
return optim
def run_scenario(input_file, timesteps, scenario, result_dir,
plot_tuples=None, plot_periods=None, report_tuples=None):
""" run an urbs model for given input, time steps and scenario
Args:
input_file: filename to an Excel spreadsheet for urbs.read_excel
timesteps: a list of timesteps, e.g. range(0,8761)
scenario: a scenario function that modifies the input data dict
result_dir: directory name for result spreadsheet and plots
plot_tuples: (optional) list of plot tuples (c.f. urbs.result_figures)
plot_periods: (optional) dict of plot periods (c.f. urbs.result_figures)
report_tuples: (optional) list of (sit, com) tuples (c.f. urbs.report)
Returns:
the urbs model instance
"""
# scenario name, read and modify data for scenario
sce = scenario.__name__
data = urbs.read_excel(input_file)
data = scenario(data)
# create model
prob = urbs.create_model(data, timesteps)
# refresh time stamp string and create filename for logfile
now = prob.created
log_filename = os.path.join(result_dir, '{}.log').format(sce)
# solve model and read results
optim = SolverFactory('glpk') # cplex, glpk, gurobi, ...
optim = setup_solver(optim, logfile=log_filename)
result = optim.solve(prob, tee=True)
# copy input file to result directory
shutil.copyfile(input_file, os.path.join(result_dir, input_file))
# save problem solution (and input data) to HDF5 file
urbs.save(prob, os.path.join(result_dir, '{}.h5'.format(sce)))
# write report to spreadsheet
urbs.report(
prob,
os.path.join(result_dir, '{}.xlsx').format(sce),
report_tuples=report_tuples)
# result plots
urbs.result_figures(
prob,
os.path.join(result_dir, '{}'.format(sce)),
plot_title_prefix=sce.replace('_', ' '),
plot_tuples=plot_tuples,
periods=plot_periods,
figure_size=(24, 9))
return prob
if __name__ == '__main__':
input_file = 'mimo-example.xlsx'
result_name = os.path.splitext(input_file)[0] # cut away file extension
result_dir = prepare_result_directory(result_name) # name + time stamp
# simulation timesteps
(offset, length) = (3500, 168) # time step selection
timesteps = range(offset, offset+length+1)
# plotting commodities/sites
plot_tuples = [
('North', 'Elec'),
('Mid', 'Elec'),
('South', 'Elec'),
(['North', 'Mid', 'South'], 'Elec')]
# detailed reporting commodity/sites
report_tuples = [
('North', 'Elec'), ('Mid', 'Elec'), ('South', 'Elec'),
('North', 'CO2'), ('Mid', 'CO2'), ('South', 'CO2')]
# plotting timesteps
plot_periods = {
'all': timesteps[1:]
}
# add or change plot colors
my_colors = {
'South': (230, 200, 200),
'Mid': (200, 230, 200),
'North': (200, 200, 230)}
for country, color in my_colors.items():
urbs.COLORS[country] = color
# select scenarios to be run
scenarios = [
scenario_base,
scenario_stock_prices,
scenario_co2_limit,
scenario_co2_tax_mid,
scenario_no_dsm,
scenario_north_process_caps,
scenario_all_together]
for scenario in scenarios:
prob = run_scenario(input_file, timesteps, scenario, result_dir,
plot_tuples=plot_tuples,
plot_periods=plot_periods,
report_tuples=report_tuples)