def mean(values, axis=0):
    """Returns mean values and their mean errors of a given array. Return value will be a unp.uarray
    Args:
            values:     (list)  Array containing numbers whose mean is desired.
            axis:       (int)   Axis along which the means are computed. The default is to compute the mean of the flattened array.
    """
    return unp.uarray(np.mean(noms(values), axis=axis), scipy.stats.sem(noms(values), axis=axis))
Esempio n. 2
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()
Esempio n. 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)
def mean(values, axis=0):
    """Returns mean values and their mean errors of a given array. Return value will be a unp.uarray
    Args:
            values:     (list)  Array containing numbers whose mean is desired.
            axis:       (int)   Axis along which the means are computed. The default is to compute the mean of the flattened array.
    """
    return unp.uarray((np.mean(noms(values), axis=axis), scipy.stats.sem(noms(values), axis=axis)))
Esempio n. 5
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()
Esempio n. 6
0
def table(name, data):
	j=0
	i=0
	f = np.zeros(len(data))
	for i in range(len(data)):
		if(type(data[i][0]) == type(dummy) or type(data[i][0]) == type(dummyarray[1]) or type(data) == type(udummyarray)):
			f[i] = True
		else:
			f[i] = False
	print(f)
	#Runden
	for i in range(len(data)):
		if(f[i]):
			for j in range(data[0]):
				sdevs(data[i][j]) = rts(sdevs(data[i][j]))
				noms(data[i][j]) = round((noms(data[i][j]), -int(m.floor(m.log10(abs(x))))))
							
			
	output = open(name, 'w')
	output.write(r'\begin{table}[h]' + '\n' + r'\centering' + '\n' + r'\caption{CAPTION}' + '\n' +r'\sisetup{%uncertainty-seperator = {\,},'+'\n'+r'table-number-alignment = center,'+'\n'+'table-unit-alignment = center,'+'\n'+'%table-figures-integer = 1,'+'\n'+'%table-figures-decimal = 1,'+'\n'+'table-auto-round = true'+'\n'+'}'+'\n'+ r'\begin{tabular}{ ')
	for i in range(len(data)):
		if(f[i]):
			output.write(r'S[table-format= 3.1]'+'\n'+' @{\,$\pm{}$\,} '+'\n' + r' S[table-format= 3.1] ')
		else:
			output.write(r' S[table-format= 3.1] '+'\n')
	output.write(r'}' + '\n' + r'\toprule' + '\n')
	
	for i in range(len(data)):
		if(i < (len(data)-1)): 
			if(f[i]):
				output.write(r'\multicolumn{2}{c}{TITLE}'+'\n'+'&')
			else:
				output.write(r'{$\text{Title}$}'+'\n'+'&')
		else:
			if(f[i]):
				output.write(r'\multicolumn{2}{c}{TITLE} \\'+'\n')
			else:
				output.write(r'{$\text{Title}$} \\'+'\n')
	output.write(r' \midrule' + '\n')
	
	#Tabelle
	for j in range(len(data[0])):
		i = 0
		while i <= len(data)-1:
				if(f[i]):
					if(i == len(data)-1):
						output.write(str(data[i][j].n) + '&' + str(data[i][j].s) + r'\\' + '\n')
					else:
						output.write(str(data[i][j].n)+ '&' + str(data[i][j].s) + '&')
					i = i+1
				else:
					if(i == len(data)-1):
						output.write(str(data[i][j]) + r'\\' + '\n')
					else:
						output.write(str(data[i][j]) + '&')
					i = i+1
	#Tabelle Ende
	output.write(r'\bottomrule' + '\n' + r'\end{tabular}' + '\n' + r'\label{tab:LABEL}' + '\n' + r'\end{table}')
	output.close()
Esempio n. 7
0
def plot(x, y, file, fitfunktion, tau_erw, abklingzeit_erw, x_fit=None, xlim=None, ylim=None):
    plt.errorbar(unp.nominal_values(x), unp.nominal_values(y),
                 xerr=unp.std_devs(x), yerr=unp.std_devs(y), fmt='-', label='Messwerte')

    # maxima finden
    x_nom = noms(x)
    y_nom = noms(y)
    left_right = 1
    ende = 30
    start = 30
    maxima_x = []
    maxima_y = []
    for i in range(start, len(x_nom)-ende):
        if y_nom[i-left_right]<y_nom[i] and y_nom[i+left_right]<=y_nom[i] and y_nom[i-3]<y_nom[i] and y_nom[i+3]<y_nom[i]:
            maxima_x.append(x_nom[i])
            maxima_y.append(y_nom[i])
            #i += 500
    maxima_x, maxima_y = maxima_x[:14], maxima_y[:14]
    plt.plot(maxima_x, maxima_y, 'x', label='Maxima')
    maxima_x = np.asarray(maxima_x)
    U_0 = 0.000007
    # fitten:
    if x_fit is not None:
        params, covariance = curve_fit(fitfunktion, maxima_x,
                                        maxima_y,
                                        p0=[tau_erw.n, U_0])
        errors = np.sqrt(np.diag(covariance))
        print('tau= ', params[0] * 1e3, '±', errors[0] * 1e3)
        k = ufloat(params[0], errors[0])
        print('U_0= ', params[1], '±', errors[1])
        U_0 = ufloat(params[1], errors[1])

        print('Abweichung von tau_erw = ', abweichungen(tau_erw, k), '%')
        x_fit = np.linspace(x_fit[0], x_fit[1], 10000)
        plt.plot(x_fit, fitfunktion(x_fit, *params), label='Fit')
        label=r'Maximum$\:/\:e$'
        #label='test'
        plt.plot((xlim[0], xlim[1]), (maxima_y[0]/np.e, maxima_y[0]/np.e), label=label)

        for x_loop in x_fit:
            if fitfunktion(x_loop, *params) < maxima_y[0]/np.e:
                print('Abklingzeit =', x_loop - maxima_x[0], abklingzeit_erw, abweichungen(abklingzeit_erw, x_loop - maxima_x[0]))
                break

    if xlim is not None:
        plt.xlim(xlim[0], xlim[1])
    if ylim is not None:
        plt.ylim(ylim[0], ylim[1])
    xlabel = r'$t\:/\:\si{\second}$'
    ylabel = r"$U_\text{A}\:/\:\si{\volt}$"
    #xlabel, ylabel = 'test', 'test'
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    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/'+file+'.pdf')
    plt.close()
def automatic_spectrum_anaysis(
    channel_content,
    index_of_peak,
    fit_function,
):

    # use as fit_intervall \pm 15, create for fit numpy array with index values
    index_channel = np.arange(index_of_peak - 15, index_of_peak + 15, 1)
    index = noms(g(index_channel, m, b))

    params_gaus, cov_gaus = curve_fit(
        fit_function,
        index,
        channel_content[index_channel],
        p0=[channel_content[index_of_peak], 1,
            noms(g(index_of_peak, m, b))])

    error_gaus = np.sqrt(np.diag(cov_gaus))

    amplitude = ufloat(params_gaus[0], error_gaus[0])
    sigma = ufloat(params_gaus[1], error_gaus[1])
    offset = ufloat(params_gaus[2], error_gaus[2])

    # --- Calculate area under peak --- #

    area_under_peak = sum(channel_content[index_of_peak - 5:index_of_peak + 5])

    # --- Plot function ---  #

    index_fit_plot = np.linspace(index_of_peak - 15, index_of_peak + 15, 1e4)

    #plt.clf()
    #plt.xlim(noms(g(index_of_peak, m, b))-1, noms(g(index_of_peak, m, b))+1)
    #plt.ylim(0, channel_content[index_of_peak] * 1.2)
    #plt.hist(noms(g(np.arange(0, len(channel_content_sb_ba), 1), m, b)),
    #         bins=noms(g(np.linspace(0, len(channel_content_sb_ba),
    #         len(channel_content_sb_ba)), m, b)),
    #         weights=channel_content_sb_ba, label='Spektrum')

    #plt.plot(index_fit_plot, fit_function(index_fit_plot, *params_gaus),
    #         label='Fit')
    #plt.xlabel(r'$\mathrm{Channel}$')
    #plt.ylabel(r'$\mathrm{Count}$')
    #plt.legend()
    #plt.savefig(f'./plots/sb_or_ba/spectrum_fit_at_index_{str(index_of_peak)}.pdf')

    # --- Return values --- #

    return amplitude, sigma, offset, int(area_under_peak)
Esempio n. 9
0
def plotWiderstand(widerstand, spannung, V_N, dateiname, T):
    spannung = unp.uarray(spannung, 0.005)
    widerstand = unp.uarray(widerstand, 1)
    y = spannung / V_N**2
    x = widerstand
    plt.errorbar(unp.nominal_values(x),
                 unp.nominal_values(y),
                 xerr=unp.std_devs(x),
                 yerr=unp.std_devs(y),
                 fmt='kx',
                 label='Messwerte')

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

    # kBoltzmann
    if dateiname == "1" or dateiname == "2":
        #int, intf = np.genfromtxt('build/eichungeinfach.txt', unpack='True')
        int = ufloat(4.9486e11, 0.001e11)
    else:
        #int, intf = np.genfromtxt('build/eichungKorrelator.txt', unpack='True')
        int = ufloat(7.41e9, 0.04e9)

    #int = ufloat(int, intf)
    T = ufloat(296.15, 2)  # K
    k_B = m / (4 * int * T)
    print('k_B_', dateiname, " = ", k_B)
    kBTheorie = ufloat(constants.physical_constants["Boltzmann constant"][0],
                       constants.physical_constants["Boltzmann constant"][2])
    print("Abweichung von Theorie= ", abweichungen(kBTheorie, k_B))

    plt.xlabel(r'$R/\si{\ohm}$')
    plt.ylabel(r'$U_\text{A} \:/\: \si{\volt\squared}$')
    plt.xlim(0, 1.01 * max(noms(x)))
    plt.legend(loc='best')

    # in matplotlibrc leider (noch) nicht möglich
    #plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
    plt.savefig('build/plotWiderstand' + dateiname + '.pdf')
    plt.close()
    def SelectPeaks(self):
        """
        Function opens a Window with the data, you can choose initial values for the peaks by clicking on the plot.
        """

        fig, ax = plt.subplots()
        ax.plot(self.x, self.y)
        polyparams = self.Fitbaseline()
        ax.plot(self.x, poly(self.x, *noms(polyparams)), 'r-')
        x = []
        y = []

        def onclickpeaks(event):
            if event.button:
                x.append(event.xdata)
                y.append(event.ydata)
                plt.plot(event.xdata, event.ydata, 'ko')
                fig.canvas.draw()

        cid = fig.canvas.mpl_connect('button_press_event', onclickpeaks)
        figManager = plt.get_current_fig_manager()
        figManager.window.showMaximized()
        plt.show()
        np.savetxt(self.label + '/locpeak_' + self.label + '.txt',
                   np.transpose([np.array(x), np.array(y)
                                 ]))  # store the chosen initial values
        self.peakfile = self.label + '/locpeak_' + self.label + '.txt'
Esempio n. 11
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' \\'
Esempio n. 14
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()
Esempio n. 15
0
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
Esempio n. 16
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])))
Esempio n. 17
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()
Esempio n. 18
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)
Esempio n. 19
0
def Miriam_n(Druck,M,L = L, Lambda = 632.99e-9):
    n = Lambda/L * M + 1
    params, cov = curve_fit(f, Druck, noms(n))
    errors = np.sqrt(np.diag(cov))
    params = unp.uarray(params,errors)
    T_0 = 15 + 273.15
    Steigung_norm = params[0] * T/T_0
    atm =  1.01325e3
    n_atm = Steigung_norm * atm + params[1]
    return [params,Druck,n,n_atm]
Esempio n. 20
0
def lnint(T, I, hr):
    array = np.array([])
    for t in T:
        if t == T[-1]:
            break
        array = np.append(
            array,
            np.log(
                np.abs(np.trapz(np.abs(I[T >= t]), T[T >= t])) /
                (np.abs(I[T == t]) * noms(hr))))
    return array
Esempio n. 21
0
def plot(x, y, label, filename, x_label, y_label,
         fitfunktion, p_list, pname_list):
    plt.errorbar(unp.nominal_values(x), unp.nominal_values(y),
                 xerr=unp.std_devs(x), yerr=unp.std_devs(y),
                 fmt='kx', label='Messwerte '+label)

    werte_start = 0
    werte_ende = len(x)-1
    params, covariance = curve_fit(fitfunktion, unp.nominal_values(x[werte_start:werte_ende]),
                                   unp.nominal_values(y[werte_start:werte_ende]),
                                   p0=p_list)
    errors = np.sqrt(np.diag(covariance))
    for i, name in enumerate(pname_list):
        print('{0} = {1} ± {2}'.format(name, round(params[i], 5), round(errors[i], 5)))
    # print('I_0= ', params[0], '±', errors[0])
    # print('phi_verschieb= ', params[1], '±', errors[1])
    # print('m = ', params[2], '±', errors[2])
    # m = ufloat(params[0], errors[0])
    x_fit = np.linspace(noms(x[0])-(noms(x[-1]))*0.1, (noms(x[-1]))*1.1, 1000)
    plt.plot(x_fit, fitfunktion(x_fit, *params), label='Fit ' + label)

    # plotting
    plt.legend(loc='best')
    plt.xlim(noms(x[0])-(noms(x[-1]))*0.06, (noms(x[-1]))*1.06)

    # y_label, x_label= 'test', 'x_label'
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.savefig('build/{}.pdf'.format(filename))
    plt.close()
Esempio n. 22
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')
Esempio n. 23
0
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)))
Esempio n. 24
0
def plotDurchlass(spannung, nu, V_N, amplitude, dateiname):
    # plt.errorbar(unp.nominal_values(x), unp.nominal_values(y),
    # xerr=unp.std_devs(x), yerr=unp.std_devs(y), fmt='kx', label='Messwerte')
    amplitude *= 10**(-3)  # abschwächer

    if V_N is not None:  # umrechnen da verschieden verstärkt
        spannung /= V_N**2  # auf V_N = 1 normieren
        plt.yscale('log')
    spannung /= amplitude**2
    x = unp.uarray(nu, 0.01)
    y = unp.uarray(spannung, 0.005)
    plt.errorbar(unp.nominal_values(x), unp.nominal_values(y),
                 xerr=unp.std_devs(x), yerr=unp.std_devs(y), fmt='kx', label='Messwerte')
    plt.xlabel(r'$\nu/\si{\kilo\hertz}$')
    plt.ylabel(r'$U_\text{A}^2 \:/\: \si{\volt\squared}$')
    plt.legend(loc='best')

    # in matplotlibrc leider (noch) nicht möglich
    #plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
    plt.savefig('build/plotdurchlass'+dateiname+'.pdf')
    plt.close()

    # integration:
    x *= 10**(3)  # auf Hz umrechnen
    # int = (max(x) - min(x))/len(x) * sum(y)
    # print("Integral der Durchlasskurve= ", int)
    int_trapez = trapezFormel(x, y)
    print("Integral mit trapez = ", int_trapez)
    int_scipy = integrate.simps(noms(y), x=noms(x))

    print("Integral mit scipy = ", int_scipy)
    int = ufloat(int_scipy, 0)
    file = open("build/eichung"+dateiname+".txt", "w")
    file.write(str(int.n))
    file.write(" ")
    file.write(str(int.s))
    file.close()
Esempio n. 25
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()
Esempio n. 26
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')
Esempio n. 27
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' \\'
Esempio n. 28
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' \\'
Esempio n. 29
0
def fitten(axes, x, y, fitfunktion, p_list, pname_list, color, label, schnittwert=None):
    params, covariance = curve_fit(fitfunktion, noms(x),
                                   noms(y),
                                   p0=p_list)
    errors = np.sqrt(np.diag(covariance))
    print('Werte ' + label)
    for i, name in enumerate(pname_list):
        print('{0} = {1} ± {2}'.format(name, round(params[i], 5), round(errors[i], 5)))
    x_fit = np.linspace(noms(x[0]) - (noms(x[-1])) * 1, (noms(x[-1])) * 1.1, 10000)
    axes.plot(x_fit, fitfunktion(x_fit, *params), color, label='Fit ' + label)

    if schnittwert is not None:
        for x_loop in x_fit:
            if fitfunktion(x_loop, *params) < noms(schnittwert) and params[0] < 0:
                return unp.exp(x_loop)
                break
            elif fitfunktion(x_loop, *params) > noms(schnittwert) and params[0] > 0:
                return unp.exp(x_loop)
                break
Esempio n. 30
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' \\'
Esempio n. 31
0
params_gitterkonstante = ucurve_fit(
    reg_linear, sin_phi_helium, lambda_helium)

g, offset = params_gitterkonstante                  # g in m, offset Einheitenfrei
write('build/gitterkonstante.tex', make_SI(g * 1e9, r'\nano\meter', figures=1))
write('build/offset.tex', make_SI(offset * 1e9, r'\nano\meter', figures=1))
write('build/Tabelle_messdaten_kalium.tex', make_table([phi_kalium*180/np.pi],[1]))
write('build/Tabelle_messdaten_natrium.tex', make_table([phi_natrium*180/np.pi],[1]))
write('build/Tabelle_messdaten_rubidium.tex', make_table([phi_rubidium*180/np.pi],[1]))

##### PLOT lineare Regression #####
t_plot = np.linspace(np.amin(sin_phi_helium), np.amax(sin_phi_helium), 2)
plt.xlim(t_plot[0] - 1 / np.size(sin_phi_helium) * (t_plot[-1] - t_plot[0]),
         t_plot[-1] + 1 / np.size(sin_phi_helium) * (t_plot[-1] - t_plot[0]))
plt.plot(t_plot,
         reg_linear(t_plot, *noms(params_gitterkonstante))* 1e9,
         'b-', label='Fit')
plt.plot(sin_phi_helium,
         lambda_helium * 1e9,
         'rx', label='Messdaten')
plt.ylabel(r'$\lambda \:/\: \si{\nano\meter}$')
plt.xlabel(r'$\sin(\varphi)$')
plt.legend(loc='best')
plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
plt.savefig('build/aufgabenteil_a_plot.pdf')
plt.clf()
#### Ende Plot ####

#### TABELLE ####
write('build/Tabelle_a.tex', make_table([lambda_helium*1e9, -phi_helium, -sin_phi_helium],[1, 3, 3]))
write('build/Tabelle_a_texformat.tex', make_full_table(
Esempio n. 32
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
# write('build1/offset2.tex', make_SI(1e-5*g(373.1, *noms(params_2))-1, r'\bar', '', 1))
# p2 += 1e5-g(373.1, *noms(params_2))
# params_2 = ucurve_fit(g, T2, p2)

a2, b2, c2, d2 = params_2
d2 += 48*1e3    # Korrektur Offset (laut Protokoll)
write('build1/a2.tex', make_SI(a2 * 1e-5, r'\bar\per\kelvin\tothe{3}', '', 1))
write('build1/b2.tex', make_SI(b2 * 1e-5, r'\bar\per\kelvin\tothe{2}', '', 1))
write('build1/c2.tex', make_SI(c2 * 1e-5, r'\bar\per\kelvin\tothe{1}', '', 1))
write('build1/d2.tex', make_SI(d2 * 1e-5, r'\bar', '', 1))

T_hilf = np.linspace(np.amin(T2), np.amax(T2), 5)
T_plot = np.linspace((T_hilf[0]-1/np.size(T2)*(T_hilf[-1]-T_hilf[0])), (T_hilf[-1]+1/np.size(T2)*(T_hilf[-1]-T_hilf[0])), 10)

plt.clf()
plt.plot(T_plot, g(T_plot, *noms(params_2))*1e-5, 'b-', label='Fit')
plt.plot(T2, p2*1e-5, '.r', label='Messdaten')

plt.xlim(np.amin(T_plot), np.amax(T_plot))
plt.xlabel(r'$T \:/\: \si{\kelvin}$')
plt.ylabel(r'$p \:/\: \si{\bar}$')
plt.legend(loc='best')
plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
plt.savefig('build1/plot2.pdf')

plt.clf()
T_plot = np.linspace(200,600,100)
plt.plot(T_plot, L(0.9, R[0], T_plot, *noms(params_2)), 'b-', label='Fit numpy curve_fit')
plt.plot(T_plot, L(0.9, R[0], T_plot, 4.32*1e-1, -4.07*1e2, 1.262*1e5, -127.82*1e5+48*1e3), 'r-', label='Fit Origin 8')
#plt.plot(T2, p2*1e-5, '.r', label='Messdaten')
Esempio n. 34
0
U_1, I_1 = np.loadtxt("Messdaten/I_aU_a_I.txt", unpack=True)

# Fehler
u_err = 0.05  # Volt pro Millimeter
i_err = 0.1   # Zentimeter

U_1_err = unp.uarray(U_1, [u_err]*len(U_1))
I_1_err = unp.uarray(I_1, [i_err]*len(U_1))


dU_1_err = [(U_1_err[i+1] - U_1_err[i]) for i in range(len(I_1_err)-1)]


dI_1_err = [(I_1_err[i] - I_1_err[i+1]) for i in range(len(I_1)-1)]

print("Maximum:", U_1_err[np.where(noms(dI_1_err) == max(noms(dI_1_err)))[0][0]], "/", max(dI_1_err))
print("Kontaktpotenzial:", ufloat(11, 1) - U_1_err[np.where(noms(dI_1_err) == max(noms(dI_1_err)))[0][0]])
K_1_err = ufloat(11, 1) - U_1_err[np.where(noms(dI_1_err) == max(noms(dI_1_err)))[0][0]]


plt.plot(noms(U_1_err[:-1]), noms(dI_1_err), label="differenzielle\nEnergieverteilung")
plt.stem([noms(U_1_err[np.where(noms(dI_1_err) == max(noms(dI_1_err)))[0][0]])], [max(noms(dI_1_err))],
         linefmt="k--", markerfmt="ko",
         label="max. Änderung ({}|{})".format(U_1[np.where(noms(dI_1_err) == max(noms(dI_1_err)))[0][0]],
                                              max(noms(dI_1_err))))
plt.grid()
plt.xlabel(r"Bremsspannung $U_{A}$")
plt.ylabel("Änderung des Auffängerstroms\n $I_{A}(U_{A}) - I_{A}(U_{A} + \Delta U_{A})$")
plt.legend(loc="upper left")
#plt.show()
plt.savefig("Grafiken/Diff_EVerteilung_20.pdf")
Esempio n. 35
0
#Fit
# y2 = 1/T**2
# params2 = ucurve_fit(reg.reg_linear, B, y2)
# m2,D2 = params2
# # m2 *= 4*np.pi**2*(Theta_Kugel+Theta_Aufhaengung)
# write('build/m2.tex', make_SI(m2*1e3, r'\ampere\square\meter', 'e-3', figures=1))
# write('build/D2.tex', make_SI(D2*1e5, r'\kilogram\square\meter\per\square\second', 'e-5', figures=1))

y = 4*np.pi**2*(Theta_Kugel+Theta_Aufhaengung)/T**2
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)
Esempio n. 36
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)))
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')
Esempio n. 38
0
#plt.show()
plt.clf()


# Subtraktion der Langlebigen Zerfälle
N_Rh_lang = np.array(np.exp(-popt_Rh_2[0]*T_Rh[:10])*exp(popt_Rh_2[1]))
#print(N_Rh_lang)

# Fehler der Werte
n_Rh_lang_err = np.array([m.sqrt(x) for x in N_Rh_lang])
# Fehlerbehaftete Größe
N_Rh_lang_err = unp.uarray(N_Rh_lang, n_Rh_lang_err)

N_Rh_kurz_err= np.array(np.subtract(N_Rh_err[:10], N_Rh_lang_err))
#print(N_Rh_kurz_err)
lnN_Rh_kurz = np.array([m.log(x) for x in noms(N_Rh_kurz_err)])
#print(lnN_Rh_kurz)



# Regression kurzlebig
popt_Rh_1, pcov_Rh_1 = curve_fit(f_gerade, T_Rh[:10], lnN_Rh_kurz) #sigma=stds(N_Rh_kurz_err)/noms(N_Rh_kurz_err))
errors_Rh_1 = np.sqrt(np.diag(pcov_Rh_1))
param_a_Rh_1 = ufloat(popt_Rh_1[0], errors_Rh_1[0])
param_b_Rh_1 = ufloat(popt_Rh_1[1], errors_Rh_1[1])

print("Parameter Exp. Regression a,b :", param_a_Rh_1, param_b_Rh_1)



# Plot der Messwerte für t < t*
Esempio n. 39
0
def geradeF(x, b):
    return noms(param_VI_g_M) * x + b
Esempio n. 40
0
Ip_calc = uY_p/R
Im_calc = uY_m/R

n = 1
for c in uC3:
    plt.clf()
    plt.grid()
    plt.tick_params("both", labelsize=16)
    plt.xlabel("Frequenz $f\,[\mathrm{kHz}]$", fontsize=16)
    plt.xlim(2e04, 6e04)
    plt.gca().xaxis.set_major_formatter(mpl.ticker.FuncFormatter
                                       (lambda x, _: float(x * 1e-03)))
    plt.gca().yaxis.set_major_formatter(mpl.ticker.FuncFormatter
                                       (lambda x, _: float(x * 1e03)))
    plt.ylabel("Stromstärke $I\,[\mathrm{mA}]$", fontsize=16)
    plt.plot(Xrange, noms(Strom(4, Xrange * 2 * const.pi, uC, c, R, uL)))
    plt.savefig("Grafiken/Stromverlauf{}.pdf".format(str(n)))
    n += 1

plt.clf()
plt.grid()
plt.xlabel("Frequenz $f\,[\mathrm{kHz}]$")
plt.xlim(2e04, 6e04)
plt.gca().xaxis.set_major_formatter(mpl.ticker.FuncFormatter
                                    (lambda x, _: float(x * 1e-03)))
plt.ylabel("Stromstärke $I\,[\mathrm{A}]$")
plt.plot(Xrange, noms(Strom(4, Xrange * 2 * const.pi, uC, uC3[0], R, uL)))


### Noch ein paar Plots
plt.clf()
Esempio n. 41
0
write('build/Abschirmkonstante_Zink.tex', make_SI(sigma_zink, r' ', figures=2))
write('build/Abschirmkonstante_Zirkonium.tex', make_SI(sigma_zir, r' ', figures=2))

#Moseley-Diagramm

E_k = (E_zink, E_ger, E_zir)
Z   = (30,32,40) # Zn, Ge, Zr
E_k_wurzel = np.sqrt(E_k)
params = ucurve_fit(reg_linear, Z, E_k_wurzel)
m,b = params
write('build/hcRydbergonstante.tex', make_SI(4/3*m**2, r'\electronvolt', figures=1))
write('build/Rydbergonstante.tex', make_SI(4/3*m**2/(h*c), r'\per\meter', figures=1))

plt.clf
t_plot = np.linspace(25,45, 100)
plt.plot(t_plot , reg_linear(t_plot, *noms(params)), 'b-', label='Fit')
plt.plot(Z, E_k_wurzel, 'rx', label='Messdaten')
plt.xlabel(r'Kernladungszahl  $Z$')
plt.ylabel(r'$\sqrt{E_\textrm{k} \:/\: \si{\kilo\electronvolt}}$')
plt.legend(loc='best')
plt.savefig("build/Moseley_Diagramm.pdf")
plt.close

################################ FREQUENTLY USED CODE ################################
#
########## IMPORT ##########
# t, U, U_err = np.genfromtxt('data.txt', unpack=True)
# t *= 1e-3


########## ERRORS ##########

m_g=107.67
m_gw=465.18#
Tgw=293.40
Tgm=296.63
Tg=352.19

ckz=ck(m_zw,m_z,Tzm,Tzw,Tz)
ckg=ck(m_gw,m_g,Tgm,Tgw,Tg)
#ckg=ck(465.18,107.67,295.63,293.40,352.19)


ckz=unp.uarray(np.average(ckz),np.std(ckz))
Tzm=np.average(Tzm)
print('Abweichung von ckz',ab(noms(ckz),0.23))
print('Abweichung von ckg',ab(ckg,0.715))

print('ckz',ckz)
print('ckg',ckg)
Cz=C(ckz,Molz,az,kz,rhoz,Tzm)
Cg=C(ckg,Molg,ag,kg,rhog,Tgm)


print('Cz',Cz)
print('Cg',Cg)
print('3R',3*8.3144598)

print('Abweichung von 3R z',ab(noms(Cz),3*8.3144598))
print('Abweichung von 3R g',ab(Cg,3*8.3144598))
#print(ckz)
Esempio n. 43
0
s_ds_mic *= scale_mic * 1e-3            # in m


############# STARTING FITS ##################
plot_it = True
#### KLEINER EINZELSPALT ####
zeta_0_k = zeta_0[0]                        # in m
phi_k = phi1 - zeta_0_k/L                   # in rad
phi_k_plot = phi1_plot - zeta_0_k/L         # in rad

params_k = ucurve_fit(theory_einfach, phi_k, I_k, p0=[np.sqrt(max(I_k)) / b_k_hst, b_k_hst])
A0_k, b_k = params_k

if (plot_it):
    plt.clf()
    plt.plot(phi1_plot*1e3, theory_einfach(phi_k_plot, *noms(params_k))*1e6, 'b-', label='Fit')
    plt.plot(phi1*1e3, I_k*1e6, 'rx', label='Messdaten')
    plt.xlabel(r'$\varphi \:/\: \si{\milli\radian}$')
    plt.ylabel(r'$I \:/\: \si{\micro\ampere}$')
    plt.legend(loc='best')
    plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
    plt.savefig('build/plot_klein.pdf')


#### MITTLERER EINZELSPALT ####
zeta_0_m = zeta_0[1]            # in m
phi_m = phi1 - zeta_0_m/L
phi_m_plot = phi1_plot - zeta_0_m/L

params_m = ucurve_fit(theory_einfach, phi_m, I_m, p0=[np.sqrt(max(I_m)) / b_m_hst, b_m_hst])
A0_m, b_m = params_m
#N_zu

I_s1=3.110
I_s2=2.440
I_s3=1.294
I_s4=0.721
I_s5=0.250


Austritt_1=-unp.log((I_s1/f)*(const.h**3)/(const.e*const.m_e*(const.k**2)*(T_w1**2)))*const.k*T_w1/const.e
Austritt_2=-unp.log((I_s2/f)*(const.h**3)/(const.e*const.m_e*(const.k**2)*(T_w2**2)))*const.k*T_w2/const.e
Austritt_3=-unp.log((I_s3/f)*(const.h**3)/(const.e*const.m_e*(const.k**2)*(T_w3**2)))*const.k*T_w3/const.e
Austritt_4=-unp.log((I_s4/f)*(const.h**3)/(const.e*const.m_e*(const.k**2)*(T_w4**2)))*const.k*T_w4/const.e
Austritt_5=-unp.log((I_s5/f)*(const.h**3)/(const.e*const.m_e*(const.k**2)*(T_w5**2)))*const.k*T_w5/const.e




#Austritt_Leistung=-unp.log((I_s1/f)*(const.h**3)/(const.e*const.m_e*(const.k**2)*(T_w1**2)))*const.k*T_w1/const.e

print('Austritt_1',Austritt_1)
print('Austritt_2',Austritt_2)
print('Austritt_3',Austritt_3)
print('Austritt_4',Austritt_4)
print('Austritt_5',Austritt_5)


print('Mittelwert normal',np.mean([Austritt_1,Austritt_2,Austritt_3,Austritt_4,Austritt_5]),'+-',np.std([noms(Austritt_1),noms(Austritt_2),noms(Austritt_3),noms(Austritt_4),noms(Austritt_5)]))
#print('Mittelwert np',np.mean([Austritt_2,Austritt_1]),'+-',np.std([noms(Austritt_2),noms(Austritt_1)]))
Esempio n. 45
0
R_a, Offset_a = params_max

print('R_a')
print(R_a)
R_a_2 = R_a*(-2*10.11e-3)
R_dampf_theo = 2*(unp.sqrt(L[0]/C[0]))
print('hhhhhhh')
print(L[0])
print(C[0])
write('build/R_daempfung_theo.tex', make_SI(R_1[0], r'\ohm', figures=1))
write('build/R_daempfung_mess.tex', make_SI(R_a_2, r'\ohm', figures=1))     # type in Anz. signifikanter Stellen
write('build/R_abweichung.tex', make_SI(R_a_2-R_1[0], r'\ohm', figures=1))
# write('build/loesung-b.tex', make_SI(b * 1e-3, r'\kilo\hertz', figures=1))

# Abklingzeit ausrechnen
Abklingzeit_max = np.log(np.max(Umax)/np.exp(1)/noms(Offset_a)) / R_a
Abklingzeit_theo = 2*L[0] / R_1[0]
write('build/Abklingzeit_theo.tex', make_SI(Abklingzeit_theo*1e3, r'\milli\second', figures=1))
write('build/Abklingzeit_mess.tex', make_SI(Abklingzeit_max*(-1e3), r'\milli\second', figures=1))
write('build/Abklingzeit_abweichung.tex', make_SI(-Abklingzeit_max*(-1e3)+Abklingzeit_theo*1e3, r'\milli\second', figures=1))

# plt.plot(tmax*1e3, Umax, 'rx', label='Messdaten')
# plt.plot(tmax*1e3, np.exp(noms(Offset_a)+tmax*noms(R_a)), 'b-', label='Fit')
plt.plot(text*1e3, np.abs(Uext), 'rx', label='Messdaten')
plt.plot(text*1e3, np.exp(noms(Offset_a)+text*noms(R_a)), 'b-', label='Fit')

plt.ylabel(r'$U \:/\: \si{\volt}$')
plt.xlabel(r'$t \:/\: \si{\milli\second}$')
plt.legend(loc='best')
plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
plt.savefig('build/moin_1.pdf')
Esempio n. 46
0
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')

Ma = unp.uarray(ma, stda)
Ba = unp.uarray(ba, fehler_b(stda, 1 / Ubges))
Esempio n. 47
0
#
# plt.plot(t_plot, reg.reg_linear(t_plot, *noms(params)), 'b-', label='Fit')
# plt.xlim(t_plot[0], t_plot[-1])
# # plt.xlabel(r'$t \:/\: \si{\milli\second}$')
# # plt.ylabel(r'$U \:/\: \si{\kilo\volt}$')
# plt.legend(loc='best')
# plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
# plt.savefig('build/test-plot.pdf')

# Ablesen der Grenzfrequenzen und Umrechnen
f_gr = 9
f_gr1 = 5.60
f_gr2 = 14.73
f_gr3 = 18.15

f_gr = np.exp(reg.reg_linear(f_gr, noms(m1), noms(b1)))
f_gr1 = np.exp(reg.reg_linear(f_gr1, noms(m2), noms(b2)))
f_gr2 = np.exp(reg.reg_linear(f_gr2, noms(m2), noms(b2)))
f_gr3 = np.exp(reg.reg_linear(f_gr3, noms(m2), noms(b2)))

write('build/Z_w_gr.tex', make_SI(Wellenwiderstand(2*np.pi*f_gr), r'\ohm', figures=0))
write('build/f_mess.tex', make_SI(f_gr*1e-3, r'\kilo\hertz', 'e-3',figures=1))
write('build/f1_mess.tex', make_SI(f_gr1*1e-3, r'\kilo\hertz', 'e-3',figures=1))
write('build/f2_mess.tex', make_SI(f_gr2*1e-3, r'\kilo\hertz', 'e-3',figures=1))
write('build/f3_mess.tex', make_SI(f_gr3*1e-3, r'\kilo\hertz', 'e-3',figures=1))

# Theoriewerte der Grenzfrequenzen
w_th = 2 / np.sqrt(L*C1)
w1_th = np.sqrt(2/(L*C1))
w2_th = np.sqrt(2/(L*C2))
w3_th = np.sqrt( 2/L * (C1+C2)/(C1*C2) )
Esempio n. 48
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')
Esempio n. 49
0
v_8_0 = 88 # s/mm
U_8 = 185

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









Esempio n. 51
0
# Umrechnung der Messwerte
L_1_off_err = L_1_err[:]
L_1_err = AbstandOhneOffset(L_1_err)
#print("Abstände ohne", L_1_err)

# Laden der Intensitäten, l nicht gebraucht
l , J_1 = np.loadtxt("Messdaten/Abstand_Intensitaet_1.txt", unpack=True)

# Fehlerbehaftete Intensitäten
J_1_err = unp.uarray(J_1, [j_err1 if J_1[i] < 10 else j_err2 for i in range(len(J_1))])


# Auftragen des Stroms gegen die Intensität
# linearer Fit der Messwerte
func_gerade = lambda x,a,b: a*x+b
popt_1, pcov_1 = curve_fit(func_gerade, noms(J_1_err), noms(I_k_1_err))
error_1 = np.sqrt(np.diag(pcov_1))
param_a_1 = ufloat(popt_1[0], error_1[0])
param_b_1 = ufloat(popt_1[1], error_1[1])
print("Kurzschlussstrom-Fit:")
print("Steigung:", param_a_1)
print("Y-Achsenabschnitt:", param_b_1)


# Plot der Wertepaare (J/I)
plt.plot(noms(J_1_err), noms(I_k_1_err), "xr", label="Messwerte")

# Plot der Fit-Gerade
X = np.linspace(1,30, 300)
plt.plot(X, func_gerade(X, *popt_1), color="gray", label="Regressionsgerade")
t, u_c = np.genfromtxt('a.txt', unpack=True)
U_c=unp.uarray(u_c,0.05)
T=unp.uarray(t,0.05)
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)
Esempio n. 53
0
gv = unp.uarray  #Geschw. vorwärts
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$')
Esempio n. 54
0
def main():
    args = parse_args()
    config = parse_config(args.config_file)
    if config is None:
        print('No configuration file is defined. '
              'Define one with `--config-file`.')
        sys.exit(1)

    # read dataset
    files = config['files']
    if 'filepath' in config:
        files = [config['filepath'] + f for f in files]
    kwargs = config['pandas_kwargs']

    print('Reading ', end='')
    entries = 0
    for f in files:
        rootfile = ROOT.TFile(f)
        tree = rootfile.Get(kwargs['key'])
        entries += tree.GetEntries()
    maxslices = args.max_slices
    chunksize = kwargs['chunksize']
    total = (maxslices
             if maxslices is not None and maxslices < (entries / chunksize)
             else (entries / chunksize))
    print(total * chunksize, 'events.')
    df = pd.concat([
        df for df in tqdm(
            islice(
                read_root(files, flatten=True, **kwargs), maxslices),
            total=total)])

    # rename the tagging particle branches
    df.rename(columns=dict(zip(df.columns,
        [c.replace(config['tagging_particle_prefix'], 'tp').replace('-', '_')
            for c in df.columns])),
        inplace=True)
    df['event_id'] = df.runNumber.apply(str) + '_' + df.eventNumber.apply(str)
    if 'invert_target' in config and config['invert_target']:
        df['target'] = np.sign(df.B_ID) != np.sign(df.tp_ID)
    else:
        df['target'] = np.sign(df.B_ID) == np.sign(df.tp_ID)

    # read features and selections
    try:
        if 'inclusive_mva_features' in config:
            mva_features = ['tp_' + f for f in config['inclusive_mva_features']]
        else:
            mva_features = ['tp_' + f.split(' ')[0] for f in config['selections']]
    except:
        raise ValueError('Tried to parse features for the BDT.'
                         ' Either provide well-formatted `selections` or'
                         ' define a `inclusive_mva_features` set.')

    # build BDT model and train the classifier n_cv x 3 times
    xgb_kwargs = config['xgb_kwargs']
    n_jobs = config['n_jobs']

    bootstrap_scores = []
    bootstrap_d2s = []
    nfold = (args.bootstrap_folds
             if args.bootstrap_folds is not None
             else config['n_cv'])
    print('Starting bootstrapping.')
    pbar = tqdm(total=nfold * 3)
    for _ in range(nfold):
        # yield 3-fold split for CV
        df_sets = [df.iloc[indices] for indices in NSplit(df)]

        cv_scores = []
        for i in range(3):
            df1, df2, df3 = (df_sets[i % 3].copy(),
                             df_sets[(i + 1) % 3].copy(),
                             df_sets[(i + 2) % 3].copy())
            model = XGBClassifier(nthread=n_jobs, **xgb_kwargs)
            sample_weight = (df1.target
                             if 'training_weights' in config
                                and config['training_weights']
                             else None)
            model.fit(df1[mva_features], df1.target,
                      sample_weight=df1.SigYield_sw)

            df2['probas'] = model.predict_proba(df2[mva_features])[:, 1]
            df2.reset_index(inplace=True, drop=True)
            df2_max = df2.iloc[df2.groupby('event_id')['probas'].idxmax()].copy()
            df3['probas'] = model.predict_proba(df3[mva_features])[:, 1]
            df3.reset_index(inplace=True, drop=True)
            df3_max = df3.iloc[df3.groupby('event_id')['probas'].idxmax()].copy()

            # calibrate
            calibrator = PolynomialLogisticRegression(power=4,
                                                      solver='lbfgs',
                                                      n_jobs=n_jobs)
            calibrator.fit(df2_max.probas.reshape(-1, 1), df2_max.target,
                           sample_weight=df2_max.SigYield_sw)

            df3_max['calib_probas'] = calibrator.predict_proba(df3_max.probas)[:, 1]

            score = tagging_power_score(df3_max.calib_probas,
                                        tot_event_number=get_event_number(df3_max),
                                        sample_weight=df3_max.SigYield_sw)
            bootstrap_scores.append(score)
            bootstrap_d2s.append(d2_score(df3_max.calib_probas,
                                          sample_weight=df3_max.SigYield_sw))
            pbar.update(1)

    pbar.close()
    print(dedent("""\
          Final {}-fold bootstrap performance
             D2 = {:<6}%
          ε_eff = {:<6}%""")
          .format(nfold,
                  100 * ufloat(np.mean(bootstrap_d2s),
                               np.std(bootstrap_d2s)),
                  100 * ufloat(np.mean(noms(bootstrap_scores)),
                               np.std(noms(bootstrap_scores)))))
Esempio n. 55
0
for i in range(xmin,xmax): # going thru all col
    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)
Esempio n. 56
0
def do_job_b(filename, error, P, limits):
    # Einlesen der Messdaten
    Tiefe, Delta_f, Intensity = np.genfromtxt(filename, unpack=True)

    colors = ["rx", "bx", "gx"]

    Delta_f_error = Delta_f * error
    Delta_f = unp.uarray(Delta_f, Delta_f_error)

    v = c_L / 2 / nu_0 * Delta_f / np.cos(alpha[1])  # 15 ° Winkel

    ###### Fit im Intervall limits mit quadratischer Funktion gemäß dem Gesetz von Hagen-Poiseuille
    i = 0
    start = 0
    end = 0
    for x in Tiefe:
        if x == limits[0]:
            start = i
        if x == limits[1]:
            end = i
        i += 1
    params = ucurve_fit(reg_quadratic, Tiefe[start : (end + 1)], v[start : (end + 1)])  # quadratischer Fit
    a, x0, c = params
    write("build/parameter_a.tex", make_SI(a * 1e-3, r"\kilo\volt", figures=1))
    ##### Ende Fit ########

    # Plotting
    plt.clf
    fig, ax1 = plt.subplots()
    t_plot = np.linspace(limits[0] - 0.5, limits[1] + 0.5, 50)

    # Momentangeschwindigkeiten
    Ins1 = ax1.plot(Tiefe, noms(v), "rx", label="Momentangeschwindigkeit")
    Ins2 = ax1.plot(t_plot, reg_quadratic(t_plot, *noms(params)), "r--", label="Fit")
    ax1.set_xlabel(r"$\text{Laufzeit} \:/\: \si{\micro\second}$")
    ax1.set_ylabel(r"$v \:/\: \si{\meter\per\second}$")
    if P == 45:
        ax1.set_ylim(0.45, 0.9)  # hard coded stuff ftl !

    # Streuintensitäten
    ax2 = ax1.twinx()
    Ins3 = ax2.plot(Tiefe, Intensity, "b+", label="Intensität")
    ax2.set_ylabel(r"$I \:/\: \si{\kilo\volt\squared\per\second}$")

    # Theoretische Grenzen des Rohres einzeichnen
    ax1.plot((noms(x0) - 5 / 1.5, noms(x0) - 5 / 1.5), (ax1.get_ylim()[0], ax1.get_ylim()[1]), "k:", linewidth=1)
    ax1.plot((noms(x0) + 5 / 1.5, noms(x0) + 5 / 1.5), (ax1.get_ylim()[0], ax1.get_ylim()[1]), "k:", linewidth=1)
    ax1.plot(
        (noms(x0) - 5 / 1.5 - 2.5 / 2.5, noms(x0) - 5 / 1.5 - 2.5 / 2.5),
        (ax1.get_ylim()[0], ax1.get_ylim()[1]),
        "k:",
        linewidth=1,
    )
    ax1.plot(
        (noms(x0) + 5 / 1.5 + 2.5 / 2.5, noms(x0) + 5 / 1.5 + 2.5 / 2.5),
        (ax1.get_ylim()[0], ax1.get_ylim()[1]),
        "k:",
        linewidth=1,
    )

    Ins = Ins1 + Ins2 + Ins3
    labs = [l.get_label() for l in Ins]
    ax1.legend(Ins, labs, loc="upper left")
    plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
    plt.savefig("build/Plot_b_P" + str(P) + ".pdf")
Esempio n. 57
0
        'Druck': p,
        'Weglange': w,
        'verhaeltnis': verhaeltnis
    }


####### Frank-Hertz-Kurve

abstand_frank_hertz, spannung_frank_hertz = np.genfromtxt(
    'spannung_abstand_frankhertzkurve_188grad.txt', unpack=True)
anzahl, abstaende_maxima = np.genfromtxt('abstaende_frankhertzkurve_188.txt',
                                         unpack=True)

parmeter_frank_hertz = linfit(abstand_frank_hertz, spannung_frank_hertz, 1, 1,
                              1, 1, 'frank_hertz_kuvre')
anregungsspannung = g(noms(parmeter_frank_hertz['Steigung']), abstaende_maxima,
                      noms(parmeter_frank_hertz['Achsenabschnitt']))
anregungspannung_u = ufloat(
    np.mean(anregungsspannung),
    np.std(anregungsspannung, ddof=1) / np.sqrt(len(anregungsspannung)))
anregungsenergie = anregungspannung_u  #eV

print('\n \n \n')
print('Parameter Spannungs Fit Frank (m,b)', parmeter_frank_hertz['Steigung'],
      parmeter_frank_hertz['Achsenabschnitt'])
print('Anregungsenergie (eV)', anregungsenergie)
wellenlaenge = (h * speed_of_light) / (anregungsenergie * e)

print('Wellenlänge', wellenlaenge)
K_frank = 2 * anregungspannung_u - g(
    noms(parmeter_frank_hertz['Steigung']), 3.1,
Esempio n. 58
0
def mean(values, axis=0):
    return unp.uarray((np.mean(noms(values), axis=axis), scipy.stats.sem(noms(values), axis=axis)))
Esempio n. 59
0
#omega_x.SetParLimits(2, 5e-14 * 0.52, 4e-13)

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)
Esempio n. 60
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