def get_physical_params_from_psd_model(model_fit, Pgas, T = 300, rho_m=2200, Mgas=28.97e-3): """ retrieve the physical parameters from the fitted models to power spectral density :param model_fit: :param Pgas: gas pressure in mBar :param T: temperature of environment in Kelvins, default is 300K :param rho_m: mass density in units of kg/m^3, default is 2200kg/m^3 :param Mgas: molar mass of molecules, default is 28.97e-3 kg/mol for dry air :return: """ # get all the a parameters with their uncertainties fo, g, noise = [ufloat(m, s) for m, s in zip(model_fit.best_values.values(), np.sqrt(model_fit.covar.diagonal()))] wo = 2*pi*fo gamma = 2*pi*g mgas = Mgas/N_A # calculate the physical values with errors radius = 2.223 / rho_m * umath.sqrt(mgas / (kB * T)) * (Pgas*100) / gamma # radius in meters mass = 4*pi/3*rho_m*radius**3 # mass in kg C = wo**2 * noise / (T) # energy calibration factor in (bit*Hz)^2 / Kelvin c = umath.sqrt(mass*wo**2*noise / (kB * T))*1e-9 # position calibration factor in bit/nm (or V/nm) return {'radius': radius*1e9, 'mass': mass, 'C': C, 'c': c, 'fo':fo, 'g':g, 'x2':noise*C}
def get_einstein_R(lensMass, lensDist, sourceDist=None): """Calculates the einstein radius of a lens and source system. Args: lensMass (float) : Mass of the foreground lens object [Msol] lensMass Error (float) : Error im the Mass of the foreground lens object [Msol] lensDist (float) : Distance to the lens [pc] lensDist Error (float) : Error in the Distance to the lens [pc] SourceDist (float,optional) : Distance to the source. defaults to None. If none, caculation will assume sourceDist to be at infinity. [pc] Returns: einsteinR (float) : The Einstein radius [mas] """ if sourceDist is None: return (90.2 * np.sqrt(lensMass / lensDist)) else: return (90.2 * np.sqrt( (lensMass / lensDist) * (1 - lensDist / sourceDist)))
def fit_orthorhombic_cell(data_df, wavelength, verbose=True): """ data_df = data in pandas DataFrame wavelength = wavelength, can we get this from .get_bast_ptn_wavelength verbose returns unit cell fit results and statistics for an orthorhombic cell """ res_lin = fit_l_orthorhombic_cell(data_df, verbose=verbose) a_lin_star = ufloat(res_lin.params['Prefactor0'], res_lin.bse['Prefactor0']) b_lin_star = ufloat(res_lin.params['Prefactor1'], res_lin.bse['Prefactor1']) c_lin_star = ufloat(res_lin.params['Prefactor2'], res_lin.bse['Prefactor2']) a_lin = umath.sqrt(1. / a_lin_star) b_lin = umath.sqrt(1. / b_lin_star) c_lin = umath.sqrt(1. / c_lin_star) if verbose: print( str(datetime.datetime.now())[:-7], ': Orthorhombic cell: ', a_lin, b_lin, c_lin) res_nlin = fit_nl_orthorhombic_cell(data_df, a_lin.nominal_value, b_lin.nominal_value, c_lin.nominal_value, wavelength, verbose=verbose) a_res_nlin = ufloat(res_nlin.params['a'].value, res_nlin.params['a'].stderr) b_res_nlin = ufloat(res_nlin.params['b'].value, res_nlin.params['b'].stderr) c_res_nlin = ufloat(res_nlin.params['c'].value, res_nlin.params['c'].stderr) v_res_nlin = a_res_nlin * b_res_nlin * c_res_nlin a_nlin = a_res_nlin.nominal_value s_a_nlin = a_res_nlin.std_dev b_nlin = b_res_nlin.nominal_value s_b_nlin = b_res_nlin.std_dev c_nlin = c_res_nlin.nominal_value s_c_nlin = c_res_nlin.std_dev v_nlin = v_res_nlin.nominal_value s_v_nlin = v_res_nlin.std_dev if verbose: print( str(datetime.datetime.now())[:-7], ': Orthorhombic cell: ', a_res_nlin, b_res_nlin, c_res_nlin) if np.abs(a_lin.nominal_value - a_nlin) > a_lin.std_dev: print( str(datetime.datetime.now())[:-7], ': Difference between nonlinear and linear results exceed the error bar.' ) return a_nlin, s_a_nlin, b_nlin, s_b_nlin, c_nlin, s_c_nlin, \ v_nlin, s_v_nlin, res_lin, res_nlin
def get_dl_and_kpc_per_asec(z, H0=70, WM=0.26, WV=0.74): """Get luminosity distance. See """ WR = 0. # Omega(radiation) WK = 0. # Omega curvaturve = 1-Omega(total) c = 299792.458 # velocity of light in km/sec DTT = 0.5 # time from z to now in units of 1/H0 age = 0.5 # age of Universe in units of 1/H0 zage = 0.1 # age of Universe at redshift z in units of 1/H0 DCMR = 0.0 # comoving radial distance in units of c/H0 DA = 0.0 # angular size distance DA_Mpc = 0.0 kpc_DA = 0.0 DL = 0.0 # luminosity distance DL_Mpc = 0.0 a = 1.0 # 1/(1+z), the scale factor of the Universe az = 0.5 # 1/(1+z(object)) h = H0 / 100. WR = 4.165E-5 / (h * h) # includes 3 massless neutrino species, WK = 1 - WM - WR - WV az = 1.0 / (1 + 1.0 * z) age = 0. n = 1000 # number of points in integrals for i in range(n): a = az * (i + 0.5) / n adot = sqrt(WK + (WM / a) + (WR / (a * a)) + (WV * a * a)) age = age + 1. / adot zage = az * age / n DTT = 0.0 DCMR = 0.0 for i in range(n): a = az + (1 - az) * (i + 0.5) / n adot = sqrt(WK + (WM / a) + (WR / (a * a)) + (WV * a * a)) DTT = DTT + 1. / adot DCMR = DCMR + 1. / (a * adot) DTT = (1. - az) * DTT / n DCMR = (1. - az) * DCMR / n age = DTT + zage ratio = 1.00 x = sqrt(abs(WK)) * DCMR if x > 0.1: if WK > 0: ratio = 0.5 * (exp(x) - exp(-x)) / x else: ratio = sin(x) / x else: y = x * x if WK < 0: y = -y ratio = 1. + y / 6. + y * y / 120. return (c / H0) * ((az * ratio * DCMR) / (az * az)) * 3.086e22, ((c / H0) * az * ratio * DCMR) / 206.264806
def integral(): x1 = uc.ufloat( 20 /2 *10**(-3) , 1*10**(-3)) x2 = uc.ufloat( 150/2 *10**(-3) , 1*10**(-3)) L = uc.ufloat( 175 *10**(-3) , 1*10**(-3)) l = uc.ufloat( 150 *10**(-3) , 1*10**(-3)) I = uc.ufloat(10 , 0.1) N = 3600 A = N / (2 *L * (x2-x1)) factor = (x2 * (sqrt( x2**2 + ((L+l)/2)**2)- sqrt( x2**2 + ((L-l)/2)**2) ) \ -x1 * (sqrt( x1**2 + ((L+l)/2)**2)- sqrt( x1**2 + ((L-l)/2)**2) ) \ + (((L+l)/2)**2* log((x2 + sqrt(((L+l)/2)**2 + x2**2))/ (x1 + sqrt(((L+l)/2)**2 + x1**2)) ) \ -((L-l)/(4))**2* log((x2 + sqrt(((L-l)/2)**2 + x2**2))/ (x1 + sqrt(((L-l)/2)**2 + x1**2)) ))) print(factor) print(A * factor) a = np.load(input_dir +"a_3.npy") I = np.load(input_dir + "i_3.npy") I_fit = np.linspace(min(I),max(I),100) S_a = 0.2 S_I = 0.05 weights = a*0 + 1/S_a p, cov= np.polyfit(I,a, 1, full=False, cov=True, w=weights) (p1, p2) = uc.correlated_values([p[0],p[1]], cov) print(p1 / (A*factor)) print(p1/2556/100 *oe *60)
def calculate_abc_geometry(h, d): '''Returns the perpendicular distance geometry for the bicycle from the raw measurements. Parameters ---------- h : tuple Tuple containing the measured parameters h1-h5. (h1, h2, h3, h4, h5) d : tuple Tuple containing the measured parameters d1-d4 and d. (d1, d2, d3, d4, d) Returns ------- a : ufloat or float The rear frame offset. b : ufloat or float The fork offset. c : ufloat or float The steer axis distance. ''' # extract the values h1, h2, h3, h4, h5 = h d1, d2, d3, d4, d = d # get the perpendicular distances a = h1 + h2 - h3 + .5 * d1 - .5 * d2 b = h4 - .5 * d3 - h5 + .5 * d4 c = umath.sqrt(-(a - b)**2 + (d + .5 * (d2 + d3))**2) return a, b, c
def calculate_cbase(pH, pCO2, ctHb=3): """Calculate base excess. Calculate standard base excess, known as SBE, cBase(Ecf) or actual base excess, known as ABE, cBase(B) if ctHb is given. References ---------- [1] Radiometer ABL800 Flex Reference Manual English US. chapter 6-29, p. 265, equation 5. [2] Siggaard-Andersen O. The acid-base status of the blood. 4th revised ed. Copenhagen: Munksgaard, 1976. http://www.cabdirect.org/abstracts/19751427824.html :param float pH: :param float pCO2: kPa :param float ctHb: Concentration of total hemoglobin in blood, mmol/L If given, calculates ABE, if not - SBE. :return: Standard base excess (SBE) or actual base excess (ABE), mEq/L. :rtype: float """ a = 4.04 * 10**-3 + 4.25 * 10**-4 * ctHb pHHb = 4.06 * 10**-2 * ctHb + 5.98 - 1.92 * 10**(-0.16169 * ctHb) log_pCO2Hb = -1.7674 * (10** -2) * ctHb + 3.4046 + 2.12 * 10**(-0.15158 * ctHb) pHst = pH + math.log10(5.33 / pCO2) * ( (pHHb - pH) / (log_pCO2Hb - math.log10(7.5006 * pCO2))) cHCO3_533 = 0.23 * 5.33 * 10**((pHst - 6.161) / 0.9524) # There is no comments, as there is no place for weak man cBase = 0.5 * ((8 * a - 0.919) / a) + 0.5 * math.sqrt((( (0.919 - 8 * a) / a)**2) - 4 * ((24.47 - cHCO3_533) / a)) return cBase
def fit_cubic_cell(data_df, wavelength, verbose=True): """ data_df = data in pandas DataFrame wavelength = wavelength, can we get this from .get_bast_ptn_wavelength verbose returns unit cell fit results and statistics for a cubic cell """ res_lin = fit_l_cubic_cell(data_df, verbose=verbose) a_lin_star = ufloat(res_lin.params['Prefactor'], res_lin.bse['Prefactor']) a_lin = umath.sqrt(1. / a_lin_star) res_nlin = fit_nl_cubic_cell(data_df, a_lin.nominal_value, wavelength, verbose=verbose) a_res_nlin = ufloat(res_nlin.params['a'].value, res_nlin.params['a'].stderr) v_res_nlin = a_res_nlin * a_res_nlin * a_res_nlin a_nlin = a_res_nlin.nominal_value s_a_nlin = a_res_nlin.std_dev v_nlin = v_res_nlin.nominal_value s_v_nlin = v_res_nlin.std_dev if np.abs(a_lin.nominal_value - a_nlin) > a_lin.std_dev: print( 'Difference between nonlinear and linear results exceed the error bar.' ) return a_nlin, s_a_nlin, v_nlin, s_v_nlin, res_lin, res_nlin
def CalculateSTD(df): StandardDeviation = [] for key, grp in df.groupby(['SampleB', 'configuration']): astr = [ufloat(a, b) for a, b in zip(grp.CTR, grp.CTRerr)] StandardDeviation.append(tidystring(umath.sqrt(var(astr)))) return StandardDeviation
def magnetic_field(): x1 = uc.ufloat( 20 /2 *10**(-3) , 1*10**(-3)) x2 = uc.ufloat( 150/2 *10**(-3) , 1*10**(-3)) L = uc.ufloat( 175 *10**(-3) , 1*10**(-3)) l = uc.ufloat( 150 *10**(-3) , 1*10**(-3)) I = uc.ufloat(10 , 0.1) N = 3600 beta = N * I / (2 * (x2-x1)) #magnetic field at z = L/2 H = beta * log((x2 + sqrt((L/2)**2+ x2**2))/ ( x1 +\ sqrt((L/2)**2 + x1**2))) print(H) print(H/oe)
def qm_res1(): ''' solves the quadritic formular to compute q/m in air the list can obtain up to 2 values, depending on the discriminant of the quadratic formular ''' diskriminant = (u_w*r*w)**4 - 4*(4*K*u_x*A*w_res)**4 if diskriminant < 0: print 'Keine Lösung für Luft gefunden' return [] x1 = ( 4*u_w**2*r**6*w**4 + 4*r**4*w**2 * umath.sqrt( diskriminant ) ) / (128*A**2*(K*u_x)**4) x2 = ( 4*u_w**2*r**6*w**4 - 4*r**4*w**2 * umath.sqrt( diskriminant ) ) / (128*A**2*(K*u_x)**4) result = [] for x in [x1, x2]: if x > 0: result.append( umath.sqrt(x) ) return result
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 planet_prot(f,req,mp,j2): """ Function to calculate period of rotation of a planet Parameters ----------- f : float; planet oblateness req : float; Equatorial radius of planet in jupiter radii. mp : float; mass of planet in jupiter masses j2 : float; quadrupole moment of the planet Returns: -------- prot: rotation peropd of the planet in hours """ radius=req*c.R_jup mass= mp*c.M_jup prot=2*np.pi*sqrt(radius**3 / (c.G*mass*(2*f-3*j2))) return prot.to(u.hr).value
def output_params(timedays, NormFlux, fit, success, period, ecc, arg_periapsis): Flux, Ing, Egr = transiterout(np.arange(0, np.size(NormFlux)), fit[0], fit[1], fit[2], fit[3], fitting=True) print Ing # Get values and uncertainties from the fit Rp = ufloat((fit[0], np.sqrt(success[0][0]))) b1 = ufloat((fit[1], np.sqrt(success[1][1]))) vel = ufloat((fit[2], np.sqrt(success[2][2]))) midtrantime = ufloat((fit[3], np.sqrt(success[3][3]))) # gam1=ufloat((fit[4],np.sqrt(success[4][4]))) # gam2=ufloat((fit[5],np.sqrt(success[5][5]))) P = period ecc_corr = np.sqrt(1 - ecc ** 2) / (1 + ecc * umath.sin(arg_periapsis * np.pi / 180.0)) Ttot = (Egr[np.size(Egr) - 1] - Ing[0]) * ecc_corr Tfull = (Egr[0] - Ing[np.size(Ing) - 1]) * ecc_corr # delta=ufloat((1-Flux[fit[3]],1-Flux[fit[3]]+sqrt(success[3][3]))) delta = Rp ** 2 dt = timedays[2] - timedays[1] aRstar = ( 2 * delta ** 0.25 * P / (np.pi * dt * umath.sqrt(Ttot ** 2 - Tfull ** 2)) ) # *umath.sqrt(1-ecc**2)/(1+ecc*sin(arg_periapsis*pi/180.)) # bmodel=umath.sqrt((1-(Tfull/Ttot)**2)/((1-umath.sqrt(delta))**2-(Tfull/Ttot)**2 * (1+umath.sqrt(delta))**2)) #Not too sure why this doesn't work inc = (180 / np.pi) * umath.acos(b1 / aRstar) # print bmodel poutnames = ("Rp", "b1", "vel", "midtrantime", "gam1", "gam2") for iz in range(0, np.size(fit)): print poutnames[iz], fit[iz], np.sqrt(success[iz][iz]) print "--------------------------------" # Useful Conversions # R_Jup/R_Sun = 0.10279 # R_Sun = 0.00464913034 AU aRstarFIT = vel * P / (dt * 2 * np.pi) incFIT = (180 / np.pi) * umath.acos(b1 / aRstarFIT) # midtrantime_convert=midtrantime*dt*24*3600+time_days[0] # midtrantime_MJD=timedays[midtrantime]+54964.00111764 timebetween = timedays[int(midtrantime.nominal_value) + 1] - timedays[int(midtrantime.nominal_value)] print timebetween * dt # print "Midtrantime",midtrantime_convert.std_dev()#midtrantime_MJD print "aRstarFIT", aRstarFIT print "inclination", incFIT print "frac. rad.", Rp print "aRstar_mod", aRstar aRs = (aRstarFIT + aRstar) / 2 print "--------------------------------" print "Planetary Radius/Star Radius: ", Rp print "Inclination: ", incFIT print "Semi - Major Axis / Stellar Radius: ", aRs print "Mid-Transit Time [MJD]", pyplot.plot(time, NormFlux, linestyle="None", marker=".") pyplot.plot(time, transiter(np.arange(np.size(NormFlux)), fit[0], fit[1], fit[2], fit[3])) pyplot.show() return Flux, Rp, aRstarFIT, incFIT, aRstar, midtrantime
def fractionofevents(k, n): """https://indico.cern.ch/event/66256/contributions/2071577/attachments/1017176/1447814/EfficiencyErrors.pdf""" k = 1.0 * k n = 1.0 * n return ufloat( k / n, sqrt((k + 1) * (k + 2) / ((n + 2) * (n + 3)) - (k + 1)**2 / (n + 2)**2))
def ustd(list): """standard deviation""" if len(list) < 1: return float('nan') mean = umean(list) n = len(list) std = sqrt(sum([(x - mean)**2 for x in list])/( n*(n-1) )) return std*t_n(len(list))
def ThreePointU(p1, p2, p3): ''' ThreePointU calculates the strike (strike) and dip (dip) of a plane given the east (E), north (N), and up (U) coordinates of three non-collinear points on the plane p1, p2 and p3 are 1 x 3 arrays defining the location of the points in an ENU coordinate system. For each one of these arrays the first entry is the E coordinate, the second entry the N coordinate, and the third entry the U coordinate. These coordinates have uncertainties NOTE: strike and dip are returned in radians and they follow the right-hand rule format. The returned uncertainties are also in radians ThreePointU uses functions CartToSphU and Pole It also uses the uncertainties package from Eric O. Lebigot ''' # make vectors v (p1 - p3) and u (p2 - p3) v = p1 - p2 u = p2 - p3 # take the cross product of v and u vcu0 = v[1] * u[2] - v[2] * u[1] vcu1 = v[2] * u[0] - v[0] * u[2] vcu2 = v[0] * u[1] - v[1] * u[0] # magnitude of the vector r = umath.sqrt(vcu0 * vcu0 + vcu1 * vcu1 + vcu2 * vcu2) # unit vector uvcu0 = vcu0 / r uvcu1 = vcu1 / r uvcu2 = vcu2 / r # make the pole vector in NED coordinates pole0 = uvcu1 pole1 = uvcu0 pole2 = -uvcu2 # Make sure pole point downwards if pole2 < 0: pole0 *= -1 pole1 *= -1 pole2 *= -1 # find the trend and plunge of the pole trd, plg = CartToSphU(pole0, pole1, pole2) # find strike and dip of plane strike, dip = Pole(trd, plg, 0) return strike, dip
def transit_duration(P, Rp, a, b=0, e=0, w=90, inc=None, total=True): """ Function to calculate the total (T14) or full (T23) transit duration Parameters: ---------- P: Period of planet orbit in days Rp: Radius of the planet in units of stellar radius b: Impact parameter of the planet transit [0, 1+Rp] a: scaled semi-major axis of the planet in units of solar radius inc: inclination of the orbit. Optional. If given b is not used. if None, b is used to calculate inc total: if True calculate the the total transit duration T14, else calculate duration of full transit T23 Returns ------- Tdur: duration of transit in same unit as P """ #eqn 30 and 31 of Kipping 2010 https://doi.org/10.1111/j.1365-2966.2010.16894.x factor = (1-e**2)/(1+e*sin(radians(w))) if inc == None: inc = inclination(b,a,e,w) if total is False: Rp = -Rp sini = sin(radians(inc)) cosi = cos(radians(inc)) denom = a*factor*sini tdur= (P/np.pi) * (factor**2/sqrt(1-e**2)) * (asin ( sqrt((1+Rp)**2 - (a*factor*cosi)**2)/ denom ) ) return tdur
def std(s, uncert=False): if s.__class__ == frameseries: N = s.N elif s.__class__ == np.ndarray: N = s else: raise ValueError if uncert: return umath.sqrt(var(N, uncert=True)) else: return np.std(N)
def analyse_impedance_circle(self): # all quantities for equivalent circuit components have a name like self.ec_* d=self.aqd; db=self.aqdb; #dc=self.aqdc d['Rmax']=2*self.center.real d['X0']=self.center.imag if (self.fr is not None) and (self.fa is not None): db['Qprod'] = self.fr**2 / (self.fa**2 - self.fr**2) if (self.fs is not None) and (self.fp is not None): db['k'] = umath.sqrt(1 - self.fs**2/self.fp**2) d['header']="1st run based on own target resonance" db['header']="2nd run incorporating fr and fs"
def effective_ringed_planet_radius(rp, rin, rout, ir): """ Calculate effective radius of a ringed planet accounting for possible overlap between ring and planet. - eqn (2) from zuluaga+2015 http://dx.doi.org/10.1088/2041-8205/803/1/L14 Parameters: ----------- rp : float, ufloat; Radius of the planet hosting the ring rin, rout : float, ufloat; Inner and outer radii of the ring in units of rp. ir : float, ufloat; Inclination of the ring from the skyplane. 0 is face-on ring, 90 is edge on Returns: -------- eff_R : float, ufloat; effective radius of the ringed planet in same unit as rp """ cosir = cos(radians(ir)) sinir = sin(radians(ir)) y = lambda r: sqrt(r**2 - 1) / (r * sinir) def eff(r): if r * cosir > 1: eff_r = r**2 * cosir - 1 else: eff_r = (r**2 * cosir * 2 / np.pi * asin(y(r))) - (2 / np.pi * asin(y(r) * r * cosir)) return eff_r rout_eff2 = eff(rout) rin_eff2 = eff(rin) Arp = rp**2 + rp**2 * (rout_eff2 - rin_eff2) return sqrt(Arp)
def GenerateCTR(df, reference=ufloat(42, 2), refflag=True, verbose=0): ''' Calculates time resolution and error from scale parameter ''' # TotalSigma = [ufloat(grp.scale, grp.scaleerr) # for key, grp in df.groupby('uniquename')] if refflag==True: def afunc(srs): if srs["scale"]>reference.nominal_value: return ufloat(srs["scale"], srs["scaleerr"]) else: return reference.nominal_value TotalSigma = array(df.apply(afunc,axis=1)) if verbose > 0: print("Subtracting",reference,"in quadrature!") TimeResolution = [uncmath.sqrt(val**2 - reference**2) for val in TotalSigma] else: def afunc(srs): return ufloat(srs["scale"], srs["scaleerr"]) TotalSigma = array(df.apply(afunc,axis=1)) if verbose > 0: print("identical scintillator detectors") TimeResolution = [val / uncmath.sqrt(2) for val in TotalSigma] if verbose > 0: for i, val in enumerate(TimeResolution): print(i, ":", val, "ps") ##print("\nmean value :", mean(TimeResolution), "ps") return zip(*[[val.n, val.s] for val in TimeResolution])
def analyse_admittance_circle(self): # all quantities for equivalent circuit components have a name like self.ec_* d=self.aqd; db=self.aqdb; #dc=self.aqdc d['Gmax']=2*self.center.real d['R']=1./d['Gmax'] d['Bs']=self.center.imag d['Qe']=d['Bs']/d['Gmax'] d['Qm'] = self.fs / (self.fnB-self.fmB) d['Qprod']=d['Qe']*d['Qm'] d['L'] = d['Qm'] * d['R'] / (2*pi*self.fs) d['C'] = 1. / (d['Qm']*d['R']*2*pi*self.fs) d['C01'] = d['Bs'] / (2*pi*self.fs) d['C02'] = d['C'] * d['Qprod'] # based on Bs, Gmax, fs, fnB, fmB d['k'] = umath.sqrt(d['C']/(d['C01']+d['C'])) d['Ma'] = d['Qm'] / d['Qprod'] d['Mb'] = 1. / (2*pi*self.fs*d['C01']*d['R']) d['Gamma'] = d['C']*3e-3 / (2*pi*34e-3*25e-3) if (self.fs is not None) and (self.fp is not None): db['k'] = umath.sqrt(1 - self.fs**2/self.fp**2) db['Qprod2'] = (1-db['k']**2) / db['k']**2 db['M2'] = d['Qm'] / db['Qprod2'] if (self.fa is not None) and (self.fr is not None): db['Qprod1'] = self.fr**2 / (self.fa**2 - self.fr**2) db['M1'] = d['Qm'] / db['Qprod1'] db['C01'] = d['C'] * db['Qprod1'] # based on fa, fr db['C02'] = d['C'] * db['Qprod2'] # based on fs, fp db['k1'] = umath.sqrt(d['C']/(d['C01']+d['C'])) db['k2'] = umath.sqrt(d['C']/(d['C02']+d['C'])) db['k1b'] = umath.sqrt(d['C']/(db['C01']+d['C'])) db['k2b'] = umath.sqrt(d['C']/(db['C01']+d['C'])) #db['Bs'] = 2*pi*self.fs * db['C0'] #db['Qe'] = db['Qprod'] / d['Qm'] #d['Qprodb'] = d['C0']/d['C'] d['header']="1st run based on own target resonance" db['header']="2nd run incorporating fa and fp"
def calculateTotSigma(sigma_vec, f_vec): if len(sigma_vec) != len(f_vec) + 1: print 'calculateTotSigma: Warning! wrong vector lenghts' return 0 totSigma = ufloat(0., 0.) sum_f = ufloat(0., 0.) s1 = sigma_vec[0] s2 = sigma_vec[1] f1 = f_vec[0] totSigma = pow(s1, 2) * f1 + (1-f1)* pow(s2,2) for i in range(len(f_vec)-1): s1 = totSigma s2 = sigma_vec[i+2] f1 = f_vec[i+1] totSigma = pow(s1, 2) * f1 + (1-f1)* pow(s2,2) # print 'calculateTotSigma: totSigma = ', totSigma, ' sum_f = ', sum_f # totSigma += (1-sum_f) * pow(sigma_vec[-1],2) print 'calculateTotSigma: ', umath.sqrt(totSigma) return umath.sqrt(totSigma)
def corr(s1, s2, uncert=False): ''' Normalized photon-number correlation coefficient Parameters ---------- ''' if uncert: return covar(s1, s2, uncert) / umath.sqrt( stat1d.var(s1, uncert) * stat1d.var(s2, uncert)) else: return covar(s1, s2, uncert) / np.sqrt( stat1d.var(s1, uncert) * stat1d.var(s2, uncert))
def max_load(usl_fit): """What's the estimated maximum load in the benchmark? Parameters ---------- usl_fit : lmfit.model.ModelResult USL scalabilty model result Returns ---------- sca_tools.graphing.GraphResult Container of graph artifacts to render """ params = _unpack_params(usl_fit) return sqrt((1 - params['sigma_']) / params['kappa'])
def sigma_CCF(res): """ Function to obtain the CCF width of non-rotating star in km/s based on resolution of spectrograph Parameters: ---------- res: Resolution of spectrograph Returns ------- sigma: CCF Width of non-rotating star in km/s """ return 3e5/(res*2*sqrt(2*log(2)))
def cartesian_to_angular(x, y, z): """Converts from cartesian to angular coordinates """ norm = np.sqrt(x**2 + y**2 + z**2) x = x / norm y = y / norm z = z / norm dec = np.asin(z) ra = np.atan2(y, x) ra = ra * rad2deg dec = dec * rad2deg return numpy.array([ra, dec])
def get_angular_sep(ra1, dec1, ra2, dec2): ra1 = ra1 * deg2rad ra2 = ra2 * deg2rad dec1 = dec1 * deg2rad dec2 = dec2 * deg2rad top = np.sqrt((np.cos(dec2) * np.sin(ra2 - ra1))**(2) + (np.cos(dec1) * np.sin(dec2) - np.sin(dec1) * np.cos(dec2) * np.cos(ra2 - ra1))**(2)) bottom = (np.sin(dec1) * np.sin(dec2)) + (np.cos(dec1) * np.cos(dec2) * np.cos(ra2 - ra1)) dist = np.atan2(top, bottom) return (dist / deg2rad) * 3600.0 * 1000.0
def getTeqpl_error(Teffst, aR, ecc, A=0, f=1/4.): """Return the planet equilibrium temperature. Relation adapted from equation 4 page 4 in http://www.mpia.de/homes/ppvi/chapter/madhusudhan.pdf and https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law and later updated to include the effect of excentricity on the average stellar planet distance according to equation 5 p 25 of Laughlin & Lissauer 2015arXiv150105685L (1501.05685) Plus Exoplanet atmospheres, physical processes, Sara Seager, p30 eq 3.9 for f contribution. :param float/np.ndarray Teffst: Effective temperature of the star :param float/np.ndarray aR: Ration of the planetary orbital semi-major axis over the stellar radius (without unit) :param float/np.ndarray A: Bond albedo (should be between 0 and 1) :param float/np.ndarray f: Redistribution factor. If 1/4 the energy is uniformly redistributed over the planetary surface. If f = 2/3, no redistribution at all, the atmosphere immediately reradiate whithout advection. :return float/np.ndarray Teqpl: Equilibrium temperature of the planet """ return Teffst * (f * (1 - A))**(1 / 4.) * um.sqrt(1 / aR) / (1 - ecc**2)**(1/8.)
def qm_res2(): ''' same as above, only other way of calculating ''' from uncertainties.umath import sqrt a = (4*K*u_x/w**2/r**2)**4 /4 b = - ( 2*u_w / r / w**2 /A )**2 c = - (2*w_res/w)**4 discriminant = b**2 - 4*a*c if discriminant < 0: return [] x1 = ( -b + sqrt( discriminant) ) / (2*a) #eigentlich sind nur das + interessant x2 = ( -b - sqrt( discriminant) ) / (2*a) result = [] for x in [x1, x2]: if x > 0: result.append( - umath.sqrt(x) ) return result
def circle_fit(X, Y): """ Implementation of a Least-Squares Circle Fit as described by Randy Bullock in circle_fit.pdf. It returns coordinates of the center and radius. """ assert(len(X) == len(Y)) N = len(X) xm = sum(X)/ N ym = sum(Y)/N u = X - xm v = Y - ym Suuu = sum(u**3) Svvv = sum(v**3) Suvv = sum(u*(v**2)) Suuv = sum((u**2)*v) Suu = sum(u**2) Svv = sum(v**2) Suv = sum(u*v) # Can't find an easy way to solve the system with uncertaintis. So I did it by hand: # a1 x + b1 y = c1 # a2 x + b2 y = c2 a1 = Suu b1 = Suv c1 = (Suuu + Suvv)/2 a2 = Suv b2 = Svv c2 = (Svvv + Suuv)/2 det = a1*b2-b1*a2 uc = -(b1*c2-c1*b2)/det vc = (a1*c2-c1*a2)/det # Solutions xc = uc + xm yc = vc + ym radius = umath.sqrt(uc**2 + vc**2 + (Suu + Svv)/N) return xc, yc, radius
def min_mass(K, period, ecc, mstar): """ Calculates de minimum mass using known parameters for the planet and the star K [m/s]: radial velocity amplitud period [days]: orbital period of planet ecc: eccentricity of planet mstar [Msun]: Mass of star in Sun masses """ from uncertainties import ufloat, umath # Unit conversions period *= 86400 # days to seconds mstar *= 1.9891e30 # Sun masses to kg msini = K*(mstar)**(2/3) * \ (period/(2*np.pi*6.67e-11))**(1/3) * umath.sqrt(1-ecc**2) # Convert to Earth masses msini /= 5.972e24 return msini
def D(self, a): """ Arguments --------- a : angle of rotation [rad] Return ------ D : distance between target and detector [mm] """ Rd = self.R + self.d r = self.r AT = self.AT if isinstance(a, (int, float, np.number, uncertainties.core.AffineScalarFunc)): return umath.sqrt(Rd**2.0 + r**2.0 - 2.0 * Rd * r * umath.cos(a + AT)) elif isinstance(a, np.ndarray): return unp.sqrt(Rd**2.0 + r**2.0 - 2.0 * Rd * r * unp.cos(a + AT)) else: raise ValueError( f"This function not supported for the input types. argument 'a' must be number or array")
def T_eq(T_st,a_r): """ calculate equilibrium temperature of planet in Kelvin Parameters ---------- T_st: Array-like; Effective Temperature of the star a_r: Array-like; Scaled semi-major axis of the planet orbit Returns ------- T_eq: Array-like; Equilibrium temperature of the planet """ print("T_st is {0:.2f}, a_r is {1:.2f}".format(T_st,a_r)) return T_st*sqrt(0.5/a_r)
def get_angular_sep(ra1, dec1, ra2, dec2): """ implements the vincinerty distance formular in the case of a sphere. """ ra1 = ra1 * deg2rad ra2 = ra2 * deg2rad dec1 = dec1 * deg2rad dec2 = dec2 * deg2rad top = np.sqrt((np.cos(dec2) * np.sin(ra2 - ra1))**(2) + (np.cos(dec1) * np.sin(dec2) - np.sin(dec1) * np.cos(dec2) * np.cos(ra2 - ra1))**(2)) bottom = (np.sin(dec1) * np.sin(dec2)) + (np.cos(dec1) * np.cos(dec2) * np.cos(ra2 - ra1)) dist = np.atan2(top, bottom) return (dist / deg2rad) * 3600.0 * 1000.0
def calculate_cbase(pH, pCO2, ctHb=3): """Calculate base excess. Calculate standard base excess, known as SBE, cBase(Ecf) or actual base excess known as ABE, cBase(B). References ---------- [1] Radiometer ABL800 Flex Reference Manual English US. chapter 6-29, p. 265, equation 5. [2] Siggaard-Andersen O. The acid-base status of the blood. 4th revised ed. Copenhagen: Munksgaard, 1976. http://www.cabdirect.org/abstracts/19751427824.html :param float pH: :param float pCO2: kPa :param float ctHb: Concentration of total hemoglobin in blood, mmol/L If not given, calculate cBase(Ecf), otherwise cBase(B). :return: Standard base excess (SBE) or actual base excess (ABE), mEq/L. :rtype: float """ # pCO2 *= 0.133322368 # mmHg to kPa a = 4.04 * 10 ** -3 + 4.25 * 10 ** -4 * ctHb pHHb = 4.06 * 10 ** -2 * ctHb + 5.98 - 1.92 * 10 ** (-0.16169 * ctHb) log_pCO2Hb = -1.7674 * (10 ** -2) * ctHb + 3.4046 + 2.12 * 10 ** ( -0.15158 * ctHb) pHst = pH + math.log10(5.33 / pCO2) * ( (pHHb - pH) / (log_pCO2Hb - math.log10(7.5006 * pCO2))) cHCO3_533 = 0.23 * 5.33 * 10 ** ((pHst - 6.161) / 0.9524) # There is no comments, as there is no place for weak man cBase = 0.5 * ((8 * a - 0.919) / a) + 0.5 * math.sqrt( (((0.919 - 8 * a) / a) ** 2) - 4 * ((24.47 - cHCO3_533) / a)) return cBase
def test_uncertainties(): """ Tests the method used to calculate uncertainties in SQL Note: this tests uncertainties on the calculation of the mean itself! """ # Build array of 100 values n = 100 arr = N.random.randn(2, n) arr[1] = 0.1 * N.abs(arr[1]) unc = uarray(arr[0], arr[1]) avg = N.mean(unc) # Test uncertainties in the calculation of the mean of # the distribution k = arr[0].mean() s = N.sqrt(N.sum(arr[1]**2)) / n avg2 = ufloat(k, s) print(avg, avg2) assert N.allclose(avg.n, avg2.n) assert N.allclose(avg.s, avg2.s) # Test uncertainties in the calculation of a single # measured value fo the distribution mu = unc.mean() # Shim for standard deviation variance = N.mean((unc - avg)**2) + mu.s**2 avg = ufloat(mu.n, umath.sqrt(variance).n) k = arr[0].mean() s = N.sqrt(N.sum(arr[1]**2)) / n s = arr[0].std() + s avg2 = ufloat(k, s) print(avg, avg2) assert N.allclose(avg.n, avg2.n, rtol=0.5) assert N.allclose(avg.s, avg2.s, rtol=0.5)
def theta(theta_lab, n): """ function to convert θ in the lab system to θ in the center-of-mass system 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 ------ theta_cm : scattering angle in the center-of-mass system [rad] Notice ------ This function do not consider relativity """ if isinstance(theta_lab, uncertainties.core.AffineScalarFunc): coslab2 = umath.pow(umath.cos(theta_lab), 2.0) coscm = (coslab2 - 1.0) / n \ + umath.sqrt((1.0 - 1.0 / n**2.0) * coslab2 + umath.pow(coslab2 / n, 2.0)) return np.sign(theta_lab) * umath.acos(coscm) elif isinstance(theta_lab, np.ndarray) and isinstance( theta_lab[0], uncertainties.core.AffineScalarFunc): coslab2 = unp.pow(unp.cos(theta_lab), 2.0) coscm = (coslab2 - 1.0) / n \ + unp.sqrt((1.0 - 1.0 / n**2.0) * coslab2 + unp.pow(coslab2 / n, 2.0)) return np.sign(theta_lab) * unp.arccos(coscm) else: coslab2 = np.power(np.cos(theta_lab), 2.0) coscm = (coslab2 - 1.0) / n \ + np.sqrt((1.0 - 1.0 / n**2.0) * coslab2 + np.power(coslab2 / n, 2.0)) return np.sign(theta_lab) * np.arccos(coscm)
#~ printError(u, unit = 'V') ug_new = [] ug_new2 = [] for i in [1,6,10]: #~ print u_g[i+1] - u_g[i-1] diff = (u_g[i+1] - u_g[i-1])/2 ug_new.append( [ u_g[i].nominal_value , diff.nominal_value,i] ) #~ ug_new2.append( ufloat( u_g[i].nominal_value , diff ) print "U_G" ug_new.reverse() ug_new.append([273,55,4]) d = ufloat( ( 0.0305, 0.002 ) )# m g = 9.81 # m/s² #~ for u in ug: #~ qm_grav = g * d / u #~ printError(qm_grav, unit = 'C/kg') dval = d.nominal_value edval = d.std_dev() print "Messung 1 bei 450mbar" for i,u in enumerate(ug_new): print i+1 print "U_g: %f +- %f (stat.) +- %f (sys.) V"%(u[0],u_g[u[2]].std_dev(),u[1]) qm_grav = g * d.nominal_value / u_g[u[2]] qm = g * dval / u[0] #~ print "uncertain q/m: %e +- %e (stat.) +- %e (sys.) C/kg \n"%(qm,qm_grav.std_dev(),usysqm(g,dval,edval,u[0],u[1])) print "byhand q/m: %e +- %e (stat.) +- %e (sys.) +- %e (comb.)C/kg \n"%(qm,usysqm( g,dval,0,u[0],u_g[u[2]].std_dev() ),usysqm( g,dval,edval,u[0],u[1]),sqrt(pow(usysqm( g,dval,0,u[0],u_g[u[2]].std_dev() ),2) + pow(usysqm( g,dval,edval,u[0],u[1]),2) ) )
def output_params(timedays, NormFlux, fit, success, period, ecc, arg_periapsis): Flux, Ing, Egr = transiterout(np.arange(0, np.size(NormFlux)), fit[0], fit[1], fit[2], fit[3], fitting=True) print Ing #Get values and uncertainties from the fit Rp = ufloat((fit[0], np.sqrt(success[0][0]))) b1 = ufloat((fit[1], np.sqrt(success[1][1]))) vel = ufloat((fit[2], np.sqrt(success[2][2]))) midtrantime = ufloat((fit[3], np.sqrt(success[3][3]))) #gam1=ufloat((fit[4],np.sqrt(success[4][4]))) #gam2=ufloat((fit[5],np.sqrt(success[5][5]))) P = period ecc_corr = np.sqrt(1 - ecc**2) / ( 1 + ecc * umath.sin(arg_periapsis * np.pi / 180.)) Ttot = (Egr[np.size(Egr) - 1] - Ing[0]) * ecc_corr Tfull = (Egr[0] - Ing[np.size(Ing) - 1]) * ecc_corr #delta=ufloat((1-Flux[fit[3]],1-Flux[fit[3]]+sqrt(success[3][3]))) delta = Rp**2 dt = timedays[2] - timedays[1] aRstar = (2 * delta**0.25 * P / (np.pi * dt * umath.sqrt(Ttot**2 - Tfull**2)) ) #*umath.sqrt(1-ecc**2)/(1+ecc*sin(arg_periapsis*pi/180.)) #bmodel=umath.sqrt((1-(Tfull/Ttot)**2)/((1-umath.sqrt(delta))**2-(Tfull/Ttot)**2 * (1+umath.sqrt(delta))**2)) #Not too sure why this doesn't work inc = (180 / np.pi) * umath.acos(b1 / aRstar) #print bmodel poutnames = ('Rp', 'b1', 'vel', 'midtrantime', 'gam1', 'gam2') for iz in range(0, np.size(fit)): print poutnames[iz], fit[iz], np.sqrt(success[iz][iz]) print "--------------------------------" #Useful Conversions #R_Jup/R_Sun = 0.10279 #R_Sun = 0.00464913034 AU aRstarFIT = vel * P / (dt * 2 * np.pi) incFIT = (180 / np.pi) * umath.acos(b1 / aRstarFIT) #midtrantime_convert=midtrantime*dt*24*3600+time_days[0] #midtrantime_MJD=timedays[midtrantime]+54964.00111764 timebetween = timedays[int(midtrantime.nominal_value) + 1] - timedays[int( midtrantime.nominal_value)] print timebetween * dt #print "Midtrantime",midtrantime_convert.std_dev()#midtrantime_MJD print "aRstarFIT", aRstarFIT print "inclination", incFIT print "frac. rad.", Rp print "aRstar_mod", aRstar aRs = (aRstarFIT + aRstar) / 2 print "--------------------------------" print "Planetary Radius/Star Radius: ", Rp print "Inclination: ", incFIT print "Semi - Major Axis / Stellar Radius: ", aRs print "Mid-Transit Time [MJD]", pyplot.plot(time, NormFlux, linestyle='None', marker='.') pyplot.plot( time, transiter(np.arange(np.size(NormFlux)), fit[0], fit[1], fit[2], fit[3])) pyplot.show() return Flux, Rp, aRstarFIT, incFIT, aRstar, midtrantime
def longBeta(a, q): from uncertainties.umath import sqrt return 1.*sqrt( a - (a-1)*q**2 / (2*(a-1)**2-q**2) - (5*a+7)*q**4 / (32*(a-1)**3*(a-4)) - (9*a**2+58*a+29)*q**6 / (64*(a-1)**5*(a-4)*(a-9) ) )
def shortBeta(a,q): from uncertainties.umath import sqrt return 1.*sqrt(a+q**2/2)
def usysqm (g,d,ed,u,eu): return g/u * sqrt(ed**2 + eu**2 * d**2 / u**2)
def get_summary(self, nodmx=False): """Return a human-readable summary of the Fitter results. Parameters ---------- nodmx : bool Set to True to suppress printing DMX parameters in summary """ # Need to check that fit has been done first! if not hasattr(self, "covariance_matrix"): log.warning( "fit_toas() has not been run, so pre-fit and post-fit will be the same!" ) from uncertainties import ufloat import uncertainties.umath as um # First, print fit quality metrics s = "Fitted model using {} method with {} free parameters to {} TOAs\n".format( self.method, len(self.get_fitparams()), self.toas.ntoas) s += "Prefit residuals Wrms = {}, Postfit residuals Wrms = {}\n".format( self.resids_init.rms_weighted(), self.resids.rms_weighted()) s += "Chisq = {:.3f} for {} d.o.f. for reduced Chisq of {:.3f}\n".format( self.resids.chi2, self.resids.dof, self.resids.chi2_reduced) s += "\n" # Next, print the model parameters s += "{:<14s} {:^20s} {:^28s} {}\n".format("PAR", "Prefit", "Postfit", "Units") s += "{:<14s} {:>20s} {:>28s} {}\n".format("=" * 14, "=" * 20, "=" * 28, "=" * 5) for pn in list(self.get_allparams().keys()): if nodmx and pn.startswith("DMX"): continue prefitpar = getattr(self.model_init, pn) par = getattr(self.model, pn) if par.value is not None: if isinstance(par, strParameter): s += "{:14s} {:>20s} {:28s} {}\n".format( pn, prefitpar.value, "", par.units) elif isinstance(par, AngleParameter): # Add special handling here to put uncertainty into arcsec if par.frozen: s += "{:14s} {:>20s} {:>28s} {} \n".format( pn, str(prefitpar.quantity), "", par.units) else: if par.units == u.hourangle: uncertainty_unit = pint.hourangle_second else: uncertainty_unit = u.arcsec s += "{:14s} {:>20s} {:>16s} +/- {:.2g} \n".format( pn, str(prefitpar.quantity), str(par.quantity), par.uncertainty.to(uncertainty_unit), ) else: # Assume a numerical parameter if par.frozen: s += "{:14s} {:20g} {:28s} {} \n".format( pn, prefitpar.value, "", par.units) else: # s += "{:14s} {:20g} {:20g} {:20.2g} {} \n".format( # pn, # prefitpar.value, # par.value, # par.uncertainty.value, # par.units, # ) s += "{:14s} {:20g} {:28SP} {} \n".format( pn, prefitpar.value, ufloat(par.value, par.uncertainty.value), par.units, ) # Now print some useful derived parameters s += "\nDerived Parameters:\n" if hasattr(self.model, "F0"): F0 = self.model.F0.quantity if not self.model.F0.frozen: p, perr = pint.utils.pferrs(F0, self.model.F0.uncertainty) s += "Period = {} +/- {}\n".format(p.to(u.s), perr.to(u.s)) else: s += "Period = {}\n".format((1.0 / F0).to(u.s)) if hasattr(self.model, "F1"): F1 = self.model.F1.quantity if not any([self.model.F1.frozen, self.model.F0.frozen]): p, perr, pd, pderr = pint.utils.pferrs( F0, self.model.F0.uncertainty, F1, self.model.F1.uncertainty) s += "Pdot = {} +/- {}\n".format( pd.to(u.dimensionless_unscaled), pderr.to(u.dimensionless_unscaled)) brakingindex = 3 s += "Characteristic age = {:.4g} (braking index = {})\n".format( pint.utils.pulsar_age(F0, F1, n=brakingindex), brakingindex) s += "Surface magnetic field = {:.3g}\n".format( pint.utils.pulsar_B(F0, F1)) s += "Magnetic field at light cylinder = {:.4g}\n".format( pint.utils.pulsar_B_lightcyl(F0, F1)) I_NS = I = 1.0e45 * u.g * u.cm**2 s += "Spindown Edot = {:.4g} (I={})\n".format( pint.utils.pulsar_edot(F0, F1, I=I_NS), I_NS) if hasattr(self.model, "PX"): if not self.model.PX.frozen: s += "\n" px = ufloat( self.model.PX.quantity.to(u.arcsec).value, self.model.PX.uncertainty.to(u.arcsec).value, ) s += "Parallax distance = {:.3uP} pc\n".format(1.0 / px) # Now binary system derived parameters binary = None for x in self.model.components: if x.startswith("Binary"): binary = x if binary is not None: s += "\n" s += "Binary model {}\n".format(binary) if binary.startswith("BinaryELL1"): if not any([ self.model.EPS1.frozen, self.model.EPS2.frozen, self.model.TASC.frozen, self.model.PB.frozen, ]): eps1 = ufloat( self.model.EPS1.quantity.value, self.model.EPS1.uncertainty.value, ) eps2 = ufloat( self.model.EPS2.quantity.value, self.model.EPS2.uncertainty.value, ) tasc = ufloat( # This is a time in MJD self.model.TASC.quantity.mjd, self.model.TASC.uncertainty.to(u.d).value, ) pb = ufloat( self.model.PB.quantity.to(u.d).value, self.model.PB.uncertainty.to(u.d).value, ) s += "Conversion from ELL1 parameters:\n" ecc = um.sqrt(eps1**2 + eps2**2) s += "ECC = {:P}\n".format(ecc) om = um.atan2(eps1, eps2) * 180.0 / np.pi if om < 0.0: om += 360.0 s += "OM = {:P}\n".format(om) t0 = tasc + pb * om / 360.0 s += "T0 = {:SP}\n".format(t0) s += pint.utils.ELL1_check( self.model.A1.quantity, ecc.nominal_value, self.resids.rms_weighted(), self.toas.ntoas, outstring=True, ) s += "\n" # Masses and inclination if not any([self.model.PB.frozen, self.model.A1.frozen]): pbs = ufloat( self.model.PB.quantity.to(u.s).value, self.model.PB.uncertainty.to(u.s).value, ) a1 = ufloat( self.model.A1.quantity.to(pint.ls).value, self.model.A1.uncertainty.to(pint.ls).value, ) fm = 4.0 * np.pi**2 * a1**3 / (4.925490947e-6 * pbs**2) s += "Mass function = {:SP} Msun\n".format(fm) mcmed = pint.utils.companion_mass( self.model.PB.quantity, self.model.A1.quantity, inc=60.0 * u.deg, mpsr=1.4 * u.solMass, ) mcmin = pint.utils.companion_mass( self.model.PB.quantity, self.model.A1.quantity, inc=90.0 * u.deg, mpsr=1.4 * u.solMass, ) s += "Companion mass min, median (assuming Mpsr = 1.4 Msun) = {:.4f}, {:.4f} Msun\n".format( mcmin, mcmed) if hasattr(self.model, "SINI"): if not self.model.SINI.frozen: si = ufloat( self.model.SINI.quantity.value, self.model.SINI.uncertainty.value, ) s += "From SINI in model:\n" s += " cos(i) = {:SP}\n".format(um.sqrt(1 - si**2)) s += " i = {:SP} deg\n".format( um.asin(si) * 180.0 / np.pi) psrmass = pint.utils.pulsar_mass( self.model.PB.quantity, self.model.A1.quantity, self.model.M2.quantity, np.arcsin(self.model.SINI.quantity), ) s += "Pulsar mass (Shapiro Delay) = {}".format(psrmass) return s
def SolveProblem(d): # Get our needed variables for k in d["vars"]: if k in set(("S1", "S2", "S3", "A1", "A2", "A3")): exec("%s = d['vars']['%s']" % (k, k)) angle_conv = d["angle_measure"] # Converts angle measure to radians prob = d["problem_type"] try: if prob == "sss": # Law of cosines to find two angles, angle law to find third. A1 = acos((S2**2 + S3**2 - S1**2)/(2*S2*S3)) A2 = acos((S1**2 + S3**2 - S2**2)/(2*S1*S3)) A3 = pi - A1 - A2 elif prob == "ssa": # Law of sines to find the other two angles and remaining # side. Note it can have two solutions (the second solution's # data will be in the variables s1_2, s2_2, etc.). A1 *= angle_conv # Make sure angle is in radians A2 = asin((S2/S1*sin(A1))) A3 = pi - A1 - A2 S3 = S2*sin(A3)/sin(A2) # Check for other solution A1_2 = A1 A2_2 = pi - A2 A3_2 = pi - A1_2 - A2_2 if A1_2 + A2_2 + A3_2 > pi: # Second solution not possible del A1_2 del A2_2 del A3_2 else: # Second solution is possible S1_2 = S1 S2_2 = S2 S3_2 = S2_2*sin(A3_2)/sin(A2_2) elif prob == "sas": # Law of cosines to find third side; law of sines to find # another angle; angle law for other angle. Note we rename # the incoming angle to be consistent with a solution diagram. A3 = A1*angle_conv # Make sure angle is in radians S3 = sqrt(S1**2 + S2**2 - 2*S1*S2*cos(A3)) A2 = asin(S2*sin(A3)/S3) A1 = pi - A2 - A3 elif prob == "asa": # Third angle from angle law; law of sines for other two # sides. Note we rename the sides for consistency with a # diagram. A1 *= angle_conv # Make sure angle is in radians A2 *= angle_conv # Make sure angle is in radians A3 = pi - A1 - A2 S3 = S1 S2 = S3*sin(A2)/sin(A3) S1 = S3*sin(A1)/sin(A3) elif prob == "saa": # Third angle from angle law; law of sines for other two # sides. A1 *= angle_conv # Make sure angle is in radians A2 *= angle_conv # Make sure angle is in radians A3 = pi - A1 - A2 S2 = S1*sin(A2)/sin(A1) S3 = S1*sin(A3)/sin(A1) else: raise ValueError("Bug: unrecognized problem") except UnboundLocalError as e: s = str(e) loc = s.find("'") s = s[loc + 1:] loc = s.find("'") s = s[:loc] Error("Variable '%s' not defined" % s) except ValueError as e: msg = "Can't solve the problem:\n" msg += " Error: %s" % str(e) Error(msg) # Collect solution information solution = {} vars = set(( "S1", "S2", "S3", "A1", "A2", "A3", "S1_2", "S2_2", "S3_2", "A1_2", "A2_2", "A3_2", )) for k in vars: if k in locals(): exec("solution['%s'] = %s" % (k, k)) d["solution"] = solution
def qm_res4(): dis = umath.sqrt( (u_w / A)**4 + ( 4*K*u_x*w_res/w)**4 ) front = (u_w/A)**2 return [ -umath.sqrt( (front + dis) / ( 32*r**2 * (u_x*K/w/r**2)**4 ) ) ]
#this part is for the case multiple measurements have been performed #with the same parameters -> set numpoints to this value if numPoints>1: newpropVals=[] newpropErrs=[] #construct an array with values and errors using the uncertainties package valNerr=[[ufloat(propVals[i][j],propErrs[i][j]) for j in xrange(len(propVals[i]))] for i in xrange(len(propVals))] valNerr=np.array(valNerr) for line in valNerr: valtemp=[] errtemp=[] for i in xrange(len(line)/numPoints): #temporary, this should be checked for correct propagation of errors! l=line[numPoints*i:numPoints*(i+1)] mean=l.mean() std=sqrt(l.var()) valtemp.append(mean.n) errtemp.append(std.n) newpropVals.append(valtemp) newpropErrs.append(errtemp) propVals=newpropVals propErrs=newpropErrs #create a figure for the parameters plt.figure(figsize=(20,20)) #plot the parameters for i in xrange(len(params)): plt.subplot(5,5,i+1) plt.errorbar(range(len(params[i])),params[i],paramErrs[i]) #set the function name as plot title