-
Notifications
You must be signed in to change notification settings - Fork 0
/
post_hpc_sensitivity_test_analysis.py
2507 lines (2352 loc) · 85.7 KB
/
post_hpc_sensitivity_test_analysis.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
#!/usr/bin/python3
import json
import math
import matplotlib.colors as mcolors
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import re
import seaborn as sns
from matplotlib import rc, rcParams
from pycirclize import Circos
from tqdm import tqdm
COMBINED_CSV_FILENAME: str = "combined_17_may_post_hpc_sensitivity_test.csv"
INDEX: int = 1
TOTEX_HEADER: str = "Other TOTEX"
rc("font", **{"family": "sans-serif", "sans-serif": ["Arial"]})
# rc("figure", **{"figsize": (48 / 5, 32 / 5)})
rcParams["pdf.fonttype"] = 42
rcParams["ps.fonttype"] = 42
sns.set_context("notebook")
sns.set_style("whitegrid")
# Set custom color-blind colormap
colorblind_palette = sns.color_palette(
[
"#E04606", # Orange
"#F09F52", # Pale orange
"#52C0AD", # Pale green
"#006264", # Green
"#144E56",
"#D8247C", # Pink
"#EDEDED", # Pale pink
"#E7DFBE", # Pale yellow
"#FBBB2C", # Yellow
]
)
sns.set_palette(colorblind_palette)
colorblind_plus_palette = sns.color_palette(
[
"#E04606", # Orange
"#F09F52", # Pale orange
"#EFF2DD",
"#52C0AD", # Pale green
"#006264", # Green
"#144E56",
"#D8247C", # Pink
"#EDEDED", # Pale pink
"#E7DFBE", # Pale yellow
"#FBBB2C", # Yellow
]
)
thesis_palette = sns.color_palette(
[
"#E04606",
"#F9A130",
"#EFF2DD",
"#27BFE6", # SDG 6
"#006264", # Green
"#144E56",
"#D8247C", # Pink
"#EDEDED", # Pale pink
"#E7DFBE", # Pale yellow
"#FBBB2C", # Yellow
]
)
blue_first_thesis_palette = sns.color_palette(
[
"#006264", # Green
"#27BFE6", # SDG 6
"#EFF2DD",
"#F9A130", # Orange
"#E04606", # Dark orange
# "#F5B112", # SDG 7
"#E7DFBE", # Pale yellow
"#EDEDED", # Pale pink
"#D8247C", # Pink
"#FBBB2C", # Yellow
]
)
# Expand the thesis blue-first palette to have double the number of colours
blue_first_thesis_colours = blue_first_thesis_palette.as_hex()
colourmap = mcolors.LinearSegmentedColormap.from_list(
"", np.array(blue_first_thesis_colours), 20
)
blue_first_thesis_palette_7 = sns.color_palette(
colourmap(np.linspace(0, 1, 7)).tolist()
)
sns.set_palette(blue_first_thesis_palette_7)
blue_first_thesis_palette_18 = sns.color_palette(
colourmap(np.linspace(0, 1, 18)).tolist()
)
sns.set_palette(blue_first_thesis_palette_18)
blue_first_thesis_palette_20 = sns.color_palette(
colourmap(np.linspace(0, 1, 20)).tolist()
)
sns.set_palette(blue_first_thesis_palette_20)
# Figure size
# fig, axes = plt.subplots(2, 2, figsize=(48 / 5, 32 / 5))
fig = plt.figure(figsize=(48 / 5, 32 / 5))
##############################
# Fit of reduced temperature #
##############################
# For this fit of reduced temperature, a file can be opened from the analysis, and the
# thermal efficiency of the collector at various reduced-temperature values can be
# plotted. It's then possible to have the reduecd temperature quadratic curves added to
# the plot.
with open(
(
reduced_temperature_plot_filename := os.path.join(
"output_files",
"17_may_24",
"autotherm_sensitivity_of_glass_thermal_conductivity_with_value_0.58.json",
)
)
) as f:
frame_to_plot = pd.DataFrame(
[value for key, value in json.load(f).items() if "run" in key]
)
reduced_temperature_fit = np.poly1d(
np.polyfit(
frame_to_plot["reduced_collector_temperature"].dropna(),
frame_to_plot["thermal_efficiency"].dropna(),
2,
)
)
frame_to_plot["marker"] = [
"h" if row[1]["wind_speed"] == 1 else "H" if row[1]["wind_speed"] == 5 else "D"
for row in frame_to_plot.iterrows()
]
fig = plt.figure(figsize=(48 / 5, 32 / 5))
for marker, sub_frame in frame_to_plot.groupby("marker"):
plt.scatter(
[],
[],
alpha=0,
label=f"Wind speed = {'1' if marker == 'h' else '5' if marker == 'H' else '10'} m/s",
)
sns.scatterplot(
sub_frame,
x="reduced_collector_temperature",
y="thermal_efficiency",
hue="collector_input_temperature",
marker=marker,
alpha=0.5,
s=200,
palette=sns.color_palette(
"RdBu_r" if marker == "h" else "PiYG_r" if marker == "H" else "PRGn", 4
),
linewidth=0,
)
# sub_reduced_temperature_fit = np.poly1d(
# np.polyfit(
# sub_frame["reduced_collector_temperature"],
# sub_frame["thermal_efficiency"],
# 2,
# )
# )
# sns.lineplot(
# x=(
# x_linspace := np.linspace(
# min(sub_frame["reduced_collector_temperature"]),
# max(sub_frame["reduced_collector_temperature"]),
# )
# ),
# y=sub_reduced_temperature_fit(x_linspace),
# color="C4",
# dashes=(2, 2),
# label="Quadratic fit",
# )
plt.xlabel("Reduced collector temperature / Km$^2$/W")
plt.ylabel("Thermal efficiency")
plt.legend(
title="HTF input temperature / $^\circ$C",
fontsize="medium",
title_fontsize="medium",
)
plt.savefig(
"17_may_"
+ reduced_temperature_plot_filename.split("autotherm_sensitivity_of_")[1]
+ f"_{INDEX}.png",
transparent=True,
bbox_inches="tight",
dpi=400,
)
plt.show()
#############################################
# Sensitivity analysis of parameters varied #
#############################################
# This space will be used to plot the sensitivity of the thermal efficiency to the
# various parameters that were explored.
filename_regex = re.compile(
r"autotherm_sensitivity_of_(?P<component_name>absorber|adhesive|air_gap|bond|eva|glass|insulation|pipe|pv|pvt|tedlar)_(?P<parameter_name>.*)_with_value_(?P<value>.*)\.json"
)
run_number_regex = re.compile(r"run_(?P<run_number>\d*)_T.*")
# with open((benchmark_filename := "15_mar_benchmark.json")) as benchmark_file:
with open((benchmark_filename := "30_apr_benchmark.json")) as benchmark_file:
benchmark_data = json.load(benchmark_file)
if not os.path.isfile(COMBINED_CSV_FILENAME):
un_concatenated_dataframes: list[pd.DataFrame] = []
for filename in tqdm(
os.listdir(
(output_directory_name := os.path.join("output_files", "17_may_24"))
),
desc="processing files",
unit="files",
leave=True,
):
with open(os.path.join(output_directory_name, filename)) as output_file:
# Parse the file data
loaded_data = json.load(output_file)
file_dataframe = pd.DataFrame(
[value for key, value in loaded_data.items() if "run" in key]
)
# Add the run number as a column
try:
run_number = [
run_number_regex.match(entry).group("run_number")
for entry in [
sub_entry for sub_entry in loaded_data.keys() if "run" in sub_entry
]
]
except AttributeError:
print("Couldn't match for run name.")
raise
file_dataframe["run_number"] = run_number
# Determine the parameter being varied and the current value of that parameter
match = filename_regex.match(filename)
if match is None:
raise Exception(
f"Could not match the filename '{filename}' with the regex."
)
# Save the component name, parameter name, and value to the dataframe.
file_dataframe["component_name"] = match.group("component_name")
file_dataframe["parameter_name"] = match.group("parameter_name")
file_dataframe["parameter_value"] = match.group("value")
# Append this to the dict of data
un_concatenated_dataframes.append(file_dataframe)
combined_output_frame = pd.concat(un_concatenated_dataframes).reset_index(drop=True)
del un_concatenated_dataframes
# Produce a mapping between run number and the thermal efficiency for the benchmark
# data.
benchmark_thermal_efficiency_map = {
run_number_regex.match(key).group("run_number"): value["thermal_efficiency"]
for key, value in {
k: v for k, v in benchmark_data.items() if "run" in k
}.items()
}
# Determine the percentage difference (increase and decrease welcome) as well as the
# variance in the value from the benchmark value for the thermal efficiency for each
# entry in the dataframe.
combined_output_frame["fractional_thermal_efficiency_change"] = None
combined_output_frame["fractional_parameter_value_change"] = None
combined_output_frame["percentage_thermal_efficiency_change"] = None
combined_output_frame["squared_thermal_efficiency_change"] = None
for index, row in tqdm(
combined_output_frame.iterrows(),
desc="reduced-temperature calculation",
unit="row",
leave=True,
total=len(combined_output_frame),
):
# Compute the values
try:
_fractional_thermal_efficiency_change = (
row["thermal_efficiency"]
- (
_this_benchmark_value := benchmark_thermal_efficiency_map[
row["run_number"]
]
)
) / _this_benchmark_value
except KeyError:
continue
except TypeError:
combined_output_frame.at[index, "fractional_thermal_efficiency_change"] = (
None
)
combined_output_frame.at[index, "percentage_thermal_efficiency_change"] = (
None
)
combined_output_frame.at[index, "squared_thermal_efficiency_change"] = None
continue
_percentage_thermal_efficiency_change = (
100 * _fractional_thermal_efficiency_change
)
_squared_thermal_efficiency_change = _fractional_thermal_efficiency_change**2
# Set the values
combined_output_frame.at[index, "fractional_thermal_efficiency_change"] = (
_fractional_thermal_efficiency_change
)
combined_output_frame.at[index, "percentage_thermal_efficiency_change"] = (
_percentage_thermal_efficiency_change
)
combined_output_frame.at[index, "squared_thermal_efficiency_change"] = (
_squared_thermal_efficiency_change
)
# Sanitise the parameter and componet names
combined_output_frame["component_name"] = [
entry.replace("_", " ").capitalize()
for entry in combined_output_frame["component_name"]
]
combined_output_frame["parameter_name"] = [
entry.replace("_", " ").capitalize()
for entry in combined_output_frame["parameter_name"]
]
with open(COMBINED_CSV_FILENAME, "w") as combined_outputfile:
combined_output_frame.to_csv(combined_outputfile)
else:
with open(COMBINED_CSV_FILENAME, "r") as combined_outputfile:
combined_output_frame = pd.read_csv(combined_outputfile, index_col=0)
def _temp(data):
return [np.sqrt(entry) if entry is not None else None for entry in data]
combined_output_frame["abs_thermal_efficiency_change"] = _temp(combined_output_frame["squared_thermal_efficiency_change"])
###############################################
# Plot a marginal abatement curve--style plot #
###############################################
blue_first_thesis_palette_20 = sns.color_palette(
colourmap(np.linspace(0, 1, 20)).tolist()
)
sns.set_palette(blue_first_thesis_palette_20)
def _fix_component_name(name_to_fix: str) -> str:
"""
Fix un-capitalised names.
Inputs:
- name_to_fix:
The name to fix.
Returns:
The fixed name.
"""
match name_to_fix:
case "Pv":
return "PV"
case "Pvt":
return "PV-T"
case "Eva":
return "EVA"
case _:
return name_to_fix \
combined_output_frame["component_name"] = list(map(_fix_component_name, combined_output_frame["component_name"]))
combined_output_frame["combined_name"] = (
combined_output_frame["component_name"]
+ " "
+ combined_output_frame["parameter_name"]
)
sns.set_style("whitegrid")
sns.set_context("notebook")
# Exclude parameters that have no impact in order to reduce empty space
# Ugly I know!!
masked_combined_output_frame = combined_output_frame[combined_output_frame.combined_name != "Absorber Heat capacity"]
masked_combined_output_frame = masked_combined_output_frame[masked_combined_output_frame.combined_name != "Glass Density"]
masked_combined_output_frame = masked_combined_output_frame[masked_combined_output_frame.combined_name != "Glass Heat capacity"]
masked_combined_output_frame = masked_combined_output_frame[masked_combined_output_frame.combined_name != "PV Density"]
masked_combined_output_frame = masked_combined_output_frame[masked_combined_output_frame.combined_name != "PV Heat capacity"]
# Generate a combined plot with the marker size and shape indicating the irradiance.
parameter_median_squared_fractional_changes: dict[tuple[str, str], float] = {}
for component_name, sub_frame in tqdm(
masked_combined_output_frame[masked_combined_output_frame["solar_irradiance"] == 1000].groupby("component_name"), leave=True
):
for parameter_name, sub_sub_frame in tqdm(
sub_frame.groupby("parameter_name"), leave=False
):
parameter_median_squared_fractional_changes[
component_name, parameter_name
] = float(sub_sub_frame["abs_thermal_efficiency_change"].median())
sorted_medians = sorted(
parameter_median_squared_fractional_changes.items(), key=lambda item: item[1]
)
median_values_by_irradiance = {G: {combined_name: sub_frame["abs_thermal_efficiency_change"].median() for combined_name, sub_frame in masked_combined_output_frame[masked_combined_output_frame["solar_irradiance"] == G].groupby("combined_name")} for G in [200, 400, 600, 800, 1000]}
median_frame_to_plot = pd.concat([pd.DataFrame({"median_abs_change": median_values_by_irradiance[G], "Solar irradiance / W/m$^2$": G}) for G in [200, 400, 600, 800, 1000]], axis=0)
median_frame_to_plot["Component"] = [entry.split(" ")[0].replace("Air", "Air gap") for entry in list(median_frame_to_plot.index)]
fig = plt.figure(figsize=(32 / 5, 32 / 5))
ax = plt.gca()
sns.scatterplot(
(frame_to_plot:=median_frame_to_plot.sort_values(by="median_abs_change", ascending=False)),
y=frame_to_plot.index,
x="median_abs_change",
hue="Component",
hue_order=sorted(set(combined_output_frame["component_name"])),
markers=["h", "H", "s", "D", "P"],
s=150,
alpha=0.5,
style="Solar irradiance / W/m$^2$",
ax=ax,
edgecolor="black"
)
# ax.tick_params(axis="x", rotation=90)
ax.set_ylabel("")
ax.set_xlabel("Median absolute fractional change in thermal efficiency")
ax.set_xscale("log")
ax.axvline(0.01, linestyle="--", color="grey", label="1% impact")
ax.axvline(0.042, linestyle="-.", color="grey", label="4.2% impact")
ax.set_xlim((min_ylim:=10**(-4)), 1/3)
ax.axvspan(min_ylim, 0.042, color="grey",
zorder=0,
label="Rejected parameters", alpha=0.1)
ax.axvspan(0.01, 0.042, color="C0",
zorder=0,
label="Limited impact", alpha=0.1)
legend = ax.legend(fancybox=True, framealpha=1, facecolor="white", bbox_to_anchor=(1, 1))
# legend.set_title("Component")
frame = legend.get_frame()
frame.set_facecolor("white")
frame.set_alpha(1)
plt.savefig(
f"abs_scatter_sensitivity_autotherm_all_irradiances_{INDEX}.png",
transparent=True,
format="png",
dpi=400,
bbox_inches="tight",
)
# fig = plt.figure(figsize=(48 / 5, 32 / 5))
# ax = plt.gca()
# sns.scatterplot(
# (frame_to_plot:=median_frame_to_plot.sort_values(by="median_abs_change", ascending=True)),
# x=frame_to_plot.index,
# y="median_abs_change",
# hue="Component",
# hue_order=sorted(set(combined_output_frame["component_name"])),
# marker="h",
# alpha=0.5,
# s=200,
# size="Solar irradiance / W/m$^2$",
# ax=ax,
# )
# ax.tick_params(axis="x", rotation=90)
# ax.set_xlabel("")
# ax.set_ylabel("Median absolute fractional change in thermal efficiency")
# ax.set_yscale("log")
# ax.axhline(0.01, linestyle="--", color="grey", label="1% impact")
# ax.axhline(0.042, linestyle="-.", color="grey", label="4.2% impact")
# ax.set_ylim((min_ylim:=10**(-13)), 10)
# ax.axhspan(min_ylim, 0.042, color="grey",
# zorder=0,
# label="Rejected parameters", alpha=0.1)
# ax.axhspan(0.01, 0.042, color="C0",
# zorder=0,
# label="Limited impact", alpha=0.1)
# legend = ax.legend(loc='lower right', fancybox=True, framealpha=1, facecolor="white")
# # legend.set_title("Component")
# frame = legend.get_frame()
# frame.set_facecolor("white")
# frame.set_alpha(1)
# plt.savefig(
# f"abs_scatter_sensitivity_autotherm_all_irradiances_{INDEX}.png",
# transparent=True,
# format="png",
# dpi=300,
# bbox_inches="tight",
# )
median_frame_to_plot = median_frame_to_plot.sort_values(by="median_abs_change", ascending=True)
# Generate separate plots disaggregated by irradiance
for G in tqdm([200, 400, 600, 800, 1000]):
parameter_median_squared_fractional_changes: dict[tuple[str, str], float] = {}
parameter_mean_squared_fractional_changes: dict[tuple[str, str], float] = {}
frame_to_plot = masked_combined_output_frame[
masked_combined_output_frame["solar_irradiance"] == G
]
for component_name, sub_frame in tqdm(
frame_to_plot.groupby("component_name"), leave=True
):
for parameter_name, sub_sub_frame in tqdm(
sub_frame.groupby("parameter_name"), leave=False
):
parameter_median_squared_fractional_changes[
component_name, parameter_name
] = float(sub_sub_frame["abs_thermal_efficiency_change"].median())
parameter_mean_squared_fractional_changes[
component_name, parameter_name
] = float(sub_sub_frame["abs_thermal_efficiency_change"].median())
sorted_medians = sorted(
parameter_median_squared_fractional_changes.items(), key=lambda item: item[1]
)
sorted_means = sorted(
parameter_mean_squared_fractional_changes.items(), key=lambda item: item[1]
)
# g = sns.catplot(x=["_".join(entry[0]) for entry in sorted_medians], y=[entry[1] for entry in sorted_medians], hue=[entry[0][0] for entry in sorted_medians], kind="bar")
gng = sns.catplot(
frame_to_plot,
x="abs_thermal_efficiency_change",
y="combined_name",
hue="component_name",
kind="box",
log_scale=True,
order=[" ".join(entry[0]) for entry in reversed(sorted_medians)],
whis=(1, 99),
flierprops={"marker": "D", "alpha": 0.7},
hue_order=(alphabetical_component_names:=sorted(set(frame_to_plot["component_name"]))),
height=32/5,
aspect=48/32,
legend_out=True,
)
# gng.figure.axes[0].tick_params(axis="x", rotation=90)
gng.figure.axes[0].set_xlabel("Absolute fractional change in thermal efficiency")
gng.figure.axes[0].set_ylabel("")
gng.figure.axes[0].axvline(0.01, linestyle="--", color="grey", label="1% impact")
gng.figure.axes[0].axvline(0.042, linestyle="-.", color="grey", label="4.2% impact")
gng.legend.set_title("Component")
gng.legend.set_alpha(1)
gng.figure.axes[0].set_xlim((min_ylim:=10**(-15)), 10**3)
# gng.figure.axes[0].axhspan(min_ylim, 0.042, color="grey",
# zorder=0,
# label="Rejected parameters", alpha=0.1)
# gng.figure.axes[0].axhspan(0.01, 0.042, color="C0",
# zorder=0,
# label="Limited impact", alpha=0.1)
# sns.move_legend(gng.figure, "upper left", bbox_to_anchor=(0.1, 0.725))
# rect = mpatches.Rectangle(
# [ax.get_position().x0, ax.get_position().y0],
# ax.get_position().x1 - ax.get_position().x0,
# 0.5,
# ec="k",
# fc="grey",
# alpha=0.1,
# clip_on=False,
# transform=fig.transFigure,
# linewidth=0,
# )
# ax.add_patch(rect)
plt.savefig(
f"abs_box_sensitivity_autotherm_G_{G}_{INDEX}.png",
transparent=True,
format="png",
dpi=300,
bbox_inches="tight",
)
gng = sns.catplot(
frame_to_plot,
x="abs_thermal_efficiency_change",
y="combined_name",
hue="component_name",
kind="boxen",
log_scale=True,
order=[" ".join(entry[0]) for entry in reversed(sorted_medians)],
outlier_prop=0,
showfliers=False,
hue_order=alphabetical_component_names,
height=32/5,
aspect=48/32,
legend_out=True,
)
# gng.figure.axes[0].tick_params(axis="x", rotation=90)
gng.figure.axes[0].set_xlabel("Absolute fractional change in thermal efficiency")
gng.figure.axes[0].set_ylabel("")
gng.figure.axes[0].axvline(0.01, linestyle="--", color="grey", label="1% impact")
gng.figure.axes[0].axvline(0.042, linestyle="-.", color="grey", label="4.2% impact")
gng.legend.set_title("Component")
gng.legend.set_alpha(1)
gng.figure.axes[0].set_xlim((min_ylim:=10**(-15)), 10**3)
# gng.figure.axes[0].axhspan(min_ylim, 0.042, color="grey",
# zorder=0,
# label="Rejected parameters", alpha=0.1)
# gng.figure.axes[0].axhspan(0.01, 0.042, color="C0",
# zorder=0,
# label="Limited impact", alpha=0.1)
# sns.move_legend(gng.figure, "upper left", bbox_to_anchor=(0.1, 0.725))
plt.savefig(
f"abs_boxen_sensitivity_autotherm_G_{G}_{INDEX}.png",
transparent=True,
format="png",
dpi=300,
bbox_inches="tight",
)
# Violin plot
# gng = sns.catplot(
# frame_to_plot,
# x="combined_name",
# y="abs_thermal_efficiency_change",
# hue="component_name",
# kind="violin",
# log_scale=True,
# order=[" ".join(entry[0]) for entry in sorted_medians],
# )
# ax = plt.gca()
# ax.tick_params(axis="x", rotation=90)
# ax.set_xlabel("")
# ax.set_ylabel("Absolute fractional change in thermal efficiency")
# gng.figure.axes[0].axhline(0.01, linestyle="--", color="grey", label="1% impact")
# gng.figure.axes[0].axhline(0.042, linestyle="-.", color="grey", label="4.2% impact")
# gng.legend.set_title("Component")
# plt.savefig(
# f"abs_violin_sensitivity_autotherm_G_{G}_{INDEX}.png",
# transparent=True,
# format="png",
# dpi=300,
# bbox_inches="tight",
# )
# Plot the median values only as a scatter
median_values_only = {combined_name: sub_frame["abs_thermal_efficiency_change"].median() for combined_name, sub_frame in frame_to_plot.groupby("combined_name")}
fig = plt.figure(figsize=(32 / 5, 32 / 5))
ax = plt.gca()
sns.scatterplot(
y = reversed(sorted_names:=[" ".join(entry[0]) for entry in sorted_medians]),
x=[median_values_only[name] for name in reversed(sorted_names)],
hue=[entry[0][0] for entry in sorted_medians],
ax=ax,
marker="D",
s=100,
alpha=1,
hue_order=alphabetical_component_names,
edgecolor=None,
)
# ax.tick_params(axis="x", rotation=90)
ax.set_ylabel("")
ax.set_xlabel("Median absolute fractional change in thermal efficiency")
ax.set_xscale("log")
ax.axvline(0.01, linestyle="--", color="grey", label="1% impact")
ax.axvline(0.042, linestyle="-.", color="grey", label="4.2% impact")
ax.set_xlim((min_ylim:=10**(-4)), 1/3)
ax.axvspan(min_ylim, 0.042, color="grey",
zorder=0,
label="Rejected parameters", alpha=0.1)
ax.axvspan(0.01, 0.042, color="C0",
zorder=0,
label="Limited impact", alpha=0.1)
legend = ax.legend(fancybox=True, framealpha=1, facecolor="white", bbox_to_anchor=(1, 1))
# legend.set_title("Component")
frame = legend.get_frame()
frame.set_facecolor("white")
frame.set_alpha(1)
plt.savefig(
f"abs_scatter_sensitivity_autotherm_G_{G}_{INDEX}.png",
transparent=True,
format="png",
dpi=400,
bbox_inches="tight",
)
# Output, for each variable, the median impact.
mapping: dict[int, dict[str, float]] = {}
for G in tqdm([200, 400, 600, 800, 1000]):
parameter_median_squared_fractional_changes: dict[tuple[str, str], float] = {}
parameter_mean_squared_fractional_changes: dict[tuple[str, str], float] = {}
frame_to_plot = combined_output_frame[
combined_output_frame["solar_irradiance"] == G
]
for component_name, sub_frame in frame_to_plot.groupby("component_name"):
for parameter_name, sub_sub_frame in sub_frame.groupby("parameter_name"):
parameter_median_squared_fractional_changes[
component_name, parameter_name
] = float(sub_sub_frame["abs_thermal_efficiency_change"].median())
parameter_mean_squared_fractional_changes[
component_name, parameter_name
] = float(sub_sub_frame["abs_thermal_efficiency_change"].median())
sorted_medians = sorted(
parameter_median_squared_fractional_changes.items(), key=lambda item: item[1]
)
median_values_only = {combined_name: sub_frame["abs_thermal_efficiency_change"].median() for combined_name, sub_frame in frame_to_plot.groupby("combined_name")}
print("\n".join([f"{'**' if median_values_only[name] >= 0.042 else '*' if median_values_only[name] >= 0.01 else ''}{name}: {median_values_only[name]:.3g}" for name in [f"{entry[0][0]} {entry[0][1]}" for entry in sorted_medians]]))
mapping[G] = {name: 100 * float(f"{median_values_only[name]:.3g}") for name in [f"{entry[0][0]} {entry[0][1]}" for entry in sorted_medians]}
frame = pd.DataFrame.from_dict(mapping)
frame = frame.sort_values(1000, ascending=False)
#####################################################################
# Plot a single variable with the parameter value dictating the hue #
#####################################################################
sns.set_context("notebook")
parameter_name_to_unit_map: dict[str, str] = {
"Absorptivity": None,
"Collector width": "pipes",
"Density": "kg/m$^3$",
"Diffuse reflection coefficient": None,
"Emissivity": None,
"Heat capacity": "J/kgK",
"Reference efficiency": None,
"Thermal coefficient": "K$^-1$",
"Thermal conductivity": "W/m K",
"Thickness": "m",
"Transmissivity": None,
"Width": "m",
}
start = 0
end = 8
def _size_from_component_and_parameter(component: str, parameter: str) -> int:
"""Determine the size of the points based on the component and parameter."""
# if component == "Absorber":
# if parameter in ("Thickness"):
# return 0.5
# if component in ("Adhesive", "Eva", "Tedlar", "Air gap",):
# if parameter in ("Thermal conductivity"):
# return 0.5
# if component == "Bond":
# if parameter in ("Thermal conductivity", "Width"):
# return 0.5
# if component == "Glass":
# if parameter in ("Diffuse reflection coefficient", "Emissivity", "Thermal conductivity", "Thickenss"):
# return 0.5
# if component == "Insulation":
# if parameter in ("Thermal conductivity", "Thickness"):
# return 0.5
# if component == "PV":
# if parameter in ("Emissivity", "Reference efficiency", "Thermal coefficienct", "Transmissivity"):
# return 0.5
# if component == "Pvt":
# return 0.5
return 0.25
for _component_name, start_hue in zip(
[
# "Absorber",
"Adhesive",
"Air gap",
# "Bond",
"Eva",
"Glass",
"Insulation",
"Pv",
"Pvt",
"Tedlar",
][start:end],
[0.2, 0.0, -0.2, -0.4, -0.6, -0.8, -1.0, -1.2, -1.4][start:end],
):
for _parameter_name in set(
combined_output_frame[(combined_output_frame["component_name"] == _component_name)][
"parameter_name"
]
):
frame_to_plot = combined_output_frame[
(combined_output_frame["component_name"] == _component_name)
& (combined_output_frame["parameter_name"] == _parameter_name)
& (
~combined_output_frame["parameter_value"]
.astype(str)
.str.contains("checkpoint")
)
& (combined_output_frame["solar_irradiance"] > 0)
]
# Drop nan entries
frame_to_plot = frame_to_plot.dropna(subset="percentage_thermal_efficiency_change")
frame_to_plot.loc[:, "parameter_value"] = frame_to_plot[
"parameter_value"
].astype(float)
if _component_name == "PV-T":
frame_to_plot.loc[:, "parameter_value"] = [
int(0.86 / entry)
for entry in frame_to_plot["parameter_value"].astype(float)
]
_unit: str | None = parameter_name_to_unit_map[_parameter_name]
# sns.swarmplot(
# frame_to_plot,
# x="percentage_thermal_efficiency_change",
# y="parameter_name",
# hue="parameter_value",
# palette=(
# this_palette := sns.cubehelix_palette(
# start=start_hue,
# rot=-0.2,
# dark=0.1,
# n_colors=len(set(frame_to_plot["parameter_value"])),
# )
# ),
# marker="D",
# size=_size_from_component_and_parameter(_component_name, _parameter_name),
# )
# Create the data
# rs = np.random.RandomState(1979)
# x = rs.randn(500)
# g = np.tile(list("ABCDEFGHIJ"), 50)
# df = pd.DataFrame(dict(x=x, g=g))
# m = df.g.map(ord)
# df["x"] += m
# Initialize the FacetGrid object
# pal = sns.cubehelix_palette(10, rot=-.25, light=.7)
g = sns.FacetGrid(frame_to_plot, row="parameter_value", hue="parameter_value", aspect=15, height=0.5, palette=(
this_palette := sns.cubehelix_palette(
start=start_hue,
rot=-0.6,
dark=0.15,
light=0.9,
n_colors=len(set(frame_to_plot["parameter_value"])),
)
),)
# Draw the densities in a few steps
g.map(sns.kdeplot, "percentage_thermal_efficiency_change",
bw_adjust=.5, clip_on=False,
fill=True, alpha=1, linewidth=1.5)
# g.map(sns.kdeplot, "percentage_thermal_efficiency_change",
# bw_adjust=.5, clip_on=False, fill=True,
# linewidth=1.5,
# marker="D",
# alpha=0.1,
# size=10
# )
g.map(sns.kdeplot, "percentage_thermal_efficiency_change", clip_on=False, color="w", lw=2, bw_adjust=.5)
# g.map(sns.stripplot, "percentage_thermal_efficiency_change",
# # clip_on=False,
# color="w", linewidth=2,
# # bw_adjust=.5
# )
# passing color=None to refline() uses the hue mapping
g.refline(y=0, linewidth=2, linestyle="-", color=None, clip_on=False)
# Define and use a simple function to label the plot in axes coordinates
def label(x, color, label):
ax = plt.gca()
ax.text(0, 0.8, f"{label} W/m$^2$", fontweight="bold", color=color,
ha="left", va="center", transform=ax.transAxes) \
g.map(label, "parameter_value")
# Set the subplots to overlap
g.figure.subplots_adjust(hspace=-0.1)
# Remove axes details that don't play well with overlap
g.set_titles("")
g.set(yticks=[], ylabel="")
g.despine(bottom=True, left=True)
# g.set_xlabels("Percentage thermal efficiency change")
# axis = plt.gca()
# levels = sorted(set(frame_to_plot["parameter_value"]))
# cmap, norm = mcolors.from_levels_and_colors(levels, this_palette[:-1])
# # norm = plt.Normalize(
# # frame_to_plot["parameter_value"].min(),
# # frame_to_plot["parameter_value"].max(),
# # )
# scalar_mappable = plt.cm.ScalarMappable(
# cmap=cmap,
# norm=norm,
# )
# colorbar = axis.figure.colorbar(
# scalar_mappable,
# ax=axis,
# label=(
# (
# f"{_component_name} {_parameter_name}"
# if _component_name != "PV-T"
# else "Number of pipes"
# )
# + (f" / {_unit}" if _unit is not None else "")
# ),
# )
axis = plt.gca()
# Stripplot
# sns.stripplot(
# frame_to_plot,
# x="solar_irradiance",
# y="percentage_thermal_efficiency_change",
# hue="parameter_value",
# palette=(
# this_palette := sns.cubehelix_palette(
# start=start_hue,
# rot=-0.6,
# dark=0.15,
# light=0.9,
# n_colors=len(set(frame_to_plot["parameter_value"])),
# )
# ),
# marker="D",
# jitter=1,
# dodge=True,
# orient="h",
# alpha=0.3,
# size=10,
# )
# axis = plt.gca()
# norm = plt.Normalize(
# frame_to_plot["parameter_value"].min(),
# frame_to_plot["parameter_value"].max(),
# )
# scalar_mappable = plt.cm.ScalarMappable(
# cmap=mcolors.LinearSegmentedColormap.from_list(
# "Custom",
# [(value, colour) for value, colour in zip(this_palette.as_hex(), sorted(frame_to_plot["parameter_value"]))],
# ),
# norm=norm,
# )
# colorbar = axis.figure.colorbar(
# scalar_mappable,
# ax=axis,
# label=(
# (
# f"{_component_name} {_parameter_name}"
# if _component_name != "PV-T"
# else "Number of pipes"
# )
# + (f" / {_unit}" if _unit is not None else "")
# ),
# )
# axis = plt.gca()
# axis.get_legend().remove()
# axis.set_xlabel("Percentage change in thermal efficiency / %")
# axis.set(ylabel=None, yticklabels=[])
# axis.axvline(x=0, linestyle="--", color="grey", linewidth=1)
plt.savefig(
f"(KDE) Sensitivity of {_component_name} {_parameter_name}_{INDEX}.png",
transparent=True,
dpi=400,
bbox_inches="tight",
pad_inches=0,
)
# plt.show()
for _component_name, start_hue in zip(
[
# "Absorber",
"Adhesive",
"Air gap",
# "Bond",
"Eva",
"Glass",
"Insulation",
"Pv",
"Pvt",
"Tedlar",
][start:end],
[0.2, 0.0, -0.2, -0.4, -0.6, -0.8, -1.0, -1.2, -1.4][start:end],
):
for _parameter_name in set(
combined_output_frame[
(combined_output_frame["component_name"] == _component_name)
]["parameter_name"]
):
frame_to_plot = combined_output_frame[
(combined_output_frame["component_name"] == _component_name)
& (combined_output_frame["parameter_name"] == _parameter_name)
& (
~combined_output_frame["parameter_value"]
.astype(str)
.str.contains("checkpoint")
)
]
frame_to_plot.loc[:, "parameter_value"] = frame_to_plot[
"parameter_value"
].astype(float)
if _component_name == "Pvt":
frame_to_plot.loc[:, "parameter_value"] = [
int(0.86 / entry)
for entry in frame_to_plot["parameter_value"].astype(float)
]
_unit: str | None = parameter_name_to_unit_map[_parameter_name]
fig = plt.figure(figsize=(48 / 5, 32 / 5))
sns.swarmplot(
frame_to_plot,
x="percentage_thermal_efficiency_change",
y="parameter_name",
hue="parameter_value",
palette=(
this_palette := sns.cubehelix_palette(
start=start_hue,
rot=-0.2,
dark=0.1,
n_colors=len(set(frame_to_plot["parameter_value"])),