-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathta_analyzer_core.py
More file actions
3092 lines (2782 loc) · 121 KB
/
Copy pathta_analyzer_core.py
File metadata and controls
3092 lines (2782 loc) · 121 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
from pathlib import Path
import lmfit
import matplotlib
import matplotlib.axes
import matplotlib.figure
import matplotlib.pyplot as plt
from matplotlib import colormaps
import numpy as np
import xarray as xr
import re
from scipy.stats import norm
# %matplotlib widget #uncomment for interactive plot
from matplotlib.colors import ListedColormap
from tqdm import tqdm
from itertools import cycle # Import cycle
"""
from glotaran.optimization.optimize import optimize
from glotaran.io import load_model
from glotaran.io import load_parameters
from glotaran.io import save_dataset
from glotaran.io.prepare_dataset import prepare_time_trace_dataset
from glotaran.project.scheme import Scheme
"""
__docformat__ = "google"
JACS_SINGLE_COLUMN_WIDTH_IN = 3.25
JACS_DOUBLE_COLUMN_WIDTH_IN = 7.0
JACS_LINE_WIDTH = 0.8
def _apply_jacs_style(fontsize: float = 8) -> None:
"""Apply journal-friendly matplotlib defaults for publication figures."""
plt.rcParams.update(
{
"font.family": "sans-serif",
"font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"],
"font.size": fontsize,
"axes.labelsize": fontsize,
"axes.titlesize": fontsize,
"axes.linewidth": JACS_LINE_WIDTH,
"xtick.labelsize": fontsize,
"ytick.labelsize": fontsize,
"xtick.major.width": JACS_LINE_WIDTH,
"ytick.major.width": JACS_LINE_WIDTH,
"xtick.minor.width": JACS_LINE_WIDTH,
"ytick.minor.width": JACS_LINE_WIDTH,
"xtick.major.size": 3.0,
"ytick.major.size": 3.0,
"xtick.minor.size": 1.5,
"ytick.minor.size": 1.5,
"legend.frameon": False,
"legend.fontsize": max(fontsize - 2, 5),
"figure.dpi": 300,
"savefig.dpi": 1200,
"savefig.bbox": "tight",
"savefig.pad_inches": 0.02,
}
)
def _style_axis_for_jacs(ax: matplotlib.axes.Axes, fontsize: float = 8, legend: bool = True) -> None:
"""Apply consistent tick and spine formatting to a matplotlib axis."""
ax.tick_params(
axis="both",
which="major",
labelsize=fontsize,
width=JACS_LINE_WIDTH,
length=3.0,
)
ax.tick_params(axis="both", which="minor", width=JACS_LINE_WIDTH, length=1.5)
for spine in ax.spines.values():
spine.set_linewidth(JACS_LINE_WIDTH)
if legend:
ax.legend(frameon=False, fontsize=max(fontsize - 2, 5))
def mat_avg(name: Path, select: list) -> tuple[np.ndarray, np.ndarray]:
"""
Average the TA matrice of multiple experiments.
Args:
name (Path): The path of the file to be loaded (e.g., "dir/expt_").
select (list): A list of indices for the selected experiments to be loaded.
For example, [0, 2, 3, 5] will load files like "expt_1", "expt_3", "expt_4", "expt_6".
Returns:
tuple[np.ndarray, np.ndarray]: A tuple containing:
- The averaged matrix (2D numpy array).
- The 3D matrix array with all experiments loaded.
Notes:
- The function attempts to load files using `Path` methods. If it fails, it falls back to string-based file paths.
- The averaged matrix is saved as a new file with "averaged" appended to the base name.
"""
try:
first_array = np.loadtxt(name.with_name(name.stem + str(select[0] + 1)))
except Exception as e:
print(f"Error in loading file using Pathlib: {e}")
first_array = np.loadtxt(str(name) + str(select[0] + 1))
rows, columns = first_array.shape
mat_array = np.zeros((rows, columns, len(select)))
for i, x in enumerate(select):
try:
mat_array[:, :, i] = np.loadtxt(name.with_name(name.stem + str(x + 1)))
except Exception as e:
print(f"Error in loading file using Pathlib: {e}")
mat_array[:, :, i] = np.loadtxt(str(name) + str(x + 1))
sum_array = np.sum(mat_array, axis=2)
avg_array = sum_array / len(select)
try:
np.savetxt(
name.with_name(name.stem + "averaged"), avg_array, fmt="%f", delimiter="\t"
)
except Exception as e:
print(f"Error in saving file using Pathlib: {e}")
np.savetxt(str(name) + "averaged", avg_array, fmt="%f", delimiter="\t")
return avg_array, mat_array
def load_tatime(mat: np.ndarray) -> np.ndarray:
"""Load the time axis TATime0 of the TA matrix
Args:
mat (np.ndarray): The TA matrix as a numpy array
Returns:
np.ndarray: The time axis of the TA matrix
"""
tatime = mat[: mat.shape[1] - 2, 0]
return tatime
def load_tawavelength(mat: np.ndarray) -> np.ndarray:
"""Load the wavelength axis TAWavelength0 of the TA matrix
Args:
mat (2darray): The TA matrix as a numpy array
Returns:
1darray: The wavelength axis of the TA matrix
"""
tawavelength = mat[:, 1]
return tawavelength
class load_single:
"""
Load and process a single TA spectrum file.
Args:
file_name (str | Path): The name of the file to be loaded (e.g., "expt_1").
Attributes:
filename (Path): The full path of the file.
filestem (str): The stem (name without extension) of the file.
tawavelength (np.ndarray): The wavelength axis of the TA spectrum.
spec_ta (np.ndarray): The TA spectrum data.
spec_on (np.ndarray): The "ON" spectrum data.
spec_off (np.ndarray): The "OFF" spectrum data.
ax (list | None): Axes for plotting.
Methods:
plot(ylim: tuple[float, float] | None = None) -> None:
Plot the TA spectrum along with the ON and OFF spectra.
Notes:
- The class automatically loads and processes the file upon initialization.
- The `plot` method provides an option to set y-axis limits for the TA spectrum.
"""
def __init__(self, file_name: str | Path) -> None:
self.filename = Path(file_name)
self.filestem = self.filename.stem
data = np.loadtxt(self.filename)
self.tawavelength = data[:, 0]
self.spec_ta = data[:, 1]
self.spec_on = data[:, 2]
self.spec_off = data[:, 3]
self.fig_spec = None
self.ax_spec = None
def plot(self, ylim: tuple[float, float] | None = None) -> None:
"""Plot the TA spectrum, ON and OFF spectrum
Args:
ylim (tuple, optional): y axis limit of TA spectrum. Defaults to None.
"""
self.fig_spec, self.ax_spec = plt.subplots(nrows=2)
self.ax_spec[1].plot(self.tawavelength, self.spec_ta, label="TA")
self.ax_spec[0].plot(self.tawavelength, self.spec_on, label="ON")
self.ax_spec[0].plot(self.tawavelength, self.spec_off, label="OFF")
self.ax_spec[0].legend()
self.ax_spec[1].set_xlabel("Wavelength (nm)")
self.ax_spec[0].set_ylabel("ΔOD")
self.ax_spec[1].set_ylabel("ΔOD")
self.ax_spec[1].set_ylim(ylim)
self.ax_spec[1].set_title("TA spectrum")
self.ax_spec[0].set_title("On and Off spectrum")
self.fig_spec.show()
class load_spectra:
"""class to include single or multiple experiments (average) TA matrix
Args:
file_inp (str): The name of the file to be loaded. e.g. "expt_". if num_spec = 1, file_inp should use full name, e.g. "expt_3".
num_spec (int, optional): num_spec is the number of experiments to be loaded. e.g. 5. Note this will load expt_1, expt_2, expt_3, expt_4, expt_5. Defaults to None.
select (list, optional): select is a list of the selected experiments to be loaded. e.g. [0,2,3,5]. Defaults to None.
Notes:
select [0,2,3,5] will load expt_1, expt_3, expt_4, expt_6. select CANNOT be a one element list.
Use num_spec = 1 instead for single experiment.
"""
def __init__(
self, file_name: str, num_spec: int, select: list | None = None
) -> None:
self.file_name = file_name
self.file_inp = Path(self.file_name)
self.file_inp_stem = self.file_inp.stem
if select is None and (num_spec is None or num_spec == 1):
self.num_spec = 1
self.tamatrix_avg = np.loadtxt(self.file_inp)
self.tatime = load_tatime(self.tamatrix_avg)
self.tawavelength = load_tawavelength(self.tamatrix_avg)
elif select is not None:
self.select = select
self.num_spec = len(self.select)
self.tamatrix_avg, self.mat_array = mat_avg(self.file_inp, self.select)
# load tatime and tawavelength axes
self.tatime = load_tatime(self.tamatrix_avg)
self.tawavelength = load_tawavelength(self.tamatrix_avg)
elif num_spec >= 1:
self.num_spec = num_spec
# average the matrix
self.select = list(range(self.num_spec))
self.tamatrix_avg, self.mat_array = mat_avg(self.file_inp, self.select)
# load tatime and tawavelength axes
self.tatime = load_tatime(self.tamatrix_avg)
self.tawavelength = load_tawavelength(self.tamatrix_avg)
else:
print("Invalid input. Please check the input parameters")
return
def mat_sub(self, obj_bg: "load_spectra", modifier: float | None = None) -> None:
"""Subtract background from the TA matrix
Args:
obj_bg (load_spectra): load_spectra object of the blank background TA matrix
modifier (float, optional): modifier applied (multiplied) to the blank for subtraction. Defaults to None.
"""
if modifier is None:
modifier = 1
self.tamatrix_avg = self.tamatrix_avg - obj_bg.tamatrix_avg * modifier
self.mat_array = (
self.mat_array - obj_bg.tamatrix_avg[:, :, np.newaxis] * modifier
)
def get_1ps(self) -> np.ndarray:
"""Get the 1ps spectrum and plot it
Returns:
1darray: 1ps spectrum
"""
diff = np.abs(self.tatime - 1)
pt = pt = np.argmin(diff)
self.spec_1ps = self.tamatrix_avg[:, pt + 2]
self.fig_s, self.ax_s = plt.subplots()
self.ax_s.plot(self.tawavelength, self.spec_1ps)
try:
self.ax_s.set_title(self.file_inp.stem)
except Exception as e:
print(f"Error in loading file using Pathlib: {e}")
self.ax_s.set_title(self.file_name)
self.ax_s.set_xlabel("Wavelength (nm)")
self.ax_s.set_ylabel("ΔOD")
return self.spec_1ps
def get_traces(self, wavelength: float, disable_plot: bool = False) -> np.ndarray:
"""Get the traces at a specific wavelength and plot them
Args:
wavelength (num): The wavelength to be plotted
disable_plot (_type_, optional): Not in use currently. Defaults to None.
Returns:
2darray: The traces at the specific wavelength
"""
self.fig_k, self.ax_k = plt.subplots()
self.trace_array = np.zeros((len(self.tatime), self.num_spec))
diff = np.abs(self.tawavelength - wavelength)
pt = np.argmin(diff)
if self.num_spec == 1:
self.trace_avg = self.tamatrix_avg[pt, 2:]
self.ax_k.plot(
np.log(self.tatime), self.trace_avg, label=f"{wavelength} nm trace"
)
else:
for i, x in enumerate(self.select):
self.trace_array[:, i] = self.mat_array[pt, 2:, i]
self.ax_k.plot(
np.log(self.tatime),
self.trace_array[:, i],
label=f"{wavelength} nm trace {x + 1}",
)
self.trace_avg = self.tamatrix_avg[pt, 2:]
self.ax_k.plot(
np.log(self.tatime),
self.trace_avg,
label=f"{wavelength} nm trace averaged",
)
self.ax_k.legend()
self.ax_k.set_xlabel("Time (Log scale ps)")
self.ax_k.set_ylabel("ΔOD")
try:
self.ax_k.set_title(self.file_inp.stem)
except Exception as e:
print(f"Error in loading file using Pathlib: {e}")
self.ax_k.set_title(self.file_name)
return self.trace_avg
def fit_kinetic(
self,
wavelength: float,
num_of_exp: int = 1,
params: lmfit.Parameters | None = None,
time_split: float = 5.0,
w1_vary: bool = True,
w12_vary: bool = True,
) -> lmfit.model.ModelResult:
"""Fit the kinetics at a specific wavelength
Args:
wavelength (num): The wavelength to be fitted
num_of_exp (int, optional): Number of exponential to be fitted. Defaults to None.
params (lmfit.Parameters, optional): The initial parameters for the fitting. Defaults to None.
time_split (num, optional): The time point to split the plot. Defaults to None.
w1_vary (bool, optional): Vary the w1 parameter. Defaults to None.
w12_vary (bool, optional): Vary the w12 parameter. Defaults to None.
Returns:
lmfit.model.ModelResult: The result of the fitting
"""
if params is None:
params = params_init(num_of_exp, w1_vary=w1_vary, w12_vary=w12_vary)
# plot spectra together
diff = np.abs(self.tawavelength - wavelength)
wavelength_index = np.argmin(np.abs(diff))
y = self.trace_avg
t = self.tatime
lmodel = lmfit.Model(multiexp_func)
result = lmodel.fit(
y,
params=params,
t=t,
max_nfev=100000,
ftol=1e-9,
xtol=1e-9,
nan_policy="omit",
)
# print(result.fit_report())
print("-------------------------------")
print(
f"{self.file_inp.stem} kinetics fit at {self.tawavelength[wavelength_index]:.2f} nm"
)
print("-------------------------------")
print(f"chi-square: {result.chisqr:11.6f}")
pearsonr = np.corrcoef(result.best_fit, y)[0, 1]
print(f"Pearson's R: {pearsonr:11.6f}")
print("-------------------------------")
print("Parameter Value Stderr")
for name, param in result.params.items():
print(f"{name:7s} {param.value:11.6f} {param.stderr:11.6f}")
print("-------------------------------")
# result.plot_fit()
pt_split = find_closest_value([time_split], self.tatime)[0]
fig, (ax1, ax2) = plt.subplots(
1, 2, sharey=True, gridspec_kw={"width_ratios": [2, 3]}
)
fig.subplots_adjust(wspace=0.05)
ax1.scatter(t[:pt_split], y[:pt_split], marker="o", color="black")
ax1.plot(t[:pt_split], result.best_fit[:pt_split], color="red")
ax1.set_xlim(t[0], t[pt_split - 1])
# ax1.set_ylim(min(result.best_fit), max(result.best_fit)*1.1)
ax1.spines["right"].set_visible(False)
ax1.tick_params(right=False)
ax2.scatter(
t[pt_split:],
y[pt_split:],
marker="o",
color="black",
label=f"{self.tawavelength[wavelength_index]:.2f} nm",
)
ax2.plot(
t[pt_split:],
result.best_fit[pt_split:],
color="red",
label=f"{self.tawavelength[wavelength_index]:.2f} nm fit",
)
ax2.set_xscale("log")
ax2.set_xlim(t[pt_split - 1], t[-1])
# ax2.set_ylim(min(result.best_fit), max(result.best_fit)*1.1)
ax2.spines["left"].set_visible(False)
ax2.tick_params(left=False)
# Creating a gap between the subplots to indicate the broken axis
gap = 0.1
ax1.spines["right"].set_position(("outward", gap))
ax2.spines["left"].set_position(("outward", gap))
ax1.axhline(0, color="black", linestyle="-", linewidth=0.5)
ax2.axhline(0, color="black", linestyle="-", linewidth=0.5)
# Centered title above subplots
fig.suptitle(self.file_inp.stem, fontsize=10, ha="center")
plt.legend(loc="best")
fig.text(0.5, 0.04, "Time (ps)", ha="center", fontsize=8)
ax1.set_ylabel("ΔOD")
plt.show()
return result
def correct_burn(self, wavelength: float, disable_plot: bool = False) -> None:
"""Correct the sample burning (degredation) according to selected wavelength in the TA matrix. Savethe corrected matrix as a new TA matrix file
Args:
wavelength (num): The wavelength to be sampled for burning correction
disable_plot (_type_, optional): Not in use. Defaults to None.
"""
self.fig_b, self.ax_b = plt.subplots()
self.trace_array = np.zeros((len(self.tatime), self.num_spec))
burn_correction = np.zeros_like(self.tatime)
pts_time = np.arange(len(self.tatime))
diff = np.abs(self.tawavelength - wavelength)
pt = np.argmin(diff)
diff2 = np.abs(self.tatime - 1)
pt2 = np.argmin(diff2)
if self.num_spec == 1:
print("single experiment. No burn correction")
else:
percent_per_point = (
(
self.mat_array[pt, pt2 + 2, 0]
- self.mat_array[pt, pt2 + 2, len(self.select) - 1]
)
/ self.mat_array[pt, pt2 + 2, 0]
/ (len(self.tatime) * (len(self.select) - 1))
)
burn_correction = 1 + percent_per_point * pts_time
self.ax_b.plot(pts_time, burn_correction, label="Burn correction")
self.ax_b.legend()
self.ax_b.set_xlabel("time point")
self.ax_b.set_ylabel("correction")
self.tamatrix_avg_burncorr = self.tamatrix_avg.copy()
self.tamatrix_avg_burncorr[:, 2:] *= burn_correction
np.savetxt(
self.file_name + "avg_burncorrected",
self.tamatrix_avg_burncorr,
fmt="%f",
delimiter="\t",
)
class compare_traces:
"""compare traces from load_spectra object
Args:
obj (load_spectra): first load_spectra object
wavelength (num): wavelength to be compared
"""
def __init__(self, obj: "load_spectra", wavelength: float) -> None:
self.wavelength = wavelength
self.tatime = obj.tatime
trace = obj.get_traces(wavelength, disable_plot=True).reshape(1, -1)
self.trace_array = np.empty((0, len(self.tatime)))
print(self.trace_array.size)
print(trace.size)
self.trace_array = np.append(self.trace_array, trace, axis=0)
self.wavelength_list = [self.wavelength]
self.name_list = [obj.file_inp]
def add_trace(self, obj: "load_spectra", wavelength: float | None = None) -> None:
"""add traces from another load_spectra object
Args:
obj (load_spectra): load_spectra object
wavelength (num, optional): wavelength to be added if want to compare traces at diff wavelength. Defaults to None will use the wavelength from first object.
"""
self.name_list.append(obj.file_inp)
if wavelength is None:
trace_toadd = obj.get_traces(self.wavelength, disable_plot=True).reshape(
1, -1
)
self.wavelength_list.append(self.wavelength)
else:
try:
trace_toadd = obj.get_traces(wavelength, disable_plot=True).reshape(
1, -1
)
self.wavelength_list.append(wavelength)
except AttributeError:
print("Invalid wavelength")
return
self.trace_array = np.append(self.trace_array, trace_toadd, axis=0)
def plot(self) -> None:
"""plot the loaded traces"""
self.fig, self.ax = plt.subplots()
for i in range(len(self.trace_array)):
self.ax.plot(
np.log(self.tatime),
self.trace_array[i, :] / np.max(np.abs(self.trace_array[i, :])),
label=f"{self.name_list[i]} @ {self.wavelength_list[i]} nm",
)
self.ax.legend()
self.ax.set_title("Normalized traces with logarithmic time axis")
self.ax.set_xlabel("Time (Log scale ps)")
self.ax.set_ylabel("ΔOD")
class glotaran:
"""Class to export the IGOR generated TAmatrix to Glotaran input format. Initialize the class with the TA matrix (Output from IGOR macro auto_tcorr. Without time and wavelength axis.
NOT original TAMatrix like file), time axis and wavelength axis. Use SaveMatrix()macro in IGOR to get those inputs.
Output file will be named as matrix_corr+"glo.ascii"
Args:
matrix_corr (str): The filename of the TA matrix file to be loaded.
tatime (str): The filename of the time axis
tawavelength (str): The filename of the wavelength axis
"""
def __init__(self, matrix_corr: str | Path, tatime: str, tawavelength: str) -> None:
self.filename = Path(matrix_corr)
self.filestem = self.filename.stem
self.tatime = np.loadtxt(tatime)
self.tawavelength = np.loadtxt(tawavelength)
# np.genfromtext will read nan as nan, avoid size mismatch with np.loadtxt
self.output_matrix = np.genfromtxt(
matrix_corr, delimiter="\t", filling_values=np.nan
)
self.output_matrix = np.append(
self.tatime.reshape(1, -1), self.output_matrix, axis=0
)
self.output_matrix = np.append(
np.append("", self.tawavelength).reshape(1, -1).T,
self.output_matrix,
axis=1,
)
self.header = (
self.filestem + "\n\nTime explicit\nintervalnr " + str(len(self.tatime))
)
np.savetxt(
self.filename.with_suffix(".ascii"),
self.output_matrix,
header=self.header,
fmt="%s",
comments="",
delimiter="\t",
)
class merge_glotaran:
"""Class to merge the Glotaran input files from visible and IR region
The output will be saved as filename+"_ir_merged.ascii"
Maybe write this as a function instead
Args:
glotaran_vis (glotaran): The load_glotaran object of the visible region
glotaran_ir (glotaran): The load_glotaran object of the IR region
vis_max (num): The maximum wavelength of the visible region
ir_min (num): The minimum wavelength of the IR region
"""
def __init__(
self,
glotaran_vis: "glotaran",
glotaran_ir: "glotaran",
vis_max: float,
ir_min: float,
) -> None:
self.glotaran_vis = glotaran_vis
self.glotaran_ir = glotaran_ir
if np.array_equal(self.glotaran_vis.tatime, self.glotaran_ir.tatime):
self.tatime = self.glotaran_vis.tatime
else:
print("Time axis mismatch")
self.vis_max_pt = np.argmin(np.abs(self.glotaran_vis.tawavelength - vis_max))
self.ir_min_pt = np.argmin(np.abs(self.glotaran_ir.tawavelength - ir_min))
self.output_matrix = np.vstack(
(
self.glotaran_vis.output_matrix[0 : self.vis_max_pt + 1, :],
self.glotaran_ir.output_matrix[self.ir_min_pt :, :],
)
)
self.header = self.glotaran_vis.header
try:
# May need further work to save the file correctly
np.savetxt(
self.glotaran_vis.filename.with_name(
self.glotaran_vis.filestem + "_ir_merged"
).with_suffix(".ascii"),
self.output_matrix,
header=self.header,
fmt="%s",
comments="",
delimiter="\t",
)
except Exception as e:
print(f"Error in merging using Pathlib: {e}")
np.savetxt(
self.glotaran_vis.filename.with_name(
self.glotaran_vis.filestem + "_ir_merged"
).with_suffix(".ascii"),
self.output_matrix,
header=self.header,
fmt="%s",
comments="",
delimiter="\t",
)
print("Load with filename")
class load_glotaran:
"""Class to load the Glotaran input file. Output will be the time axis, wavelength axis and the TA matrix without time and wavelength axis
Args:
dir (str): The filename of the Glotaran input file to be loaded.
"""
def __init__(self, dir):
self.filename = Path(dir)
try:
self.filestem = self.filename.stem
except Exception as e:
print(f"Error in loading Glotaran file using Pathlib: {e}")
self.filestem = dir.split(".")[-2]
print("Load with filename")
matrix = np.loadtxt(dir, skiprows=4, delimiter="\t", dtype=str)
matrix[matrix == ""] = np.nan
matrix = matrix.astype(np.float64)
self.tatime = matrix[0, 1:]
self.tawavelength = matrix[1:, 0]
self.tamatrix = matrix[1:, 1:]
def batch_load_glotaran(
dir: Path | str = Path("."),
time_pts: list[float] = [0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000],
figsize: tuple[float, float] = (6.4, 4.8),
save: bool = False,
fontsize: float = 8,
xlim: tuple[float, float] | None = None,
ylim: tuple[float, float] | None = None,
) -> (
tuple[list[Path], list["tamatrix_importer"], dict[str, "tamatrix_importer"]] | None
):
"""Batch load all the Glotaran input files in the directory and process them.
This function scans the specified directory for .ascii files, loads each file using
the load_glotaran function, processes them with tamatrix_importer, and automatically
extracts time-resolved spectra at specific time points.
Args:
dir (str, optional): The directory path where Glotaran input files (.ascii) are stored.
Defaults to the current directory (".").
time_pts (list, optional): List of time points (in ps) for extracting spectra.
Defaults to [0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000].
xlim (tuple, optional): x-axis limits for the plot. Defaults to None.
ylim (tuple, optional): y-axis limits for the plot. Defaults to None.
figsize (tuple, optional): Figure size for the plot. Defaults to (8, 4).
Returns:
tuple: A tuple containing three elements:
- ascii_files_list (list): List of Path objects for all found .ascii files.
- glotaran_instance_list (list): List of processed Glotaran objects.
- glotaran_instance_dict (dict): Dictionary mapping filenames (without extension)
to their corresponding Glotaran objects.
Raises:
Exception: If there is an error loading the directory with Pathlib.
Notes:
- The function automatically applies auto_taspectra to each loaded file with
predefined time points [0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000].
- If the directory doesn't exist, the function prints "Invalid directory" and returns None.
"""
try:
current_dir = Path(dir)
except Exception as e:
print(f"Error in loading directory using Pathlib: {e}")
return
ascii_files_list = list(current_dir.glob("*.ascii"))
print(ascii_files_list)
glotaran_instance_list: list["tamatrix_importer"] = []
glotaran_instance_dict = {}
for i, ascii_file in enumerate(ascii_files_list):
print(i, ascii_file)
glotaran_instance_list.append(
tamatrix_importer(load_glotaran=load_glotaran(ascii_file))
)
glotaran_instance_list[i].auto_taspectra(
mat="tcorr",
time_pts=time_pts,
xlim=xlim,
ylim=ylim,
figsize=figsize,
fontsize=fontsize,
save=save,
)
glotaran_instance_dict[ascii_files_list[i].stem] = glotaran_instance_list[i]
return ascii_files_list, glotaran_instance_list, glotaran_instance_dict
class glotaran_output:
"""Class to plot Glotaran output files, including traces and DAS (Decay Associated Spectra).
This class provides methods to visualize and analyze Glotaran output files:
- Traces: "filename_traces.ascii"
- DAS: "filename_DAS.ascii"
- Summary: "filename_summary.txt"
Usage:
- Save the DAS as "filename_DAS.ascii", traces as "filename_traces.ascii", and summary as "filename_summary.txt".
- For the plot_trace_fit method, ensure the Glotaran input file "filename.ascii" is present.
Args:
dir (str): Path to the file (without extension) for the Glotaran output set.
low_threshold (float, optional): Lower threshold (in ps) to filter out ultrafast DAS. Default is 0.07.
Raises:
Exception: If there is an error loading the directory or files.
"""
def __init__(self, dir: str):
self.rate_list = []
self.error_list = []
self.filename = dir
self.rate_list = []
self.error_list = []
try:
with open(dir + "_summary.txt", "r") as file:
find_rate = False
for line in file:
stripped_line = line.strip()
if stripped_line.startswith(
"Estimated Kinetic parameters: Dataset1:"
):
# Split the line by spaces or commas and convert to float
self.rate_list = [
value for value in stripped_line.replace(",", " ").split()
]
find_rate = True
if find_rate is True and stripped_line.startswith(
"Standard errors:"
):
self.error_list = [
value for value in stripped_line.replace(",", " ").split()
]
find_rate = False
try:
if stripped_line.startswith("Estimated Irf parameters: Dataset1:"):
self.irf_paramters = [
value for value in stripped_line.replace(",", " ").split()
]
except Exception as e:
print(f"Error in loading Irf parameters: {e}")
# Convert the list of rate and error to a NumPy array
try:
self.irf_parameters_array = np.array(self.irf_paramters[4:]).astype(float)
self.irf_offset = self.irf_parameters_array[0]
self.irf_width = self.irf_parameters_array[1]
except Exception as e:
print(f"Error in loading Irf parameters: {e}")
self.rate_array = np.array(self.rate_list[4:]).astype(float)
self.error_array = np.array(self.error_list[2:]).astype(float)
except Exception as e:
print(f"Error in loading file: {e}")
def _load_das(self) -> None:
"""Load decay-associated spectra when they are first needed."""
if not hasattr(self, "das"):
self.das = np.loadtxt(self.filename + "_DAS.ascii", skiprows=1)
def _load_traces(self) -> None:
"""Load component traces and apply Glotaran's positive IRF offset fix."""
if hasattr(self, "traces"):
return
self.traces = np.loadtxt(self.filename + "_traces.ascii", skiprows=1)
if getattr(self, "irf_offset", 0) > 0:
self.traces[:, 0::2] += self.irf_offset
def plot_das(
self,
low_threshold: float = 0.07,
save: bool = False,
figsize: tuple[float, float] = (6.4, 4.8),
fontsize: float = 8,
time_split: float = 1,
title: str | None = None,
xlabel: str | None = None,
ylabel: str | None = None,
legend_loc: str | None = None,
xlim: tuple[float, float] | None = None,
ylim: tuple[float, float] | None = None,
) -> None:
_apply_jacs_style(fontsize=fontsize)
# Load the DAS and traces data
self._load_das()
if xlim is not None:
xmin = find_closest_value([xlim[0]], self.das[:,0])[0]
xmax = find_closest_value([xlim[1]], self.das[:,0])[0]
self.fig_das, self.ax_das = plt.subplots(figsize=figsize)
self.fig_das.subplots_adjust(left=0.2)
# Set title
if title:
self.fig_das.suptitle(title, fontsize=fontsize, ha="center")
else:
self.fig_das.suptitle(
self.filename.replace("_", " "), fontsize=fontsize, ha="center"
)
if self.das.shape[1] != 2 * self.rate_array.shape[0]:
print("das and rate array size mismatch")
for i in range(int(self.das.shape[1] / 2)):
if 1 / self.rate_array[i] < low_threshold:
continue
else:
self.ax_das.plot(
self.das[xmin:xmax, 2 * i],
self.das[xmin:xmax, 2 * i + 1],
label=(
"Long-term"
if 1 / self.rate_array[i] > 10000.0
else f"{1 / self.rate_array[i]:.2f} ps"
),
)
colorwaves(self.ax_das)
self.ax_das.tick_params(axis="both", which="major", labelsize=fontsize)
# Set legend location
if legend_loc:
self.ax_das.legend(loc=legend_loc, fontsize=fontsize)
else:
self.ax_das.legend(fontsize=fontsize)
# Set x and y labels
if xlabel:
self.ax_das.set_xlabel(xlabel, fontsize=fontsize)
else:
self.ax_das.set_xlabel("Wavelength (nm)", fontsize=fontsize)
if ylabel:
self.ax_das.set_ylabel(ylabel, fontsize=fontsize)
else:
self.ax_das.set_ylabel("DAS", fontsize=fontsize)
# print(self.das[:,i], self.das[:,i+1])
self.ax_das.axhline(y=0, c="black", linewidth=JACS_LINE_WIDTH, zorder=0)
_style_axis_for_jacs(self.ax_das, fontsize=fontsize)
self.ax_das.set_xlim(xlim)
self.ax_das.autoscale(axis='y')
self.ax_das.set_ylim(ylim)
if save:
self.fig_das.savefig(
self.filename + "_DAS.svg",format="svg"
)
# Load and plot the das trace data
try:
self._load_traces()
self.fig_traces, (self.ax_traces, self.ax_traces_2) = new_split_axes(
figsize=figsize
)
self.ax_traces.tick_params(axis="both", which="major", labelsize=fontsize)
self.ax_traces_2.tick_params(axis="both", which="major", labelsize=fontsize)
self.fig_traces.suptitle(
self.filename.replace("_", " "), fontsize=fontsize, ha="center"
)
for i in range(int(self.traces.shape[1] / 2)):
if 1 / self.rate_array[i] < low_threshold:
continue
else:
self.ax_traces.plot(
self.traces[:, 2 * i],
self.traces[:, 2 * i + 1],
label=(
"Long-term"
if 1 / self.rate_array[i] > 10000.0
else f"{1 / self.rate_array[i]:.2f} ps"
),
)
self.ax_traces_2.plot(
self.traces[:, 2 * i],
self.traces[:, 2 * i + 1],
label=(
"Long-term"
if 1 / self.rate_array[i] > 10000.0
else f"{1 / self.rate_array[i]:.2f} ps"
),
)
self.ax_traces.set_xlim(-0.5, time_split)
self.ax_traces_2.set_xlim(time_split + 0.01, self.traces[-1, 2 * i])
self.ax_traces.spines["right"].set_visible(False)
self.ax_traces_2.spines["left"].set_visible(False)
self.ax_traces.yaxis.tick_left()
self.ax_traces.tick_params(labelright=False)
self.ax_traces_2.tick_params(axis="y", labelleft=False,left=False)
# self.ax_traces_2.yaxis.tick_right()
d = 0.5 # proportion of vertical to horizontal extent of the slanted line
kwargs = dict(
marker=[(-1, -d), (1, d)],
markersize=12,
linestyle="none",
color="k",
mec="k",
mew=1,
clip_on=False,
)
self.ax_traces.plot(
[1, 1],
[1, 0],
transform=self.ax_traces.transAxes,
**kwargs, # type: ignore
)
self.ax_traces_2.plot(
[0, 0],
[0, 1],
transform=self.ax_traces_2.transAxes,
**kwargs, # type: ignore
)
colorwaves(self.ax_traces)
colorwaves(self.ax_traces_2)
self.ax_traces_2.legend(loc="best", frameon=False)
self.ax_traces_2.set_xscale("log")
self.ax_traces_2.set_xlabel("Time (ps)")
self.ax_traces_2.xaxis.set_label_coords(0.2, -0.15)
self.ax_traces.set_ylabel("Amplitude")
_style_axis_for_jacs(self.ax_traces, fontsize=fontsize, legend=False)
_style_axis_for_jacs(self.ax_traces_2, fontsize=fontsize)
if save:
self.fig_traces.savefig(
self.filename + "_DAStraces.svg",
format="svg",
dpi=1200,
bbox_inches="tight",
)
except Exception as e:
print(f"No trace data found or error in loading trace data: {e}")
def plot_trace_fit(
self,
wavelength_select: list[float],
tmax: int = 1000,
figsize: tuple[float, float] = (6.4, 4.8),
save: bool = False,
time_split: float = 1,
fontsize: float = 8,
) -> None:
"""Plot the traces with the fitted curve
Args:
wavelength_select (list[float]): The wavelength to be fitted..
tmax (int, optional): The maximum time for the plot. Defaults to 1000.
figsize (tuple[int, int], optional): The size of the figure. Defaults to (8, 3).
"""
_apply_jacs_style(fontsize=fontsize)
self._load_das()
self._load_traces()
self.wavelength_select = wavelength_select
self.glotaran_matrix_dir = _get_glotaran_base_path(self.filename)
try:
self.glotaran_matrix = tamatrix_importer(
load_glotaran=load_glotaran(
self.glotaran_matrix_dir.with_suffix(".ascii")
)
)
except FileNotFoundError:
print(f"Glotaran matrix file not found: {self.glotaran_matrix_dir}")
return
kinetics_set = self.glotaran_matrix.auto_takinetics(
self.wavelength_select, tmax=tmax, plot=False
)
pts_select_fit = find_closest_value(wavelength_select, self.das[:, 0])
self.kinect_fit_set = np.array([])
if getattr(self, "irf_width", None):
self.cdf = norm.cdf(self.traces[:, 0], loc=0, scale=self.irf_width)
self.fig_kin_fit, (self.ax_kin_fit1, self.ax_kin_fit2) = new_split_axes(
figsize=figsize
)
for i in range(len(kinetics_set)):
kinetic_fit = np.zeros_like(self.traces[:, 0])
for j in range(int(self.das.shape[1] / 2)):
kinetic_fit += (
self.das[pts_select_fit[i], 2 * j + 1] * self.traces[:, 2 * j + 1]
)