def perform_fit(m, y_m, series): global j m = m[y_m!=0] y_m = y_m[y_m!=0] popt, pstats = papstats.curve_fit(fit_y_m, m, y_m, p0=[E_Ry, E_3p.nominal_value, 0]) popt_fixedERy, pstats_fixedERy = papstats.curve_fit(fit_y_m_fixedERy, m, y_m, p0=[E_3p.nominal_value, 0]) D_index = ['d', 's'][series-1] D = [0, d_s][series-1] plt.clf() plt.title(u'Diagramm 3.6.' + str(j) + u': Spektrallinien der ' + str(series) + u'. Nebenserie: $m' + D_index + ur' \rightarrow 3p$') papstats.plot_data(m, y_m) papstats.plot_fit(fit_y_m, popt, pstats, xspace=np.linspace(m[0], m[-1], 100), eq=r'\lambda_m = h*c/(E_{Ry}/(m - \Delta_' + D_index + ')^2 - E_{3p})', plabels=['E_{Ry}', 'E_{3p}', '\Delta_' + D_index], punits=['eV', 'eV', None]) papstats.plot_fit(fit_y_m_fixedERy, popt_fixedERy, pstats_fixedERy, xspace=np.linspace(m[0], m[-1], 100), eq=r'E_{Ry}=13.605eV', plabels=['E_{3p}', '\Delta_' + D_index], punits=['eV', None]) plt.ylabel(u'Wellenlänge der Spektrallinie $\lambda \, [nm]$') plt.xlabel(u'Anfangsniveau $m$') plt.legend(loc='upper right') papstats.savefig_a4('5.' + str(j) + '.png') j = j + 1 erw = np.array([E_Ry, E_3p, D]) res_fit = np.array(popt) diff = np.abs(erw - res_fit) res_fit_fixedERy = [E_Ry, popt_fixedERy[0], popt_fixedERy[1]] diff_fixedERy = np.abs(erw - res_fit_fixedERy) print papstats.table(labels=['', 'Erwartung', 'Fit', 'Abweichung', u'σ-Bereich', 'Fit mit E_Ry fixiert', 'Abweichung', u'σ-Bereich'], columns=[['E_Ry [eV]', 'E_3p [eV]', 'D_' + D_index], erw, res_fit, diff, unp.nominal_values(diff)/unp.std_devs(diff), res_fit_fixedERy, diff_fixedERy, unp.nominal_values(diff_fixedERy)/unp.std_devs(diff_fixedERy)])
def perform_fit(m, y_m, series): global j m = m[y_m != 0] y_m = y_m[y_m != 0] popt, pstats = papstats.curve_fit(fit_y_m, m, y_m, p0=[E_Ry, E_3p.nominal_value, 0]) popt_fixedERy, pstats_fixedERy = papstats.curve_fit( fit_y_m_fixedERy, m, y_m, p0=[E_3p.nominal_value, 0]) D_index = ['d', 's'][series - 1] D = [0, d_s][series - 1] plt.clf() plt.title(u'Diagramm 3.6.' + str(j) + u': Spektrallinien der ' + str(series) + u'. Nebenserie: $m' + D_index + ur' \rightarrow 3p$') papstats.plot_data(m, y_m) papstats.plot_fit(fit_y_m, popt, pstats, xspace=np.linspace(m[0], m[-1], 100), eq=r'\lambda_m = h*c/(E_{Ry}/(m - \Delta_' + D_index + ')^2 - E_{3p})', plabels=['E_{Ry}', 'E_{3p}', '\Delta_' + D_index], punits=['eV', 'eV', None]) papstats.plot_fit(fit_y_m_fixedERy, popt_fixedERy, pstats_fixedERy, xspace=np.linspace(m[0], m[-1], 100), eq=r'E_{Ry}=13.605eV', plabels=['E_{3p}', '\Delta_' + D_index], punits=['eV', None]) plt.ylabel(u'Wellenlänge der Spektrallinie $\lambda \, [nm]$') plt.xlabel(u'Anfangsniveau $m$') plt.legend(loc='upper right') papstats.savefig_a4('5.' + str(j) + '.png') j = j + 1 erw = np.array([E_Ry, E_3p, D]) res_fit = np.array(popt) diff = np.abs(erw - res_fit) res_fit_fixedERy = [E_Ry, popt_fixedERy[0], popt_fixedERy[1]] diff_fixedERy = np.abs(erw - res_fit_fixedERy) print papstats.table( labels=[ '', 'Erwartung', 'Fit', 'Abweichung', u'σ-Bereich', 'Fit mit E_Ry fixiert', 'Abweichung', u'σ-Bereich' ], columns=[['E_Ry [eV]', 'E_3p [eV]', 'D_' + D_index], erw, res_fit, diff, unp.nominal_values(diff) / unp.std_devs(diff), res_fit_fixedERy, diff_fixedERy, unp.nominal_values(diff_fixedERy) / unp.std_devs(diff_fixedERy)])
def compute_hwz(N_list, ttor, fit, plotname, title, sl=slice(None,None), Uscale=1, p0=None, eq=None, plabels=None, punits=None, Th_erw=None): N = np.sum(unp.uarray(N_list,np.sqrt(N_list)), axis=0) t = np.arange(len(N))*ttor+ttor/2. table = pt.PrettyTable() table.add_column('t [s]', t.astype(int), align='r') if len(N_list) > 1: for i in range(len(N_list)): table.add_column('N'+str(i+1), N_list[i].astype(int), align='r') table.add_column('Summe', N, align='r') else: table.add_column('N', N, align='r') with open("Resources/table_"+plotname+".txt", "w") as text_file: text_file.write(table.get_string()) global N_U N_U = N_U0*Uscale*ttor popt, pstats = papstats.curve_fit(fit, t[sl], N[sl], p0=p0) # Untergrundfehler N_U = (N_U0-N_U0.s)*Uscale*ttor popt_min, pstats_min = papstats.curve_fit(fit, t[sl], N[sl], p0=p0) N_U = (N_U0+N_U0.s)*Uscale*ttor popt_max, pstats_max = papstats.curve_fit(fit, t[sl], N[sl], p0=p0) N_U = N_U0*Uscale*ttor s_U = unp.nominal_values(((np.abs(popt-popt_min)+np.abs(popt-popt_max))/2.)) s_corrected = np.sqrt(unp.std_devs(popt)**2 + s_U**2) popt_corrected = unp.uarray(unp.nominal_values(popt),s_corrected) # Halbwertszeit Th = popt_corrected[::2]*unc.umath.log(2) for i in range(len(Th)): papstats.print_rdiff(Th[i]/60, Th_erw[i]/60) # Plot plt.clf() plt.title('Diagramm '+plotname+': '+title) plt.xlabel('Messzeit $t \, [s]$') plt.ylabel('Ereigniszahl $N$') xspace = np.linspace(0, t[-1]) papstats.plot_data(t, N, label='Messpunkte') papstats.plot_fit(fit, popt, pstats, xspace, eq=eq, plabels=plabels, punits=punits) plt.fill_between(xspace, fit(xspace, *unp.nominal_values(popt_min)), fit(xspace, *unp.nominal_values(popt_max)), color='g', alpha=0.2) Nmin = np.amin(unp.nominal_values(N)) for i in range(len(Th)): plt.hlines(popt[1::2][i].n/2.+N_U.n, 0, Th[i].n, lw=2, label='Halbwertszeit $'+papstats.pformat(Th[i], label=r'T_{\frac{1}{2}}'+('^'+str(i+1) if len(Th)>1 else ''), unit='s')+'$') handles, labels = plt.gca().get_legend_handles_labels() p = plt.Rectangle((0, 0), 1, 1, color='g', alpha=0.2) handles.append(p) labels.append('Fit im '+r'$1 \sigma$'+'-Bereich von $N_U$:'+''.join(['\n$'+papstats.pformat(s_U[i], label='\Delta '+plabels[i]+'^{U}', unit=punits[i])+'$' for i in range(len(plabels))])) plt.legend(handles, labels) papstats.savefig_a4(plotname+'.png')
def analyze_spektrallinien(fileprefix, figindex, crstl, sl, d=None, y=None): data = np.append(np.loadtxt(fileprefix+'.b.1.txt', skiprows=1), np.loadtxt(fileprefix+'.b.2.txt', skiprows=1), axis=0) b, n = data[:,0], data[:,1] n = unp.uarray(n, np.sqrt(n*20)/20) sl = [ [(b >= bounds[0]) & (b <= bounds[1]) for bounds in sl_row] for sl_row in sl] def fit_gauss(x, m, s, A, n_0): return A/np.sqrt(2*const.pi)/s*np.exp(-((x-m)**2)/2/(s**2))+n_0 r = [] plt.clf() papstats.plot_data(b,n) papstats.savefig_a4('3.'+str(figindex)+'.a.png') plt.clf() plt.suptitle('Diagramm 3.'+str(figindex)+u': Spektrallinien von Molybdän bei Vermessung mit einem '+crstl+'-Kristall') for i in range(2): r.append([]) # Linie for k in range(2): # Ordnung b_k = b[sl[i][k]] n_k = n[sl[i][k]] xspace = np.linspace(b_k[0], b_k[-1], num=1000) plt.subplot(2,2,i*2+k+1) plt.xlim(xspace[0], xspace[-1]) if i==1: plt.xlabel(u'Bestrahlungswinkel '+r'$\beta \, [^\circ]$') if k==0: plt.ylabel(u'Zählrate '+r'$n \, [\frac{Ereignisse}{s}]$') plt.title('$K_{'+(r'\alpha' if i==0 else r'\beta')+'}$ ('+str(k+1)+'. Ordnung)') papstats.plot_data(b_k, n_k) # Gauss-Fit popt, pstats = papstats.curve_fit(fit_gauss, b_k, n_k, p0=[b_k[0]+(b_k[-1]-b_k[0])/2, (b_k[-1]-b_k[0])/4, np.sum(n_k).n, n_k[0].n]) plt.fill_between(b_k, 0, unp.nominal_values(n_k), color='g', alpha=0.2) FWHM = popt[1]*2*unp.sqrt(2*unp.log(2)) plt.hlines(popt[3].n+(fit_gauss(xspace, *unp.nominal_values(popt)).max()-popt[3].n)/2, popt[0].n-FWHM.n/2, popt[0].n+FWHM.n/2, color='black', lw=2, label='$'+papstats.pformat(FWHM, label='FWHM', unit=r'^\circ')+'$') papstats.plot_fit(fit_gauss, popt, xspace=xspace, plabels=[r'\mu', r'\sigma', 'A', 'n_0'], punits=['^\circ', '^\circ', 's^{-1}', 's^{-1}']) plt.ylim(unp.nominal_values(n_k).min()-n_k[unp.nominal_values(n_k).argmin()].s, unp.nominal_values(n_k).max()+(unp.nominal_values(n_k).max()-unp.nominal_values(n_k).min())) plt.legend(loc='upper center', prop={'size':10}) b_S = unc.ufloat(popt[0].n, np.abs(popt[1].n)) print "Winkel:", papstats.pformat(b_S, unit='°', format='.2u') if y is None: r[i].append(y_bragg(b_S, n=k+1)) print "Wellenlänge der Linie:", papstats.pformat(r[i][k]/const.pico, label='y', unit='pm', format='.2u') if d is None: r[i].append((k+1)*y[i][k]/unc.umath.sin(b_S*const.degree)) print "Gitterkonstante:", papstats.pformat(r[i][k]/const.pico, label='a', unit='pm', format='.2u') papstats.savefig_a4('3.'+str(figindex)+'.png') return r
def compare_gauss_poisson(t, data, p0, title, filename, xlim, ylim): N = data[:,0] n = data[:,1] n = unp.uarray(n,np.sqrt(n)) sl = (n >= 10) # TODO: Häufigkeit n mindestens 10 # Fit popt_gauss, pstats_gauss = papstats.curve_fit(fit_gauss, N[sl], n[sl], p0=p0, sigma=unp.std_devs(n[sl])) popt_poisson, pstats_poisson = papstats.curve_fit(fit_poisson, N[sl], n[sl], p0=[p0[0],p0[2]], sigma=unp.std_devs(n[sl])) # Plot for log in [False, True]: plt.clf() plt.title('Diagramm '+filename+('.b' if log else '.a')+': '+title + (' (logarithmisch)' if log else '')) if log: plt.yscale('log') papstats.plot_data(N/t, n) xrange = 4*popt_gauss[1].n xspace = np.linspace(xlim[2 if log else 0]*t,xlim[3 if log else 1]*t,num=200) papstats.plot_fit(fit_gauss, popt_gauss, pstats_gauss, xspace, xscale=1./t, eq=r'G(N;\mu,\sigma)', plabels=[r'\mu',r'\sigma','A']) papstats.plot_fit(fit_poisson, popt_poisson, pstats_poisson, xspace, xscale=1./t, eq=r'P(N;\mu)', plabels=[r'\mu','A'], ls='dashed') plt.xlim(xspace[0]/t,xspace[-1]/t) plt.ylim(ylim[2 if log else 0],ylim[3 if log else 1]) plt.xlabel(u'Zählrate '+r'$Z=\frac{N}{t} \, [\frac{Ereignisse}{s}]$') plt.ylabel(u'Häufigkeit '+r'$n$') plt.legend(loc=('lower center' if log else 'upper right')) papstats.savefig_a4(filename+('.b' if log else '.a')+'.png') # Residuum plt.clf() plt.title('Diagramm '+filename+'.c: Residuum') plt.hist(fit_gauss(unp.nominal_values(N), *unp.nominal_values(popt_gauss))-unp.nominal_values(n), bins=30) plt.hist(pstats_gauss.residual, bins=30) plt.hist(pstats_poisson.residual, bins=30) papstats.savefig_a4(filename+'.c.png')
d = d_LiF ##### print u"\n# a: Grenzwellenlänge und Plancksche Konstante aus LiF Spektrum" ##### b, n = np.loadtxt('1.a.txt', skiprows=1, unpack=True) n = unp.uarray(n, np.sqrt(n*5)/5) # Untergrund def fit_U(b, n_U): return b-b+n_U sl_U = slice(0, 13) popt_U, pstats_U = papstats.curve_fit(fit_U, b[sl_U], n[sl_U]) n_U = popt_U[0] print "Untergrund:", papstats.pformat(n_U, format='.2u') # Bremsspektrum-Fit mit Kramerscher Regel def kramer(y, ymin, K): y = unp.nominal_values(y) return K*(y/ymin-1)/y**2 def fit_brems(b, ymin, K): return kramer(y=y_bragg(b), ymin=ymin, K=K) sl_brems = ( (n <= 200) & ( (b <= 17) | (n <= 45) ) ) & (n > 20) popt_brems, pstats_brems = papstats.curve_fit(fit_brems, b[sl_brems], n[sl_brems], p0=[4.133e-11, 1e-18]) # Extrapolation def fit_lin(b, a, n_0): return a*b + n_0
n[i] = n[i] + 0.5 return n n = nspace_centered_offset(I) print papstats.table(labels=['n', 'x', 'I'], units=[None, 'px', None], columns=[n, x, I]) def fit_linear(x, m): return m * x def approximate_I(n): x = n*const.pi + 1e-6 return np.sin(x)**2/x**2 # Fit Minima popt, pstats = papstats.curve_fit(fit_linear, n[1::2], x[1::2]) # Plot Abstand plt.clf() plt.title(u'Diagramm 3.1: Abstand der Interferenzmaxima und -minima vom Hauptmaximum') papstats.plot_data(n[1::2], x[1::2], c='b', label='Minima') papstats.plot_data(n[0::2], x[0::2], c='r', label='Maxima') papstats.plot_fit(fit_linear, popt, xspace=n, eq='x_{Min}=m*n', punits=['px']) plt.legend(loc='upper left') plt.xlabel('Ordnung $n$') plt.ylabel('Abstand vom Hauptmaximum $x \, [px]$') papstats.savefig_a4('3.1.png') # Spaltweite d = 80 * const.milli * 635 * const.nano / (popt[0] * px) # TODO: use px_erw? print papstats.pformat(d / const.micro, label='Spaltweite d', unit='um')
U = unp.uarray(data[:, 0], 10) N = data[:, 1] N = unp.uarray(N, np.sqrt(N)) / 30 def fit_platlin(x, c, N_0): return c * x + N_0 def fit_platconst(x, N_0): return np.zeros(len(x)) + N_0 popt_const, pstats_const = papstats.curve_fit(fit_platconst, U[1:], N[1:], p0=[60]) popt_lin, pstats_lin = papstats.curve_fit(fit_platlin, U[1:], N[1:]) popt_lin2, pstats_lin2 = papstats.curve_fit(fit_platlin, U[8:], N[8:]) plt.clf() plt.title( u'Diagramm 3.1: Vermessung des Plateaubereichs der Zählrohrkennlinie') papstats.plot_data(U, N) papstats.plot_fit(fit_platconst, popt_const, pstats_const, np.linspace(U[1].n, U[-1].n), eq='N=N_0', ls='dashed', lw=2)
t = np.reshape(t, (len(r), 5)) t = unp.uarray(np.mean(t, axis=1), np.std(t, axis=1) / np.sqrt(len(t))) v = s / t v_k = v / drho y = (1 + 2.1 * r / R) v_kl = v_k * y r_sq = r**2 def fit_linear_origin(x, m): return m * x popt, pstats = papstats.curve_fit(fit_linear_origin, r_sq, v_k) popt_l, pstats_l = papstats.curve_fit(fit_linear_origin, r_sq, v_kl) eta = 2. / 9. * const.g / popt_l[0] print papstats.pformat(eta, label='eta') v_lam = 2. / 9. * const.g * drho / eta * r_sq plt.clf() plt.title(u'Diagramm 3.1: Bestimmung der Viskosität nach Stokes') papstats.plot_data(r_sq / const.centi**2, v_k, label='Messwerte') papstats.plot_data(r_sq / const.centi**2, v_kl, label='Ladenburgkorrigierte Messwerte', color='red') papstats.plot_data(r_sq / const.centi**2, v_lam / drho,
dm = np.array([0, 10, 20, 30, 40]) m_0 = np.array([48, 49, 49]) def fit_dm(x, d): global m_0_i return d * x + m_0_i plt.clf() plt.suptitle(u'Diagramm 3.1: Vorbeigezogene Interferenzmaxima über Druck in der Küvette') xspace = np.linspace(- const.atm / const.torr, 0) ax = None d_list = [] for i in range(len(p)): m_0_i = m_0[i] popt, pstats = papstats.curve_fit(fit_dm, p[i], dm) ax = plt.subplot(len(p), 1, i + 1, sharex=ax, sharey=ax) plt.title('Messung '+str(i+1)) papstats.plot_data(p[i], dm, label='Messwerte') papstats.plot_fit(fit_dm, popt, xspace=xspace, eq='\Delta m=p*d+\Delta m_0', punits=['Torr^{-1}']) if i != len(p) - 1: plt.setp(ax.get_xticklabels(), visible=False) else: plt.xlabel(u'Druck $p \, [Torr]$') plt.ylabel(u'$\Delta m$') plt.xlim(xspace[0], xspace[-1]) plt.ylim(0, 50) plt.legend(loc='upper left') d_list.append(popt[0]) papstats.savefig_a4('3.1.png')
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0,parentdir) import papstats ##### print u"# 3.2: Dämpfung des Kreisels" ##### def fit_exp(x, a, A): return A * np.exp(a * x) t, w = np.loadtxt('2.2.txt', skiprows=1, unpack=True) t = t w = unp.uarray(w, 10) popt, pstats = papstats.curve_fit(fit_exp, t, w) plt.clf() plt.title(u'Diagramm 3.1: Dämpfung des Kreisels') papstats.plot_data(t, w) papstats.plot_fit(fit_exp, popt, pstats, xspace=np.linspace(t[0], t[-1], 100), eq=r'w_0*e^{\lambda * t}', plabels=[r'\lambda', '\omega_0'], punits=[ur'\frac{1}{min}', ur'\frac{2π}{min}']) plt.xlabel('Zeit $t \, [min]$') plt.ylabel(ur'Drehfrequenz $\omega_F \, [\frac{2π}{min}]$') plt.yscale('log') plt.legend() papstats.savefig_a4('3.1.png') tau = -1. / popt[0] * const.minute t_H = np.log(2) * tau print papstats.pformat(tau / const.minute, label=u'Dämpfungskonstante tau', unit='min') print papstats.pformat(t_H / const.minute, label=u'Halbwertszeit t_H', unit='min')
# Fit Uind = n*B*A*w def fit_Uind(x, c): return c*x # a) Abhängigkeit von der Frequenz I = unc.ufloat(4, 0.05) data = np.loadtxt('2.a.txt', skiprows=1) w = unp.uarray(data[:,0], data[:,1])*2*const.pi Uind = unp.uarray(data[:,2], data[:,3])/2 popt, pstats = papstats.curve_fit(fit_Uind, w, Uind) # Berechnung der Magnetfeldstärke B = popt[0]/nF/AF papstats.print_rdiff(B, B_helmh(I)) Uind_true = nF*B_helmh(I)*AF*w plt.clf() plt.title(u'Diagramm 3.1: Induktionsspannung in Abhängigkeit von der Rotationsfrequenz der Flachspule') plt.xlabel('Kreisfrequenz $\omega \, [Hz]$') plt.ylabel('Max. Induktionsspannung $U_{ind} \, [V]$') papstats.plot_data(w, Uind, label='Messpunkte') papstats.plot_fit(fit_Uind, popt, pstats, np.linspace(w[0].n, w[-1].n), eq='U_{ind}=c*\omega', punits=[r'T \times m^2']) papstats.plot_data(w, Uind_true, label='Erwartungswerte '+r'$U_{ind}=\frac{8*\mu_0*n_H*I}{\sqrt{125}*R}*n_F*A_F*\omega$') plt.legend(loc='lower right')
##### print "\n# 3 Absorption von y-Strahlung in Blei" ##### data = np.loadtxt('2.txt', skiprows=1) x = data[:,0]*const.milli N = data[:,1] n = unp.uarray(N, np.sqrt(N))/60 n = n-nU def fit_damp(x, mu, n_0): return n_0*np.exp(-mu*x) popt, pstats = papstats.curve_fit(fit_damp, x, n) rhoPb = 11.34*const.gram/const.centi**3 k = popt[0]/rhoPb print "Materialunabhängiger Schwächungskoeffizient:", papstats.pformat(k/(const.centi**2/const.gram), label='k', unit='cm^2/g', format='.2u') Ey = unc.ufloat(1.45, 0.15) print "Energie der y-Quanten" papstats.print_rdiff(Ey,unc.ufloat((1.173+1.333)/2,0)) plt.clf() plt.title('Diagramm 3.2: '+r'$\gamma$'+u'-Strahlung in Abhängigkeit der Absorberdicke') plt.yscale('log') plt.xlabel('Absorberdicke $x \, [mm]$') plt.ylabel(u'korrigierte Zählrate '+r'$(n-n_U) \, [\frac{Ereignisse}{s}]$') ylim = [1.5,1e2] xlim = np.array([0,55])*const.milli
print papstats.table(labels=['n', 'x', 'I'], units=[None, 'px', None], columns=[n, x, I]) def fit_linear(x, m): return m * x def approximate_I(n): x = n * const.pi + 1e-6 return np.sin(x)**2 / x**2 # Fit Minima popt, pstats = papstats.curve_fit(fit_linear, n[1::2], x[1::2]) # Plot Abstand plt.clf() plt.title( u'Diagramm 3.1: Abstand der Interferenzmaxima und -minima vom Hauptmaximum' ) papstats.plot_data(n[1::2], x[1::2], c='b', label='Minima') papstats.plot_data(n[0::2], x[0::2], c='r', label='Maxima') papstats.plot_fit(fit_linear, popt, xspace=n, eq='x_{Min}=m*n', punits=['px']) plt.legend(loc='upper left') plt.xlabel('Ordnung $n$') plt.ylabel('Abstand vom Hauptmaximum $x \, [px]$') papstats.savefig_a4('3.1.png') # Spaltweite
def fit_Uind(x, c): return c * x # a) Abhängigkeit von der Frequenz I = unc.ufloat(4, 0.05) data = np.loadtxt('2.a.txt', skiprows=1) w = unp.uarray(data[:, 0], data[:, 1]) * 2 * const.pi Uind = unp.uarray(data[:, 2], data[:, 3]) / 2 popt, pstats = papstats.curve_fit(fit_Uind, w, Uind) # Berechnung der Magnetfeldstärke B = popt[0] / nF / AF papstats.print_rdiff(B, B_helmh(I)) Uind_true = nF * B_helmh(I) * AF * w plt.clf() plt.title( u'Diagramm 3.1: Induktionsspannung in Abhängigkeit von der Rotationsfrequenz der Flachspule' ) plt.xlabel('Kreisfrequenz $\omega \, [Hz]$') plt.ylabel('Max. Induktionsspannung $U_{ind} \, [V]$') papstats.plot_data(w, Uind, label='Messpunkte') papstats.plot_fit(fit_Uind,
def compare_gauss_poisson(t, data, p0, title, filename, xlim, ylim): N = data[:, 0] n = data[:, 1] n = unp.uarray(n, np.sqrt(n)) sl = (n >= 10) # TODO: Häufigkeit n mindestens 10 # Fit popt_gauss, pstats_gauss = papstats.curve_fit(fit_gauss, N[sl], n[sl], p0=p0, sigma=unp.std_devs(n[sl])) popt_poisson, pstats_poisson = papstats.curve_fit(fit_poisson, N[sl], n[sl], p0=[p0[0], p0[2]], sigma=unp.std_devs( n[sl])) # Plot for log in [False, True]: plt.clf() plt.title('Diagramm ' + filename + ('.b' if log else '.a') + ': ' + title + (' (logarithmisch)' if log else '')) if log: plt.yscale('log') papstats.plot_data(N / t, n) xrange = 4 * popt_gauss[1].n xspace = np.linspace(xlim[2 if log else 0] * t, xlim[3 if log else 1] * t, num=200) papstats.plot_fit(fit_gauss, popt_gauss, pstats_gauss, xspace, xscale=1. / t, eq=r'G(N;\mu,\sigma)', plabels=[r'\mu', r'\sigma', 'A']) papstats.plot_fit(fit_poisson, popt_poisson, pstats_poisson, xspace, xscale=1. / t, eq=r'P(N;\mu)', plabels=[r'\mu', 'A'], ls='dashed') plt.xlim(xspace[0] / t, xspace[-1] / t) plt.ylim(ylim[2 if log else 0], ylim[3 if log else 1]) plt.xlabel(u'Zählrate ' + r'$Z=\frac{N}{t} \, [\frac{Ereignisse}{s}]$') plt.ylabel(u'Häufigkeit ' + r'$n$') plt.legend(loc=('lower center' if log else 'upper right')) papstats.savefig_a4(filename + ('.b' if log else '.a') + '.png') # Residuum plt.clf() plt.title('Diagramm ' + filename + '.c: Residuum') plt.hist( fit_gauss(unp.nominal_values(N), *unp.nominal_values(popt_gauss)) - unp.nominal_values(n), bins=30) plt.hist(pstats_gauss.residual, bins=30) plt.hist(pstats_poisson.residual, bins=30) papstats.savefig_a4(filename + '.c.png')
os.sys.path.insert(0, parentdir) import papstats ##### print u"# 3.2: Dämpfung des Kreisels" ##### def fit_exp(x, a, A): return A * np.exp(a * x) t, w = np.loadtxt('2.2.txt', skiprows=1, unpack=True) t = t w = unp.uarray(w, 10) popt, pstats = papstats.curve_fit(fit_exp, t, w) plt.clf() plt.title(u'Diagramm 3.1: Dämpfung des Kreisels') papstats.plot_data(t, w) papstats.plot_fit(fit_exp, popt, pstats, xspace=np.linspace(t[0], t[-1], 100), eq=r'w_0*e^{\lambda * t}', plabels=[r'\lambda', '\omega_0'], punits=[ur'\frac{1}{min}', ur'\frac{2π}{min}']) plt.xlabel('Zeit $t \, [min]$') plt.ylabel(ur'Drehfrequenz $\omega_F \, [\frac{2π}{min}]$') plt.yscale('log') plt.legend()
##### print u"\n# a: Grenzwellenlänge und Plancksche Konstante aus LiF Spektrum" ##### b, n = np.loadtxt('1.a.txt', skiprows=1, unpack=True) n = unp.uarray(n, np.sqrt(n * 5) / 5) # Untergrund def fit_U(b, n_U): return b - b + n_U sl_U = slice(0, 13) popt_U, pstats_U = papstats.curve_fit(fit_U, b[sl_U], n[sl_U]) n_U = popt_U[0] print "Untergrund:", papstats.pformat(n_U, format='.2u') # Bremsspektrum-Fit mit Kramerscher Regel def kramer(y, ymin, K): y = unp.nominal_values(y) return K * (y / ymin - 1) / y**2 def fit_brems(b, ymin, K): return kramer(y=y_bragg(b), ymin=ymin, K=K) sl_brems = ((n <= 200) & ((b <= 17) | (n <= 45))) & (n > 20)
# kombiniertes Histogramm der x- und y-Daten dr = np.append(dx, dy) / const.micro n, bins, patches = plt.hist(dr, bins=13, label="Messungen") bin_centers = bins[:-1] + np.diff(bins) / 2. # Gauss Fit def fit_gauss(x, mu, sigma, A): return A / np.sqrt( (sigma**2) * 2 * const.pi) * np.exp(-((x - mu)**2) / 2 / (sigma**2)) popt, pstats = papstats.curve_fit(fit_gauss, bin_centers, n, p0=[dr.mean(), dr.std(), 1. / np.sum(n)]) xspace = np.linspace(popt[0].nominal_value - 4 * popt[1].nominal_value, popt[0].nominal_value + 4 * popt[1].nominal_value, 100) papstats.plot_fit(fit_gauss, popt, xspace=xspace, plabels=['\mu', '\sigma', 'A'], punits=['\mu m', '\mu m', None]) plt.xlim(xspace[0], xspace[-1]) plt.xlabel(ur'Verschiebung $\Delta x$ und $\Delta y$ $[\mu m]$') plt.ylabel(ur'Häufigkeit $N$') plt.legend() papstats.savefig_a4('2.png')
def analyze_spektrallinien(fileprefix, figindex, crstl, sl, d=None, y=None): data = np.append(np.loadtxt(fileprefix + '.b.1.txt', skiprows=1), np.loadtxt(fileprefix + '.b.2.txt', skiprows=1), axis=0) b, n = data[:, 0], data[:, 1] n = unp.uarray(n, np.sqrt(n * 20) / 20) sl = [[(b >= bounds[0]) & (b <= bounds[1]) for bounds in sl_row] for sl_row in sl] def fit_gauss(x, m, s, A, n_0): return A / np.sqrt(2 * const.pi) / s * np.exp(-((x - m)**2) / 2 / (s**2)) + n_0 r = [] plt.clf() papstats.plot_data(b, n) papstats.savefig_a4('3.' + str(figindex) + '.a.png') plt.clf() plt.suptitle('Diagramm 3.' + str(figindex) + u': Spektrallinien von Molybdän bei Vermessung mit einem ' + crstl + '-Kristall') for i in range(2): r.append([]) # Linie for k in range(2): # Ordnung b_k = b[sl[i][k]] n_k = n[sl[i][k]] xspace = np.linspace(b_k[0], b_k[-1], num=1000) plt.subplot(2, 2, i * 2 + k + 1) plt.xlim(xspace[0], xspace[-1]) if i == 1: plt.xlabel(u'Bestrahlungswinkel ' + r'$\beta \, [^\circ]$') if k == 0: plt.ylabel(u'Zählrate ' + r'$n \, [\frac{Ereignisse}{s}]$') plt.title('$K_{' + (r'\alpha' if i == 0 else r'\beta') + '}$ (' + str(k + 1) + '. Ordnung)') papstats.plot_data(b_k, n_k) # Gauss-Fit popt, pstats = papstats.curve_fit(fit_gauss, b_k, n_k, p0=[ b_k[0] + (b_k[-1] - b_k[0]) / 2, (b_k[-1] - b_k[0]) / 4, np.sum(n_k).n, n_k[0].n ]) plt.fill_between(b_k, 0, unp.nominal_values(n_k), color='g', alpha=0.2) FWHM = popt[1] * 2 * unp.sqrt(2 * unp.log(2)) plt.hlines(popt[3].n + (fit_gauss(xspace, *unp.nominal_values(popt)).max() - popt[3].n) / 2, popt[0].n - FWHM.n / 2, popt[0].n + FWHM.n / 2, color='black', lw=2, label='$' + papstats.pformat(FWHM, label='FWHM', unit=r'^\circ') + '$') papstats.plot_fit(fit_gauss, popt, xspace=xspace, plabels=[r'\mu', r'\sigma', 'A', 'n_0'], punits=['^\circ', '^\circ', 's^{-1}', 's^{-1}']) plt.ylim( unp.nominal_values(n_k).min() - n_k[unp.nominal_values(n_k).argmin()].s, unp.nominal_values(n_k).max() + (unp.nominal_values(n_k).max() - unp.nominal_values(n_k).min())) plt.legend(loc='upper center', prop={'size': 10}) b_S = unc.ufloat(popt[0].n, np.abs(popt[1].n)) print "Winkel:", papstats.pformat(b_S, unit='°', format='.2u') if y is None: r[i].append(y_bragg(b_S, n=k + 1)) print "Wellenlänge der Linie:", papstats.pformat(r[i][k] / const.pico, label='y', unit='pm', format='.2u') if d is None: r[i].append( (k + 1) * y[i][k] / unc.umath.sin(b_S * const.degree)) print "Gitterkonstante:", papstats.pformat(r[i][k] / const.pico, label='a', unit='pm', format='.2u') papstats.savefig_a4('3.' + str(figindex) + '.png') return r
rho_F = unc.ufloat(1.1442, 0.0002) * const.gram/const.centi**3 drho = rho_K - rho_F t = np.reshape(t, (len(r), 5)) t = unp.uarray(np.mean(t, axis=1), np.std(t, axis=1)/np.sqrt(len(t))) v = s / t v_k = v / drho y = (1 + 2.1 * r / R) v_kl = v_k * y r_sq = r**2 def fit_linear_origin(x, m): return m * x popt, pstats = papstats.curve_fit(fit_linear_origin, r_sq, v_k) popt_l, pstats_l = papstats.curve_fit(fit_linear_origin, r_sq, v_kl) eta = 2. / 9. * const.g / popt_l[0] print papstats.pformat(eta, label='eta') v_lam = 2. / 9. * const.g * drho / eta * r_sq plt.clf() plt.title(u'Diagramm 3.1: Bestimmung der Viskosität nach Stokes') papstats.plot_data(r_sq / const.centi**2, v_k, label='Messwerte') papstats.plot_data(r_sq / const.centi**2, v_kl, label='Ladenburgkorrigierte Messwerte', color='red') papstats.plot_data(r_sq / const.centi**2, v_lam / drho, label='Erwartungswerte', color='orange') papstats.plot_fit(fit_linear_origin, popt, pstats, xspace=unp.nominal_values(r_sq), xscale=1./const.centi**2, eq=r'\frac{v}{\rho_K-\rho_F}=m*r^2', punits=[r'\frac{m^2}{kg*s}']) papstats.plot_fit(fit_linear_origin, popt_l, pstats_l, xspace=unp.nominal_values(r_sq), xscale=1./const.centi**2, eq=r'\frac{v}{\rho_K-\rho_F}=m*r^2', punits=[r'\frac{m^2}{kg*s}']) plt.xlabel('$r^2 \, [cm^2]$ mit $r$: Kugelradius') plt.ylabel(r'$\frac{v}{\rho_K-\rho_F}$ mit $v$: mittlere Sinkgeschwindigkeit')
##### data = np.loadtxt('2.txt', skiprows=1) x = data[:, 0] * const.milli N = data[:, 1] n = unp.uarray(N, np.sqrt(N)) / 60 n = n - nU def fit_damp(x, mu, n_0): return n_0 * np.exp(-mu * x) popt, pstats = papstats.curve_fit(fit_damp, x, n) rhoPb = 11.34 * const.gram / const.centi**3 k = popt[0] / rhoPb print "Materialunabhängiger Schwächungskoeffizient:", papstats.pformat( k / (const.centi**2 / const.gram), label='k', unit='cm^2/g', format='.2u') Ey = unc.ufloat(1.45, 0.15) print "Energie der y-Quanten" papstats.print_rdiff(Ey, unc.ufloat((1.173 + 1.333) / 2, 0)) plt.clf() plt.title('Diagramm 3.2: ' + r'$\gamma$' + u'-Strahlung in Abhängigkeit der Absorberdicke') plt.yscale('log') plt.xlabel('Absorberdicke $x \, [mm]$') plt.ylabel(u'korrigierte Zählrate ' + r'$(n-n_U) \, [\frac{Ereignisse}{s}]$')
##### print('# 1 (Plateaubereich des Zählrohrs)') ##### data = np.loadtxt('2.txt', skiprows=1) U = unp.uarray(data[:,0], 10) N = data[:,1] N = unp.uarray(N, np.sqrt(N))/30 def fit_platlin(x, c, N_0): return c*x+N_0 def fit_platconst(x, N_0): return np.zeros(len(x))+N_0 popt_const, pstats_const = papstats.curve_fit(fit_platconst, U[1:], N[1:], p0=[60]) popt_lin, pstats_lin = papstats.curve_fit(fit_platlin, U[1:], N[1:]) popt_lin2, pstats_lin2 = papstats.curve_fit(fit_platlin, U[8:], N[8:]) plt.clf() plt.title(u'Diagramm 3.1: Vermessung des Plateaubereichs der Zählrohrkennlinie') papstats.plot_data(U, N) papstats.plot_fit(fit_platconst, popt_const, pstats_const, np.linspace(U[1].n, U[-1].n), eq='N=N_0', ls='dashed', lw=2) papstats.plot_fit(fit_platlin, popt_lin, pstats_lin, np.linspace(U[1].n, U[-1].n), eq='N=c*U_Z+N_0', ls='dotted', lw=2) papstats.plot_fit(fit_platlin, popt_lin2, pstats_lin2, np.linspace(U[8].n, U[-1].n), eq='N=c*U_Z+N_0, \, U_Z \in [600,700]V', lw=2) plt.xlabel(u'Zählrohrspannung '+r'$U_Z \, [V]$') plt.ylabel(u'Zählrate '+r'$\frac{N}{t} \, [\frac{Ereignisse}{s}]$') plt.xlim(430,720) plt.ylim(10,65) plt.legend(loc='lower right') papstats.savefig_a4('3.1.png')
def compute_hwz(N_list, ttor, fit, plotname, title, sl=slice(None, None), Uscale=1, p0=None, eq=None, plabels=None, punits=None, Th_erw=None): N = np.sum(unp.uarray(N_list, np.sqrt(N_list)), axis=0) t = np.arange(len(N)) * ttor + ttor / 2. table = pt.PrettyTable() table.add_column('t [s]', t.astype(int), align='r') if len(N_list) > 1: for i in range(len(N_list)): table.add_column('N' + str(i + 1), N_list[i].astype(int), align='r') table.add_column('Summe', N, align='r') else: table.add_column('N', N, align='r') with open("Resources/table_" + plotname + ".txt", "w") as text_file: text_file.write(table.get_string()) global N_U N_U = N_U0 * Uscale * ttor popt, pstats = papstats.curve_fit(fit, t[sl], N[sl], p0=p0) # Untergrundfehler N_U = (N_U0 - N_U0.s) * Uscale * ttor popt_min, pstats_min = papstats.curve_fit(fit, t[sl], N[sl], p0=p0) N_U = (N_U0 + N_U0.s) * Uscale * ttor popt_max, pstats_max = papstats.curve_fit(fit, t[sl], N[sl], p0=p0) N_U = N_U0 * Uscale * ttor s_U = unp.nominal_values( ((np.abs(popt - popt_min) + np.abs(popt - popt_max)) / 2.)) s_corrected = np.sqrt(unp.std_devs(popt)**2 + s_U**2) popt_corrected = unp.uarray(unp.nominal_values(popt), s_corrected) # Halbwertszeit Th = popt_corrected[::2] * unc.umath.log(2) for i in range(len(Th)): papstats.print_rdiff(Th[i] / 60, Th_erw[i] / 60) # Plot plt.clf() plt.title('Diagramm ' + plotname + ': ' + title) plt.xlabel('Messzeit $t \, [s]$') plt.ylabel('Ereigniszahl $N$') xspace = np.linspace(0, t[-1]) papstats.plot_data(t, N, label='Messpunkte') papstats.plot_fit(fit, popt, pstats, xspace, eq=eq, plabels=plabels, punits=punits) plt.fill_between(xspace, fit(xspace, *unp.nominal_values(popt_min)), fit(xspace, *unp.nominal_values(popt_max)), color='g', alpha=0.2) Nmin = np.amin(unp.nominal_values(N)) for i in range(len(Th)): plt.hlines(popt[1::2][i].n / 2. + N_U.n, 0, Th[i].n, lw=2, label='Halbwertszeit $' + papstats.pformat(Th[i], label=r'T_{\frac{1}{2}}' + ('^' + str(i + 1) if len(Th) > 1 else ''), unit='s') + '$') handles, labels = plt.gca().get_legend_handles_labels() p = plt.Rectangle((0, 0), 1, 1, color='g', alpha=0.2) handles.append(p) labels.append('Fit im ' + r'$1 \sigma$' + '-Bereich von $N_U$:' + ''.join([ '\n$' + papstats.pformat( s_U[i], label='\Delta ' + plabels[i] + '^{U}', unit=punits[i]) + '$' for i in range(len(plabels)) ])) plt.legend(handles, labels) papstats.savefig_a4(plotname + '.png')
f = unc.ufloat(10.1, 0.1) omega = f * 2 * c.pi I = unp.uarray(data[:, 0], data[:, 1]) U_ss = unp.uarray(data[:, 2], data[:, 3]) U_ind = U_ss / 2. U_ind_exp = B_H(I) * A_F * n_F * omega def U_ind_max(I, c): return I * c popt, pstats = papstats.curve_fit(U_ind_max, I, U_ind) plt.xlabel('Spulenstrom $I$ in $A$') papstats.plot_data(I, U_ind, label="Messpunkte") papstats.plot_fit(U_ind_max, popt, pstats, unp.nominal_values(I), eq=u"Û_{ind} = c * I") papstats.plot_data(I, U_ind_exp, label='Erwartungswerte') plt.legend(borderpad=1) papstats.savefig_a4('2.b.png') print "Induktionspannung bei periodischem Feldstrom" Omega = unc.ufloat(104, 1) * 2 * c.pi # Kreisfrequenz der Wechselspannung data = np.loadtxt('3.a.txt', skiprows=1)
##### print "3.2: Kontrollverteilung" ##### plt.cla() plt.title(ur'Diagramm 3.2: Histogramm der Verschiebungen mit Gauß-Fit') # kombiniertes Histogramm der x- und y-Daten dr = np.append(dx, dy) / const.micro n, bins, patches = plt.hist(dr, bins=13, label="Messungen") bin_centers = bins[:-1] + np.diff(bins) / 2. # Gauss Fit def fit_gauss(x, mu, sigma, A): return A/np.sqrt((sigma**2)*2*const.pi)*np.exp(-((x-mu)**2)/2/(sigma**2)) popt, pstats = papstats.curve_fit(fit_gauss, bin_centers, n, p0=[dr.mean(), dr.std(), 1./np.sum(n)]) xspace = np.linspace(popt[0].nominal_value - 4 * popt[1].nominal_value, popt[0].nominal_value + 4 * popt[1].nominal_value, 100) papstats.plot_fit(fit_gauss, popt, xspace=xspace, plabels=['\mu', '\sigma', 'A'], punits=['\mu m', '\mu m', None]) plt.xlim(xspace[0], xspace[-1]) plt.xlabel(ur'Verschiebung $\Delta x$ und $\Delta y$ $[\mu m]$') plt.ylabel(ur'Häufigkeit $N$') plt.legend() papstats.savefig_a4('2.png') # Berechnung der Konstanten mu, sigma = popt[0] * const.micro, popt[1] * const.micro D_fit = sigma**2 / 2. / t_mean print papstats.pformat(D_fit, format='c', label='D_fit', unit='m^2/s') papstats.print_rdiff(D_fit, D) k_B_fit = 6 * const.pi * eta * D_fit * a / T