/
draw.py
1479 lines (1278 loc) · 56.3 KB
/
draw.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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import networkx as nx
from matplotlib import rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = 'Roboto'
rcParams['font.weight'] = 'normal'
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.ticker import ScalarFormatter
import matplotlib.gridspec as gridspec
from matplotlib import cm
from matplotlib.colors import ListedColormap
import numpy as np
import pandas as pd
import geopandas as gpd
import os
import warnings
import seaborn as sns
# set seaborn style
sns.set()
import plotly.express as px
import plotly.io as pio
import plotly.graph_objs as go
import plotly.offline as pltly
from plotly.colors import n_colors, unconvert_from_RGB_255
from plotly.subplots import make_subplots
from oemof.outputlib import views
from oemof.graph import create_nx_graph
from windnode_abw.model.region.tools import calc_dsm_cap_up, calc_dsm_cap_down
import logging
logger = logging.getLogger('windnode_abw')
PRINT_NAMES = {
'bhkw': "Large-scale CHP",
'bio': "Biogas",
'demand': 'Demand',
'district_heating': 'District Heating',
'gas': "Open-cycle gas turbine",
'grid': "Grid",
'Grid': 'Grid',
'Grid new': 'Grid new',
'grid new': 'Grid new',
'gud': "Combined-cycle gas turbine",
'hydro': "Hydro",
'pv_ground': "PV ground-mounted",
"pv_roof": "PV roof",
'pv_roof_large': "PV roof top (large)",
'pv_roof_small': "PV roof top (small)",
'wind': "Wind",
"export": "Export (national grid)",
'import': "Import (national grid)",
"el_heating": "electrical Heating",
"elenergy": "Direct electric heating",
"fuel_oil": "Oil heating",
"gas_boiler": "Gas (district heating)",
"natural_gas": "Gas heating",
"solar": "Solar thermal heating",
"solar_heat": "Solar heating",
"wood": "Wood heating",
"coal": "Coal heating",
"pth": "Power-to-heat (district heating)",
"pth_ASHP": "Air source heat pump",
"pth_ASHP_nostor": "Air source heat pump, no storage",
"pth_ASHP_stor": "Air source heat pump, storage",
"pth_GSHP": "Ground source heat pump",
"pth_GSHP_nostor": "Ground source heat pump, no storage",
"pth_GSHP_stor": "Ground source heat pump, storage",
"stor_th_large": "Thermal storage (district heating)",
"stor_th_small": "Thermal storage",
"flex_bat_large": "Large-scale battery storage",
"flex_bat_small": "PV system battery storage",
"hh": "Households",
"ind": "Industry",
"rca": "CTS+agriculture",
"conventional": "Conventional",
"el_hh": "Electricity households",
"el_rca": "Electricity CTS+agriculture",
"el_ind": "Electricity industry",
"th_hh_efh": "Heat single-family houses",
"th_hh_mfh": "Heat apartment buildings",
"th_rca": "Heat CTS+agriculture",
"hh_efh": "Single-family houses",
"hh_mfh": "Apartment buildings",
"ABW-export": "Export (regional)",
"ABW-import": "Import (regional)",
"roof": "Area required rel. PV rooftop",
"H_0.1": "Area required rel. PV ground H 0.1-perc agri",
"H_1": "Area required rel. PV ground H 1-perc agri",
"H_2": "Area required rel. PV ground H 2-perc agri",
"HS_0.1": "Area required rel. PV ground HS 0.1-perc agri",
"HS_1": "Area required rel. PV ground HS 1-perc agri",
"HS_2": "Area required rel. PV ground HS 2-perc agri",
"SQ": "Area required rel. Wind legal SQ (VR/EG)",
"s1000f1": "Area required rel. Wind 1000m w forest 10-perc",
"s500f0": "Area required rel. Wind 500m wo forest 10-perc",
"s500f1": "Area required rel. Wind 500m w forest 10-perc",
}
UNITS = {"relative": "%", "hours": "h", "Utilization Rate": "%", "Total Cycles": "cycles", "Full Discharge Hours": "h",
"RE": "MWh", "DSM": "MWh", "Import": "MWh", "Lineload": "%"}
# https://developer.mozilla.org/en-US/docs/Web/CSS/color_value
# https://plotly.com/python/builtin-colorscales/
COLORS = {'bio': 'green',
'district_heating': 'plum',
'grid': 'grey',
'grid new': 'darkgrey',
'Grid': 'grey',
'Grid new': 'darkgrey',
'hydro': 'royalblue',
'pv_ground': 'goldenrod',
'pv_roof_large': 'gold',
'pv_roof_small': 'darkorange',
'wind': 'skyblue',
'conventional': 'grey',
'fuel_oil': 'grey',
'solar_heat': 'peru',
'solar': 'peru',
'el_heating': 'red',
'elenergy': 'red',
'gud': 'teal',
'natural_gas': 'teal',
'bhkw': 'seagreen',
'gas': 'lightgrey',
'gas_boiler': 'lightgrey',
"wood": "maroon",
"coal": "black",
'import': 'limegreen',
'export': 'brown',
'demand': 'darkgray',
'rca': 'darkseagreen',
'hh': 'coral',
'ind': 'lightslategrey',
'el_rca': 'gray',
'el_hh': 'darkmagenta',
'el_ind': 'darkslategray',
'th_hh_efh': 'plum',
'hh_efh': 'plum',
'th_hh_mfh': 'fuchsia',
'hh_mfh': 'fuchsia',
'th_rca': 'crimson',
'ABW-export': 'mediumpurple',
'ABW-import': 'mediumorchid',
"pth": "indianred",
"pth_ASHP_nostor": "lightpink",
"pth_ASHP_stor": "lightpink",
"pth_GSHP_nostor": "lightcoral",
"pth_GSHP_stor": "lightcoral",
"flex_bat_large": "sandybrown",
"flex_bat_small": "burlywood",
"stor_th_large": "rosybrown",
"stor_th_small": "indianred",
}
# Color dict with PRINT_NAMES
COLORS_PRINT = dict()
for key in COLORS.keys():
COLORS_PRINT[PRINT_NAMES.get(key)] = COLORS[key]
def set_colors(steps=21):
# RLI Colors
# CMAP = px.colors.sequential.GnBu_r
# WindNODE Colors
colors = n_colors('rgb(0, 200, 200)', 'rgb(255, 100, 0)', steps, colortype='rgb')
# WindNODE Colormap
cmap = n_colors((0, 200, 200), (255, 100, 0), 21)
cmap = [unconvert_from_RGB_255(i) for i in cmap]
cmap = ListedColormap(cmap)
return cmap, colors
cmap, colors = set_colors()
colors_r = list(reversed(colors))
def draw_graph(grph, mun_ags=None,
edge_labels=True, node_color='#AFAFAF',
edge_color='#CFCFCF', plot=True, node_size=2000,
with_labels=True, arrows=True, layout='neato',
node_pos=None, font_size=10):
"""
Draw a graph (from oemof examples)
Parameters
----------
grph : networkxGraph
A graph to draw.
mun_ags : int
Municipality's AGS. If provided, the graph will contain only nodes from
this municipality.
edge_labels : boolean
Use nominal values of flow as edge label
node_color : dict or string
Hex color code oder matplotlib color for each node. If string, all
colors are the same.
edge_color : string
Hex color code oder matplotlib color for edge color.
plot : boolean
Show matplotlib plot.
node_size : integer
Size of nodes.
with_labels : boolean
Draw node labels.
arrows : boolean
Draw arrows on directed edges. Works only if an optimization_model has
been passed.
layout : string
networkx graph layout, one of: neato, dot, twopi, circo, fdp, sfdp.
"""
if type(node_color) is dict:
node_color = [node_color.get(g, '#AFAFAF') for g in grph.nodes()]
# set drawing options
options = {
'prog': 'dot',
'with_labels': with_labels,
'node_color': node_color,
'edge_color': edge_color,
'node_size': node_size,
'arrows': arrows,
'font_size': font_size
}
if mun_ags is not None:
nodes = [n for n in grph.nodes if str(mun_ags) in n]
nodes_neighbors = [list(nx.all_neighbors(grph, n))
for n in nodes]
nodes = set(nodes + list(set([n for nlist in nodes_neighbors
for n in nlist])))
grph = grph.subgraph(nodes)
grph = nx.relabel_nodes(grph,
lambda x: x.replace('_' + str(mun_ags), ''))
options['node_color'] = [set_node_colors(grph).get(n, '#AFAFAF')
for n in grph.nodes()]
options['node_size'] = 200
options['arrowsize'] = 15
options['with_labels'] = False
options['font_size'] = 10
pos = nx.drawing.nx_agraph.graphviz_layout(grph,
prog='neato',
args='-Gepsilon=0.0001')
nx.draw(grph, pos=pos, **options)
pos = {k: (v[0], v[1] + 10) for k, v in pos.items()}
nx.draw_networkx_labels(grph, pos=pos, **options)
else:
if node_pos is None:
pos = nx.drawing.nx_agraph.graphviz_layout(grph, prog=layout)
else:
pos = node_pos
nx.draw(grph, pos=pos, **options)
labels = nx.get_edge_attributes(grph, 'weight')
nx.draw_networkx_edge_labels(grph, pos=pos, edge_labels=labels)
# show output
if plot is True:
plt.show()
def set_node_colors(grph):
"""Define node colors
Parameters
----------
grph : networkxGraph
A graph to draw.
Returns
-------
:obj:`dict`
Node colors: graph node as key, hex color as val
Notes
-----
Colors made with color brewer (http://colorbrewer2.org)
"""
colors = {}
for node in grph.nodes():
if node[:4] == 'b_el':
colors[node] = '#bdc9e1'
elif node[:6] == 'gen_el':
colors[node] = '#016c59'
elif node[:6] == 'dem_el':
colors[node] = '#67a9cf'
elif node[:9] == 'excess_el':
colors[node] = '#cccccc'
elif node[:11] == 'shortage_el':
colors[node] = '#cccccc'
elif node[:4] == 'line':
colors[node] = '#f7f7f7'
elif node[:8] == 'b_th_dec':
colors[node] = '#fecc5c'
elif node[:10] == 'gen_th_dec':
colors[node] = '#bd0026'
elif node[:10] == 'dem_th_dec':
colors[node] = '#fd8d3c'
elif node[:8] == 'b_th_cen':
colors[node] = '#d7b5d8'
elif node[:10] == 'gen_th_cen':
colors[node] = '#980043'
elif node[:10] == 'dem_th_cen':
colors[node] = '#df65b0'
elif node[:14] == 'flex_bat_large':
colors[node] = '#08519c'
elif node[:14] == 'flex_bat_small':
colors[node] = '#08519c'
elif node[:12] == 'flex_dec_pth':
colors[node] = '#ffffb2'
elif node[:12] == 'flex_cen_pth':
colors[node] = '#ffffb2'
elif node[:8] == 'flex_dsm':
colors[node] = '#3c6ecf'
return colors
def debug_plot_results(esys, region):
"""Plots results of simulation
Parameters
----------
esys : oemof.solph.EnergySystem
Energy system including results
region : :class:`~.model.Region`
Region object
"""
logger.info('Plotting results...')
results = esys.results['main']
# om_flows = esys.results['om_flows']
imex_bus_results = views.node(results, 'b_th_dec_15001000_hh_efh')
imex_bus_results_flows = imex_bus_results['sequences']
# print some sums for import/export bus
print(imex_bus_results_flows.sum())
print(imex_bus_results_flows.info())
# some example plots for bus_el
ax = imex_bus_results_flows.sum(axis=0).plot(kind='barh')
ax.set_title('Sums for optimization period')
ax.set_xlabel('Energy (MWh)')
ax.set_ylabel('Flow')
plt.tight_layout()
plt.show()
imex_bus_results_flows.plot(kind='line', drawstyle='steps-post')
plt.show()
ax = imex_bus_results_flows.plot(kind='bar', stacked=True, linewidth=0, width=1)
ax.set_title('Sums for optimization period')
ax.legend(loc='upper right', bbox_to_anchor=(1, 1))
ax.set_xlabel('Energy (MWh)')
ax.set_ylabel('Flow')
plt.tight_layout()
dates = imex_bus_results_flows.index
tick_distance = int(len(dates) / 7) - 1
ax.set_xticks(range(0, len(dates), tick_distance), minor=False)
ax.set_xticklabels(
[item.strftime('%d-%m-%Y') for item in dates.tolist()[0::tick_distance]],
rotation=90, minor=False)
plt.show()
def sample_plots(region, results):
##############
# PLOT: Grid #
##############
fig, axs = plt.subplots(1, 2)
de = gpd.read_file(os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'data',
'DEU_adm0.shp')).to_crs("EPSG:3035")
de.plot(ax=axs[0], color='white', edgecolor='#aaaaaa')
gdf_region = gpd.GeoDataFrame(region.muns, geometry='geom')
gdf_region['centroid'] = gdf_region['geom'].centroid
gdf_region.plot(ax=axs[0])
gdf_region.plot(ax=axs[1], color='white', edgecolor='#aaaaaa')
for idx, row in gdf_region.iterrows():
axs[1].annotate(s=row['gen'],
xy=(row['geom'].centroid.x, row['geom'].centroid.y),
ha='center',
va='center',
color='#555555',
size=8)
gdf_lines = gpd.GeoDataFrame(region.lines, geometry='geom')
gdf_lines.plot(ax=axs[1], color='#88aaaa', linewidth=1.5, alpha=1)
gdf_buses = gpd.GeoDataFrame(region.buses, geometry='geom')
gdf_buses.plot(ax=axs[1], color='#338888', markersize=6, alpha=1)
for p in [0, 1]:
axs[p].set_yticklabels([])
axs[p].set_xticklabels([])
axs[0].set_title('Region ABW in Deutschland',
fontsize=16,
fontweight='normal')
axs[1].set_title('Region ABW mit Hochspannungsnetz',
fontsize=16,
fontweight='normal')
plt.show()
#######################
# PLOT: RE capacities #
#######################
fig, axs = plt.subplots(2, 2)
gdf_region = gpd.GeoDataFrame(region.muns, geometry='geom')
gdf_region['gen_capacity_pv_roof'] = gdf_region['gen_capacity_pv_roof_small'] + \
gdf_region['gen_capacity_pv_roof_large']
gdf_region.plot(column='gen_capacity_wind', ax=axs[0, 0], legend=True, cmap='viridis')
axs[0, 0].set_title('Wind')
gdf_region.plot(column='gen_capacity_pv_ground', ax=axs[0, 1], legend=True, cmap='viridis')
axs[0, 1].set_title('Photovoltaik FF-Anlagen')
gdf_region.plot(column='gen_capacity_pv_roof', ax=axs[1, 0], legend=True, cmap='viridis')
axs[1, 0].set_title('Photovoltaik Aufdachanlagen')
gdf_region.plot(column='gen_capacity_bio', ax=axs[1, 1], legend=True, cmap='viridis')
axs[1, 1].set_title('Bioenergie')
# plt.axis('off')
for x, y in zip([0, 0, 1, 1], [0, 1, 0, 1]):
axs[x, y].set_yticklabels([])
axs[x, y].set_xticklabels([])
# for idx, row in gdf_region.iterrows():
# axs[x, y].annotate(s=row['gen'],
# xy=(row['geom'].centroid.x, row['geom'].centroid.y),
# ha='center',
# va='center',
# color='#ffffff',
# size=8)
fig.suptitle('Installierte Leistung Erneuerbare Energie in Megawatt',
fontsize=16,
fontweight='normal')
plt.show()
###########################
# PLOT: RE feedin stacked #
###########################
time_start = 2000
timesteps = 240
techs = {'hydro': 'Laufwasser',
'bio': 'Bioenergie',
'wind': 'Windenergie',
'pv_ground': 'Photovoltaik (Freifläche)',
'pv_roof_small': 'Photovoltaik (Aufdach <30 kW)',
'pv_roof_large': 'Photovoltaik (Aufdach >30 kW)',
}
sectors = {'el_ind': 'Industrie',
'el_rca': 'GHD',
'el_hh': 'Haushalte'
}
fig, ax = plt.subplots()
feedin = pd.DataFrame({v: region.feedin_ts[k].sum(axis=1)
for k, v in techs.items()}).iloc[
time_start:time_start + timesteps]
demand = pd.DataFrame({v: region.demand_ts[k].sum(axis=1)
for k, v in sectors.items()}).iloc[
time_start:time_start + timesteps]
residual_load = demand.sum(axis=1) - feedin.sum(axis=1)
(-feedin).plot.area(ax=ax, cmap='viridis')
demand.plot.area(ax=ax, cmap='copper')
residual_load.plot(ax=ax, style='r--', label='Residuallast')
ax.set_title('Strom: Last- und EE-Erzeugungszeitreihen, Residuallast',
fontsize=16,
fontweight='normal')
ax.set_xlabel('Zeit', fontsize=12)
ax.set_ylabel('MW', fontsize=12)
ax.set_ylim(round(min(-feedin.sum(axis=1)) / 100 - 1) * 100,
round(max(demand.sum(axis=1)) / 100 + 1) * 100)
plt.legend()
plt.show()
#############################
# PLOT: Dec. th. generation #
#############################
timesteps = 96
fig, ax = plt.subplots()
th_generation = results['Wärmeerzeugung dezentral nach Technologie'].merge(
results['Wärmeerzeugung Wärmepumpen nach Technologie'], left_index=True, right_index=True).iloc[0:0 + timesteps]
th_generation.plot.area(ax=ax, cmap='viridis') # BrBG
ax.set_title('Wärmeerzeugung dezentral nach Technologie',
fontsize=16,
fontweight='normal')
ax.set_xlabel('Zeit', fontsize=12)
ax.set_ylabel('MW', fontsize=12)
ax.set_ylim(0)
plt.legend()
plt.show()
def plot_grid(region, lines=False, buses=False):
"""plot ABW Region, optional with powerlines and buses"""
with sns.axes_style("white"):
fig, ax = plt.subplots(figsize=(20, 10))
gdf_region = gpd.GeoDataFrame(region.muns, geometry='geom')
# gdf_region.plot(ax=ax, color='white', edgecolor='#aaaaaa')
gdf_region.plot(ax=ax, color=cmap(1), edgecolor='white', alpha=1)
for idx, row in gdf_region.iterrows():
ax.annotate(s=row['gen'],
xy=(row['geom'].centroid.x, row['geom'].centroid.y),
ha='center',
va='bottom',
color='black',
size=14)
gdf_region['centroid'] = gdf_region['geom'].centroid
gdf_centroid = gpd.GeoDataFrame(gdf_region, geometry='centroid')
gdf_centroid.plot(ax=ax, color=cmap(20), markersize=30, alpha=1)
if lines:
gdf_lines = gpd.GeoDataFrame(region.lines, geometry='geom')
gdf_lines.plot(ax=ax, color='#88aaaa', linewidth=1.5, alpha=1)
if buses:
gdf_buses = gpd.GeoDataFrame(region.buses, geometry='geom')
gdf_buses.plot(ax=ax, color='#338888', markersize=6, alpha=1)
ax.set_yticklabels([])
ax.set_xticklabels([])
ax.set_title('Region Anhalt-Bitterfeld-Wittenberg',
fontsize=16,
fontweight='normal')
sns.despine(ax=ax, top=True, bottom=True, left=True, right=True)
plt.show()
# one geoplot to fit in subplots
def plot_geoplot(name, data, region, ax, unit=None, cmap=None, vmin=None, vmax=None):
"""plot geoplot from pd.Series
Parameters
----------
name : str
title of plot
data : pd.Series
data to plot
region : :class:`~.model.Region`
Region object
ax : matplotlib.axes
coordinate system
unit : str
label of colorbar
"""
# Rli Colormap
# cmap = cm.GnBu_r(np.linspace(0,1,40))
# cmap = ListedColormap(cmap[:32,:-1])
# WindNODE Colormap
# cmap = n_colors((0, 200, 200), (255, 100, 0), 21)
# cmap = [unconvert_from_RGB_255(i) for i in cmap]
# cmap = ListedColormap(cmap)
gdf_region = gpd.GeoDataFrame(region.muns.loc[:, ['gen', 'geom']],
geometry='geom')
gdf_region = gdf_region.join(data,
how='inner')
# size the colorbar to plot
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
#
gdf_region.plot(column=data.values,
ax=ax,
legend=True,
cmap=cmap,
cax=cax,
legend_kwds={'label': unit},
vmin=vmin,
vmax=vmax,
)
# Set title, remove ticks/grid
ax.set_title(name)
ax.set_yticklabels([])
ax.set_xticklabels([])
ax.grid(False)
# ######################
# single scenario notebook
# ######################
def plot_snd_total(region, df_supply, df_demand):
"""plot barplot of yearly total supply and demand per ags
Parameters
----------
region : :class:`~.model.Region`
Region object
df_supply : pd.DataFrame
yearly total per ags
df_demand : pd.DataFrame
yearly total per ags
"""
fig = go.Figure()
for tech, data in df_supply.iteritems():
fig.add_trace(go.Bar(x=region.muns['gen'],
y=data / 1e3,
name=PRINT_NAMES[tech],
marker_color=COLORS[tech]))
for tech, data in df_demand.iteritems():
fig.add_trace(go.Bar(x=region.muns['gen'],
y=-data / 1e3,
name=PRINT_NAMES[tech],
marker_color=COLORS[tech],
visible='legendonly'))
fig.update_traces(hovertemplate='%{fullData.name}<br>' +
'%{y:.1f} GWh <br>' +
'<extra></extra>', )
fig.update_layout(
title='Power Supply and Demand',
legend_title="Technology/Sector",
barmode='relative',
height=600,
xaxis={'categoryorder': 'category ascending'},
xaxis_tickfont_size=14,
yaxis=dict(title='GWh',
titlefont_size=16,
tickfont_size=14),
autosize=True)
fig.show()
def plot_split_hbar(data, limit, ax, title=None, unit=None):
"""plot 2 horizontal barplot with data splitted at limit
Parameters
----------
data : pd.Series
indexed values to plot
limit : int/float
threshold to split barplot at
ax : matplotlib.axes
coordinate system
title : str
title describing data
unit : str
xlabel: unit of data
"""
# split data
data_left = data[data < limit]
data_right = data[data >= limit]
ax.set_title(title)
# split subplot
inner = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=ax, wspace=0.35, hspace=0.2)
# left plot
ax1 = plt.subplot(inner[0])
data_left.plot(kind='barh', ax=ax1) # , color=colors_hight(df_data_left.values, 'winter'))
ax1.set_ylabel('AGS')
ax1.set_xlabel(unit)
ax1.set_xlim([0, limit])
ax1.set_title(title, loc='left', fontsize=12)
# right plot
ax2 = plt.subplot(inner[1])
data_right.plot(kind='barh', ax=ax2) # color=colors_hight(df_data_right.values, 'winter'))
ax2.set_ylabel(None)
ax2.set_xlabel(unit)
ax2.set_title(title, loc='left', fontsize=12)
def plot_timeseries(results_scn, kind='Power', **kwargs):
"""plot generation and demand timeseries of either 'electrical' or 'thermal' components
Parameters
----------
results_scn : dict
scenario result
kind : str
'Power' or 'Thermal'
*ags : str/int
ags number or 'ABW' for whole region
"""
# start = kwargs.get('start', region.cfg['date_from'])
# end = kwargs.get('end', region.cfg['date_to'])
ags = kwargs.get('ags', 'ABW')
# remove if ags in multiindex is converted to int
ags = str(ags)
if kind == 'Power':
df_feedin = results_scn['flows_txaxt']['Stromerzeugung']
df_demand = results_scn['flows_txaxt']['Stromnachfrage']
if ags == 'ABW':
df_feedin = df_feedin.sum(level=0) # .loc[start:end,:]
df_demand = df_demand.sum(level=0) # .loc[start:end,:]
df_demand = df_demand.join(
results_scn['flows_txaxt']['Stromnachfrage Wärme'].sum(level=2).sum(axis=1).rename('el_heating'))
else:
# add intra regional exchange
df_feedin = df_feedin.join(results_scn['flows_txaxt']['Intra-regional exchange']['import'].rename(
'ABW-import')) # .loc[(slice(None), ags)])
df_demand = df_demand.join(results_scn['flows_txaxt']['Intra-regional exchange']['export'].rename(
'ABW-export')) # .loc[(slice(None), ags)])
df_feedin = df_feedin.loc[(slice(None), ags), :].sum(level=0) # .loc[start:end,:]
df_demand = df_demand.loc[(slice(None), ags), :].sum(level=0)
el_heating = results_scn['flows_txaxt']['Stromnachfrage Wärme'].loc[(slice(None), slice(None), ags), :].sum(
level='timestamp')
df_demand['el_heating'] = el_heating.sum(axis=1)
elif kind == 'Thermal':
df_feedin = results_scn['flows_txaxt']['Wärmeerzeugung']
df_demand = results_scn['flows_txaxt']['Wärmenachfrage']
if ags == 'ABW':
df_feedin = df_feedin.sum(level=0) # .loc[start:end,:]
df_demand = df_demand.sum(level=0) # .loc[start:end,:]
else:
df_feedin = df_feedin.loc[(slice(None), ags), :].sum(level=0) # .loc[start:end,:]
df_demand = df_demand.loc[(slice(None), ags), :].sum(level=0)
# else:
# raise ValueError("Enter either 'el' or 'th'")
# what is conventional
# df_residual_load = df_demand.sum(axis=1) - df_feedin.drop(columns=['conventional']).sum(axis=1)
fig = go.Figure()
for tech, data in df_feedin.iteritems():
fig.add_trace(go.Scatter(x=data.index,
y=data.values,
name=PRINT_NAMES[tech],
fill='tonexty',
mode='none',
fillcolor=COLORS[tech],
stackgroup='one'))
for tech, data in df_demand.iteritems():
fig.add_trace(go.Scatter(x=data.index,
y=(-data.values),
name=PRINT_NAMES[tech],
fill='tonexty',
mode='none',
fillcolor=COLORS[tech],
stackgroup='two'))
fig.update_xaxes(
title='Zoom',
showspikes=True,
rangeslider_visible=True,
rangeselector=dict(
buttons=list([
dict(count=6, label="6m", step="month", stepmode="backward"),
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=14, label="2w", step="day", stepmode="backward"),
dict(count=7, label="1w", step="day", stepmode="backward"),
dict(count=3, label="3d", step="day", stepmode="backward"),
# dict(step="all")
])
)
)
fig.update_layout(
title=f'{kind} Generation and Demand of {ags}',
legend_title="Technology/Sector",
height=700,
# xaxis={'categoryorder':'category ascending'},
xaxis_tickfont_size=14,
yaxis=dict(
title='MW',
titlefont_size=16,
tickfont_size=14),
autosize=True,
)
fig.update_traces(hovertemplate='%{x}<br>' +
'%{fullData.name} <br>' +
'Power: %{y:.0f} MW <br>' +
'<extra></extra>', ) #
fig.show()
def get_timesteps(region):
timestamps = pd.date_range(start=region.cfg['date_from'],
end=region.cfg['date_to'],
freq=region.cfg['freq'])
steps = len(timestamps)
return steps
def get_storage_ratios(storage_figures, region):
"""calculate storage ratios for heat or electricity
Parameters
----------
storage_figures : pd.DataFrame
DF including: discharge, capacity, power_discharge
Return
---------
storage_ratios : pd.DataFrame
'Full Load Hours', 'Total Cycles', 'Storage Usage Rate'
"""
# full load hours
full_load_hours = storage_figures.discharge / storage_figures.power_discharge
full_load_hours = full_load_hours.fillna(0)
# total
total_cycle = storage_figures.discharge / storage_figures.capacity
total_cycle = total_cycle.fillna(0)
# max
steps = get_timesteps(region)
c_rate = storage_figures.power_discharge / storage_figures.capacity
c_rate[c_rate > 1] = 1
max_cycle = 1 / 2 * steps * c_rate
max_cycle = max_cycle.fillna(0)
# relative
storage_usage_rate = total_cycle / max_cycle * 100
storage_usage_rate = storage_usage_rate.fillna(0)
# combine
storage_ratios = pd.concat([full_load_hours, total_cycle, storage_usage_rate], axis=1,
keys=['Full Discharge Hours', 'Total Cycles', 'Utilization Rate'])
storage_ratios = storage_ratios.swaplevel(axis=1)
return storage_ratios
def plot_storage_ratios(storage_ratios, region, title):
"""plot storage ratios of either heat or electricity
Parameters
----------
storage_ratios : pd.DataFrame
including 'Full Discharge Hours', 'Total Cycles', 'Utilization Rate'
region :
region
title : str
title of the figures
"""
stor_colors = {'Full Discharge Hours': colors[0],
'Total Cycles': colors[10],
'Utilization Rate': colors[20],
'ABW': 'crimson'}
sub_titles = storage_ratios.columns.get_level_values(level=0).unique()
rows = storage_ratios.sum(level=0, axis=1)
subplot_size = (rows != 0).sum() / (rows != 0).sum().sum()
subplot_size = subplot_size.replace(np.inf, 0)
subplot_size = subplot_size.where(subplot_size <= 0.8, 0.8)
subplot_size = subplot_size.where(subplot_size >= 0.2, 0.2)
fig = make_subplots(rows=1, cols=2,
horizontal_spacing=0.2,
column_widths=list(subplot_size),
# column_widths=[0.2, 0.8],
subplot_titles=(sub_titles[0], sub_titles[1]),
specs=[[{"secondary_y": True}, {"secondary_y": True}]])
for subplot, (stor, df_stor) in enumerate(storage_ratios.groupby(level=0, axis=1)):
for ratio, df in df_stor[stor].items():
secondary_y = True if ratio == 'Utilization Rate' else False
visible = 'legendonly' if ratio == 'Full Discharge Hours' else True
df = df[df != 0].dropna()
ags = df.index
df = df.rename(index=region.muns.gen.to_dict())
hovertemplate = f'{ratio}: ' + '%{y:.2f}' + f' {UNITS[ratio]}'
# municipalities
fig.add_trace(
go.Bar(x=df.index,
y=df.values,
orientation='v',
name=ratio,
legendgroup=ratio,
marker_color=stor_colors[ratio],
offsetgroup=ratio,
showlegend=bool(subplot),
visible=visible,
hovertemplate=hovertemplate),
row=1, col=subplot + 1,
secondary_y=secondary_y)
# --- ABW ---
if ratio == 'Total Cycles':
fig.add_trace(
go.Scatter(x=df.index,
y=len(df)*[df.mean()],
orientation='v',
name='ABW',
legendgroup="ABW",
mode='lines',
line=dict(dash='dash'),
marker_color=stor_colors['ABW'],
showlegend=bool(subplot),
visible='legendonly',
hovertemplate=hovertemplate, ),
row=1, col=subplot + 1,
secondary_y=False)
# === Layout ===
fig.update_layout(title=title,
autosize=True,
hovermode="x unified",
legend=dict(traceorder='normal',
orientation="h",
yanchor="bottom",
y=1.05,
xanchor="right",
x=1))
fig.update_yaxes(title_text="Full Cycles/Discharge Hours", row=1, col=1, anchor="x", secondary_y=False)
fig.update_yaxes(title_text="Full Cycles/Discharge Hours", row=1, col=2, anchor="x2", secondary_y=False)
fig.update_yaxes(title_text="Utilization Rate %", row=1, col=1, anchor="x", secondary_y=True)
fig.update_yaxes(title_text="Utilization Rate %", row=1, col=2, anchor="x2", secondary_y=True)
fig.update_xaxes(type='category', tickangle=45)
fig.show()
def plot_key_scenario_results(results_scns, scenarios, cmap_name='WindNODE', scenario_order=None):
if cmap_name == 'WindNODE':
cmap_dot_plot = n_colors((0, 200, 200), (255, 100, 0), len(scenarios))
cmap_dot_plot = [unconvert_from_RGB_255(i) for i in cmap_dot_plot]
else:
cmap_dot_plot = sns.color_palette(cmap_name, len(scenarios))
return_data = {}
plots = {
1: {'highlevel_results': [('Total costs electricity supply', 'EUR'),
('Total costs heat supply', 'EUR'),
('LCOE', 'EUR/MWh'),
('LCOH', 'EUR/MWh'),
('CO2 emissions el.', 'tCO2'),
('CO2 emissions th.', 'tCO2'),
('Electricity generation', 'MWh')],
'results_axlxt': [],
'col_order': ['Scenario', 'Total Costs [bnEUR]', 'LCOE [EUR/MWh]',
'LCOH [EUR/MWh]', 'Specific Emissions [g/kWh]'],
'title': 'Costs and Emissions'
},
2: {'highlevel_results': [('Area required rel. Wind legal SQ (VR/EG)', '%'),
('Area required rel. PV ground H 0.1-perc agri', '%'),
('Electricity exports', 'MWh')],
'results_axlxt': [('Intra-regional exchange', 'export', 'MWh')],
'col_order': ['Scenario', 'RES Area Wind (VR/EG) [%]',
'RES Area PV ground [%]',
'Intra-reg. Exchange [TWh]',
'El. Exports [TWh]'],
'title': 'Land Use and Energy Balance'
},
3: {'highlevel_results': [('Autarky', '%'), ('Net DSM activation', 'MWh'), ('Battery Storage Usage Rate', '%'),
('Heat Storage Usage Rate', '%')],
'results_axlxt': [('DSM Capacities', 'Demand decrease', 'MWh')],
'col_order': ['Scenario', 'Autarky [%]', 'El. Storage Use [%]',
'Heat Storage Use [%]', 'DSM Utilization Rate [%]'],
'title': 'Flexibility Commitment'
}
}
for no, params in plots.items():
#####################################
# get and process highlevel_results #
#####################################
data_hl = pd.DataFrame(
({f'{name} [{unit}]': results_scns[scn]['highlevel_results'][(name, unit)]
for name, unit in params['highlevel_results']}
for scn in scenarios),
index=scenarios
)
if no == 1:
data_hl['Total Costs [bnEUR]'] = (data_hl['Total costs electricity supply [EUR]'] +
data_hl['Total costs heat supply [EUR]']) / 1e9
data_hl['Emissions [MtCO2]'] = (data_hl['CO2 emissions el. [tCO2]'] +
data_hl['CO2 emissions th. [tCO2]']) / 1e6
data_hl['Specific Emissions [g/kWh]'] = data_hl['Emissions [MtCO2]'] / data_hl[