-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicfunc.py
More file actions
1362 lines (1154 loc) · 50.4 KB
/
basicfunc.py
File metadata and controls
1362 lines (1154 loc) · 50.4 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
#############################################################################################
## BASIC FUNCTIONS for PHYSICS ANALYSIS ##
## Developed during the attendance to the Master's Degree in Physics ##
## Curriculum Physics of the Fundamental Interactions ##
## at the University of Padua (Italy) ##
## Copyright (C) 2023 - 2024, All rights reserved. ##
## benedetta.rasera@studenti.unipd.it ##
#############################################################################################
##############################################################################################
# This library contains some simple fitting functions for various models #
# useful for laboratory courses in the Bachelor's degree in Physics #
# and for early lab works in the Master's degree in Physics (at least in Padua). #
# Many of these functions were implemented for data analysis in electronics #
# and gamma spectroscopy experiments, but they can also be used for similar purposes. #
# The functions included in this library are: #
# - Gaussian fit #
# - Compton edge fit (based on the error function) #
# - Background subtraction from a spectrum #
# - Linear fit #
# - Exponential fit (increasing and decreasing) #
# - Parabolic fit #
# - Lorentzian fit #
# - Breit-Wigner fit #
# - Log-normal fit #
# - Bode diagram fit (for low-pass, high-pass, and band-pass filters) #
##############################################################################################
import numpy as np
import matplotlib.pyplot as plt
import statistics as stat
import matplotlib.cm as cm
from scipy.optimize import curve_fit
from scipy.stats import norm
from scipy.special import erfc
import os
###############################################################################################
## FUNCTIONS TO FIT ##
###############################################################################################
# funzione gaussiana
def gaussian(x, amp, mu, sigma):
# return amp * np.exp(-0.5 * ((x - mu) / sigma)**2)
return amp * norm.pdf(x, loc=mu, scale=sigma)
# funzione per calcolare i bin nel fit con istogrammi
def calculate_bins(data):
bin_width = 3.49 * np.std(data) / len(data)**(1/3)
bins = int(np.ceil((max(data) - min(data)) / bin_width))
return max(bins, 1)
# funzione retta
def retta(x, m, q):
return m * x + q
# funzione parabola
def parabola(x, a, b, c):
return a * x**2 + b * x + c
# funzione esponenziale
def exp_pos(x, A, tau, f0): #esponenziale crescente
return A * np.exp(x / tau) + f0
def exp_neg(x, A, tau, f0): ##esponenziale decrescente
return A * np.exp(-x / tau) + f0
# funzione lorentziana
def lorentz(x, A, gamma, x0):
return A * (gamma / 2)**2 / ((x - x0)**2 + (gamma / 2)**2)
# curva di Wigner
def wigner(x, a, gamma, x0):
return a * gamma / ((x - x0)**2 + (gamma / 2)**2)
# funzione convoluzione gaussiana-esponenziale
def gauss_exp_conv(x, A, mu, sigma, tau):
arg = (sigma**2 - tau * (x - mu)) / (np.sqrt(2) * sigma * tau)
return (A / (2 * tau)) * np.exp((sigma**2 - 2 * tau * (x - mu)) / (2 * tau**2)) * erfc(arg)
# funzione log-normale
def l_norm(x, a, mu, sigma):
return (a / (x * sigma * np.sqrt(2 * np.pi))) * np.exp(-((np.log(x) - mu) ** 2) / (2 * sigma ** 2))
# funzioni di trasferimento per i vari tipi di filtro
def filtro_basso(omega, R, C):
return 1 / (1 + 1j * omega * R * C)
def filtro_alto(omega, R, C):
return (1j * omega * R * C) / (1 + 1j * omega * R * C)
def filtro_banda(omega, R, C, omega_0, Q):
return (1j * omega * R * C) / ((1j * omega) ** 2 + (omega_0 / Q) * (1j * omega) + omega_0**2)
# funzione per i residui di tutte le funzioni che fitta questa libreria
def res(data, fit):
return data - fit
# funzione per calcolare il chi-quadro
def chi2(model, params, x, y, sx=None, sy=None):
# Calcola il modello y in base ai parametri
y_model = model(x, *params)
# Calcola il chi-quadro, considerando gli errori sugli assi x e y
if sx is not None and sy is not None:
chi2_val = np.sum(((y - y_model) / np.sqrt(sy**2 + sx**2)) ** 2)
elif sx is not None:
chi2_val = np.sum(((y - y_model) / sx) ** 2)
elif sy is not None:
chi2_val = np.sum(((y - y_model) / sy) ** 2)
else:
chi2_val = np.sum((y - y_model) ** 2 / np.var(y))
return chi2_val
###############################################################################################
##### FITTING FUNCTIONS #####
###############################################################################################
# NORMAL FIT
def normal(data=None, bin_centers=None, counts=None, xlabel="X-axis", ylabel="Y-axis", titolo='title',
xmin=None, xmax=None, x1=None, x2=None, b=None, n=None, plot=False, save=False):
print("This fit returns a list which contains, in order:\n"
"- A numpy array with the parameters\n"
"- A numpy array with the uncertainties\n"
"- A numpy array with the residuals\n"
"- The chi squared\n"
"- The reduced chi squared \n"
"- The integral of the histogram in the range mu ± n*sigma\n"
"- The plot data (x_fit, y_fit, bin_centers, counts) if you need to plot other thing\n")
if data is not None:
if b is not None:
bins = b
else:
bins = calculate_bins(data)
counts, bin_edges = np.histogram(data, bins=bins, density=False)
bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
elif bin_centers is not None and counts is not None:
bin_edges = None
else:
raise ValueError("Devi fornire o `data`, o `bin_centers` e `counts`.")
sigma_counts = np.sqrt(counts)
if xmin is not None and xmax is not None:
fit_mask = (bin_centers >= xmin) & (bin_centers <= xmax)
bin_centers_fit = bin_centers[fit_mask]
counts_fit = counts[fit_mask]
sigma_counts_fit = sigma_counts[fit_mask]
else:
bin_centers_fit = bin_centers
counts_fit = counts
sigma_counts_fit = sigma_counts
initial_guess = [max(counts_fit), np.mean(bin_centers_fit), np.std(bin_centers_fit)]
params, cov_matrix = curve_fit(gaussian, bin_centers_fit, counts_fit, p0=initial_guess)
amp, mu, sigma = params
uncertainties = np.sqrt(np.diag(cov_matrix))
amp_unc, mu_unc, sigma_unc = uncertainties
fit_values = gaussian(bin_centers_fit, *params)
chi_quadro = np.sum(((counts_fit - fit_values) / sigma_counts_fit) ** 2)
degrees_of_freedom = len(counts_fit) - len(params)
reduced_chi_quadro = chi_quadro / degrees_of_freedom
residui = res(counts_fit, fit_values)
if n is not None:
lower_bound = mu - n * sigma
upper_bound = mu + n * sigma
bins_to_integrate = (bin_centers >= lower_bound) & (bin_centers <= upper_bound)
integral = int(np.sum(counts[bins_to_integrate]))
integral_unc = int(np.sqrt(np.sum(sigma_counts[bins_to_integrate]**2)))
print(f"Integrale dell'istogramma nel range [{lower_bound}, {upper_bound}] = {integral} ± {integral_unc}")
if xmin is not None and xmax is not None:
x_fit = np.linspace(xmin, xmax, 10000)
else:
x_fit = np.linspace(bin_centers[0], bin_centers[-1], 10000)
y_fit = gaussian(x_fit, *params)
if plot:
fig = plt.figure(figsize=(7, 8))
gs = fig.add_gridspec(5, 1, height_ratios=[1, 0.6, 5, 0.6, 1])
# --------------------- TABELLA ---------------------
ax_table = fig.add_subplot(gs[:2, 0])
ax_table.axis('tight')
ax_table.axis('off')
data = [
["Amplitude", f"{amp:.3f} ± {amp_unc:.3f}"],
["μ", f"{mu:.3f} ± {mu_unc:.3f}"],
["σ", f"{sigma:.3f} ± {sigma_unc:.3f}"],
["Chi²", f"{chi_quadro:.8f}"],
["Chi² rid.", f"{reduced_chi_quadro:.8f}"]
]
table = ax_table.table(
cellText=data,
colLabels=["Parameter", "Valuse"],
loc='center',
cellLoc='center',
colColours=["#4CAF50", "#4CAF50"],
bbox=[0, 0, 1, 1]
)
table.auto_set_font_size(False)
table.set_fontsize(10)
table.auto_set_column_width(col=list(range(len(data[0]))))
for (row, col), cell in table.get_celld().items():
cell.set_edgecolor("black")
cell.set_linewidth(1.5)
if row == 0:
cell.set_text_props(weight='bold', color='black')
cell.set_facecolor("lightblue")
# --------------------- FIT PRINCIPALE ---------------------
ax1 = fig.add_subplot(gs[2, 0])
ax1.bar(bin_centers, counts, width=(bin_centers[1] - bin_centers[0]), label='Data', alpha=0.6)
ax1.plot(x_fit, y_fit, color='red', label='Gaussian fit', lw=1.5)
ax1.set_xlabel(xlabel)
ax1.set_ylabel(ylabel)
ax1.set_title(titolo)
ax1.legend()
ax1.grid(alpha=0.5)
if x1 is not None and x2 is not None:
ax1.set_xlim(x1, x2)
else:
ax1.set_xlim(mu - 3 * sigma, mu + 3 * sigma)
ax1.set_ylim(0, np.max(counts) * 1.1)
# --------------------- RESIDUI ---------------------
ax2 = fig.add_subplot(gs[3:, 0], sharex=ax1)
ax2.errorbar(bin_centers_fit, residui, yerr=sigma_counts_fit, fmt='o', color='black', markersize=3, capsize=2, label='Residuals')
ax2.axhline(0, color='red', linestyle='--', lw=2)
ax2.set_xlabel(xlabel)
ax2.set_ylabel("(data - fit)")
ax2.grid(alpha=0.5)
ax2.legend()
plt.tight_layout()
if save:
os.makedirs("grafici", exist_ok=True)
plt.savefig("grafici/" + titolo + ".pdf", dpi=300, bbox_inches='tight')
plt.show()
plot = [x_fit, y_fit, bin_centers, counts]
parametri = np.array([amp, mu, sigma])
incertezze = np.array([amp_unc, mu_unc, sigma_unc])
return parametri, incertezze, residui, chi_quadro, reduced_chi_quadro, integral, plot
# COMPTON EDGE FIT via erfc
def compton(data=None, bin_centers=None, counts=None, xlabel="X-axis", ylabel="Y-axis", titolo='title',
xmin=None, xmax=None, x1=None, x2=None, b=None, n=None, plot=False, save=False):
print("This fit returns a list which contains, in order:\n"
"- A numpy array with the parameters\n"
"- A numpy array with the uncertainties\n"
"- A numpy array with the residuals\n"
"- The chi squared\n"
"- The reduced chi squared \n"
"- The integral of the histogram in the range mu ± n*sigma\n"
"- The plot data (x_fit, y_fit, bin_centers, counts) if you need to plot other thing\n")
if data is not None:
if b is not None:
bins = b
else:
bins = calculate_bins(data)
counts, bin_edges = np.histogram(data, bins=bins, density=False)
bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
elif bin_centers is not None and counts is not None:
bin_edges = None
else:
raise ValueError("Devi fornire o `data`, o `bin_centers` e `counts`.")
sigma_counts = np.sqrt(counts)
if xmin is not None and xmax is not None:
mask = (bin_centers >= xmin) & (bin_centers <= xmax)
bin_centers_fit = bin_centers[mask]
counts_fit = counts[mask]
sigma_counts_fit = sigma_counts[mask]
else:
bin_centers_fit = bin_centers
counts_fit = counts
sigma_counts_fit = sigma_counts
def fit_function(x, mu, sigma, rate, bkg):
return rate * erfc((x - mu) / sigma) + bkg
initial_guess = [np.median(bin_centers_fit), 5, np.max(counts_fit), np.min(counts_fit)]
params, cov_matrix = curve_fit(fit_function, bin_centers_fit, counts_fit, p0=initial_guess, sigma=sigma_counts_fit)
mu, sigma, rate, bkg = params
uncertainties = np.sqrt(np.diag(cov_matrix))
mu_unc, sigma_unc, rate_unc, bkg_unc = uncertainties
fit_values = fit_function(bin_centers_fit, *params)
chi_quadro = np.sum(((counts_fit - fit_values) / sigma_counts_fit) ** 2)
dof = len(counts_fit) - len(params)
reduced_chi = chi_quadro / dof
residui = counts_fit - fit_values
if n is not None:
lower_bound = mu - n * sigma
upper_bound = mu + n * sigma
integral_mask = (bin_centers >= lower_bound) & (bin_centers <= upper_bound)
integral = int(np.sum(counts[integral_mask]))
integral_unc = int(np.sqrt(np.sum(sigma_counts[integral_mask]**2)))
print(f"Integral within [{lower_bound}, {upper_bound}] = {integral} ± {integral_unc}")
else:
integral, integral_unc = 0, 0
x_fit = np.linspace(xmin if xmin is not None else bin_centers[0],
xmax if xmax is not None else bin_centers[-1], 1000)
y_fit = fit_function(x_fit, *params)
if plot:
fig = plt.figure(figsize=(7, 8))
gs = fig.add_gridspec(5, 1, height_ratios=[1, 0.6, 5, 0.6, 1])
# --------------------- TABELLA ---------------------
ax_table = fig.add_subplot(gs[:2, 0])
ax_table.axis('tight')
ax_table.axis('off')
data = [
["μ", f"{mu:.3f} ± {mu_unc:.3f}"],
["σ", f"{sigma:.3f} ± {sigma_unc:.3f}"],
["rate", f"{rate:.1f} ± {rate_unc:.1f}"],
["bkg", f"{bkg:.1f} ± {bkg_unc:.1f}"],
["Chi²", f"{chi_quadro:.8f}"],
["Chi² rid.", f"{reduced_chi:.8f}"]
]
table = ax_table.table(
cellText=data,
colLabels=["Parameter", "Value"],
loc='center',
cellLoc='center',
colColours=["#4CAF50", "#4CAF50"],
bbox=[0, 0, 1, 1]
)
table.auto_set_font_size(False)
table.set_fontsize(10)
table.auto_set_column_width(col=list(range(len(data[0]))))
for (row, col), cell in table.get_celld().items():
cell.set_edgecolor("black")
cell.set_linewidth(1.5)
if row == 0:
cell.set_text_props(weight='bold', color='black')
cell.set_facecolor("lightblue")
# --------------------- FIT PRINCIPALE ---------------------
ax1 = fig.add_subplot(gs[2, 0])
ax1.bar(bin_centers, counts, width=(bin_centers[1] - bin_centers[0]), alpha=0.6, label='Data')
ax1.plot(x_fit, y_fit, color='red', label='Fit via error function', lw=1.5)
ax1.set_xlabel(xlabel)
ax1.set_ylabel(ylabel)
ax1.set_title(titolo)
ax1.legend()
ax1.grid(alpha=0.5)
if x1 is not None and x2 is not None:
ax1.set_xlim(x1, x2)
else:
ax1.set_xlim(mu - 3*sigma, mu + 3*sigma)
ax1.set_ylim(0, np.max(counts) * 1.1)
# --------------------- RESIDUI ---------------------
ax2 = fig.add_subplot(gs[3:, 0], sharex=ax1)
ax2.errorbar(bin_centers_fit, residui, yerr=sigma_counts_fit, fmt='o', color='black', markersize=3, capsize=2, label='Residuals')
ax2.axhline(0, color='red', linestyle='--', lw=2)
ax2.set_xlabel(xlabel)
ax2.set_ylabel("(data - fit)")
ax2.grid(alpha=0.5)
ax2.legend()
plt.tight_layout()
if save:
os.makedirs("grafici", exist_ok=True)
plt.savefig("grafici/" + titolo + ".pdf", dpi=300, bbox_inches='tight')
plt.show()
parametri = np.array([mu, sigma, rate, bkg])
incertezze = np.array([mu_unc, sigma_unc, rate_unc, bkg_unc])
ints = np.array([integral, integral_unc])
plot_data = [x_fit, y_fit, bin_centers, counts]
return parametri, incertezze, residui, chi_quadro, reduced_chi, ints, plot_data
# BACKGROUND SUBTRACTION
def background(data, fondo, bins=None, xlabel="X-axis", ylabel="Counts", titolo='Title', plot=False, save=False):
# Calcola i bin
if bins is None:
bins = max(int(data.max()), int(fondo.max()))
# Creazione degli istogrammi
data_hist, bin_edges = np.histogram(data, bins=bins, range=(0, bins))
background_hist, _ = np.histogram(fondo, bins=bins, range=(0, bins))
# Normalizzazione del background
if background_hist.sum() > 0: # Per evitare divisione per zero
background_scaled = background_hist * (data_hist.sum() / background_hist.sum())
else:
background_scaled = background_hist
# Sottrazione del background
corrected_hist = data_hist - background_scaled
# Evitiamo valori negativi
corrected_hist[corrected_hist < 0] = 0
# Centri dei bin
bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
# Visualizzazione
if plot:
plt.figure(figsize=(7, 8))
plt.step(bin_centers, corrected_hist, label="Background subtracted", color='blue')
plt.legend()
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(titolo)
plt.grid(True)
if save:
os.makedirs("grafici", exist_ok=True)
plt.savefig("grafici/" + titolo + ".pdf", dpi=300, bbox_inches='tight')
plt.show()
return bin_centers, corrected_hist
# LINEAR FIT
def linear(x, y, sx=None, sy=None, xlabel="X-axis", ylabel="Y-axis", titolo='title', plot=False, save=False):
print("This fit returns a list which contains, in order:\n"
"- A numpy array with the parameters\n"
"- A numpy array with the uncertainties\n"
"- A numpy array with the residuals\n"
"- The chi squared\n"
"- The reduced chi squared \n")
if sx is None or np.all(sx == 0):
sx = np.zeros_like(x)
if sy is None or np.all(sy == 0):
sy = np.zeros_like(y)
if np.any(sx != 0) and np.any(sy != 0):
w = 1 / (sy**2 + sx**2)
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
elif np.any(sx != 0):
w = 1 / sx**2
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
elif np.any(sy != 0):
w = 1 / sy**2
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
else:
sigma_weights = None
fit_with_weights = False
m_guess = (y[-1] - y[0]) / (x[-1] - x[0])
q_guess = np.mean(y)
initial_guess = [m_guess, q_guess]
if fit_with_weights:
params, cov_matrix = curve_fit(retta, x, y, p0=initial_guess, sigma=sigma_weights, absolute_sigma=True)
else:
params, cov_matrix = curve_fit(retta, x, y, p0=initial_guess)
m, q = params
uncertainties = np.sqrt(np.diag(cov_matrix))
m_unc, q_unc = uncertainties
residui = np.array(y - retta(x, *params))
if fit_with_weights:
chi_squared = np.sum(((residui / sigma_weights) ** 2))
else:
chi_squared = np.sum((residui ** 2) / np.var(y))
dof = len(x) - len(params)
chi_squared_reduced = chi_squared / dof
print("Optimised parameters")
print("-----------------------------------------------")
print(f"m = {m} ± {m_unc}")
print(f"q = {q} ± {q_unc}")
print(f'Chi-squared = {chi_squared}')
print(f'Reduced chi-squared = {chi_squared_reduced}')
x_fit = np.linspace(x.min(), x.max(), 1000)
if plot:
fig = plt.figure(figsize=(7, 8))
gs = fig.add_gridspec(5, 1, height_ratios=[1, 0.6, 5, 0.6, 1])
ax_table = fig.add_subplot(gs[:2, 0])
ax_table.axis('tight')
ax_table.axis('off')
data = [
["m", f"{m:.3f} ± {m_unc:.3f}"],
["q", f"{q:.3f} ± {q_unc:.3f}"],
["Chi²", f"{chi_squared:.8f}"],
["Chi² rid.", f"{chi_squared_reduced:.8f}"]
]
table = ax_table.table(
cellText=data,
colLabels=["Parameter", "Value"],
loc='center',
cellLoc='center',
colColours=["#4CAF50", "#4CAF50"],
bbox=[0, 0, 1, 1]
)
table.auto_set_font_size(False)
table.set_fontsize(10)
table.auto_set_column_width(col=list(range(len(data[0]))))
for (row, col), cell in table.get_celld().items():
cell.set_edgecolor("black")
cell.set_linewidth(1.5)
if row == 0:
cell.set_text_props(weight='bold', color='black')
cell.set_facecolor("lightblue")
ax1 = fig.add_subplot(gs[2, 0])
ax1.errorbar(x, y, xerr=sx if np.any(sx != 0) else None,
yerr=sy if np.any(sy != 0) else None,
fmt='o', color='black', label='Data', markersize=3, capsize=2)
ax1.plot(x_fit, retta(x_fit, *params), color='red', label='Linear fit', lw=1.2)
ax1.set_xlabel(xlabel)
ax1.set_ylabel(ylabel)
ax1.set_title(titolo)
ax1.legend()
ax1.grid(alpha=0.5)
ax2 = fig.add_subplot(gs[3:, 0], sharex=ax1)
ax2.errorbar(x, residui, color='black', label='Residuals', markersize=3, fmt='o')
ax2.axhline(0, color='red', linestyle='--', lw=2)
ax2.set_xlabel(xlabel)
ax2.set_ylabel("(data - fit)")
ax2.grid(alpha=0.5)
ax2.legend()
plt.tight_layout()
if save:
os.makedirs("grafici", exist_ok=True)
plt.savefig("grafici/" + titolo + ".pdf", dpi=300, bbox_inches='tight')
plt.show()
parametri = np.array([m, q])
incertezze = np.array([m_unc, q_unc])
return parametri, incertezze, residui, chi_squared, chi_squared_reduced
# EXPONENTIAL FIT
def exponential(x, y, sx=None, sy=None, tipo="falling", xlabel="X-axis", ylabel="Y-axis", titolo='title', plot=False, save=False):
print("This fit returns a list which contains, in order:\n"
"- A numpy array with the parameters\n"
"- A numpy array with the uncertainties\n"
"- A numpy array with the residuals\n"
"- The chi squared\n"
"- The reduced chi squared \n")
if tipo == "rising":
fit_func = exp_pos
elif tipo == "falling":
fit_func = exp_neg
else:
raise ValueError("Tipo must be either 'rising' or 'falling'.")
if sx is None:
sx = np.zeros_like(x)
if sy is None:
sy = np.zeros_like(y)
# Pesi
if np.any(sy != 0):
sigma = sy
else:
sigma = None
# Fit con curve_fit
p0 = [np.max(y)-np.min(y), (np.max(x)-np.min(x))/2, np.min(y)]
params, cov = curve_fit(fit_func, x, y, sigma=sigma, absolute_sigma=True, p0=p0)
A, tau, f0 = params
perr = np.sqrt(np.diag(cov))
A_unc, tau_unc, f0_unc = perr
x_fit = np.linspace(x.min(), x.max(), 1000)
y_fit = fit_func(x, *params)
residui = res(y, y_fit)
# Chi quadro
if sigma is not None:
chi_squared = np.sum(((y - y_fit) / sigma) ** 2)
else:
chi_squared = np.sum((y - y_fit) ** 2)
dof = len(x) - 3
chi_squared_reduced = chi_squared / dof if dof > 0 else 0
print("Optimised parameters")
print("-----------------------------------------------")
print(f"A = {A} ± {A_unc}")
print(f"tau = {tau} ± {tau_unc}")
print(f"f0 = {f0} ± {f0_unc}")
print(f"Chi-squared = {chi_squared}")
print(f"Reduced Chi-squared = {chi_squared_reduced}")
if plot:
fig = plt.figure(figsize=(7, 8))
gs = fig.add_gridspec(5, 1, height_ratios=[1, 0.6, 5, 0.6, 1])
# Tabella dei parametri
ax_table = fig.add_subplot(gs[:2, 0])
ax_table.axis('tight')
ax_table.axis('off')
data_tabella = [
["A", f"{A:.3f} ± {A_unc:.3f}"],
["τ", f"{tau:.3f} ± {tau_unc:.3f}"],
["f₀", f"{f0:.3f} ± {f0_unc:.3f}"],
["Chi²", f"{chi_squared:.8f}"],
["Chi² rid.", f"{chi_squared_reduced:.8f}"]
]
table = ax_table.table(
cellText=data_tabella,
colLabels=["Parameter", "Value"],
loc='center',
cellLoc='center',
colColours=["#4CAF50", "#4CAF50"],
bbox=[0, 0, 1, 1]
)
table.auto_set_font_size(False)
table.set_fontsize(10)
table.auto_set_column_width(col=list(range(len(data_tabella[0]))))
for (row, col), cell in table.get_celld().items():
cell.set_edgecolor("black")
cell.set_linewidth(1.5)
if row == 0:
cell.set_text_props(weight='bold', color='black')
cell.set_facecolor("lightblue")
# Plot fit
ax1 = fig.add_subplot(gs[2, 0])
ax1.errorbar(x, y, xerr=sx if np.any(sx != 0) else None,
yerr=sy if np.any(sy != 0) else None,
fmt='o', color='black', label='Dati', markersize=3, capsize=2)
ax1.plot(x_fit, fit_func(x_fit, *params), color='red', label='Exponential fit', lw=1.2)
ax1.set_xlabel(xlabel)
ax1.set_ylabel(ylabel)
ax1.set_title(titolo)
ax1.legend()
ax1.grid(alpha=0.5)
# Plot residui
ax2 = fig.add_subplot(gs[3:, 0], sharex=ax1)
ax2.errorbar(x, residui, color='black', label='Residui', markersize=3, fmt='o')
ax2.axhline(0, color='red', linestyle='--', lw=2)
ax2.set_xlabel(xlabel)
ax2.set_ylabel("Residui")
ax2.grid(alpha=0.5)
ax2.legend()
plt.tight_layout()
if save:
os.makedirs("grafici", exist_ok=True)
plt.savefig("grafici/" + titolo + ".pdf", dpi=300, bbox_inches='tight')
plt.show()
parametri = np.array([A, tau, f0])
incertezze = np.array([A_unc, tau_unc, f0_unc])
return parametri, incertezze, residui, chi_squared, chi_squared_reduced
# PARABOLIC FIT
def parabolic(x, y, sx=None, sy=None, xlabel="X-axis", ylabel="Y-axis", titolo='title', plot=False, save=False):
print("This fit returns a list which contains, in order:\n"
"- A numpy array with the parameters\n"
"- A numpy array with the uncertainties\n"
"- A numpy array with the residuals\n"
"- The chi squared\n"
"- The reduced chi squared \n")
if sx is None or np.all(sx == 0):
sx = np.zeros_like(x)
if sy is None or np.all(sy == 0):
sy = np.zeros_like(y)
if np.any(sx != 0) and np.any(sy != 0):
w = 1 / (sy**2 + sx**2)
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
elif np.any(sx != 0):
w = 1 / sx**2
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
elif np.any(sy != 0):
w = 1 / sy**2
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
else:
sigma_weights = None
fit_with_weights = False
# Guess initial parameters for a, b, and c
a_guess = (y[-1] - 2 * y[-2] + y[-3]) / ((x[-1] - x[-2]) * (x[-2] - x[-3])) # Second derivative estimate
b_guess = (y[-1] - y[-2]) / (x[-1] - x[-2]) - a_guess * (x[-1] + x[-2]) # First derivative estimate
c_guess = y[0] # Estimate the intercept
initial_guess = [a_guess, b_guess, c_guess]
if fit_with_weights:
params, cov_matrix = curve_fit(parabola, x, y, p0=initial_guess, sigma=sigma_weights, absolute_sigma=True)
else:
params, cov_matrix = curve_fit(parabola, x, y, p0=initial_guess)
a, b, c = params
uncertainties = np.sqrt(np.diag(cov_matrix))
a_unc, b_unc, c_unc = uncertainties
residui = y - parabola(x, *params)
if fit_with_weights:
chi_squared = np.sum(((residui / sigma_weights) ** 2))
else:
chi_squared = np.sum((residui ** 2) / np.var(y))
dof = len(x) - len(params)
chi_squared_reduced = chi_squared / dof
print("Optimised parameters")
print("-----------------------------------------------")
print(f"a = {a} ± {a_unc}")
print(f"b = {b} ± {b_unc}")
print(f"c = {c} ± {c_unc}")
print(f'Chi-squared = {chi_squared}')
print(f'Reduced chi-squared = {chi_squared_reduced}')
x_fit = np.linspace(x.min(), x.max(), 1000)
if plot:
fig = plt.figure(figsize=(7, 8))
gs = fig.add_gridspec(5, 1, height_ratios=[1, 0.6, 5, 0.6, 1])
ax_table = fig.add_subplot(gs[:2, 0])
ax_table.axis('tight')
ax_table.axis('off')
data = [
["a", f"{a:.3f} ± {a_unc:.3f}"],
["b", f"{b:.3f} ± {b_unc:.3f}"],
["c", f"{c:.3f} ± {c_unc:.3f}"],
["Chi²", f"{chi_squared:.8f}"],
["Chi² rid.", f"{chi_squared_reduced:.8f}"]
]
table = ax_table.table(
cellText=data,
colLabels=["Parameter", "Value"],
loc='center',
cellLoc='center',
colColours=["#4CAF50", "#4CAF50"],
bbox=[0, 0, 1, 1]
)
table.auto_set_font_size(False)
table.set_fontsize(10)
table.auto_set_column_width(col=list(range(len(data[0]))))
for (row, col), cell in table.get_celld().items():
cell.set_edgecolor("black")
cell.set_linewidth(1.5)
if row == 0:
cell.set_text_props(weight='bold', color='black')
cell.set_facecolor("lightblue")
ax1 = fig.add_subplot(gs[2, 0])
ax1.errorbar(x, y, xerr=sx if np.any(sx != 0) else None,
yerr=sy if np.any(sy != 0) else None,
fmt='o', color='black', label='Data', markersize=3, capsize=2)
ax1.plot(x_fit, parabola(x_fit, *params), color='red', label='Parabolic fit', lw=1.2)
ax1.set_xlabel(xlabel)
ax1.set_ylabel(ylabel)
ax1.set_title(titolo)
ax1.legend()
ax1.grid(alpha=0.5)
ax2 = fig.add_subplot(gs[3:, 0], sharex=ax1)
ax2.errorbar(x, residui, color='black', label='Residuals', fmt='o', markersize=3, capsize=2)
ax2.axhline(0, color='red', linestyle='--', lw=2)
ax2.set_xlabel(xlabel)
ax2.set_ylabel("(data - fit)")
ax2.grid(alpha=0.5)
ax2.legend()
plt.tight_layout()
if save:
os.makedirs("grafici", exist_ok=True)
plt.savefig("grafici/" + titolo + ".pdf", dpi=300, bbox_inches='tight')
plt.show()
parametri = np.array([a, b, c])
incertezze = np.array([a_unc, b_unc, c_unc])
return parametri, incertezze, residui, chi_squared, chi_squared_reduced
# LORENTZIAN FIT
def lorentzian(x, y, sx=None, sy=None, xlabel="X-axis", ylabel="Y-axis", titolo='title', plot=False, save=False):
print("This fit returns a list which contains, in order:\n"
"- A numpy array with the parameters\n"
"- A numpy array with the uncertainties\n"
"- A numpy array with the residuals\n"
"- The chi squared\n"
"- The reduced chi squared \n")
# Gestione degli errori
if sx is None or np.all(sx == 0):
sx = np.zeros_like(x)
if sy is None or np.all(sy == 0):
sy = np.zeros_like(y)
# Gestione dei pesi
if np.any(sx != 0) and np.any(sy != 0):
w = 1 / (sy**2 + sx**2)
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
elif np.any(sx != 0):
w = 1 / sx**2
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
elif np.any(sy != 0):
w = 1 / sy**2
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
else:
sigma_weights = None
fit_with_weights = False
# Fitting Lorentziano
initial_guess = [1, 1, np.mean(x)]
if fit_with_weights:
params, cov_matrix = curve_fit(lorentz, x, y, p0=initial_guess, sigma=sigma_weights, absolute_sigma=True)
else:
params, cov_matrix = curve_fit(lorentz, x, y, p0=initial_guess)
a, gamma, x0 = params
uncertainties = np.sqrt(np.diag(cov_matrix))
a_unc, gamma_unc, x0_unc = uncertainties
# Calcolo dei residui
residui = y - lorentz(x, *params)
# Calcolo del chi quadro
if fit_with_weights:
chi_squared = np.sum(((residui / sigma_weights) ** 2))
else:
chi_squared = np.sum((residui ** 2) / np.var(y))
dof = len(x) - len(params)
chi_squared_reduced = chi_squared / dof
# Stampa dei risultati
print(f"Optimised parameters")
print(f"-----------------------------------------------")
print(f"A = {a} ± {a_unc}")
print(f"gamma = {gamma} ± {gamma_unc}")
print(f"x0 = {x0} ± {x0_unc}")
print(f"Chi-squared = {chi_squared}")
print(f"Reduced Chi-squared = {chi_squared_reduced}")
if plot:
x_fit = np.linspace(np.min(x), np.max(x), 1000)
y_fit = lorentz(x_fit, *params)
fig = plt.figure(figsize=(7, 8))
gs = fig.add_gridspec(5, 1, height_ratios=[1, 0.6, 5, 0.6, 1])
# Tabella
ax_table = fig.add_subplot(gs[:2, 0])
ax_table.axis('tight')
ax_table.axis('off')
data = [
["A", f"{a:.3f} ± {a_unc:.3f}"],
["γ", f"{gamma:.3f} ± {gamma_unc:.3f}"],
["x₀", f"{x0:.3f} ± {x0_unc:.3f}"],
["Chi²", f"{chi_squared:.8f}"],
["Chi² rid.", f"{chi_squared_reduced:.8f}"]
]
table = ax_table.table(
cellText=data,
colLabels=["Parameter", "Value"],
loc='center',
cellLoc='center',
colColours=["#4CAF50", "#4CAF50"],
bbox=[0, 0, 1, 1]
)
table.auto_set_font_size(False)
table.set_fontsize(10)
table.auto_set_column_width(col=list(range(len(data[0]))))
for (row, col), cell in table.get_celld().items():
cell.set_edgecolor("black")
cell.set_linewidth(1.5)
if row == 0:
cell.set_text_props(weight='bold', color='black')
cell.set_facecolor("lightblue")
# Fit
ax1 = fig.add_subplot(gs[2, 0])
ax1.errorbar(x, y,
xerr=sx if np.any(sx != 0) else None,
yerr=sy if np.any(sy != 0) else None,
fmt='o', color='black', label='Data', markersize=3, capsize=2)
ax1.plot(x_fit, y_fit, color='red', label='Lorentzian fit', lw=1.5)
ax1.set_xlabel(xlabel)
ax1.set_ylabel(ylabel)
ax1.set_title(titolo)
ax1.legend()
ax1.grid(alpha=0.5)
# Residui
ax2 = fig.add_subplot(gs[3:, 0], sharex=ax1)
ax2.errorbar(x, residui,
xerr=sx if np.any(sx != 0) else None,
yerr=sy if np.any(sy != 0) else None,
fmt='o', color='black', markersize=3, capsize=2, label='Residuals')
ax2.axhline(0, color='red', linestyle='--', lw=2)
ax2.set_xlabel(xlabel)
ax2.set_ylabel("(data - fit)")
ax2.legend()
ax2.grid(alpha=0.5)
plt.tight_layout()
if save:
os.makedirs("grafici", exist_ok=True)
plt.savefig("grafici/" + titolo + ".pdf", dpi=300, bbox_inches='tight')
plt.show()
parametri = np.array([a, gamma, x0])
incertezze = np.array([a_unc, gamma_unc, x0_unc])
return parametri, incertezze, residui, chi_squared, chi_squared_reduced
# BREIT-WIGNER FIT
def breitwigner(x, y, sx=None, sy=None, xlabel="X-axis", ylabel="Y-axis", titolo='title', plot=False, save=False):
print("This fit returns a list which contains, in order:\n"
"- A numpy array with the parameters\n"
"- A numpy array with the uncertainties\n"
"- A numpy array with the residuals\n"
"- The chi squared\n"
"- The reduced chi squared \n")
if sx is None or np.all(sx == 0):
sx = np.zeros_like(x)
if sy is None or np.all(sy == 0):
sy = np.zeros_like(y)
if np.any(sx != 0) and np.any(sy != 0):
w = 1 / (sy**2 + sx**2)
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
elif np.any(sx != 0):
w = 1 / sx**2
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
elif np.any(sy != 0):
w = 1 / sy**2
sigma_weights = np.sqrt(1 / w)
fit_with_weights = True
else:
sigma_weights = None
fit_with_weights = False
initial_guess = [1, 1, np.mean(x)]
if fit_with_weights:
params, cov_matrix = curve_fit(wigner, x, y, p0=initial_guess, sigma=sigma_weights, absolute_sigma=True)
else:
params, cov_matrix = curve_fit(wigner, x, y, p0=initial_guess)
a, gamma, x0 = params
uncertainties = np.sqrt(np.diag(cov_matrix))
a_unc, gamma_unc, x0_unc = uncertainties
residui = y - wigner(x, *params)
if fit_with_weights:
chi_squared = np.sum(((residui / sigma_weights) ** 2))
else:
chi_squared = np.sum((residui ** 2) / np.var(y))
dof = len(x) - len(params)
chi_squared_reduced = chi_squared / dof