-
Notifications
You must be signed in to change notification settings - Fork 2
/
Model.py
1282 lines (1122 loc) · 37.9 KB
/
Model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as col
import matplotlib.ticker as mticker
import os
import numpy as np
from lmfit import minimize, Parameters, fit_report
import scipy.integrate as scint
from models import Models
mpl.use("QtAgg")
plt.style.use('./AK_Richert.mplstyle')
#plt.style.use('default')
plt.ion()
class Model:
def __init__(self, delays_filename, spectra_filename, lambdas_filename,
d_limits, l_limits, model, opt_method, ivp_method):
"""
Initiates an object of the class Model with preset data and model.
Presets a list of colors for the 3-in-1 plot.
Parameters
----------
delays_filename : string
The path to the file for the delay values.
spectra_filename : string
The path to the file for the spectra values.
lambdas_filename : string
The path to the file for the lambda values.
d_limits : list with two int/float elements
Lower and upper limits for the delay values.
l_limits : list with two int/float elements
Lower and upper limits for the lambda values.
model : int/string
Variable for the choice of model (DAS or which SAS).
Returns
-------
None.
"""
self.d_borders = self.findBorders(d_limits, delays_filename)
self.l_borders = self.findBorders(l_limits, lambdas_filename)
self.name = self.findName(delays_filename)
self.delays = self.initDelays(delays_filename)
self.spectra = self.initSpectra(spectra_filename)
self.lambdas = self.initLambdas(lambdas_filename)
self.model = model
self.opt_method = opt_method
self.ivp_method = ivp_method
def findBorders(self, limits, filename):
"""
Finds the indices for the chosen limits in a set of values.
If none are chosen, the borders will automatically be set.
Parameters
----------
limits : list with two int/float elements
Lower and upper limits for the values in the given file.
filename : string
The path to the file for the values.
Returns
-------
borders : list with two int elements
Indexes for the lower and upper limit of the values in the file.
"""
values = np.genfromtxt(filename)
borders = [0, 1]
if limits is None:
limits = [None, None]
if limits[0] is None:
limits[0] = min(values)
if limits[1] is None:
limits[1] = max(values)
borders[0] = round(np.absolute(values - limits[0]).argmin(), 2)
borders[1] = round(np.absolute(values - limits[1]).argmin(), 2)
return borders
def findName(self, delays_filename):
"""
Find the name of the mesured data.
Parameters
----------
delays_filename : string
The path to the file for the delay values.
Returns
-------
name : string
Name of the measured data.
"""
temp = delays_filename[::-1]
temp = temp.index("/")
name = delays_filename[-temp:-11]
path = delays_filename[:-temp]
if not os.path.exists(path + 'analysis'):
os.makedirs(path + 'analysis')
self.path = delays_filename[:-temp] + "analysis/"
return name
def initDelays(self, delays_filename):
"""
Applys the border to the original data of the delays.
Parameters
----------
delays_filename : string
The path to the file for the delay values.
Returns
-------
delays : np.array
Contains the values of the delays within the chosen borders.
"""
values = np.genfromtxt(delays_filename)
delays = values[self.d_borders[0]: self.d_borders[1]]
return delays
def initLambdas(self, lambdas_filename):
"""
Applys the border to the original data of the lambdas.
Parameters
----------
lambdas_filename : string
The path to the file for the lambda values.
Returns
-------
lambdas : np.array
Contains the values of the lambdas within the chosen borders.
"""
values = np.genfromtxt(lambdas_filename)
lambdas = values[self.l_borders[0]: self.l_borders[1]]
return lambdas
def initSpectra(self, spectra_filename):
"""
Applys the border to the original data of the spectra.
Parameters
----------
spectra_filename : string
The path to the file for the spectra values.
Returns
-------
spectra : np.array
Contains the values of the spectra within the chosen borders.
"""
values = np.genfromtxt(spectra_filename)
if "eprspectra.txt" in spectra_filename:
values = values.T
spectra = values[self.l_borders[0]: self.l_borders[1],
self.d_borders[0]: self.d_borders[1]]
return spectra
# Decay Associated Spectra
def genE_tau(self, tau):
"""
Generatest the matrix E with different values for the delays in every
column and different values for tau in the rows.
Parameters
----------
tau : list
A list of the given values for tau, the decay constant.
delays : np.array
The measured delays of the TA-spectrum.
Returns
-------
E_tau : np.array
The matrix of E_tau with the exponential decay functions.
"""
E_tau = np.zeros(shape=(len(tau), len(self.delays)))
for i in range(len(tau)):
for j in range(len(self.delays)):
E_tau[i][j] = -self.delays[j] / tau[i]
E_tau = np.exp(E_tau)
return E_tau
# Species Associated Spectra
def setInitialConcentrations(self, C_0):
"""
Creates an array with the initial concentrations for the GTA.
Parameters
----------
C_0 : list
The list that contains values for C_0 set by the user.
Can be empty.
Returns
-------
C_0 : np.array/list
Contains either the user-input for C_0 or a concentration of 1 for
the first species and 0 for all the others.
"""
if C_0 == []:
C_0 = np.zeros(self.n)
C_0[0] = 1
self.C_0 = C_0
return C_0
def calcdCdt(self, delays, C_0):
"""
Calculates the matrix for the derivate of the concentration
by the time.
Parameters
----------
delays : np.array
The measured delays of the TA-spectrum.
C_0 : np.array/list
contains either the user-input for C_0 or a concentration of 1 for
the first species and 0 for all the others
Returns
-------
dCdt : np.array
derivate of the concentration by the time
"""
dCdt = self.K @ C_0
return dCdt
def solveDiff(self, ivp_method):
"""
Solves the differential equation of dCdt = K·C.
Parameters
----------
ivp_method: string
The algorithm used by the initial value problem solver.
Returns
-------
C_t : np.array
Contains the concentration of each species at each point of
time in delays.
"""
Z = scint.solve_ivp(self.calcdCdt, [min(self.delays), max(self.delays)],
self.C_0, t_eval=self.delays, method=ivp_method)
C_t = Z.get("y")
return C_t
def getK(self, tau):
"""
Outputs the matrix K for given reaction constants x.
Parameters
----------
tau : list, np.array
An array of the reaction rate constants for the SAS.
Returns
-------
K : np.array
A 2D array which corresponds to the reaction rate constant matrix
with n-species.
n : int
The number of species.
"""
if (self.model == "custom model" or self.model == "custom matrix"):
Tau = self.regenM(tau)
n = Tau.shape[0]
ones = np.full(Tau.shape, 1)
K = np.divide(ones, Tau, out=np.zeros_like(Tau), where=Tau != 0)
else:
ones = np.full(np.array(tau).shape, 1)
k = np.divide(ones, tau, out=np.zeros_like(tau, dtype='float64'),
where=tau != 0)
mod = Models(k)
K, n = mod.getK(self.model)
self.n = n
self.K = K
return K, n
def getM_lin(self, tau_guess):
"""
Transforms the custom matrix for the SAS in a linear list and a matrix
with 1 as placeholders for the corresponding values.
Saves the matrix M_ones as an attribute.
Parameters
----------
tau_guess : list, np.array
The custom matrix for the SAS with the decay constants tau.
Returns
-------
tau : np.array
An array with the decay constants tau of the custom matrix.
"""
ones = np.full(tau_guess.shape, 1)
k_guess = np.divide(ones, tau_guess, out=np.zeros_like(tau_guess),
where=tau_guess != 0)
M_lin = []
M_ones = np.zeros(k_guess.shape)
for i in range(k_guess.shape[0]):
for j in range(k_guess.shape[1]):
if i == j and i != k_guess.shape[0] - 1:
k_guess[i][j] = 0
if k_guess[i][j] != 0:
M_ones[i][j] = 1
M_lin.append(abs(k_guess[i][j]))
tau = 1 / np.array(M_lin)
self.M_ones = M_ones
return tau
def regenM(self, tau_guess):
"""
Regenerates the custom matrix with the fitted values found in x_guess.
Replaces the 1 in the M_ones matrix with the corresponding values.
Parameters
----------
tau_guess : list, np.array
The fitted decay constants for the SAS.
Returns
-------
M : np.array
The custom matrix for the SAS with the decay constants tau.
"""
a = 0
M = np.zeros(self.M_ones.shape)
for i in range(self.M_ones.shape[0]):
for j in range(self.M_ones.shape[1]):
if self.M_ones[i][j] == 1:
M[i][j] = tau_guess[a]
if j != self.M_ones.shape[0] - 1:
M[j][j] -= tau_guess[a]
a += 1
M[-1][-1] *= -1
return M
def setTauBounds(self, tau_low, tau_high, tau):
"""
Responsible for the setting of the bounds to be used in the optimizing
of the tau values.
Parameters
----------
tau_low : list
A list which contains the lower bounds for the respective tau
values.
tau_high : list
A list which contains the upper bounds for the respective tau
values.
tau : list, np.array
An array containing the decay constants tau.
Returns
-------
None.
"""
if tau_low == []:
tau_low = [None for i in tau]
if tau_high == []:
tau_high = [None for i in tau]
for i in range(len(tau_low)):
if tau_low[i] == 0 or tau_low[i] is None:
tau_low[i] = 0.01
self.tau_low = tau_low
self.tau_high = tau_high
def getTauBounds(self, tau):
"""
This method outputs the bounds of the tau values for their optimizing.
Parameters
----------
tau : list, np.array
An array containing the decay constants tau.
Returns
-------
bounds : list
A list of the bounds for each tau value.
"""
if self.model == 0:
bounds = [(0.01, None) for i in tau]
else:
bounds = list(zip(self.tau_low, self.tau_high))
return bounds
def getM(self, tau):
"""
Outputs the matrix which will be used in the matrix reconstruction
algorithm to obtain the fitted spectra A_fit. For the DAS it is the
matrix E_tau and for SAS it is the matrix C_t from the solved
differential equation.
Parameters
----------
tau : list, np.array
An array containing the decay constants tau.
Returns
-------
M : np.array
The matrix for the matrix reconstruction algorithm.
"""
if self.model == 0: # GLA
M = self.genE_tau(tau)
self.n = len(tau)
else: # GTA
self.K, n = self.getK(tau)
M = self.solveDiff(self.ivp_method)
return M
def calcD_tau(self, tau):
"""
Calculates the matrix D_tau.
Parameters
----------
tau : list, np.array
An array containing the decay constants tau.
Returns
-------
D_tau : np.array
The matrix D_tau.
"""
res1 = self.spectra @ self.M.T
res2 = self.M @ self.M.T
inv = np.linalg.inv(res2)
D_tau = res1 @ inv
return D_tau
def calcA_tau(self, tau):
"""
Generates the reconstructed spectra matrix for the values of tau.
Parameters
----------
tau : list, np.array
An array containing the decay constants tau.
Returns
-------
A_tau : np.array
The reconstructed data matrix for the values of tau.
"""
D_tau = self.calcD_tau(tau)
A_tau = D_tau @ self.M
return A_tau
def getDifference(self, tau):
"""
Calculates the measure of difference between the initial spectra
matrix and the calculated A_tau matrix with given values for tau_guess
and self.tau_fix, if DAS.
Parameters
----------
tau_guess : list, np.array
A list of the variables tau_guess for the DAS or all tau values for
the SAS.
Returns
-------
getDifferences : np.ndarray
Difference between the modeled data and the experimental data.
"""
tau_sum = list(tau.valuesdict().values())
self.M = self.getM(tau_sum)
difference = self.calcA_tau(tau_sum) - self.spectra
return difference
def findTau_fit(self, preparam, opt_method):
"""
The function takes the variable tau_guess and optimizes their values,
so that ChiSquare takes a minimal value. It outputs a list of the
optimized tau values and the non-varied ones, if GLA was used.
Parameters
----------
tau_fix : list, np.array
A list of the variables tau_fix for the DAS. Empty for SAS.
tau_guess : list, np.array
A list of the variables tau_guess for the DAS or all tau values for
the SAS.
opt_method: string
The algorithm used by the optimization function.
Returns
-------
tau_sum : list
The fitted parameters tau_fit and the fixed values tau_fix combined.
"""
params = Parameters()
self.tau_fit = []
bounds = self.getTauBounds(preparam)
for i in range(len(preparam)):
params.add('tau' + str(i), preparam[i][0],
min=bounds[i][0], max=bounds[i][1], vary=preparam[i][1])
res_fit = minimize(self.getDifference, params, method=opt_method)
fit_rep = fit_report(res_fit)
if hasattr(res_fit, "success"):
if res_fit.success is False:
print("Fitting unsuccesful!")
for name, param in res_fit.params.items():
self.tau_fit.append(param.value)
if (self.model == "custom model" or self.model == "custom matrix"):
tau_sum = self.regenM(self.tau_fit)
else:
tau_sum = self.tau_fit
return tau_sum, fit_rep
def calcD_fit(self):
"""
Calculates D_fit from the previously calculated self.tau_fit and x_fix,
if DAS.
Returns
-------
D_fit : np.array
Matrix D with the fitted values for tau.
"""
self.M_fit = self.getM(self.tau_fit)
res1 = self.spectra @ self.M_fit.T
bra1 = np.linalg.inv(self.M_fit @ self.M_fit.T)
D_fit = res1 @ bra1
self.D_fit = D_fit
return D_fit
def calcA_fit(self):
"""
Generates the reconstructed spectra matrix with the matrices
self.D_fit and self.M_fit.
Returns
-------
A_fit : np.array
The reconstructed data matrix for the values of tau_fit and x_fix,
if DAS.
"""
A_fit = self.D_fit @ self.M_fit
self.spec = A_fit
return A_fit
def calcResiduals(self):
"""
Calculates the difference between the original spectra and the
calculated spectra to obtain residuals.
Returns
-------
residuals : np.array
Difference between spectra (original data) and spec (fitted data).
"""
mul1 = self.D_fit @ self.M_fit
self.residuals = mul1 - self.spectra
return self.residuals
# Plotting of the data
def setv_min(self, data, mul):
"""
For the given data and multiplicity, this function will determine the
minimal value for the colorbar.
Parameters
----------
data : np.array
An array containing data.
mul : float
The value by which data will be multiplied.
Returns
-------
v_min : float
The minimal value for the colorbar.
"""
flat_A = data.flatten()
v_min = min(flat_A) * mul
return v_min
def setv_max(self, data, mul):
"""
For the given data and multiplicity, this function will determine the
maximal value for the colorbar.
Parameters
----------
data : np.array
An array containing data.
mul : float
The value by which data will be multiplied.
Returns
-------
v_max : float
The maximal value for the colorbar.
"""
flat_A = data.flatten()
v_max = max(flat_A) * mul
return v_max
def findNearestIndex(self, x, data):
"""
Finds the nearest indices for the elements in x in the data.
Parameters
----------
x : list
A list of values which are within the borders of the data.
data : np.array
An array containing data.
Returns
-------
x : list
The nearest indices for the given values.
"""
x = list(x)
for i in range(len(x)):
mini = np.argmin(abs(data - x[i]))
x[i] = mini
return x
def log_tick_formatter(self, val, pos=None):
'''
A logarithmic tick formatter for the 3D contour plot.
Parameters
----------
val : float
The value to be put into log scaling.
Returns
-------
string
The formated axis tick.
'''
return r"$10^{{{:.0f}}}$".format(val)
def plot1(self, grid, wave, wave_index, spectra, mul, labels):
"""
Plots a subplot of delays against absorption change for chosen
wavelenghts.
Parameters
----------
grid : plt.GridSpec
The object of the grid for all subplots.
wave : list
Wavelenghts which should be plotted.
wave_index : list
Indexes for the wavelengths to be plotted .
spectra : np.array
Contains the values of the spectra.
Returns
-------
None.
"""
ltx = str(mul).count("0")
unit = ""
if "/" in labels[0]:
unit = labels[0].split("/")[1]
dot = ""
if mul != 1:
dot = f" $\cdot 10^{ltx}$"
ax1 = plt.subplot(grid[0, 0])
ax1.set_yscale("log")
ax1.set_xlabel(labels[2] + dot)
ax1.set_ylabel(labels[1])
for i, ind in enumerate(wave_index):
ax1.plot(
spectra[ind],
self.delays,
label=f"{wave[i]} {unit}"
)
ax1.axvline(0, color="black", lw=0.5, alpha=0.75)
temp = np.concatenate([spectra[i] for i in wave_index])
ax1.axis(
[
1.05 * min(np.array(temp)),
1.05 * max(np.array(temp)),
min(self.delays),
max(self.delays),
]
)
ax1.set_xticks(())
ax1.tick_params(bottom=False)
ax1.legend(loc="upper left", frameon=False, labelcolor="linecolor",
handlelength=0, fontsize=11)
def plot2(self, grid, wave, time, v_min, v_max, spectra, add, cont, mul, labels):
"""
Plots a subplot with a heatmap of the absorption change in delays
against lambdas.
Parameters
----------
grid : plt.GridSpec
The object of the grid for all subplots.
wave : list
Wavelenghts which should be plotted.
time : list
Delays which should be plotted.
v_min : float
Lower limit for the colorbar.
v_max : float
Lower limit for the colorbar.
spectra : np.array
Contains the values of the spectra.
add : string
Addition to the title of the subplot.
cont : float
Determines how much contour lines will be shown in the 2D plot.
High values will show more lines.
Returns
-------
ax2 : plt.subplot
The axis of this subplot.
cb : plt.colorbar
The object colorbar.
"""
ax2 = plt.subplot(grid[0, 1])
ax2.set_yscale("log")
ax2.set_xlabel(labels[0])
A_t = spectra.T
pcm = ax2.pcolormesh(
self.lambdas,
self.delays,
A_t,
cmap=plt.cm.seismic,
norm=col.TwoSlopeNorm(vcenter=0, vmin=v_min, vmax=v_max),
shading="auto",
)
if v_min is None:
v_min = self.setv_min(spectra, mul)
if v_max is None:
v_max = self.setv_max(spectra, mul)
cb = plt.colorbar(pcm)
cb.set_ticks([v_min, 0, v_max])
contours = ax2.contour(
self.lambdas,
self.delays,
A_t,
levels=np.arange(v_min, v_max, (1 / cont) * (v_max - v_min)),
colors="black",
linewidths=0.7,
linestyles="solid",
)
for i in wave:
ax2.axvline(i, color="black", linestyle="-.")
for i in time:
ax2.axhline(i, color="black", linestyle="dotted")
ax2.axis(
[
min(self.lambdas),
max(self.lambdas),
[min(self.delays) if min(self.delays) > 0 else 10 ** (-2)][0],
max(self.delays),
]
)
ax2.set_yticks(())
return ax2, cb
def plot3(self, grid, time, time_index, spectra, mul, labels):
"""
Plots a subplot of absorption change against wavelenghts for chosen
delays.
Parameters
----------
grid : plt.GridSpec
The object of the grid for all subplots.
time : list
Delays which should be plotted.
time_index : list
Indexes for the delays to be plotted.
spectra : np.array
Contains the values of the spectra.
Returns
-------
None.
"""
ltx = str(mul).count("0")
unit = ""
if "/" in labels[1]:
unit = labels[1].split("/")[1]
dot = ""
if mul != 1:
dot = f" $\cdot 10^{ltx}$"
ax3 = plt.subplot(grid[0, 2])
ax3.set_ylabel(labels[2] + dot)
ax3.set_xlabel(labels[0])
y = np.zeros(len(self.lambdas))
hoehe = 0
temp = np.zeros(len(self.lambdas))
for i, ind in enumerate(time_index):
for j in range(len(self.lambdas)):
temp[j] = spectra[j][ind]
y[j] = temp[j] + hoehe
if ind == time_index[0]:
mini = min(y)
ax3.plot(self.lambdas, y, color="black")
ax3.annotate(
f"{time[i]} {unit}", (0.5 * (min(self.lambdas) +
max(self.lambdas)), hoehe)
)
ax3.axhline(hoehe, color="black", lw=0.5, alpha=0.75)
hoehe += 1.1 * (abs(max(temp)) + abs(min(temp)))
ax3.axis([min(self.lambdas), max(self.lambdas), 1.1 * mini,
1.1 * max(y)])
ax3.set_yticks(())
def plot3D(self, spectra, v_min, v_max, mul, labels, add=""):
"""
Allows for the creation of a 3D contour plot.
Parameters
----------
spectra : np.array
Contains the values of the spectra.
v_min : float
Lower limit for the colorbar.
v_max : float
Upper limit for the colorbar.
cont : float
Determines how much contour lines will be shown in the 2D plot.
High values will show more lines.
add : string, optional
Addition to the title of the subplot. The default is "".
mul : float
The value by which the spectra will be multiplied.
The default is 1.
Returns
-------
None.
"""
fig, ax = plt.subplots(figsize=(11.2, 8), subplot_kw={"projection": "3d"})
log_delay = np.log10(abs(self.delays))
ltx = str(mul).count("0")
dot = ""
if mul != 1:
dot = f" $\cdot 10^{ltx}$"
if v_min is None:
v_min = self.setv_min(spectra, mul)
if v_max is None:
v_max = self.setv_max(spectra, mul)
X, Y = np.meshgrid(self.lambdas, log_delay)
Z = spectra.T * mul
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 80, cmap='seismic')
ax.set_xlabel(labels[0])
ax.set_ylabel(labels[1])
ax.set_zlabel(labels[0] + dot)
ax.yaxis.set_major_formatter(mticker.FuncFormatter(self.log_tick_formatter))
yticks = np.linspace(min(log_delay), max(log_delay), 4)
yticks[0] = -1
ax.set_yticks(yticks)
ax.view_init(20, 250)
plt.savefig(self.path + self.name + "3DContour" + ".png")
def plotCustom(self, spectra, wave, time, v_min, v_max, custom, cont, mul, labels,
add=""):
"""
Allows for the creation of 1-3 subplots in one plot.
Parameters
----------
spectra : np.array
Contains the values of the spectra.
wave : list
Wavelenghts which should be plotted.
time : list
Delays which should be plotted.
v_min : float
Lower limit for the colorbar.
v_max : float
Upper limit for the colorbar.
custom : string
Describes which subplots will be plotted.
cont : float
Determines how much contour lines will be shown in the 2D plot.
High values will show more lines.
mul : float
The value by which the spectra will be multiplied.
The default is 1.
add : string, optional
Addition to the title of the subplot. The default is "".
Returns
-------
None.
"""
ltx = str(mul).count("0")
dot = ""
if mul != 1:
dot = f" $\cdot 10^{ltx}$"
if v_min is None:
v_min = self.setv_min(spectra, mul)
if v_max is None:
v_max = self.setv_max(spectra, mul)
wave_index = self.findNearestIndex(wave, self.lambdas)
time_index = self.findNearestIndex(time, self.delays)
space = 0
if custom == "1":
width = 2.5
w1 = 1.0
w2 = 0
w3 = 0
elif custom == "2":
width = 5.2
w1 = 0
w2 = 4.7
w3 = 0
elif custom == "3":
width = 2
w1 = 0
w2 = 0
w3 = 1.5
elif custom == "1+2":
width = 7
w1 = 1.0
w2 = 3.7
w3 = 0
elif custom == "1+3":
width = 5
w1 = 1.0
w2 = 0
w3 = 1.5
space = 0.25
elif custom == "2+3":
width = 7
w1 = 0
w2 = 4.7
w3 = 1.5
elif custom == "1+2+3":
width = 9
w1 = 1.0
w2 = 3.7
w3 = 1.5
fig = plt.figure(
figsize=(width, 3), constrained_layout=False, frameon=True
)
grid = plt.GridSpec(1, 3, wspace=space, width_ratios=[w1, w2, w3])
if w1 != 0:
self.plot1(grid, wave, wave_index, spectra * mul, mul, labels)
if w2 != 0:
ax2, cb = self.plot2(grid, wave, time, v_min,