def test_lineare_regression_mit_korrelation(): sigma = 1.0 xmin = 100. xmax = xmin + 20. x = np.arange(xmin, xmax) y = np.random.normal(3. + 2. * x, sigma) ey = 0. * x + sigma # Um die Korrelation zwischen a und b zu minimieren, # transformieren wir x geeignet x0 = 0.5 * (xmin + xmax) # x0 = 0 x = x - x0 # Aufruf der linearen Regression a,ea,b,eb,chiq,corr = \ analyse.lineare_regression(x,y,ey) print('a=%f+-%f, b=%f+-%f (x0=%f), chi2=%f, corr=%f' % \ (a,ea,b,eb,x0,chiq,corr)) # Ruecktransformation x = x + x0 b = b - a * x0 figure() subplot(2, 1, 1) title('Lineare Regression') errorbar(x, y, yerr=ey, fmt='o', color='blue') plot(x, a * x + b, '-') xlim(xmin - 1., xmax + 1.) xlabel('x') ylabel('y') subplot(2, 1, 2) title('Residuenplot') errorbar(x, y - (a * x + b), yerr=ey, fmt='o', color='blue') plot(x, 0. * x) xlim(xmin - 1., xmax + 1.) ylim(-5, 5) xlabel('x') ylabel('y-(ax+b)') show()
def test_lineare_regression(): sigma = 1.0 xmin = -20. xmax = 20. # wuerfele Daten x = np.arange(xmin, xmax) y = np.random.normal(3. + 0.5 * x, sigma) ey = 0. * x + sigma # Aufruf der linearen Regression a,ea,b,eb,chiq,corr = \ analyse.lineare_regression(x,y,ey) print('a=%f+-%f, b=%f+-%f, chi2=%f, corr=%f' % (a, ea, b, eb, chiq, corr)) figure() subplot(2, 1, 1) title('Lineare Regression') errorbar(x, y, yerr=ey, fmt='o', color='blue') plot(x, a * x + b, '-') xlim(xmin - 1., xmax + 1.) xlabel('x') ylabel('y') grid() subplot(2, 1, 2) title('Residuenplot') errorbar(x, y - (a * x + b), yerr=ey, fmt='o', color='blue') plot(x, 0. * x) # Linie bei Null xlim(xmin - 1., xmax + 1.) ylim(-5, 5) xlabel('x') ylabel('y-(ax+b)') show()
logUR = np.log((UR - Uoffset) / UR0) # Messbereich -> Digitalisierungsfehler (Cassy-ADC hat 12 bits => 4096 mögliche Werte) sigmaU = 20.0 / 4096. / np.sqrt(12.) sigmaLogUR = sigmaU / UR # Extrahiere Daten für Fit t_fit, logUR_fit = analyse.untermenge_daten(t, logUR, tmin, tmax) _, sigmaLogUR_fit = analyse.untermenge_daten(t, sigmaLogUR, tmin, tmax) errorbar(t_fit, logUR_fit, yerr=sigmaLogUR_fit, fmt='.') xlabel('t / ms') ylabel('$\log\,U/U_0$') # Lineare Regression zur Bestimmung der Zeitkonstanten a, ea, b, eb, chiq, corr = analyse.lineare_regression( t_fit, logUR_fit, sigmaLogUR_fit) tau = 1. / a sigma_tau = tau * ea / a print('tau = (%g +- %g) ms b = (%g +- %g) chi2/dof = %g / %g' % (tau, sigma_tau, b, eb, chiq, len(t_fit) - 2)) plot(t_fit, a * t_fit + b, color='red') subplot(3, N, m + 2 * N) # Residuenplot resUR = logUR_fit - (a * t_fit + b) eresUR = sigmaLogUR_fit errorbar(t_fit, resUR, yerr=eresUR, fmt='.') xlabel('t / ms') ylabel(r'$\log\,U/U_0 - (t/\tau + b)$') show()
#--------------------------------------------------- wsf = np.array(wsf) ws = np.array(ws) print(wsf) print(ws) sTs = np.array(sTs) sTsf = np.array(sTsf) kappa = np.array((wsf**2 - ws**2) / (wsf**2 + ws**2)) print(kappa) skappa = 4 * np.power(ws * wsf, 3) * (scipy.pi * 2)**(-1) * np.power( ws**2 + wsf**2, -2) * np.sqrt((sTs / ws)**2 + (sTsf / wsf)**2) print(skappa) m, em, b, eb, chiq, corr = anal.lineare_regression(lF**-2, np.array(kappa)**(-1) - 1, skappa) print(b) print(eb) plt.errorbar(lF**-2, kappa**-1, skappa / (kappa)**2, fmt="x", markersize=4, capsize=3) plt.plot(np.arange(min(lF**-2) - 0.2, max(lF**-2) + 0.2, 0.1), np.arange(min(lF**-2) - 0.2, max(lF**-2) + 0.2, 0.1) * m + b) plt.title("Die lineare Regression bzgl. $\kappa^{-1}$") plt.xlabel("$l_F^{-2}$")
mp, sp, errp = Rauschmessung.round_good(np.mean(p), np.std(p), np.std(p) / np.sqrt(len(p))) errstatp = np.sqrt((Rauschmessung.sp / np.sqrt(len(p)))**2 + sigma_p_dig**2) #errT=sT0/np.sqrt(len(T)) #errp=sigmap #Plotten print("\nDichtigkeitsmessung") print("Fehler auf jeden gemessenen Druckwert") print("s**2 = s_Gerät**2+s_Rausch**2=" + str(Rauschmessung.round_good(0.0, 0.0, sigmap**2)[2]) + " hPa") plt.plot(t, p) #Regression m, em, b, eb, chiq, corr = ana.lineare_regression(t, p, sigmap * np.ones(len(p))) print("\nErgebnis der Regression auf die Dichtigkeitskurve:") print( 'm = (%g +- %g) hPa/s, b = (%g +- %g) hPa, chi2/dof = %g / %g corr = %g' % (m, em, b, eb, chiq, len(t) - 2, corr)) m, x, em = Rauschmessung.round_good(m, 0.0, em) print( 'Verlust: ({} +-{}) mbar/s bei einem Innendruck von etwa {}+-{} mbar\n' .format(m, em, mp, errp)) #so genehmigt plt.plot(t, m * t + b, color='green') plt.title("Dichtigkeitsmessung\nVerlust: ({} +- {}) mbar/s".format(m, em)) plt.xlabel('Zeit/s') plt.ylabel(u'Druck/hPa') plt.savefig("Images/Kalib_Dichtigkeitsmessung.pdf") plt.figure()
emax = s_U_Ger * np.ones(len(maxima[0])) #Residum plt.axhline(0) plt.plot(maxima[0], U[0]*np.exp(-d*np.array(maxima[0]))-maxima[1], label = "Residum exp") plt.show() plt.legend() plt.close() if len(maxima[0])>3: plt.plot(maxima[0], maxima[1], marker="x") if d!=1.0: plt.plot(t, U[0]*np.exp(-d*np.array(t)), label = "Einhüllende") print("Die Dämpfungskonstante Delta berechnet aus der Amplitude: \n d=" + str(np.round(d,4)) + "+-" + str(np.round(ed,4))) #Berechnung von Delta aus der linearen Regression #TODO: Fehler zu groß! d2,ed2,b,eb,chiq,corr = anal.lineare_regression(np.array(maxima[0]), np.log(maxima[1]), np.log(emax)) print("Die Dämpfungskonstante Delta berechnet aus der linearen Regression: \n d=" + str(-d2) + "+-" + str(ed2)) #plot plt.title("Entladung des Kondensators über den Schwingkreis \n R = " +str(R[i]) + " $\Omega$") plt.errorbar(maxima[0],maxima[1],yerr=emax, fmt="x") plt.axvline(x=t[offsetkorr[i]], color="red", linestyle = "--") plt.plot(t, I*20, label="20$\cdot$I") plt.plot(t, np.exp(d2*np.array(t)+b), label = "Einhüllende2") plt.plot(t, U, label="U") plt.savefig("Images/C_"+str(R[i])+".pdf") plt.legend() plt.show() plt.close() #Residum2 plt.axhline(0)
n_0 = np.array([1, 2, 4, 5, 6]) for i in range(5): s_f_0 = np.append( s_f_0, np.std([ fmax_ablesen[i], fmax_peakfinder[i], fmax_maxima[i], fmax_matlab[i] ]) / 2) f_max_0 = np.append( f_max_0, np.average([ fmax_ablesen[i], fmax_peakfinder[i], fmax_maxima[i], fmax_matlab[i] ])) n = n_0[:-1] #ignoriere den letzten Punkt s_f = s_f_0[:-1] f_max = f_max_0[:-1] a, ea, b, eb, chiq, corr = anal.lineare_regression(n, f_max, s_f) plt.errorbar(n, f_max, s_f, ls="None", markersize=5, marker="x") plt.errorbar(n_0[4], f_max_0[4], s_f_0[4], fmt="o", marker="x", markersize=5, color="red") plt.plot(np.arange(0.5, 6.5, 0.01), a * np.arange(0.5, 6.5, 0.01) + b, label="f = (" + str(np.round(a, 2)) + "$\pm {}$) Hz*n+(".format(np.round(ea, 2)) + str(np.round(b, 2)) + "$\pm {}$)Hz \n $Chi^2 /f = {}/{} ≈ {}$".format( np.round(eb, 2), np.round(chiq, 2), 2, np.round(chiq / 2, 2))) plt.title("Lindeare Regression der Resonanzfrequenzen")
def pltmitres(x,y,ey,ex=0, xlabel="x", ylabel="y", xunit="", yunit="", title="", ratios=[2,1], regdata =False, precision=2,capsize=5, markersize=5): """ Erstellen eines Plots mit dazugehörigem Residumplot Parameter --------- x,y,ex,ey: Daten mit Fehler (ex optionell) xlabel,ylabel: Titel der Achsen xunit,yunit: Einheit der Werte als String title: Titel des Plots ratios: Flächenverhältnis zwischen Daten- und Residumplot regdata : Falls wahr, a,ea,b,eb,chiq,corr der Regression werden auch zurückgegeben precision: Nachkommastellen der Parameter a,b Returns -------- ax : Achsen des Datenplots (0) bzw. Residumplots (1) (a, ea), (b,eb),chiq,corr: Ergebnisse der linearen Regression (falls regdata = True) Verwendung ---------- >>> import numpy as np >>> import praktikum_addons.bib as bib >>> import matplotlib.pyplot as plt >>> x = np.arange(0.1,1.3,0.1) >>> y = np.sin(x) >>> ex = np.ones(len(x))*0.03 >>> ey = np.ones(len(y))*0.1 >>> ax = bib.pltmitres(x,y, ex, ey, yunit = "s", xunit="m", ratios=[7,1]) >>> ax[0].set_ylim(top=2) >>> plt.show() """ x = np.array(x) y = np.array(y) ex = np.array(ex) ey = np.array(ey) if ex.all()==0: a,ea,b,eb,chiq,corr = anal.lineare_regression(x,y,ey) else: a,ea,b,eb,chiq,corr = anal.lineare_regression_xy(x,y,ex,ey) fig, (ax1,ax2) = plt.subplots(2, 1,gridspec_kw = {'height_ratios':ratios}) ax1.set_title(title) ax1.errorbar(x,y, ey, np.ones(len(x))*ex, marker="x", linestyle="None", capsize=capsize, markersize=markersize) l = max(x)-min(x) x2 = np.arange(min(x)-l*0.1, max(x)+l*0.1, l/1000) y2 = a*x2+b ax1.plot(x2, y2, color="orange") if yunit!="": ax1.set_ylabel(ylabel+" [{}]".format(yunit)) else: ax1.set_ylabel(ylabel) ax1.legend(title="Lineare Regression\n{1} = ({2:.{0}f} ± {3:.{0}f}){4} $\cdot$ {5}+({6:.{0}f}±{7:.{0}f}){8}\n$\chi^2 /NDF={9:.4f}$".format(precision,ylabel,a,ea, yunit+"/"+xunit,xlabel,b, eb, yunit, chiq/(len(x)-2)), loc=1) ax2.errorbar(x,y-a*x-b, np.sqrt(ex**2*a**2+ey**2), marker="x", linestyle="None", capsize=capsize, markersize=markersize) ax2.axhline(0, color="orange") if xunit!="": plt.xlabel(xlabel+" [{}]".format(xunit)) else: plt.xlabel(xlabel) plt.tight_layout() if regdata : return (ax1, ax2), (a,ea),(b,eb),chiq,corr else: return (ax1, ax2)
tS1 = np.array([0.155, 0.465, 0.78, 1.085, 1.41, 1.72, 2.035, 2.345, 2.655, 2.975]) mS1 = np.arange(1,11,1) tS2 = np.array([0.38, 1.02, 1.66, 2.33, 2.99]) mS2 = np.arange(1,6,1) tS4 = np.array([0.075, 0.24, 0.42, 0.595, 0.76, 0.93, 1.10, 1.27, 1.445, 1.62, 1.795, 1.965, 2.135, 2.305, 2.47, 2.64, 2.81, 2.975]) mS4 = np.arange(1,19,1) # Lineare Regressionen resultierende Schwingung errtR1 = np.full((len(tR1),),0.0002) errtR3 = np.full((len(tR3),),0.0005) errtR4 = np.full((len(tR4),),0.0004) regR1 = analyse.lineare_regression(nR1, tR1, errtR1) regR2 = analyse.lineare_regression(nR2, tR2, errtR1) regR3 = analyse.lineare_regression(nR3, tR3, errtR3) regR4 = analyse.lineare_regression(nR4, tR4,errtR4) # Lineare Regressionen Schwebungsschwingung errtS1 = np.full((len(tS1),),0.005) errtS2 = np.full((len(tS2),),0.01) errtS4 = np.full((len(tS4),),0.005) regS1 = analyse.lineare_regression(mS1, tS1, errtS1)
n[0] = 1 period_p = [0.48, 15.38, 31.94, 48.48, 65.04, 81.56, 98.11, 114.68, 131.28, 147.84, 164.36, 180.9, 197.46, 214.02, 230.56, 247.12, 263.68, 280.22, 296.8, 313.34] period_s = [1.5, 16.44, 33.01, 49.59, 66.14, 82.73, 99.32, 115.86, 132.46, 149.05, 165.64, 182.18, 198.8, 215.34, 231.92, 248.47, 265.08, 281.62, 298.23, 314.83] eperiod_p = np.full((20,),0.02) eperiod_s = np.full((20,),0.02) nreg = np.arange(0,200,1) #Lineare Regression der Daten zur Bestimmung der Frequenz res_p = analyse.lineare_regression(n,period_p,eperiod_p) omega_p = 2*np.pi/res_p[0] eomega_p = 2*np.pi/(res_p[0]**2)*res_p[1] res_s = analyse.lineare_regression(n,period_s,eperiod_s) omega_s = 2*np.pi/res_s[0] eomega_s = 2*np.pi/(res_s[0]**2)*res_s[1] """ f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row', gridspec_kw={'height_ratios': [5, 2]}) ax1.plot(nreg,res_p[0]*nreg+res_p[2], linestyle="--", color = 'black') ax1.errorbar(n,period_p, yerr = 0.02, color='red', fmt='.', marker ='o') ax1.set_ylabel('$t$ / $s$') ax1.grid() ax1.set_ylim(-10,350) ax1.set_title('Messung mit Pendelkörper')
reg2plus = np.array([]) reg2minus = np.array([]) #Frequenzen und Dämpfungen bestimmen (Regression) for i in range(1, 6, 1): n = np.arange(1, 1 + dic1[i].size, 1) data = cassy.CassyDaten(dic2[i]) time = data.messung(1).datenreihe('t').werte vol = data.messung(1).datenreihe('U_B1').werte x = time[dic1[i]] ex = np.full((dic1[i].size, ), 1e-05 / np.sqrt(12)) y = np.log(np.abs(vol[dic1[i]]) - dic3[i]) ey = 4.8e-03 * 1 / (np.abs(vol[dic1[i]]) - dic3[i]) ey_sys = 0.01 * np.sqrt(vol[dic1[i]]**2 + dic3[i]**2) / (np.abs(vol[dic1[i]]) - dic3[i]) res1 = analyse.lineare_regression(n, x, ex) res2 = analyse.lineare_regression_xy(x, y, ex, ey) res2plus = analyse.lineare_regression_xy(x, y + ey_sys, ex, ey) res2minus = analyse.lineare_regression_xy(x, y - ey_sys, ex, ey) reg1 = np.concatenate((reg1, res1)) reg2 = np.concatenate((reg2, res2)) reg2plus = np.concatenate((reg2plus, res2plus)) reg2minus = np.concatenate((reg2minus, res2minus)) #Plot f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', gridspec_kw={'height_ratios': [5, 2]}) #1. Regression Vanilla Plot [Zeiten in Mikrosekunden]
I_2E=IE[N2] #C_UA=(tA[N2]-tA[N1])/Widerstand.R/ana.log(U_1A/U_2A) #TODO: anders umzustellen C_UE=(tA[N2]-tA[N1])/Widerstand.R/ana.log(U_1E/U_2E) C_IA=(tA[N2]-tA[N1])/Widerstand.R/ana.log(I_1A/I_2A) C_IE=(tA[N2]-tA[N1])/Widerstand.R/ana.log(I_1E/I_2E) ''' #linus #UA_log=ana.log(UA) UE_log = ana.log(UE) IA_log = ana.log(IA[wvm:]) tA = tA[wvm:] #IE_log=ana.log(IE) #Parameter Tau bestimmen: #Hier ist tau=-1/tau tauE, etauE, bE, ebE, chiqE, corr = ana.lineare_regression( np.array(tE), np.array(UE_log), np.array(Widerstand.U_err_stat / UE)) tauA, etauA, bA, ebA, chiqA, corr = ana.lineare_regression( np.array(tA), np.array(IA_log), np.array(Widerstand.I_err_stat / IA[wvm:])) x, tauE, etauE = Widerstand.round_good(0, tauE, etauE) x, tauA, etauA = Widerstand.round_good(0, tauA, etauA) if __name__ == '__main__': #Plot Tau-Bestimmung Entladung plt.plot(tE, UE_log, 'bo', label='logarrithmierte Messreihe U_Entladung') plt.plot( tE, tauE * tE + bE, color='brown', label=u'Geradenanpassung $\\tau$*x+b mit $\\tau$={}, b={} mit Chi²/f={}' .format(tauE, round(bE, 2), round(chiqE / len(tE), 2)))
for i in range(len(Ri)): axvline(x=Ri[i], color='red') text(Ri[i], 0.075, '$R_{{{}}}$={:.2f}'.format(indize[i], Ri[i])) xlabel('R / $\\Omega$') ylabel('U / V') savefig('stehendeWelle.pdf', bbox_inches='tight') show() Wellenlaenge = (Ri[len(Ri) - 1] - Ri[0]) * K * 2 / 33 print(Wellenlaenge) print( '1. Auswertung: gesamter Abstand=3.283 kOhm = 53.51cm ---- Wellenlaenge=3.24' ) a, ea, b, eb, chiq, corr = analyse.lineare_regression(indize, Ri, eRi) print('\n \n 2.Auswertung') print('Ergebnis: a=%f+-%f, b=%f+-%f, chi2=%f, corr=%f' % (a, ea, b, eb, chiq, corr)) figure() #title('Lin. Reg. der Widerstandpeaks bei stehenden Wellen') errorbar(indize, Ri, yerr=eRi, linestyle='none', marker='o', markersize=4, elinewidth=1, zorder=1) plot(indize, a * indize + b, '-', zorder=2)