forked from ntnuiotenergy/OpenEMPIRE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscenario_random.py
574 lines (515 loc) · 30.5 KB
/
scenario_random.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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
__author__ = "Stian Backe"
__license__ = "MIT"
__maintainer__ = "Stian Backe"
__email__ = "[email protected]"
import pandas as pd
import numpy as np
import os
def season_month(season):
if season=="winter":
return [1, 2, 3]
elif season=="spring":
return [4, 5, 6]
elif season=="summer":
return [7, 8, 9]
elif season=="fall":
return [10, 11, 12]
def year_season_filter(data, sample_year, season):
data = data.loc[data.year.isin([sample_year]), :]
data = data.loc[data.month.isin(season_month(season)), :]
return data
def remove_time_index(data):
data = data.reset_index(drop=True)
data = data.drop(['time', 'year', 'month', 'dayofweek', 'hour'], axis=1)
return data
def make_datetime(data, time_format):
data["time"] = pd.to_datetime(data["time"],
format=time_format,
exact=False)
data['year'] = data['time'].dt.year
data['month'] = data['time'].dt.month
data['hour'] = data['time'].dt.hour
data['dayofweek'] = data['time'].dt.dayofweek
return data
def gather_regular_sample(data, season, seasons, regularSeasonHours,
sample_hour):
data = data.reset_index(drop=True)
sample_data = data.iloc[sample_hour:sample_hour + regularSeasonHours,:]
# Sort sample_data to start on midnight monday (INACTIVE)
# sample_data = sample_data.sort_values(by=['dayofweek','hour'])
# Drop non-country columns
sample_data = remove_time_index(sample_data)
hours = list(range(1 + regularSeasonHours * seasons.index(season),
regularSeasonHours * (seasons.index(season) + 1) + 1))
return [sample_data, hours]
def sample_generator(data, regularSeasonHours, scenario, season, seasons,
period, generator, sample_hour):
[sample_data, hours] = gather_regular_sample(data, season, seasons,
regularSeasonHours,
sample_hour)
generator_data = pd.DataFrame()
if generator=='Windoffshore' or generator=='Windoffshoregrounded' or generator=='Windoffshorefloating':
startNOnode = 2
else:
startNOnode = 1
for c in sample_data.columns:
if c == "NO":
for i in range(startNOnode, 6):
c_no = c + str(i)
df = pd.DataFrame(
data={'Node': c_no, "IntermitentGenerators": generator,
"Operationalhour": hours,
"Scenario": "scenario" + str(scenario),
"Period": period,
"GeneratorStochasticAvailabilityRaw":
sample_data[c].values})
generator_data = pd.concat([generator_data, df], ignore_index=True)
else:
df = pd.DataFrame(
data={'Node': c, "IntermitentGenerators": generator,
"Operationalhour": hours,
"Scenario": "scenario" + str(scenario),
"Period": period,
"GeneratorStochasticAvailabilityRaw":
sample_data[c].values})
generator_data = pd.concat([generator_data, df], ignore_index=True)
return generator_data
def sample_hydro(data, regularSeasonHours, scenario, season,
seasons, period, sample_hour):
[sample_data, hours] = gather_regular_sample(data, season, seasons,
regularSeasonHours,
sample_hour)
hydro_data = pd.DataFrame()
for c in sample_data.columns:
if c != 'time':
df = pd.DataFrame(
data={'Node': c, "Period": period, "Season": season,
"Operationalhour": hours,
"Scenario": "scenario" + str(scenario),
"HydroGeneratorMaxSeasonalProduction":
sample_data[c].values})
hydro_data = pd.concat([hydro_data, df], ignore_index=True)
return hydro_data
def sample_load(data, regularSeasonHours, scenario, season, seasons,
period, sample_hour):
[sample_data, hours] = gather_regular_sample(data, season, seasons,
regularSeasonHours,
sample_hour)
load = pd.DataFrame()
for c in sample_data.columns:
if c != 'time':
df = pd.DataFrame(
data={'Node': c, "Period": period, "Operationalhour": hours,
"Scenario": "scenario" + str(scenario),
"ElectricLoadRaw_in_MW": sample_data[c].values})
load = pd.concat([load, df], ignore_index=True)
return load
def gather_peak_sample(data, seasons, regularSeasonHours, peakSeasonHours,
country_sample, overall_sample):
data = data.reset_index(drop=True)
country_peak = data.iloc[
int(country_sample - (peakSeasonHours/2)):int(
country_sample + (peakSeasonHours/2)),
:]
overall_peak = data.iloc[
int(overall_sample - (peakSeasonHours/2)):int(
overall_sample + (peakSeasonHours/2)),
:]
# Sort data to start on midnight (INACTIVE)
# country_peak = country_peak.sort_values(by=['hour'])
# overall_peak = overall_peak.sort_values(by=['hour'])
# Drop non-country columns
country_peak = remove_time_index(country_peak)
overall_peak = remove_time_index(overall_peak)
country_hours = list(
range(1 + regularSeasonHours * len(seasons),
regularSeasonHours * len(seasons) + peakSeasonHours + 1)
)
overall_hours = list(
range(1 + regularSeasonHours * len(seasons) + peakSeasonHours,
regularSeasonHours * len(seasons) + 2 * peakSeasonHours + 1)
)
return [country_peak, overall_peak, country_hours, overall_hours]
def sample_hydro_peak(data, seasons, scenario, period, regularSeasonHours,
peakSeasonHours, overall_sample, country_sample):
peak_data = pd.DataFrame()
[country_peak, overall_peak,
country_hours, overall_hours] = gather_peak_sample(data, seasons,
regularSeasonHours,
peakSeasonHours,
country_sample,
overall_sample)
for c in country_peak.columns:
df = pd.DataFrame(
data={'Node': c, "Period": period, "Season": "peak1",
"Operationalhour": country_hours,
"Scenario": "scenario" + str(scenario),
"HydroGeneratorMaxSeasonalProduction":
country_peak[c].values})
peak_data = pd.concat([peak_data, df], ignore_index=True)
df = pd.DataFrame(
data={'Node': c, "Period": period, "Season": "peak2",
"Operationalhour": overall_hours,
"Scenario": "scenario" + str(scenario),
"HydroGeneratorMaxSeasonalProduction":
overall_peak[c].values})
peak_data = pd.concat([peak_data, df], ignore_index=True)
return peak_data
def sample_load_peak(data, seasons, scenario, period, regularSeasonHours,
peakSeasonHours, overall_sample, country_sample):
peak_data = pd.DataFrame()
[country_peak, overall_peak,
country_hours, overall_hours] = gather_peak_sample(data, seasons,
regularSeasonHours,
peakSeasonHours,
country_sample,
overall_sample)
for c in country_peak.columns:
df = pd.DataFrame(
data={'Node': c, "Period": period,
"Operationalhour": country_hours,
"Scenario": "scenario" + str(scenario),
"ElectricLoadRaw_in_MW": country_peak[c].values})
peak_data = pd.concat([peak_data, df], ignore_index=True)
df = pd.DataFrame(
data={'Node': c, "Period": period,
"Operationalhour": overall_hours,
"Scenario": "scenario" + str(scenario),
"ElectricLoadRaw_in_MW": overall_peak[c].values})
peak_data = pd.concat([peak_data, df], ignore_index=True)
return peak_data
def sample_generator_peak(data, seasons, g, scenario,
period, regularSeasonHours, peakSeasonHours,
overall_sample, country_sample):
peak_data = pd.DataFrame()
[country_peak, overall_peak,
country_hours, overall_hours] = gather_peak_sample(data, seasons,
regularSeasonHours,
peakSeasonHours,
country_sample,
overall_sample)
if g=='Windoffshore' or g=='Windoffshoregrounded' or g=='Windoffshorefloating':
startNOnode = 2
else:
startNOnode = 1
for c in country_peak.columns:
if c == "NO":
for i in range(startNOnode, 6):
c_no = c + str(i)
df = pd.DataFrame(
data={'Node': c_no, "IntermitentGenerators": g,
"Operationalhour": country_hours,
"Scenario": "scenario" + str(scenario),
"Period": period,
"GeneratorStochasticAvailabilityRaw":
country_peak[c].values})
peak_data = pd.concat([peak_data, df], ignore_index=True)
df = pd.DataFrame(
data={'Node': c_no, "IntermitentGenerators": g,
"Operationalhour": overall_hours,
"Scenario": "scenario" + str(scenario),
"Period": period,
"GeneratorStochasticAvailabilityRaw":
overall_peak[c].values})
peak_data = pd.concat([peak_data, df], ignore_index=True)
else:
df = pd.DataFrame(
data={'Node': c, "IntermitentGenerators": g,
"Operationalhour": country_hours,
"Scenario": "scenario" + str(scenario),
"Period": period,
"GeneratorStochasticAvailabilityRaw":
country_peak[c].values})
peak_data = pd.concat([peak_data, df], ignore_index=True)
df = pd.DataFrame(
data={'Node': c, "IntermitentGenerators": g,
"Operationalhour": overall_hours,
"Scenario": "scenario" + str(scenario),
"Period": period,
"GeneratorStochasticAvailabilityRaw":
overall_peak[c].values})
peak_data = pd.concat([peak_data, df], ignore_index=True)
return peak_data
def generate_random_scenario(filepath, tab_file_path, scenarios, seasons,
Periods, regularSeasonHours, peakSeasonHours,
dict_countries, time_format, fix_sample,
north_sea):
if fix_sample:
print("Generating scenarios according to key...")
else:
print("Generating random scenarios...")
# Generate dataframes to print as stochastic-files
genAvail = pd.DataFrame()
elecLoad = pd.DataFrame()
hydroSeasonal = pd.DataFrame()
# Load all the raw scenario data
solar_data = pd.read_csv(filepath + "/solar.csv")
windonshore_data = pd.read_csv(filepath + "/windonshore.csv")
windoffshore_data = pd.read_csv(filepath + "/windoffshore.csv")
hydroror_data = pd.read_csv(filepath + "/hydroror.csv")
hydroseasonal_data = pd.read_csv(filepath + "/hydroseasonal.csv")
electricload_data = pd.read_csv(filepath + "/electricload.csv")
# Make datetime columns
solar_data = make_datetime(solar_data, time_format)
windonshore_data = make_datetime(windonshore_data, time_format)
windoffshore_data = make_datetime(windoffshore_data, time_format)
hydroror_data = make_datetime(hydroror_data, time_format)
hydroseasonal_data = make_datetime(hydroseasonal_data, time_format)
electricload_data = make_datetime(electricload_data, time_format)
if fix_sample:
sampling_key = pd.read_csv(filepath + "/sampling_key.csv")
sampling_key = sampling_key.set_index(['Period','Scenario','Season'])
else:
sampling_key = pd.DataFrame(columns=['Period','Scenario','Season','Year','Hour'])
for i in range(1,Periods+1):
for scenario in range(1,scenarios+1):
for s in seasons:
###################
##REGULAR SEASONS##
###################
# Get sample year (2015-2019) for each season/scenario
sample_year = np.random.choice(list(range(2015,2020)))
# Set sample year according to key
if fix_sample:
sample_year = sampling_key.loc[(i,scenario,s),'Year']
# Filter out the hours within the sample year
solar_season = year_season_filter(solar_data,
sample_year,
s)
windonshore_season = year_season_filter(windonshore_data,
sample_year,
s)
windoffshore_season = year_season_filter(windoffshore_data,
sample_year,
s)
hydroror_season = year_season_filter(hydroror_data,
sample_year,
s)
hydroseasonal_season = year_season_filter(hydroseasonal_data,
sample_year,
s)
electricload_season = year_season_filter(electricload_data,
sample_year,
s)
sample_hour = np.random.randint(
0, solar_season.shape[0] - regularSeasonHours - 1)
# Choose sample_hour from key or save sampling key
if fix_sample:
sample_hour = sampling_key.loc[(i,scenario,s),'Hour']
else:
df = pd.DataFrame(data={'Period': i,
'Scenario': scenario,
'Season': s,
'Year': sample_year,
'Hour': sample_hour}, index=[0])
sampling_key = pd.concat([sampling_key, df], ignore_index=True)
# Sample generator availability for regular seasons
genAvail = pd.concat([genAvail,
sample_generator(data=solar_season,
regularSeasonHours=regularSeasonHours,
scenario=scenario, season=s,
seasons=seasons, period=i,
generator="Solar",
sample_hour=sample_hour)],
ignore_index=True)
genAvail = pd.concat([genAvail,
sample_generator(data=windonshore_season,
regularSeasonHours=regularSeasonHours,
scenario=scenario, season=s,
seasons=seasons, period=i,
generator="Windonshore",
sample_hour=sample_hour)],
ignore_index=True)
if north_sea:
genAvail = pd.concat([genAvail,
sample_generator(data=windoffshore_season,
regularSeasonHours=regularSeasonHours,
scenario=scenario, season=s,
seasons=seasons, period=i,
generator="Windoffshoregrounded",
sample_hour=sample_hour)],
ignore_index=True)
genAvail = pd.concat([genAvail,
sample_generator(data=windoffshore_season,
regularSeasonHours=regularSeasonHours,
scenario=scenario, season=s,
seasons=seasons, period=i,
generator="Windoffshorefloating",
sample_hour=sample_hour)],
ignore_index=True)
else:
genAvail = pd.concat([genAvail,
sample_generator(data=windoffshore_season,
regularSeasonHours=regularSeasonHours,
scenario=scenario, season=s,
seasons=seasons, period=i,
generator="Windoffshore",
sample_hour=sample_hour)],
ignore_index=True)
genAvail = pd.concat([genAvail,
sample_generator(data=hydroror_season,
regularSeasonHours=regularSeasonHours,
scenario=scenario, season=s,
seasons=seasons, period=i,
generator="Hydrorun-of-the-river",
sample_hour=sample_hour)],
ignore_index=True)
# Sample electric load for regular seasons
elecLoad = pd.concat([elecLoad,
sample_load(data=electricload_season,
regularSeasonHours=regularSeasonHours,
scenario=scenario, season=s,
seasons=seasons, period=i,
sample_hour=sample_hour)],
ignore_index=True)
# Sample seasonal hydro limit for regular seasons
hydroSeasonal = pd.concat([hydroSeasonal,
sample_hydro(data=hydroseasonal_season,
regularSeasonHours=regularSeasonHours,
scenario=scenario, season=s,
seasons=seasons, period=i,
sample_hour=sample_hour)],
ignore_index=True)
################
##PEAK SEASONS##
################
# Get peak sample year (2015-2019)
sample_year = np.random.choice(list(range(2015,2020)))
if fix_sample:
sample_year = sampling_key.loc[(i,scenario,'peak'),'Year']
else:
df = pd.DataFrame(data={'Period': i,
'Scenario': scenario,
'Season': 'peak',
'Year': sample_year,
'Hour': 0}, index=[0])
sampling_key = pd.concat([sampling_key, df], ignore_index=True)
# Filter out the hours within the sample year
solar_data_year = solar_data.loc[solar_data.year.isin([sample_year]), :]
windonshore_data_year = windonshore_data.loc[windonshore_data.year.isin([sample_year]), :]
windoffshore_data_year = windoffshore_data.loc[windoffshore_data.year.isin([sample_year]), :]
hydroror_data_year = hydroror_data.loc[hydroror_data.year.isin([sample_year]), :]
hydroseasonal_data_year = hydroseasonal_data.loc[hydroseasonal_data.year.isin([sample_year]), :]
electricload_data_year = electricload_data.loc[electricload_data.year.isin([sample_year]), :]
#Peak1: The highest load when all loads are summed together
electricload_data_year_notime = remove_time_index(electricload_data_year)
overall_sample = electricload_data_year_notime.sum(axis=1).idxmax()
#Peak2: The highest load of a single country
max_load_country = electricload_data_year_notime.max().idxmax()
country_sample = electricload_data_year_notime[max_load_country].idxmax()
#Sample generator availability for peak seasons
genAvail = pd.concat([genAvail,
sample_generator_peak(data=solar_data_year,
seasons=seasons,
g="Solar", scenario=scenario, period=i,
regularSeasonHours=regularSeasonHours,
peakSeasonHours=peakSeasonHours,
overall_sample=overall_sample,
country_sample=country_sample)],
ignore_index=True)
genAvail = pd.concat([genAvail,
sample_generator_peak(data=windonshore_data_year,
seasons=seasons,
g="Windonshore", scenario=scenario,
period=i,
regularSeasonHours=regularSeasonHours,
peakSeasonHours=peakSeasonHours,
overall_sample=overall_sample,
country_sample=country_sample)],
ignore_index=True)
if north_sea:
genAvail = pd.concat([genAvail,
sample_generator_peak(data=windoffshore_data_year,
seasons=seasons,
g="Windoffshoregrounded", scenario=scenario,
period=i,
regularSeasonHours=regularSeasonHours,
peakSeasonHours=peakSeasonHours,
overall_sample=overall_sample,
country_sample=country_sample)],
ignore_index=True)
genAvail = pd.concat([genAvail,
sample_generator_peak(data=windoffshore_data_year,
seasons=seasons,
g="Windoffshorefloating", scenario=scenario,
period=i,
regularSeasonHours=regularSeasonHours,
peakSeasonHours=peakSeasonHours,
overall_sample=overall_sample,
country_sample=country_sample)],
ignore_index=True)
else:
genAvail = pd.concat([genAvail,
sample_generator_peak(data=windoffshore_data_year,
seasons=seasons,
g="Windoffshore", scenario=scenario,
period=i,
regularSeasonHours=regularSeasonHours,
peakSeasonHours=peakSeasonHours,
overall_sample=overall_sample,
country_sample=country_sample)],
ignore_index=True)
genAvail = pd.concat([genAvail,
sample_generator_peak(data=hydroror_data_year,
seasons=seasons,
g="Hydrorun-of-the-river",
scenario=scenario, period=i,
regularSeasonHours=regularSeasonHours,
peakSeasonHours=peakSeasonHours,
overall_sample=overall_sample,
country_sample=country_sample)],
ignore_index=True)
#Sample electric load for peak seasons
elecLoad = pd.concat([elecLoad,
sample_load_peak(data=electricload_data_year,
seasons=seasons,
scenario=scenario, period=i,
regularSeasonHours=regularSeasonHours,
peakSeasonHours=peakSeasonHours,
overall_sample=overall_sample,
country_sample=country_sample)],
ignore_index=True)
#Sample seasonal hydro limit for peak seasons
hydroSeasonal = pd.concat([hydroSeasonal,
sample_hydro_peak(data=hydroseasonal_data_year,
seasons=seasons,
scenario=scenario, period=i,
regularSeasonHours=regularSeasonHours,
peakSeasonHours=peakSeasonHours,
overall_sample=overall_sample,
country_sample=country_sample)],
ignore_index=True)
#Replace country codes with country names
genAvail = genAvail.replace({"Node": dict_countries})
elecLoad = elecLoad.replace({"Node": dict_countries})
hydroSeasonal = hydroSeasonal.replace({"Node": dict_countries})
#Make header for .tab-file
genAvail = genAvail[["Node", "IntermitentGenerators", "Operationalhour",
"Scenario", "Period",
"GeneratorStochasticAvailabilityRaw"]]
elecLoad = elecLoad[["Node", "Operationalhour", "Scenario","Period",
'ElectricLoadRaw_in_MW']]
hydroSeasonal = hydroSeasonal[["Node", "Period", "Season",
"Operationalhour", "Scenario",
"HydroGeneratorMaxSeasonalProduction"]]
genAvail.loc[genAvail["GeneratorStochasticAvailabilityRaw"] <= 0.001,"GeneratorStochasticAvailabilityRaw"] = 0
elecLoad.loc[elecLoad['ElectricLoadRaw_in_MW'] <= 0.001,'ElectricLoadRaw_in_MW'] = 0
hydroSeasonal.loc[hydroSeasonal["HydroGeneratorMaxSeasonalProduction"] <= 0.001,"HydroGeneratorMaxSeasonalProduction"] = 0
#Make filepath (if it does not exist) and print .tab-files
if not os.path.exists(tab_file_path):
os.makedirs(tab_file_path)
# Save sampling key
if fix_sample:
sampling_key = sampling_key.reset_index(level=['Period','Scenario','Season'])
sampling_key.to_csv(
tab_file_path + "/sampling_key" + '.csv',
header=True, index=None, mode='w')
genAvail.to_csv(
tab_file_path + "/Stochastic_StochasticAvailability" + '.tab',
header=True, index=None, sep='\t', mode='w')
elecLoad.to_csv(
tab_file_path + "/Stochastic_ElectricLoadRaw" + '.tab',
header=True, index=None, sep='\t', mode='w')
hydroSeasonal.to_csv(
tab_file_path + "/Stochastic_HydroGenMaxSeasonalProduction" + '.tab',
header=True, index=None, sep='\t', mode='w')