Assorbimento Pb

marco base "didattica" Imparare a leggere un file di testo, vedere la distribuzione di una certa variabile, customizzare la grafica, fare un fit, fare un fit su un sottorange e usare i risultati

File structure: epoch time, adc1, adc2, adc3, i5

...
001524235805 1778 80 64 112 
001524235805 2236 81 66 112 
001524235805 1651 81 65 112 
001524235805 1688 81 66 113 
001524235805 1768 81 65 112 
...

Usual imports:

In [1]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

In case I want to give the run number as an argument

In [2]:
#import sys
#nrun = int(sys.argv[1]) if len(sys.argv)>1 else 20275 # ternary operator

The read the data file using numpy loadtxt and show histos

In [3]:
datadir  = './dati/'
nrun=20275
datafile = datadir + 'run%6.6d.dat' % nrun
print('Opening file: %s' % datafile)
Opening file: ./dati/run020275.dat
In [4]:
time, adc1, adc2, adc3, i5 = np.loadtxt(datafile, unpack=True)
plt.hist(adc1)
plt.show()

Plot customizing: increase the number of bins

In [5]:
plt.hist(adc1, 500)
plt.show()

Classic line

In [6]:
plt.hist(adc1, 500, histtype='step')
plt.show()

Zooming

In [7]:
plt.hist(adc1, 500, histtype='step', range=(1000,2500))
plt.show()

axis and title (property of the plot)

In [8]:
plt.hist(adc1, 500, histtype='step', range=(1000,2500), edgecolor='black', linewidth=1.2)
plt.title('Titolo', fontsize=18)
plt.xlabel('ADC', fontsize=16)
plt.ylabel('number of events', fontsize=16)
plt.show()

Computing the mean (numpy library), the mean in the same range of the histo, and plot a vertical line

In [9]:
hrange=(1000, 2500) # <-- it's a tuple
plt.hist(adc1, 500, histtype='step', range=hrange, edgecolor='black', linewidth=1.2)
plt.title('Titolo', fontsize=18)
plt.xlabel('ADC', fontsize=16)
plt.ylabel('number of events', fontsize=16)
histomean = np.mean([v for v in adc1 if hrange[0]<v<hrange[1]])
# vertical line
plt.axvline(x=histomean, color='b')
plt.show()

Fit with a gaussian

In [10]:
import scipy.optimize as opt

def gaus(x, A, mu, sigma):
    return A*np.exp(-(x-mu)**2/(2*sigma**2))


hrange=(1000, 2500) # <-- it's a tuple
h, bins, pathes = plt.hist(adc1, 500, histtype='step', range=hrange, edgecolor='black', linewidth=1.2, label='data')
# fit 

# find subrange for fitting
subrange=(1650, 1900)
newb =[b for b,bb in zip(bins,h) if subrange[0]<b<subrange[1]]
newh =[bb for b,bb in zip(bins,h) if subrange[0]<b<subrange[1]]

optimizedParams, pCov = opt.curve_fit(gaus, newb,newh, p0=[100, 1700, 100])
print(optimizedParams)
plt.plot(newb,gaus(newb,*optimizedParams),'r--',label='fit', linewidth=2)

plt.title('Titolo', fontsize=18)
plt.xlabel('ADC', fontsize=16)
plt.ylabel('number of events', fontsize=16)
histomean = np.mean([v for v in adc1 if hrange[0]<v<hrange[1]])
# vertical line
plt.axvline(x=histomean, color='b', label='mean')
plt.legend()
plt.show()
[ 179.76822461 1739.45319745   58.65203684]