-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_analysis.py
More file actions
1533 lines (1351 loc) · 50.3 KB
/
data_analysis.py
File metadata and controls
1533 lines (1351 loc) · 50.3 KB
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
"""Generate a report of solar cell measurement data."""
import contextlib
import logging
import os
import pathlib
import time
import warnings
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
import packaging.version
import pandas as pd
import seaborn as sns
import scipy.constants
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.enum.text import MSO_ANCHOR
from gooey import Gooey, GooeyParser
from check_release_version import get_latest_release_version, REPO_URL
from format_data import format_folder
from log_generator import generate_log
from version import __version__
# supress warnings
warnings.filterwarnings("ignore")
# Define a colormap for graded plots
cmap = plt.cm.get_cmap("viridis")
@Gooey(
dump_build_config=False,
program_name="Data Analysis",
default_size=(750, 530),
header_bg_color="#7B7B7B",
)
def parse():
"""Parse command line arguments to Gooey GUI."""
desc = "Analyse solar simulator data and generate a report."
# check if latest release on github is newer than currently running version
# if so, let the user know by editing the description string
latest_release_version = get_latest_release_version()
if latest_release_version is None:
desc += (
"\n\nCould not determine latest release version. Check internet connection."
)
elif packaging.version.parse(latest_release_version) > packaging.version.parse(
__version__
):
desc += f"\n\nNEW VERSION AVAILABLE! Download it from: {REPO_URL}"
else:
desc += f"\n\nYou're running the latest version: {__version__}"
parser = GooeyParser(description=desc)
req = parser.add_argument_group(gooey_options={"columns": 1})
req.add_argument(
"folder",
metavar="Folder containing data to be analysed",
help="Absolute path to the folder containing measurement data",
widget="DirChooser",
)
req.add_argument(
"fix_ymin_0",
metavar="Zero y-axis minima",
help="Fix boxplot y-axis minima to 0",
widget="Dropdown",
choices=["yes", "no"],
default="yes",
)
req.add_argument(
"--debug",
metavar="DEBUG",
help="Export debug info to a file",
widget="CheckBox",
action="store_true",
)
return parser.parse_args()
def create_logger(log_dir: str, debug: bool = False):
"""Create a logger.
Parameters
----------
log_dir : str
Log directory.
debug : bool
Flag whether to log in debug mode, which exports logging to a file.
"""
# create logger
logging.captureWarnings(True)
_logger = logging.getLogger()
log_level = 10 if debug else 20
_logger.setLevel(log_level)
# create a filter to remove messages from certain imports
class ImportFilter(logging.Filter):
"""Filter log records from named third-party imports."""
def filter(self, record: logging.LogRecord) -> bool:
if record.name.startswith("matplotlib"):
return False
elif record.name.startswith("PIL"):
return False
else:
return True
# create console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(log_level)
console_handler.addFilter(ImportFilter())
_logger.addHandler(console_handler)
# add file handler for debugging
if debug:
formatter = logging.Formatter("%(asctime)s|%(name)s|%(levelname)s|%(message)s")
file_handler = logging.FileHandler(
pathlib.Path(log_dir).joinpath("debug.txt"), mode="w"
)
file_handler.setLevel(log_level)
file_handler.setFormatter(formatter)
file_handler.addFilter(ImportFilter())
_logger.addHandler(file_handler)
return _logger
def round_sig_fig(number: float, sig_fig: int) -> float:
"""
Round a number to the specified number of significant figures.
Parameters
----------
number : float
number to round
sig_fig : int
number of significant figures
Returns
-------
rounded_number : float
rounded number
"""
_, x_ord = map(float, f"{number:.{sig_fig}e}".split("e"))
return round(number, int(-x_ord) + 1)
def recursive_path_split(filepath) -> tuple:
"""Recursively split filepath into sub-parts delimited by OS file seperator.
Parameters
----------
path : str
filepath
Returns
-------
split : tuple
sub-parts of filepath
"""
head, tail = os.path.split(filepath)
return (head,) if tail == "" else recursive_path_split(head) + (tail,)
def title_image_slide(prs, title: str):
"""
Create a new slide in the presentation (prs) with a formatted title.
Parameters
----------
prs : presentation object
pptx presentation object
title : str
title of slide
Returns
-------
slide : slide object
pptx slide object
"""
# Add a title slide
title_slide_layout = prs.slide_layouts[5]
slide = prs.slides.add_slide(title_slide_layout)
# Add text to title and edit its layout
title_placeholder = slide.shapes.title
title_placeholder.top = Inches(0)
title_placeholder.width = Inches(10)
title_placeholder.height = Inches(0.5)
title_placeholder.text = title
# Edit margins within textbox
text_frame = title_placeholder.text_frame
text_frame.margin_bottom = Inches(0)
text_frame.margin_top = Inches(0.1)
text_frame.vertical_anchor = MSO_ANCHOR.TOP
# Edit title fontsize and style
para = text_frame.paragraphs[0]
run = para.runs[0]
font = run.font
font.size = Pt(16)
font.bold = True
return slide
def plot_boxplots(
dataframe,
params,
kind: str,
grouping: str,
variable: str = "",
start_index: int = 0,
data_slide=None,
override_grouping_title: str = "",
):
"""Create boxplots from the log file.
Parameters
----------
dataframe : pandas.DataFrame
logfile or group
params : list of str
parameters to plot
kind : str
kind of paramters plotted
grouping : str
how data are grouped
variable : str
variable
start_index : int
starting index of boxplot. Useful if carrying on page from previous plots.
data_slide : prs object
current slide. Useful if carrying on from previous plots.
override_grouping_title : str
instead of using `grouping` in slide title, use this string.
"""
plot_labels_dict = {
"jsc": {"J-V": "Jsc (mA/cm^2)"},
"voc": {"J-V": "Voc (V)"},
"pce": {"J-V": "PCE (%)"},
"vmpp": {"J-V": "Vmp (V)"},
"jmpp": {"J-V": "Jmp (mA/cm^2)"},
"jss": {"SSPO": "J_mp_ss (mA/cm^2)", "SSJsc": "J_sc_ss (mA/cm^2)"},
"pcess": {"SSPO": "PCE_ss (%)"},
"vss": {"SSPO": "V_mp_ss (V)", "SSVoc": "V_oc_ss (V)"},
"ff": {"J-V": "FF"},
"quasiff": {"SSJsc": "Quasi-FF"},
"rsvfwd": {"J-V": "Rs (ohms)"},
"rsh": {"J-V": "Rsh (ohms)"},
"pcesspcejv": {"SSPO": "PCE_ss/PCE_jv"},
}
plot_index = 0
for param in params:
# create a new slide for every 4 plots
if (start_index + plot_index) % 4 == 0:
ss_or_jv = kind if kind == "J-V" else "Steady-state"
grouping_title = override_grouping_title or grouping
page = int((start_index + plot_index) / 4)
data_slide = title_image_slide(
prs,
f"{variable} {ss_or_jv} parameters by {grouping_title}, page {page}",
)
# create boxplot
fig, ax1 = plt.subplots(
1, 1, dpi=300, **{"figsize": (A4_WIDTH / 2, A4_HEIGHT / 2)}
)
# get grouping of data for box and swarm plots
if kind == "J-V":
hue = (
dataframe["scandirection"]
+ np.array([", "] * len(dataframe["area"]))
+ dataframe["area"].astype(str)
)
else:
hue = dataframe["area"]
try:
sns.boxplot(
x=dataframe[grouping],
y=np.absolute(dataframe[param].astype(float)),
hue=hue,
palette="deep",
linewidth=0.5,
ax=ax1,
showfliers=False,
)
except ValueError as err:
logger.error(hue, grouping, param, kind)
logger.error(dataframe[param])
raise ValueError from err
sns.swarmplot(
x=dataframe[grouping],
y=np.absolute(dataframe[param].astype(float)),
hue=hue,
palette="muted",
size=3,
linewidth=0.5,
edgecolor="gray",
dodge=True,
ax=ax1,
)
# only show legend markers for box plots, not swarm plot
legend_handles, legend_labels = ax1.get_legend_handles_labels()
ax1.legend(
legend_handles[: len(legend_handles) // 2],
legend_labels[: len(legend_labels) // 2],
fontsize="small",
)
ax1.set_xticklabels(
ax1.get_xticklabels(), fontsize="small", rotation=45, ha="right"
)
ax1.set_xlabel("")
if param in ["jsc", "voc", "pce", "vmpp", "jmpp", "jss", "pcess", "vss"]:
if FIX_YMIN_0:
ax1.set_ylim(0)
elif param in ["ff", "quasiff"]:
if FIX_YMIN_0:
ax1.set_ylim(0, 1)
ax1.set_ylabel(plot_labels_dict[param][kind], fontsize="small")
fig.tight_layout()
# save figure and add to powerpoint
image_png = os.path.join(image_folder, f"boxplot_{param}.png")
image_svg = os.path.join(image_folder, f"boxplot_{param}.svg")
fig.savefig(image_png)
fig.savefig(image_svg)
if data_slide is not None:
data_slide.shapes.add_picture(
image_png,
left=LEFTS[str((start_index + plot_index) % 4)],
top=TOPS[str((start_index + plot_index) % 4)],
height=IMAGE_HEIGHT,
)
plot_index += 1
return start_index + plot_index, data_slide
def plot_countplots(
dataframe, index: int, grouping: str, data_slide, variable: str = ""
):
"""Create countplots from the log file.
Parameters
----------
dataframe : DataFrame
logfile or group
index : int
figure index
grouping : str
how data are grouped
data_slide: slide
slide in ppt to add figures to
variable : str
variable
"""
# create count plot
fig, ax1 = plt.subplots(1, 1, dpi=300, **{"figsize": (A4_WIDTH / 2, A4_HEIGHT / 2)})
if grouping == "value":
ax1.set_title(f"{variable}", fontdict={"fontsize": "small"})
sns.countplot(
x=dataframe[grouping],
data=dataframe,
hue=dataframe["scandirection"],
linewidth=0.5,
palette="deep",
edgecolor="black",
ax=ax1,
)
legend_handles, legend_labels = ax1.get_legend_handles_labels()
ax1.legend(
legend_handles[:],
legend_labels[:],
fontsize="small",
)
ax1.set_xticklabels(
ax1.get_xticklabels(), fontsize="small", rotation=45, ha="right"
)
ax1.set_xlabel("")
ax1.set_ylabel("Number of working pixels", fontsize="small")
fig.tight_layout()
# save figure and add to powerpoint
image_png = os.path.join(image_folder, f"boxchart_yields{index}.png")
image_svg = os.path.join(image_folder, f"boxchart_yields{index}.svg")
fig.savefig(image_png)
fig.savefig(image_svg)
data_slide.shapes.add_picture(
image_png,
left=LEFTS[str(index % 4)],
top=TOPS[str(index % 4)],
height=IMAGE_HEIGHT,
)
def plot_stabilisation(dataframe, title: str, short_name: str):
"""Plot stabilisation data.
Parameters
----------
dataframe : dataFrame
data to plot
title : str
slide title
short_name : str
short name for file
"""
for index, (_, row) in enumerate(dataframe.iterrows()):
# Get label, variable, value, and pixel for title and image path
label = row["label"]
variable = row["variable"]
value = row["value"]
pixel = row["pixel"]
vspo = row["vss"]
# Start a new slide after every 4th figure
if index % 4 == 0:
data_slide = title_image_slide(prs, f"{title}, page {int(index / 4)}")
# Open the data file
path = row["relativepath"]
if short_name == "sjsc":
cols = (0, 4)
elif short_name == "spo":
cols = (0, 2, 4, 6)
elif short_name == "svoc":
cols = (0, 2)
else:
cols = ()
data = np.genfromtxt(
path, delimiter="\t", skip_header=1, skip_footer=NUM_COLS, usecols=cols
)
with contextlib.suppress(Exception):
data = data[~np.isnan(data).any(axis=1)]
if data.ndim == 1:
# convert single row array to 2d array to avoid index error later
data = np.expand_dims(data, axis=0)
if short_name == "sjsc":
fig, ax1 = plt.subplots(
1, 1, figsize=(A4_WIDTH / 2, A4_HEIGHT / 2), dpi=300
)
ax1.set_title(
f"{label}, pixel {pixel}, {variable}, {value}",
fontdict={"fontsize": "small"},
)
ax1.scatter(
data[:, 0], np.absolute(data[:, 1]), color="black", s=5, label="Jsc"
)
ax1.set_ylabel("|Jsc| (mA/cm^2)", fontsize="small")
ax1.set_ylim(0, np.max(np.absolute(data[:, 1])) * 1.1)
ax1.set_xlabel("Time (s)", fontsize="small")
ax1.set_xlim(0)
ax1.tick_params(direction="in", top=True, right=True, labelsize="small")
fig.tight_layout()
elif short_name == "spo":
fig, axs = plt.subplots(
3, 1, sharex=True, figsize=(A4_WIDTH / 2, A4_HEIGHT / 2), dpi=300
)
ax1, ax2, ax3 = axs
fig.subplots_adjust(hspace=0)
ax1.set_title(
f"{label}, pixel {pixel}, {variable}, {value}, vspo = {vspo} V",
fontdict={"fontsize": "small"},
)
ax1.scatter(
data[:, 0], np.absolute(data[:, 2]), color="black", s=5, label="J"
)
ax1.set_ylabel("|J| (mA/cm^2)", fontsize="small")
ax1.set_ylim(0, np.max(np.absolute(data[:, 2])) * 1.1)
ax3.tick_params(direction="in", top=True, right=True)
ax2.scatter(
data[:, 0],
np.absolute(data[:, 3]),
color="red",
s=5,
marker="s",
label="pce",
)
ax2.set_ylabel("PCE (%)", fontsize="small")
ax2.set_ylim(0, np.max(np.absolute(data[:, 3])) * 1.1)
ax2.tick_params(direction="in", top=True, right=True)
ax3.scatter(
data[:, 0],
np.absolute(data[:, 1]),
color="blue",
s=5,
marker="s",
label="v",
)
ax3.set_ylabel("V (V)", fontsize="small")
ax3.set_ylim(0, np.max(np.absolute(data[:, 1])) * 1.1)
ax3.set_xlabel("Time (s)", fontsize="small")
ax3.tick_params(direction="in", top=True, right=True, labelsize="small")
fig.align_ylabels([ax1, ax2, ax3])
elif short_name == "svoc":
fig, ax1 = plt.subplots(
1, 1, figsize=(A4_WIDTH / 2, A4_HEIGHT / 2), dpi=300
)
ax1.set_title(
f"{label}, pixel {pixel}, {variable}, {value}",
fontdict={"fontsize": "small"},
)
ax1.scatter(
data[:, 0], np.absolute(data[:, 1]), color="black", s=5, label="Voc"
)
ax1.set_ylabel("|Voc| (V)", fontsize="small")
ax1.set_ylim(0, np.max(np.absolute(data[:, 1])) * 1.1)
ax1.set_xlabel("Time (s)", fontsize="small")
ax1.set_xlim(0)
ax1.tick_params(direction="in", top=True, right=True, labelsize="small")
fig.tight_layout()
else:
fig, ax1 = plt.subplots(
1, 1, figsize=(A4_WIDTH / 2, A4_HEIGHT / 2), dpi=300
)
# Format the figure layout, save to file, and add to ppt
image_png = os.path.join(
image_folder, f"{short_name}_{label}_{variable}_{value}_{pixel}.png"
)
image_svg = os.path.join(
image_folder, f"{short_name}_{label}_{variable}_{value}_{pixel}.svg"
)
fig.savefig(image_png)
fig.savefig(image_svg)
data_slide.shapes.add_picture(
image_png,
left=LEFTS[str(index % 4)],
top=TOPS[str(index % 4)],
height=IMAGE_HEIGHT,
)
# Close figure
plt.close(fig)
index += 1
def plot_spectra(files):
"""Plot illumination specta.
Parameters
----------
files : list
list of file paths
"""
c_div = 1 / len(files)
data_slide = title_image_slide(prs, "Measured illumination spectra")
fig, ax1 = plt.subplots(1, 1, figsize=(A4_WIDTH, A4_HEIGHT), dpi=300)
for index, file in enumerate(files):
if os.path.getsize(file) != 0:
spectrum = np.genfromtxt(file, delimiter="\t")
ax1.plot(
spectrum[:, 0],
spectrum[:, 1],
color=cmap(index * c_div),
label=f"{index}",
)
ax1.set_ylabel("Spectral irradiance (W/cm^2/nm)", fontsize="large")
ax1.set_ylim(0)
ax1.tick_params(direction="in", top=True, right=True, labelsize="large")
ax1.set_xlabel("Wavelength (nm)", fontsize="large")
ax1.set_xlim(350, 1100)
ax1.legend(fontsize="large")
fig.tight_layout()
# Format the figure layout, save to file, and add to ppt
image_png = os.path.join(image_folder, "spectra.png")
image_svg = os.path.join(image_folder, "spectra.svg")
fig.savefig(image_png)
fig.savefig(image_svg)
data_slide.shapes.add_picture(
image_png, left=LEFTS["0"], top=TOPS["0"], height=IMAGE_HEIGHT * 2
)
# Close figure
plt.close(fig)
def plot_best_jvs_by_label(groups, substrate_info):
"""Plot best jv curves for each substrate.
Parameters
----------
groups : pandas.GroupBy
data frame grouped by label.
substrate_info : pandas.DataFrame
data frame from which variables, values, and labels can be inferred.
"""
variables = list(substrate_info["variable"])
values = list(substrate_info["value"])
labels = list(substrate_info["label"])
# get parameters for plot formatting
c_div = 1 / 8
# Create figures, save images and add them to powerpoint slide
for index, (_, group) in enumerate(groups):
# Create a new slide after every four graphs are produced
if index % 4 == 0:
data_slide = title_image_slide(
prs, f"Best JV scans of every working pixel, page {int(index / 4)}"
)
# Create figure, axes, y=0 line, and title
fig, ax1 = plt.subplots(1, 1, figsize=(A4_WIDTH / 2, A4_HEIGHT / 2), dpi=300)
ax1.axhline(0, lw=0.5, c="black")
ax1.axvline(0, lw=0.5, c="black")
ax1.set_title(
f"{labels[index]}, {variables[index]}, {values[index]}",
fontdict={"fontsize": "small"},
)
pixels = list(group["pixel"].astype(int))
# find signs of jsc and voc to determine max and min axis limits
jsc_signs, jsc_counts = np.unique(np.sign(group["jmpp"]), return_counts=True)
voc_signs, voc_counts = np.unique(np.sign(group["voc"]), return_counts=True)
if len(jsc_signs) == 1:
jsc_sign = jsc_signs[0]
else:
max_ix = np.argmax(jsc_counts)
jsc_sign = jsc_signs[max_ix]
if len(voc_signs) == 1:
voc_sign = voc_signs[0]
else:
max_ix = np.argmax(voc_counts)
voc_sign = voc_signs[max_ix]
# load data for each pixel and plot on axes
fwd_j = []
rev_j = []
for data_index, (file, scan_dir) in enumerate(
zip(group["relativepath"], group["scandirection"])
):
if scan_dir == "fwd":
data_fwd = np.genfromtxt(
file,
delimiter="\t",
skip_header=1,
skip_footer=NUM_COLS,
usecols=(2, 4),
)
data_fwd = data_fwd[~np.isnan(data_fwd).any(axis=1)]
ax1.plot(
data_fwd[:, 0],
data_fwd[:, 1],
c=cmap(pixels[data_index] * c_div),
lw=2.0,
)
if (
(jsc_sign > 0) & (voc_sign > 0)
or not (jsc_sign > 0) & (voc_sign < 0)
and (jsc_sign < 0) & (voc_sign > 0)
):
fwd_j.append(data_fwd[0, 1])
rev_j.append(data_fwd[-1, 1])
elif (jsc_sign > 0) & (voc_sign < 0) or (jsc_sign < 0) & (voc_sign < 0):
fwd_j.append(data_fwd[-1, 1])
rev_j.append(data_fwd[0, 1])
elif scan_dir == "rev":
data_rev = np.genfromtxt(
file,
delimiter="\t",
skip_header=1,
skip_footer=NUM_COLS,
usecols=(2, 4),
)
data_rev = data_rev[~np.isnan(data_rev).any(axis=1)]
ax1.plot(
data_rev[:, 0],
data_rev[:, 1],
label=pixels[data_index],
c=cmap(pixels[data_index] * c_div),
lw=2.0,
)
if (
(jsc_sign > 0) & (voc_sign > 0)
or not (jsc_sign > 0) & (voc_sign < 0)
and (jsc_sign < 0) & (voc_sign > 0)
):
fwd_j.append(data_rev[-1, 1])
rev_j.append(data_rev[0, 1])
elif (jsc_sign > 0) & (voc_sign < 0) or (jsc_sign < 0) & (voc_sign < 0):
fwd_j.append(data_rev[0, 1])
rev_j.append(data_rev[-1, 1])
# Format the axes
ax1.tick_params(direction="in", top=True, right=True, labelsize="small")
ax1.set_xlabel("Applied bias (V)", fontsize="small")
ax1.set_ylabel("J (mA/cm^2)", fontsize="small")
# Adjust plot width to add legend outside plot area
box = ax1.get_position()
ax1.set_position([box.x0, box.y0, box.width * 0.85, box.height])
legend_handles, legend_labels = ax1.get_legend_handles_labels()
lgd = ax1.legend(
legend_handles,
legend_labels,
loc="upper left",
bbox_to_anchor=(1, 1),
title="pixel #",
fontsize="small",
)
# Format the figure layout, save to file, and add to ppt
image_png = os.path.join(image_folder, f"jv_all_{labels[index]}.png")
image_svg = os.path.join(image_folder, f"jv_all_{labels[index]}.svg")
fig.savefig(image_png, bbox_extra_artists=(lgd,), bbox_inches="tight")
fig.savefig(image_svg, bbox_extra_artists=(lgd,), bbox_inches="tight")
data_slide.shapes.add_picture(
image_png,
left=LEFTS[str(index % 4)],
top=TOPS[str(index % 4)],
height=IMAGE_HEIGHT,
)
# Close figure
plt.close(fig)
def plot_best_jvs_by_variable_value(best_pixels):
"""Plot JV curves of best pixels by variable value.
Parameters
----------
best_pixels : pandas.DataFrame
data frame of best pixels for each variable value
"""
# create lists of varibales and values for labelling figures
variables = list(best_pixels["variable"])
values = list(best_pixels["value"])
labels = list(best_pixels["label"])
jsc_signs = list(np.sign(best_pixels["jmpp"]))
voc_signs = list(np.sign(best_pixels["voc"]))
# Loop for iterating through best pixels dataframe and picking out JV data
# files. Each plot contains forward and reverse sweeps, both light and dark.
for index, (file, scan_dir) in enumerate(
zip(best_pixels["relativepath"], best_pixels["scandirection"])
):
# Create a new slide after every four graphs are produced
if index % 4 == 0:
data_slide = title_image_slide(
prs, f"Best pixel JVs, page {int(index / 4)}"
)
# Create figure, axes, y=0 line, and title
fig, ax1 = plt.subplots(1, 1, figsize=(A4_WIDTH / 2, A4_HEIGHT / 2), dpi=300)
ax1.axhline(0, lw=0.5, c="black")
ax1.axvline(0, lw=0.5, c="black")
ax1.set_title(
f"{variables[index]}, {values[index]}, {labels[index]}",
fontdict={"fontsize": "small"},
)
# Import data for each pixel and plot on axes, ignoring errors. If
# data in a file can't be plotted just ignore it.
# TODO: handle case with > 2 scans
if scan_dir == "rev":
jv_light_rev_path = file
if file.endswith("liv1"):
jv_light_fwd_path = file.replace("liv1", "liv2")
elif file.endswith("liv2"):
jv_light_fwd_path = file.replace("liv2", "liv1")
elif scan_dir == "fwd":
jv_light_fwd_path = file
if file.endswith("liv1"):
jv_light_rev_path = file.replace("liv1", "liv2")
elif file.endswith("liv2"):
jv_light_rev_path = file.replace("liv2", "liv1")
with contextlib.suppress(OSError, NameError):
jv_light_rev_data = np.genfromtxt(
jv_light_rev_path,
delimiter="\t",
skip_header=1,
skip_footer=NUM_COLS,
usecols=(2, 4),
)
jv_light_fwd_data = np.genfromtxt(
jv_light_fwd_path,
delimiter="\t",
skip_header=1,
skip_footer=NUM_COLS,
usecols=(2, 4),
)
jv_dark_rev_data = np.genfromtxt(
jv_light_rev_path.replace("liv", "div"),
delimiter="\t",
skip_header=1,
skip_footer=NUM_COLS,
usecols=(2, 4),
)
jv_dark_fwd_data = np.genfromtxt(
jv_light_fwd_path.replace("liv", "div"),
delimiter="\t",
skip_header=1,
skip_footer=NUM_COLS,
usecols=(2, 4),
)
jv_light_rev_data = jv_light_rev_data[
~np.isnan(jv_light_rev_data).any(axis=1)
]
jv_light_fwd_data = jv_light_fwd_data[
~np.isnan(jv_light_fwd_data).any(axis=1)
]
jv_dark_rev_data = jv_dark_rev_data[~np.isnan(jv_dark_rev_data).any(axis=1)]
jv_dark_fwd_data = jv_dark_fwd_data[~np.isnan(jv_dark_fwd_data).any(axis=1)]
# plot light J-V curves
ax1.plot(
jv_light_rev_data[:, 0],
jv_light_rev_data[:, 1],
label="rev",
c="red",
lw=2.0,
)
ax1.plot(
jv_light_fwd_data[:, 0],
jv_light_fwd_data[:, 1],
label="fwd",
c="black",
lw=2.0,
)
# find y-limits for plotting
fwd_j = []
rev_j = []
if (jsc_signs[index] > 0) & (voc_signs[index] > 0):
fwd_j.append(jv_light_rev_data[-1, 1])
rev_j.append(jv_light_rev_data[0, 1])
fwd_j.append(jv_light_fwd_data[0, 1])
rev_j.append(jv_light_fwd_data[-1, 1])
elif (jsc_signs[index] > 0) & (voc_signs[index] < 0):
fwd_j.append(jv_light_rev_data[0, 1])
rev_j.append(jv_light_rev_data[-1, 1])
fwd_j.append(jv_light_fwd_data[-1, 1])
rev_j.append(jv_light_fwd_data[0, 1])
elif (jsc_signs[index] < 0) & (voc_signs[index] > 0):
fwd_j.append(jv_light_rev_data[-1, 1])
rev_j.append(jv_light_rev_data[0, 1])
fwd_j.append(jv_light_fwd_data[0, 1])
rev_j.append(jv_light_fwd_data[-1, 1])
elif (jsc_signs[index] < 0) & (voc_signs[index] < 0):
fwd_j.append(jv_light_rev_data[0, 1])
rev_j.append(jv_light_rev_data[-1, 1])
fwd_j.append(jv_light_fwd_data[-1, 1])
rev_j.append(jv_light_fwd_data[0, 1])
ax1.plot(
jv_dark_rev_data[:, 0],
jv_dark_rev_data[:, 1],
label="rev",
c="orange",
lw=2.0,
)
ax1.plot(
jv_dark_fwd_data[:, 0],
jv_dark_fwd_data[:, 1],
label="fwd",
c="blue",
lw=2.0,
)
# Format the axes
ax1.tick_params(direction="in", top=True, right=True, labelsize="small")
ax1.set_xlabel("Applied bias (V)", fontsize="small")
ax1.set_ylabel("J (mA/cm^2)", fontsize="small")
ax1.legend(loc="best")
# Format the figure layout, save to file, and add to ppt
image_png = os.path.join(
image_folder, f"jv_best_{variables[index]}_{variables[index]}.png"
)
image_svg = os.path.join(
image_folder, f"jv_best_{variables[index]}_{variables[index]}.svg"
)
fig.tight_layout()
fig.savefig(image_png)
fig.savefig(image_svg)
data_slide.shapes.add_picture(
image_png,
left=LEFTS[str(index % 4)],
top=TOPS[str(index % 4)],
height=IMAGE_HEIGHT,
)
# Close figure
plt.close(fig)
def plot_all_jvs(all_jv_groups):
"""Plot all JV curves.
Parameters
----------
all_jv_groups : pandas.GroupBy
all jv scans grouped by pixel number
"""
# get parameters for plot formatting
c_div = 1 / 4
# Create figures, save images and add them to powerpoint slide
for index, (_, group) in enumerate(all_jv_groups):
# Create a new slide after every four graphs are produced
if index % 4 == 0:
data_slide = title_image_slide(prs, f"All JV scans, page {int(index / 4)}")
label = group["label"].unique()[0]
pixel = group["pixel"].unique()[0]
variable = group["variable"].unique()[0]
value = group["value"].unique()[0]
fig, ax1 = plt.subplots(1, 1, figsize=(A4_WIDTH / 2, A4_HEIGHT / 2), dpi=300)
ax1.axhline(0, lw=0.5, c="black")
ax1.axvline(0, lw=0.5, c="black")
ax1.set_title(
f"{label}, {variable}, {value}, pixel {pixel}",
fontdict={"fontsize": "small"},
)
jsc_signs, jsc_counts = np.unique(np.sign(group["jmpp"]), return_counts=True)
voc_signs, voc_counts = np.unique(np.sign(group["voc"]), return_counts=True)
if len(jsc_signs) == 1:
jsc_sign = jsc_signs[0]
else:
max_ix = np.argmax(jsc_counts)
jsc_sign = jsc_signs[max_ix]
if len(voc_signs) == 1:
voc_sign = voc_signs[0]
else:
max_ix = np.argmax(voc_counts)
voc_sign = voc_signs[max_ix]
# load data for each pixel and plot on axes
fwd_j = []
rev_j = []
for file, scan_dir, scannumber, intensity in zip(
group["relativepath"],
group["scandirection"],
group["scannumber"],
group["intensity"],
):
if scan_dir == "rev":
data_rev = np.genfromtxt(
file,
delimiter="\t",
skip_header=1,
skip_footer=NUM_COLS,
usecols=(2, 4),
)
data_rev = data_rev[~np.isnan(data_rev).any(axis=1)]
if intensity == 0:
ax1.plot(
data_rev[:, 0],
data_rev[:, 1],
label=f"{scannumber} {scan_dir} dark",
c="black",
lw=1.5,
ls="--",
)
else:
ax1.plot(
data_rev[:, 0],
data_rev[:, 1],
label=f"{scannumber} {scan_dir}",
c=cmap(scannumber * c_div),
lw=1.5,
ls="--",
)
if (
(jsc_sign > 0) & (voc_sign > 0)