def Levakovic_i(param, y): if certain: num = (y / param[0])**(1 / (2 * param[2])) * np.sqrt(param[1]) den = np.sqrt(1 - ((y / param[0])**(1 / param[2]))) else: num = (y / param[0])**(1 / (2 * param[2])) * unp.sqrt(param[1]) den = unp.sqrt(1 - ((y / param[0])**(1 / param[2]))) x = num / den return x
def plot_u(cal_file, fm_file, offset_file, description, accidental_offset, results_file): M = np.genfromtxt(cal_file) N = np.genfromtxt(fm_file) O = np.genfromtxt(offset_file) i_helm = M[:,1] #current applied to helmholtz for calibration measurement b_helm = M[:,2] #field applied to helmholtz coil for calibration measurement p, cov = np.polyfit(i_helm, b_helm, 1, cov=True) #fit a line to calibration measurement so that we get a calibration i_fm = N[:,1] #current applied to helmmholtz for shielding measurement b_fm = unumpy.uarray(N[:,2],0.0005) - accidental_offset #field measured inside of ferromagnet shield B_earth = np.polyval(p,0) #We get the Earths magnetic field from i=0 of the Helmholtz calibration B_fm_no_i = unumpy.uarray(np.mean(O[:,2]), np.std(O[:,2])) #Get average and error for initial magnetization mag = B_fm_no_i - B_earth #initial magnetization is the field inside of the ferromagnet before any field is applied minus the earths magnetic field Bin = b_fm - mag #internal magnetization is the measured internal field minus the initial magnetization. This correction might not be necessary for a soft ferromagnet Bext = unumpy.uarray(np.polyval(p,i_fm), 0.0005) #external field Bext_nom = unumpy.nominal_values(Bext) Bext_err = unumpy.std_devs(Bext) B = Bext/Bin c = a/b u=(-2*B + c**2 - 2*unumpy.sqrt(B**2 - B*c**2 - B + c**2) + 1)/(c**2 - 1) u_nom = unumpy.nominal_values(u) u_err = unumpy.std_devs(u) #cakculate uerr with just point to point uncertainties. I define this as just #uncertainty from the field measurements u_pp=(-2*B + c.nominal_value**2 - 2*unumpy.sqrt(B**2 - B*c.nominal_value**2 - B + c.nominal_value**2) + 1)/(c.nominal_value**2 - 1) #calculate uerr from just geometry uncertainties u_geom=(-2*unumpy.nominal_values(B) + c**2 - 2*unumpy.sqrt(unumpy.nominal_values(B)**2 - unumpy.nominal_values(B)*c**2 - unumpy.nominal_values(B) + c**2) + 1)/(c**2 - 1) ##obtain uncertainties from field u_err_pp = unumpy.std_devs(u_pp) ##obtain uncertainties from geometry u_err_geom = unumpy.std_devs(u_geom) with open(results_file, "w") as myfile: myfile.write('#Bext, sig_Bext, ur, sig_ur, sig_ur_pp, sig_ur_corr\n') for j in range(0, len(u_nom)): myfile.write('%s\t%s\t%s\t%s\t%s\t%s\n' %( Bext_nom[j], Bext_err[j], u_nom[j], u_err[j], u_err_pp[j], u_err_geom[j])) plt.errorbar(Bext_nom, u_nom, u_err, marker = '.', label = description)
def Stix_Vp_Vs(pressure, temperature, params, Tr=300.): ''' Returns unit:[km/s]` Returns unit:[km/s]` Returns unit:[kg/m3]` ''' r, K, G, V, Rho = Stix_EOS(pressure, temperature, params, Tr) Vp = unp.sqrt((K + 4. * G / 3.) / Rho) / 1000. Vs = unp.sqrt(G / Rho) / 1000. #print Vs return Vp, Vs, Rho / 1000., K, G
def plot_u(cal_file, fm_file, offset_file, description, accidental_offset, results_file): M = np.genfromtxt(cal_file) N = np.genfromtxt(fm_file) O = np.genfromtxt(offset_file) i_helm = M[:,1] #current applied to helmholtz for calibration measurement b_helm = M[:,2] #field applied to helmholtz coil for calibration measurement p, cov = np.polyfit(i_helm, b_helm, 1, cov=True) #fit a line to calibration measurement so that we get a calibration i_fm = N[:,1] #current applied to helmmholtz for shielding measurement b_fm = unumpy.uarray(N[:,2],0.0005) - accidental_offset #field measured inside of ferromagnet shield B_earth = np.polyval(p,0) #We get the Earths magnetic field from i=0 of the Helmholtz calibration B_fm_no_i = unumpy.uarray(np.mean(O[:,2]), np.std(O[:,2])) #Get average and error for initial magnetization mag = B_fm_no_i - B_earth #initial magnetization is the field inside of the ferromagnet before any field is applied minus the earths magnetic field Bin = b_fm - mag #internal magnetization is the measured internal field minus the initial magnetization. This correction might not be necessary for a soft ferromagnet Bext = unumpy.uarray(np.polyval(p,i_fm), 0.0005) #external field Bext_nom = unumpy.nominal_values(Bext) Bext_err = unumpy.std_devs(Bext) B = Bext/Bin c = a/b #calculate u_r u=(-2*B + c**2 - 2*unumpy.sqrt(B**2 - B*c**2 - B + c**2) + 1)/(c**2 - 1) u_nom = unumpy.nominal_values(u) u_err = unumpy.std_devs(u) #cakculate uerr with just point to point uncertainties. I define this as just #uncertainty from the field measurements u_pp=(-2*B + c.nominal_value**2 - 2*unumpy.sqrt(B**2 - B*c.nominal_value**2 - B + c.nominal_value**2) + 1)/(c.nominal_value**2 - 1) #calculate uerr from just geometry uncertainties u_geom=(-2*unumpy.nominal_values(B) + c**2 - 2*unumpy.sqrt(unumpy.nominal_values(B)**2 - unumpy.nominal_values(B)*c**2 - unumpy.nominal_values(B) + c**2) + 1)/(c**2 - 1) ##obtain uncertainties from field u_err_pp = unumpy.std_devs(u_pp) ##obtain uncertainties from geometry u_err_geom = unumpy.std_devs(u_geom) with open(results_file, "w") as myfile: myfile.write('#Bext, sig_Bext, ur, sig_ur, sig_ur_pp, sig_ur_corr\n') for j in range(0, len(u_nom)): myfile.write('%s\t%s\t%s\t%s\t%s\t%s\n' %( Bext_nom[j], Bext_err[j], u_nom[j], u_err[j], u_err_pp[j], u_err_geom[j])) plt.errorbar(Bext_nom, u_nom, u_err, marker = '.', label = description)
def HP_Vp_Vs(Pressure, Temperature, params, Tr=298): ''' Returns unit:[km/s]` Returns unit:[km/s]` Returns unit:[kg/m3]` ''' K = HP_K(Pressure, Temperature, params) G, Rho = HP_G(Pressure, Temperature, params, Tr, return_Rho=True) Vp = unp.sqrt((K + 4. * G / 3.) / Rho) Vs = unp.sqrt(G / Rho) #print Vs return Vp, Vs, Rho, K, G
def plot_u(cal_file, fm_file, description, accidental_offset, results_file): M = np.genfromtxt(cal_file) #turn calibration file into a matrix N = np.genfromtxt(fm_file) #turn fm_scan file into a matrix i_helm = M[:,1] #current applied to helmholtz for calibration measurement b_helm = M[:,2] #field applied to helmholtz coil for calibration measurement p, cov = np.polyfit(i_helm, b_helm, 1, cov=True) #fit a line to calibration measurement so that we get a calibration i_fm = N[:,1] #current applied to helmmholtz for shielding measurement Bin = unumpy.uarray(N[:,2],0.0005) - accidental_offset #field measured inside of ferromagnet shield Bin_nom = unumpy.nominal_values(Bin) Bin_err = unumpy.std_devs(Bin) Bext = unumpy.uarray(np.polyval(p,i_fm), 0.0005) #external field Bext_nom = unumpy.nominal_values(Bext) Bext_err = unumpy.std_devs(Bext) B = Bin/Bext #ratio of internal to external field #calculate permeability u = (B*c**2 + B -2 -2*unumpy.sqrt(B**2*c**2 - B*c**2 - B + 1))/(B*c**2-B) print(u) u_nom = unumpy.nominal_values(u) u_err = unumpy.std_devs(u) #cakculate uerr with just point to point uncertainties. I define this as just #uncertainty from the field measurements u_pp = (B*c.n**2 + B -2 -2*unumpy.sqrt(B**2*c.n**2 - B*c.n**2 - B + 1))/(B*c.n**2-B) u_err_pp = unumpy.std_devs(u_pp) #calculate uerr from just geometry uncertainties u_geom = (unumpy.nominal_values(B)*c**2 + unumpy.nominal_values(B) -2 -2*unumpy.sqrt(unumpy.nominal_values(B)**2*c**2 - unumpy.nominal_values(B)*c**2 - unumpy.nominal_values(B) + 1))/(unumpy.nominal_values(B)*c**2-unumpy.nominal_values(B)) u_err_geom = unumpy.std_devs(u_geom) #write results onto a text file with open(results_file, "w") as myfile: myfile.write('#Bext, sig_Bext, Bi, sig_Bi, ur, sig_ur, sig_ur_pp, sig_ur_corr\n') for j in range(0, len(u_nom)): myfile.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' %( Bext_nom[j], Bext_err[j], Bin_nom[j], Bin_err[j], u_nom[j], u_err[j], u_err_pp[j], u_err_geom[j])) plt.errorbar(Bext_nom, u_nom, u_err, marker = '.', label = description)
def calc_mu(Bin, Bout, radius_inner, radius_outer): # ratio of inner and outer radius radius_ratio = radius_inner / radius_outer print( radius_ratio ) # ratio of internal to external field B_ratio = Bin / Bout # convert from Series object to Numpy Array object B_ratio = B_ratio.values # If value under square root becomes neagtive, set B_ratio to NaN # (this seems to happen with Argonne MRI measurements at low fields) B_ratio[ (B_ratio**2) * (radius_ratio**2) - B_ratio * (radius_ratio**2) - B_ratio + 1 < 0 ] = np.nan # Calculate permeability. Here, use both uncertainties from field measurements and uncertainties from geometry, i.e. radius measurements. mu = ( B_ratio * (radius_ratio**2) + B_ratio - 2 -2 * unumpy.sqrt( (B_ratio**2) * (radius_ratio**2) - B_ratio * (radius_ratio**2) - B_ratio + 1 ) ) / ( B_ratio * (radius_ratio**2) - B_ratio ) # store nominal values of mu in separate array mu_val = unumpy.nominal_values(mu) # store combined uncertainties of mu in separate array mu_err = unumpy.std_devs(mu) # Calculate uncertainties of mu values from just field measurement uncertainties (= point-to-point fluctuations). Ignore geometry (=radius) uncertainties. mu_pp = ( B_ratio * (radius_ratio.n**2) + B_ratio - 2 -2 * unumpy.sqrt( (B_ratio**2) * (radius_ratio.n**2) - B_ratio * (radius_ratio.n**2) - B_ratio + 1 ) ) / ( B_ratio * (radius_ratio.n**2) - B_ratio ) # store point-to-point uncertainties of mu in separate array mu_err_pp = unumpy.std_devs(mu_pp) # Calculate uncertainties of mu values from just geometry uncertainties (= systematic uncertainty, i.e. all points move together). Ignore field uncertainties. B_ratio_n = unumpy.nominal_values( B_ratio ) mu_geom = ( B_ratio_n * (radius_ratio**2) + B_ratio_n - 2 -2 * unumpy.sqrt( (B_ratio_n**2) * (radius_ratio**2) - B_ratio_n * (radius_ratio**2) - B_ratio_n + 1 ) ) / ( B_ratio_n * (radius_ratio**2) - B_ratio_n ) # store geometric uncertainties of mu in separate array mu_err_geom = unumpy.std_devs(mu_geom) return( mu_val, mu_err, mu_err_pp, mu_err_geom )
def linregress(x, y): assert len(x) == len(y) N = len(y) Delta = N * sum(x**2) - (sum(x))**2 A = (N * sum(x * y) - sum(x) * sum(y)) / Delta B = (sum(x**2) * sum(y) - sum(x) * sum(x * y)) / Delta sigma_y = unp.sqrt(sum((y - A * x - B)**2) / (N - 2)) A_error = sigma_y * unp.sqrt(N / Delta) B_error = sigma_y * unp.sqrt(sum(x**2) / Delta) return [A, B], [A_error, B_error], sigma_y
def hugoniot_p_nlin(rho, rho0, a, b, c): """ calculate pressure along a Hugoniot throug nonlinear equations presented in Jameison 1982 :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param a: prefactor for nonlinear fit of Hugoniot data :param b: prefactor for nonlinear fit of Hugoniot data :param c: prefactor for nonlinear fit of Hugoniot data :return: pressure along Hugoniot in GPa """ eta = 1. - (rho0 / rho) Up = np.zeros_like(eta) if isuncertainties([rho, rho0, a, b, c]): Up[eta != 0.] = ((b * eta - 1.) + unp.sqrt( np.power((1. - b * eta), 2.) - 4. * np.power(eta, 2.) * a * c)) /\ (-2. * eta * c) else: Up[eta != 0.] = ((b * eta - 1.) + np.sqrt( np.power((1. - b * eta), 2.) - 4. * np.power(eta, 2.) * a * c)) /\ (-2. * eta * c) Us = a + Up * b + Up * Up * c Ph = rho0 * Up * Us return Ph
def compute_fliper_guess(f_data: np.ndarray, kwargs: Dict) -> Union[float, None]: if internal_teff in kwargs.keys(): T_eff = kwargs[internal_teff] else: return None mask_high = f_data[0] < 277 F_p_list = [] for lower_f, weight in [(0.7, 78), (7, 8), (0.2, 7), (50, 4), (20, 2)]: mask = np.logical_and(f_data[0] > lower_f, mask_high) F_p = np.mean(f_data[1][mask]) - noise( np.array((f_data[0][mask], f_data[1][mask]))) F_p_list.append((F_p, weight)) F_p_list = np.array(F_p_list).T F_p = np.average(F_p_list.T[0], weights=F_p_list.T[1]) log_g = quadraticPolynomial(np.log10(F_p), *fliper_fit()) t_sun = 5778 nu_max_sun = 3090 logg_sun = 4.44 nu_max = (10**log_g / 10**logg_sun) * 1 / unp.sqrt( T_eff / t_sun) * nu_max_sun return nu_max.nominal_value
def u_normalize_dir(self, u_dir_x, u_dir_y, u_dir_z): """Normalize direction vector Parameters ---------- u_dir_x : unumpy.array The x-component of the direction vector with uncertainty. u_dir_y : unumpy.array The y-component of the direction vector with uncertainty. u_dir_z : unumpy.array The z-component of the direction vector with uncertainty. Returns ------- unumpy.array, unumpy.array, unumpy.array The normalized direction vector components with uncertainties. """ if self.weighted_normalization: if not self.is_normalized(u_dir_x.nominal_value, u_dir_y.nominal_value, u_dir_z.nominal_value): raise NotImplementedError( 'Direction vector must be normalized!') return u_dir_x, u_dir_y, u_dir_z else: norm = unumpy.sqrt(u_dir_x**2 + u_dir_y**2 + u_dir_z**2) return u_dir_x / norm, u_dir_y / norm, u_dir_z / norm
def mStarred(a, N, B, n): e_0 = constants.value(u'elementary charge') #eps_0 = constants.value(u'epsilon_0') doesnt work for whatever reason eps_0 = 8.8541878128e-12 c = constants.value(u'speed of light in vacuum') return unp.sqrt(N * B * e_0**3 / (8 * np.pi * np.pi * eps_0 * a * c**3 * n))
def depth2rp(P_days, depth, duration_days, Ms, Rs): '''Compute the planet radius from the transit depth and duration using the analtyical treatment from Mandel & Agol 2002''' assert 0 < depth < 1 # compute distance from centres at T0 sma = rvs.semimajoraxis(P_days, Ms, 0) a_Rs = rvs.AU2m(sma) / rvs.Rsun2m(Rs) assert a_Rs > 1 b = rvs.impactparam_T(P_days, Ms, Rs, duration_days) assert abs(b) <= 1 inc = float(rvs.inclination(P_days, Ms, Rs, b)) z = compute_distance_center(a_Rs, inc) # compute size ratio (p=rp/Rs) p_simple = unp.sqrt(depth) if z <= 1 - p_simple: p = p_simple else: ps = np.logspace(-6, 0, 1000) depths = p2depth_grazing(ps, z) if (np.nanmax(depths) < z) or (np.nanmin(depths) > z): p = p_simple else: fint = interp1d(ps, depths) p = float(fint(depth)) # compute planet radius rp = rvs.m2Rearth(rvs.Rsun2m(p * Rs)) return rp
def radius(drops, viscosity): radi = [] for i in range(len(drops)): radius = unp.sqrt(9*viscosity*(drops[i][2]-drops[i][3])/(2*d.g*(d.density_oil-d.density_air))) radi.append(radius) # print("UNICORNS 4 EVVAA:", len(radi)) return radi
def charge(E, drops, viscosity): q_charge = [] for i in range(len(drops)): charge = 3 * np.pi * viscosity * unp.sqrt(9*viscosity*(drops[i][2]-drops[i][3])/(4*d.g*(d.density_oil-d.density_air))) *(drops[i][2]+drops[i][3])/E[i] q_charge.append(charge) # print("HEEEEELPP:", len(q_charge)) return q_charge
def get_average_quantities(self,number_format='f',soln_cov_orig=None, verbose=False): values = [] labels = [] attributes = np.array(['closure_quantities','baseline_quantities']) for ii,attribute in enumerate(attributes): for jj,col_name in enumerate(getattr(self,attribute).colnames): mean_value = np.mean(getattr(self,attribute)[col_name]) std_value = np.std( getattr(self,attribute)[col_name]) if verbose: if number_format=='f': print('Average %s is %3.3f +/- %3.3f' % (col_name,mean_value,std_value)) values.append(mean_value) labels.append('Mean '+col_name+'_simple') values.append(std_value) labels.append('RMS '+col_name+'_simple') if soln_cov_orig is not None: fringe_phase_cov, fringe_amplitude_cov, closure_phase_cov, closure_amplitude_cov = u_get_phases_and_amplitudes(soln_cov_orig) for observable in ['fringe_phase_cov', 'fringe_amplitude_cov', 'closure_phase_cov', 'closure_amplitude_cov']: exec('data = %s'%observable) mean_value = np.mean( unumpy.nominal_values(data) ) weighted_mean_value = np.average(unumpy.nominal_values(data), weights=unumpy.std_devs(data) ) std_value = unumpy.nominal_values( unumpy.sqrt(np.mean(np.abs(data - np.mean(data))**2)) ) values.append(mean_value) labels.append('Mean '+observable) values.append(weighted_mean_value) labels.append('Weighted mean '+observable) values.append(std_value) labels.append('RMS '+observable) return np.array(values), np.array(labels)
def stress_from_strain_inplane(ex,ey,exy=0,ec=None,dex=None): if dex is None: if ec is None: raise else: E,v = ec else: E,v = __Ev_from_DEX(*dex) f = E/(1-v**2) stress_x=f*(ex+v*ey) stress_y=f*(ey+v*ex) stress_xy=f*(1-v)*exy smean = (stress_x+stress_y)/2. sdiff = unumpy.sqrt(((stress_x-stress_y)/2)**2.+stress_xy**2) stress_1 = smean+sdiff stress_2 = smean-sdiff rotation = unumpy.arctan2(stress_xy,sdiff)/2 #s1,s2,srot = __principal_inplane(nominal_value(stress_x),nominal_value(stress_y),nominal_value(stress_xy)) return dict(stress_x=stress_x, stress_y=stress_y, stress_xy=stress_xy, stress_1=stress_1, stress_2=stress_2, stress_rotation=rotation)
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 Stix_thermal_pressure(Pressure, Temperature, params, Tr=300): """ This function calcaulte the thermal pressure, equation of state from Stixrude and Lithgow-Bertelloni (2005) Args: Pressure: unit Pa Temperautre: unit K Tr: temperature at reference unit K, default 300K """ r = Stix_Compressive(Pressure, Temperature, params, Tr) aii = 6. * params['grueneisen_0'] #Eq47 aiikk = -12. * params['grueneisen_0'] + 36. * ( params['grueneisen_0']** 2) - 18. * params['q_0'] * params['grueneisen_0'] f = 0.5 * (r**(2. / 3.) - 1) Gru = (1. / 6.) / (1 + aii * f + 0.5 * aiikk * f * f) * (2 * f + 1) * (aii + aiikk * f) Debye = abs( unp.sqrt(1 + aii * f + 0.5 * aiikk * f * f)) * params['Debye_0 (K)'] E1 = Energy(Debye, Temperature) E2 = Energy(Debye, Tr) EthVT = (9. * params['n'] * gas_constant * Temperature) * ( (Debye / Temperature) **(-3)) * E1 #integrate.quad(Debye_int_func,0.,Debye/Temperature)[0] EthVT0 = (9. * params['n'] * gas_constant * Tr) * ((Debye / Tr)**( -3)) * E2 #integrate.quad(Debye_int_func,0.,Debye/Tr)[0] Pth = (EthVT - EthVT0) * (Gru * r / params['V_0 (cm³/mol)']) return Pth, aii, aiikk, r, E1, E2
def col_dens_hnco_err(Tex, tau, dtex, dtau): """ Returns the column density (Garden et al 1991) From sanhueza 2012, and references therein Tex: Excitation temperature tau=integral of the opacity (\int tau dv) nu=frequeancy in Hz Asumin R=1 which is diferent only for molecules with hyperfine structure """ #EJ is EJ/k nu = 87.925252e9 Ej = 6.32957 R = 1 c = 2.98e10 #cm s-1 pi = 3.141516 k = 1.38 * 1e-16 #erg K-1 h = 6.626 * 1e-27 #erg s Tbg = 2.73 Tex = unumpy.uarray(Tex, dtex) tau = unumpy.uarray(tau, dtau) Qrot = unumpy.sqrt((pi * ((Tex * k)**3)) / ((h**3) * 918.417805e9 * 11.071010e9 * 10.910577e9)) gu = 9.0 aul = 8.78011e-6 a1 = (8 * pi * (nu**3)) / ((c**3) * R) a2 = Qrot / (gu * aul) a3 = unumpy.exp(Ej / Tex) / (1 - unumpy.exp(-(h * nu) / (k * Tex))) a4 = 1 / (jota2(Tex, nu) - jota2(Tbg, nu)) a5 = tau #where tau=integral (tau dv) return a1 * a2 * a3 * a4 * a5
def dOmega(theta_lab, n): """ function to find dΩlab/dΩcm Arguments --------- theta_lab : scattering angle in the lab system [rad] n : A_t / A_i; A_t, A_i means mass number of target particle or incident particle Return ------ dΩlab/dΩcm : factor to convert differential cross-section in the lab system to differential cross-section in the center-of-mass system Notice ------ This function do not consider relativity """ if isinstance(theta_lab, uncertainties.core.AffineScalarFunc): return umath.pow( 2.0 * umath.cos(theta_lab) / n + (1.0 + umath.cos(2.0 * theta_lab) / (n**2.0)) / umath.sqrt(1.0 - umath.pow(umath.sin(theta_lab) / n, 2.0)), -1.0) elif isinstance(theta_lab, np.ndarray) and isinstance( theta_lab[0], uncertainties.core.AffineScalarFunc): return unp.pow( 2.0 * unp.cos(theta_lab) / n + (1.0 + unp.cos(2.0 * theta_lab) / (n**2.0)) / unp.sqrt(1.0 - unp.pow(unp.sin(theta_lab) / n, 2.0)), -1.0) else: return np.power( 2.0 * np.cos(theta_lab) / n + (1.0 + np.cos(2.0 * theta_lab) / (n**2.0)) / np.sqrt(1.0 - np.power(np.sin(theta_lab) / n, 2.0)), -1.0)
def _compute_sigrp(frac_sigRs=.1): ''' Use the TESS parameters to estimate the measurement uncertainty on the planet's radius. See http://adsabs.harvard.edu/abs/2008ApJ...689..499C for equations. ''' # Get the 3sigma results starnums, Nharps, Nnirps, Nspirou, texpharps, texpnirps, texpspirou, tobsharps, tobsnirps, tobsspirou, min_Nrv, bestspectrograph_Nrv, min_tobs, bestspectrograph_tobs = np.loadtxt( 'Results/median_results_3sigma_mp.dat', delimiter=',').T # Get TESS parameters including photometric uncertainty inds = np.array([2, 3, 5, 6, 14]) rp, P, K, Rs, logsigV = np.ascontiguousarray(get_TESS_data())[inds] # Compute transit depth uncertainty depth = compute_depth(rp, Rs) Gamma = compute_Gamma() T = compute_transit_duration(rp, P, K, Rs) Q = compute_Q(Gamma, T, depth, logsigV) sigdepth = compute_sigdepth(depth, Q) # compute corresponding planet radius uncertainty depth = unp.uarray(depth, sigdepth) Rs2 = rvs.m2Rearth(rvs.Rsun2m(unp.uarray(Rs, frac_sigRs * Rs))) rp2 = unp.sqrt(depth) * Rs2 return rp, unp.std_devs(rp2)
def calc_mu(Bin, Bout, radius_inner, radius_outer): # ratio of inner and outer radius radius_ratio = radius_inner / radius_outer # ratio of internal to external field B_ratio = Bin / Bout # convert from Series object to Numpy Array object B_ratio = B_ratio.values # If value under square root becomes neagtive, set B_ratio to NaN # (this seems to happen with Argonne MRI measurements at low fields) B_ratio[(B_ratio**2) * (radius_ratio**2) - B_ratio * (radius_ratio**2) - B_ratio + 1 < 0] = np.nan # Calculate permeability. Here, use both uncertainties from field measurements and uncertainties from geometry, i.e. radius measurements. mu = (B_ratio * (radius_ratio**2) + B_ratio - 2 - 2 * unumpy.sqrt( (B_ratio**2) * (radius_ratio**2) - B_ratio * (radius_ratio**2) - B_ratio + 1)) / (B_ratio * (radius_ratio**2) - B_ratio) # store nominal values of mu in separate array mu_val = unumpy.nominal_values(mu) # store combined uncertainties of mu in separate array mu_err = unumpy.std_devs(mu) # Calculate uncertainties of mu values from just field measurement uncertainties (= point-to-point fluctuations). Ignore geometry (=radius) uncertainties. mu_pp = (B_ratio * (radius_ratio.n**2) + B_ratio - 2 - 2 * unumpy.sqrt( (B_ratio**2) * (radius_ratio.n**2) - B_ratio * (radius_ratio.n**2) - B_ratio + 1)) / (B_ratio * (radius_ratio.n**2) - B_ratio) # store point-to-point uncertainties of mu in separate array mu_err_pp = unumpy.std_devs(mu_pp) # Calculate uncertainties of mu values from just geometry uncertainties (= systematic uncertainty, i.e. all points move together). Ignore field uncertainties. B_ratio_n = unumpy.nominal_values(B_ratio) mu_geom = (B_ratio_n * (radius_ratio**2) + B_ratio_n - 2 - 2 * unumpy.sqrt( (B_ratio_n**2) * (radius_ratio**2) - B_ratio_n * (radius_ratio**2) - B_ratio_n + 1)) / (B_ratio_n * (radius_ratio**2) - B_ratio_n) # store geometric uncertainties of mu in separate array mu_err_geom = unumpy.std_devs(mu_geom) return (mu_val, mu_err, mu_err_pp, mu_err_geom)
def e_geo(x, d=0): d /= 2 a = unumpy.sqrt(x**2 + (2 - d) ** 2) # Look at geometric_efficiency.png to see what these mean h1 = ufloat(2,0.1) h2 = ufloat(3,0.1) w1 = ufloat(22, 0.1) w2 = ufloat(30, 0.1) if x < 8: c = unumpy.sqrt(((w1 + w2) / 2)**2 + (h2 - h1)**2) b = unumpy.sqrt((h2 - d)**2 + ((w1 + w2) / 2 - x)**2) else: c = w1 b = unumpy.sqrt((w1 - x)**2 + (h1 - d)**2) theta = unumpy.arccos((a**2 + b**2 - c**2) / (2 * a * b)) return (1 - unumpy.cos(theta / 2)) / 2
def f_unc(time, Omega, Delta, maxAmp): """ similar to the raw function call, but uses unp instead of np for uncertainties calculations. :return: """ sin_arg = unp.sqrt(Omega**2 + Delta**2) * time / 2 amp = maxAmp * Omega**2 / (Omega**2 + Delta**2) return amp * unp.sin(sin_arg)**2
def Levakovic2_i(param, y): num = (y / param[0])**(1 / param[1]) den = 1 - num if certain: x = np.sqrt(num / den) else: x = unp.sqrt(num / den) return x
def meanDerivation(a): # a ist ein Array N = len(a) # Anzahl an Messwerten temp = 0. mittelwert = np.mean(a) # Mittelwert der Messwerte for value in a: temp += (value - mittelwert)**2 temp *= 1 / (N * (N - 1)) return unp.sqrt(temp)
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 linregress(x, y): assert len(x) == len(y) N = len(y) Delta = N * sum(x**2) - (sum(x))**2 A = (N * sum(x * y) - sum(x) * sum(y)) / Delta B = (sum(x**2) * sum(y) - sum(x) * sum(x * y)) / Delta sigma_y = unp.sqrt(sum((y - A * x - B)**2) / (N - 2)) A_error = sigma_y * unp.sqrt(N / Delta) B_error = sigma_y * unp.sqrt(sum(x**2) / Delta) y_quer = sum(y) / (N - 1) R = sum((A * x + B - y_quer)**2) / sum((y - y_quer)**2) #Bestimmtheitsmaß return [A, B], [A_error, B_error], R
def f_unc(o, O, o_0): """ similar to the raw function call, but uses unp instead of np for uncertainties calculations. :return: """ t = 0.045e-3 t1 = O**2 / ((o - o_0)**2 + O**2) sin_arg = t / 2 * unp.sqrt((o - o_0)**2 + O**2) return t1 * unp.sin(sin_arg)**2
def GcGs_to_azi(self): self.psi2[:] = np.arctan2(self.Gs, self.Gc)/2./np.pi*180. self.psi2[self.psi2<0.] += 180. self.amp[:] = np.sqrt(self.Gs**2 + self.Gc**2)/2.*100. Gc_with_un = unumpy.uarray(self.Gc, self.unGc) Gs_with_un = unumpy.uarray(self.Gs, self.unGs) self.unpsi2[:] = unumpy.std_devs( unumpy.arctan2(Gs_with_un, Gc_with_un)/2./np.pi*180.) self.unpsi2[self.unpsi2>90.] = 90. self.unamp[:] = unumpy.std_devs( unumpy.sqrt(Gs_with_un**2 + Gc_with_un**2)/2.*100.) self.unamp[self.unamp>self.amp] = self.amp[self.unamp>self.amp]
def _process(self, data: np.array) -> np.array: """Take the absolute value of the IQ data. Args: data: An N-dimensional array of complex IQ point as [real, imaginary]. Returns: A N-1 dimensional array, each entry is the absolute value of the given IQ data. """ # pylint: disable=no-member return unp.sqrt(data[..., 0] ** 2 + data[..., 1] ** 2) * self.scale
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 sqrt_lorentzian(x: np.ndarray, amp: float = 1.0, kappa: float = 1.0, x0: float = 0.0, baseline: float = 0.0) -> np.ndarray: r"""Square-root Lorentzian function for spectroscopy. .. math:: y = \frac{{\rm amp} |\kappa|}{\sqrt{\kappa^2 + 4(x -x_0)^2}} + {\rm baseline} """ return amp * np.abs(kappa) / unp.sqrt(kappa**2 + 4 * (x - x0)**2) + baseline
def pointDist(self): for i in range(4): for j in range(i + 1, 4): #self.dist_data[i][j]=self.dist_data[j][i]=unp.linalg.norm(self.points[i].means-self.points[j].means) x1 = self.points[i].means[0] #x1_err=self.points[i].ster[0] x2 = self.points[j].means[0] #x2_err=self.points[j].ster[0] y1 = self.points[i].means[1] #y1_err=self.points[i].ster[1] y2 = self.points[j].means[1] #print(x1,x2,y1,y2) self.dist_data[i][j] = unp.sqrt((x1 - x2)**2 + (y1 - y2)**2)
def tan2visibilities(coeffs): """ Long Summary ------------ Technically the fit measures phase AND amplitude, so to retrieve the phase we need to consider both sin and cos terms. Consider one fringe: A { cos(kx)cos(dphi) + sin(kx)sin(dphi) } = A(a cos(kx) + b sin(kx)), where a = cos(dphi) and b = sin(dphi) and A is the fringe amplitude, therefore coupling a and b. In practice we measure A*a and A*b from the coefficients, so: Ab/Aa = b/a = tan(dphi) call a' = A*a and b' = A*b (we actually measure a', b') (A*sin(dphi))^2 + (A*cos(dphi)^2) = A^2 = a'^2 + b'^2 Short Summary ------------- From the solution to the fit, calculate the fringe amplitude and phase. Parameters ---------- coeffs: 1D float array Returns ------- amp, delta: 1D float array, 1D float array fringe amplitude & phase """ if type(coeffs[0]).__module__ != 'uncertainties.core': # if uncertainties not present, proceed as usual # coefficients of sine terms mulitiplied by 2*pi delta = np.zeros(int((len(coeffs) - 1) / 2)) amp = np.zeros(int((len(coeffs) - 1) / 2)) for q in range(int((len(coeffs) - 1) / 2)): delta[q] = (np.arctan2(coeffs[2 * q + 2], coeffs[2 * q + 1])) amp[q] = np.sqrt(coeffs[2 * q + 2]**2 + coeffs[2 * q + 1]**2) log.debug('tan2visibilities: shape coeffs:%s shape delta:%s ', np.shape(coeffs), np.shape(delta)) # returns fringe amplitude & phase return amp, delta else: # propagate uncertainties qrange = np.arange(int((len(coeffs) - 1) / 2)) fringephase = unumpy.arctan2(coeffs[2 * qrange + 2], coeffs[2 * qrange + 1]) fringeamp = unumpy.sqrt(coeffs[2 * qrange + 2]**2 + coeffs[2 * qrange + 1]**2) return fringeamp, fringephase
def get_lumi_imbalance( data_frame: tfs.TfsDataFrame) -> Tuple[UFloat, UFloat, UFloat]: """ Calculate the IP1 / IP5 luminosity imbalance. The luminosity is taken as defined in `Concept of luminosity`, Eq(17): https://cds.cern.ch/record/941318/files/p361.pdf The calculation of the luminosity imbalance is then: .. math:: \\frac{L_{IP1}}{L_{IP5}}=\\frac{\\sqrt{\\beta_{x1,IP5}+\\beta_{x2,IP5}} \\cdot\\sqrt{\\beta_{y1,IP5}+\\beta_{y2,IP5}}} {\\sqrt{\\beta_{x1,IP1}+\\beta_{x2,IP1}}\\cdot\\sqrt{\\beta_{y1,IP1}+\\beta_{y2,IP1}}} and the error: .. math:: \\sigma_{\\frac{L_{IP1}}{L_{IP5}}} = \\frac{1}{2}\\frac{L_{IP1}}{L_{IP5}} \\cdot \\sqrt{\\sum_{\substack{z \\in (x,y) \\\\ i \\in (IP1, IP5) }} {\\frac{\\sigma^2_{\\beta_{z1,i}} + \\sigma^2_{\\beta_{z2,i}}} {(\\beta_{z1,i}+\\beta_{z2,i})^2}}} Args: data_frame (tfs.TfsDataFrame): a `TfsDataFrame` with the results from a kmod analysis. Returns: Tuple with the imbalance, the betas at IPs as ufloats. """ lumi_coefficient: Dict[str, UFloat] = {} for ip in IPS: LOG.debug(f"Computing luminosity contribution from optics for IP {ip}") ip_rows = data_frame.loc[[f"{ip}{beam}" for beam in BEAMS], :] beta_sums = [ up.uarray(ip_rows[f"{BETA}{plane}"].to_numpy(), ip_rows[f"{ERR}{BETA}{plane}"].to_numpy()).sum( ) # sum over beams for plane in PLANES ] lumi_coefficient[ip] = 0.5 * up.sqrt(np.prod(beta_sums)) imbalance = lumi_coefficient[IPS[0]] / lumi_coefficient[IPS[1]] LOG.info(f'{"Luminosity Imbalance":22s}: {imbalance:s}') LOG.info(f'{"Effective beta IP1":22s}: {lumi_coefficient[IPS[0]]:s}') LOG.info(f'{"Effective beta IP5":22s}: {lumi_coefficient[IPS[1]]:s}') return imbalance, lumi_coefficient[IPS[0]], lumi_coefficient[IPS[1]]
def experimental_form2(q_bin, dG, m, m_P, m_D, m_Pr, t0): Return = [] Q = np.array([np.mean(i) for i in q_bin]) for i in range(len(q_bin)): dq = q_bin[i][1] - q_bin[i][0] q = q_bin[i][0] + dq/2.0 P = p(q, m_P, m_D)**3 Return.append( 1.0 * unp.sqrt( dG[i] / dq * (24.0*np.pi**3) / (fermi**2 * P)) ) return Q, unp.nominal_values(Return), unp.std_devs(Return)
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 sqrt(number): number = Mixed(number) if isinstance(number.value, fr.Fraction): p = np.sqrt(number.value.numerator) q = np.sqrt(number.value.denominator) if (p % 1 == 0) and (q % 1 == 0): return Mixed(fr.Fraction(int(p), int(q))) else: return Mixed(np.sqrt(float(number.value))) elif isinstance(number.value, uc.UFloat): return Mixed(unumpy.sqrt(number.value).item()) elif isinstance(number.value, int): s = np.sqrt(number.value) if s % 1 == 0: return Mixed(int(s)) else: return Mixed(s) elif isinstance(number.value, float): return Mixed(float(np.sqrt(number.value)))
def Radius_korr(auf, ab, eta): return unp.sqrt((9*eta*((1/ab)*1e-3 - (1/auf)*1e-3))/(4*g*(rho_oel - rho_l)))
def Radius(auf, ab): return unp.sqrt((9*eta_l*((1/ab)*1e-3 - (1/auf)*1e-3))/(4*g*(rho_oel - rho_l)))
def Ladung(auf, ab, U): return 3*np.pi*unp.sqrt((9*eta_l*((1/ab)*1e-3 - (1/auf)*1e-3))/(4*g*(rho_oel - rho_l)))* ((1/ab)*1e-3 + (1/auf)*1e-3)/(U/d)
print(mag) Bin = ( b_fm - mag ) # internal magnetization is the measured internal field minus the initial magnetization. This correction might not be necessary for a soft ferromagnet Bext = unumpy.uarray(np.polyval(p, i_fm), 0.0005) # external field Bext_nom = unumpy.nominal_values(Bext) Bext_err = unumpy.std_devs(Bext) print(Bext - Bin) # calculate u_r u = ( -2 * Bext * b ** 2 + Bin * a ** 2 + Bin * b ** 2 - 2 * unumpy.sqrt(b ** 2 * (Bext ** 2 * b ** 2 - Bext * Bin * a ** 2 - Bext * Bin * b ** 2 + Bin ** 2 * a ** 2)) ) / (Bin * (a ** 2 - b ** 2)) # obtain nominal value and uncertainty from u u_nom = unumpy.nominal_values(u) u_err = unumpy.std_devs(u) # plt.errorbar(unumpy.nominal_values(Bext), u_nom, u_err) plt.errorbar(Bext_nom, u_nom, u_err, fmt=".") # plot u_r vs B_ext plt.errorbar( Bext_nom, u_nom, u_err, color="b" ) # plot a line as well so that it doesn't look like the values are just jumping around. plt.xlabel("$B_{ext}$ [mT]") plt.ylabel("Relative permeability") plt.title("Relative permeability measurement for kapton/steel powder") plt.savefig("permeability_scan.png")
Csp=ufloat(37,1)*10**-12 L=ufloat(31.90,0.05)*10**-3 R= ufloat(50,0) uCkopplung=unp.uarray([9.99,8.00,6.47,5.02,4.00,3.00,2.03,1.01],[9.99/100,8.00/100,6.47/100,5.02/100,4.00/100,3.00/100,2.03/100,1.01/100]) Ckopplung=uCkopplung*10**(-9) Cgesamt=(C*Ckopplung)/(2*C+Ckopplung)+Csp vau1m=np.array([30.56,30.57,30.57,30.57,30.57,30.57,30.58,30.58])*1000 vau2m=np.array([32.85,33.38,33.98,34.88,35.86,37.40,40.12,47.23])*1000 alpham=np.array([14,11,9,7,6,5,4,2]) # Resonanzfrequenz fres=unp.sqrt(1/(L*(C+Csp))-R**2/(4*L**2))/(2*np.pi) # Fundamentalfrequenz vau1 =1/(2*np.pi*unp.sqrt(L*(C+Csp))) vau2 = 1/(2*np.pi*unp.sqrt(L*Cgesamt)) #Abweichung der Fundamentalfrequenzen vau1dev=(vau1-vau1m)*100/vau1 vau2dev=(vau2-vau2m)*100/vau2 #Frequenzverhältnisse alpha=-(vau1+vau2)/(2*(vau1-vau2)) alphav=(alpha-alpham)*100/alpham # Ausgabe print("""
plt.plot(f, uc , 'b.', label="Kondensatorspannung") plt.xlabel(r'$Frequenz / Hz$') plt.ylabel(r'$Uc/U$') plt.xscale('log') plt.tight_layout() plt.legend(loc='best') plt.savefig('Kondensatorspannungen.pdf') L=ufloat(10.11e-3,0.03e-3) C=ufloat(2.098e-9,0.006e-9) R=ufloat(509.5,0.5) Re=R+50 rdiffomega=Re/L romegares=unp.sqrt(1/(C*L)-(Re/L)**2/2) print ('rdiffomega') print (rdiffomega) print ('romegares') print (romegares) rguete=romegares/rdiffomega print ('rguete') print (rguete) eomegadiff=ufloat(10000,0.1) eomegares=ufloat(33500,0.1) eguete=1/eomegadiff*eomegares print (eguete) #(rdiffomega)(5.040+/-0.016)e+04 #(romegares)(2.171+/-0.004)e+05 #(rguete)4.309+/-0.010
print(pcov) # Ausgabe: # 0.06566+/-0.00023 # (5.7+/-1.2)e-05 # # (0.06565624625512359+/-0.0002273424226440303, 5.658138734608184e-05+/-1.1937364033455201e-05) # [[ 5.16845771e-08 -2.45941014e-09] # [ -2.45941014e-09 1.42500660e-10]] # # a1=ufloat(parameters1[0].n,parameters1[0].s) # braucht man nicht, da python, wenn man parameters1[0] schreibt, mit ufloats rechnet. # Elasitzitätsmodul: E = (6 * m * const.g) / (h ** 4 * parameters1[0]) print(E) # Berechnung Mittelwert des Emoduls von Stab 1 e1 = ufloat(9.146e10, 0.032e10) e2 = ufloat(9.46e10, 0.20e10) e3 = ufloat(9.52e10, 0.04e10) e = (e1 + e2 + e3) / 3 print(e) # Standardabweichung des Mittelwerts s = unp.sqrt(1 / 6 * ((e1 - e) ** 2 + (e2 - e) ** 2 + (e3 - e) ** 2)) print(s)
p, cov = np.polyfit(i_helm, b_helm, 1, cov=True) #fit a line to calibration measurement so that we get a calibration print(cov) B_earth = np.polyval(p,0) #We get the Earths magnetic field from i=0 of the Helmholtz calibration B_fm_no_i = unumpy.uarray(np.mean(O[:,2]), np.std(O[:,2])) #Get average and error for initial magnetization print(B_earth) print(B_fm_no_i) mag = B_fm_no_i - B_earth #initial magnetization is the field inside of the ferromagnet before any field is applied minus the earths magnetic field print(mag) Bin = b_fm - mag #internal magnetization is the measured internal field minus the initial magnetization. This correction might not be necessary for a soft ferromagnet Bext = unumpy.uarray(np.polyval(p,i_fm), 0.0005) #external field Bext_nom = unumpy.nominal_values(Bext) Bext_err = unumpy.std_devs(Bext) #calculate u_r u=(-2*Bext*b**2 + Bin*a**2 + Bin*b**2 - 2*unumpy.sqrt(b**2*(Bext**2*b**2 - Bext*Bin*a**2 - Bext*Bin*b**2 + Bin**2*a**2)))/(Bin*(a**2 - b**2)) #obtain nominal value and uncertainty from u u_nom = unumpy.nominal_values(u) u_err = unumpy.std_devs(u) #plt.errorbar(unumpy.nominal_values(Bext), u_nom, u_err) plt.errorbar(Bext_nom, u_nom*Bext_nom, u_err, fmt = '.') #plot u_r vs B_ext plt.errorbar(Bext_nom, u_nom*Bext_nom, u_err, color = 'b') #plot a line as well so that it doesn't look like the values are just jumping around. plt.xlabel('$B_{ext}$ [mT]') plt.ylabel('Relative permeability') plt.title('Relative permeability measurement for kapton/steel powder') plt.savefig('permeability_scan.png')
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}$") plt.plot(1e6*sd, sd*slope1+intercept1, 'r-', label=r"Lineare Regression, $R < R_\text{max}$") plt.errorbar(1e6*unp.nominal_values(d[:5]), unp.nominal_values(N[:5]), fmt='rx', yerr=unp.std_devs(N[:5]), label=r"Messdaten, $R < R_\text{max}$") plt.errorbar(1e6*unp.nominal_values(d[5:]), unp.nominal_values(N[5:]), fmt='bx', yerr=unp.std_devs(N[5:]), label=r"Messdaten, $R > R_\text{max}$") #plt.errorbar(1e6*unp.nominal_values(d[4:5]), unp.nominal_values(N[4:5]), fmt='kx', yerr=unp.std_devs(N[4:5]), label=r"Messdaten, unberücksichtigt") plt.legend(loc='best') plt.xlabel(r"$D/\si{\micro\meter}$") plt.ylabel(r"$\ln((N-N_U)/\si{\per\second})$")
def sigma_2 (n, l, Delta_E, z): return z-unp.sqrt(unp.sqrt(Delta_E * l * (l+1) * n**3 / (R*a**2)))
unc1 = (0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001) unc2 = (0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01,0.01,0.01,0.01) unc3 = (0.005/3, 0.005/3,0.005/3, 0.005/3,0.005/3, 0.005/3,0.005/3, 0.005/3,0.005/3) unc4 = (0.001,0.001,0.001,0.001,0.001) Tung1 = unp.uarray(np.genfromtxt('data/l2/Tungekoppelt1.txt', unpack = True)/5, unc1) Tung2 = unp.uarray(np.genfromtxt('data/l2/Tungekoppelt2.txt', unpack = True)/5, unc1) Tplus = unp.uarray(np.genfromtxt('data/l2/Tplus.txt', unpack = True)/5, unc1) Tminus = unp.uarray(np.genfromtxt('data/l2/Tminus.txt', unpack = True)/5, unc1) Tgek1 = unp.uarray(np.genfromtxt('data/l2/Tgekoppelt1.txt', unpack = True)/5, unc4) Tgek2 = unp.uarray(np.genfromtxt('data/l2/Tgekoppelt2.txt', unpack = True)/3, unc3) Tgek = np.append(Tgek1, Tgek2) Tschwebung = unp.uarray(np.genfromtxt('data/l2/Tschwebung.txt', unpack = True)*2, unc2) l = ufloat(0.502, 0.005) K = ((Tplus.sum()/10)**2 - (Tminus.sum()/10)**2) / ((Tminus.sum()/10)**2 + (Tplus.sum()/10)**2) Ttheorie = unp.sqrt(l/9.81)*2*np.pi Tminustheorie = 2*np.pi/(unp.sqrt(9.81/l + 2*K/l)) Tschwebungtheorie = (Tplus.sum()/10)*(Tminus.sum()/10)/((Tplus.sum()/10)-(Tminus.sum()/10)) print(1-(Tschwebungtheorie)/(Tschwebung.sum()/14)) print('Kopplungskonstante aus T+ und T- errechnet:') print(K) #print((unp.sqrt(9.81/l + 2*K/l))) #print(unp.sqrt(l/9.81)**-1) print('Mittelwert der Schwingungsdauer des ersten Pendels:' ) print(Tung1.sum()/10) print('Mittelwert der Schwingungsdauer des zweiten Pendels:' ) print(Tung2.sum()/10)
def I(gf): return -(1-(gj/(4*gf)))+sqrt((1-(gj/(4*gf)))**2-0.75*(1-(gj/gf)))
##### from scipy import constants as const from imp import reload from uncertainties import unumpy as unp reload(eos_analysis) mass_li = 9.988346e-27 pi = const.pi hbar = const.hbar kb = const.Boltzmann profile = np.mean(profiles_865[:, :], 1) prof_offset = np.mean(profile[60:65]) profile -= prof_offset profile *= 1.20 density = 2 * profile / 7.265 * 10**12 omega_z = unp.uarray((5154) * 2 * pi, 140 * 2 * pi) a_z = unp.sqrt(hbar / (mass_li * omega_z)) omega_r = eos_analysis.radial_trap(864) * 2 * pi pixel_area = (13e-6*83.0/400)**2 r = np.linspace(0, len(profile), len(profile)) r *= np.sqrt(pixel_area) potential = 0.5 * mass_li * omega_r**2 * r**2 potential_nk = (potential/kb)* (10**9) a2d = eos_analysis.scattering2d(865, a_z) eb = (hbar**2) / (a2d**2 * mass_li) cutoff =43 end = 70 dens_fit, fit_result = eos_analysis.virial_fit_residuals2(0.2, 0.6, eb, density[cutoff:end], potential[cutoff:end])
print('tmax:') print(tmax) print ('Umax') print(Umax) # Dämpfungswiderstand ausrechnen # params_max = ucurve_fit(reg.reg_linear, tmax, Umax_log) params_max = ucurve_fit(reg.reg_linear, text, U_pos_ges_log) 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))
print(((Tplus.sum()/10)*(Tminus.sum()/10)/((Tplus.sum()/10)-(Tminus.sum()/10)))/(Tschwebung.sum()/10)) print('Kopplungskonstante aus T+ und T- errechnet:') print(K) #print((unp.sqrt(9.81/l + 2*K/l))) #print(unp.sqrt(l/9.81)**-1) print('Mittelwert der Schwingungsdauer des ersten Pendels:' ) print(Tung1.sum()/10) print('Mittelwert der Schwingungsdauer des zweiten Pendels:' ) print(Tung2.sum()/10) print('Mittelwert der Schwingungsdauer der phasengleichen Schwingung:' ) print(Tplus.sum()/10) print('Theoriewert für Schwingungsdauer der einzelnen Pendel sowie phasengleicher Schwingung:') print(unp.sqrt(l/9.81)*2*np.pi) print('Mittelwert der Schwingungsdauer der gegenphasigen Schwingung:' ) print(Tminus.sum()/10) print('Theoriewert für Schwingungsdauer der gegenphasigen Schwingung:') print(2*np.pi/(unp.sqrt(9.81/l + 2*K/l))) print('Mittelwert der Schwingungsdauer bei gekoppelter Schwingung:' ) print(Tgek.sum()/10) print('Mittelwert der Schwebungsdauer bei gekoppelter Schwingung:' ) print(Tschwebung.sum()/10) print('Theoriewert für Schwebungsdauer:') print((Tplus.sum()/10)*(Tminus.sum()/10)/((Tplus.sum()/10)-(Tminus.sum()/10)))
Bin = b_fm - mag #internal magnetization is the measured internal field minus the initial magnetization. This correction might not be necessary for a soft ferromagnet Bext = unumpy.uarray(np.polyval(p,i_fm), 0.001) #external field print(Bin) print(Bext) #Bin = abs(Bin) #Bext = abs(Bext) #print(Bin) #print(Bext) Bext_nom = unumpy.nominal_values(Bext) Bext_err = unumpy.std_devs(Bext) #calculate u_r B = Bext/Bin c = a/b u=(-2*B + c**2 - 2*unumpy.sqrt(B**2 - B*c**2 - B + c**2) + 1)/(c**2 - 1) #obtain nominal value and uncertainty from u u_nom = unumpy.nominal_values(u) u_err = unumpy.std_devs(u) #pylab.errorbar(unumpy.nominal_values(Bext), u_nom, u_err) pylab.errorbar(Bext_nom, u_nom, u_err, fmt = '.') #plot u_r vs B_ext pylab.errorbar(Bext_nom, u_nom, u_err, color = 'b') #plot a line as well so that it doesn't look like the values are just jumping around. pylab.xlabel('$B_{ext}$ [mT]') pylab.ylabel('Relative permeability') pylab.title('Relative permeability measurement') pylab.savefig('permeability_scan.png') with open("uncertainties.txt", "a") as myfile: for j in range(0,len(u_nom)): myfile.write('%s \t %s \t %s \n' %(Bext_nom[j], u_nom[j], u_err[j]))
#R2(509.5,0.5) #Rap(3.3e3) #1.22627763e-01 1.63147814e+02 3.47381148e+02 5.80136682e-02 #1.15649731e-02 L=ufloat(10.11e-3,0.03e-3) C=ufloat(2.098e-9,0.006e-9) Reff=2*L*pi2ny print ('pi2ny') print (pi2ny) #pi2ny(-5.53+/-0.16)e+03 print ('Reff') print(Reff) #Reff-111.9+/-3.3 Rap=unp.sqrt(4*L/C) print('Rap') print (Rap) #Rap4390.4+/-9.0 Tex=1/pi2ny print('Tex') print(Tex) #Tex-0.000181+/-0.000005 #print ('Refft') #print ('Text')
def norm(v): return unumpy.sqrt(np.dot(v, v))
def j(dt, ft): return ((-1/(dt*ft))+unp.sqrt((1/(dt*ft))**2+1))