Esempio n. 1
0
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)])
Esempio n. 2
0
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)])
Esempio n. 3
0
File: n.py Progetto: knly/PAP2
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
Esempio n. 4
0
File: n.py Progetto: knly/PAP2
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')
Esempio n. 5
0
File: n.py Progetto: knly/PAP2
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')
Esempio n. 6
0
                                        label='b',
                                        unit='°',
                                        format='.2u')

# Plot
plt.clf()
plt.title(
    u'Diagramm 3.1: Bremsspektrum von LiF mit Untergrund und Extrapolation am kurzwelligen Ende'
)
axmain = plt.subplot(111)
plt.xlabel(ur'Bestrahlungswinkel $\beta \, [^\circ]$')
plt.ylabel(ur'Zählrate $n \, [\frac{Ereignisse}{s}]$')
xlim = [b[0], b[-1]]
xspace = np.linspace(*xlim, num=1000)
axmain.set_xlim(*xlim)
papstats.plot_data(b, n, label='Messpunkte')
plt.fill_between(unp.nominal_values(b),
                 0,
                 unp.nominal_values(n),
                 color='g',
                 alpha=0.2)

from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

zoomxlim = [3, 7]
zoomylim = [0, 200]
zoomxspace = np.linspace(*zoomxlim, num=100)
axzoom = zoomed_inset_axes(axmain, 2.5, loc=1)
axzoom.set_xlim(*zoomxlim)
axzoom.set_ylim(*zoomylim)
Esempio n. 7
0
File: n.py Progetto: knly/PAP2
print "Grenzwellenlänge:", papstats.pformat(y_G/const.pico, label='y_G', unit='pm', format='.2u')
print "Plancksches Wirkungsquantum:"
papstats.print_rdiff(h_planck(y=y_G, U_B=30*const.kilo), h_erw)
# 2. Ordnung
print "2. Ordung ab:", papstats.pformat(unp.arcsin(y_G/d)/2/const.pi*360, label='b', unit='°', format='.2u')

# Plot
plt.clf()
plt.title(u'Diagramm 3.1: Bremsspektrum von LiF mit Untergrund und Extrapolation am kurzwelligen Ende')
axmain = plt.subplot(111)
plt.xlabel(ur'Bestrahlungswinkel $\beta \, [^\circ]$')
plt.ylabel(ur'Zählrate $n \, [\frac{Ereignisse}{s}]$')
xlim = [b[0], b[-1]]
xspace = np.linspace(*xlim, num=1000)
axmain.set_xlim(*xlim)
papstats.plot_data(b, n, label='Messpunkte')
plt.fill_between(unp.nominal_values(b), 0, unp.nominal_values(n), color='g', alpha=0.2)

from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

zoomxlim = [3, 7]
zoomylim = [0, 200]
zoomxspace = np.linspace(*zoomxlim, num=100)
axzoom = zoomed_inset_axes(axmain, 2.5, loc=1)
axzoom.set_xlim(*zoomxlim)
axzoom.set_ylim(*zoomylim)
mark_inset(axmain, axzoom, loc1=4, loc2=2, fc="none", ec="0.5")
papstats.plot_data(b, n)
plt.fill_between(unp.nominal_values(b), 0, unp.nominal_values(n), color='g', alpha=0.2)
papstats.plot_fit(fit_U, popt_U, xspace=zoomxspace, eq=ur'n=n_U, \, \beta \in ['+str(b[sl_U][0])+','+str(b[sl_U][-1])+ur']^\circ', punits=['s^{-1}'], lw=2)
Esempio n. 8
0
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')
Esempio n. 9
0
# Kombiniertes Spektrum
#####

data = np.array(
    [np.loadtxt('data/' + e[0] + '.txt', skiprows=1) for e in elements],
    dtype=object)
data[:, :, 1] = unp.uarray(data[:, :, 1], data[:, :, 1] / np.sqrt(180))

plt.clf()
plt.title(u'Diagramm 3.1: Röntgenfluoreszenzspektrum verschiedener Elemente')
plt.xlabel('Strahlungsenergie $E \, [keV]$')
plt.ylabel(u'Zählrate ' + r'$n \, [\frac{Ereignisse}{s}]$')
for i in range(data.shape[0]):
    p = papstats.plot_data(data[i, :, 0],
                           data[i, :, 1],
                           label=elements[i][0] + ' (' + str(elements[i][1]) +
                           ')',
                           elinewidth=0.5,
                           capsize=4)
    plt.fill_between(data[i, :, 0],
                     0,
                     unp.nominal_values(data[i, :, 1]),
                     color=p[0].get_color(),
                     alpha=0.1)
#plt.xlim(np.min(data[:,:,0]), np.max(data[:,:,0]))
#plt.ylim(np.min(unp.nominal_values(data[:,:,1])), np.max(unp.nominal_values(data[:,:,1])))
plt.xlim(0, 26)
plt.legend()
papstats.savefig_a4('3.1.png')

#####
# Spektrallinien
Esempio n. 10
0

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}'])
Esempio n. 11
0
                   converters=dict.fromkeys([1], unc.ufloat_fromstr),
                   dtype=object,
                   unpack=True)
f, dt = np.array(f, dtype=float) * const.kilo, dt * const.micro
phi = 360 * dt * f

plt.clf()
plt.title(u'Diagramm 3.1: Phasengang eines RC-Glieds')
plt.xlabel('Wechselstromfrequenz der Eingangsspannung $f \, [kHz]$')
plt.ylabel(ur'Phasenverschiebung der Ausgangsspannung $\Phi \, [^\circ]$')
plt.xscale('log')
xspace = np.logspace(0.2, 1) * const.kilo
yspace = np.linspace(0, 90)
plt.ylim(yspace[0], yspace[-1])
plt.xlim(xspace[0] / const.kilo, xspace[-1] / const.kilo)
papstats.plot_data(f / const.kilo, phi, label='Messpunkte')
extrapolater = ip.UnivariateSpline(unp.nominal_values(f),
                                   unp.nominal_values(phi),
                                   k=3)
plt.plot(xspace / const.kilo,
         extrapolater(xspace),
         label='Extrapolation',
         color='b')
plt.axhline(45, color='black', label='$\Phi = 45^\circ$')
plt.axvline(f_G_theo.n / const.kilo,
            label='Theoretische Grenzfrequenz $f_G^{theo}$\nmit Fehlerbereich',
            color='g')
plt.fill_betweenx(yspace, (f_G_theo.n - f_G_theo.s) / const.kilo,
                  (f_G_theo.n + f_G_theo.s) / const.kilo,
                  color='g',
                  alpha=0.2)
Esempio n. 12
0
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
Esempio n. 13
0
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')

print d_list
d = np.mean(d_list)
print papstats.pformat(d, label='d', unit='Torr^(-1)', format='c')
Esempio n. 14
0
File: n.py Progetto: knly/PAP2
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')
papstats.savefig_a4('3.1.png')

# Vergleich mit Erwartungswerten

V = Uind/Uind_true

sigma_upper = unp.nominal_values(V+unp.std_devs(V)*3)
sigma_lower = unp.nominal_values(V-unp.std_devs(V)*3)

plt.clf()
plt.title(u'Diagramm 3.1.b: Verhältnis aus gemessener und erwarteter Induktionsspannung mit $3 \sigma$-Bereich')
plt.xlabel('Kreisfrequenz $\omega \, [Hz]$')
Esempio n. 15
0
File: n.py Progetto: knly/PAP2
        np.savetxt('data/'+filenames[i]+'.txt', data[:,2*i:2*i+2], delimiter='\t', header='E [eV]\tn [1/s]')


#####
# Kombiniertes Spektrum
#####

data = np.array([np.loadtxt('data/'+e[0]+'.txt', skiprows=1) for e in elements], dtype=object)
data[:,:,1] = unp.uarray(data[:,:,1], data[:,:,1]/np.sqrt(180))

plt.clf()
plt.title(u'Diagramm 3.1: Röntgenfluoreszenzspektrum verschiedener Elemente')
plt.xlabel('Strahlungsenergie $E \, [keV]$')
plt.ylabel(u'Zählrate '+r'$n \, [\frac{Ereignisse}{s}]$')
for i in range(data.shape[0]):
    p = papstats.plot_data(data[i,:,0], data[i,:,1], label=elements[i][0]+' ('+str(elements[i][1])+')', elinewidth=0.5, capsize=4)
    plt.fill_between(data[i,:,0], 0, unp.nominal_values(data[i,:,1]), color=p[0].get_color(), alpha=0.1)
#plt.xlim(np.min(data[:,:,0]), np.max(data[:,:,0]))
#plt.ylim(np.min(unp.nominal_values(data[:,:,1])), np.max(unp.nominal_values(data[:,:,1])))
plt.xlim(0, 26)
plt.legend()
papstats.savefig_a4('3.1.png')


#####
# Spektrallinien
#####

Z = np.array([e[1] for e in elements])

converters = dict.fromkeys(range(1, 4), unc.ufloat_fromstr)
Esempio n. 16
0
File: n.py Progetto: knly/PAP2
# Berechnung der Maximalenergie
RbES = 0.13*const.gram/const.centi**2
rAl = 2.7*const.gram/const.centi**3
Rb = RbES + xM * rAl
print "Flächendichte:", papstats.pformat(Rb/(const.gram/const.centi**2), label='R^b', unit='g/cm^2', format='.2u')
print "Maximalenergie:"
EM = unc.ufloat(2.25,0.1) # Aus Diagramm in Versuchsanleitung abgelesen
papstats.print_rdiff(EM,unc.ufloat(2.274,0))

# Plot
plt.clf()
plt.title(u'Diagramm 3.1: '+r'$\beta$'+u'-Strahlung in Abhängigkeit der Absorberdicke mit Extrapolation')
plt.yscale('log', nonposy='clip')
plt.xlabel('Absorberdicke $x \, [mm]$')
plt.ylabel(u'korrigierte Zählrate '+r'$(n-n_U^{\beta}) \, [\frac{Ereignisse}{s}]$')
papstats.plot_data(x/const.milli, n, label='Messpunkte')
sl_upper = 10
sl = (n > 0) & (n <= sl_upper)
k = 5
xspace = np.linspace(x[sl][0].n, 0.004, num=1000)
extrapolater = ip.UnivariateSpline(unp.nominal_values(x[sl]), np.log(unp.nominal_values(n[sl])), k=k)
plt.plot(xspace/const.milli, np.exp(extrapolater(xspace)), color='r', label='Extrapolation mit Polynom der Ordnung $k='+str(k)+'$ mit $n \in (0,'+str(sl_upper)+']$')
plt.fill_betweenx(np.linspace(1e-3,1e2), x1/const.milli, x2/const.milli, color='g', alpha=0.2)
plt.xlim(0, xspace[-1]/const.milli)
plt.ylim(1e-3,1e2)
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(u'Abschätzung der Maximalreichweite:\n$'+papstats.pformat(xM/const.milli, label='x_M', unit='mm')+'$')
plt.legend(handles, labels, loc='lower left')
papstats.savefig_a4('3.1.png')
Esempio n. 17
0

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')

# Maxima nach Fit
n_maxima_fit = x[0::2] / popt[0]
diff = np.abs(n[0::2] - n_maxima_fit)
print papstats.table(labels=['n_erw', 'n', u'|n-n_erw|', u'σ-Bereich'],
Esempio n. 18
0
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')
papstats.savefig_a4('3.1.png')

# Vergleich mit Erwartungswerten
Esempio n. 19
0
#####
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')


#####
print u"# 3.3: Präzession"
Esempio n. 20
0
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
Esempio n. 21
0
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')
plt.legend(loc='upper left')
papstats.savefig_a4('1.png')

V = v / v_lam
Re = rho_F * v * 2. * r / eta

plt.clf()
plt.title(u'Diagramm 3.2: Abschätzung der kritischen Reynoldszahl')
plt.xscale('log')
Esempio n. 22
0
                                         label='R^b',
                                         unit='g/cm^2',
                                         format='.2u')
print "Maximalenergie:"
EM = unc.ufloat(2.25, 0.1)  # Aus Diagramm in Versuchsanleitung abgelesen
papstats.print_rdiff(EM, unc.ufloat(2.274, 0))

# Plot
plt.clf()
plt.title(u'Diagramm 3.1: ' + r'$\beta$' +
          u'-Strahlung in Abhängigkeit der Absorberdicke mit Extrapolation')
plt.yscale('log', nonposy='clip')
plt.xlabel('Absorberdicke $x \, [mm]$')
plt.ylabel(u'korrigierte Zählrate ' +
           r'$(n-n_U^{\beta}) \, [\frac{Ereignisse}{s}]$')
papstats.plot_data(x / const.milli, n, label='Messpunkte')
sl_upper = 10
sl = (n > 0) & (n <= sl_upper)
k = 5
xspace = np.linspace(x[sl][0].n, 0.004, num=1000)
extrapolater = ip.UnivariateSpline(unp.nominal_values(x[sl]),
                                   np.log(unp.nominal_values(n[sl])),
                                   k=k)
plt.plot(xspace / const.milli,
         np.exp(extrapolater(xspace)),
         color='r',
         label='Extrapolation mit Polynom der Ordnung $k=' + str(k) +
         '$ mit $n \in (0,' + str(sl_upper) + ']$')
plt.fill_betweenx(np.linspace(1e-3, 1e2),
                  x1 / const.milli,
                  x2 / const.milli,
Esempio n. 23
0
File: n.py Progetto: knly/PAP2
# Phasengang

f, dt = np.loadtxt('3.txt', skiprows=1, converters=dict.fromkeys([1], unc.ufloat_fromstr), dtype=object, unpack=True)
f, dt = np.array(f, dtype=float)*const.kilo, dt*const.micro
phi = 360*dt*f

plt.clf()
plt.title(u'Diagramm 3.1: Phasengang eines RC-Glieds')
plt.xlabel('Wechselstromfrequenz der Eingangsspannung $f \, [kHz]$')
plt.ylabel(ur'Phasenverschiebung der Ausgangsspannung $\Phi \, [^\circ]$')
plt.xscale('log')
xspace = np.logspace(0.2,1)*const.kilo
yspace = np.linspace(0,90)
plt.ylim(yspace[0], yspace[-1])
plt.xlim(xspace[0]/const.kilo, xspace[-1]/const.kilo)
papstats.plot_data(f/const.kilo, phi, label='Messpunkte')
extrapolater = ip.UnivariateSpline(unp.nominal_values(f), unp.nominal_values(phi), k=3)
plt.plot(xspace/const.kilo, extrapolater(xspace), label='Extrapolation', color='b')
plt.axhline(45, color='black', label='$\Phi = 45^\circ$')
plt.axvline(f_G_theo.n/const.kilo, label='Theoretische Grenzfrequenz $f_G^{theo}$\nmit Fehlerbereich', color='g')
plt.fill_betweenx(yspace, (f_G_theo.n-f_G_theo.s)/const.kilo, (f_G_theo.n+f_G_theo.s)/const.kilo, color='g', alpha=0.2)
f_G_phas = unc.ufloat(3.09, 0.2)*const.kilo
plt.axvline(f_G_phas.n/const.kilo, color='r', label='Grenzfrequenz $'+papstats.pformat(f_G_phas/const.kilo, unit='kHz', label='f_G^{phas}')+'$\nnach Extrapolation mit Fehlerbereich')
plt.fill_betweenx(yspace, (f_G_phas.n-f_G_phas.s)/const.kilo, (f_G_phas.n+f_G_phas.s)/const.kilo, color='r', alpha=0.2)
plt.legend()
papstats.savefig_a4('3.1.png')


#####
print "# 4: Frequenzgang eines Serienschwingkreises"
#####
Esempio n. 24
0
                 [31140, 30857, 30474], [29626, 29808, 30999]]) * 1e-4
W_pV = unp.uarray(np.mean(W_pV, axis=1), np.std(W_pV, axis=1))
f = np.array([[304.5, 303.1, 303.4], [271.4, 270.3, 269.9],
              [233.3, 238.4, 230.5], [170.2, 185.5, 183.3]]) / const.minute
f = unp.uarray(np.mean(f, axis=1),
               np.sqrt(np.std(f, axis=1)**2 + (2 / const.minute)**2))
Q_el = unc.ufloat(13.21, 0.01) * unc.ufloat(2.9, 0.01) * 5 / f
eta_th = W_pV / Q_el
W_D = 2 * const.pi * 0.25 * F
eta_eff = W_D / Q_el

print papstats.table(
    labels=['F', 'W_pV', 'f_M', 'Q_el', 'eta_th', 'W_D', 'eta_eff'],
    units=['N', 'J', 'Hz', 'J', '%', 'J', '%'],
    columns=[F, W_pV, f, Q_el, eta_th * 100, W_D, eta_eff * 100])

# plot
plt.clf()
plt.suptitle(
    u'Diagramm 3.1: Der Heißluftmoter als Kältemaschine - Thermischer und effektiver Wirkungsgrad über der Motordrehzahl'
)
ax1 = plt.subplot(211)
papstats.plot_data(f, eta_th * 100)
plt.setp(ax1.get_xticklabels(), visible=False)
plt.ylabel(u'Thermischer Wirkungsgrad $\eta_{th} \, [\%]$')
ax2 = plt.subplot(212, sharex=ax1)
papstats.plot_data(f, eta_eff * 100)
plt.ylabel(u'Effektiver Wirkungsgrad $\eta_{eff} \, [\%]$')
plt.xlabel(u'Motordrehzahl $f \, [Hz]$')
papstats.savefig_a4('3.1.png')
Esempio n. 25
0
print papstats.pformat(Q_V, format='c', unit='J', label=u'Motorverluste Q_V')


# Drehmomentmessung

F = unp.uarray([0.2, 0.4, 0.6, 0.8], 0.02)
W_pV = np.array([[28832, 28393, 28432], [29848, 29640, 29525], [31140, 30857, 30474], [29626, 29808, 30999]]) * 1e-4
W_pV = unp.uarray(np.mean(W_pV, axis=1), np.std(W_pV, axis=1))
f = np.array([[304.5, 303.1, 303.4], [271.4, 270.3, 269.9], [233.3, 238.4, 230.5], [170.2, 185.5, 183.3]]) / const.minute
f = unp.uarray(np.mean(f, axis=1), np.sqrt(np.std(f, axis=1)**2 + (2 / const.minute)**2))
Q_el = unc.ufloat(13.21, 0.01) * unc.ufloat(2.9, 0.01) * 5 / f
eta_th = W_pV / Q_el
W_D = 2 * const.pi * 0.25 * F
eta_eff = W_D / Q_el

print papstats.table(labels=['F', 'W_pV', 'f_M', 'Q_el', 'eta_th', 'W_D', 'eta_eff'], units=['N', 'J', 'Hz', 'J', '%', 'J', '%'], columns=[F, W_pV, f, Q_el, eta_th*100, W_D, eta_eff*100])


# plot
plt.clf()
plt.suptitle(u'Diagramm 3.1: Der Heißluftmoter als Kältemaschine - Thermischer und effektiver Wirkungsgrad über der Motordrehzahl')
ax1 = plt.subplot(211)
papstats.plot_data(f, eta_th * 100)
plt.setp(ax1.get_xticklabels(), visible=False)
plt.ylabel(u'Thermischer Wirkungsgrad $\eta_{th} \, [\%]$')
ax2 = plt.subplot(212, sharex=ax1)
papstats.plot_data(f, eta_eff * 100)
plt.ylabel(u'Effektiver Wirkungsgrad $\eta_{eff} \, [\%]$')
plt.xlabel(u'Motordrehzahl $f \, [Hz]$')
papstats.savefig_a4('3.1.png')
Esempio n. 26
0
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')
Esempio n. 27
0
File: n.py Progetto: knly/PAP2
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')

#####
print('\n# 2 (Untersuchung des Plateauanstiegs)')
#####

data = np.loadtxt('3.txt', skiprows=1)
Esempio n. 28
0
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')

# Maxima nach Fit
n_maxima_fit = x[0::2] / popt[0]
diff = np.abs(n[0::2]-n_maxima_fit)
print papstats.table(labels=['n_erw', 'n', u'|n-n_erw|', u'σ-Bereich'], columns=[n[0::2], n_maxima_fit, diff, unp.nominal_values(diff)/unp.std_devs(diff)])
Esempio n. 29
0
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)

a = unp.uarray(data[:, 0], 2) / 360. * 2 * c.pi
U_ind = unp.uarray(data[:, 1], data[:, 2]) / 2
Esempio n. 30
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,