def _calculate_r(self, age): oma = self._original_monitor_age torig = self._original_total_decay_constant ex_orig = umath.exp(torig * oma * 1e6) - 1 ex = umath.exp(torig * age * 1e6) - 1 r = ex / ex_orig return r, ex, ex_orig
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 _linear_error_propagation(self, age, r, sr): """ age in years :param age: :param r: :return: linear error propagation age error in years """ lambda_total = self._lambda_t b = self._lambda_b el = self._lambda_ec f = self._f # partial derivatives pd_el = -(1. / lambda_total) * (age + (b * f * r / ( (el**2) * umath.exp(lambda_total * age)))) pd_b = (1 / lambda_total) * ( (f * r / (el * umath.exp(lambda_total * age))) - age) pd_f = r / (el * umath.exp(lambda_total * age)) pd_r = f / (el * umath.exp(lambda_total * age)) sel = std_dev(el) sb = std_dev(b) sf = std_dev(self._f) # sr = std_dev(r) # (partial derivatives x sigma) ** 2 pd_el2 = (pd_el * sel)**2 pd_b2 = (pd_b * sb)**2 pd_f2 = (pd_f * sf)**2 pd_r2 = (pd_r * sr)**2 sum_pd = pd_el2 + pd_b2 + pd_f2 + pd_r2 # covariances cov_f_el = 7.1903e-19 cov_f_b = -6.5839e-19 cov_el_b = -3.4711e-26 cov_f_el2 = 2. * cov_f_el * pd_f * pd_el cov_f_b2 = 2. * cov_f_b * pd_f * pd_b cov_el_b = 2. * cov_el_b * pd_el * pd_b sum_cov = cov_f_el2 + cov_f_b2 + cov_el_b ss = sum_pd + sum_cov # uncertainty in age st = ss**0.5 return nominal_value(st)
def _linear_error_propagation(self, age, r, sr): """ age in years :param age: :param r: :return: linear error propagation age error in years """ lambda_total = self._lambda_t b = self._lambda_b el = self._lambda_ec f = self._f # partial derivatives pd_el = -(1. / lambda_total) * (age + (b * f * r / ((el ** 2) * umath.exp(lambda_total * age)))) pd_b = (1 / lambda_total) * ((f * r / (el * umath.exp(lambda_total * age))) - age) pd_f = r / (el * umath.exp(lambda_total * age)) pd_r = f / (el * umath.exp(lambda_total * age)) sel = std_dev(el) sb = std_dev(b) sf = std_dev(self._f) # sr = std_dev(r) # (partial derivatives x sigma) ** 2 pd_el2 = (pd_el * sel) ** 2 pd_b2 = (pd_b * sb) ** 2 pd_f2 = (pd_f * sf) ** 2 pd_r2 = (pd_r * sr) ** 2 sum_pd = pd_el2 + pd_b2 + pd_f2 + pd_r2 # covariances cov_f_el = 7.1903e-19 cov_f_b = -6.5839e-19 cov_el_b = -3.4711e-26 cov_f_el2 = 2. * cov_f_el * pd_f * pd_el cov_f_b2 = 2. * cov_f_b * pd_f * pd_b cov_el_b = 2. * cov_el_b * pd_el * pd_b sum_cov = cov_f_el2 + cov_f_b2 + cov_el_b ss = sum_pd + sum_cov # uncertainty in age st = ss ** 0.5 return nominal_value(st)
def calculate_flux(f, age, arar_constants=None): """ #rad40: radiogenic 40Ar #k39: 39Ar from potassium f: F value rad40Ar/39Ar age: age of monitor in years solve age equation for J """ # if isinstance(rad40, (list, tuple)): # rad40 = ufloat(*rad40) # if isinstance(k39, (list, tuple)): # k39 = ufloat(*k39) if isinstance(f, (list, tuple)): f = ufloat(*f) if isinstance(age, (list, tuple)): age = ufloat(*age) # age = (1 / constants.lambdak) * umath.log(1 + JR) try: # r = rad40 / k39 if arar_constants is None: arar_constants = ArArConstants() j = (umath.exp(age * arar_constants.lambda_k.nominal_value) - 1) / f return j.nominal_value, j.std_dev except ZeroDivisionError: return 1, 0
def value(self, E): try: value = E.value except AttributeError: value = E return self.norm * exp(self.TF1.Eval(log(value), 0.0, 0.0, 0.0))
def error(self, E): # TODO: this need checking try: value = E.value except AttributeError: value = E ln_err = _Efficiency.error(self, log(value)) ln_eff = self.TF1.Eval(log(value), 0.0, 0.0, 0.0) tmp1 = self.norm * exp(ln_eff + ln_err) tmp2 = self.norm * exp(ln_eff - ln_err) error = abs(tmp1 - tmp2) / 2.0 return self.norm * error
def eval_saturation(self, pO2, A, T): """Calculate saturation by curve. (Saturation can be measured by multiwavelength hemoximetry.) S = ODC(P,A,T) References ---------- .. [1] Radiometer ABL800 Flex Reference Manual English US. chapter 6-44, p. 280, equation 46-47. :param float pO2: measured partial O2 pressure, kPa (46.1) :param float A: an curve displacement along axis x (46.5). :param float T: Body temperature, °C (46.7). :return: s, hemoglobin saturation at given pO2 and T conditions for current ODC, fraction. No hemoglobin corrections performed. :rtype: float """ x_0 = eval_x_0(a=A, T=T) # 46.1 x = math.log(pO2) y = haldane_odc(x=x, x_0=x_0, y_0=self.y_0, a=A) s = 1 / (math.exp(-y) + 1) # Reverse 46.2 return s
def calc_tiT_diff(pO2, sO2, T, A): # Derivative from paper alphaO2 = 9.83 * 10 ** -3 * math.exp( -1.15 * 10 ** -2 * (T - 37) + 2.1 * 10 ** -4 * (T - 37) ** 2) x = math.log(pO2) x_0 = eval_x_0(a=A, T=T) n = haldane_odc_diff(x=x, x_0=x_0, y_0=self.y_0, a=A) return alphaO2 + ctHb * n * (1 - sO2) / pO2
def normalize(self): # Normalize the efficiency function try: self.norm = 1.0 / exp( self.TF1.GetMaximum(min([p[0] for p in self._fitInput]), max([p[0] for p in self._fitInput]))) except ZeroDivisionError: self.norm = 1.0 self.TF1.SetParameter(0, self.norm) normfunc = TF2("norm_" + hex(id(self)), "[0]*y") normfunc.SetParameter(0, self.norm) self.TGraph.Apply(normfunc)
def fo2_cal_single(P,T,PV,r,method='earth',flag=False,fit='fit3'): """ calculate fo2 for a single P,T point P : pressure, GPa, P is actually not used, it is included in PV integration info T : temperature, K PV : term int\{P0 to P0, deltaV}, it requires to get the dV at every single pressure and temperature, and then integrate. This could be very time demanding. r : Fe3/Fe2 ratio method : earth, mars, moon, specify the composition, default is earth flag : boolean, uncertainty flag, default is False fit3 : W model, default is fit3 Note ---- Term int\{P0 to P0, deltaV}, deltaV is at reference temperature, not along geotherm. That means, to calcualte this term, for every point in geotherm, P,T, one needs to calculate the dV from P0 to P along T, and then integrate. Note this is different from just calculate dV along the goetherm, then integrate. Typically, the 2nd method will underestimate the PV term since goetherm is T0 to T, whereas here we need keep T as T. Nevertheless, `cal_PV_geo` function in the package solve this problem. The obtained PV term along the geotherm is then used as input and kept in the excel eos.xlsx """ Fe2 = (1-r)*planets.loc[method]['FeO'] Fe3 = r*planets.loc[method]['FeO'] Si = planets.loc[method]['SiO2']; Mg = planets.loc[method]['MgO']; Al = planets.loc[method]['Al2O3']; Ca = planets.loc[method]['CaO']; K = planets.loc[method]['K2O']; Na = planets.loc[method]['Na2O']; Ph = planets.loc[method]['P2O5']; Ti = planets.loc[method]['TiO2']; a,b,W_Fe,W_Mg,W_Si,W_Al,W_Ca,W_Na,W_K,W_Ph,W_Ti = unpack_par(W.loc[fit],flag) Gterm = np.array(tl.Gr_janaf(T,flag))/R/T Wterm = (W_Fe*(Fe2 - Fe3) + W_Mg*Mg + W_Al*Al + W_Si*Si + W_Ca*Ca +W_Na*Na + W_K*K + W_Ph*Ph + W_Ti*Ti)/R/T tmp = (PV + Gterm + Wterm)*4 lnXfe3_Xfe2 = np.log(Fe3/Fe2)*4 fg = umath.exp(tmp+lnXfe3_Xfe2) log10fg = (umath.log10(fg)) return log10fg
def test_against_uncertainties_package(): try: from uncertainties import ufloat from uncertainties import umath from math import sqrt as math_sqrt except ImportError: return X, varX = 0.5, 0.04 Y, varY = 3, 0.09 N = 3 ux = ufloat(X, math_sqrt(varX)) uy = ufloat(Y, math_sqrt(varY)) def _compare(result, u): Z, varZ = result assert abs(Z-u.n)/u.n < 1e-13 and (varZ-u.s**2)/u.s**2 < 1e-13, \ "expected (%g,%g) got (%g,%g)"%(u.n,u.s**2,Z,varZ) def _check_pow(u): _compare(pow(X, varX, N), u) def _check_unary(op, u): _compare(op(X, varX), u) def _check_binary(op, u): _compare(op(X, varX, Y, varY), u) _check_pow(ux**N) _check_binary(add, ux+uy) _check_binary(sub, ux-uy) _check_binary(mul, ux*uy) _check_binary(div, ux/uy) _check_binary(pow2, ux**uy) _check_unary(exp, umath.exp(ux)) _check_unary(log, umath.log(ux)) _check_unary(sin, umath.sin(ux)) _check_unary(cos, umath.cos(ux)) _check_unary(tan, umath.tan(ux)) _check_unary(arcsin, umath.asin(ux)) _check_unary(arccos, umath.acos(ux)) _check_unary(arctan, umath.atan(ux)) _check_binary(arctan2, umath.atan2(ux, uy))
def test_against_uncertainties_package(): try: from uncertainties import ufloat from uncertainties import umath from math import sqrt as math_sqrt except ImportError: return X, varX = 0.5, 0.04 Y, varY = 3, 0.09 N = 3 ux = ufloat(X, math_sqrt(varX)) uy = ufloat(Y, math_sqrt(varY)) def _compare(result, u): Z, varZ = result assert abs(Z-u.n)/u.n < 1e-13 and (varZ-u.s**2)/u.s**2 < 1e-13, \ "expected (%g,%g) got (%g,%g)"%(u.n, u.s**2, Z, varZ) def _check_pow(u): _compare(pow(X, varX, N), u) def _check_unary(op, u): _compare(op(X, varX), u) def _check_binary(op, u): _compare(op(X, varX, Y, varY), u) _check_pow(ux**N) _check_binary(add, ux + uy) _check_binary(sub, ux - uy) _check_binary(mul, ux * uy) _check_binary(div, ux / uy) _check_binary(pow2, ux**uy) _check_unary(exp, umath.exp(ux)) _check_unary(log, umath.log(ux)) _check_unary(sin, umath.sin(ux)) _check_unary(cos, umath.cos(ux)) _check_unary(tan, umath.tan(ux)) _check_unary(arcsin, umath.asin(ux)) _check_unary(arccos, umath.acos(ux)) _check_unary(arctan, umath.atan(ux)) _check_binary(arctan2, umath.atan2(ux, uy))
def eval_pressure(self, sO2, A, T): """Calculate O2 pressure by saturation. P = ODC(S,A,T) [16] Siggaard-Andersen O, Wimberley PD, Göthgen IH, Siggaard-Andersen M. A mathematical model of the hemoglobin-oxygen dissociation curve of human blood and of the oxygen partial pressure as a function of temperature. Clin Chem 1984; 30: 1646-51. [18] Siggaard-Andersen O, Siggaard-Andersen M. The oxygen status algorithm: a computer program for calculating and displaying pH and blood gas data. Scand J Clin Lab Invest 1990; 50, Suppl 203: 29-45. :param float sO2: measured hemoglobin saturation, fraction (46.2) :param float A: an curve displacement along axis x (46.5). :param float T: Body temperature, °C (46.7). :return: p, partial O2 pressure at given sO2 and T conditions for current ODC, kPa. No hemoglobin corrections performed. :rtype: float """ # 46.2 y = math.log(sO2 / (1 - sO2)) # Newtom-Rapson iterative method x_0 = eval_x_0(a=A, T=T) x = x_0 # Start value, as described in paper while True: y_i = haldane_odc(x=x, x_0=x_0, y_0=self.y_0, a=A) if abs(y - y_i) < epsilon: # print("FOUND x", x) break # n ~ 2.7 according to paper n = haldane_odc_diff(x, x_0, self.y_0, A) x = x + (y - y_i) / n # print(y, y_i) # print('y', y, 'x', x) # print('\n%s y ~ \n%s y_hal\n' % ( # y, haldane_odc(x, x_0, self.y_0, A))) p = math.exp(x) # Reverse 46.1 return p
def calculate_flux(rad40, k39, age, arar_constants=None): ''' rad40: radiogenic 40Ar k39: 39Ar from potassium age: age of monitor in years solve age equation for J ''' if isinstance(rad40, (list, tuple, str)): rad40 = ufloat(rad40) if isinstance(k39, (list, tuple, str)): k39 = ufloat(k39) if isinstance(age, (list, tuple, str)): age = ufloat(age) # age = (1 / constants.lambdak) * umath.log(1 + JR) r = rad40 / k39 if arar_constants is None: arar_constants = ArArConstants() j = (umath.exp(age * arar_constants.lambda_k) - 1) / r return j.nominal_value, j.std_dev
def calculate_flux(f, age, arar_constants=None): """ #rad40: radiogenic 40Ar #k39: 39Ar from potassium f: F value rad40Ar/39Ar age: age of monitor in years solve age equation for J """ if isinstance(f, (list, tuple)): f = ufloat(*f) if isinstance(age, (list, tuple)): age = ufloat(*age) try: if arar_constants is None: arar_constants = ArArConstants() j = (umath.exp(age * arar_constants.lambda_k.nominal_value) - 1) / f return j.nominal_value, j.std_dev except ZeroDivisionError: return 1, 0
def calculate_flux(rad40, k39, age, arar_constants=None): ''' rad40: radiogenic 40Ar k39: 39Ar from potassium age: age of monitor in years solve age equation for J ''' if isinstance(rad40, (list, tuple)): rad40 = ufloat(*rad40) if isinstance(k39, (list, tuple)): k39 = ufloat(*k39) if isinstance(age, (list, tuple)): age = ufloat(*age) # age = (1 / constants.lambdak) * umath.log(1 + JR) try: r = rad40 / k39 if arar_constants is None: arar_constants = ArArConstants() j = (umath.exp(age * arar_constants.lambda_k) - 1) / r return j.nominal_value, j.std_dev except ZeroDivisionError: return 1, 0
def calculate_flux(f, age, arar_constants=None, lambda_k=None): """ #rad40: radiogenic 40Ar #k39: 39Ar from potassium f: F value rad40Ar/39Ar age: age of monitor in years solve age equation for J """ if isinstance(f, (list, tuple)): f = ufloat(*f) if isinstance(age, (list, tuple)): age = ufloat(*age) try: if not lambda_k: if arar_constants is None: arar_constants = ArArConstants() lambda_k = nominal_value(arar_constants.lambda_k) j = (umath.exp(age * lambda_k) - 1) / f return j except ZeroDivisionError: return ufloat(1, 0)
xlim(0,0.02) ylim(10,32) errorbar(d_1,A_1-A_0,A_1_err,0, "x", label="Messwerte") legend() savefig("gamma1_lin.png") #Lineare Regression from Tools import lin_reg, make_LaTeX_table m_1, b_1 = lin_reg(d_1,log(A_1-A_0)) print "mu %s und A(0) = %s" % (m_1,b_1) print "A_0:%s " % umath.exp(b_1) #Plot LinFit yscale("log") ylim(10,100) d = linspace(0,0.02) plot(d,exp(m_1.n * d+b_1.n), label = "Lineare Regression") legend() savefig("gamma1_log.png") #Latex Tabelle erzeugen data = array([[int(d_1[i]*1e3),int(N_1[i]), ufloat(A_1[i]-A_0, A_1_err[i]) ]for i in range(7)]) #print make_LaTeX_table(data, [r'{$\frac{d}{\si{\milli\meter}}$} ',r'$N$' ,r'{ $\frac{A-A_0}{\si{\second^{-1}}}$ }'])
Tlist = np.arange(minT, maxT + 10, 10) Authorlist = np.array(data['Author']) klist = np.zeros((len(Tlist), len(Authorlist))) kulist = np.zeros((len(Tlist), len(Authorlist))) #print(klist) for i in range(len(data.index)): # print(i) A = ufloat(data.iloc[i]['A'], data.iloc[i]['Au']) n = ufloat(data.iloc[i]['n'], data.iloc[i]['nu']) E = ufloat(data.iloc[i]['E'], data.iloc[i]['Eu']) for j in range(len(Tlist)): T = j * 10 + minT # print(T) if data.iloc[i]['min T'] <= T <= data.iloc[i]['max T']: k = (A * (T / 298)**n) * umath.exp(-E * 1000 / 8.314 / T) klist[j][i] = k.n kulist[j][i] = k.s else: klist[j][i] = np.nan kulist[j][i] = np.nan rate = pd.DataFrame(klist, columns=Authorlist, index=Tlist) rateu = pd.DataFrame(kulist, columns=Authorlist, index=Tlist) rate.dropna(axis=0, how='all', inplace=True) print(len(rate.index)) klist = rate.values.tolist() rateu.dropna(axis=0, how='all', inplace=True) Tlist = rateu.index.tolist()
def fit_value3(th, a, b, c, d, e, g, f): return a * umath.exp(-(th**2) / b) + c * umath.exp( -(th**2) / d) + e * umath.exp(-(th**2) / g)
def fit_value1(x, a, b, c, d, e, g, f): return a * umath.exp(b * x) + c * umath.exp( -(x**2) / d) + e * umath.exp(-(x * g))
def fit_value4(th, a, b, c, d, f): return a * umath.exp(-th * b) + c * umath.exp(-(th**2) / d)
def calc_tiT(pO2, sO2, T): """O2 content. Based on eq. 19 from paper. """ alphaO2 = 9.83 * 10 ** -3 * math.exp( -1.15 * 10 ** -2 * (T - 37) + 2.1 * 10 ** -4 * (T - 37) ** 2) return ctHb * (1 - self.FCOHb - self.FMetHb) * sO2 + alphaO2 * pO2