-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspectral_analysis.py
1891 lines (1405 loc) · 63.5 KB
/
spectral_analysis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from math import floor, log10
from scipy.fft import fft, fftfreq, fftshift, ifft, ifftshift
from scipy.interpolate import CubicSpline
from scipy.special import hermite as hermite_gen
import pyvisa
import pylab as plt
from pyvisa.constants import VI_FALSE, VI_ATTR_SUPPRESS_END_EN, VI_ATTR_SEND_END_EN
from IPython.display import display, clear_output
import time
# --------------
# SPECTRUM CLASS
# --------------
class spectrum:
'''
Class of an optical spectrum. It stores values of the \"X\" axis (wavelength, frequency or time) and the \"Y\" axis
(intensity or phase) as 1D numpy arrays. Several standard transforms and basic statistics are implemented as class methods.
'''
def __init__(self, X, Y, x_type, y_type):
if x_type not in ["time", "THz", "wl"]:
raise Exception("x_type must be either \"time\" or \"freq\" or \"wl\".")
if y_type not in ["phase", "intensity"]:
raise Exception("y_type must be either \"phase\" or \"intensity\".")
if len(X) != len(Y):
raise Exception("X and Y axis must be of the same size.")
self.X = X
self.Y = Y
self.x_type = x_type
self.y_type = y_type
self.spacing = self.calc_spacing()
def __len__(self):
return len(self.X)
def calc_spacing(self):
return np.mean(np.diff(np.real(self.X)))
def copy(self):
X_copied = self.X.copy()
Y_copied = self.Y.copy()
return (spectrum(X_copied, Y_copied, self.x_type, self.y_type))
def save(self, title):
data = pd.DataFrame(np.transpose(np.vstack([self.X, self.Y])))
data.to_csv(title, index = False)
def wl_to_freq(self, inplace = True):
'''
Transformation from wavelength domain [nm] to frequency domain [THz].
'''
c = 299792458 # light speed
freq = np.flip(c / self.X / 1e3) # output in THz
intensity = np.flip(self.Y)
if inplace == True:
self.X = freq
self.Y = intensity
self.x_type = "THz"
self.spacing = self.calc_spacing()
else:
return spectrum(freq, intensity, "THz", self.y_type)
def constant_spacing(self, inplace = True):
'''
Transformation of a spectrum to have constant spacing on X-axis by linearly interpolating two nearest values on
Y-axis.
'''
def linear_inter(a, b, c, f_a, f_b):
if a == b:
return (f_a + f_b)/2
else:
f_c = f_a * np.abs(b-c) / np.abs(b-a) + f_b * np.abs(a-c) / np.abs(b-a)
return f_c
length = self.__len__()
freq = self.X.copy()
intens = self.Y.copy()
new_freq = np.linspace(start = freq[0], stop = freq[-1], num = length, endpoint = True)
new_intens = []
j = 1
for f in range(length): # each new interpolated intensity
interpolated_int = 0
if f == 0:
new_intens.append(intens[0])
continue
if f == length - 1:
new_intens.append(intens[length - 1])
continue
for i in range(j, length): # we compare with "each" measured intensity
if new_freq[f] <= freq[i]: # so for small i that's false. That's true for the first freq[i] greater than new_freq[f]
interpolated_int = linear_inter(freq[i - 1], freq[i], new_freq[f], intens[i-1], intens[i])
break
else:
j += 1 # j is chosen in such a way, because for every new "THz" it will be greater than previous
new_intens.append(interpolated_int)
if inplace == True:
self.X = new_freq
self.Y = new_intens
self.spacing = self.calc_spacing()
else:
return spectrum(new_freq, new_intens, self.x_type, self.y_type)
def cut(self, start = None, end = None, how = "units", inplace = True):
'''
Limit spectrum to a segment [\"start\", \"end\"].
ARGUMENTS:
start - start of the segment, to which the spectrum is limited.
end - end of the segment, to which the spectrum is limited.
how - defines meaning of \"start\" and \"end\". If \"units\", then those are values on X-axis.
If \"fraction\", then the fraction of length of X-axis. If \"index\", then corresponding indices of border observations.
'''
if start != None:
if how == "units":
s = np.searchsorted(self.X, start)
elif how == "fraction":
s = floor(start*self.__len__())
elif how == "index":
s = start
else:
raise Exception("\"how\" must be either \"units\", \"fraction\" or \"index\".")
if end != None:
if how == "units":
e = np.searchsorted(self.X, end)
elif how == "fraction":
e = floor(end*self.__len__())
elif how == "index":
e = end
else:
raise Exception("\"how\" must be either \"units\", \"fraction\" or \"index\".")
new_X = self.X.copy()
new_Y = self.Y.copy()
if start != None and end != None:
new_X = new_X[s:e]
new_Y = new_Y[s:e]
elif start == None and end != None:
new_X = new_X[:e]
new_Y = new_Y[:e]
elif start != None and end == None:
new_X = new_X[s:]
new_Y = new_Y[s:]
else: pass
if inplace == True:
self.X = new_X
self.Y = new_Y
else:
return spectrum(new_X, new_Y, self.x_type, self.y_type)
def fourier(self, inplace = True):
'''
Performs Fourier Transform from \"frequency\" to \"time\" domain.
'''
# Exceptions
if self.x_type == "wl":
raise Exception("Before applying Fourier Transform, transform spectrum from wavelength to frequency domain.")
if self.x_type == "time":
raise Exception("Sticking to the convention: use Inverse Fourier Transform.")
# prepare input
intens = self.Y.copy()
intens = np.sqrt(np.abs(intens))*np.exp(1j*np.angle(intens)) # in order to have same powers in both domains
intens = fftshift(intens)
# Fourier Transform
FT_intens = fft(intens, norm = "ortho")
FT_intens = fftshift(FT_intens)
FT_intens = FT_intens*np.abs(FT_intens)
time = fftfreq(self.__len__(), self.spacing)
time = fftshift(time)
if inplace:
self.X = time
self.Y = FT_intens
self.x_type = "time"
self.spacing = self.calc_spacing()
else:
return spectrum(time, FT_intens, "time", self.y_type)
def inv_fourier(self, inplace = True):
'''
Performs Inverse Fourier Transform from \"time\" to \"frequency\" domain.
'''
if self.x_type != "time":
raise Exception("Sticking to the convention: use Fourier Transform (not Inverse).")
# prepare input
intens = self.Y.copy()
intens = np.sqrt(np.abs(intens))*np.exp(1j*np.angle(intens)) # in order to have same powers in both domains
intens = ifftshift(intens)
# Fourier Transform
FT_intens = ifft(intens, norm = "ortho")
FT_intens = ifftshift(FT_intens)
FT_intens = FT_intens*np.abs(FT_intens)
freq = fftfreq(self.__len__(), self.spacing)
freq = ifftshift(freq)
if inplace == True:
self.X = freq
self.Y = FT_intens
self.x_type = "THz"
self.spacing = self.calc_spacing()
else:
return spectrum(freq, FT_intens, "THz", self.y_type)
def find_period(self, height = 0.5, hist = False):
'''
Function finds period in interference fringes by looking for wavelengths, where intensity is around given height and is decreasing.
ARGUMENTS:
height - height, at which we to look for negative slope. Height is the fraction of maximum intensity.
hist - if to plot the histogram of all found periods.
RETURNS:
(mean, std) - mean and standard deviation of all found periods.
'''
wl = self.X
intens = self.Y
h = height * np.max(intens)
nodes = []
for i in range(2, len(intens) - 2):
# decreasing
if intens[i-2] > intens[i-1] > h > intens[i] > intens[i+1] > intens[i+2]:
nodes.append(wl[i])
diff = np.diff(np.array(nodes))
if hist:
plt.hist(diff, color = "orange")
plt.xlabel("Period length [nm]")
plt.ylabel("Counts")
plt.show()
mean = np.mean(diff)
std = np.std(diff)
if len(diff) > 4:
diff_cut = [d for d in diff if np.abs(d - mean) < std]
else:
diff_cut = diff
return np.mean(diff_cut), np.std(diff_cut)
def naive_visibility(self):
'''
Function returns float in range (0, 1) which is the fraction of maximum intensity,
at which the greatest number of fringes is observable.
'''
maximum = np.max(self.Y)
# Omg, this loop is so smart. Sometimes I impress myself.
heights = []
sample_levels = 1000
for height in np.linspace(0, maximum, sample_levels, endpoint = True):
if height == 0:
continue
safe_Y = self.Y.copy()
safe_Y[safe_Y < height] = 0
safe_Y[safe_Y > 0] = 1
safe_Y += np.roll(safe_Y, shift = 1)
safe_Y[safe_Y == 2] = 0
heights.append(np.sum(safe_Y))
heights = np.array(heights) # height is array of numbers of fringes on given level (times 2)
fring_num = np.max(heights)
indices = np.array([i for i in range(sample_levels-1) if heights[i] == fring_num])
the_index = indices[0] #[floor(len(indices)/2)]
level = the_index/sample_levels
print(1-level)
return 1-level
def visibility(self, to_plot = False):
'''
Find visibility of interference fringes. First maxima and minima of fringes are found, then they are interpolated
and corresponding sums of intensities are calculated. Visibility is then (max_int-min_int)/max_int
Optionally you can plot plot interpolated maxima and minima. It looks very nice.
'''
safe_X = self.X.copy()
minima = find_minima(self)
maxima = find_maxima(self)
inter_minima = interpolate(minima, safe_X)
inter_maxima = interpolate(maxima, safe_X)
max_sum = np.sum(inter_maxima.Y)
min_sum = np.sum(inter_minima.Y)
left = self.quantile(0.2)
right = self.quantile(0.8)
delta = right-left
if to_plot:
compare_plots([self, inter_maxima, inter_minima],
colors = ["deepskyblue", "green", "red"],
title = "Visibility of {}".format(round((max_sum-min_sum)/max_sum, 3)),
start = left-delta, end = right+delta)
return (max_sum-min_sum)/max_sum
def replace_with_zeros(self, start = None, end = None, inplace = True):
'''
Replace numbers on Y axis from "start" to "end" with zeroes. "start" and "end" are in X axis' units.
If \"start\" and \"end\" are \"None\", then beginning and ending of whole spectrum are used as the borders.
'''
if start == None:
s = 0
else:
s = np.searchsorted(self.X, start)
if end == None:
e = self.__len__() - 1
else:
e = np.searchsorted(self.X, end)
new_Y = self.Y.copy()
new_Y[s:e] = np.zeros(e-s)
if inplace == True:
self.Y = new_Y
if inplace == False:
return spectrum(self.X, new_Y, self.x_type, self.y_type)
def shift(self, shift, inplace = True):
'''
Shifts the spectrum by X axis. Warning: only values on X axis are modified.
'''
new_X = self.X.copy()
new_X = new_X + shift
if inplace == True:
self.X = new_X
if inplace == False:
return spectrum(new_X, self.Y, self.x_type, self.y_type)
def smart_shift(self, shift = None, inplace = True):
'''
Shift spectrum by rolling Y-axis. Value of shift is to be given in X axis units. If shift = \"None\",
the spectrum is shifted so, that 1/2-order quantile for Y axis is reached for x = 0.
'''
shift2 = shift
if shift == None:
shift2 = -self.quantile(1/2)
index_shift = floor(np.real(shift2)/np.real(self.spacing))
Y_new = self.Y.copy()
Y_new = np.roll(Y_new, index_shift)
if inplace == True:
self.Y = Y_new
if inplace == False:
return spectrum(self.X, Y_new, self.x_type, self.y_type)
def very_smart_shift(self, shift, inplace = True):
'''
Shift spectrum by applying FT, multiplying by linear temporal phase and applying IFT. Value of shift is to be given in X axis units.
'''
X2 = self.X.copy()
Y2 = self.Y.copy()
spectrum2 = spectrum(X2, Y2, self.x_type, self.y_type)
try:
spectrum2.fourier()
spectrum2.Y *= np.exp(2j*np.pi*shift*spectrum2.X)
spectrum2.inv_fourier()
spectrum2.Y = np.abs(spectrum2.Y)
except:
spectrum2.inv_fourier()
spectrum2.Y *= np.exp(2j*np.pi*shift*spectrum2.X)
spectrum2.fourier()
spectrum2.Y = np.abs(spectrum2.Y)
if inplace == True:
self.Y = spectrum2.Y
if inplace == False:
return spectrum2
def comp_center(self, norm):
'''
Return center of mass of the spectrum in X-axis units. \"norm\" is either \"L1\" or \"L2\".
'''
if norm == "L1":
return np.sum(self.X*np.abs(self.Y))/np.sum(np.abs(self.Y))
elif norm == "L2":
return np.sum(self.X*self.Y*np.conjugate(self.Y))/np.sum(self.Y*np.conjugate(self.Y))
else:
raise Exception("The \"norm\" must be either \"L1\" or \"L2\".")
def zero_padding(self, length, inplace = True):
'''
Add zeros on Y-axis to the left and right of data with constant (mean) spacing on X-axis.
\"length\" specifies number of added zeroes on the left and on the right side of spectrum.
'''
left_start = self.X[0] - self.spacing*length
left_X = np.linspace(left_start, self.X[0], endpoint = False, num = length)
left_Y = np.zeros(length)
right_end = self.X[-1] + self.spacing*length
right_X = np.linspace(self.X[-1] + self.spacing, right_end, endpoint = True, num = length)
right_Y = np.zeros(length)
new_X = np.concatenate([left_X, self.X.copy(), right_X])
new_Y = np.concatenate([left_Y, self.Y.copy(), right_Y])
if inplace == True:
self.X = new_X
self.Y = new_Y
if inplace == False:
return spectrum(new_X, new_Y, self.x_type, self.y_type)
def shorten(self, length, inplace = True):
'''
Delete \"length\" points on the left and on the right of the spectrum.
'''
left_start = self.X[0] - self.spacing*length
left_X = np.linspace(left_start, self.X[0], endpoint = False, num = length - 1)
left_Y = np.zeros(length - 1)
right_end = self.X[-1] + self.spacing*length
right_X = np.linspace(self.X[-1] + self.spacing, right_end, endpoint = True, num = length - 1)
right_Y = np.zeros(length-1)
new_X = np.concatenate([left_X, self.X.copy(), right_X])
new_Y = np.concatenate([left_Y, self.Y.copy(), right_Y])
if inplace == True:
self.X = new_X
self.Y = new_Y
if inplace == False:
return spectrum(new_X, new_Y, self.x_type, self.y_type)
def quantile(self, q, norm):
'''
Finds x in X axis such that integral of intensity to x is fraction of value \"q\" of whole intensity.
The\"norm\" is either \"L1\" or \"L2\".
'''
if norm not in ["L1", "L2"]:
raise Exception("The norm must be either \"L1\" or \"L2\".")
integral = 0
if norm == "L1":
integral_infinite = np.sum(np.abs(self.Y))
if norm == "L2":
integral_infinite = np.sum(self.Y*np.conjugate(self.Y))
for i in range(self.__len__()):
if norm == "L1": integral += np.abs(self.Y[i])
if norm == "L2": integral += self.Y[i]*np.conjugate(self.Y[i])
x = self.X[0]
if integral >= integral_infinite*q:
x = self.X[i]
break
return x
def normalize(self, norm = "highest", shift_to_zero = True, inplace = True):
'''
Normalize spectrum by linearly changing values of intensity and eventually shifting spectrum to zero.
ARGUMENTS:
by - way of normalizing the spectrum. If \"highest\", then the spectrum is scaled to 1, so that its greatest value is 1.
If \"intensity\", then spectrum is scaled, so that its integral is equal to 1.
shift_to_zero - if \"True\", then spectrum is shifted by X axis, by simply np.rolling it.
'''
if norm not in ["sup", "L1", "L2"]:
raise Exception("\"norm\" parameter must be either \"sup\", \"L1\" or \"L2\".")
X_safe = self.X.copy()
Y_safe = self.Y.copy()
safe_spectrum = spectrum(X_safe, Y_safe, self.x_type, self.y_type)
if norm == "sup":
max = np.max(np.abs(Y_safe))
max_idx = np.argmax(np.abs(Y_safe))
Y_safe /= max
if shift_to_zero:
zero_idx = np.searchsorted(X_safe, 0)
shift_idx = max_idx - zero_idx
X_safe = np.roll(X_safe, shift_idx)
if norm == "L1":
integral = np.sum(np.abs(Y_safe))/(X_safe[-1]-X_safe[0])
median = safe_spectrum.quantile(1/2)
max_idx = np.searchsorted(np.abs(Y_safe), median)
Y_safe /= integral
if shift_to_zero:
zero_idx = np.searchsorted(X_safe, 0)
shift_idx = max_idx - zero_idx
X_safe = np.roll(X_safe, shift_idx)
if norm == "L2":
integral = np.sum(Y_safe*np.conjugate(Y_safe))/(X_safe[-1]-X_safe[0])
median = safe_spectrum.quantile(1/2, norm = "L2")
max_idx = np.searchsorted(np.abs(Y_safe), median)
Y_safe /= np.sqrt(integral)
if shift_to_zero:
zero_idx = np.searchsorted(X_safe, 0)
shift_idx = max_idx - zero_idx
X_safe = np.roll(X_safe, shift_idx)
if inplace == True:
self.X = X_safe
self.Y = Y_safe
if inplace == False:
return spectrum(X_safe, Y_safe, self.x_type, self.y_type)
def power(self):
'''
Power of a spectrum. In other words - integral of absolute value of it.
'''
# simple function to round to significant digits
def round_to_dig(x, n):
return round(x, -int(floor(log10(abs(x)))) + n - 1)
return round_to_dig(np.sum(self.X*np.conjugate(self.X)), 3)
def FWHM(self):
'''
Calculate Full Width at Half Maximum. If multiple peaks are present in spectrum, the function might not work properly.
'''
left = None
right = None
peak = np.max(self.Y)
for idx, y in enumerate(self.Y):
if y >= peak/2:
left = idx
for idx, y in enumerate(np.flip(self.Y)):
if y >= peak/2:
right = self.__len__() - idx
if self.__len__() == 0:
raise Exception("Failed to calculate FWHM, because spectrum is empty.")
if self.__len__() < 5:
raise Exception("The spectrum consists of too little data points to calculate FWHM.")
if left == None or right == None:
raise Exception("Failed to calculate FWHM due to very strange error.")
width = right-left
width *= self.spacing
return np.abs(width)
def remove_offset(self, period, inplace = True):
'''
The function improves visibility of interference fringes by subtracting moving minimum i. e.
minimum of a segment of length \"period\", centered at given point.
'''
idx_period = floor(period/self.spacing)
new_Y = []
for i in range(self.__len__()):
left = np.max([i - floor(idx_period/2), 0])
right = np.min([i + floor(idx_period/2), self.__len__() - 1])
new_Y.append(self.Y - np.min(self.Y[left:right]))
new_Y = np.array(new_Y)
if inplace == True:
self.Y = new_Y
if inplace == False:
return spectrum(self.X, new_Y, self.x_type, self.y_type)
def moving_average(self, period, inplace = True):
'''
Smooth spectrum by taking moving average with \"period\" in X axis units.
On the beginning and ending of spectrum shorter segments are used.
'''
idx_period = floor(period/self.spacing)
new_Y = []
for i in range(self.__len__()):
left = np.max([i - floor(idx_period/2), 0])
right = np.min([i + floor(idx_period/2), self.__len__() - 1])
new_Y.append(np.mean(self.Y[left:right]))
new_Y = np.array(new_Y)
if inplace == True:
self.Y = new_Y
if inplace == False:
return spectrum(self.X, new_Y, self.x_type, self.y_type)
def moving_average_interior(self, period, inplace = True):
'''
Smooth the INTERIOR of the spectrum by taking moving average with \"period\" in X axis units.
On the beginning and ending of spectrum shorter segments are used.
'''
sup = np.max(self.Y)
support = self.X[self.Y >= sup/2]
left_border = support[0]
right_border = support[-1]
left_border_idx = np.searchsorted(self.X, left_border)
right_border_idx = np.searchsorted(self.X, right_border)
idx_period = floor(period/self.spacing)
new_Y = []
for i in range(self.__len__()):
if i < left_border_idx + 1 or i > right_border_idx - 1:
new_Y.append(self.Y[i])
continue
smooth_range = np.min([idx_period, 2*np.abs(left_border_idx - i), 2*np.abs(right_border_idx - i)])
left = np.max([i - floor(smooth_range/2), 0])
right = np.min([i + floor(smooth_range/2), self.__len__() - 1])
new_Y.append(np.mean(self.Y[left:right]))
new_Y = np.array(new_Y)
if inplace == True:
self.Y = new_Y
if inplace == False:
return spectrum(self.X, new_Y, self.x_type, self.y_type)
# ------------------------
# SPECTRUM CLASS FUNCTIONS
# ------------------------
def load_csv(filename, x_type = "wl", y_type = "intensity", rows_to_skip = 2):
'''
Load CSV file to a spectrum class. Spectrum has on default wavelengths on X axis and intensity on Y axis.
'''
spectr = pd.read_csv(filename, skiprows = rows_to_skip)
return spectrum(spectr.values[:, 0], spectr.values[:, 1], x_type = x_type, y_type = y_type)
def load_tsv(filename, x_type = "wl", y_type = "intensity"):
'''
Load TSV file to a spectrum class. Spectrum has on default wavelengths on X axis and intensity on Y axis.
'''
spectr = pd.read_table(filename, skiprows = 2)
return spectrum(spectr.values[:, 0], spectr.values[:, 1], x_type = x_type, y_type = y_type)
def interpolate(old_spectrum, new_X):
'''
Interpolate rarely sampled spectrum for values in new X-axis. Interpolation is performed with cubic functions.
If y-values to be interpolated are complex, they are casted to reals.
ARGUMENTS:
old_spectrum - spectrum that is the basis for interpolation.
new_X - new X axis (i. e. frequencies or wavelengths). Interpolated Y-values are calculated for values from new_X.
RETURNS:
Interpolated spectrum.
'''
X = np.real(old_spectrum.X.copy())
Y = np.real(old_spectrum.Y.copy())
model = CubicSpline(X, Y)
new_Y = model(np.real(new_X))
return spectrum(new_X, new_Y, old_spectrum.x_type, old_spectrum.y_type)
def div(x, by):
if x == 0 and by == 0:
return 0
elif by != 0:
return x/by
else:
raise Exception("You can not divide non-zero number by zero.")
divide = np.vectorize(div)
def fit_fiber_length(phase_spectrum):
'''
Fit parabolic spectral phase to the given spectrum and return the length of chirping fiber corresponding to that phase.
'''
def chirp_phase(frequency, centre, fiber_length):
c = 299792458
l_0 = c/(centre*1e3)
D_l = 20
omega = frequency*2*np.pi
omega_mean = centre*2*np.pi
return l_0**2*fiber_length*D_l/(4*np.pi*c)*(omega-omega_mean)**2
param, cov = curve_fit(chirp_phase, phase_spectrum.X, phase_spectrum.Y, [80, 192])
return np.abs(param[1])
def chirp_r2(phase_spectrum, fiber_length, plot = False):
'''
Given spectral phase spectrum and the length of fiber employed in experiment, fit corresponding spectral phase to
experimental data (only fitting center) and return the R^2 statistics judging quality of that fit.
Additionally you can plot both phases on a single plot.
'''
def R2(data_real, data_pred):
TSS = np.sum(np.power(data_real - np.mean(data_real), 2))
RSS = np.sum(np.power(data_real - data_pred, 2))
return (TSS - RSS)/TSS
if np.mean(phase_spectrum.Y) < 0:
sign = -1
else:
sign = 1
def chirp_phase(frequency, centre):
c = 299792458
l_0 = c/(centre*1e3)
D_l = 20
omega = frequency*2*np.pi
omega_mean = centre*2*np.pi
return sign*l_0**2*fiber_length*D_l/(4*np.pi*c)*(omega-omega_mean)**2
param, cov = curve_fit(chirp_phase, phase_spectrum.X, phase_spectrum.Y, p0 = 192)
centrum = param[0]
Y_real = phase_spectrum.Y.copy()
Y_pred = chirp_phase(phase_spectrum.X, centrum)
score = R2(Y_real, Y_pred)
if plot:
reality = spectrum(phase_spectrum.X.copy(), Y_real, x_type = "THz", y_type = "phase")
prediction = spectrum(phase_spectrum.X.copy(), Y_pred, x_type = "THz", y_type = "phase")
if np.mean(reality.Y) < 0:
reality.Y *= -1
prediction.Y *= -1
compare_plots([reality, prediction],
title = "Experimental and model chirp phase for fiber of {}m\nR-squared value equal to {}".format(fiber_length, round(score, 3)),
legend = ["Experiment", "Model"],
colors = ["darkorange", "darkgreen"])
return score
def find_minima(fringes_spectrum):
'''
Find minima of interference fringes by looking at nearest neighbors. Spectrum with minima is returned.
'''
X = []
Y = []
for i in range(len(fringes_spectrum)):
if i in [0, 1, len(fringes_spectrum) - 2, len(fringes_spectrum) - 1]:
continue
if fringes_spectrum.Y[i-2] >= fringes_spectrum.Y[i-1] >= fringes_spectrum.Y[i] <= fringes_spectrum.Y[i+1] <= fringes_spectrum.Y[i+2]:
X.append(fringes_spectrum.X[i])
Y.append(fringes_spectrum.Y[i])
return spectrum(np.array(X), np.array(Y), fringes_spectrum.x_type, fringes_spectrum.y_type)
def find_maxima(fringes_spectrum):
'''
Find maxima of interference fringes by looking at nearest neighbors. Spectrum with maxima is returned.
'''
X = []
Y = []
for i in range(len(fringes_spectrum)):
if i in [0, 1, len(fringes_spectrum) - 2, len(fringes_spectrum) - 1]:
continue
if fringes_spectrum.Y[i-2] <= fringes_spectrum.Y[i-1] <= fringes_spectrum.Y[i] >= fringes_spectrum.Y[i+1] >= fringes_spectrum.Y[i+2]:
X.append(fringes_spectrum.X[i])
Y.append(fringes_spectrum.Y[i])
return spectrum(np.array(X), np.array(Y), fringes_spectrum.x_type, fringes_spectrum.y_type)
def plot(spectrum,
title = "Spectrum",
what_to_plot = "trigonometric",
intensity_plot = "line",
start = None, end = None,
save = False,
show_grid = False):
'''
### Fast spectrum plotting using matplotlib.pyplot library.
ARGUMENTS:
spectrum - the spectrum object class to be plotted.
title - title of the plot.
what_to_plot - either \"abs\", \"imag\", \"real\", \"complex\" or \"trigonometric\". In the last two cases two curves are plotted.
start - starting point (in X-axis units) of a area to be shown on plot. If \"min\", then plot starts with lowest X-value in all spectra.
end - ending point (in X-axis units) of a area to be shown on plot. If \"max\", then plot ends with highest X-value in all spectra.
save - if to save the plot in the program's directory. The title of the plot will be by default used as the filename.
intensity_plot - how do you want to plot intensity spectrum (it might be either \"fill\" or \"line\").
'''
spectrum_safe = spectrum.copy()
# simple function to round to significant digits
def round_to_dig(x, n):
if x == 0:
return 0
return round(x, -int(floor(log10(abs(x)))) + n - 1)
# invalid arguments
if what_to_plot not in ("abs", "imag", "real", "complex", "trigonometric"):
raise Exception("Argument \"what_to_plot\" must be either \"abs\", \"imag\", \"real\", \"complex\" or \"trigonometric\".")
# if we dont want to plot whole spectrum
n_points = len(spectrum_safe)
to_cut = False
inf = round(np.real(spectrum_safe.X[0]))
sup = round(np.real(spectrum_safe.X[-1]))
s = 0
e = -1
if start != None:
s = np.searchsorted(spectrum_safe.X, start)
to_cut = True
if end != None:
e = np.searchsorted(spectrum_safe.X, end)
to_cut = True
spectrum_safe.cut(s, e, how = "index")
# what do we want to have on Y axis
if what_to_plot == "abs":
spectrum_safe.Y = np.abs(spectrum_safe.Y)
if what_to_plot == "real":
spectrum_safe.Y = np.real(spectrum_safe.Y)
if what_to_plot == "imag":
spectrum_safe.Y = np.imag(spectrum_safe.Y)
# a bit of aesthetics
if spectrum_safe.x_type == "THz":
main_color = "orange"
elif spectrum_safe.x_type == "time":
main_color = "limegreen"
elif spectrum_safe.x_type == "nm":
main_color = "aqua"
else:
main_color = "yellow"
# start to plot
fig, ax = plt.subplots()
if what_to_plot == "complex":
ax.plot(spectrum_safe.X, np.real(spectrum_safe.Y), color = "darkviolet")
ax.plot(spectrum_safe.X, np.imag(spectrum_safe.Y), color = "green")
ax.legend(["Real part", "Imaginary part"], bbox_to_anchor = [1, 0.17])
elif what_to_plot == "trigonometric":
phase = np.angle(spectrum_safe.Y)
intensity = np.abs(spectrum_safe.Y)
start_idx_phase = 0
end_idx_phase = len(phase) -1
for i in range(len(phase)): # we don't plot the phase in the area, where it is equal to zero
if np.abs(phase[i]) > 1e-5:
start_idx = i
break
for i in reversed(range(len(phase))):
if np.abs(phase[i]) > 1e-5:
end_idx = i
break
start_idx_intens = np.searchsorted(spectrum_safe.X, spectrum_safe.quantile(0.005, "L1"))
end_idx_intens = np.searchsorted(spectrum_safe.X, spectrum_safe.quantile(0.995, "L1"))
start_idx = np.max([start_idx_phase, start_idx_intens])
end_idx = np.min([end_idx_phase, end_idx_intens])
phase = np.unwrap(phase)
if intensity_plot == "fill":
ax.fill_between(spectrum_safe.X, intensity, color = main_color, alpha = 0.5, label = "Intensity")
phase_style = "solid"
elif intensity_plot == "line":
ax.plot(spectrum_safe.X, intensity, color = main_color, label = "Intensity")
phase_style = "dashed"
else:
raise Exception("\"intensity_plot\" must be either \"fill\" or \"line\"")
phase_ax = ax.twinx()
phase_ax.plot(spectrum_safe.X[start_idx: end_idx], phase[start_idx: end_idx], color = "darkviolet", label = "Phase", linestyle = phase_style)
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = phase_ax.get_legend_handles_labels()
phase_ax.legend(lines + lines2, labels + labels2, loc=0)
else:
ax.plot(spectrum_safe.X, spectrum_safe.Y, color = main_color)
if spectrum_safe.y_type == "intensity":
ax.set_ylim([min([0, np.min(spectrum_safe.Y)]), 1.1*np.max(spectrum_safe.Y)])
ax.grid()
if to_cut:
ax.set_title(title + " [only part shown]")
else:
ax.set_title(title)
if spectrum_safe.y_type == "phase":
ax.set_ylabel("Phase (rad)")
if spectrum_safe.y_type == "intensity":
ax.set_ylabel("Intensity (a.u.)")
if spectrum_safe.y_type == "e-field":
ax.set_ylabel("Electric Field")
if spectrum_safe.x_type == "nm":
ax.set_xlabel("Wavelength (nm)")
unit = "nm"