-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpectraPlot.py
More file actions
845 lines (793 loc) · 31.5 KB
/
Copy pathSpectraPlot.py
File metadata and controls
845 lines (793 loc) · 31.5 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
# coding: utf-8
# In[1]:
import matplotlib as mpl
# mpl.use("pgf")
import matplotlib.pyplot
import numpy as np
import scipy as sci
import scipy.interpolate as inter
from scipy.signal import savgol_filter
import copy
import sys
import os
import string
import warnings
import functools
from functools import wraps
import copy
import inspect
from matplotlib import rc
from Filereader import fileToNpArray
from Data import Data
from Fitter import Fitter
from Plot import Plot
import matplotlib.ticker as mtick
# In[2]:
class SpectraPlot(Plot):
# NaturKonst
e = 1.6 * 10 ** -19 # C
K_m = 683 # lm/W
c = 2.99 * 10 ** 17 # nm/s
h = 6.63 * 10 ** -34 # J*s
# ProgKonst
chars = list(string.ascii_uppercase) # alphabetUppercase
convFac = (h * c) / e # eV*nm
sigma_to_FWHM = 2 * np.sqrt(2 * np.log(2))
wavelength = 1
intensity_wavelength = 2
spectralRadiance_wavelength = 3
energy = 4
spectralRadiance_energy = 5
intensity_energype = 7
default_fstring="Emission at \n{:4.1f} nm / {:3.2f} eV"
default_fwhm_string="Peak: {:3.0f}\\,nm / {:3.2f}\\,eV\nFWHM: {:3.0f}\\,nm / {:3.0f}\\,"
spectral_data_format_default = {
"separator": "\t",
"skiplines": 40,
"fileEnding": ".txt",
"codec": "iso-8859-1",
}
@classmethod
def wavelengthToEV(cls, wavelength, spectralRadiance):
energy = wavelength ** -1 * cls.convFac # eV
corFac = wavelength ** 2 * cls.e / (cls.h * cls.c) # nm/eV
spectralRadianceEnergy = spectralRadiance * corFac # W/(sr*m^2*eV)
return (energy, spectralRadianceEnergy)
@classmethod
def noNegatives(cls, a):
return np.maximum(a, np.zeros(len(a), dtype=np.float64))
@classmethod
def lum_interpolator(cls, lumFunc, fill_value="extrapolate", kind="cubic"):
"""
Prepare an interpolator, that extrapolates or returns zero if the extrapolation is smaller than 0
"""
interpolator = sci.interpolate.interp1d(
*lumFunc, kind=kind, fill_value=fill_value, bounds_error=False
)
@wraps(interpolator)
def wrapper(*args, **kwargs):
return np.maximum(
abs(interpolator(*args, **kwargs) * 0), interpolator(*args, **kwargs)
)
return wrapper
@classmethod
def normalize(cls, a, value=None, col=None):
b = a - np.amin(a)
if value is None:
return b / np.amax(b, axis=0)
try:
temp_trial = value[0]
c = [value] * len(b)
values_array = np.vstack(c)
return b / (values_array[:, col - 1] - np.amin(a))
except:
return b / (value - np.amin(a))
@classmethod
def doubleGauss(cls, x, mu, amp, sigma, mu2, amp2, sigma2):
return amp / (np.sqrt(2 * np.pi * sigma ** 2)) * np.exp(
-((x - mu) ** 2 / (2 * sigma ** 2))
) + amp2 / (np.sqrt(2 * np.pi * sigma2 ** 2)) * np.exp(
-((x - mu2) ** 2 / (2 * sigma2 ** 2))
)
@classmethod
def tripleGauss(cls, x, mu, amp, sigma, mu2, amp2, sigma2, mu3, amp3, sigma3):
return (
amp
/ (np.sqrt(2 * np.pi * sigma ** 2))
* np.exp(-((x - mu) ** 2 / (2 * sigma ** 2)))
+ amp2
/ (np.sqrt(2 * np.pi * sigma2 ** 2))
* np.exp(-((x - mu2) ** 2 / (2 * sigma2 ** 2)))
+ amp3
/ (np.sqrt(2 * np.pi * sigma3 ** 2))
* np.exp(-((x - mu3) ** 2 / (2 * sigma3 ** 2)))
)
@classmethod
def twoGaussSplines(cls, x, mu, amp, sigma, sigma2):
return amp * np.exp(-((x - mu) ** 2 / (2 * sigma ** 2))) * np.heaviside(
x - mu, 0
) + amp * np.exp(-((x - mu) ** 2 / (2 * sigma2 ** 2))) * np.heaviside(mu - x, 0)
@classmethod
def createNGauss(cls, N, defaults=[1, 1, 1]):
gauss_inp = list(defaults) * N
def NGauss(x, *gauss_inp):
val = 0
for n in range(0, 3 * N, 3):
val += cls.gauss(x, *gauss_inp[n : n + 3])
return val
return NGauss
@classmethod
# see https://journals.aps.org/prapplied/supplemental/10.1103/PhysRevApplied.13.024061/SI-revised_final.pdf
def createFrankCondonGauss(cls, m, S=1, E_0=2, E_vib=0.2, amp=1, sigma=0.05):
def NFrankCGauss(E, S, E_0, E_vib, amp, sigma):
val = 0
for n in range(0, m):
val += (
(S ** n)
/ (np.math.factorial(n))
* np.exp(-S)
* cls.gauss(E, E_0 - n * E_vib, amp, sigma)
)
return val
return NFrankCGauss
@classmethod
def FWHMbySigma(cls, sigma):
return sigma * 2.3548
def __init__(
self,
name,
fileList=None,
fileFormat=spectral_data_format_default,
title=None,
validYCol=[2],
bgYCol=[None],
showColAxType=["lin", "lin", "lin", "lin", "lin", "lin", "lin"],
showColAxLim=[None, None, None, None, None, None, None],
showColLabel=[
"",
"Wavelength",
"Normalised Intensity",
"Spectral Radiance",
"Energy",
"Normalised Intensity",
"reduced Intensity",
],
showColLabel_filename=[
"",
"Wavelength",
"Normalised Intensity",
"Spectral Radiance",
"Energy",
"Normalised Intensity",
"reduced Intensity",
],
showColLabelUnit=[
"",
"Wavelength (nm)",
"Normalised Intensity",
"Spectral Radiance ($\\tfrac{\\mathrm{W}}{\\mathrm{sr}\\cdot \\mathrm{m}^2\\cdot \\mathrm{nm}}$)",
"Energy (eV)",
"Normalised Intensity", # energy scaled
"Reduced Intensity ($\\tfrac{1}{\\mathrm{eV}}$)",
],
averageMedian=False,
errors=False,
xParamPos=0,
FWHMParamPos=2,
rainbowMode=False,
fitColors=[
"#000000",
"#000000",
"#2ca02c",
"#9467bd",
"#8c564b",
"#e377c2",
"#7f7f7f",
"#ff7f0e",
(148 / 255, 103 / 255, 189 / 255, 0.7),
(214 / 255, 39 / 255, 40 / 255, 0.7),
(31 / 255, 119 / 255, 180 / 255, 0.7),
],
bgfile=None,
validYTable=None,
normalizeMode="single",
showFWHM=False,
ticklabelformat="sci",
rb_pos=-0.035,
rb_h=0.01,
**kwargs,
):
if rainbowMode:
kwargs.update({"legendBool": False})
Plot.__init__(
self,
name,
fileList,
averageMedian=averageMedian,
showColAxType=showColAxType,
showColAxLim=showColAxLim,
showColLabel=showColLabel,
showColLabel_filename=showColLabel_filename,
showColLabelUnit=showColLabelUnit,
fileFormat=fileFormat,
errors=errors,
fitColors=fitColors,
partialFitLabels=["Partial mono-Gaussian fit"],
**kwargs,
)
# dyn inits
if title is None:
self.title = name
else:
self.title = title
self.bgYCol = bgYCol
self.validYCol = validYCol
self.xParamPos = xParamPos
self.rainbowMode = rainbowMode
self.bgfile = bgfile
self.validYTable = validYTable
self.normalizeMode = normalizeMode
self.showFWHM = showFWHM
self.FWHMParamPos = FWHMParamPos
self.postprocess_normalization = False
self.ticklabelformat = ticklabelformat
self.rb_pos = rb_pos
self.rb_h = rb_h
# self.dataList=self.importData()
def processFileName(self, option=".pdf"):
if self.filename is None:
string = self.name.replace(" ", "") + self.fill + "spectra"
else:
string = self.filename
if self.xCol == SpectraPlot.wavelength:
string += self.fill + self.showColLabel_filename[self.showCol].replace(
" ", ""
)
else:
string += (
self.fill
+ self.showColLabel_filename[self.showCol].replace(" ", "")
+ "vs"
+ self.showColLabel_filename[self.xCol].replace(" ", "")
)
if not self.scaleX == 1:
string += self.fill + "scaledWith{:03.0f}Pct".format(self.scaleX * 100)
if self.filenamePrefix is not None:
self.processFileName_makedirs()
string = self.filenamePrefix + string
if self.normalizeMode is None:
string += self.fill + "not"
string += self.fill + "normalised"
if self.normalizeMode == "global":
string += self.fill + "globally"
string += self.fill + "normalised"
if self.rainbowMode:
string += self.fill + "rainbow"
return string + option
def process_normalization(self, data):
if self.normalizeMode == "single":
data.processData(self.normalize, yCol=2)
data.processData(self.normalize, yCol=5)
data.processData(self.normalize, yCol=6)
self.postprocess_normalization = False
elif self.normalizeMode == "global":
self.postprocess_normalization = True
else:
return
def filter_data(self, data):
try:
if self._filter["type"] == "savgol":
def this_savgol_filter(data):
return savgol_filter(data, self._filter["p1"], self._filter["p2"])
data.processData(this_savgol_filter, yCol=2)
data.processData(this_savgol_filter, yCol=5)
data.processData(this_savgol_filter, yCol=6)
except:
return
def __sub_processData(self, data, yCol, backg=None):
try:
if backg is None:
raise TypeError
energy, specRad = self.wavelengthToEV(
data.getSplitData2D(xCol=1, yCol=yCol)[0],
data.getSplitData2D(xCol=1, yCol=yCol)[1]
- data.getSplitData2D(xCol=1, yCol=backg)[1],
)
specRadpe = specRad / energy
data.setData(
Data.mergeData(
(
data.getSplitData2D(xCol=1, yCol=yCol)[0],
data.getSplitData2D(xCol=1, yCol=yCol)[1]
- data.getSplitData2D(xCol=1, yCol=backg)[1],
data.getSplitData2D(xCol=1, yCol=yCol)[1]
- data.getSplitData2D(xCol=1, yCol=backg)[1],
energy,
specRad,
specRadpe,
)
)
)
except (IndexError, TypeError):
energy, specRad = self.wavelengthToEV(
*data.getSplitData2D(xCol=1, yCol=yCol)
)
specRadpe = specRad / energy
data.setData(
Data.mergeData(
(
data.getSplitData2D(xCol=1, yCol=yCol)[0],
data.getSplitData2D(xCol=1, yCol=yCol)[1],
data.getSplitData2D(xCol=1, yCol=yCol)[1],
energy,
specRad,
specRadpe,
)
)
)
data.processData(self.noNegatives, yCol=2)
data.processData(self.noNegatives, yCol=3)
data.processData(self.noNegatives, yCol=5)
data.processData(self.noNegatives, yCol=6)
data.limitData(xLim=self.xLimOrig)
self.process_normalization(data)
if self._filter != None:
self.filter_data(data)
self.dataProcessed = True
return
def processData(self):
if not self.dataProcessed:
if self.validYTable is not None:
if self.bgfile is None:
for device, validYCol in zip(self.dataList, self.validYTable):
for data, yCol, bg in zip(device, validYCol, self.bgYCol):
self.__sub_processData(data, yCol, backg=bg)
else:
bg = fileToNpArray(self.bgfile, **self.fileFormat)[0][:, 1]
for device, validYCol in zip(self.dataList, self.validYTable):
for data, yCol in zip(device, validYCol):
self.__sub_processData(data, yCol, backg=bg)
else:
if self.bgfile is None:
for device in self.dataList:
while len(self.validYCol) > len(device):
device.append(copy.deepcopy(device[-1]))
while len(self.validYCol) > len(self.bgYCol):
self.bgYCol.append(self.bgYCol[-1])
for data, yCol, bg in zip(device, self.validYCol, self.bgYCol):
self.__sub_processData(data, yCol, backg=bg)
else:
bg = fileToNpArray(self.bgfile, **self.fileFormat)[0][:, 1]
for device in self.dataList:
while len(self.validYCol) > len(device):
device.append(copy.deepcopy(device[-1]))
for data, yCol in zip(device, self.validYCol):
self.__sub_processData(data, yCol, backg=bg)
if self.postprocess_normalization:
maximum_values = []
for device in self.dataList:
for data in device:
maximum_values.append(data.getExtremValues(typus="max"))
value = np.amax(np.asarray(maximum_values), axis=0)
for device in self.dataList:
for data in device:
data.processData(self.normalize, yCol=2, value=value, col=2)
data.processData(self.normalize, yCol=5, value=value, col=5)
data.processData(self.normalize, yCol=6, value=value, col=6)
return self.dataList
def handleDesc(
self,
fitter,
n=2,
param_pos=0,
xsy=None,
tp=None,
ax=None,
sze=None,
yoffset_fac=0.1,
fstring=default_fstring,
fwhm_string=default_fwhm_string,
FWHMParamPos=2,
showFWHM=False,
override_xpos=None,
override_curve_data=None,
):
if ax is None:
ax= self.ax
if override_xpos is not None:
peak = override_xpos
FWHMval = fitter.params[FWHMParamPos]
else:
peak = fitter.params[param_pos]
FWHMval = abs(fitter.params[FWHMParamPos + param_pos])
if override_curve_data is not None:
ann_y = override_curve_data
else:
ann_y = fitter.CurveData
if showFWHM:
FWHM = self.sigma_to_FWHM * FWHMval
if FWHM < 1:
fstring = fwhm_string + "meV"
ev_FWHM = np.round(FWHM * 1000, decimals=0)
else:
fstring = fwhm_string + "eV"
ev_FWHM = np.round(FWHM, decimals=2)
FWHM_nm = self.convFac * (1 / (peak - FWHM / 2) - 1 / (peak + FWHM / 2))
se = fstring.format(
np.round(self.convFac / peak, decimals=0),
np.round(peak, decimals=2),
np.round(FWHM_nm, decimals=0),
ev_FWHM,
)
else:
se = fstring.format(
np.round(self.convFac / peak, decimals=1), np.round(peak, decimals=2)
)
if xsy is None:
xsy = (
peak,
np.amax(ann_y.getSplitData2D()[1])
- yoffset_fac * np.amax(ann_y.getSplitData2D()[1]),
)
if sze is None:
sze = self.default_font_size[2]
if tp is None:
tp = fitter.textPos
return ax.annotate(
text=se,
size=sze,
xy=xsy,
xytext=tp,
arrowprops=dict(
arrowstyle="<-",
connectionstyle="arc3",
facecolor=fitter.fitColors[-n-1],
edgecolor=fitter.fitColors[-n-1],
linewidth=mpl.rcParams["lines.linewidth"],
),
)
def plot_gauss(self, fitter, n, ax=None):
if ax is None:
ax=self.ax
xdata = fitter.CurveData.getSplitData2D()[0]
ydata = self.gauss(xdata, *fitter.params[0:3])
textPos = fitter.textPos
amp = fitter.params[1] / (np.sqrt(2 * np.pi * fitter.params[2] ** 2))
self.handleDesc(fitter, n, tp=textPos, ax=ax)
return [ax.errorbar(
xdata,
ydata1,
c=fitter.fitColors[-n-1],
ls=fitter.fitLs,
label="Gaussian fit",
alpha=fitter.fitAlpha,
)]
def plot_doubleGauss(self, fitter, n, ax=None):
if ax is None:
ax=self.ax
xdata = fitter.CurveData.getSplitData2D()[0]
ydata1 = self.gauss(xdata, *fitter.params[0:3])
ydata2 = self.gauss(xdata, *fitter.params[3:6])
textPos = fitter.textPos
textPos2 = [fitter.textPos[0], fitter.textPos[1] + 0.1]
amp = fitter.params[1] / (np.sqrt(2 * np.pi * fitter.params[2] ** 2))
amp2 = fitter.params[1 + 3] / (np.sqrt(2 * np.pi * fitter.params[2 + 3] ** 2))
if amp > amp2:
tp1 = textPos2
tp2 = textPos
else:
tp1 = textPos
tp2 = textPos2
lines=[
ax.errorbar(
xdata,
ydata1,
c=fitter.fitColors[-n-1],
ls=fitter.fitLs,
label="Partial mono-Gaussian fit",
alpha=fitter.fitAlpha,
),
ax.errorbar(
xdata,
ydata2,
c=fitter.fitColors[-n-1],
ls=fitter.fitLs,
label="Partial mono-Gaussian fit",
alpha=fitter.fitAlpha,
)
]
self.handleDesc(fitter, n, tp=tp1, ax=ax)
self.handleDesc(fitter, n, param_pos=3, tp=tp2, ax=ax, override_curve_data=ydata2)
return lines
def plot_tripleGauss(self, fitter, n, ax=None):
if ax is None:
ax=self.ax
xdata = fitter.CurveData.getSplitData2D()[0]
ydata1 = self.gauss(xdata, *fitter.params[0:3])
ydata2 = self.gauss(xdata, *fitter.params[3:6])
ydata3 = self.gauss(xdata, *fitter.params[6:9])
textPos = fitter.textPos
textPos2 = [fitter.textPos[0], fitter.textPos[1] + 0.1]
textPos3 = [fitter.textPos[0], fitter.textPos[1] + 0.2]
amp = fitter.params[1] / (np.sqrt(2 * np.pi * fitter.params[2] ** 2))
amp2 = fitter.params[1 + 3] / (np.sqrt(2 * np.pi * fitter.params[2 + 3] ** 2))
amp3 = fitter.params[1 + 6] / (np.sqrt(2 * np.pi * fitter.params[2 + 6] ** 2))
if amp > amp2:
if amp > amp3:
tp1 = textPos3
if amp2 > amp3:
tp2 = textPos2
tp3 = textPos
else:
tp2 = textPos
tp3 = textPos2
else:
tp3 = textPos3
tp1 = textPos2
tp2 = textPos
else:
if amp2 > amp3:
tp2 = textPos3
if amp > amp3:
tp1 = textPos2
tp3 = textPos
else:
tp3 = textPos2
tp1 = textPos
else:
tp3 = textPos3
tp2 = textPos2
tp1 = textPos
# fit1
lines=[
self.ax.errorbar(
xdata,
ydata1,
c=fitter.fitColors[-n-1],
ls=fitter.fitLs,
label="Partial mono-Gaussian fit",
alpha=fitter.fitAlpha,
),
# fit2
self.ax.errorbar(
xdata,
ydata2,
c=fitter.fitColors[-n-1],
ls=fitter.fitLs,
label="Partial mono-Gaussian fit",
alpha=fitter.fitAlpha,
),
# fit3
self.ax.errorbar(
xdata,
ydata3,
c=fitter.fitColors[-n-1],
ls=fitter.fitLs,
label="Partial mono-Gaussian fit",
alpha=fitter.fitAlpha,
),
]
self.handleDesc(fitter, n, tp=tp1, ax=ax)
self.handleDesc(fitter, n, param_pos=3, tp=tp2, ax=ax, override_curve_data=ydata2)
self.handleDesc(fitter, n, param_pos=6, tp=tp3, ax=ax, override_curve_data=ydata3)
return lines
def plotNFrankCGauss(self, fitter, n, amp_thresh=0.1):
xdata = fitter.CurveData.getSplitData2D()[0]
ydataList = []
self.FWHMParamPos = 4
k = 0
actual_amp = 1
S, E_0, E_vib, amp, sigma = fitter.params
while actual_amp > amp_thresh:
pre_fac = (S ** k) / (np.math.factorial(k)) * np.exp(-S)
actual_amp = amp * pre_fac
ydataList.append(self.gauss(xdata, E_0 - k * E_vib, actual_amp, sigma))
k += 1
m = 1
for ydata in ydataList:
self.ax.errorbar(
xdata,
ydata,
c=self.fitColors[n + m],
ls=self.fitLs,
label=f"Order {m} transition gaussian fit",
alpha=self.fitAlpha,
)
self.process_annotation(
(m - 1) * 3,
[fitter.textPos[0], fitter.textPos[1] - (m - 1) * 0.15],
n,
ydata,
fitter,
override_xpos=E_0 - (m - 1) * E_vib,
)
m += 1
def rect(self, x, y, w, h, c):
polygon = matplotlib.pyplot.Rectangle((x, y), w, h, color=c)
self.ax.add_patch(polygon)
def rainbow_fill(
self, expectData, cmap=matplotlib.pyplot.get_cmap("nipy_spectral")
):
X, Y = expectData[0].getSplitData2D()
dx = X[1] - X[0]
S = 380
N = 670
if self.normalizeMode == "single" or self.normalizeMode == "global":
h = self.rb_h
p = self.rb_pos
else:
maxi = np.amax(
np.asarray(
[
np.amax(expect.getSplitData2D(yCol=self.showCol)[1])
for expect in expectData
]
)
)
h = self.rb_h * maxi
p = self.rb_pos * maxi
if not self.rainbowMode:
for n, (x, y) in enumerate(zip(X, Y)):
if x > N:
color = cmap(0.9999)
elif x < S:
color = cmap(0)
else:
color = cmap(min((x - S) / (N - S), 0.9999))
self.rect(x, p, dx, h, color)
else:
for n, (x, y) in enumerate(zip(X, Y)):
if x > N:
color = cmap(0.95)
elif x < S:
color = cmap(0)
else:
color = cmap(min((x - S) / (N - S), 0.95))
self.rect(x - dx / 2, 0, dx, y, color)
def xColTicksToXCol2Ticks(self, ticks):
if self.xCol == 1 and self.xCol2 == 4:
ticks = ticks ** -1 * self.convFac
ticks = np.around(ticks, decimals=2)
return ["{:3.2f}".format(tick) for tick in ticks]
elif self.xCol == 4 and self.xCol2 == 1:
ticks = ticks ** -1 * self.convFac
ticks = np.around(ticks, decimals=0)
return ["{:3.0f}".format(tick) for tick in ticks]
else:
return ticks
# def importData(self):
# self.dataList=[[Data(fileToNpArray(pixel, **self.fileFormat)[0], desc=fileToNpArray(pixel, **self.fileFormat)[1]) for pixel in device] for device in self.fileList]
# return self.dataList
def afterPlot(self):
ax = self.ax
form = mtick.ScalarFormatter(useMathText=True)
# form.set_scientific(True)
form.set_powerlimits((-1, 1))
ax.yaxis.set_major_formatter(form)
ax.yaxis.get_offset_text().set_visible(False)
if self.xCol == 1:
self.rainbow_fill(self.expectData)
if self.rainbowMode:
ax.get_lines()[0].set_alpha(0)
# ax.annotate(s="",xy=(503,0.5), xytext=(503-20,0.5), arrowprops=dict(arrowstyle="->", connectionstyle="arc3", shrinkA=0, shrinkB=0, linewidth=mpl.rcParams["lines.linewidth"]))
# ax.annotate(s="",xy=(520,0.5), xytext=(520+20,0.5), arrowprops=dict(arrowstyle="->", connectionstyle="arc3", shrinkA=0, shrinkB=0, linewidth=mpl.rcParams["lines.linewidth"]))
# bbox_props = dict(boxstyle="round,pad=0.3", fc="white", alpha=1, lw=0.5)
# ax.text(520+30,0.55,"FWHM: 85\,meV $\equiv$ 17\,nm", bbox=bbox_props, size=self.customFontsize[2])
# ax.annotate(s="CsPbBr\\textsubscript{3}- Emission at 511\,nm", size=self.customFontsize[2], xy=(511,0.9), xytext=(550,0.7), arrowprops=dict(arrowstyle="<-", connectionstyle="arc3", linewidth=mpl.rcParams["lines.linewidth"]))
# try:
for n in range(0, len(self.expectData)):
try:
if self.fitterList[n] is not None:
if type(self.fitterList[n]) is list:
for fitter in self.fitterList[n]:
if fitter.function == self.doubleGauss:
self.plotDoubleGauss(fitter, n)
if fitter.function == self.tripleGauss:
self.plotTripleGauss(fitter, n)
if fitter.function.__name__ == "NFrankCGauss":
print("inside")
self.plotNFrankCGauss(fitter, n)
# annotation
if fitter.desc != None:
if self.xCol != 4:
se = fitter.desc.format(
np.round(fitter.params[self.xParamPos])
)
else:
try:
se = fitter.desc.format(
np.round(
self.convFac
/ fitter.params[self.xParamPos],
decimals=0,
),
np.round(
fitter.params[self.xParamPos],
decimals=1,
),
)
except IndexError:
se = fitter.desc.format(
np.round(
self.convFac
/ fitter.params[self.xParamPos]
)
)
ax.annotate(
s=se,
size=self.customFontsize[2],
xy=(
fitter.params[self.xParamPos],
np.amax(fitter.CurveData.getSplitData2D()[1])
- 0.1
* np.amax(fitter.CurveData.getSplitData2D()[1]),
),
xytext=fitter.textPos,
arrowprops=dict(
arrowstyle="<-",
connectionstyle="arc3",
facecolor=self.fitColors[n],
edgecolor=self.fitColors[n],
linewidth=mpl.rcParams["lines.linewidth"],
),
)
else:
if self.fitterList[n].function == self.doubleGauss:
self.plotDoubleGauss(self.fitterList[n], n)
if self.fitterList[n].function == self.tripleGauss:
self.plotTripleGauss(self.fitterList[n], n)
if self.fitterList[n].function.__name__ == "NFrankCGauss":
self.plotNFrankCGauss(self.fitterList[n], n)
# annotation
if self.fitterList[n].desc != None:
fitter = self.fitterList[n]
if self.xCol != 4:
se = fitter.desc.format(
np.round(fitter.params[self.xParamPos])
)
else:
try:
se = fitter.desc.format(
np.round(
self.convFac
/ fitter.params[self.xParamPos],
decimals=0,
),
np.round(
fitter.params[self.xParamPos], decimals=1
),
)
except IndexError:
se = fitter.desc.format(
np.round(
self.convFac
/ fitter.params[self.xParamPos],
decimals=0,
)
)
sze = self.customFontsize[2]
xsy = (
fitter.params[self.xParamPos],
np.amax(fitter.CurveData.getSplitData2D()[1])
- 0.1 * np.amax(fitter.CurveData.getSplitData2D()[1]),
)
arprps = dict(
arrowstyle="<-",
connectionstyle="arc3",
facecolor=self.fitColors[n],
edgecolor=self.fitColors[n],
linewidth=mpl.rcParams["lines.linewidth"],
)
ax.annotate(
s=se,
size=sze,
xy=xsy,
xytext=fitter.textPos,
arrowprops=arprps,
)
except AttributeError as e:
pass
# print(e)
except Exception as e:
raise
print(e)