-
Notifications
You must be signed in to change notification settings - Fork 7
/
plotting_results.py
2765 lines (2250 loc) · 79.7 KB
/
plotting_results.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
"""Plotting model results and storing as PDF to result folder
"""
import os
import logging
from collections import defaultdict
import operator
from math import pi
import math
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from scipy import stats
from energy_demand import enduse_func
from energy_demand.plotting import plotting_program
from energy_demand.basic import basic_functions, conversions
from energy_demand.plotting import plotting_styles
from energy_demand.technologies import tech_related
from energy_demand.profiles import load_factors
from energy_demand.plotting import plotting_results
from scipy.interpolate import interp1d
def smooth_data(x_list, y_list, num=500, spider=False):
"""Smooth data
x_list : list
List with hours
# https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html
"""
if spider:
nr_x_values = len(x_list)
min_x_val = min(x_list)
max_x_val = math.pi * 2 #max is tow pi
x_values = np.linspace(min_x_val, max_x_val, num=nr_x_values, endpoint=True)
f2 = interp1d(x_values, y_list, kind='quadratic') #quadratic cubic
smoothed_data_x = np.linspace(
min_x_val,
max_x_val,
num=num,
endpoint=True)
else:
nr_x_values = len(x_list)
min_x_val = min(x_list)
max_x_val = max(x_list)
x_values = np.linspace(min_x_val, max_x_val, num=nr_x_values, endpoint=True)
f2 = interp1d(x_values, y_list, kind='cubic')
smoothed_data_x = np.linspace(
min_x_val,
max_x_val,
num=num,
endpoint=True)
smoothed_data_y = f2(smoothed_data_x)
return smoothed_data_x, smoothed_data_y
def plot_lp_dh_SCRAP(data_dh_modelled):
x_values = range(24)
plt.plot(x_values, list(data_dh_modelled), color='red', label='modelled')
plt.tight_layout()
plt.margins(x=0)
plt.show()
def run_all_plot_functions(
results_container,
reg_nrs,
regions,
lookups,
result_paths,
assumptions,
enduses,
plot_crit
):
"""Summary function to plot all results
"""
if plot_crit['plot_lad_cross_graphs']:
# Plot cross graph where very region is a dot
plot_cross_graphs(
base_yr=2015,
comparison_year=2050,
regions=regions,
ed_year_fueltype_regs_yh=results_container['results_every_year'],
reg_load_factor_y=results_container['reg_load_factor_y'],
fueltype_int=lookups['fueltypes']['electricity'],
fueltype_str='electricity',
fig_name=os.path.join(
result_paths['data_results_PDF'], "comparions_LAD_cross_graph_electricity_by_cy.pdf"),
label_points=False,
plotshow=False)
plot_cross_graphs(
base_yr=2015,
comparison_year=2050,
regions=regions,
ed_year_fueltype_regs_yh=results_container['results_every_year'],
reg_load_factor_y=results_container['reg_load_factor_y'],
fueltype_int=lookups['fueltypes']['gas'],
fueltype_str='gas',
fig_name=os.path.join(
result_paths['data_results_PDF'], "comparions_LAD_cross_graph_gas_by_cy.pdf"),
label_points=False,
plotshow=False)
# ----------
# Plot LAD differences for first and last year
# ----------
try:
plot_lad_comparison(
base_yr=2015,
comparison_year=2050,
regions=regions,
ed_year_fueltype_regs_yh=results_container['results_every_year'],
fueltype_int=lookups['fueltypes']['electricity'],
fueltype_str='electricity',
fig_name=os.path.join(
result_paths['data_results_PDF'], "comparions_LAD_modelled_electricity_by_cy.pdf"),
label_points=False,
plotshow=False)
print("... plotted by-cy LAD energy demand compariosn")
# Plot peak h for every hour
plot_lad_comparison_peak(
base_yr=2015,
comparison_year=2050,
regions=regions,
ed_year_fueltype_regs_yh=results_container['results_every_year'],
fueltype_int=lookups['fueltypes']['electricity'],
fueltype_str='electricity',
fig_name=os.path.join(
result_paths['data_results_PDF'], "comparions_LAD_modelled_electricity_peakh_by_cy.pdf"),
label_points=False,
plotshow=False)
print("... plotted by-cy LAD energy demand compariosn")
except:
pass
# ----------------
# Plot demand for every region over time
# -------------------
if plot_crit['plot_line_for_every_region_of_peak_demand']:
logging.info("... plot fuel per fueltype for every region over annual teimsteps")
plt_one_fueltype_multiple_regions_peak_h(
results_container['results_every_year'],
lookups,
regions,
os.path.join(
result_paths['data_results_PDF'],
'peak_h_total_electricity.pdf'),
fueltype_str_to_plot="electricity")
if plot_crit['plot_fuels_enduses_y']:
logging.info("... plot fuel per fueltype for whole country over annual timesteps")
#... Plot total fuel (y) per fueltype as line chart"
plt_fuels_enduses_y(
results_container['results_every_year'],
lookups,
os.path.join(
result_paths['data_results_PDF'],
'y_fueltypes_all_enduses.pdf'))
# ------------
# Plot stacked annual enduses
# ------------
if plot_crit['plot_stacked_enduses']:
logging.info("plot stacked enduses")
# Residential
plt_stacked_enduse(
assumptions['simulated_yrs'],
results_container['results_enduse_every_year'],
enduses['rs_enduses'],
os.path.join(
result_paths['data_results_PDF'], "stacked_rs_country.pdf"))
# Service
plt_stacked_enduse(
assumptions['simulated_yrs'],
results_container['results_enduse_every_year'],
enduses['ss_enduses'],
os.path.join(
result_paths['data_results_PDF'], "stacked_ss_country.pdf"))
# Industry
plt_stacked_enduse(
assumptions['simulated_yrs'],
results_container['results_enduse_every_year'],
enduses['is_enduses'],
os.path.join(
result_paths['data_results_PDF'], "stacked_is_country_.pdf"))
# ------------------------------
# Plot annual demand for enduses for all submodels
# ------------------------------
if plot_crit['plot_y_all_enduses']:
logging.info("plot annual demand for enduses for all submodels")
plt_stacked_enduse_sectors(
lookups,
assumptions['simulated_yrs'],
results_container['results_enduse_every_year'],
enduses['rs_enduses'],
enduses['ss_enduses'],
enduses['is_enduses'],
os.path.join(result_paths['data_results_PDF'],
"stacked_all_enduses_country.pdf"))
# --------------
# Fuel per fueltype for whole country over annual timesteps
# ----------------
if plot_crit['plot_fuels_enduses_y']:
logging.info("... plot fuel per fueltype for whole country over annual timesteps")
#... Plot total fuel (y) per fueltype as line chart"
plt_fuels_enduses_y(
results_container['results_every_year'],
lookups,
os.path.join(
result_paths['data_results_PDF'],
'y_fueltypes_all_enduses.pdf'))
# ----------
# Plot seasonal typical load profiles
# Averaged load profile per daytpe for a region
# ----------
# ------------------------------------
# Load factors per fueltype and region
# ------------------------------------
if plot_crit['plot_lf'] :
for fueltype_str, fueltype_int in lookups['fueltypes'].items():
logging.info("plot Load factors per fueltype and region")
plot_seasonal_lf(
fueltype_int,
fueltype_str,
results_container['load_factor_seasons'],
reg_nrs,
os.path.join(
result_paths['data_results_PDF'],
'lf_seasonal_{}.pdf'.format(fueltype_str)))
'''plot_lf_y(
fueltype_int,
fueltype_str,
results_container['reg_load_factor_yd'],
reg_nrs,
os.path.join(
result_paths['data_results_PDF'], 'lf_yd_{}.pdf'.format(fueltype_str)))'''
# reg_load_factor_yd = max daily value / average annual daily value
plot_lf_y(
fueltype_int,
fueltype_str,
results_container['reg_load_factor_y'],
reg_nrs,
os.path.join(
result_paths['data_results_PDF'],
'lf_y_{}.pdf'.format(fueltype_str)))
# --------------
# Fuel week of base year
# ----------------
if plot_crit['plot_week_h']:
logging.debug("... plot a full week")
plt_fuels_enduses_week(
results_container['results_every_year'],
lookups,
assumptions['model_yearhours_nrs'],
assumptions['model_yeardays_nrs'],
2015,
os.path.join(result_paths['data_results_PDF'], "tot_all_enduse03.pdf"))
# ------------------------------------
# Plot averaged per season and fueltype
# ------------------------------------
if plot_crit['plot_averaged_season_fueltype']:
base_year = 2015
for year in results_container['av_season_daytype_cy'].keys():
for fueltype_int in results_container['av_season_daytype_cy'][year].keys():
fueltype_str = tech_related.get_fueltype_str(
lookups['fueltypes'], fueltype_int)
plot_load_profile_dh_multiple(
path_fig_folder=result_paths['data_results_PDF'],
path_plot_fig=os.path.join(
result_paths['data_results_PDF'],
'season_daytypes_by_cy_comparison__{}__{}.pdf'.format(year, fueltype_str)),
calc_av_lp_modelled=results_container['av_season_daytype_cy'][year][fueltype_int], # current year
calc_av_lp_real=results_container['av_season_daytype_cy'][base_year][fueltype_int], # base year
calc_lp_modelled=results_container['season_daytype_cy'][year][fueltype_int], # current year
calc_lp_real=results_container['season_daytype_cy'][base_year][fueltype_int], # base year
plot_peak=True,
plot_all_entries=False,
plot_max_min_polygon=True,
plotshow=False,
plot_radar=plot_crit['plot_radar_seasonal'],
max_y_to_plot=120,
fueltype_str=fueltype_str,
year=year)
# ---------------------------------
# Plot hourly peak loads over time for different fueltypes
# --------------------------------
if plot_crit['plot_h_peak_fueltypes']:
plt_fuels_peak_h(
results_container['results_every_year'],
lookups,
os.path.join(
result_paths['data_results_PDF'],
'fuel_fueltypes_peak_h.pdf'))
print("finisthed plotting")
return
def order_polygon(upper_boundary, lower_boundary):
"""Create correct sorting to draw filled polygon
Arguments
---------
upper_boundary
lower_boundary
Returns
-------
"""
min_max_polygon = []
for pnt in upper_boundary:
min_max_polygon.append(pnt)
for pnt in reversed(lower_boundary):
min_max_polygon.append(pnt)
return min_max_polygon
def create_min_max_polygon_from_lines(line_data):
"""
Arguments
---------
line_data : dict
linedata containing info
{'x_value': [y_values]}
"""
upper_boundary = []
lower_bdoundary = []
for x_value, y_value in line_data.items():
min_y = np.min(y_value)
max_y = np.max(y_value)
upper_boundary.append((x_value, min_y))
lower_bdoundary.append((x_value, max_y))
# create correct sorting to draw filled polygon
min_max_polygon = order_polygon(upper_boundary, lower_bdoundary)
return min_max_polygon
def plot_seasonal_lf(
fueltype_int,
fueltype_str,
load_factors_seasonal,
reg_nrs,
path_plot_fig,
plot_individ_lines=False,
plot_max_min_polygon=True
):
"""Plot load factors per region for every year
Arguments
--------
fueltype_int : int
Fueltype_int to print (see lookup)
fueltype_str : str
Fueltype string to print
load_factors_seasonal : dict
Seasonal load factors per season
reg_nrs : int
Number of region
"""
logging.info("... plotting seasonal load factors")
# Set figure size
fig = plt.figure(figsize=plotting_program.cm2inch(8, 8))
ax = fig.add_subplot(1, 1, 1)
# Settings
color_list = {
'winter': 'midnightblue',
'summer': 'olive',
'spring': 'darkgreen',
'autumn': 'gold'}
classes = list(color_list.keys())
#class_colours = list(color_list.values())
# ------------
# Iterate regions and plot load factors for every region
# ------------
if plot_individ_lines:
for reg_nr in range(reg_nrs):
for season, lf_fueltypes_season in load_factors_seasonal.items():
x_values_season_year = []
y_values_season_year = []
for year, lf_fueltype_reg in lf_fueltypes_season.items():
x_values_season_year.append(year)
y_values_season_year.append(lf_fueltype_reg[fueltype_int][reg_nr])
# plot individual saisonal data point
plt.plot(
x_values_season_year,
y_values_season_year,
color=color_list[season],
linewidth=0.2,
alpha=0.2)
# -----------------
# Plot min_max_area
# -----------------
if plot_max_min_polygon:
for season, lf_fueltypes_season in load_factors_seasonal.items():
upper_boundary = []
lower_bdoundary = []
min_max_polygon = plotting_results.create_min_max_polygon_from_lines(lf_fueltypes_season)
#TODO GOOD
'''for year_nr, lf_fueltype_reg in lf_fueltypes_season.items():
# Get min and max of all entries of year of all regions
min_y = np.min(lf_fueltype_reg[fueltype_int])
max_y = np.max(lf_fueltype_reg[fueltype_int])
upper_boundary.append((year_nr, min_y))
lower_bdoundary.append((year_nr, max_y))
# create correct sorting to draw filled polygon
min_max_polygon = order_polygon(upper_boundary, lower_bdoundary)'''
polygon = plt.Polygon(
min_max_polygon,
color=color_list[season],
alpha=0.2,
edgecolor=None,
linewidth=0,
fill='True')
ax.add_patch(polygon)
# ------------------------------------
# Calculate average per season for all regions
# and plot average line a bit thicker
# ------------------------------------
for season in classes:
years = []
average_season_year_years = []
for year in load_factors_seasonal[season].keys():
average_season_year = []
# Iterate over regions
for reg_nr in range(reg_nrs):
average_season_year.append(
load_factors_seasonal[season][year][fueltype_int][reg_nr])
years.append(int(year))
average_season_year_years.append(np.average(average_season_year))
# plot average
plt.plot(
years,
average_season_year_years,
color=color_list[season],
linewidth=0.5,
linestyle='--',
alpha=1.0,
markersize=0.5,
marker='o',
label=season)
# Plot markers for average line
'''plt.plot(
years,
average_season_year_years,
color=color_list[season],
markersize=0.5,
linewidth=0.5,
marker='o')'''
# -----------------
# Axis
# -----------------
plt.ylim(0, 100)
# -----------------
# Axis labelling and ticks
# -----------------
plt.xlabel("years")
plt.ylabel("load factor {} [%]".format(fueltype_str))
base_yr = 2015
minor_interval = 5
major_interval = 10
# Major ticks
major_ticks = np.arange(base_yr,years[-1] + major_interval, major_interval)
ax.set_xticks(major_ticks)
#ax.set_xlabel(major_ticks)
# Minor ticks
minor_ticks = np.arange(base_yr,years[-1] + minor_interval, minor_interval)
ax.set_xticks(minor_ticks, minor=True)
#ax.set_xlabel(minor_ticks)
# ------------
# Plot color legend with colors for every season
# ------------
plt.legend(
ncol=2,
prop={
'family': 'arial',
'size': 5},
loc='best',
frameon=False)
# Tight layout
plt.tight_layout()
plt.margins(x=0)
# Save fig
plt.savefig(path_plot_fig)
plt.close()
def plot_lf_y(
fueltype_int,
fueltype_str,
reg_load_factor_y,
reg_nrs,
path_plot_fig,
plot_individ_lines=False,
plot_max_min_polygon=True
):
"""Plot load factors per region for every year
Arguments
--------
"""
logging.info("... plotting load factors")
# Set figure size
fig = plt.figure(figsize=plotting_program.cm2inch(8, 8))
ax = fig.add_subplot(1, 1, 1)
if plot_individ_lines:
# Line plot for every region over years
for reg_nr in range(reg_nrs):
x_values_year = []
y_values_year = []
for year, lf_fueltype_reg in reg_load_factor_y.items():
x_values_year.append(year)
y_values_year.append(lf_fueltype_reg[fueltype_int][reg_nr])
plt.plot(
x_values_year,
y_values_year,
linewidth=0.2,
color='grey')
if plot_max_min_polygon:
'''lower_bdoundary = []
upper_boundary = []
for year_nr, lf_fueltype_reg in reg_load_factor_y.items():
# Get min and max of all entries of year of all regions
min_y = np.min(lf_fueltype_reg[fueltype_int])
max_y = np.max(lf_fueltype_reg[fueltype_int])
upper_boundary.append((year_nr, min_y))
lower_bdoundary.append((year_nr, max_y))
# create correct sorting to draw filled polygon
min_max_polygon = order_polygon(upper_boundary, lower_bdoundary)'''
min_max_polygon = plotting_results.create_min_max_polygon_from_lines(reg_load_factor_y)
polygon = plt.Polygon(
min_max_polygon,
color='grey',
alpha=0.2,
edgecolor=None,
linewidth=0,
fill='True')
ax.add_patch(polygon)
# -----------------
# Axis
# -----------------
plt.ylim(0, 100)
# -----------------
# Axis labelling
# -----------------
plt.xlabel("years")
plt.ylabel("load factor, fueltpye {} [%]".format(fueltype_str))
years = list(reg_load_factor_y.keys())
base_yr = 2015
# Major ticks
major_interval = 10
major_ticks = np.arange(base_yr, years[-1] + major_interval, major_interval)
ax.set_xticks(major_ticks)
# Minor ticks
minor_interval = 5
minor_ticks = np.arange(base_yr, years[-1] + minor_interval, minor_interval)
ax.set_xticks(minor_ticks, minor=True)
# Tight layout
plt.tight_layout()
plt.margins(x=0)
plt.savefig(path_plot_fig)
plt.close()
def plt_stacked_enduse(
years_simulated,
results_enduse_every_year,
enduses_data,
fig_name
):
"""Plots stacked energy demand
Arguments
----------
years_simulated : list
Simulated years
results_enduse_every_year : dict
Results [year][enduse][fueltype_array_position]
enduses_data :
fig_name : str
Figure name
Note
----
- Sum across all fueltypes
- Not possible to plot single year
https://matplotlib.org/examples/pylab_examples/stackplot_demo.html
"""
nr_of_modelled_years = len(years_simulated)
x_data = np.array(years_simulated)
y_value_arrays = []
legend_entries = []
for enduse_array_nr, enduse in enumerate(enduses_data):
legend_entries.append(enduse)
y_values_enduse_yrs = np.zeros((nr_of_modelled_years))
for year_array_nr, model_year in enumerate(results_enduse_every_year.keys()):
# Sum across all fueltypes
tot_across_fueltypes = np.sum(results_enduse_every_year[model_year][enduse])
# Conversion: Convert GWh per years to GW
yearly_sum_twh = conversions.gwh_to_twh(tot_across_fueltypes)
logging.debug("... model_year {} enduse {} twh {}".format(
model_year, enduse, np.sum(yearly_sum_twh)))
if yearly_sum_twh < 0:
raise Exception("no minus values allowed {} {} {}".format(enduse, yearly_sum_twh, model_year))
y_values_enduse_yrs[year_array_nr] = yearly_sum_twh
# Add array with values for every year to list
y_value_arrays.append(y_values_enduse_yrs)
# Convert to stacked
y_stacked = np.row_stack((y_value_arrays))
# Set figure size
fig = plt.figure(
figsize=plotting_program.cm2inch(8, 8))
ax = fig.add_subplot(1, 1, 1)
color_list = plotting_styles.color_list_scenarios()
# ----------
# Stack plot
# ----------
color_stackplots = color_list[:len(enduses_data)]
ax.stackplot(
x_data,
y_stacked,
colors=color_stackplots)
plt.legend(
legend_entries,
prop={
'family':'arial',
'size': 5},
ncol=2,
loc='upper center',
bbox_to_anchor=(0.5, -0.05),
frameon=False,
shadow=True)
# -------
# Axis
# -------
plt.xticks(years_simulated, years_simulated)
# -------
# Labels
# -------
plt.ylabel("TWh", fontsize=10)
plt.xlabel("Year", fontsize=10)
plt.title("ED whole UK", fontsize=10)
# Tight layout
plt.tight_layout()
plt.margins(x=0)
# Save fig
plt.savefig(fig_name)
plt.close()
def plt_stacked_enduse_sectors(
lookups,
years_simulated,
results_enduse_every_year,
rs_enduses,
ss_enduses,
is_enduses,
fig_name
):
"""Plots summarised endues for the three sectors. Annual
GWh are converted into GW.
Arguments
----------
data : dict
Data container
results_objects :
enduses_data :
Note
----
- Sum across all fueltypes
# INFO Cannot plot a single year?
"""
x_data = years_simulated
nr_submodels = 3
y_data = np.zeros((nr_submodels, len(years_simulated)))
# Set figure size
fig = plt.figure(figsize=plotting_program.cm2inch(8, 8))
ax = fig.add_subplot(1, 1, 1)
for model_year, data_model_run in enumerate(results_enduse_every_year.values()):
submodel = 0
for fueltype_int in range(lookups['fueltypes_nr']):
for enduse in rs_enduses:
# Conversion: Convert gwh per years to gw
yearly_sum_gw = np.sum(data_model_run[enduse][fueltype_int])
yearly_sum_twh = conversions.gwh_to_twh(yearly_sum_gw)
y_data[submodel][model_year] += yearly_sum_twh #yearly_sum_gw
submodel = 1
for fueltype_int in range(lookups['fueltypes_nr']):
for enduse in ss_enduses:
# Conversion: Convert gwh per years to gw
yearly_sum_gw = np.sum(data_model_run[enduse][fueltype_int])
yearly_sum_twh = conversions.gwh_to_twh(yearly_sum_gw)
y_data[submodel][model_year] += yearly_sum_twh #yearly_sum_gw
submodel = 2
for fueltype_int in range(lookups['fueltypes_nr']):
for enduse in is_enduses:
# Conversion: Convert gwh per years to gw
yearly_sum_gw = np.sum(data_model_run[enduse][fueltype_int])
yearly_sum_twh = conversions.gwh_to_twh(yearly_sum_gw)
y_data[submodel][model_year] += yearly_sum_twh #yearly_sum_gw
# Convert to stack
y_stacked = np.row_stack((y_data))
##import matplotlib.colors as colors #for color_name in colors.cnmaes:
color_stackplots = ['darkturquoise', 'orange', 'firebrick']
# ----------
# Stack plot
# ----------
ax.stackplot(
x_data,
y_stacked,
colors=color_stackplots)
# ------------
# Plot color legend with colors for every SUBMODEL
# ------------
leg_labels = ['residential', 'service', 'industry']
plt.legend(
leg_labels,
ncol=1,
prop={
'family': 'arial',
'size': 5},
loc='best',
frameon=False)
# -------
# Axis
# -------
plt.xticks(years_simulated, years_simulated)
plt.axis('tight')
# -------
# Labels
# -------
plt.ylabel("TWh")
plt.xlabel("year")
plt.title("UK ED per sector")
# Tight layout
plt.margins(x=0)
fig.tight_layout()
# Save fig
plt.savefig(fig_name)
plt.close()
def plot_load_curves_fueltype(results_objects, data, fig_name, plotshow=False):
"""Plots stacked end_use for a region
# INFO Cannot plot a single year?
"""
fig, ax = plt.subplots()
nr_y_to_plot = len(results_objects) #number of simluated years
x = range(nr_y_to_plot)
legend_entries = []
# Initialise (number of enduses, number of hours to plot)
y_init = np.zeros((data['lookups']['fueltypes_nr'], nr_y_to_plot))
for fueltype_str, fueltype_int in data['lookups']['fueltypes'].items():
# Legend
legend_entries.append(fueltype_str)
# REad out fueltype specific max h load
data_over_years = []
for model_year_object in results_objects:
# Max hourly load curve of fueltype
fueltype_load_max_h = model_year_object.tot_country_fuel_load_max_h
data_over_years.append(fueltype_load_max_h[fueltype_int][0])
y_init[fueltype_int] = data_over_years
# Plot lines
for line, _ in enumerate(y_init):
plt.plot(y_init[line])
ax.legend(legend_entries)
plt.xticks(range(nr_y_to_plot), range(2015, 2015 + nr_y_to_plot))
plt.axis('tight')
plt.ylabel("Percent %")
plt.xlabel("Simulation years")
plt.title("Load factor of maximum hour across all enduses")
plt.savefig(fig_name)
if plotshow:
plt.show()
plt.close()
else:
plt.close()
def plt_fuels_enduses_week(
results_resid,
lookups,
nr_of_h_to_plot,
model_yeardays_nrs,
year_to_plot,
fig_name
):
"""Plots stacked end_use for all regions. As
input GWh per h are provided, which cancels out to
GW.
Arguments
---------
year_to_plot : int
2015 --> 0
# INFO Cannot plot a single year?
"""
days_to_plot = range(model_yeardays_nrs)
fig, ax = plt.subplots()
legend_entries = []
# Initialise (number of enduses, number of hours to plot)
y_init = np.zeros((lookups['fueltypes_nr'], nr_of_h_to_plot))
for fueltype_str, fueltype_int in lookups['fueltypes'].items():
legend_entries.append(fueltype_str)
# Select year to plot
fuel_all_regions = results_resid[year_to_plot][fueltype_int]
data_over_day = np.zeros((8760))
for region_data in fuel_all_regions:
data_over_day += region_data
y_init[fueltype_int] = data_over_day
# Plot lines
for line, _ in enumerate(y_init):
plt.plot(y_init[line])
ax.legend(legend_entries)
x_tick_pos = []
for day in range(model_yeardays_nrs):
x_tick_pos.append(day * 24)
plt.xticks(x_tick_pos, days_to_plot, color='black')
plt.axis('tight')
plt.legend(
ncol=2,
frameon=False,
prop={
'family': 'arial',
'size': 10},)
plt.ylabel("GW")
plt.xlabel("day")
plt.title("tot annual ED, all enduses, fueltype {}".format(year_to_plot + 2050))
plt.savefig(fig_name)
plt.close()
def plt_fuels_enduses_y(results, lookups, fig_name, plotshow=False):
"""Plot lines with total energy demand for all enduses
per fueltype over the simluation period. Annual GWh
are converted into GW.
Arguments
---------
results : dict
Results for every year and fueltype (yh)
lookups : dict
Lookup fueltypes
fig_name : str
Figure name
Note
----
Values are divided by 1'000
"""
# Set figure size
plt.figure(figsize=plotting_program.cm2inch(14, 8))
# Initialise (number of enduses, number of hours to plot)
y_values_fueltype = {}
for fueltype_str, fueltype_int in lookups['fueltypes'].items():