def burkert_mass_22(self): a_h = self.R_halo()[0] rho0 = self.burkert_rho0() R22 = 2.2 * self.baryonic_scalelength() a = 2 * math.pi * rho0 * a_h**3 b = (unp.log((R22 + a_h) / a_h) + 0.5 * unp.log( (R22**2 + a_h**2) / a_h**2) - unp.arctan(R22 / a_h)) self.M_burkert_22 = a * b return self.M_burkert_22
def Gompertz_i(param, y): if certain: x = np.log(y / param[0]) x = np.log(-x / param[1]) x = -x / param[2] else: x = unp.log(y / param[0]) x = unp.log(-x / param[1]) x = -x / param[2] return x
def burkert_rho0(self): exists = 'rho0' in self.__dict__ if exists is False: a_h, r200 = self.R_halo() M_h = self.M_halo() self.rho0 = (M_h / ((2 * np.pi * a_h**3) * (unp.log( (r200 + a_h) / a_h) + 0.5 * unp.log( (r200**2 + a_h**2) / a_h**2) - unp.arctan(r200 / a_h)))) return self.rho0
def ExtremeValue_i(param, y): x = -(-param[0] + y) / param[0] try: if certain: x = np.log(-np.log(x)) else: x = unp.log(-unp.log(x)) x = (x - param[2]) / param[1] except: x = np.zeros(np.size(y)) return x
def calculateNApproximate(self, freq, Habs, Hphase, d): n0 = 1 omega = 2 * np.pi * freq n = n0 - c / (omega * d) * Hphase if isinstance(Habs[0], float): kappa = c / (omega * d) * \ (np.log(4 * n * n0 / (n + n0)**2) - np.log(Habs)) else: kappa = c / (omega * d) * (unumpy.log(4 * n * n0 / (n + n0)**2) - unumpy.log(Habs)) return n, -kappa
def burkert_arm_number(self, y=1, X=1.5): M_d = self.M_disc + self.M_hi R_d = self.baryonic_scalelength() rho0 = self.burkert_rho0() a_h = self.R_halo()[0] a = unp.exp(2 * y) / X R = y * 2 * R_d c = (2 * np.pi * rho0 * R**3 / M_d) * (1 / (4 * y**2)) * ( (R**2 / (R**2 + a_h**2)) + (R / (a_h * (R**2 / a_h**2 + 1))) + unp.log(1 + R / a_h) + unp.log(1 + (R / a_h)**2) - unp.arctan(R / a_h)) self.m_burkert = a * c return self.m_burkert
def ChapmanRichards_i(param, y): if certain: x = np.log(1 - ((y / param[0])**(1 / param[2]))) else: x = unp.log(1 - ((y / param[0])**(1 / param[2]))) x = -x / param[1] return x
def fit_roughness(wavelengths, transmission): p0 = { 'log_I0': (np.log(100), ''), '\\beta_2': (1, 'micron$^2$'), '\\beta_4': (0, 'micron nm$^3$'), } params, meta, residuals = fit(roughness_model, wavelengths, unp.log(transmission), p0) # Compute roughness beta_0, beta_2, beta_4 = params if beta_2.n > 0: theta = np.arcsin(np.sin(45 * np.pi / 180) * ior) delta_n = ior - 1 roughness = unp.sqrt(2 * beta_2) / (delta_n * np.cos(theta)) else: roughness = ufloat(0, 0) I0 = np.e**beta_0 return [ I0, roughness, *params, meta[1]['chisq/dof'], ]
def Korf_i(param, y): if certain: x = (-np.log(y / param[0]) / param[1])**(-1 / param[2]) else: x = (-unp.log(y / param[0]) / param[1])**(-1 / param[2]) return x
def monomolecular_i(param, y): if certain: x = np.log(-(-param[0] + y) / (param[0] * param[2])) else: x = unp.log(-(-param[0] + y) / (param[0] * param[2])) x = -x / param[1] return x
def vonBertalanffy_i(param, y): if certain: x = np.log(1 - ((y / param[0])**(1 / 3))) else: x = unp.log(1 - ((y / param[0])**(1 / 3))) x = (param[1] * param[2] - x) / param[1] return x
def NegativeExponential_i(param, y): if certain: x = (param[1] * param[2] - np.log(-(-param[0] + y) / param[0])) / param[1] else: x = (param[1] * param[2] - unp.log(-(-param[0] + y) / param[0])) / param[1] return x
def analyze_spektrallinien(fileprefix, figindex, crstl, sl, d=None, y=None): data = np.append(np.loadtxt(fileprefix+'.b.1.txt', skiprows=1), np.loadtxt(fileprefix+'.b.2.txt', skiprows=1), axis=0) b, n = data[:,0], data[:,1] n = unp.uarray(n, np.sqrt(n*20)/20) sl = [ [(b >= bounds[0]) & (b <= bounds[1]) for bounds in sl_row] for sl_row in sl] def fit_gauss(x, m, s, A, n_0): return A/np.sqrt(2*const.pi)/s*np.exp(-((x-m)**2)/2/(s**2))+n_0 r = [] plt.clf() papstats.plot_data(b,n) papstats.savefig_a4('3.'+str(figindex)+'.a.png') plt.clf() plt.suptitle('Diagramm 3.'+str(figindex)+u': Spektrallinien von Molybdän bei Vermessung mit einem '+crstl+'-Kristall') for i in range(2): r.append([]) # Linie for k in range(2): # Ordnung b_k = b[sl[i][k]] n_k = n[sl[i][k]] xspace = np.linspace(b_k[0], b_k[-1], num=1000) plt.subplot(2,2,i*2+k+1) plt.xlim(xspace[0], xspace[-1]) if i==1: plt.xlabel(u'Bestrahlungswinkel '+r'$\beta \, [^\circ]$') if k==0: plt.ylabel(u'Zählrate '+r'$n \, [\frac{Ereignisse}{s}]$') plt.title('$K_{'+(r'\alpha' if i==0 else r'\beta')+'}$ ('+str(k+1)+'. Ordnung)') papstats.plot_data(b_k, n_k) # Gauss-Fit popt, pstats = papstats.curve_fit(fit_gauss, b_k, n_k, p0=[b_k[0]+(b_k[-1]-b_k[0])/2, (b_k[-1]-b_k[0])/4, np.sum(n_k).n, n_k[0].n]) plt.fill_between(b_k, 0, unp.nominal_values(n_k), color='g', alpha=0.2) FWHM = popt[1]*2*unp.sqrt(2*unp.log(2)) plt.hlines(popt[3].n+(fit_gauss(xspace, *unp.nominal_values(popt)).max()-popt[3].n)/2, popt[0].n-FWHM.n/2, popt[0].n+FWHM.n/2, color='black', lw=2, label='$'+papstats.pformat(FWHM, label='FWHM', unit=r'^\circ')+'$') papstats.plot_fit(fit_gauss, popt, xspace=xspace, plabels=[r'\mu', r'\sigma', 'A', 'n_0'], punits=['^\circ', '^\circ', 's^{-1}', 's^{-1}']) plt.ylim(unp.nominal_values(n_k).min()-n_k[unp.nominal_values(n_k).argmin()].s, unp.nominal_values(n_k).max()+(unp.nominal_values(n_k).max()-unp.nominal_values(n_k).min())) plt.legend(loc='upper center', prop={'size':10}) b_S = unc.ufloat(popt[0].n, np.abs(popt[1].n)) print "Winkel:", papstats.pformat(b_S, unit='°', format='.2u') if y is None: r[i].append(y_bragg(b_S, n=k+1)) print "Wellenlänge der Linie:", papstats.pformat(r[i][k]/const.pico, label='y', unit='pm', format='.2u') if d is None: r[i].append((k+1)*y[i][k]/unc.umath.sin(b_S*const.degree)) print "Gitterkonstante:", papstats.pformat(r[i][k]/const.pico, label='a', unit='pm', format='.2u') papstats.savefig_a4('3.'+str(figindex)+'.png') return r
def calculate_c(A1, A2, R, t1, t2): t = t2 - t1 t = uarray((t, terror)) A1 = uarray((replace0(A1), 1)) A2 = uarray((replace0(A2), 1)) # http://en.wikipedia.org/wiki/RC_circuit # if A1 > 0 and A2 > 0 and R > 0 and A1 != A2: c = -t / (R * unumpy.log(A2 / A1)) return c
def total_shear(self, y=1, halo='hernquist'): r = 2 * y * self.baryonic_scalelength() a_b = self.R_bulge M_b = self.M_bulge kappa2_b = M_b * (4 / (r * (r + a_b)**2) - (3 * r + a_b) / (r * (r + a_b)**3)) omega2_b = M_b * (1 / (r * (r + a_b)**2)) R_d = self.R_disc M_d = self.M_disc C = M_d / (2 * R_d) kappa2_d = C * ((r / (4 * R_d) * (3 * I(1, y) * K(0, y) - 3 * I(0, y) * K(1, y) + I(1, y) * K(2, y) - I(2, y) * K(1, y))) + 4 * (I(0, y) * K(0, y) - I(1, y) * K(1, y))) omega2_d = C * (I(0, y) * K(0, y) - I(1, y) * K(1, y)) if halo == 'hernquist': a_h = self.R_halo()[0] M_h = self.M_halo_hernquist() kappa2_h = M_h * (4 / (r * (r + a_h)**2) - (3 * r + a_h) / (r * (r + a_h)**3)) omega2_h = M_h * (1 / (r * (r + a_h)**2)) else: a_h = self.R_halo()[0] rho0 = self.burkert_rho0() C = 2 * math.pi * rho0 * a_h**3 kappa2_h = (C / r**3) * (r**2 / (r**2 + a_h**2) - r / (a_h * ( (r / a_h)**2 + 1)) + r / (r + a_h) + unp.log( (r + a_h) / a_h) + (1 / 2) * unp.log( (r**2 + a_h**2) / a_h**2) - unp.arctan(r / a_h)) omega2_h = (C / r**3) * (unp.log( (r + a_h) / a_h) + (1 / 2) * unp.log( (r**2 + a_h**2) / a_h**2) - unp.arctan(r / a_h)) omega2 = omega2_b + omega2_d + omega2_h kappa2 = kappa2_b + kappa2_d + kappa2_h self.Gamma = 2 - kappa2 / (2 * omega2) return self.Gamma
def func_err_prop(func, x, p): if func == func_log: # return p[0]*unumpy.log((extrapolate_times + 1 +p[1])) + p[2] return p[0] * unumpy.log(extrapolate_times / p[1] + 1) + p[2] if func == func_power: return p[0] * (extrapolate_times + p[2])**p[1] if func == func_stretched_exp: return p[0] * unumpy.exp(-(extrapolate_times / p[1])**p[2]) + bo else: sys.exit("Error")
def func_err_prop(func, x,p): if func == func_log: # return p[0]*unumpy.log((extrapolate_times + 1 +p[1])) + p[2] return p[0]*unumpy.log(extrapolate_times/p[1] + 1 ) + p[2] if func == func_power: return p[0]*(extrapolate_times+p[2])**p[1] if func == func_stretched_exp: return p[0]*unumpy.exp(-(extrapolate_times/p[1])**p[2]) + bo else: sys.exit("Error")
def evaluate(energy, amplitude, reference, alpha, beta): # cast dimensionless values as np.array, because of bug in Astropy < v1.2 # https://github.com/astropy/astropy/issues/4764 try: xx = (energy / reference).to('') exponent = -alpha - beta * np.log(xx) except AttributeError: from uncertainties.unumpy import log xx = energy / reference exponent = -alpha - beta * log(xx) return amplitude * np.power(xx, exponent)
def evaluate(energy, amplitude, reference, alpha, beta): """Evaluate the model (static function).""" try: xx = (energy / reference).to("") exponent = -alpha - beta * np.log(xx) except AttributeError: from uncertainties.unumpy import log xx = energy / reference exponent = -alpha - beta * log(xx) return amplitude * np.power(xx, exponent)
def Weibull_i(param, y): try: if certain: x = -np.log(-(-param[0] + y) / param[0]) / param[1] x = x**(-1 / param[2]) else: x = -unp.log(-(-param[0] + y) / param[0]) / param[1] x = x**(-1 / param[2]) except: x = np.zeros(np.size(y)) return x
def bethe(E, n, z, I, m): print(E, n, z, I, m) v = unp.sqrt((2 * E / m).to_base_units().magnitude) * (u.meter/u.second) print(v.to('m/s')) ln = unp.log(((2 * m_e * v**2) / I).to_base_units().magnitude) a = (4 * np.pi * n * z**2) / (m_e * v**2) b = ((c.e * u.coulomb)**2 / (4 * np.pi * epsilon_0))**2 return (a * b * ln).to('MeV / cm')
def evaluate(energy, amplitude, reference, alpha, beta): """Evaluate the model (static function).""" # TODO: can this comment be removed? # cast dimensionless values as np.array, because of bug in Astropy < v1.2 # https://github.com/astropy/astropy/issues/4764 try: xx = (energy / reference).to("") exponent = -alpha - beta * np.log(xx) except AttributeError: from uncertainties.unumpy import log xx = energy / reference exponent = -alpha - beta * log(xx) return amplitude * np.power(xx, exponent)
def Te_O3(OIII4363, OIII4959, OIII5007, Hbeta): ''' Computing T_e from [O III] λλ 4363, 4959, 5007, using the method from Mas-Hesse's code (any better options out there?) ''' Te = pd.DataFrame(OIII4363.copy()) OIII4363 /= Hbeta OIII4959 /= Hbeta OIII5007 /= Hbeta # First time # Te['Te4'] = 3.297 / ( # ((OIII4959 + OIII5007) * 1 ** 0.05) / (OIII4363 * 7.76) # ) # DEBUG Te['Te4'] = 3.297 / unp.log( ((OIII4959 + OIII5007) * 1 ** 0.05) / (OIII4363 * 7.76) ) Te.loc[(Te['Te4'] < 0.), 'Te4'] = np.nan Te['Te4'] = 3.297 / unp.log( ((OIII4959 + OIII5007) * Te['Te4'] ** 0.05) / (OIII4363 * 7.76) ) Te['Te'] = Te['Te4'] * 1.e4 #return Te Te = Te.drop('OIII4363', axis=1) #print Te #Te.to_string()#.head() return Te
def flux2mag(flux, err_flux): # select the value without problem index_proper_value = (err_flux > 0) & (flux > 0) # find the mag in proper values. uflux = unumpy.uarray(flux[index_proper_value], err_flux[index_proper_value]) umag = -2.5 * unumpy.log(uflux, 10) proper_mag = unumpy.nominal_values(umag) proper_err_mag = unumpy.std_devs(umag) # fill up the rest with -999 mag = np.full(len(flux), -999.0) err_mag = np.full(len(flux), -999.0) mag[index_proper_value] = proper_mag err_mag[index_proper_value] = proper_err_mag return mag, err_mag
def crit_gni(Re,Pr): """ Calculeaza criteriul Gnielinski Intrare ------- Re: criteriul Reynolds Pr: criteriul Prandtl Iesire ------ Nu: criteriul Nusselt """ fric=(0.79*unp.log(Re)-1.64)**(-2) return (fric/8.)*(Re-1000.)*Pr/(1+12.7*unp.sqrt(fric/8.)*(Pr**(2./3)-1))
def lnR_R0_u(T, B=4600, T0=298.15): """ T: Temperature estimated on the Arduino given a resistance R of the thermistor B: Supposed B value of the thermistor T0: Reference temperature return: lnR_RO_u the ln(R/R0) with its uncertainty """ #Calculate V_measured back from T ln = (1 / T - 1 / T0) * B V_measured = ((np.exp(ln) + 1) / 1023)**(-1) V_measured_u = unp.uarray([V_measured], [0.5]) lnR_R0_u = unp.log(1023 / V_measured_u - 1) return lnR_R0_u
def exp_mgca_2_temp(mgca_f, p=None): """ Calculate foram Mg/Ca from temperature using the 'classic' exponential function. Parameters ---------- mgca_f : array_like Foraminiferal Mg/Ca in mmol/mol p : array_like Parameters for the model, in the order [A, B]. Returns ------- Temperature in Celcius. : array_like """ A, B = p return log(mgca_f / A) / B
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
def fit_log(x, y, yerr, xlong): start = time.time() p, cov = curve_fit(func_log, x, y, sigma = yerr, maxfev = 100000) perr = np.sqrt(np.diag(cov)) yfit = func_log(x, p[0], p[1], p[2]) resid = y-yfit chi2 = np.sum((resid/yerr)**2) dof = y.size-len(p) chi2red = chi2/dof p_val = 1 - stats.chi2.cdf(chi2,dof) yfit = func_log(xlong, p[0], p[1], p[2]) p = unumpy.uarray(p,perr) extrapolate_val = p[0]*unumpy.log(extrapolate_times + 1 + p[1]) + p[2] end = time.time() elapsed = end-start return (chi2red, resid, extrapolate_val, 1, unumpy.nominal_values(p), unumpy.std_devs(p), yfit, elapsed, p_val)
def _xy(self, plot_type='conc'): """Returns the x and y values, and their errors, for plots Parameters ---------- plot_type : str, optional Plot type. 'conc' for concentration vs time; 'ln_conc' for ln(concentration) vs time; or 'inv_conc' for 1/concentration vs time.By default 'conc' Returns ------- tuple x values, x errors, y values and y errors Raises ------ ValueError Error when plot_type is not 'conc', 'ln_conc' or 'inv_conc' """ if plot_type == 'conc': x = self.time_array_u y = self.conc_array_u elif plot_type == 'ln_conc': x = self.time_array_u y = unumpy.log(self.conc_array_u) elif plot_type == 'inv_conc': x = self.time_array_u y = 1 / (self.conc_array_u) else: raise ValueError('Plot type not valid') x_values = unumpy.nominal_values(x) y_values = unumpy.nominal_values(y) x_err = unumpy.std_devs(x) y_err = unumpy.std_devs(y) x_err[x_err == 0] = 1e-30 y_err[y_err == 0] = 1e-30 return x_values, x_err, y_values, y_err
def Tgrove_u(T, Bgrove_u=unp.uarray([4275], [25]), T0_u=unp.uarray([298.15], [0.1])): """ T: Calculated temperature T value in Kelvin (Grove temperature) Bgrove_u: B value with uncertainty T0_u: Reference temperature with uncertainty return: T_u -> Temperature with uncertainty """ #Calculate V_measured back ln = (1 / T - 1 / unp.nominal_values(T0_u)) * unp.nominal_values(Bgrove_u) V_measured = ((np.exp(ln) + 1) / 1023)**(-1) V_measured_u = unp.uarray([V_measured], [0.5]) R_NTC_u = unp.uarray([1e5], [5e3]) R_0_u = unp.uarray([1e5], [1e3]) #Calculate the uncertainty of T T_u = (unp.log(1023 / V_measured_u - 1) * R_NTC_u / R_0_u / Bgrove_u + 1 / T0_u)**(-1) return T_u
def speziale_debyetemp(v, v0, gamma0, q0, q1, theta0): """ calculate Debye temperature for the Speziale equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param q0: logarithmic derivative of Gruneisen parameter :param q1: logarithmic derivative of Gruneisen parameter :param theta0: Debye temperature at 1 bar in K :return: Debye temperature in K """ if isuncertainties([v, v0, gamma0, q0, q1, theta0]): f_vu = np.vectorize(uct.wrap(integrate_gamma), excluded=[1, 2, 3, 4, 5, 6]) integ = f_vu(v, v0, gamma0, q0, q1, theta0) theta = unp.exp(unp.log(theta0) - integ) else: f_v = np.vectorize(integrate_gamma, excluded=[1, 2, 3, 4, 5, 6]) integ = f_v(v, v0, gamma0, q0, q1, theta0) theta = np.exp(np.log(theta0) - integ) return theta
def holland2020_calc_temp(mgca, mgca_sw=5.17, ca_sw=10.2e-3, carb_sw=2000e-6, p=None): """ Calculate Temperature from foram Mg/Ca, and seawater Mg/Ca, [Ca] and carbon chemistry. Parameters ---------- mgca : array_like Foraminiferal Mg/Ca in mmol/mol mgca_sw : array_like Seawater Mg/Ca, in mol/mol. ca_sw : array_like Seawater calcium concentration, in mol kg-1. carb_sw : array_like Seawater carbon parameter - either DIC, CO3 or pH, depending on the species. p : array_like Parameters for the model, in the order [A, B, C, D, E]. Returns ------- Temperature in Celcius. : array_like """ A, B, C, D, E = p return (log(mgca / (mgca_sw**A * carb_sw**B)) - ca_sw * C - E) / D
def InvDetEff(omega, llims, ulims, corners, missval=-999.0): ranges = ulims - llims V = np.prod(ranges, axis=0) n_om = len(omega) jtot = len(corners[0]) - 1 jfull = jtot**len(corners) Vj = V / jfull #Volume of a single element mult = 1 indfin = np.zeros(len(omega[0]), dtype=int) for i in range(n_om): ind = np.searchsorted(corners[i], omega[i]) - 1 indfin += ind * mult mult *= jtot allind = np.arange(jfull) uniq, cts = np.unique(indfin, return_counts=True) diff = np.setdiff1d(allind, uniq, assume_unique=True) theta, thetae = np.zeros(jfull), np.zeros(jfull) expth = cts / Vj exptherr = expth / np.sqrt(cts) uth = unumpy.log(unumpy.uarray(expth, exptherr)) theta[uniq], thetae[uniq] = unumpy.nominal_values(uth), unumpy.std_devs( uth) theta[diff], thetae[diff] = missval, missval return theta, thetae
def func_err_prop(func, x,p): if func == func_log: return p[0]*unumpy.log(extrapolate_times + 1 + p[1]) + p[2] if func == func_2log: return p[0]*unumpy.log(extrapolate_times + 1 + p[1]) +\ p[2]*unumpy.log(extrapolate_times + 1 +p[1]) + p[3] if func == func_stretched_exp: return p[0]*unumpy.exp(-(extrapolate_times/p[1])**p[2])+p[3] if func == func_stretched_exp_assume: return p[0]*unumpy.exp(-(extrapolate_times/p[1])**u)+p[2] if func == func_double_log: return p[0]*unumpy.log(1+unumpy.log(x+1+p[1]))+p[2] if func == func_2stretched_exp: return p[0]*unumpy.exp(-(x/p[1])**p[2])+p[3]*unumpy.exp(-(x/p[4])**p[5]) + p[6] # if func == func_vortex: # return p[0]/((1 + p[1]*p[2]*unumpy.log(x/p[3]+p[4]+1))**(1/p[2])) if func == func_vortex: return (p[0] + p[1]*unumpy.log(x+p[2]+1))**(-1/p[3]) else: sys.exit("Error")
def func_err_prop(func, x,p): if func == func_log: return p[0]*unumpy.log((extrapolate_times + 1 + p[1])) + p[2] if func == func_2log: return p[0]*unumpy.log(extrapolate_times + 1 + p[1]) +\ p[2]*unumpy.log(extrapolate_times + 1 +p[1]) + p[3] if func == func_stretched_exp: return p[0]*unumpy.exp(-(extrapolate_times/p[1])**p[2])+p[3] if func == func_stretched_exp_assume: return p[0]*unumpy.exp(-(extrapolate_times/p[1])**u)+p[2] if func == func_double_log: return p[0]*unumpy.log(1+unumpy.log(x+1+p[1]))+p[2] if func == func_2stretched_exp: return p[0]*unumpy.exp(-(x/p[1])**p[2])+p[3]*unumpy.exp(-(x/p[4])**p[5]) + p[6] # if func == func_vortex: # return p[0]/((1 + p[1]*p[2]*unumpy.log(x/p[3]+p[4]+1))**(1/p[2])) if func == func_vortex: return (p[0] + p[1]*unumpy.log(x+p[2]+1))**(-1/p[3]) else: sys.exit("Error")
print(n0) print("") # ## INDIUM ### # N_ind=np.genfromtxt("../Werte/Indium.txt").T N_ind_err=np.sqrt(N_ind) N_ind=unp.uarray(N_ind-nom(n0)*250,N_ind_err-std(n0)*250) print("INDIUM:") print("Berichtigung:") print("") print(N_ind) N_ind=unp.log(N_ind) def f(t, a, b): return a*t+b params, covariance = curve_fit(f, np.arange(250,(1+len(N_ind))*250,250), nom(N_ind),sigma=std(N_ind)) errors = np.sqrt(np.diag(covariance)) print("Parameter:") a=ufloat(params[0],errors[0]) print("a={}".format(a)) b=ufloat(params[1],errors[1]) print("b={}".format(b)) print("") print('T ={}'.format(np.log(2)/-a)) print('N0 ={}'.format(unp.exp(b)/(1-unp.exp(a*250)))) print("")
def main(): parser = argparse.ArgumentParser(description='') parser.add_argument('fileNames', help='Reduce scalar estimator', nargs='+') args = parser.parse_args() #Set up the figure rcParams.update(mplrc.aps['params']) figure(1,(8,5)) #figure(1,(3,2.25)) ax = subplot(1,1,1) #ax.set_xlabel(r'$\mathrm{A/(L_xL_y)}$') #ax.set_ylabel(r'$\mathrm{I_2^A}$') #ax.set_xlabel(r'$\mathrm{\beta = J/T \, [K^{-1}]}$') #ax.set_ylabel(r'$\mathrm{I_2^{half}/L_x}$') #minorLocator = AutoMinorLocator(5) #ax.xaxis.set_minor_locator(minorLocator) #minorLocator = AutoMinorLocator(5) #ax.yaxis.set_minor_locator(minorLocator) connect('key_press_event',kevent.press) #ax.yaxis.set_ticks([0,0.05,0.10,0.15]) #ax.yaxis.set_ticks([0,0.15]) #ax.xaxis.set_ticks([0.995,1.00]) Xs = [] Values = [] Errors = [] used = [] for j,fileName in enumerate(args.fileNames): scalarhelp = ssexyhelp.ScalarReduce(fileName) # Get parameters of a simulation fileparams = scalarhelp.getParmap() #dA = 3 dA = fileparams['dA'] Lx = fileparams['Lx'] Ly = fileparams['Ly'] Beta = fileparams['b'] #Load the files scalarhelp.loadData() #Get the range of region-A sizes rp, As = scalarhelp.getrParams() #Get the ratios from the advanced loop column ratios, dratios = scalarhelp.getAverages('ALRatio') #ratios = np.insert(ratios,0,0) #dratios = np.insert(dratios,0,0) #As = np.insert(As,0,0) #dratios *= 1.0/(2.0**j) ratios = unumpy.uarray(ratios,dratios) #Get the products from the const increament data if len(ratios.shape)==1: for i in range(1,len(ratios)): ratios[i] = ratios[i-1]*ratios[i] #Plot the results ratios = -unumpy.log(ratios)#/(float(Lx)) if len(As.shape) == 1: ratios = np.insert(ratios,0,0) ratios = ratios[:] + ratios[-1::-1] ratios = ratios - ratios[-1] ratios /=2.0 colors = ["#66CAAE", "#CF6BDD", "#E27844", "#7ACF57", "#92A1D6", "#E17597", "#C1B546",'b'] if len(As.shape)==1: x = (As+(As[1]-As[0])) x /=float(x[-1]) x = np.insert(x,0,0) ratios = ratios/float(Lx) ax.errorbar(x, unumpy.nominal_values(ratios), unumpy.std_devs(ratios), color = colors[j], ls = '-', marker='s', label=r'$\mathrm{dA=%02d}$' %int(dA)) #label=r'$\mathrm{L_x x L_y=%02d x %02d}$' %(int(Lx),int(Lx))) #ax.plot(x, unumpy.std_devs(ratios), # color = colors[j], ls = '-', marker='s', # label=r'$\mathrm{dA=%02d}$' %int(dA)) #d = 8.0/3.0 #d = 8.0/1.0 #d = 8.0/2.0 d = 8.0/4.0 print x[len(x)//d] Xs.append(Beta) value = unumpy.nominal_values(ratios)[len(x)//d] error = unumpy.std_devs(ratios)[len(x)//d] Values.append(value) Errors.append(error) #ax.errorbar(1.0/d,value,error,color='b',marker='s') #if j%2 == 0: # tratios = ratios #else: # ratios = ratios - tratios #ax.errorbar(x, unumpy.nominal_values(ratios), unumpy.std_devs(ratios), color=colors[j],ls = '-', marker=['s','o','d','>'][j//2], label=r'$\mathrm{L = %2.0d}$' %(int(Lx))) #ax.errorbar(x, unumpy.nominal_values(ratios), unumpy.std_devs(ratios), ls = '-', color=colors[j//2], marker=['s','o','d','>'][j%2], label=r'$\mathrm{L = %2.0d \, \beta=%0.0f}$' %(int(Lx),float(Beta))) #tratios = ratios[:] + ratios[-1::-1] #tratios = tratios - ratios[-1] #tratios /=2.0 #ratios = ratios - tratios #ax.errorbar(x, unumpy.nominal_values(ratios), unumpy.std_devs(ratios), color=colors[j//4],ls = '-', marker=['s','o','d','>'][j%4], label=r'$\mathrm{L = %2.0d \, \beta=%0.0f}$' %(int(Lx),float(Beta))) #ratios = ratios[4:-5] #x = x[4:-5] #if not(int(Lx) in used): # ax.errorbar(float(Beta), value, error, # color=colors[int(Lx)//4 -2], ls = '-', marker='s', # label=r'$\mathrm{L_xxL_y=%02d x %02d}$' %(int(Lx),int(Lx))) # used.append(int(Lx)) #else: # ax.errorbar(float(Beta), value, error, # color=colors[int(Lx)//4 -2], ls = '-', marker='s') #ax.errorbar(float(Beta), unumpy.nominal_values(ratio), unumpy.std_devs(ratio), color=colors[i], ls = '-',ms=7, marker=['s','o'][i%2]) #ratios = 1.0/ratios #ax.errorbar(x, unumpy.nominal_values(ratios), unumpy.std_devs(ratios), ls = '-', marker='s', label=r'$\mathrm{dA=%2d}$' %int(dA)) else: x = float(dA)/float(dA) ax.errorbar(x, unumpy.nominal_values(ratios), unumpy.std_devs(ratios), ls = '-', marker='s',color='orange', label=r'$\mathrm{dA=%02d}$' %int(dA)) #ax.errorbar(x, unumpy.nominal_values(ratios), unumpy.std_devs(ratios), ls = '-', marker='s', label=r'$\mathrm{dA=%2d}$' %int(dA)) #if j==0: ref = ratios #mask = array(range(0,64+1,2**j))[1:] - 1 #ax.plot(x, unumpy.std_devs(ratios)/unumpy.std_devs(ref[mask]), ls = '-', marker='s', label=r'$\mathrm{dA=%2d}$' %int(dA)) #ax.plot(x, unumpy.std_devs(ratios)/unumpy.std_devs(ref[mask]), ls = '-', marker='s', label=r'$\mathrm{dA=%2d}$' %int(dA)) #ax.plot(x, unumpy.std_devs(ratios), ls = '-', marker='s', label=r'$\mathrm{dA=%2d}$' %int(dA)) #ax.plot(x, unumpy.std_devs(ratios)/unumpy.nominal_values(ratios), ls = '-', marker='s', label=r'$\mathrm{dA=%2d}$' %int(dA)) print "Xs: ", Xs print "Values: ", Values print "Errors: ", Errors #print len(Xs),' ',len(Values),' ',len(Errors) #ax.set_xlim(-.005,1.25) #ax.set_xlim(-.005,1.005) #ax.set_xlim(-.005,3700) #ax.set_xlim(0.995,1.001) #ax.set_ylim(0,.15) tight_layout() lgd = legend(loc='best',ncol=1,frameon=False) lgd.draggable(state=True) show()
U_regression = np.log(U_0-U) print(U_regression) def f(t, m, b): return m*t+b parameters, popt = curve_fit(f, t, U_regression) m = ufloat(parameters[0], np.sqrt(popt[0,0])) b = ufloat(parameters[1], np.sqrt(popt[1,1])) Zeitkonstante = (-1/m) Ausgangsspannung = unp.exp(b) #Fehlerbalken in y-Richtung ausrechnen: U_err = unp.log(U_0 - U_gesamt) x=np.linspace(0,0.0035) #plt.plot(t, U_regression, 'rx') plt.errorbar(t, U_regression, xerr=t_err, yerr = unp.std_devs(U_err), fmt='r.', label='Datenpunkte mit Messunsicherheit') plt.plot(x, f(x, *parameters), 'b-', label='Lineare Ausgleichsgerade') plt.ylabel('$\log(U_0-U)$') plt.xlabel('Zeit / s') #plt.legend(loc='best') plt.savefig('Spannung2.png') plt.show() print('Steigung der Geraden', m) print('Achsenabschnitt der Geraden', b) print('Zeitkonstante', Zeitkonstante.n, Zeitkonstante.s)
def main(): # define the mapping between short names and label names parMap = {'x': r'L_x', 'y': r'L_y', 'b': r'\beta', 'T': r'T', 'r': r'r'} parser = argparse.ArgumentParser(description='Plot Raw MC Equilibration Data for Scalar Estimators.') parser.add_argument('fileNames', help='Scalar estimator files', nargs='+') parser.add_argument('--cutoff', action='store_true', default=False, help='Plot Delta as function of the cut-off') args = parser.parse_args() #rcParams.update(mplrc.aps['params']) colors = ["#66CAAE", "#CF6BDD", "#E27844", "#7ACF57", "#92A1D6", "#E17597", "#C1B546",'b'] if args.cutoff: figure(2,(7,6)) ax2 = subplot(211) connect('key_press_event',kevent.press) #ax2.set_xlabel(r'$\beta_{\mathrm{cutoff}}$') xticks([],[]) ax2.set_ylabel(r'$\Delta$') ax4 = subplot(212) ax4.set_xlabel(r'$\beta_{\mathrm{cutoff}}$') ax4.set_ylabel(r'$\Delta$') subplots_adjust(hspace=0) figure(1,(7,6)) connect('key_press_event',kevent.press) ax1 = subplot2grid((2,2), (0,0),colspan=2) ax1.set_xlabel(r'$\beta$') ax1.set_ylabel(r'$S_2^l$') global L global l global j_z i = 0 geom = 'ful' LDelta = [] LDeltaE = [] LJz = [] doubleJz = 1.0 for fileName in args.fileNames: #print fileName scalarhelp = ssexyhelp.ScalarReduce(fileName) parmap = scalarhelp.getParmap() dA = int(parmap['dA']) Lx = int(parmap['Lx']) if 'delta' in parmap.keys(): j_z = float(parmap['delta'])*doubleJz delta_fit = fDeltaJz(j_z) else: delta_fit = .5 LJz += [j_z] L = Lx l = dA scalarhelp.loadData() rb, Beta = scalarhelp.getrParams() if 'ALRatio' in scalarhelp.headers: Zr, dZr = scalarhelp.getAverages('ALRatio') Zr = unumpy.uarray(Zr,dZr) elif 'nAred' in scalarhelp.headers: Ar, dAr = scalarhelp.getAverages('nAred') Ar = unumpy.uarray(Ar,dAr) Ae, dAe = scalarhelp.getAverages('nAext') Ae = unumpy.uarray(Ae,dAe) Zr = Ae/Ar S2A = -unumpy.log(Zr) S2n = unumpy.nominal_values(S2A) S2d = unumpy.std_devs(S2A) #ax1.plot([Beta[0],Beta[-1]],[RenyiZero(),RenyiZero()],color='black',label = r'$S_2(T=0)$') mins = S2n - S2d maxs = S2n + S2d fill_between(Beta, mins,maxs, facecolor = colors[i%len(colors)], alpha =0.25, edgecolor='None') ax1.plot(Beta[0],S2n[0], color = colors[i%len(colors)],linewidth=4)#,label = r"$Data \, L=%2d$" %Lx) (A,B,C) = (0.4,1,0.4) #flshift = np.max(np.where(Beta<1.14)) minB = CutOff(j_z) if (Beta[0] > Lx) and (j_z>0): flshift = 0# np.max(np.where(Beta<Lx)) else: if Beta[0] < minB: flshift = np.max(np.where(Beta<minB)) else: flshift = 0 fhshift = len(Beta)# np.min(np.where(Beta>245)) ZBeta = np.linspace(Beta[flshift],Beta[fhshift-1],1000) #coeff, var_matrix = curve_fit(RenyiCorrection_C,np.array(Beta)[flshift:fhshift],S2n[flshift:fhshift],p0=(C)) #(C) = coeff #errs = np.sqrt(var_matrix.diagonal()) #S2pred = RenyiCorrection_C(ZBeta,C) #ax1.plot(ZBeta, S2pred, color=colors[i%len(colors)], linewidth = 1.5, label = r"$\mathrm{L=%2d \, J_z=%0.2f }$" %(Lx,j_z)) #coeff, var_matrix = curve_fit(RenyiCorrection_DeltaC,np.array(Beta)[flshift:fhshift],S2n[flshift:fhshift],p0=(delta_fit,C)) #(Delta,C) = coeff #errs = np.sqrt(var_matrix.diagonal()) #print 'Length: %3d J_z: %4.3f Theory: %4.3f Fit: %4.3f +/- %4.3f' %(L, j_z, delta_fit,Delta,errs[0]) #LDelta += [Delta] #LDeltaE += [errs[0]] #S2pred = RenyiCorrection_DeltaC(ZBeta,Delta,C) #ax1.plot(ZBeta, S2pred, color=colors[i%len(colors)], linewidth = 1.5, label = r"$\mathrm{L=%2d \, J_z=%0.2f }$" %(Lx,j_z)) if args.cutoff: #minB = 30 flshift2 = flshift if Beta[0] < minB: flshift = np.max(np.where(Beta<minB)) else: flshift = 0 leg = False ax2.plot([Beta[0],Beta[flshift]],[fDeltaJz(j_z),fDeltaJz(j_z)], ls = '-',color=colors[i%len(colors)], linewidth = 1.5) Bs = [] mins = [] maxs = [] chisqs = [] cdfs = [] Bs2 = [] for flshift in range(flshift): ZBeta = np.linspace(Beta[flshift],Beta[fhshift-1],1000) coeff, var_matrix = curve_fit(RenyiCorrection_DeltaC,np.array(Beta)[flshift:fhshift],S2n[flshift:fhshift],p0=(delta_fit,C)) (Delta,C) = coeff if type(var_matrix) is float: break errs = np.sqrt(var_matrix.diagonal()) if flshift!=flshift2: if not(leg): ax2.errorbar(Beta[flshift],Delta,errs[0], color=colors[i%len(colors)], label = r"$\mathrm{L=%2d \, J_z=%0.2f }$" %(Lx,j_z)) leg = True else: mins += [Delta - errs[0]] maxs += [Delta + errs[0]] Bs += [Beta[flshift]] ax2.errorbar(Beta[flshift],Delta,errs[0], color=colors[i%len(colors)]) else: ax2.errorbar(Beta[flshift],Delta,errs[0], color='black') Bs2 += [Beta[flshift]] dof = len(np.array(Beta)[flshift:fhshift]) - len(coeff) chisqs += [sum(((S2n[flshift:fhshift]- RenyiCorrection_DeltaC(np.array(Beta)[flshift:fhshift],Delta,C))/np.array(S2d)[flshift:fhshift])**2)] cdfs += [special.chdtrc(dof,chisqs[-1])] ax2.fill_between(Bs, mins,maxs, facecolor = colors[i%len(colors)], alpha =0.25, edgecolor='None') #ax4.plot(Bs2,chisqs, color=colors[i%len(colors)]) ax4.plot(Bs2,cdfs, color=colors[i%len(colors)]) i += 1 ax1.set_title(r'$A_{\Delta} e^{-\beta*B_{\Delta}}-C$') #lg = ax1.legend(loc='best',ncol = 2,frameon=False) #lg.draggable(state=True) if args.cutoff: lg = ax2.legend(loc='best',ncol = 2,frameon=False) lg.draggable(state=True) ax2.set_ylim([0,1]) ax4.set_ylim([0,1]) #ax3.set_xlim([-1.05,1.05]) ax3 = subplot2grid((2,2), (1,0),colspan=2) ax3.set_xlabel(r'$J_z$') ax3.set_ylabel(r'$\Delta$') ax3.set_ylim([0,0.5]) ax3.set_xlim([-1.05,1.05]) #LJz = np.arccos(np.array(LJz)) #print LJz if len(LJz)==len(LDelta): ax3.errorbar(np.array(LJz), LDelta, LDeltaE, ls='',marker='.',color=colors[2],mec=colors[2],mfc='white', label=r"$\mathrm{QMC}$") Jzs = np.linspace(-1.0,1.0,5000) deltas = fDeltaJz(Jzs) #Jzs = np.arccos(Jzs) ax3.plot(Jzs*1.0, deltas, color=colors[0], linewidth = 1.5, label = r"$\mathrm{Theory}$") lg = ax3.legend(loc='best',ncol = 1,frameon=False) lg.draggable(state=True) tight_layout() show()
def main(): parser = argparse.ArgumentParser(description='') parser.add_argument('fileNames', help='Reduce scalar estimator', nargs='+') args = parser.parse_args() rcParams.update(mplrc.aps['params']) connect('key_press_event',kevent.press) figure(1) ax = subplot(1,1,1) ax.set_xlabel(r'$l/L$')#, labelpad=-1.5) ax.set_ylabel(r'$S_2$')#, labelpad=-1.0) #ax.set_ylim([yl,yh]) ax.set_xlim([-0.05,1.05]) minorLocator = AutoMinorLocator(3) ax.xaxis.set_minor_locator(minorLocator) minorLocator = AutoMinorLocator(5) ax.yaxis.set_minor_locator(minorLocator) #subplots_adjust(top=0.94,bottom=0.15, right=0.995, left=0.139) Xs = [] Values = [] Errors = [] used = [] global L for j,fileName in enumerate(args.fileNames): scalarhelp = ssexyhelp.ScalarReduce(fileName) # Get parameters of a simulation fileparams = scalarhelp.getParmap() #dA = 3 dA = fileparams['dA'] Lx = fileparams['Lx'] Ly = fileparams['Ly'] global Beta Beta = float(fileparams['b']) global L L = float(Lx) global j_z j_z = float(fileparams['delta']) #if j==0: m = j #else: m = j-1 #Load the files scalarhelp.loadData() #Get the range of region-A sizes rp, As = scalarhelp.getrParams() #Get the ratios from the advanced loop column ratios, dratios = scalarhelp.getAverages('ALRatio') ratios = unumpy.uarray(ratios,dratios) #Get the products from the const increament data if len(ratios.shape)==1: for i in range(1,len(ratios)): ratios[i] = ratios[i-1]*ratios[i] #Plot the results ratios = -unumpy.log(ratios)#/(float(Lx)) colors = ["#66CAAE", "#CF6BDD", "#E27844", "#7ACF57", "#92A1D6", "#E17597", "#C1B546"] for choice in [0]: if len(As.shape) == 1: if choice==1: ratios = ratios[:] + ratios[-1::-1] ratios = ratios - ratios[-1] ratios /=2.0 else: ratios = np.insert(ratios,0,0) x = (As+(As[1]-As[0])) x /=float(x[-1]) x = np.insert(x,0,0) if choice==1: ax.errorbar(x, unumpy.nominal_values(ratios), unumpy.std_devs(ratios), color = colors[j+choice], ls = ['--','','-'][choice], marker='s', mec=colors[j+choice],mfc='None',ms=3,capsize=3) else: # Subtract off ground state entropy #S2 = EE1dFit(x,0.5486) #maxS2 = EE1dFit(x,0.5486+0.0015) #S2ground = unumpy.uarray(S2,maxS2-S2) #ratios -= S2ground # Ignore the thermal entropy point x = x[:-1] ratios = ratios[:-1]#*np.exp(np.pi*float(Beta)/L) mratios = ratios - EETfullFit(x,0,0) # Plot data ax.errorbar(x, unumpy.nominal_values(mratios), unumpy.std_devs(mratios), color = colors[j+choice], ls = ['','--','-'][choice], marker='s', mec=colors[j+choice],mfc='None',ms=3,capsize=3, label=r'$L=%0.0f \, \beta = %0.0f \, J_z = %0.1f$' %(L,Beta,j_z)) ## (A,B) = (1,100) last = -5 coeff, var_matrix = curve_fit(EETfullFit,x[1:last],unumpy.nominal_values(ratios)[1:last],p0=(A,B)) (nCoef,eCoef) = (coeff,np.sqrt(var_matrix.diagonal())) #Plot the fit l = np.linspace(0,x[-1]*0.9991,1000) S2T = EETfullFit(l,*nCoef) S2T -= EETfullFit(l,0,.0) eBeta = -1.0*unumpy.log(ufloat(nCoef[-1], eCoef[-1]))/np.pi*L print 'Effective beta: %3.2f +/- %0.2f' %(eBeta.n, eBeta.s), " Real beta: %0.2f " %Beta ax.plot(l,S2T,ls='-',color = colors[j+choice],alpha=0.5) #for p,text in enumerate(lgd.get_texts()): # if p==0: m = p # else: m = p+#1 # text.set_color(colors[m]) lgd = legend(loc='best',ncol=1,frameon=False) lgd.draggable(state=True) tight_layout() show()
print('tg',Tg_10) V=np.append(Vg,V) print('Volumen Groß',Vog) print('Volumen klein',Vok) T=np.append(Tg_10,T) n=Kkl*(rhok-rhow)*Tk print('Viskosität',n) Kgr= n/((rhog-rhow)*Tg_10) print('Kgr',Kgr) ngr=Kgr*(rhog-rhow)*T m, b, r, p, stdsm=stats.linregress(noms(1/Temp),np.log(noms(Kgr*(rhog-1)*T))) x=np.linspace(20+273.15,65+273.15) print('1/T',1/Temp) print('ln(eha/pas)',unp.log(Kgr*(rhog-1)*T)) print('Geschwindigkeit klein=',Vk,'Zeitmittelwert=',Tk) plt.figure(1) plt.errorbar(noms(1/Temp),noms(unp.log(Kgr*(rhog-1)*T)),xerr=stds(1/Temp),yerr=stds(unp.log(Kgr*(rhog-1)*T)),fmt='rx') plt.plot(noms(1/Temp),noms(unp.log(Kgr*(rhog-1)*T)),'xk',label=r'$Messwerte$') plt.plot(1/x,m*(1/x)+b,'-b',label=r'$Ausgleichsfunktion$') plt.legend(loc='best') plt.grid(True) plt.xlabel(r'$\frac{1}{T}/{K^{-1}}$') plt.ylabel(r'$\ln(\eta / Pa \cdot s)$') plt.savefig('plot.pdf') def Fehlera(x,sa): b=sa*(sum(x**2)/len(x))**(1/2) return b
valuesm = (eta_th(T_, *(unp.nominal_values(params) - unp.std_devs(params)))).astype(float) plt.errorbar(T, 1000*unp.nominal_values(eta), yerr=1000*unp.std_devs(eta), fmt='rx', label='Messdaten', markersize=3) plt.plot(T_, 1000*eta_th(T_, *unp.nominal_values(params)), 'b-', label='Fit') plt.fill_between(T_, 1000*valuesm, 1000*valuesp, facecolor='blue', alpha=0.125, edgecolor='none', label=r'$1\sigma$-Umgebung') plt.xlim(C2K(26),C2K(65)) plt.xlabel(r'$T / \si{\kelvin}$') plt.ylabel(r'$\eta / \si{\milli\pascal\second}$') plt.legend(loc='best') plt.tight_layout(pad=0) plt.savefig('build/viskosität.pdf') plt.clf() T_r = 1/T T_r_ = 1/T_ lneta = unp.log(eta) slope, intercept, r_value, p_value, std_err = linregress(T_r, unp.nominal_values(lneta)) print(slope, intercept, r_value**2) B = unc.ufloat(slope, std_err) A = unp.exp(unc.ufloat(intercept, std_err * T_r.mean())) print("A = {}, B = {}".format(A, B)) valuesp = (slope + std_err) * T_r_ + intercept + std_err * T_r.mean() valuesm = (slope - std_err) * T_r_ + intercept - std_err * T_r.mean() plt.errorbar(T_r, unp.nominal_values(lneta), yerr=unp.std_devs(lneta), fmt='rx', label='Messdaten', markersize=3) plt.plot(T_r_, slope*T_r_ + intercept, 'b-', label='Lineare Regression') plt.fill_between(T_r_, valuesm, valuesp, facecolor='blue', alpha=0.125, edgecolor='none', label=r'$1\sigma$-Umgebung') plt.xlim(0.00297, 0.00333) plt.xlabel(r'$T^{-1} / \si{\per\kelvin}$')
19961,19552,19589,17596,15917,15361,16543]) print(np.mean([6361,10509, 10692,10940,6447,11279,10401,10737,10720,13163,12112, 11262])) print(np.mean([1105,1729, 2314, 2539, 1037, 4671, 2223, 2528, 3610,5777, 2662, 3454])) print(np.mean([12503,62255, 3108,61660,11767, 19961,19552,19589,17596,15917,15361,16543])) print("Würfel 1,2,4") print("Projektionen in der Reihe") print("") print(unp.log(unp.uarray(array[2],np.sqrt(array[2]))/unp.uarray(array[4],np.sqrt(array[4])))) print(unp.log(unp.uarray(array[1],np.sqrt(array[1]))/unp.uarray(array[5],np.sqrt(array[5])))) print(unp.log(unp.uarray(array[1],np.sqrt(array[1]))/unp.uarray(array[6],np.sqrt(array[6])))) print(unp.log(unp.uarray(array[1],np.sqrt(array[1]))/unp.uarray(array[7],np.sqrt(array[7])))) print(unp.log(unp.uarray(array[2],np.sqrt(array[2]))/unp.uarray(array[8],np.sqrt(array[8])))) print(unp.log(unp.uarray(array[1],np.sqrt(array[1]))/unp.uarray(array[9],np.sqrt(array[9])))) print(unp.log(unp.uarray(array[1],np.sqrt(array[1]))/unp.uarray(array[10],np.sqrt(array[10])))) print(unp.log(unp.uarray(array[1],np.sqrt(array[1]))/unp.uarray(array[11],np.sqrt(array[11])))) print(unp.log(unp.uarray(array[3],np.sqrt(array[3]))/unp.uarray(array[12],np.sqrt(array[12])))) print(unp.log(unp.uarray(array[3],np.sqrt(array[3]))/unp.uarray(array[13],np.sqrt(array[13])))) print(unp.log(unp.uarray(array[3],np.sqrt(array[3]))/unp.uarray(array[14],np.sqrt(array[14])))) print(unp.log(unp.uarray(array[3],np.sqrt(array[3]))/unp.uarray(array[15],np.sqrt(array[15])))) print("") print(unp.log(unp.uarray(array[2],np.sqrt(array[2]))/unp.uarray(array[16],np.sqrt(array[16])))) print(unp.log(unp.uarray(array[1],np.sqrt(array[1]))/unp.uarray(array[17],np.sqrt(array[17])))) print(unp.log(unp.uarray(array[1],np.sqrt(array[1]))/unp.uarray(array[18],np.sqrt(array[18]))))
#Quotient aus Wärmeleistung und gemittelter elektrischer Leistung (= Gütezahl) ν = test_T1 / np.mean(P) #Gütezahlen ausgeben #print(ν) #Wirkungsgrade einer idealen Wärmepumpe bei den Temperaturniveaus der Testzeitpunkte bestimmen ν_ideal = T(test_points, *params1_u)/(T(test_points, *params1_u) - T(test_points, *params2_u)) #Ideale Wirkungsgrade ausgeben #print(ν_ideal) #Verhältnis bestimmen verhältnis = ν / ν_ideal #Auswertung der Dampfdruckkurve dampf_p_log = unp.log(dampf_p) dampf_T_reziprok = 1 / dampf_T #Lineare Regression des logarithmierten Drucks über der reziproken Temperatur result = linregress(dampf_T_reziprok, unp.nominal_values(dampf_p_log)) # (slope, intercept, r_value, p_value, std_err) print(-unc.ufloat(result[0], result[4])) L = -unc.ufloat(result[0], result[4]) * R maketable([-unc.ufloat(result[0], result[4]),L], "build/table_verdampfungswärme.tex", False) #Massendurchsatz berechnen m = -test_T2 / L m *= M #Massendurchsätze ausgeben print(m) #Berechnung der mechanischen Kompressorleistung
print(Re1) print(Re2) eta_t = K_gr * (roh2 - rohf * 1000) * tm_3 / 1000 print("eta temperaturabhängig") print(eta_t) T1n = unp.nominal_values(T1) # def f(T1n,a_0, a_1): # return (a_0* np.exp(a_1/T1n)) def f(T, a_0, a_1): return np.log(a_0) + (a_1 * T) T1x = 1 / T1n lneta = unp.log(eta_t / 1000) print("Tx") print(1 / T1) print("ln eta") print(lneta) params, covar = curve_fit(f, 1 / T1n, np.log(unp.nominal_values(eta_t)), p0=[0.0000046, 1600]) # lneta=np.log(unp.nominal_values(eta_t)) x_plot1 = np.linspace(0.0029, 0.0035, 1000) plot.plot(x_plot1, f(x_plot1, *params), "b-", label="Fit") plot.plot(1 / unp.nominal_values(T1), np.log(unp.nominal_values(eta_t)), "rx", label="Messwerte") plot.legend(loc="best") plot.yscale("linear") plot.xlim(0.0029, 0.0035) plot.xscale("linear") plot.xlabel("$1/T \;1/\mathrm{ K }$")
a = np.mean(Falldauer_roh[j:(j+2)]) b = np.std(Falldauer_roh[j:(j+2)]) Falldauer_unc[i] = ufloat(a, b) T_2[i] = T[j] i += 1 j += 1 Falldauer_unc[0] = t_gr_a # print (Falldauer_unc) rho_Wasser = [998.8, 996.5, 995.3, 994.0, 992.6, 991.0, 989.3, 987.5, 985.7, 983.2] rho_K = rho_gr * np.ones(10) eta_gr_b = K_gr * (rho_K - rho_Wasser) * Falldauer_unc print('eta') print(eta_gr_b) eta_gr_b_log = unp.log(eta_gr_b) params = ucurve_fit(reg.reg_linear, 1/T_2, noms(eta_gr_b_log)) m, b = params write('build/Steigung_b.tex', make_SI(m, r'\kelvin', figures=1)) # Dies ist tatsächlich B ! write('build/Offset_b.tex', make_SI(b, r'', figures=1)) A = unp.exp(b) # print(A) write('build/ParameterA_b.tex', make_SI(A*1e3, r'\kilogram\meter\per\second', 'e-3', figures=1)) # write('build/Tabelle_daten1.tex', make_table([T_2-273, noms(Falldauer_unc), stds(Falldauer_unc), rho_Wasser, 1/T_2*1e3, noms(eta_gr_b)*1e3, stds(eta_gr_b)*1e3, noms(eta_gr_b_log)*(-1), stds(eta_gr_b_log)],[0, 2, 2, 1, 3, 3, 2 , 2, 2])) write('build/Tabelle_daten1.tex', make_table([T_2-273, Falldauer_unc, rho_Wasser, 1/T_2*1e3, eta_gr_b*1e3, (-1)*eta_gr_b_log],[0, 1, 1, 3, 1, 1])) # FULLTABLE write('build/Tabelle_daten1_texformat.tex', make_full_table( 'Messdaten Falldauer in Abhängigkeit der Temperatur.', 'table:daten1',
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()
print('T_w5',T_w5 ) #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)
A_error = sigma_y * np.sqrt(N / Delta) B_error = sigma_y * np.sqrt(np.sum(x**2) / Delta) return A, A_error, B, B_error Al = np.genfromtxt('daten/{}.txt'.format('Al'), unpack=True, dtype=object) d, delta_d, t, n = Al.astype(float) N_u = unc.ufloat(324/900, np.sqrt(324)/900) d = unp.uarray(d, delta_d) * 1e-6 N = unp.uarray(n/t, np.sqrt(n)/t) - N_u tools.table((Al[0], Al[2], Al[3], N), ("D/µm", "n", "\Delta t/s", "(N-N_U)/\per\second"), "build/Al.tex", "Messdaten von Aluminium.", "tab:datenAl", split=2, round_figures=(0,0,0,3)) N = unp.log(N) slope1, std_a1, intercept1, std_b1 = linregress(unp.nominal_values(d[:5]), unp.nominal_values(N[:5])) slope2, std_a2, intercept2, std_b2 = linregress(unp.nominal_values(d[5:]), unp.nominal_values(N[5:])) D_max = (unc.ufloat(intercept2, std_b2)-unc.ufloat(intercept1, std_b1))/(unc.ufloat(slope1, std_a1) - unc.ufloat(slope2, std_a2)) print(D_max) R_max = D_max * 2700 / 10 E_max = 1.92*unp.sqrt(R_max**2 + 0.22*R_max) print("D_max = {}µm, R_max = {}g/cm², E_max = {} MeV".format(D_max*1e6, R_max, E_max)) #print(unp.nominal_values(d), N) sd = np.linspace(0, 0.5e-3) plt.ylim(-3, 8) plt.plot(1e6*sd, sd*slope2+intercept2, 'b-', label=r"Lineare Regression, $R > R_\text{max}$")
def main() : file_graphs = {} file_graphs_dIdVovI = {} file_graphs_dVdI = {} file_graphs_dlnIdV = {} file_graphs_sub = {} file_graphs_sub_dIdVovI = {} file_list = [] if options.fileList is not None : for split in options.fileList.split(',') : file_list.append( split ) elif options.baseDir is not None : for file in os.listdir( options.baseDir ) : file_list.append( '%s/%s' %( options.baseDir, file ) ) selected_files = [] for file in file_list : if file.count('.txt') : if options.fileKey is not None : if file.count( options.fileKey ) : selected_files.append(file ) else : selected_files.append( file ) print selected_files file_order = ['']*len(selected_files) common_title = '' file_is_with_source = {} for file in selected_files : res = re.match( '.*?/Measurements_for_(.*?)_(\d)_(\d)\.txt', file ) file_is_with_source[file] = False if res is not None : common_title = res.group(1) src = int(res.group(2)) pos = int(res.group(3)) location = 0 if src == 2 : location += 1 location += (pos-1) file_is_with_source[file] = True file_order[location] = file while '' in file_order : file_order.remove('') if not options.srcCompare : file_order = selected_files print file_order file_data = {} for idx, file in enumerate(file_order) : ofile = open( file, 'r' ) collected_data = {} for line in ofile : splitline = line.split() collected_data.setdefault( splitline[0], []).append( splitline[1] ) ofile.close() # average over currents measured at the same voltage file_data[file] = [] for voltage, currents in collected_data.iteritems() : avg = math.fsum( [float(c) for c in currents] )/len(currents) stddev = math.sqrt( math.fsum( [ (float(c) - avg)*(float(c) - avg) for c in currents] )/len(currents) ) file_data[file].append( ( float( voltage), ufloat( avg , stddev ) ) ) #if math.fabs(float(voltage)-86) < 0.05 : # print '%f - %e' %( float( voltage), avg ) file_data[file].sort() file_data_diff = {} for file in file_order[1:] : data_src = file_data[file] data_bkg = file_data[file_order[0]] file_data_diff[file] = [] for src, bkg in zip( data_src, data_bkg ) : if src[0] != bkg[0] : print 'Values should be equal!' file_data_diff[file].append( (src[0], src[1]-bkg[1]) ) for file_idx, file in enumerate(file_order) : color = get_color( file_idx ) file_graphs[file] = ROOT.TGraphErrors( len(file_data[file]) ) file_graphs[file].SetName( file ) file_graphs[file].SetMarkerStyle( 20 ) file_graphs[file].SetMarkerSize( 1.2 ) file_graphs[file].SetMarkerColor( color ) file_graphs[file].SetTitle( 'Measured current for ' + common_title ) file_graphs_dIdVovI[file] = ROOT.TGraphErrors( len(file_data[file])-1 ) file_graphs_dIdVovI[file].SetName( file ) file_graphs_dIdVovI[file].SetMarkerStyle( 20 ) file_graphs_dIdVovI[file].SetMarkerSize( 1.2 ) file_graphs_dIdVovI[file].SetMarkerColor( color ) file_graphs_dIdVovI[file].SetTitle( '(dI/dV)/I for ' + common_title ) file_graphs_dVdI[file] = ROOT.TGraphErrors( len(file_data[file])-1 ) file_graphs_dVdI[file].SetName( file ) file_graphs_dVdI[file].SetMarkerStyle( 20 ) file_graphs_dVdI[file].SetMarkerSize( 1.2 ) file_graphs_dVdI[file].SetMarkerColor( color ) file_graphs_dVdI[file].SetTitle( 'dV/dI for ' + common_title ) file_graphs_dlnIdV[file] = ROOT.TGraphErrors( len(file_data[file])-1 ) file_graphs_dlnIdV[file].SetName( file ) file_graphs_dlnIdV[file].SetMarkerStyle( 20 ) file_graphs_dlnIdV[file].SetMarkerSize( 1.2 ) file_graphs_dlnIdV[file].SetMarkerColor( color ) file_graphs_dlnIdV[file].SetTitle( 'd lnI/dV for ' + common_title ) #(d( lnI )/dV) ^-1 vs V # for making plots with subtracted data # ignore the 0th file which is the background # measurement if file_idx>0 : file_graphs_sub[file] = ROOT.TGraphErrors( len(file_data_diff[file]) ) file_graphs_sub[file].SetName( file ) file_graphs_sub[file].SetMarkerStyle( 20 ) file_graphs_sub[file].SetMarkerSize( 1.2 ) file_graphs_sub[file].SetMarkerColor( color ) file_graphs_sub[file].SetTitle( 'Background subtracted current for ' + common_title ) file_graphs_sub_dIdVovI[file] = ROOT.TGraphErrors( len(file_data_diff[file])-1 ) file_graphs_sub_dIdVovI[file].SetName( file ) file_graphs_sub_dIdVovI[file].SetMarkerStyle( 20 ) file_graphs_sub_dIdVovI[file].SetMarkerSize( 1.2 ) file_graphs_sub_dIdVovI[file].SetMarkerColor( color ) file_graphs_sub_dIdVovI[file].SetTitle( 'Background subtracted (dI/dV)/I for ' + common_title ) # fill graphs with subtracted data # data[0] is voltage data[1] is current difference for idx, data in enumerate(file_data_diff[file]) : file_graphs_sub[file].SetPoint( idx, data[0], data[1] ) for idx, lower_data in enumerate(file_data_diff[file][:-1]) : upper_data = file_data_diff[file][idx+1] avg_voltage = (lower_data[0] + upper_data[0] )/2. avg_current = (lower_data[1] + upper_data[1] )/2. delta_voltage = upper_data[0] - lower_data[0] delta_current = upper_data[1] - lower_data[1] x_point_dIdVovI = avg_voltage y_point_dIdVovI = ( delta_current / delta_voltage ) / avg_current file_graphs_sub_dIdVovI[file].SetPoint( idx, x_point_dIdVovI, y_point_dIdVovI ) # fill graphs with raw data # data[0] is voltage data[1] is current for idx, data in enumerate(file_data[file]) : file_graphs[file].SetPoint( idx, data[0], data[1].n ) file_graphs[file].SetPointError( idx, 0, data[1].s ) # get two data points for derivatives. lower_data is the # lower voltage and upper_data is the next voltage point # data[0] is the voltage and data[1] is the current for idx, lower_data in enumerate(file_data[file][:-1]) : upper_data = file_data[file][idx+1] avg_voltage = (lower_data[0] + upper_data[0] )/2. avg_current = (lower_data[1] + upper_data[1] )/2. delta_voltage = upper_data[0] - lower_data[0] delta_current = upper_data[1] - lower_data[1] delta_ln_current = unumpy.log( upper_data[1] ) - unumpy.log( lower_data[1] ) #delta_ln_current = math.log( upper_data[1] - lower_data[1] ) x_point_dIdVovI = avg_voltage y_point_dIdVovI = ( delta_current / delta_voltage ) / avg_current file_graphs_dIdVovI[file].SetPoint( idx, x_point_dIdVovI, y_point_dIdVovI.n ) file_graphs_dIdVovI[file].SetPointError( idx, 0, y_point_dIdVovI.s ) x_point_dVdI = avg_voltage y_point_dVdI = ( delta_voltage / delta_current ) file_graphs_dVdI[file].SetPoint( idx, x_point_dVdI, y_point_dVdI.n ) file_graphs_dVdI[file].SetPointError( idx, 0, y_point_dVdI.s ) x_point_dlnIdV = avg_voltage y_point_dlnIdV = 1.0/( delta_ln_current / delta_voltage ) file_graphs_dlnIdV[file].SetPoint( idx, x_point_dlnIdV, y_point_dlnIdV.n ) file_graphs_dlnIdV[file].SetPointError( idx, 0, y_point_dlnIdV.s ) c1 = ROOT.TCanvas('c1', 'c1') leg_I_vs_V = None leg_dIdVovI_vs_V = None leg_dVdI_vs_V = None leg_dlnIdV_vs_V = None leg_sub_I_vs_V = None leg_sub_dIdVovI_vs_V = None if len( file_order ) <= len(_leg_entries) : leg_I_vs_V = ROOT.TLegend(0.12, 0.55, 0.42, 0.85) leg_dIdVovI_vs_V = ROOT.TLegend(0.12, 0.55, 0.42, 0.85) leg_dVdI_vs_V = ROOT.TLegend(0.2, 0.25, 0.5, 0.55) leg_dlnIdV_vs_V = ROOT.TLegend(0.68, 0.6, 0.95, 0.85) leg_sub_I_vs_V = ROOT.TLegend(0.12, 0.55, 0.42, 0.85) leg_sub_dIdVovI_vs_V = ROOT.TLegend(0.12, 0.55, 0.42, 0.85) leg_I_vs_V .SetFillColor( ROOT.kWhite ) leg_dIdVovI_vs_V .SetFillColor( ROOT.kWhite ) leg_dVdI_vs_V .SetFillColor( ROOT.kWhite ) leg_dlnIdV_vs_V .SetFillColor( ROOT.kWhite ) leg_sub_I_vs_V .SetFillColor( ROOT.kWhite ) leg_sub_dIdVovI_vs_V .SetFillColor( ROOT.kWhite ) for idx, file in enumerate(file_order) : leg_I_vs_V. AddEntry(file_graphs[file], _leg_entries[idx], 'PE' ) leg_dIdVovI_vs_V .AddEntry(file_graphs[file], _leg_entries[idx], 'PE' ) leg_dVdI_vs_V .AddEntry(file_graphs[file], _leg_entries[idx], 'PE' ) leg_dlnIdV_vs_V .AddEntry(file_graphs[file], _leg_entries[idx], 'PE' ) if idx > 0 : leg_sub_I_vs_V .AddEntry(file_graphs[file], _leg_entries[idx], 'PE' ) leg_sub_dIdVovI_vs_V .AddEntry(file_graphs[file], _leg_entries[idx], 'PE' ) for idx, file in enumerate(file_order) : if idx == 0 : file_graphs[file].Draw('AP') file_graphs[file].GetXaxis().SetTitle('Bias Voltage') else : file_graphs[file].Draw('Psame') if leg_I_vs_V is not None : leg_I_vs_V.Draw() c1.SetLogy() c2 = ROOT.TCanvas('c2', 'c2') for idx, file in enumerate(file_order) : if idx == 0 : file_graphs_dIdVovI[file].Draw('AP') file_graphs_dIdVovI[file].GetXaxis().SetTitle('Bias Voltage') else : file_graphs_dIdVovI[file].Draw('Psame') if leg_dIdVovI_vs_V is not None : leg_dIdVovI_vs_V.Draw() c3 = ROOT.TCanvas('c3', 'c3') for idx, file in enumerate(file_order) : if idx == 0 : file_graphs_dVdI[file].Draw('AP') file_graphs_dVdI[file].GetXaxis().SetTitle('Bias Voltage') else : file_graphs_dVdI[file].Draw('Psame') if leg_dVdI_vs_V is not None : leg_dVdI_vs_V.Draw() c3.SetLogy() c4 = ROOT.TCanvas('c4', 'c4') for idx, file in enumerate(file_order) : if idx == 0 : file_graphs_dlnIdV[file].Draw('AP') file_graphs_dlnIdV[file].GetXaxis().SetTitle('Bias Voltage') file_graphs_dlnIdV[file].SetMaximum(1.5) else : file_graphs_dlnIdV[file].Draw('Psame') if leg_dlnIdV_vs_V is not None : leg_dlnIdV_vs_V.Draw() c5 = ROOT.TCanvas('c5', 'c5') for idx, file in enumerate(file_order) : if idx == 0 : continue elif idx == 1 : file_graphs_sub[file].Draw('AP') file_graphs_sub[file].GetXaxis().SetTitle('Bias Voltage') else : file_graphs_sub[file].Draw('Psame') c5.SetLogy() if leg_sub_I_vs_V is not None : leg_sub_I_vs_V.Draw() c6 = ROOT.TCanvas('c6', 'c6') for idx, file in enumerate(file_order) : if idx == 0 : continue elif idx == 1 : file_graphs_sub_dIdVovI[file].Draw('AP') file_graphs_sub_dIdVovI[file].GetXaxis().SetTitle('Bias Voltage') else : file_graphs_sub_dIdVovI[file].Draw('Psame') if leg_sub_dIdVovI_vs_V is not None : leg_sub_dIdVovI_vs_V.Draw() if not options.batch : raw_input('cont') if options.outputDir is not None : save = 'n' if options.batch : save = 'y' else : save = raw_input('save ? (y/n)' ) if save == 'y' : if not os.path.isdir( options.outputDir ) : os.makedirs( options.outputDir ) c1.SaveAs( '%s/Results_I_vs_V_%s.pdf' %(options.outputDir, common_title )) c2.SaveAs( '%s/Results_dIdVovI_vs_V_%s.pdf' %(options.outputDir, common_title )) c3.SaveAs( '%s/Results_dVdI_vs_V_%s.pdf' %(options.outputDir, common_title )) c4.SaveAs( '%s/Results_dlnIdV_vs_V_%s.pdf' %(options.outputDir, common_title )) c5.SaveAs( '%s/Results_sub_I_vs_V_%s.pdf' %(options.outputDir, common_title )) c6.SaveAs( '%s/Results_sub_dIdVovI_vs_V_%s.pdf' %(options.outputDir, common_title ))
def main(): # define the mapping between short names and label names parMap = {'x': r'L_x', 'y': r'L_y', 'b': r'\beta', 'T': r'T', 'r': r'r'} parser = argparse.ArgumentParser(description='Plot Raw MC Equilibration Data for Scalar Estimators.') parser.add_argument('fileNames', help='Scalar estimator files', nargs='+') args = parser.parse_args() rcParams.update(mplrc.aps['params']) colors = ["#66CAAE", "#CF6BDD", "#E27844", "#7ACF57", "#92A1D6", "#E17597", "#C1B546",'b'] figure(1,(7,6)) connect('key_press_event',kevent.press) ax1 = subplot(1,1,1,) global L L = 64.0 #L = 256.0 global beta beta = 150.0 geom = 'ful' for fileName in args.fileNames: scalarhelp = ssexyhelp.ScalarReduce(fileName) parmap = scalarhelp.getParmap() Lx = int(parmap['Lx']) scalarhelp.loadData() rb, As = scalarhelp.getrParams() As = As + As[1]-As[0] As = np.insert(As,0,0) nAs = np.linspace(As[1],As[-2],100) Zr, dZr = scalarhelp.getAverages('ALRatio') Zr = unumpy.uarray(Zr,dZr) if len(Zr.shape)==1: for i in range(1,len(Zr)): Zr[i] = Zr[i-1]*Zr[i] S2A = -unumpy.log(Zr) S2A = np.insert(S2A,0,0) S2A = S2A[:] + S2A[-1::-1] S2A = S2A - S2A[-1] S2A /=2.0 As = As[1:-1] S2A = S2A[1:-1] S2A = S2A-RenyiZero(As) S2n = unumpy.nominal_values(S2A) S2d = unumpy.std_devs(S2A) ax1.errorbar(As,S2n,S2d, color = colors[i%len(colors)],label = ((r'$\mathrm{L=%2.0d}$' %Lx) +'\n'+ (r'$\mathrm{S_{2}^{\beta=%3.2f}}$' %(beta) ))) #ax1.plot(nAs,RenyiZero(nAs),color='black',label = r'$S_2(T=0)$') (A,B,C) = (0.4,1,0.4) #coeff, var_matrix = curve_fit(RenyiCorrection_C,As,S2n,p0=(C)) #(C) = coeff #errs = np.sqrt(var_matrix.diagonal()) #S2pred = RenyiCorrection_C(nAs,C) #ax1.plot(nAs, S2pred, linewidth = 2, label = r"$\mathrm{A(\Delta=\frac{1}{4})e^{-\beta*B(\Delta=\frac{1}{4})}-C}$" ) #(A,B,C) = (0.4,1,0.4) #coeff, var_matrix = curve_fit(RenyiCorrection_DeltaC,As,S2n,p0=(B,C)) #(Delta,C) = coeff #errs = np.sqrt(var_matrix.diagonal()) #S2pred = RenyiCorrection_DeltaC(nAs,Delta,C) #ax1.plot(nAs, S2pred, linewidth = 2, label = r"$\mathrm{A(\Delta) e^{-\beta*B(\Delta)}-C, \, \Delta=%0.3f(%0.3f)}$" %(Delta,errs[0])) #(A,B,C) = (0.4,1,0.4) #coeff, var_matrix = curve_fit(RenyiCorrection_DeltaBC,As,S2n,p0=(A,B,C)) #(Delta,B,C) = coeff #errs = np.sqrt(var_matrix.diagonal()) # #S2pred = RenyiCorrection_DeltaBC(nAs,Delta,B,C) #ax1.plot(nAs, S2pred, linewidth = 2, label = r"$\mathrm{A(\Delta) e^{-\beta*B(\Delta)}-C, \, \Delta=%0.3f(%0.3f)}$" %(Delta,errs[0])) i += 1 ax1.legend(loc='best',frameon=False) tight_layout() show()
[nu_3[0:10]/1e3, unp.uarray(U_3[0:10], dU_3[0:10])*1e3, nu_3[10:20]/1e3, unp.uarray(U_3[10:20], dU_3[10:20])*1e3] )) with open('build/a_data_4.tex', 'w') as f: f.write(table([r'$\nu / \si{\kilo\hertz}$', r'$U / \si{\volt}$', r'$\nu / \si{\kilo\hertz}$', r'$U / \si{\volt}$'], [nu_4[0:10]/1e3, unp.uarray(U_4[0:10], dU_4[0:10]), nu_4[10:20]/1e3, unp.uarray(U_4[10:20], dU_4[10:20])] )) V_1 = unp.uarray(U_1,dU_1) / U_ein V_2 = unp.uarray(U_2,dU_2) / U_ein V_3 = unp.uarray(U_3,dU_3) / U_ein V_4 = unp.uarray(U_4,dU_4) / U_ein nu_1_log, V_1_log = np.log(nu_1)+0, unp.log(V_1)+0 nu_2_log, V_2_log = np.log(nu_2)+0, unp.log(V_2)+0 nu_3_log, V_3_log = np.log(nu_3)+0, unp.log(V_3)+0 nu_4_log, V_4_log = np.log(nu_4)+0, unp.log(V_4)+0 # Fit Data def func(x,a,b): return a*x+b popt_1, pcov_1 = curve_fit(func,nu_1_log,unp.nominal_values(V_1_log)) popt_2, pcov_2 = curve_fit(func,nu_2_log[6:14],unp.nominal_values(V_2_log[6:14])) popt_3, pcov_3 = curve_fit(func,nu_3_log[12:18],unp.nominal_values(V_3_log[12:18])) popt_4, pcov_4 = curve_fit(func,nu_4_log[11:18],unp.nominal_values(V_4_log[11:18])) m = np.array([ufloat(popt_1[0],pcov_1[0][0]), ufloat(popt_2[0],pcov_2[0][0]),
print(T7x_M3) print(T7n_M3) print("ergibt",(T7x_M3-T7n_M3)/2) print("") print("Quotient ist:",(T7x_M3-T7n_M3)/(T8x_M3-T8n_M3)) # # Phasenversatz # T1x_M2=ufloat(np.mean(T1x_M2_x-T2x_M2_x),sem(T1x_M2_x-T2x_M2_x)) T5x_M2=ufloat(np.mean(T5x_M2_x-T6x_M2_x),sem(T5x_M2_x-T6x_M2_x)) T8x_M3=ufloat(np.mean(T8x_M3_x-T7x_M3_x),sem(T8x_M3_x-T7x_M3_x)) # Aluminium M2 print("Alu M2") #warmth=(c*rho*0.009)/(2*T8x_M3*ln(quot)) print(T5x_M2) warmthi=((830*2800*0.0009)/(2*T5x_M2*unp.log(ufloat(1.893,0.021)))) print(warmthi) # Aluminium M3 #print("Alu M3") #print(np.mean(T5x_M3_x-T6x_M3_x)) # Messing M2 print("Messing M2") print(T1x_M2) warmthi=((385*8520*0.0009)/(2*T1x_M2*unp.log(ufloat(3.47,0.06)))) print(warmthi) # Messing M3 #print("Messing M3") #print(np.mean(T1x_M3_x-T2x_M3_x)) # Edelstahl M3 print("Edelstahl M3") print(T8x_M3)
def richardson(T,I_S): arbeit = [] for i in range(len(T)): arbeit.append(k_B*T[i]* unp.log((4*np.pi*e_0*m_0*f_diode2*(k_B**2) * (T[i]**2))/((h**3)*I_S[i]))) return arbeit
y = un.nominal_values(A_ratio) sy = un.std_devs(A_ratio) mean_ratio = np.mean(y) std_ratio = np.std(y) mean_ratio_e = uc.ufloat(mean_ratio, std_ratio) for I_l, Is, Ias, A_rat in zip(labels, intensities[0], intensities[1], A_ratio): print("\cellcolor{LightCyan}$%s$ A & $%s$ & $%s$ & $%s$ \\\\"%( I_l[:-2], uc_str(Is), uc_str(Ias), uc_str(A_rat, 5))) print('\n') print('Mean intensity ratio: ', uc_str(uc.ufloat(mean_ratio, std_ratio))) # Print latex table of wavenumbers lamb_all = np.array(x0s).reshape(9, 2) d_lin = np.load(npy_dir + 'ccd_calibration.npy') lamb_all = linear(lamb_all, *d_lin) # Integrate error on wavelength of CCD lamb_mean = np.mean(lamb_all, 0) lamb_laser = np.load(npy_dir + 'ccd_lamb_laser.npy')[0] dnu = (1 / lamb_mean - 1 / lamb_laser) * 10**7 lits = np.array(['bla', 'blub']) # S, S, S, AS, AS for CCl4 print('\n Wavenumbers of both peaks:') for i, x0, dnu_cm, lit in enum(lamb_mean, lamb_to_cm(lamb_mean), lits): print("\cellcolor{LightCyan}$%i$ & $%s$ & $%s$ & $%s$ \\\\"%( i+1, uc_str(x0), uc_str(dnu_cm), lit)) # Calculation of temperature (uses SI units!) from scipy.constants import k, c, h nu_l_si = c / lamb_laser dnu_si = np.mean(abs(c / lamb_mean - nu_l_si)) # in Hz!!! T = -(h * dnu_si * 10**9) / (k * un.log(mean_ratio_e * ((nu_l_si - dnu_si) / (nu_l_si + dnu_si))**4)) print('\n\Delta \\nu = ' + uc_str(dnu_si * 10**-2) + ' Hz') print('Temperatur T = ' + uc_str(T) + ' K') print('Temperatur T = ' + uc_str(T - 273.15) + ' ^\circ C')
import matplotlib.pyplot as plt 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')
# Temperaturdifferenzen dT = unp.uarray(np.zeros(len(T) - 1), 0) for i in range(len(T) - 1): dT[i] = T[i + 1] - T[i] # print(dT) # Energie bestimmen/ bzw. die zugeführte Wärmemenge E = U * I * t # print(t) # Conclusio: Verwende die Funktion für alpha perr = np.sqrt(np.diag(covs)) param = unp.uarray(params, perr) # print(param) alpha = param[2] * unp.log(param[0] * T + param[1]) # print(alpha) # Cp bestimmen Cp = M / m * E / dT # Cv bestimmen Cv = Cp - 9 * (alpha[1:]) ** 2 * V0 * T[1:] * K # Plot plt.errorbar(noms(T[1:]), noms(Cp), xerr=sdevs(T[1:]), yerr=sdevs(Cp), fmt="bx", label=r"$C_p$") plt.errorbar(noms(T[1:]), noms(Cv), xerr=sdevs(T[1:]), yerr=sdevs(Cv), fmt="mx", label=r"$C_V$") plt.grid() plt.xlabel(r"$T\:/\:\si\kelvin$")