Beispiel #1
0
def plotElement(anodenstrom, spannung, V_N, R):
    spannung /= (V_N**2 * 1000**2 * 10)  # verstärkung rausrechnen
    x = anodenstrom*10**(-3)
    y = spannung/(R**2)  # I^2 bestimmt
    plt.errorbar(noms(x), noms(y),
    xerr=stds(x), yerr=stds(y), fmt='kx', label='Messwerte')

    # fitten:
    params, covariance = curve_fit(fitfunktion, unp.nominal_values(x),
                                   unp.nominal_values(y),
                                   p0=[1])
    errors = np.sqrt(np.diag(covariance))
    print('m= ', params[0], '±', errors[0])
    m = ufloat(params[0], errors[0])
    x_fit = np.linspace(-0.0001, max(noms(x))+0.001)
    plt.plot(x_fit, fitfunktion(x_fit, *params), label='Fit')

    plt.xlim(0, 0.0045)
    plt.ylim(0, 1.75e-17)
    plt.xlabel(r'$I_0 \:/\: \si{\ampere}$')
    plt.ylabel(r'$I^2 \:/\: \si{\ampere\squared}$')
    delta_nu = ufloat(24.4, 0.4)
    delta_nu *= 10**3
    e0 = m/(2*delta_nu)
    print("e0 = ", e0)
    e0theorie = ufloat(constants.physical_constants["elementary charge"][0],
                       constants.physical_constants["elementary charge"][2])
    print("Abweichung von Theorie= ", abweichungen(e0theorie, e0))
    plt.legend(loc='best')

    # in matplotlibrc leider (noch) nicht möglich
    plt.tight_layout(pad=0.2, h_pad=1.08, w_pad=1.08)
    plt.savefig('build/plotElement.pdf')
    plt.close()
Beispiel #2
0
def plotalpha(alpha_mz, mass_Z):
    mu = np.logspace(-1, 30, 10000)
    alf = alpha(alpha_mz, mass_Z, mu)
    plt.fill_between(mu,
                     noms(alf) + stds(alf),
                     noms(alf) - stds(alf),
                     color='red',
                     label='1$\sigma$-Intervall')

    plt.plot(mu, noms(alf), label='Kurve')

    d = np.zeros(len(alf))
    d = noms(alf) - 1 / 128
    print(d)
    for i in range(len(d) - 1):
        if d[i] == 0. or d[i] * d[i + 1] < 0.:  # crossover at i
            print('Grafische Lösung:', alf[i])

    plt.xlim(0.1, 1000)
    plt.xlabel(r'$\mu \:/\: \si{\giga\electronvolt}$')
    plt.ylabel(r'$\alpha_S$')
    plt.legend(loc='best')

    plt.xscale('log')

    # in matplotlibrc leider (noch) nicht möglich
    plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
    plt.savefig('build/plotalpha.pdf')
    plt.close()
Beispiel #3
0
def Plot(x=[], y=[], limx=None, limy=None, xname='', yname='', name='', markername='Wertepaare', marker='rx', linear=True, linecolor='b-', linename='Ausgleichsgerade', xscale=1, yscale=1, save=True, Plot=True):
	uParams = None
	if(Plot):
		dx = abs(x[-1]-x[0])
		if(limx==None):
			xplot = np.linspace((x[0]-0.05*dx)*xscale,(x[-1]+0.05*dx)*xscale,1000)
		else:
			xplot = np.linspace(limx[0]*xscale,limx[1]*xscale,1000)
		if(save):
			plt.cla()
			plt.clf()
		plt.errorbar(noms(x)*xscale, noms(y)*yscale, xerr=stds(x)*xscale, yerr=stds(y)*yscale, fmt=marker, markersize=6, elinewidth=0.5, capsize=2, capthick=0.5, ecolor='g',barsabove=True ,label=markername)
	if(linear == True):
		params, covar = curve_fit(Line, noms(x), noms(y))
		uParams=uncertainties.correlated_values(params, covar)
		if(Plot):
			plt.plot(xplot*xscale, Line(xplot, *params)*yscale, linecolor, label=linename)
	if(Plot):
		if(limx==None):
			plt.xlim((x[0]-0.05*dx)*xscale,(x[-1]+0.05*dx)*xscale)
		else:
			plt.xlim(limx[0]*xscale,limx[1]*xscale)
		if(limy != None):
			plt.ylim(limy[0]*yscale,limy[1]*yscale)
		plt.xlabel(xname)
		plt.ylabel(yname)
		plt.legend(loc='best')
		plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
		if(save):
			plt.savefig('build/'+name+'.pdf')
	if(linear):
		return(uParams)
Beispiel #4
0
def make_table(columns, figures=None):
    assert hasattr(columns[0],'__iter__'), "Wenn nur eine Zeile von Daten vorliegt, funktioniert zip nicht mehr; die Elemente von columns müssen Listen sein, auch wenn sie ihrerseits nur ein Element enthalten."

    if figures is None:
        figures = [None] * len(columns)

    cols = []
    for column, figure in zip(columns, figures):
        assert (type(column) != str), "Hier ist ein einzelner String übergeben worden. Baue daraus eine Liste und alles ist gut ( column = [string] )."
        if (type(column) == list):
            col = zip(*zip(column))     # hard to find this kind of code... this will unzip the list column, ref: https://docs.python.org/3/library/functions.html#zip
            cols.extend(col)
        elif np.any(stds(column)):
            if figure is None:
                figure = ''
            col = list(zip(*['{0:.{1:}uf}'.format(x, figure).split('+/-') for x in column]))
        else:
            col = list(zip(*[['{0:.{1:}f}'.format(x, figure)] for x in noms(column)]))
        cols.extend(col)

    max_lens = [max(len(s) for s in col) for col in cols]
    cols = [['{0:<{1:}}'.format(s, ml) for s in col] for col, ml in zip(cols, max_lens)]

    rows = list(itertools.zip_longest(*cols))

    return (r' \\' + '\n').join([' & '.join(s for s in row if s is not None) for row in rows]) + r' \\'
def write_table(columns, filename, figures=None, row_names=None, column_names=None, dont_align=False):
    """Generates just the table contents and writes it to the given file."""
    assert hasattr(columns[0], '__iter__'), "Wenn nur eine Zeile von Daten vorliegt, funktioniert zip nicht mehr; die Elemente von columns müssen Listen sein, auch wenn sie ihrerseits nur ein Element enthalten."

    if figures is None:
        figures = [None] * len(columns)

    if dont_align:
        number_format = '\\num{{{0:.{1:}g}}}'
    else:
        number_format = '{0:.{1:}g}'

    cols = []
    for column, figure in zip(columns, figures):
        if np.any(stds(column)):
            if figure is None:
                figure = ''
            col = list(zip(*['{0:.{1:}uf}'.format(x, figure).split('+/-') for x in column]))
        else:
            col = list(zip(*[[number_format.format(x, figure)] for x in noms(column)]))
        cols.extend(col)

    max_lens = [max(len(s) for s in col) for col in cols]
    cols = [['{0:<{1:}}'.format(s, ml) for s in col] for col, ml in zip(cols, max_lens)]

    rows = list(itertools.zip_longest(*cols))

    if row_names is not None:
        for i in range(len(rows)):
            rows[i] = [row_names[i]] + list(rows[i])
    if column_names is not None:
        rows = [column_names] + list(rows)  # ["$\text{{{0}}}".format(i) for i in column_names]

    filecontent = (r' \\' + '\n').join([' & '.join(s for s in row if s is not None) for row in rows]) + r' \\'
    write(filename, filecontent)
def make_table(columns, figures=None):
    assert hasattr(
        columns[0], '__iter__'
    ), "Wenn nur eine Zeile von Daten vorliegt, funktioniert zip nicht mehr; die Elemente von columns müssen Listen sein, auch wenn sie ihrerseits nur ein Element enthalten."

    if figures is None:
        figures = [None] * len(columns)

    cols = []
    for column, figure in zip(columns, figures):
        if np.any(stds(column)):
            if figure is None:
                figure = ''
            col = list(
                zip(*[
                    '{0:.{1:}uf}'.format(x, figure).split('+/-')
                    for x in column
                ]))
        else:
            col = list(
                zip(*[['{0:.{1:}f}'.format(x, figure)] for x in noms(column)]))
        cols.extend(col)

    max_lens = [max(len(s) for s in col) for col in cols]
    cols = [['{0:<{1:}}'.format(s, ml) for s in col]
            for col, ml in zip(cols, max_lens)]

    rows = list(itertools.zip_longest(*cols))

    return (r' \\' + '\n').join(
        [' & '.join(s for s in row if s is not None) for row in rows]) + r' \\'
Beispiel #7
0
def transform2latex_tab_2(data, dir, dataname):
    if not os.path.exists(dir):
        os.makedirs(dir)
    size = len(data)
    save_data = open((dir + 'latex_' + dataname), 'w')
    print('\nSaving data to "%s"' % (dir + dataname))
    for i in range(0, size):
        array_len = len(data[i])
        for j in range(0, array_len):
            if (j == array_len - 1):
                save_data.write("\\num{" + str(noms(data[i][j])) + " \\pm " +
                                str(stds(data[i][j])) + "}\t \\\\ \n")
            else:
                save_data.write("\\num{" + str(noms(data[i][j])) + " \\pm " +
                                str(stds(data[i][j])) + "}\t	&	\t")
    save_data.close()
Beispiel #8
0
def make_SI(num, unit, exp='', figures=None):
    if np.any(stds([num])):
        if figures is None:
            figures = ''
        x = '{0:.{1:}uf}'.format(num, figures).replace('/', '')
    else:
        x = '{0:.{1:}f}'.format(num, figures)

    return r'\SI{{{}{}}}{{{}}}'.format(x, exp, unit)
def getOutValues(pFighterStrings, pEnemieStrings, pAttStats, pDefStats):
    vOutputString = 'Kampfstats fuer ' + pFighterStrings[
        0] + ' gegen ' + pEnemieStrings[0] + ':'

    for u in range(0, len(pAttStats[0])):
        vOutLine = '\n' + pEnemieStrings[0] + ' ' + pEnemieStrings[u +
                                                                   1] + ':\t\t'

        for i in range(0, len(pAttStats)):
            vAT = ufloat(np.round(noms(pAttStats[i][u]), 1),
                         np.round(stds(pAttStats[i][u]), 1))
            vPA = ufloat(np.round(noms(pDefStats[i][u]), 1),
                         np.round(stds(pDefStats[i][u]), 1))

            vOutLine += 'AT {}, PA {};\t'.format(vAT, vPA)

        vOutputString += vOutLine

    return vOutputString
Beispiel #10
0
def tabelle_fertig(r, winkel, hkl, a_m_hkl, name):
    hkl_sum = hkl[:, 0]**2 + hkl[:, 1]**2 + hkl[:, 2]**2
    rundung = np.array([1, 2, 0, 0, 0, 0, 2, 2, 3])
    hkl_table = np.array([
        r * 100, winkel, hkl[:, 0], hkl[:, 1], hkl[:, 2], hkl_sum,
        noms(a_m_hkl) * 10**(10),
        stds(a_m_hkl) * 10**(10),
        np.cos(inrad(winkel))**2
    ])
    tabelle(hkl_table, name + "_table", rundung)
def make_SI(num, unit, exp='', figures=None):
    ''' Format an uncertainties ufloat as a \SI quantity '''
    if np.any(stds([num])):
        if figures is None:
            figures = ''
        x = '{0:.{1:}uf}'.format(num, figures).replace('/', '')
    else:
        x = '{0:.{1:}f}'.format(num, figures)

    return r'\SI{{{}{}}}{{{}}}'.format(x, exp, unit)
Beispiel #12
0
def make_SI(num, unit, exp='', figures=None):
    ''' Format an uncertainties ufloat as a \SI quantity '''
    if np.any(stds([num])):
        if figures is None:
            figures = ''
        x = '{0:.{1:}uf}'.format(num, figures).replace('/', '')
    else:
        x = '{0:.{1:}f}'.format(num, figures)

    return r'\SI{{{}{}}}{{{}}}'.format(x, exp, unit)
Beispiel #13
0
def make_SI(num, unit, exp='', figures=None):
    y = ufloat(0.0, 0) #siunitx mag kein 0 +- 0, deshalb hier der workaround
    if num == y:
        return "(0 \pm 0) ~ \si{" + unit + "}"
    if np.any(stds([num])):
        if figures is None:
            figures = ''
        x = '{0:.{1:}uf}'.format(num, figures).replace('/', '')
    else:
        x = '{0:.{1:}f}'.format(num, figures)

    return r'\SI{{{}{}}}{{{}}}'.format(x, exp, unit)
Beispiel #14
0
def make_SI(num, unit, exp='', figures=None):
    y = ufloat(0.0, 0)  #siunitx mag kein 0 +- 0, deshalb hier der workaround
    if num == y:
        return "(0 \pm 0) ~ \si{" + unit + "}"
    if np.any(stds([num])):
        if figures is None:
            figures = ''
        x = '{0:.{1:}uf}'.format(num, figures).replace('/', '')
    else:
        x = '{0:.{1:}f}'.format(num, figures)

    return r'\SI{{{}{}}}{{{}}}'.format(x, exp, unit)
Beispiel #15
0
def Plot(x,
         y,
         limx,
         xname,
         yname,
         params,
         name,
         linear=True,
         xscale=1,
         yscale=1,
         limy=None):
    xplot = np.linspace(limx[0] * xscale, limx[1] * xscale, 1000)
    plt.cla()
    plt.clf()
    plt.errorbar(noms(x) * xscale,
                 noms(y) * yscale,
                 xerr=stds(x) * xscale,
                 yerr=stds(y) * yscale,
                 fmt='rx',
                 markersize=6,
                 elinewidth=0.5,
                 capsize=2,
                 capthick=0.5,
                 ecolor='g',
                 barsabove=True,
                 label='Wertepaare')
    if (linear == True):
        plt.plot(xplot * xscale,
                 Line(xplot, *params) * yscale,
                 'b-',
                 label='Ausgleichsgerade')
    plt.xlim(limx[0] * xscale, limx[1] * xscale)
    if (limy != None):
        plt.ylim(limy[0] * yscale, limy[1] * yscale)
    plt.xlabel(xname)
    plt.ylabel(yname)
    plt.legend(loc='best')
    plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
    plt.savefig('build/' + name + '.pdf')
Beispiel #16
0
def make_SI(num, unit, exp='', figures=None):
    ''' Format an uncertainties ufloat as a \SI quantity '''
    if np.any(stds([num])):
        if figures is None:
            figures = ''
        x = '{0:.{1:}uf}'.format(num, figures).replace('/', '')
    else:
        x = '{0:.{1:}f}'.format(num, figures)

    return r'\SI{{{}{}}}{{{}}}'.format(x, exp, unit)


#with open('build/M_BH.tex', 'w') as f:
#  f.write(make_SI(M*1e-08,r'M_{\odot}',exp='e08' ,figures=2))
Beispiel #17
0
def printScores(pScores, pID):
    vX = np.linspace(0, 100, len(pScores[0]))

    if pID == 0:
        vTitle = 'NaiveBayes'
    elif pID == 1:
        vTitle = 'RandomForest'
    elif pID == 2:
        vTitle = 'KNN'
    else:
        vTitle = 'Default'

    plt.errorbar(vX,
                 noms(pScores[0]),
                 yerr=stds(pScores[0]),
                 color='g',
                 fmt=',',
                 label='Reinheit')
    plt.errorbar(vX,
                 noms(pScores[1]),
                 yerr=stds(pScores[1]),
                 color='b',
                 fmt=',',
                 label='Effizienz')
    plt.plot(vX, noms(pScores[0]), 'g-')
    plt.plot(vX, noms(pScores[1]), 'b-')

    plt.ylim(-0.05, 1.05)
    plt.xlabel('Konfidenzniveau in %', {'size': '16'})
    plt.ylabel('Wert', {'size': '16'})
    plt.title(vTitle)
    plt.legend(loc='best', prop={'size': 16})
    plt.tight_layout()
    plt.savefig('Bilder/' + vTitle + '.pdf')
    plt.show()
    plt.clf()
def make_SI(num, unit, exp='', figures=None):
    ''' Format an uncertainties ufloat as a \SI quantity '''
    if np.any(stds([num])):
        if figures is None:
            figures = ''
        x = '{0:.{1:}uf}'.format(num, figures).replace('/', '')
    else:
        x = '{0:.{1:}f}'.format(num , figures)

    return r'\SI{{{}{}}}{{{}}}'.format(x, exp, unit)

## tex file for P_1
#
#with open('build/P_1.tex', 'w') as f:
#  f.write(make_SI(P_1*1e+57,r'\percent', exp='1e-55', figures=1))
Beispiel #19
0
def plot(axes, x, y, V_strich_theorie, label, filename, x_label, y_label, grenze, ylim=None, logy=None, uebergang=None, letzter_wert_kacke=False):
    #label = 'test'
    flanke_grenze = grenze
    flanke_grenze_oben = None
    if letzter_wert_kacke:
        flanke_grenze_oben = -1
        axes.errorbar(noms(x[-1:]), noms(y[-1:]),
                     xerr=stds(x[-1:]), yerr=stds(y[-1:]),
                     fmt='kx', label='Unberücksichtigt bei {}'.format(label))
    if uebergang is not None:
        flanke_grenze = grenze + 1
        axes.errorbar(noms(x[uebergang:uebergang+1]), noms(y[uebergang:uebergang+1]),
                     xerr=stds(x[uebergang:uebergang+1]), yerr=stds(y[uebergang:uebergang+1]),
                     fmt='gx', label='Messwerte Übergang bei {}'.format(label))

    axes.errorbar(noms(x[flanke_grenze:flanke_grenze_oben]), noms(y[flanke_grenze:flanke_grenze_oben]),
                 xerr=stds(x[flanke_grenze:flanke_grenze_oben]), yerr=stds(y[flanke_grenze:flanke_grenze_oben]),
                 fmt='rx', label='Messwerte Flanke bei {}'.format(label))
    axes.errorbar(noms(x[:grenze]), noms(y[:grenze]),
                 xerr=stds(x[:grenze]), yerr=stds(y[:grenze]),
                 fmt='bx', label='Messwerte Plateau bei {}'.format(label))
    plateau_mittel = ufloat(np.mean(np.exp(noms(y[:grenze]))), np.std(np.exp(noms(y[:grenze]))))
    plateau_mittel_halb = unp.log(plateau_mittel / unp.sqrt(2)) if plateau_mittel.n >= 1 else unp.log(plateau_mittel * unp.sqrt(2))
    label_v_halb = r"$V_\text{Plateau}' / \sqrt{2}$" if plateau_mittel.n >= 1 else r"$V_\text{Plateau}' \cdot \sqrt{2}$"
    #label_v_halb = 'test'
    axes.plot((min(noms(x)), max(noms(x))), (noms(plateau_mittel_halb), noms(plateau_mittel_halb)), '-', label=label_v_halb)
    grenzfrequenz = fitten(axes, x[flanke_grenze:flanke_grenze_oben], y[flanke_grenze:flanke_grenze_oben], linear, [-1, 5], ['m', 'b'], 'r', 'Flanke', schnittwert=plateau_mittel_halb)
    print('grenzfrequenz = ', grenzfrequenz)
    # fitten(x[:grenze], y[:grenze], linear, [0, 0], ['m', 'b'], 'g', 'Plateau')

    print('Mittelwert Plateau = ', plateau_mittel, 'Abweichung von ', abweichungen(V_strich_theorie, plateau_mittel))


    # plotting
    axes.legend(loc='best')
    axes.set_xlim(min(noms(x)) - max(noms(x)) * 0.06, (max(noms(x))) * 1.06)
    if ylim is not None:
        axes.set_ylim(ylim[0], ylim[1])
    #x_label, y_label = 'test', 'test'
    axes.set_xlabel(x_label)
    axes.set_ylabel(y_label)
    plt.close()

    return grenzfrequenz, plateau_mittel
Beispiel #20
0
def plotPhis(pPhis):
    vX = range(1, len(pPhis) + 1)

    plt.plot(vX, noms(np.array(pPhis)), 'r-')
    plt.errorbar(vX,
                 noms(np.array(pPhis)),
                 yerr=stds(np.array(pPhis)),
                 color='k',
                 fmt='x')

    #plt.ylim(-0.05, 1.05)
    plt.xlabel('Anzahl an Bestfeatures', {'size': '16'})
    plt.ylabel('$\Phi$', {'size': '16'})
    plt.title('$\Phi$-Scores')
    plt.legend(loc='best', prop={'size': 16})
    plt.tight_layout()
    plt.savefig('Bilder/PhiScores.pdf')
    plt.show()
    plt.clf()
Beispiel #21
0
def gk_plot(name, winkel, gk, funktion, korr, fitgrenzen):
    params, errors = cf(funktion,
                        np.cos(inrad(winkel[fitgrenzen[0]:fitgrenzen[1]]))**2,
                        noms(gk[fitgrenzen[0]:fitgrenzen[1]]))
    g_plot = np.linspace(0, 1)
    plt.errorbar(np.cos(inrad(winkel))**2,
                 noms(gk) * 1e10,
                 xerr=korr(winkel),
                 yerr=stds(gk) * 1e10,
                 fmt='x',
                 label=r'Messwert')
    plt.plot(g_plot, funktion(g_plot, *params) * 1e10, label=r'Fit')
    plt.xlabel(r'$\cos^2\left(\theta\right)$')
    plt.ylabel(r'$a \:/\: \si{\angstrom}$')
    plt.legend(loc='best')
    plt.tight_layout()
    plt.savefig("build/plot_" + name + ".pdf")
    plt.close()
    return (unp.uarray(params[1], np.sqrt(np.diag(errors)[1])))
Beispiel #22
0
def make_table(columns, figures=None):
    if figures is None:
        figures = [None] * len(columns)

    cols = []
    for column, figure in zip(columns, figures):
        if np.any(stds(column)):
            if figure is None:
                figure = ''
            col = list(zip(*['{0:.{1:}uf}'.format(x, figure).split('+/-') for x in column]))
        else:
            col = list(zip(*[['{0:.{1:}f}'.format(x, figure)] for x in noms(column)]))
        cols.extend(col)

    max_lens = [max(len(s) for s in col) for col in cols]
    cols = [['{0:<{1:}}'.format(s, ml) for s in col] for col, ml in zip(cols, max_lens)]

    rows = list(itertools.zip_longest(*cols))

    return (r' \\' + '\n').join([' & '.join(s for s in row if s is not None) for row in rows]) + r' \\'
Beispiel #23
0
def plotphase(nu_1, phi_1, nu_2, phi_2, nu_3, phi_3, nu_4, phi_4):
    # nu_1, nu_2, nu_3, nu_4 = unp.log(nu_1), unp.log(nu_2), unp.log(nu_3), unp.log(nu_4)
    # phi_1, phi_2, phi_3, phi_4 = unp.abs(phi_1), unp.abs(phi_2), unp.abs(phi_3), unp.abs(phi_4)
    plt.errorbar(noms(nu_1), np.abs(noms(phi_1)),
                  xerr=stds(nu_1), yerr=stds(phi_1), label='Messwerte bei 1. Widerstandskombination')
    plt.errorbar(noms(nu_2), np.abs(noms(phi_2)),
                  xerr=stds(nu_2), yerr=stds(phi_2), label='Messwerte bei 2. Widerstandskombination')
    plt.errorbar(noms(nu_3), np.abs(noms(phi_3)),
                  xerr=stds(nu_3), yerr=stds(phi_3), label='Messwerte bei 3. Widerstandskombination')
    plt.errorbar(noms(nu_4), np.abs(noms(phi_4)),
                  xerr=stds(nu_4), yerr=stds(phi_4), label='Messwerte bei 4. Widerstandskombination')

    xlabel = r'$\nu\:/\:\si{\kilo\hertz}$'
    ylabel = r'$\phi\:/\:\si{\degree}$'
    #xlabel = 'test'
    #ylabel = 'test'
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.xscale('log')
    plt.legend(loc='best')

    plt.savefig('build/phasen.pdf')
Beispiel #24
0
def make_table(columns, figures=None):
    if figures is None:
        figures = [None] * len(columns)

    cols = []
    for column, figure in zip(columns, figures):
        if (type(column) == str):
            column = [column]
        if (type(column) == list):
            col = zip(
                *zip(column)
            )  # hard to find this kind of code... this will unzip the list column, ref: https://docs.python.org/3/library/functions.html#zip
            cols.extend(col)
        elif np.any(stds(column)):
            if figure is None:
                figure = ''
            col = list(
                zip(*[
                    '{0:.{1:}uf}'.format(x, figure).split('+/-')
                    for x in column
                ]))
        else:
            try:
                test_iterator = iter(
                    column
                )  # if only one entry is given, then this will throw a type error exception - handled below
                col = list(
                    zip(*[['{0:.{1:}f}'.format(x, figure)]
                          for x in noms(column)]))
            except TypeError:
                col = list(zip(*[['{0:.{1:}f}'.format(column, figure)]]))
        cols.extend(col)

    max_lens = [max(len(s) for s in col) for col in cols]
    cols = [['{0:<{1:}}'.format(s, ml) for s in col]
            for col, ml in zip(cols, max_lens)]

    rows = list(itertools.zip_longest(*cols))

    return (r' \\' + '\n').join(
        [' & '.join(s for s in row if s is not None) for row in rows]) + r' \\'
Beispiel #25
0
def make_table(columns, figures=None):
    assert hasattr(columns[0],'__iter__'), "Wenn nur eine Zeile von Daten vorliegt, funktioniert zip nicht mehr; die Elemente von columns müssen Listen sein, auch wenn sie ihrerseits nur ein Element enthalten."

    if figures is None:
        figures = [None] * len(columns)

    cols = []
    for column, figure in zip(columns, figures):
        if np.any(stds(column)):
            if figure is None:
                figure = ''
            col = list(zip(*['{0:.{1:}uf}'.format(x, figure).split('+/-') for x in column]))
        else:
            col = list(zip(*[['{0:.{1:}f}'.format(x, figure)] for x in noms(column)]))
        cols.extend(col)

    max_lens = [max(len(s) for s in col) for col in cols]
    cols = [['{0:<{1:}}'.format(s, ml) for s in col] for col, ml in zip(cols, max_lens)]

    rows = list(itertools.zip_longest(*cols))

    return (r' \\' + '\n').join([' & '.join(s for s in row if s is not None) for row in rows]) + r' \\'
Beispiel #26
0
gr = unp.uarray  #Geschw. rückwärts
for v in V:
    v *= 1.25e-4  #Zählwerkverzögerung
    gv = np.append(gv, np.mean(v))
gv = gv[1:]
gv = s / gv

for r in R:
    r *= 1.25e-4  #Zählwerkverzögerung
    gr = np.append(gr, np.mean(r))
gr = gr[1:]
gr = s / gr
x = np.linspace(1, 10, num=10)
np.savetxt('GangGeschwVorRueck4Tab.txt',
           np.column_stack([x, noms(gv),
                            stds(gv), -noms(gr),
                            stds(gr)]),
           delimiter=' & ',
           newline=r' \\'
           '\n ')
np.savetxt('GeschwVorRueck.txt',
           np.column_stack([noms(gv), stds(gv), -noms(gr),
                            stds(gr)]))
#
# x= np.linspace(1,10,num=10)
# np.savetxt('GeschwMittelproGang.txt',y,header='#inMeterproSekund')
#
# Plot der Geschw. im arith. Mittel
# plt.plot(x , y,'rx', label='arith. Mittel der gemessenen Geschwindigkeiten')
# plt.xlabel(r'$ Gäng\;der\; Versuchsapparatur$')
# plt.ylabel(r'$ v\:/\:ms^{-1}$')
Beispiel #27
0
v_9_auf, v_9_ab = np.genfromtxt('messdaten/9_Tropfen.txt', unpack=True)
v_9_auf_mittel = ufloat(np.mean(v_9_auf), np.std(v_9_auf))  # s/mm
v_9_ab_mittel = ufloat(np.mean(v_9_ab), np.std(v_9_ab))     # s/mm
v_9_0 = 112 # s/mm
U_9 = 184

v_10_auf, v_10_ab = np.genfromtxt('messdaten/10_Tropfen.txt', unpack=True)
v_10_auf_mittel = ufloat(np.mean(v_10_auf), np.std(v_10_auf))  # s/mm
v_10_ab_mittel = ufloat(np.mean(v_10_ab), np.std(v_10_ab))     # s/mm
v_10_0 = 59.4 # s/mm
U_10 = 286

v_auf_mittel_nom=[ noms(v_2_auf_mittel), noms(v_3_auf_mittel), noms(v_4_auf_mittel), noms(v_5_auf_mittel), noms(v_6_auf_mittel), noms(v_7_auf_mittel), noms(v_8_auf_mittel), noms(v_9_auf_mittel), noms(v_10_auf_mittel)]

v_auf_mittel_stds=[ stds(v_2_auf_mittel), stds(v_3_auf_mittel), stds(v_4_auf_mittel), stds(v_5_auf_mittel), stds(v_6_auf_mittel), stds(v_7_auf_mittel), stds(v_8_auf_mittel), stds(v_9_auf_mittel), stds(v_10_auf_mittel)]

v_ab_mittel_nom=[ noms(v_2_ab_mittel), noms(v_3_ab_mittel), noms(v_4_ab_mittel), noms(v_5_ab_mittel), noms(v_6_ab_mittel), noms(v_7_ab_mittel), noms(v_8_ab_mittel), noms(v_9_ab_mittel), noms(v_10_ab_mittel)]

v_ab_mittel_stds=[ stds(v_2_ab_mittel), stds(v_3_ab_mittel), stds(v_4_ab_mittel), stds(v_5_ab_mittel), stds(v_6_ab_mittel), stds(v_7_ab_mittel), stds(v_8_ab_mittel), stds(v_9_ab_mittel), stds(v_10_ab_mittel)]

# v_0 = array(1/v_2_0, 1/v_3_0, 1/v_4_0, 1/v_5_0, 1/v_6_0, 1/v_7_0, 1/v_8_0, 1/v_9_0, 1/v_10_0)
v_0 = np.genfromtxt('messdaten/V_0.txt', unpack=True)
v_0 = 1/v_0
U = np.genfromtxt('messdaten/Spannung.txt', unpack=True)
v_auf = unp.uarray(v_auf_mittel_nom, v_auf_mittel_stds)
v_auf = 1/v_auf
v_ab  = unp.uarray(v_ab_mittel_nom, v_ab_mittel_stds)
v_ab = 1/v_ab
write('build/Tabelle_Geschwindigkeiten.tex', make_table([v_auf, v_auf ,v_0, U],[1, 1, 3, 0]))     # Jeder fehlerbehaftete Wert bekommt zwei Spalten
write('build/Tabelle_Geschwindigkeiten_texformat.tex', make_full_table(
            bbox_inches='tight',
            pad_inches=0)

#Bestimmung der Debye-Temperatur

C_p = C_p(U[:-1], I[:-1], Q_(np.diff(t), 'second'),
          Q_(np.diff(T_prob), 'kelvin'))
alpha = Q_(model_alpha(noms(T_mean[:-1])), '1 / kelvin')

C_v = C_v(C_p[:-1], alpha, T_mean[:-1]).to('joule / kelvin / mol')

rcParams['figure.figsize'] = 5.906, 6.2
fig, ax = plt.subplots(1, 1)
ax.errorbar(x=noms(T_mean[:-1]),
            y=noms(C_v),
            xerr=stds(T_mean[:-1]),
            yerr=stds(C_v),
            fmt='.',
            label='Daten',
            linestyle=None)
ax.errorbar(x=noms(T_mean[1]),
            y=noms(C_v)[1],
            xerr=stds(T_mean[1]),
            yerr=stds(C_v)[1],
            fmt='.',
            label='Ausreißer',
            linestyle=None,
            color='r')


def c_v_debye(T, T_D):
def wellenlaenge(d_array, mitte, L):
    d_links = unp.uarray(np.zeros(mitte), np.zeros(mitte))
    d_rechts = unp.uarray(np.zeros(12-mitte), np.zeros(12-mitte))
    for i in range(0, mitte, 1):
        d_links[i] = np.sum(d_array[mitte-(i+1):mitte])
    for i in range(0, 12-mitte, 1):
        d_rechts[i] = np.sum(d_array[mitte:mitte+(i+1)])
    g = (10**-3)/80
    print('g = ', g*10**6, 'micro meter')
    d_links = d_links*10**-2
    d_rechts = d_rechts*10**-2
    d_all = np.concatenate((noms(d_links), noms(d_rechts)))
    n_links = np.linspace(1, 6, 6)
    lamda_links = g * unp.sin(unp.arctan(d_links/L))/n_links
    n_rechts = range(1, len(d_rechts)+1, 1)
    n_all = np.concatenate((n_links, n_rechts))
    lamda_rechts = g * unp.sin(unp.arctan(d_rechts/L))/n_rechts
    lamda_all = np.concatenate((lamda_links, lamda_rechts))
    werteZuTabelle(d_all*100, n_all.astype(int), (noms(lamda_all)*10**9).astype(int), (stds(lamda_all)*10**9).astype(int), rundungen=[3, 0, 0, 0])
    print('lambda = ', (np.sum(lamda_all))/12)
    print('Abweichung = ', abweichungen(632.8*10**-9, (np.sum(lamda_all))/12))
    print('Mittelwert = ', np.mean(noms(lamda_all)), '±', np.std(noms(lamda_all)))
Beispiel #30
0
# fitten
params_1 = ucurve_fit(reg.reg_quadratic, t, T1)      # quadratischer Fit
a_1, b_1, c_1 = params_1
write('build/Fit1-a.tex', make_SI(a_1 * 1e6, r'\kelvin\per\square\second', 'e-6', figures=1))
write('build/Fit1-b.tex', make_SI(b_1 * 1e3, r'\kelvin\per\second', 'e-3', figures=1))
write('build/Fit1-c.tex', make_SI(c_1,       r'\kelvin', figures=1))
params_2 = ucurve_fit(reg.reg_quadratic, t, T2)      # quadratischer Fit
a_2, b_2, c_2 = params_2
write('build/Fit2-a.tex', make_SI(a_2 * 1e6, r'\kelvin\per\square\second', 'e-6', figures=1))
write('build/Fit2-b.tex', make_SI(b_2 * 1e3, r'\kelvin\per\second', 'e-3', figures=1))
write('build/Fit2-c.tex', make_SI(c_2,       r'\kelvin', figures=1))

# Plot Temperaturverlauf mit der Zeit
plt.clf()
plt.errorbar(t, noms(T1_unc),yerr=stds(T1_unc), fmt='r.', label=r'$Messdaten T_1$')
plt.errorbar(t, noms(T2_unc),yerr=stds(T2_unc), fmt='b.', label=r'$Messdaten T_2$')
x_plot = np.linspace(0, 31*60, 1000)
plt.plot(x_plot, reg.reg_quadratic(x_plot, *noms(params_1)), 'r-', label=r'Fit $T_1$', linewidth=1)
plt.plot(x_plot, reg.reg_quadratic(x_plot, *noms(params_2)), 'b-', label=r'Fit $T_2$', linewidth=1)
plt.xlabel(r'$t \:/\: \si{\second}$')
plt.ylabel(r'$T \:/\: \si{\kelvin}$')
plt.legend(loc='best')
plt.xlim(0, 31*60)
plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
plt.savefig('build/Temperaturverlauf.pdf')

## Differentialquotienten
# wähle 8, 16, 24, 32 Minuten

parameter1 = params_1
Beispiel #31
0
plt.legend(loc='best')
plt.savefig('build/Energiespektrum.pdf')

#Würfel 1, Bestimmung von I_0
I0_gerade = unp.uarray(50636, 254) / 300
print('I0_gerade', I0_gerade)
I0_schraeg1 = unp.uarray(16660, 146) / 100
I0_schraeg2 = unp.uarray(16417, 145) / 100
#I0_schraeg = np.mean([I0_schraeg1,I0_schraeg2])
I0_schraeg = avg_and_sem([noms(I0_schraeg1), noms(I0_schraeg2)])
I0_schraeg = unp.uarray(I0_schraeg[0], I0_schraeg[1])
print('I0_schraeg', I0_schraeg)

makeTable([
    noms([I0_gerade * 300, I0_schraeg1 * 100, I0_schraeg2 * 100]),
    stds([I0_gerade * 300, I0_schraeg1 * 100, I0_schraeg2 * 100]),
    [300, 100, 100],
    noms([I0_gerade, I0_schraeg1, I0_schraeg2]),
    stds([I0_gerade, I0_schraeg1, I0_schraeg2])
], r'\multicolumn{2}{c}{' + r'$N_0$' + r'} & {' +
          r'$\Delta t_0/\si{\second}$' + r'} & \multicolumn{2}{c}{' +
          r'$I_0/\si{\becquerel}$' + r'}', 'tabReferenzmessung', [
              'S[table-format=5.0]', '@{${}\pm{}$}S[table-format=3.0]',
              'S[table-format=3.0]', 'S[table-format=3.1]',
              '@{${}\pm{}$}S[table-format=1.1]'
          ], ["%5.0f", "%3.0f", "%3.0f", "%3.1f", "%1.1f"])

#Würfel 2
I2_gerade = unp.uarray(8054, 103) / 300
I2_schraeg1 = unp.uarray(4864, 81) / 300
I2_schraeg2 = unp.uarray(8707, 106) / 300
Beispiel #32
0
T_VI.addColumn(g_VI_err, title="Gegenstandsweite",
               symbol="g'", unit="\centi\meter")
T_VI.addColumn(b_VI_err, title="Bildweite",
               symbol="b'", unit="\centi\meter")
T_VI.addColumn(V_err, title="Abbildungsmaßstab",
               symbol="V")
#T_VI.show()
#T_VI.save("Tabellen/Messwerte_VI.tex")





#Regression der Messwerte
popt_VI_g, pcov_VI_g = curve_fit(gerade, abbeX_g(noms(V_err)), noms(g_VI_err),
                                 sigma=stds(g_VI_err))
error_VI_g = np.sqrt(np.diag(pcov_VI_g))
param_VI_g_M = ufloat(popt_VI_g[0], error_VI_g[0])
param_VI_g_B = ufloat(popt_VI_g[1], error_VI_g[1])
print("Regressionsparameter g(V):\n", param_VI_g_M, param_VI_g_B)


def geradeF(x, b):
    return noms(param_VI_g_M) * x + b

popt_VI_b, pcov_VI_b = curve_fit(gerade, abbeX_b(noms(V_err)), noms(b_VI_err),
                                 sigma=stds(b_VI_err))
error_VI_b = np.sqrt(np.diag(pcov_VI_b))
param_VI_b_M = ufloat(popt_VI_b[0], error_VI_b[0])
param_VI_b_B = ufloat(popt_VI_b[1], error_VI_b[1])
print("Regressionsparameter b(V):\n",  param_VI_b_M, param_VI_b_B)
Beispiel #33
0
distance_avr_I = intercept_x
#energy_I = distanceToEnergy(distance_avr_I)
energy_I = distanceToEnergy(ufloat(distance_avr_I, 0.5))
print("Energie der Alphateilchen:", energy_I)

# Erstellen des Plots
plt.clf()
plt.xlim(-5, 20)
plt.ylim(0, 300)
plt.grid()
plt.xlabel("Effektive Länge $x\ [\mathrm{mm}]$", fontsize=14, family='serif')
plt.ylabel("Zerfallsrate $A\ [\mathrm{s^{-1}}]$", fontsize=14, family='serif')

#Messwerte für Regression
#plt.plot(x_eff[0:-7], rate_I[0:-7], "rx", label="Messwerte")
plt.errorbar(x_eff[0:-7], rate_I[0:-7], xerr=stds(x_eff_err[0:-7]) ,fmt="rx", label="Messwerte")
#Messwerte ohne Regression
plt.plot(x_eff[-7:], rate_I[-7:], "kx")
#Fit
plt.plot(X, func(X, popt[0], popt[1]), label="Regressionsgerade", color="gray")
#Halbesmaximum
plt.plot(X, len(X)*[rate_max_half_I],"r--", alpha=0.7, label="Halbe maximal Zerfallsrate")
#Schnittpunkt
plt.plot(intercept_x, rate_max_half_I, "ko", alpha=0.7,
         label="Schnittpunkt ({}|{})".format(round(intercept_x, 2),
                                             round(rate_max_half_I, 2)))

plt.tight_layout()
plt.legend(loc="best")
plt.show() if SHOW else plt.savefig("Grafiken/MittlereReichweiteI.pdf")
Beispiel #34
0
N[no_of_first_ignored_values:-no_of_last_ignored_values])   # skip first 3 and last 5 values as they dont belong to the plateau
write('build/plateaulaenge.tex', make_SI(U[-no_of_last_ignored_values] - U[no_of_first_ignored_values], r'\volt', figures = 0))
a, b = params
write('build/parameter_a.tex', make_SI(a, r'\per\second\per\volt', figures=1))
write('build/plateaumitte.tex', make_SI(reg_linear(500, *noms(params)), r'\per\second', figures=1) )   # Der Wert in der Hälfte des Plateaus als Referenz für die plateausteigung
write('build/plateausteigung.tex', make_SI(a*100*100/reg_linear(500, *noms(params)), r'\percent', figures=1))  #   %/100V lässt sich nicht mit siunitx machen -> wird in latex hart reingeschrieben
write('build/parameter_b.tex', make_SI(b, r'\per\second', figures=1))

#### Plot ####
t_plot = np.linspace(350, 650, 2)
plt.xlim(290,710)
plt.plot(t_plot, reg_linear(t_plot, *noms(params)), 'b-', label='Fit')
U[no_of_first_ignored_values:-no_of_last_ignored_values]
plt.errorbar(U[no_of_first_ignored_values:-no_of_last_ignored_values],
    noms(N[no_of_first_ignored_values:-no_of_last_ignored_values]),
    fmt='bx', yerr=stds(N[no_of_first_ignored_values:-no_of_last_ignored_values]),
    label='Messdaten auf dem Plateau')
plt.errorbar(U[0:no_of_first_ignored_values],
    noms(N[0:no_of_first_ignored_values]),
    fmt='rx', yerr=stds(N[0:no_of_first_ignored_values]),
    label='Messdaten außerhalb des Plateaus')
plt.errorbar(U[-no_of_last_ignored_values:],
    noms(N[-no_of_last_ignored_values:]),
    fmt='rx', yerr=stds(N[-no_of_last_ignored_values:]))
plt.ylabel(r'$N \:/\: \si{\per\second}$')
plt.xlabel(r'$U \:/\: \si{\volt}$')
plt.grid()
plt.legend(loc='best')
plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
plt.savefig('build/aufgabenteil_a_plot.pdf')
Beispiel #35
0
                                  std_devs as stds)
import uncertainties.unumpy as unp
from linregress import linregress

print('################################################################################a')
####################orange########################
Udata,Idata=np.genfromtxt('orange.txt',unpack=True)
U=unp.uarray(Udata,0.005)
I=unp.uarray(Idata*10**-9,0.1*10**-9)
sqI=unp.uarray(np.sqrt(noms(I*10**9)),np.sqrt(0.001))
print('farbe',sqI)

i=range(2,9)
a,aerr,b,berr=linregress(noms(U[i]),noms(sqI[i]*10**-9))
x=np.linspace(noms(U[0]),noms(U[len(U)-1]),100)
plt.errorbar(noms(U),noms(sqI),xerr=stds(U),yerr=stds(sqI),fmt='k+',label="Daten")
plt.plot(x,a*x*10**9+b*10**9,'k-',label="Fit")
plt.xlabel(r'Gegenspannung $ U\ / \ \mathrm{V}$')
plt.ylabel(r'reduzierter Photostrom $ \sqrt{I}\ / \ \mathrm{\sqrt{nA}}$')
plt.xlim(noms(U[0]),noms(U[len(U)-1]))
plt.legend(loc='best')
plt.tight_layout()
plt.grid()
plt.savefig('plotorange.pdf')
plt.close()

b=ufloat(b,berr)
a=ufloat(a,aerr)
print(a,b,'m,b')
Ugo=-b/a
print(Ugo,'Ug orange')
print("Eta, bestimmt mit der kleinen Kugel, ist in Pa*sec:")
print(etaK)
print("Mit diesem Eta ist die Apparaturkonstante in willkuerlichen Einheiten:")
print(apparatG)
print("")
print("Viskositaet in Pa*sec:")
print(etaG_2) 
print("")
print("Viskositaet in mPa*sec, vgl. Literatur:")
print(etaG_2*1000) 
print("")
print("Geschwindigkeiten in m/s:")
print((0.1/fallzeit))
print("")
print("Reynoldzahlen:")
print(Re)

np.savetxt("Auswertung/Viskositaeten.txt", np.array([noms(etaG_2),stds(etaG_2)]).T)
np.savetxt("Auswertung/Reynoldzahlen.txt", np.array([noms(Re),stds(Re)]).T)
np.savetxt("Auswertung/Geschwindigkeiten.txt", np.array([noms((0.1/fallzeit)),stds((0.1/fallzeit))]).T)
np.savetxt("Auswertung/Zeiten.txt", np.array([noms((fallzeit)),stds((fallzeit))]).T)









Beispiel #37
0
params = ucurve_fit(reg.reg_linear, B, y)         # linearer Fit
m, D = params
write('build/m.tex', make_SI(m*1e3, r'\ampere\square\meter', 'e-3', figures=1))
write('build/D.tex', make_SI(D*1e5, r'\kilogram\square\meter\per\square\second', 'e-5', figures=1))
# D = 4*(np.pi**2)*(Theta_Kugel+Theta_Aufhaengung)/(T**2)
m_th = 1/B * (4*(np.pi**2) * (Theta_Kugel+Theta_Aufhaengung) / T**2 - D_ohneB)
m_th_unc = ufloat(np.mean(noms(m_th)), MeanError(noms(m_th)))
write('build/m_th.tex', make_SI(m_th_unc*1e3, r'\ampere\square\meter', 'e-3', figures=1))
# print(m_th)

t_plot = np.linspace(np.amin(B), np.amax(B), 100)
#
plt.plot(t_plot*1e3, reg.reg_linear(t_plot, *noms(params))*1e5, 'b-', label='Methode 1')
plt.plot(t_plot*1e3, reg.reg_linear(t_plot, np.mean(noms(m_th)), np.mean(noms(D)))*1e5, 'g-', label='Methode 2')
# plt.plot(B * 1e3, noms(y)*1e5, 'rx', label='Messdaten')
plt.errorbar(B * 1e3, noms(y) * 1e5, fmt='r.', yerr=stds(y) * 1e5, label='Messdaten')
## plt.xscale('log')    # logarithmische x-Achse
plt.xlim((t_plot[0]-1/np.size(B)*(t_plot[-1]-t_plot[0]))*1e3, (t_plot[-1]+1/np.size(B)*(t_plot[-1]-t_plot[0]))*1e3)
plt.xlabel(r'$B \:/\: \SI{e-3}{\tesla}$')
plt.ylabel(r'$\frac{4\pi^2 \Theta_\text{Gesamt}}{T^2} \:/\: \SI{e-5}{\kilogram\square\meter\per\square\second}$')
plt.legend(loc='best')
plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
plt.savefig('build/zeta.pdf')

# Berechnung des Erdmagnetfeldes
B_Erde = (D_mitB-D_ohneB)/m
write('build/B_Erde.tex', make_SI(B_Erde*1e6, r'\micro\tesla', figures=1))

T_FehlerDesMittelwerts = unp.uarray(noms(T),[MeanError(noms(T_10)), MeanError(noms(T_08)), MeanError(noms(T_06)), MeanError(noms(T_04)), MeanError(noms(T_02))])
write('build/Tabelle_Magnet.tex', make_table([I,T_FehlerDesMittelwerts,B*1e3],[1,1,3]))
# FULLTABLE
Beispiel #38
0
    content = []
    error = []

    x_value.append(i)
    y_value.append(0)

    for j in range(ymin,ymax): # going thru all rows
        content.append( qMap_Ag_C0_V0.GetBinContent(i,j))
        error.append( qMap_Ag_C0_V0.GetBinError(i,j)) # Is this the real error

    content_bin = unp.uarray( content, error)
    mean_content_col = content_bin.mean() # mean value of each bin in the col

    # Saving values in lists
    mean_value_col_list.append( noms(mean_content_col))
    mean_error_col_list.append( stds(mean_content_col))


########################### Create errorbar plot #####################################

errorbar_plot_col = root.TGraphErrors( len(x_value), array( 'f', x_value), array( 'f', mean_value_col_list), array( 'f', y_value), array( 'f', mean_error_col_list) )

############################## Set axis label of errobar plot ##################################

errorbar_plot_col.GetXaxis().SetTitle("Col")
errorbar_plot_col.GetYaxis().SetTitle("Mean Hit / Vcal")

####################### create Canvas ##########################################

c1 = root.TCanvas("c1", "c1", 1980, 1080)
errorbar_plot_col.Fit('gaus')
Beispiel #39
0
    [1, 1, 1, 2, 2],
    caption=
    'Aus Abbildung \\ref{fig: messkurve_energie_hot} abgelesene Steigungen.',
    label='steigungen_hot')

#########Tabellen

##Sapnnugnsfit
liste_steigungen = [
    float(noms(parmeter_zim['Steigung'])),
    float(noms(parmeter_hot['Steigung'])),
    float(noms(parmeter_frank_hertz['Steigung'])),
    float(noms(parmeter_ioni['Steigung']))
]
liste_steigungen_fehler = [
    float(stds(parmeter_zim['Steigung'])),
    float(stds(parmeter_hot['Steigung'])),
    float(stds(parmeter_frank_hertz['Steigung'])),
    float(stds(parmeter_ioni['Steigung']))
]
liste_abschnitt = [
    float(noms(parmeter_zim['Achsenabschnitt'])),
    float(noms(parmeter_zim['Achsenabschnitt'])),
    float(noms(parmeter_frank_hertz['Achsenabschnitt'])),
    float(noms(parmeter_ioni['Achsenabschnitt']))
]
liste_abschnitt_fehler = [
    float(stds(parmeter_zim['Achsenabschnitt'])),
    float(stds(parmeter_hot['Achsenabschnitt'])),
    float(stds(parmeter_frank_hertz['Achsenabschnitt'])),
    float(stds(parmeter_ioni['Achsenabschnitt']))
Beispiel #40
0
        ba_events.append([x, s, I])
        ax.set_xlabel('Energie / keV')
        ax.set_ylabel('Ereignisse')
        fig.savefig('../build/plots/ba_gauss-'+str(maximum[0])+'.pdf')
        fig.clf()
    ba_events = np.array(ba_events)

    # efficiency-parameters
    ba_energies, ba_props = np.genfromtxt('../data/ba_spectrum_lit.txt',
            unpack=True)
    eff_coeff, eff_errs = np.genfromtxt('../build/data/efficiency-params.txt',
            unpack=True)

    xs = ba_props * eff(noms(ba_events[:, 0]), *eff_coeff)
    ys = np.abs(noms(ba_events[:, 2]))
    y_errs = stds(ba_events[:, 2])

    act_coeff, act_covar = curve_fit(activity_func, xs, ys, sigma=y_errs)
    act_errs = np.sqrt(np.diag(act_covar))

    x = np.linspace(0, 0.25)
    plt.plot(x, activity_func(x, *act_coeff), label='Fit')
    plt.errorbar(xs, ys, yerr=y_errs, fmt='+', label='Datenpunkte')
    plt.legend(loc='best')
    plt.xlabel(r'$W \cdot Q$')
    plt.ylabel('Ereignisse')
    plt.savefig('../build/plots/ba_activity.pdf')
    plt.clf()

    np.savetxt('../build/data/ba_activity-params.txt',
            np.array([act_coeff, act_errs]).T)
Beispiel #41
0
Begin der Auswertung zum Dopplereffekt

"""

# Laden der Daten zur Bestimmung der Geschwindigkeit
## Laden der Strecke
l = np.loadtxt("Messdaten/Strecke.txt", unpack=True)
l_err = np.loadtxt("Messdaten/Fehler_Strecke.txt")

### Fehler behaftete Messwerte
ul = unp.uarray(l, [l_err]*len(l))

### Mittelwert
ul_avr = Umean(ul)
ul_avr = ufloat(noms(ul_avr), stds(ul_avr))
ul_avr *= 1e-02  # [cm] --> [m]

## Laden der Zeiten in den verschiedenen Gängen
G, t_h1, t_h2, t_r1, t_r2 = np.loadtxt("Messdaten/Zeiten.txt", unpack=True)
t_err = np.loadtxt("Messdaten/Fehler_Zeiten.txt")

### Fehlerbehaftete Messwerte
ut_h1 = unp.uarray(t_h1, [t_err]*len(t_h1))
ut_h2 = unp.uarray(t_h2, [t_err]*len(t_h2))
ut_r1 = unp.uarray(t_r1, [t_err]*len(t_r1))
ut_r2 = unp.uarray(t_r2, [t_err]*len(t_r2))

### Mittelwerte der Zeiten

uT_h_avr = unp.uarray(np.zeros(len(G)), np.zeros(len(G)))
Beispiel #42
0
N_Rh -= A_null*dt_Rh



# Berechnung der Fehler
n_Rh_err = np.sqrt(N_Rh)

# Fehlerbehafteter Messwert
N_Rh_err = unp.uarray(N_Rh, n_Rh_err)



# Plot aller Messwerte

T_Rh = np.arange(20, 740, dt_Rh)
plt.errorbar(T_Rh, np.log(N_Rh), yerr=stds(N_Rh_err)/N_Rh, fmt="rx", label="Messwerte")

plt.xlim(0,730)
plt.ylim(1.5, 5.5)
plt.xlabel(r"Zeit $t\ [s]$", fontsize=14, family="serif")
plt.ylabel(r"Logarithmierte Zerfälle $\ln(N)$", fontsize=14, family="serif")
plt.grid()
plt.legend(loc="best")
plt.tight_layout()
plt.savefig("Grafiken/Messwerte_Rh.pdf")
#plt.show()
plt.clf()


# Wählen des Zeitpunkts t*
t_x = 480
Beispiel #43
0
def f(x, m, b):
    return m*x+b
def linregress(x, y):
    N = len(y) 
    Delta = N*np.sum(x**2)-(np.sum(x))**2
    m = (N*np.sum(x*y)-np.sum(x)*np.sum(y))/Delta
    b = (np.sum(x**2) * np.sum(y) - np.sum(x) * np.sum(x * y)) / Delta
    sigma_y = np.sqrt(np.sum((y - m * x - b)**2) / (N - 2))
    m_error = sigma_y * np.sqrt(N / Delta)
    b_error = sigma_y * np.sqrt(np.sum(x**2) / Delta)
    print ("Die Regressionssteigung/B ist:", m,"+/-", m_error)
    print ("Der Regressions-Y-Achsenabschnitt ist:", b,"+/-", b_error)
    print("Die Konstante A im Andradeschen Gesetz ist:",np.exp(b),"+/-",np.sqrt(np.exp(2*b)*b_error**2))
    return(m,m_error,b,b_error) 

																#### Plots
etaG =unp.log(apparatG*(rhoG-rhoW)*fallzeit)
linregress(1/T,noms(etaG))

reg, cov = curve_fit(f, 1/T, noms(etaG))
plt.plot(T_func, f(T_func, *reg), 'r-', label='Fit')
plt.text(0.0031,-7.8, r"$x_{lin}= \; T^{-1} \; \lbrack a.u.\rbrack$", horizontalalignment='center',fontsize=12)
plt.text(0.00285,-7.1, r"$y = 29.61x+7.43$", horizontalalignment='center',color="r",fontsize=12)
plt.ylabel(r'$ln(\eta)\;\lbrack a.u.\rbrack$')
plt.errorbar(1/T, noms(etaG) ,yerr=stds(etaG),fmt="bx", label="Werte")
plt.legend(loc="best")
plt.tight_layout
plt.show()




MB=unp.uarray(mB,stdB)
BB=unp.uarray(bB,fehler_b(stdB,U_B))
MG=unp.uarray(mG,stdG)
BG=unp.uarray(bG,fehler_b(stdG,U_G))
MO=unp.uarray(mO,stdO)
BO=unp.uarray(bO,fehler_b(stdO,U_O))
MT=unp.uarray(mT,stdT)
BT=unp.uarray(bT,fehler_b(stdT,U_T)) # könnte wegen der länge scjeiteren
MV=unp.uarray(mV,stdV)
BV=unp.uarray(bV,fehler_b(stdV,U_V))

M_ges=unp.uarray([noms(MO),noms(MG),noms(MT),noms(MB),noms(MV)],
[stds(MO),stds(MG),stds(MT),stds(MB),stds(MV)])

B_ges=unp.uarray([noms(BO),noms(BG),noms(BT),noms(BB),noms(BV)],
[stds(BO),stds(BG),stds(BT),stds(BB),stds(BV)])




def Ug(M,B):
    return(-B/M)

U_gO=Ug(MO,BO)
U_gG=Ug(MG,BG)
U_gT=Ug(MT,BT)
U_gB=Ug(MB,BB)
U_gV=Ug(MV,BV)
    amplitude_of_peaks.append(amplitude)

    sigma_of_peaks.append(sigma)

    offset_of_peak.append(offset)

    area_under_peak.append(area)

# Save data in table
print(index)

l.Latexdocument(
    filename=abs_path('tabs/europium/peak_charakteristiken_eu.tex')).tabular(
        data=[
            index,
            unp.uarray(noms(amplitude_of_peaks), stds(amplitude_of_peaks)),
            unp.uarray(noms(sigma_of_peaks), stds(sigma_of_peaks)),
            unp.uarray(noms(offset_of_peak), stds(offset_of_peak))
        ],
        header=['Kanal / ', r'A / ', r'\sigma / ', r'\mu / '],
        places=[0, (2.2, 2.2), (1.2, 1.2), (4.2, 1.2)],
        caption='Bestimmte Eigenschaften der Peaks von $^{152}\ce{Eu}$.',
        label='results_peaks_eu')
# ########################################################################### #
# ## --- Linear Regression to get transformations parameters--- ## #
# ########################################################################### #


def g(x, m, b):
    '''Define linear function for Transformation purpose'''
    return m * x + b
Beispiel #46
0
uP_2 = unp.uarray(P_2, P_dim * [P_2_err])

#%%

## Plots der Temperaturverläufe

# 16 t- Werte in Sekunden (0, 90, 180, ..., 1350)
t = np.linspace(0, (T_dim - 1) * DELTA_T, num=T_dim)

# "Kontinuierliche" Werte von -10 bis 2000
x = np.linspace(-10, 2000, num=1000)


# Bearbeitung von T_1
    #Berechnung der Fit-Parameter
poptI_T1, pcovI_T1 = curve_fit(T_FitI, t, noms(uT_1), sigma=stds(uT_1))
poptII_T1, pcovII_T1 = curve_fit(T_FitII, t, noms(uT_1), sigma=stds(uT_1))
poptIII_T1, pcovIII_T1 = curve_fit(T_FitIII, t, noms(uT_1), sigma=stds(uT_1))

    # Berechnung der Fit-Fehler
errorI_T1 = np.sqrt(np.diag(pcovI_T1))
#errorII_T1 = np.sqrt(np.diag(pcovII_T1))
#errorIII_T1 = np.sqrt(np.diag(pcovIII_T1))

uA_1 = ufloat(poptI_T1[0], errorI_T1[0]) 
uB_1 = ufloat(poptI_T1[1], errorI_T1[1]) 
uC_1 = ufloat(poptI_T1[2], errorI_T1[2]) 



    # Plot Einstellungen
Beispiel #47
0
# Erstellen von 3x3 Matrizen für die Werte von Cu und Al
# Spalte entspricht einer Versuchsreihe, Zeile: Entspricht einer Größe

uU_CU = unp.matrix([uU_CU_C, uU_CU_H, uU_CU_M])
uU_AL = unp.matrix([uU_AL_C, uU_AL_H, uU_AL_M])

# Umrechnung der Spannungen in Temperaturen

uT_CU = TensToTemp(uU_CU)
uT_AL = TensToTemp(uU_AL)

TEST = True
if TEST:
    for i in range(3):
        for j in range(3):
            uT_CU[i, j] = ufloat(noms(uT_CU[i, j]), stds(uT_CU[i, j]))

if TEST:
    for i in range(3):
        for j in range(3):
            uT_AL[i, j] = ufloat(noms(uT_AL[i, j]), stds(uT_AL[i, j]))

## Versuchsergebnisse der Kalorimetermessung:M_c, M_h, M_m, U_c, U_h, U_m
M_W_C, M_W_H, M_W_M, U_W_C, U_W_H, U_W_M = np.loadtxt(
    "Messdaten/Messung_Kalorimeter.txt", unpack=True)

# Umrechnung in SI-Einheiten
if SI:
    M_W_C *= 1e-03  # kg
    M_W_H *= 1e-03  # kg
    M_W_M *= 1e-03  # kg
plt.figure(2)
plt.plot(Ud2,D_U2,'cx',label=r'$\mathrm{Messwerte \  für \ U_b=250\mathrm{V}}$')
plt.errorbar(Ud2,D_U2,xerr=0,yerr=0.002, fmt='cx')
plt.plot(Ud4,D_U4,'gx',label=r'$\mathrm{Messwerte \  für \ U_b=400\mathrm{V}}$')
plt.errorbar(Ud4,D_U4,xerr=0,yerr=0.002, fmt='gx')
plt.plot(x_U,m2*x_U+b2,'c-',label=r'$\mathrm{Ausgleichsfunkion \ für\ U_b=250V  }$')
plt.plot(x_U,m4*x_U+b4,'g-',label=r'$\mathrm{Ausgleichsfunkion \ für\ U_b=400V  }$')
plt.legend(loc='best')
plt.xlabel(r'$\mathrm{Ablenkspannung \ U_d/V}$')
plt.ylabel(r'$\mathrm{Verschiebung \ D/m}$')
plt.savefig('plotV5012.pdf')

np.savetxt('1tabelle.txt',np.column_stack((D_U1,Ud1,Ud2,Ud3)),fmt='%r',delimiter=' & ')


Mges=unp.uarray([m1,m2,m3,m4,m5],[stds(M1),stds(M2),stds(M3),stds(M4),stds(M5)])
Ubges=np.array([Ub1,Ub2,Ub3,Ub4,Ub5])


print(noms(Mges))
ma , ba , ra ,pa ,stda =stats.linregress(1/Ubges,noms(Mges))

x_ub=np.linspace(0,0.006)
plt.figure(3)
plt.plot(1/Ubges,noms(Mges),'rx',label=r'$\mathrm{Messwerte}$')
plt.errorbar(1/Ubges,noms(Mges),xerr=0,yerr=stds(Mges), fmt='rx')
plt.plot(x_ub,ma*x_ub+ba,'c-',label=r'$\mathrm{Ausgleichsfunkion}$')
plt.legend(loc='best')
plt.xlabel(r'$\mathrm{U_b^{-1}/V^{-1}}$')
plt.ylabel(r'$D\,U_d^{-1}\mathrm{/m V^{-1} }$')
plt.savefig('plotV501a.pdf')
def weight_mean(X):
    n = noms(X)
    s = stds(X)
    mean = sum(n * 1 / s**2) / sum(1 / s**2)
    std = np.sqrt(1 / sum(1 / s**2))
    return ufloat(mean, std)
Beispiel #50
0
# Spalte entspricht einer Versuchsreihe, Zeile: Entspricht einer Größe

uU_CU = unp.matrix([uU_CU_C, uU_CU_H, uU_CU_M])
uU_AL = unp.matrix([uU_AL_C, uU_AL_H, uU_AL_M])


# Umrechnung der Spannungen in Temperaturen

uT_CU = TensToTemp(uU_CU)
uT_AL = TensToTemp(uU_AL)

TEST = True
if TEST:
    for i in range(3):
        for j in range(3):
            uT_CU[i,j] = ufloat(noms(uT_CU[i,j]), stds(uT_CU[i,j]))

if TEST:
    for i in range(3):
        for j in range(3):
            uT_AL[i,j] = ufloat(noms(uT_AL[i,j]), stds(uT_AL[i,j]))

## Versuchsergebnisse der Kalorimetermessung:M_c, M_h, M_m, U_c, U_h, U_m
M_W_C, M_W_H, M_W_M, U_W_C, U_W_H, U_W_M = np.loadtxt("Messdaten/Messung_Kalorimeter.txt",
                                                      unpack=True)

# Umrechnung in SI-Einheiten
if SI:
    M_W_C *= 1e-03  # kg
    M_W_H *= 1e-03  # kg
    M_W_M *= 1e-03  # kg
Beispiel #51
0
plt.savefig('build/zoom.pdf')
plt.clf()
print(noms(U_c_ges[Indem_max]/U_er_ges[Indem_max]))

# Abgelesene Werte
V_abgelesen = np.array([ufloat(33.925, 0.005)])
w_0_abgelesen = V_abgelesen *2*np.pi
print('Vergleiche')
print(w_0_abgelesen)
v_minus_abgelesen = V_abgelesen - X
w_minus_abgelesen = v_minus_abgelesen *(-2)*np.pi + w_0_abgelesen
v_plus_abgelesen = Y-V_abgelesen
w_plus_abgelesen = v_plus_abgelesen *2*np.pi + w_0_abgelesen
q_abgelesen = (w_0_abgelesen)/(w_plus_abgelesen - w_minus_abgelesen)
print('HEY')
print(stds(w_minus_abgelesen))
write('build/Tabelle_aufgabenteil_c_exp.tex', make_table([[q_abgelesen[0]], [w_0_abgelesen[0]], [w_minus_abgelesen[0]],
[w_plus_abgelesen[0]]] ,[1,1,1,1]))

# L = np.array([ufloat(10.11, 0.03)]) # in mH
print('Hier')
print(q_abgelesen)



# Aufgabenteil d)
fre_ges *=1e3  # umrechnung in Hz
w_ges = fre_ges * 2* np.pi *(1/1000)
Takt = 1/fre_ges

def phi(a,T):
U_0=unp.uarray(19.4,0.05)
y=1-(U_c/U_0)
#phi=(a/b)*2*np.pi
#plt.figure(1)
#plt.plot(1/(b*10**-3),phi,'rx')
#plt.savefig('plot.pdf')
print(T)
index= [12,13]
Tt=np.delete(T, index)
print(Tt)
yy=np.delete(y, index)

m , b , r ,p ,std =stats.linregress(noms(Tt),np.log(noms(yy)))
print('m', m)
plt.figure(1)
plt.errorbar(t ,noms(y),xerr=stds(T),yerr=stds(y), fmt='rx')
plt.plot(noms(T),noms(y),'kx',label=r'$Messwerte$')
x=np.linspace(0,5)
plt.plot(t, np.exp(m*t+b),label=r'$Ausgleichsfunktion$')
plt.yscale('log')
plt.legend(loc='best')
plt.xlabel(r'$t/s$')
plt.ylabel(r'$ln(1-(U_c/U_0)) $')
plt.savefig('a.pdf')
M=unp.uarray(m,std)
print('RC ist = ', 1/M, M)
print('Delta Rc',std/m**2)

w , a_w =np.genfromtxt('b.txt',unpack=True)
# RC=0.001388
A_w=unp.uarray(a_w,0.0005)
Beispiel #53
0
         m4 * x_U + b4,
         'g-',
         label=r'$\mathrm{Ausgleichsfunkion \ für\ U_b=400V  }$')
plt.legend(loc='best')
plt.xlabel(r'$\mathrm{Ablenkspannung \ U_d/V}$')
plt.ylabel(r'$\mathrm{Verschiebung \ D/m}$')
plt.savefig('plotV5012.pdf')

np.savetxt('1tabelle.txt',
           np.column_stack((D_U1, Ud1, Ud2, Ud3)),
           fmt='%r',
           delimiter=' & ')

Mges = unp.uarray(
    [m1, m2, m3, m4, m5],
    [stds(M1), stds(M2), stds(M3),
     stds(M4), stds(M5)])
Ubges = np.array([Ub1, Ub2, Ub3, Ub4, Ub5])

print(noms(Mges))
ma, ba, ra, pa, stda = stats.linregress(1 / Ubges, noms(Mges))

x_ub = np.linspace(0, 0.006)
plt.figure(3)
plt.plot(1 / Ubges, noms(Mges), 'rx', label=r'$\mathrm{Messwerte}$')
plt.errorbar(1 / Ubges, noms(Mges), xerr=0, yerr=stds(Mges), fmt='rx')
plt.plot(x_ub, ma * x_ub + ba, 'c-', label=r'$\mathrm{Ausgleichsfunkion}$')
plt.legend(loc='best')
plt.xlabel(r'$\mathrm{U_b^{-1}/V^{-1}}$')
plt.ylabel(r'$D\,U_d^{-1}\mathrm{/m V^{-1} }$')
plt.savefig('plotV501a.pdf')
Beispiel #54
0
def do_job_a(filename, error, j, filename_out=None):
    # Einlesen der Messdaten
    P, Delta_f_30, Delta_f_15, Delta_f_60 = np.genfromtxt(filename, unpack=True)

    #
    di = [7, 10, 16]
    colors = ["rx", "bx", "gx"]

    Delta_f_30_error = Delta_f_30 * error
    Delta_f_30 = unp.uarray(Delta_f_30, Delta_f_30_error)
    Delta_f_15_error = Delta_f_15 * error
    Delta_f_15 = unp.uarray(Delta_f_15, Delta_f_15_error)
    Delta_f_60_error = Delta_f_60 * error
    Delta_f_60 = unp.uarray(Delta_f_60, Delta_f_60_error)

    v = unp.uarray(np.zeros(3), np.zeros(3))
    v[0] = c_L / 2 / nu_0 * Delta_f_30 / np.cos(alpha[0])
    v[1] = c_L / 2 / nu_0 * Delta_f_15 / np.cos(alpha[1])
    v[2] = c_L / 2 / nu_0 * Delta_f_60 / np.cos(alpha[2])

    v_mean = mean([v[0], v[1], v[2]], 0)

    # TABLES
    write(
        "build/Tabelle_a_" + str(di[j]) + ".tex",
        make_table([P, Delta_f_30, Delta_f_15, Delta_f_60, v[0], v[1], v[2], v_mean], [0, 1, 1, 1, 1, 1, 1, 1]),
    )
    write(
        "build/Tabelle_a_" + str(di[j]) + "_texformat.tex",
        make_full_table(
            r"Messdaten und daraus errechnete Geschwindikgiet für $\d_i = $" + str(di[j]) + r"$\si{\milli\meter}$.",
            "table:A" + str(j),
            "build/Tabelle_a_" + str(di[j]) + ".tex",
            [1, 2, 3, 4, 5, 6, 7],
            [
                r"$\frac{P}{P_\text{max}} \:/\: \si{\percent}$",
                r"$\Delta f_{30°} \:/\: \si{\hertz}$",
                r"$\Delta f_{15°} \:/\: \si{\hertz}$",
                r"$\Delta f_{60°} \:/\: \si{\hertz}$",
                r"$v_{30°} \:/\: \si{\meter\per\second}$",
                r"$v_{15°} \:/\: \si{\meter\per\second}$",
                r"$v_{60°} \:/\: \si{\meter\per\second}$",
                r"$\overline{v} \:/\: \si{\meter\per\second}$",
            ],
        ),
    )

    # Plotting
    plt.figure(1)
    y = Delta_f_30 / np.cos(alpha[0])
    plt.errorbar(
        noms(v[0]),
        noms(y),
        fmt=colors[j],
        xerr=stds(v[0]),
        yerr=stds(y),
        label=r"$d_i = " + str(di[j]) + r"\si{\milli\meter}$",
    )

    plt.figure(2)
    y = Delta_f_15 / np.cos(alpha[1])
    plt.errorbar(
        noms(v[1]),
        noms(y),
        fmt=colors[j],
        xerr=stds(v[1]),
        yerr=stds(y),
        label=r"$d_i = " + str(di[j]) + r"\si{\milli\meter}$",
    )

    plt.figure(3)
    y = Delta_f_60 / np.cos(alpha[2])
    plt.errorbar(
        noms(v[2]),
        noms(y),
        fmt=colors[j],
        xerr=stds(v[2]),
        yerr=stds(y),
        label=r"$d_i = " + str(di[j]) + r"\si{\milli\meter}$",
    )

    i = 1
    if filename_out:
        for name in filename_out:
            plt.figure(i)
            plt.xlabel(r"$v \:/\: \si{\meter\per\second}$")
            plt.ylabel(r"$\Delta\nu / \cos{\alpha} \:/\: \si{\kilo\volt}$")
            plt.legend(loc="best")
            plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
            plt.savefig(name)
            i += 1
Beispiel #55
0
#Messung 2

def Brech(z,lamb,T,p0,b,T0,deltaP):
    n=1+z*lamb*T*p0/(2*b*T0*deltaP)
    return n

p1,p2,ticks =np.genfromtxt('Messung2.txt', unpack = True)
deltaP=p2-p1
p0=1.0132
T0=273.15
b=50e-3
T=293.15


n=unp.uarray(noms(Brech(ticks,L,T,p0,b,T0,deltaP)),stds(Brech(ticks,L,T,p0,b,T0,deltaP)))

# n=Brech(ticks,L,T,p0,b,T0,deltaP)
print(n,'n Luft')
print(np.mean(noms(n)),stats.sem(noms(n)),'Luft np.mean(noms(n)),stats.sem(noms(n))')
nL=ufloat(np.mean(noms(n)),stats.sem(noms(n)))




#Messung3
p1,p2,ticks =np.genfromtxt('Messung3.txt', unpack = True)
deltaP=p2-p1

n=unp.uarray(noms(Brech(ticks,L,T,p0,b,T0,deltaP)),stds(Brech(ticks,L,T,p0,b,T0,deltaP)))
print(n,'n 1-Butylen')
Beispiel #56
0
delta_E_natrium = h*c*delta_lambda_natrium/(lambda_natrium_mean**2)         # # in eV (wegen h in eVs)
delta_E_rubidium = h*c*delta_lambda_rubidium/(lambda_rubidium_mean**2)      # # in eV (wegen h in eVs)

# final step : calculate sigma_2
def sigma_2 (n, l, Delta_E, z):
    return z-unp.sqrt(unp.sqrt(Delta_E * l * (l+1) * n**3 / (R*a**2)))

sigma_2_kalium = sigma_2(4, 1, delta_E_kalium, 19)  # Kalium : z=19, 4P1/2 Übergang (P bedeutet l=1)
sigma_2_natrium = sigma_2(3, 1, delta_E_natrium, 11)  # Kalium : z=11, 3P1/2 Übergang (P bedeutet l=1)
sigma_2_rubidium = sigma_2(5, 1, delta_E_rubidium, 37)  # Kalium : z=37, 5P1/2 Übergang (P bedeutet l=1)

# da der Fehler systematische Fehler der Eingangsgrößen klein ist, geben wir nur den Fehler des Mittelwerts an.
sigma_2_kalium_mean = ufloat(np.mean(noms(sigma_2_kalium)), np.std(noms(sigma_2_kalium)))
sigma_2_natrium_mean = ufloat(np.mean(noms(sigma_2_natrium)), np.std(noms(sigma_2_natrium)))
# Für Rubidium haben wir nur einen Messwert, daher gibts auch nichts zu mitteln
sigma_2_rubidium_unc = ufloat(noms(sigma_2_rubidium), stds(sigma_2_rubidium))

write('build/sigma_kalium.tex', make_SI(sigma_2_kalium_mean, r'', figures=1))
write('build/sigma_natrium.tex', make_SI(sigma_2_natrium_mean, r'', figures=1))
write('build/sigma_rubidium.tex', make_SI(sigma_2_rubidium_unc, r'', figures=1))

#### TABELLEn ####
write('build/Tabelle_c_kalium.tex', make_table([
                                                -phi_kalium_mean,
                                                lambda_kalium_mean*1e9,
                                                delta_s_kalium,
                                                delta_lambda_kalium*1e9,
                                                delta_E_kalium*1e3,
                                                sigma_2_kalium
                                                ],
                                                [1, 1, 2, 1, 1, 1]))
from linregress import ulinregress

Delta_t_0 = np.loadtxt('Delta_t_0.txt')
N_0 = np.loadtxt('N_0.txt')
N_0 = unc.ufloat(N_0, np.sqrt(N_0))

Delta_t = np.loadtxt('Delta_t.txt')
N_g = np.loadtxt('N_g.txt', unpack=True)
N_g = unp.uarray(N_g, np.sqrt(N_g))

t = Delta_t * np.arange(1, len(N_g) + 1)
N = N_g - N_0 / Delta_t_0 * Delta_t

A, B = ulinregress(t, unp.log(N))
print(A, B, sep='\n')
lambda_ = -A
print("λ =", lambda_)

x = np.linspace(0, 4000)
plt.plot(x, np.exp(noms(A * x + B)), 'b-', label='Regressionsgerade')
plt.errorbar(t, noms(N), yerr=stds(N), fmt='rx', label='Messwerte')
plt.yscale('log', nonposy='clip')
plt.xlabel(r'$t \,/\, \mathrm{s}$')
plt.ylabel(r'$N$')
plt.ylim(8e2, 3e3)
plt.yticks([8e2, 1e3, 3e3], [r"$8 \cdot 10^2$", r"$10^3$", r"$3 \cdot 10^3$"])
plt.legend(loc='upper right')
plt.tight_layout()
plt.savefig('loesung.pdf')
Beispiel #58
0
##print(P_C_j_err)
#
## Regression der Messwerte
#popt_C, pcov_C = curve_fit(func_gerade, noms(U_C_j_err),
#                           noms(P_C_j_err), sigma=stds(P_C_j_err))
#error = np.sqrt(np.diag(pcov_C))
#param_m_C = ufloat(popt_C[0], error[0])
#param_b_C = ufloat(popt_C[1], error[1])
#
#print("Steigung:", param_m_C)
#print("Steigung in % pro 100V:", param_m_C*100,"%")
#print("y-Abschnitt:", param_b_C)

# Regression der Messwerte
popt_C, pcov_C = curve_fit(func_gerade, noms(U_C_err),
                           noms(P_C_err), sigma=stds(P_C_err))
error = np.sqrt(np.diag(pcov_C))
param_m_C = ufloat(popt_C[0], error[0])
param_b_C = ufloat(popt_C[1], error[1])

print("Steigung:", param_m_C)
print(func_gerade(100, param_m_C,param_b_C))
print(func_gerade(0, param_m_C,param_b_C))
print((func_gerade(100, param_m_C,param_b_C)- func_gerade(0, param_m_C,param_b_C))/func_gerade(0, param_m_C,param_b_C))
print("Steigung in % pro 100V:", 100 * (func_gerade(100, param_m_C,param_b_C)- func_gerade(0, param_m_C,param_b_C))/func_gerade(0, param_m_C,param_b_C),"%")
print("y-Abschnitt:", param_b_C)



# Plot der Messwerte
plt.errorbar(noms(U_C_err), noms(P_C_err), yerr=stds(P_C_err),  fmt="rx", label="Messwerte")
omega_x.SetParameter(0, 1e-10)
omega_x.SetParameter(1, 0.00898)
omega_x.SetParameter(2, (1060e-9)**2 / np.pi**2)

omega_y.SetParameter(0, 1e-10)
omega_y.SetParameter(1, 0.00898)
omega_y.SetParameter(2, (1060e-9)**2 / np.pi**2)

c1 = root.TCanvas("c1", "c1", 1980, 1080)
c1.SetGrid()

mg = root.TMultiGraph()  #Create multigraph

plot_xsigma = root.TGraphErrors(len(xsigma), array('f', noms(uheight)),
                                array('f', noms(usigma_x)),
                                array('f', stds(uheight)),
                                array('f', stds(usigma_x)))
plot_ysigma = root.TGraphErrors(len(xsigma), array('f', noms(uheight)),
                                array('f', noms(usigma_y)),
                                array('f', stds(uheight)),
                                array('f', stds(usigma_y)))

mg.GetXaxis().SetRangeUser(2., 10.)
plot_xsigma.GetXaxis().SetMaxDigits(2)

plot_xsigma.GetXaxis().SetLimits(0, 1)  #Set xLimits
plot_ysigma.GetXaxis().SetLimits(0, 1)  #Set xLimits

plot_xsigma.SetMarkerColor(1756)
plot_xsigma.SetLineColor(1756)
omega_x.SetLineColor(1758)  #Set Linecolor xsigma
Beispiel #60
0

### Noch ein paar Plots
plt.clf()
CAP = np.linspace(1e-20, 14e-09, num=1e02)
plt.grid()
plt.tick_params("both", labelsize=14)
plt.ylim(20e03, 1e05)
plt.xlabel(r"Koppelkondensatoren $C_{K}\ [\mathrm{nF}]$", fontsize=14)
plt.gca().xaxis.set_major_formatter(mpl.ticker.FuncFormatter(lambda x, _: float(x * 1e09)))
plt.ylabel(r"Frequenz $f\ [\mathrm{kHz}]$", fontsize=14)
plt.gca().yaxis.set_major_formatter(mpl.ticker.FuncFormatter(lambda x, _: float(x * 1e-03)))
plt.plot(CAP, len(CAP)*[resFreq_plus(noms(uC), C_sp, noms(uL))], color="blue",
         label="Theoretischer Kurve $v^{+}(C_{K})$")

plt.errorbar(noms(uC1), noms(uf_p), yerr=stds(uf_p), fmt="bo",
             label="Messwerte $v^{+}(C_{K})$")

plt.plot(CAP, resFreq_minus(noms(uC), CAP, C_sp, noms(uL)), color="green",
         label="Theoretischer Kurve $v^{-}(C_{K})$")
plt.errorbar(noms(uC1), noms(uf_m), yerr=stds(uf_m), fmt="go",
             label="Messwerte $v^{-}(C_{K})$")
plt.legend(loc="best")
plt.tight_layout()
plt.savefig("Grafiken/Frequenz_CK.pdf")



## Print Funktionen