def Sesar_relation(Period,ePeriod,FeH,eFeH,RRab,symmetric): if RRab: # relation: y = a + b*Fe + c*logP stdamin = 0.10 stdaplus = 0.12 stdbmin = 0.08 stdbplus = 0.09 stdcmin = 0.73 stdcplus = 0.74 Fe = ufloat(FeH,eFeH) logP = um.log(ufloat(Period,ePeriod),10) # relation only applicable for RRab ! sigma_M_max = 0.04 epsilon_max = ufloat(0,((-2.47*logP.std_dev)**2) + ((-0.42*Fe.std_dev)**2) + ((sigma_M_max)**2)) # only using maximum a posteriori values for sigma M if symmetric: # Option 1 a = ufloat(-2.47,max(stdamin,stdaplus)) # take conservative symmetric error! b = ufloat(0.15,max(stdbmin,stdbplus)) c = ufloat(-0.42,max(stdcmin,stdcplus)) Magnitudeuncertainties = a + b*(Fe-(-1.4)) + c*(logP-um.log(0.52854,10)) + epsilon_max # else: # Option 2 # create the combined PDF's from which one could potentially extract a more correct error return Magnitudeuncertainties else: print("Warning: The star passed to this relation is not of type RRab. This relation is only suitable for such stars. The end result for this star will be NaN +/- NaN.") return ufloat(np.NaN,np.NaN)
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 temperature(self, pressure=None): if pressure == None: pressure = self.P pressure = pressure * 10 # BKN uses kilobars internally lnKd = log(1 - self.Ca_("cpx")) - log(1 - self.Ca_("opx")) top = 23664 + (24.9 + 126.3 * self.X_Fe("cpx")) * pressure bottom = 13.38 + lnKd**2 + 11.59 * self.X_Fe("opx") return top / bottom - 273.15
def test_math_module(): "Operations with the math module" x = ufloat(-1.5, 0.1) # The exponent must not be differentiated, when calculating the # following (the partial derivative with respect to the exponent # is not defined): assert (x**2).nominal_value == 2.25 # Regular operations are chosen to be unchanged: assert isinstance(umath.sin(3), float) # Python >=2.6 functions: if sys.version_info >= (2, 6): # factorial() must not be "damaged" by the umath module, so as # to help make it a drop-in replacement for math (even though # factorial() does not work on numbers with uncertainties # because it is restricted to integers, as for # math.factorial()): assert umath.factorial(4) == 24 # Boolean functions: assert not umath.isinf(x) # Comparison, possibly between an AffineScalarFunc object and a # boolean, which makes things more difficult for this code: assert umath.isinf(x) == False # fsum is special because it does not take a fixed number of # variables: assert umath.fsum([x, x]).nominal_value == -3 # The same exceptions should be generated when numbers with uncertainties # are used: ## !! The Nose testing framework seems to catch an exception when ## it is aliased: "exc = OverflowError; ... except exc:..." ## surprisingly catches OverflowError. So, tests are written in a ## version-specific manner (until the Nose issue is resolved). if sys.version_info < (2, 6): try: math.log(0) except OverflowError, err_math: # "as", for Python 2.6+ pass else: raise Exception('OverflowError exception expected') try: umath.log(0) except OverflowError, err_ufloat: # "as", for Python 2.6+ assert err_math.args == err_ufloat.args
def Muraveva_relations_plx(Period,ePeriod,FeH,eFeH,RRab): # FU/FO Ks MCMC plx Fe = ufloat(FeH,eFeH) a = ufloat(-1.25,0.06) b = ufloat(0.03,0.07) c = ufloat(-2.73,0.25) if RRab: logP = um.log(ufloat(Period,ePeriod),10) else: logP = um.log(ufloat(Period,ePeriod),10) + 0.127 # fundamentalized Magnitudeuncertainties = a + b*Fe + c*logP return Magnitudeuncertainties
def Dambis_W1_relation(Period,ePeriod,FeH,eFeH,RRab): # <M_W1> # y = a + b*Fe + c*log(P_f) Fe = ufloat(FeH,eFeH) a = ufloat(-0.825,0.088) b = ufloat(0.088,0.026) c = 2.33 if RRab: logP = um.log(ufloat(Period,ePeriod),10) else: logP = um.log(ufloat(Period,ePeriod),10) + 0.127 Magnitudeuncertainties = a + b*Fe + c*logP return Magnitudeuncertainties
def age_equation(j, R, scalar=1, include_decay_error=False, arar_constants=None): if isinstance(j, (tuple, str)): j = ufloat(j) if isinstance(R, (tuple, str)): R = ufloat(R) if arar_constants is None: arar_constants = ArArConstants() # print constants.lambda_k, 'dec' if include_decay_error: age = (1 / arar_constants.lambda_k) * umath.log(1 + j * R) / float(scalar) else: age = (1 / arar_constants.lambda_k.nominal_value) * umath.log(1 + j * R) / float(scalar) return age
def age_equation(j, R, scalar=1, include_decay_error=False, constants=None): if isinstance(j, (tuple, str)): j = ufloat(j) if isinstance(R, (tuple, str)): R = ufloat(R) if constants is None: from src.processing.constants import Constants constants = Constants() # print constants.lambda_k, 'dec' if include_decay_error: age = (1 / constants.lambda_k) * umath.log(1 + j * R) / float(scalar) else: age = (1 / constants.lambda_k.nominal_value) * umath.log(1 + j * R) / float(scalar) return age
def Klein_relations_W1(Period,ePeriod,RRab): # FU/FO W1 MCMC,k # define the ufloat P = ufloat(Period,ePeriod) # first check wether star is a RRab star or whether star is a RRc star! if RRab: # uncertainties package: a + b*x = y a = ufloat(-0.495,0.013) b = ufloat(-2.38,0.20) Magnitudeuncertainties = a + b*um.log(P/0.55,10) else: # uncertainties package: a + b*x = y a = ufloat(-0.231,0.031) b = ufloat(-1.64,0.62) Magnitudeuncertainties = a + b*um.log(P/0.32,10) return Magnitudeuncertainties
def convert(self, age, error): if hasattr(age, '__iter__'): m = len(age) else: m = 1 torig = self._original_total_decay_constant t = self._lambda_t r, ex, ex_orig = self._calculate_r(age) sr = torig * exp(torig * age * 1e6) * error * 1e6 / ex_orig r_mc = ones(self._n) * r sr_mc = ones(self._n) * sr # return age, error vr = r_mc + sr_mc * randn(self._n, m) age = umath.log(((t / self._lambda_ec) * self._f * r) + 1) / (t * 1e6) # linear error propagation e = self._linear_error_propagation(age * 1e6, r, sr) e *= 1e-6 # tm, tme = self._monte_carlo_error_propagation() # tm *= 1e-6 # tme *= 1e-6 tm, tme = 0, 0 return age, e, tm, tme
def extract_gates_T1_from_result_GST(result, gate_operation_time): """Calculates the T1 from the extracted diagonal decay out of the result of GST analysis. Which is given as a number e.g. 0.001, from which T1 can be calculated. Which is done by: (1-decayrate)**N=e**(N*ln(1-decayrate)), where N is the number of gates applied. And: e**(N*ln(1-decayrate))=e**(-t/T1). This gives: T1=-time_per_gate/ln(1-decayrate) Parameters -------------------------------- result: pygsti.report.results.Results object Result from standard GST analysis. gate_operation_time: float The time each gate operation (pulse) takes in seconds. Returns --------------------------------- T1 in seconds""" decomptable = result.tables['bestGatesetDecompTable'] gatelabels = decomptable.keys() T1_dict = {} for i, gatelabel in enumerate(gatelabels): diag_dec = ufloat(decomptable[gatelabel]['Diag. decay']) T1 = -gate_operation_time/umath.log(1-diag_dec) T1_dict[gatelabel] = T1 # T1_gates = [-gate_operation_time/np.log((1-i)) for i in Diagonal_decay_rates] return T1_dict
def temperature(self, pressure=None): if pressure == None: pressure = self.P pressure = pressure * 10 top = 6425 + 26.4 * pressure bottom = -log(self.opx["Ca"]) + 1.843 return top / bottom - 273.15
def extract_gates_T1_from_result_GST(result, gate_operation_time): """Calculates the T1 from the extracted diagonal decay out of the result of GST analysis. Which is given as a number e.g. 0.001, from which T1 can be calculated. Which is done by: (1-decayrate)**N=e**(N*ln(1-decayrate)), where N is the number of gates applied. And: e**(N*ln(1-decayrate))=e**(-t/T1). This gives: T1=-time_per_gate/ln(1-decayrate) Parameters -------------------------------- result: pygsti.report.results.Results object Result from standard GST analysis. gate_operation_time: float The time each gate operation (pulse) takes in seconds. Returns --------------------------------- T1 in seconds""" decomptable = result.tables['bestGatesetDecompTable'] gatelabels = decomptable.keys() T1_dict = {} for i, gatelabel in enumerate(gatelabels): diag_dec = ufloat(decomptable[gatelabel]['Diag. decay']) T1 = -gate_operation_time / umath.log(1 - diag_dec) T1_dict[gatelabel] = T1 # T1_gates = [-gate_operation_time/np.log((1-i)) for i in Diagonal_decay_rates] return T1_dict
def age_equation(j, f, include_decay_error=False, lambda_k=None, arar_constants=None): if isinstance(j, tuple): j = ufloat(*j) elif isinstance(j, str): j = ufloat(j) if isinstance(f, tuple): f = ufloat(*f) elif isinstance(f, str): f = ufloat(f) if not lambda_k: if arar_constants is None: arar_constants = ArArConstants() lambda_k = arar_constants.lambda_k if arar_constants is None: arar_constants = ArArConstants() if not include_decay_error: lambda_k = nominal_value(lambda_k) try: # lambda is defined in years, so age is in years age = lambda_k**-1 * umath.log(1 + j * f) return arar_constants.scale_age(age, current='a') except (ValueError, TypeError): return ufloat(0, 0)
def age_equation(j, f, include_decay_error=False, lambda_k=None, scalar=None, arar_constants=None): if isinstance(j, tuple): j = ufloat(*j) elif isinstance(j, str): j = ufloat(j) if isinstance(f, tuple): f = ufloat(*f) elif isinstance(f, str): f = ufloat(f) if not lambda_k: if arar_constants is None: arar_constants = ArArConstants() lambda_k = arar_constants.lambda_k if not scalar: if arar_constants is None: arar_constants = ArArConstants() scalar = float(arar_constants.age_scalar) if not include_decay_error: lambda_k = nominal_value(lambda_k) try: return (lambda_k ** -1 * umath.log(1 + j * f)) / scalar except (ValueError, TypeError): return ufloat(0, 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 age_equation(j, f, include_decay_error=False, lambda_k=None, scalar=None, arar_constants=None): if isinstance(j, tuple): j = ufloat(*j) elif isinstance(j, str): j = ufloat(j) if isinstance(f, tuple): f = ufloat(*f) elif isinstance(f, str): f = ufloat(f) if not lambda_k: if arar_constants is None: arar_constants = ArArConstants() lambda_k = arar_constants.lambda_k if not scalar: if arar_constants is None: arar_constants = ArArConstants() scalar = float(arar_constants.age_scalar) if not include_decay_error: lambda_k = nominal_value(lambda_k) try: return (lambda_k**-1 * umath.log(1 + j * f)) / scalar except (ValueError, TypeError): return ufloat(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 extinction_ratio(source, fitting, Av): Av_value = np.zeros(len(fitting)) Av_error = np.zeros(len(fitting)) for i in range(8): u_source = ufloat(source[i], source[i + 8]) u_Av = ufloat(Av[0], Av[1]) print('source: {0}'.format(u_source)) print('intrinsic data: {0}'.format(fitting[i])) result = -2.5 * (umath.log(u_source, 10.0) - umath.log(fitting[i], 10.0)) print('result: {0}'.format(result)) print('Av: {0}'.format(u_Av)) ratio = result / u_Av print(ratio) Av_value[i] = ratio.n Av_error[i] = ratio.s return Av_value, Av_error
def boltzmann_inverse(y, a1=1., a2=0., B=1., Q=1, logfit=True, altfit=0): """Inverts and finds the user defined crossing point (default at 80%)""" try: y = y.nominal_value if logfit: if altfit == 1: b_inv = np.power((1 / Q * ((a1 - y) / (y - a2))), -B) else: b_inv = np.power((1 / Q * ((a1 - y) / (y - a2))), -1 / B) else: if altfit == 1: b_inv = -B * umath.log(1 / Q * ((a1 - y) / (y - a2))) else: b_inv = -1 / B * umath.log(1 / Q * ((a1 - y) / (y - a2))) except: print('Failed to invert') b_inv = [] return b_inv
def eval_x_0(a, T): """Will be calculated multiple times to allow other functions get temperature as parameter. :param float T: Celsus temperature. Return `x_0` for `haldane_odc` or `haldane_odc_diff`. """ b = 0.055 * (T - T_0) # Eq. 46.7, temperature shift along `x` return math.log(p_00) + a + b # Eq. 46.4
def temperature(self, pressure=None): """Uncertainties from Taylor, page 402""" if pressure == None: pressure = self.P cpx = self.formula["cpx"] opx = self.formula["opx"] lnKd = log(self.a_en("cpx")) - log(self.a_en("opx")) bottom = sum([ self.num(15.67, 0.77, "0"), self.num(14.37, 3.13, "1") * cpx["Ti"], self.num(3.69, 1.61, "2") * cpx["Fe"], self.num(-3.25, 0.81, "3") * self.X_ts(), lnKd**2 ]) T = (self.num(24787, 826, "4") + self.num(678, 87, "5") * pressure) / bottom return T - 273.15
def Neeley_relations(Period,ePeriod,FeH,eFeH,RRab): Fe = ufloat(FeH,eFeH) logP = um.log(ufloat(Period,ePeriod),10) # Model: y = a + b*Fe + c*log P if RRab: # W1 FU a = ufloat(-0.784,0.007) b = ufloat(0.183,0.004) c = ufloat(-2.274,0.022) else: # W1 FO a = ufloat(-1.341,0.024) b = ufloat(0.152,0.004) c = ufloat(-2.716,0.047) Magnitudeuncertainties = a + b*Fe + c*logP return Magnitudeuncertainties
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 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 age_equation(j, f, include_decay_error=False, arar_constants=None): if isinstance(j, (tuple, str)): j = ufloat(j) if isinstance(f, (tuple, str)): f = ufloat(f) if arar_constants is None: arar_constants = ArArConstants() scalar = float(arar_constants.age_scalar) lk = arar_constants.lambda_k if not include_decay_error: lk = lk.nominal_value try: return (lk**-1 * umath.log(1 + j * f)) / scalar except (ValueError, TypeError): return ufloat(0, 0)
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 age_equation(j, f, include_decay_error=False, arar_constants=None): if isinstance(j, (tuple, str)): j = ufloat(j) if isinstance(f, (tuple, str)): f = ufloat(f) if arar_constants is None: arar_constants = ArArConstants() scalar = float(arar_constants.age_scalar) lk = arar_constants.lambda_k if not include_decay_error: lk = lk.nominal_value try: return (lk ** -1 * umath.log(1 + j * f)) / scalar except (ValueError, TypeError): return ufloat(0,0)
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))
# fsum is special because it does not take a fixed number of # variables: assert umath.fsum([x, x]).nominal_value == -3 # The same exceptions should be generated when numbers with uncertainties # are used: try: math.log(0) except ValueError, err_math: # "as", for Python 2.6+ pass else: raise Exception('ValueError exception expected') try: umath.log(0) except ValueError, err_ufloat: # "as", for Python 2.6+ assert err_math.args == err_ufloat.args else: raise Exception('ValueError exception expected') try: umath.log(uncertainties.ufloat((0, 0))) except ValueError, err_ufloat: # "as", for Python 2.6+ assert err_math.args == err_ufloat.args else: raise Exception('ValueError exception expected') try: umath.log(uncertainties.ufloat((0, 1))) except ValueError, err_ufloat: # "as", for Python 2.6+ assert err_math.args == err_ufloat.args else:
def test_math_module(): "Operations with the math module" x = uncertainties.ufloat((-1.5, 0.1)) # The exponent must not be differentiated, when calculating the # following (the partial derivative with respect to the exponent # is not defined): assert (x**2).nominal_value == 2.25 # Regular operations are chosen to be unchanged: assert isinstance(umath.sin(3), float) # Python >=2.6 functions: if sys.version_info >= (2, 6): # factorial() must not be "damaged" by the umath module, so as # to help make it a drop-in replacement for math (even though # factorial() does not work on numbers with uncertainties # because it is restricted to integers, as for # math.factorial()): assert umath.factorial(4) == 24 # Boolean functions: assert not umath.isinf(x) # Comparison, possibly between an AffineScalarFunc object and a # boolean, which makes things more difficult for this code: assert umath.isinf(x) == False # fsum is special because it does not take a fixed number of # variables: assert umath.fsum([x, x]).nominal_value == -3 # The same exceptions should be generated when numbers with uncertainties # are used: ## !! The Nose testing framework seems to catch an exception when ## it is aliased: "exc = OverflowError; ... except exc:..." ## surprisingly catches OverflowError. So, tests are written in a ## version-specific manner (until the Nose issue is resolved). if sys.version_info < (2, 6): try: math.log(0) except OverflowError(err_math): # "as", for Python 2.6+ pass else: raise Exception('OverflowError exception expected') try: umath.log(0) except OverflowError(err_ufloat): # "as", for Python 2.6+ assert err_math.args == err_ufloat.args else: raise Exception('OverflowError exception expected') try: umath.log(uncertainties.ufloat((0, 0))) except OverflowError( err_ufloat): # "as", for Python 2.6+ assert err_math.args == err_ufloat.args else: raise Exception('OverflowError exception expected') try: umath.log(uncertainties.ufloat((0, 1))) except OverflowError( err_ufloat): # "as", for Python 2.6+ assert err_math.args == err_ufloat.args else: raise Exception('OverflowError exception expected') elif sys.version_info < (3,): try: math.log(0) except ValueError( err_math): pass else: raise Exception('ValueError exception expected') try: umath.log(0) except ValueError( err_ufloat): assert err_math.args == err_ufloat.args else: raise Exception('ValueError exception expected') try: umath.log(uncertainties.ufloat((0, 0))) except ValueError( err_ufloat): assert err_math.args == err_ufloat.args else: raise Exception('ValueError exception expected') try: umath.log(uncertainties.ufloat((0, 1))) except ValueError( err_ufloat): assert err_math.args == err_ufloat.args else: raise Exception('ValueError exception expected') else: # Python 3+ # !!! The tests should be made to work with Python 3 too! pass
def CalcG(te, k12, k21, k13, k31, k23, k32, pB, pC, rettype="list"): # Recast exchange rates as ufloats k12 = ufloat(k12.n, k12.std_dev) k13 = ufloat(k13.n, k13.std_dev) k21 = ufloat(k21.n, k21.std_dev) k31 = ufloat(k31.n, k31.std_dev) k23 = ufloat(k23.n, k23.std_dev) k32 = ufloat(k32.n, k32.std_dev) # Unpack numpy arrays to ufloats pB = ufloat(pB[0], pB[1]) pC = ufloat(pC[0], pC[1]) pA = 1. - (pB + pC) # Calc kcals kcal = calorie * 1e3 # Delta G's of ESs (dG) and transition barriers (ddG) dG12, dG13 = ufloat(0., 0.), ufloat(0., 0.) ddG12, ddG13 = ufloat(0., 0.), ufloat(0., 0.) ddG21, ddG31 = ufloat(0., 0.), ufloat(0., 0.) ddG23, ddG32 = ufloat(0., 0.), ufloat(0., 0.) # Calculate energies of excited states if k12 != 0. and k21 != 0.: dG12 = (-umath.log((k12 * hC) / (kB * te)) * rG * te) - (-umath.log( (k21 * hC) / (kB * te)) * rG * te) dG12 = dG12 / kcal elif pB != 0.: dG12 = -rG * te * umath.log(pB / pA) dG12 = dG12 / kcal if k13 != 0. and k31 != 0.: dG13 = (-umath.log((k13 * hC) / (kB * te)) * rG * te) - (-umath.log( (k31 * hC) / (kB * te)) * rG * te) dG13 = dG13 / kcal elif pC != 0.: dG13 = -rG * te * umath.log(pC / pA) dG13 = dG13 / kcal # Calculate forward and reverse barriers (Joules/mol) # Then convert to kcal/mol if k12 != 0.: ddG12 = -umath.log((k12 * hC) / (kB * te)) * rG * te ddG12 = ddG12 / kcal # Convert to kcal/mol if k21 != 0.: ddG21 = -umath.log((k21 * hC) / (kB * te)) * rG * te ddG21 = ddG21 / kcal # Convert to kcal/mol if k13 != 0.: ddG13 = -umath.log((k13 * hC) / (kB * te)) * rG * te ddG13 = ddG13 / kcal # Convert to kcal/mol if k31 != 0.: ddG31 = -umath.log((k31 * hC) / (kB * te)) * rG * te ddG31 = ddG31 / kcal # Convert to kcal/mol if k23 != 0.: ddG23 = -umath.log((k23 * hC) / (kB * te)) * rG * te ddG23 = ddG23 / kcal # Convert to kcal/mol if k32 != 0.: ddG32 = -umath.log((k32 * hC) / (kB * te)) * rG * te ddG32 = ddG32 / kcal # Convert to kcal/mol if rettype == "list": return dG12, ddG12, ddG21, dG13, ddG13, ddG31, ddG23, ddG32 elif rettype == "dict": # Get separate dictionaries of errors and parameter values # then combine and return the master dict parD = { "dG12": dG12.n, "dG13": dG13.n, "ddG12": ddG12.n, "ddG21": ddG21.n, "ddG13": ddG13.n, "ddG31": ddG31.n, "ddG23": ddG23.n, "ddG32": ddG32.n } parErr = { "dG12_err": dG12.std_dev, "dG13_err": dG13.std_dev, "ddG12_err": ddG12.std_dev, "ddG21_err": ddG21.std_dev, "ddG13_err": ddG13.std_dev, "ddG31_err": ddG31.std_dev, "ddG23_err": ddG23.std_dev, "ddG32_err": ddG32.std_dev } retDict = parD.copy() retDict.update(parErr) return retDict
plt.savefig("magnetization-plot.png") plt.cla() # Plotting susceptibility for L in L_values: plot_feature(L, "chi", False) plt.title("Susceptibility vs Temperature") plt.xlabel("Temperature") plt.ylabel("Susceptibility") plt.legend() plt.savefig("susceptibility-plot.png") plt.cla() # Plotting chi(Tc) vs L x = np.log(np.array(L_values)) chi_at_Tc = [umath.log(chi_max(get_output(L))) for L in L_values] y = [x.nominal_value for x in chi_at_Tc] yerr = [x.std_dev for x in chi_at_Tc] plt.errorbar(x, y, yerr=yerr, fmt='o') # Plot linear fit slope, intercept = np.polyfit(x, y, 1) y = slope * x + intercept plt.plot(x, y, color='red') plt.title("Susceptibility as a function of $\log L$") plt.xlabel("$\log L$") plt.ylabel("$\\log \\chi(T_c(L))$") plt.savefig("chi-max-plot.png") plt.cla()
#a, b, c = p return a + b * c**x # p0 is the initial guess for the fitting coefficients p0 = [1., 1., 1.] p, cov = curve_fit(func, x, data, p0=p0) #, sigma=np.sqrt(1/error)) p_uc = uc.correlated_values(p, cov) c = p_uc[2] T12_lit = 98 lamb_lit = -(np.log(2)/T12_lit) print("lit",lamb_lit) lamb = umath.log(c) print(lamb) T12 = -np.log(2) /lamb print("t12=",T12) x_fit = np.linspace(min(x),max(x)) data_fit = unv(func(x_fit,*p_uc) ) data_fit_min = unv(func(x_fit, *p_uc)) - usd(func(x_fit, *p_uc)) data_fit_max = unv(func(x_fit, *p_uc)) + usd(func(x_fit, *p_uc)) """ ax1.fill_between(Is, unv(np.polyval(c, Is)) + usd(np.polyval(c, Is)), unv(np.polyval(c, Is)) - usd(np.polyval(c, Is)), facecolor=colors[0], color=colors[0], alpha=0.2)
if sys.version_info < (2, 6): try: math.log(0) except OverflowError, err_math: # "as", for Python 2.6+ pass else: raise Exception('OverflowError exception expected') try: umath.log(0) except OverflowError, err_ufloat: # "as", for Python 2.6+ assert err_math.args == err_ufloat.args else: raise Exception('OverflowError exception expected') try: umath.log(ufloat(0, 0)) except OverflowError, err_ufloat: # "as", for Python 2.6+ assert err_math.args == err_ufloat.args else: raise Exception('OverflowError exception expected') try: umath.log(ufloat(0, 1)) except OverflowError, err_ufloat: # "as", for Python 2.6+ assert err_math.args == err_ufloat.args else: raise Exception('OverflowError exception expected') else: try: math.log(0)
from uncertainties import umath import matplotlib.pyplot as plt t = [] #ms lnv = [] tau = 47 * 47 / 100000 with open('dadosdescarga.tsv', 'r') as tsvfile: reader = csv.reader(tsvfile, delimiter='\t') for row in reader: t.append(float(row[0])) lnv.append(float(row[1])) y = [] dy = [] for i in range(10): dd = ufloat(lnv[i], (lnv[i]) * 4 / 100 + 0.5001) dy.append(umath.log(math.fabs((dd).s))) y.append(lnv[i]) ye = linegress.lineregression(t, y) #for i in range(10): # print(math.log(v0-v[i])) plt.plot(t, y, '.', label="pontos obtidos experimentalmente", color='grey') plt.plot(t, ye, label='regressao') plt.errorbar(t, y, yerr=dy, label='barra de erros') plt.legend() plt.show()
def extinction_ratio(u_source, u_fitting, u_Av): A_lambda = -2.5 * (umath.log(u_source, 10.0) - umath.log(u_fitting, 10.0)) ratio = A_lambda/u_Av return A_lambda
def test_math_module(): "Operations with the math module" x = ufloat(-1.5, 0.1) # The exponent must not be differentiated, when calculating the # following (the partial derivative with respect to the exponent # is not defined): assert (x**2).nominal_value == 2.25 # Regular operations are chosen to be unchanged: assert isinstance(umath.sin(3), float) # Python >=2.6 functions: if sys.version_info >= (2, 6): # factorial() must not be "damaged" by the umath module, so as # to help make it a drop-in replacement for math (even though # factorial() does not work on numbers with uncertainties # because it is restricted to integers, as for # math.factorial()): assert umath.factorial(4) == 24 # fsum is special because it does not take a fixed number of # variables: assert umath.fsum([x, x]).nominal_value == -3 # Functions that give locally constant results are tested: they # should give the same result as their float equivalent: for name in umath.locally_cst_funcs: try: func = getattr(umath, name) except AttributeError: continue # Not in the math module, so not in umath either assert func(x) == func(x.nominal_value) # The type should be left untouched. For example, isnan() # should always give a boolean: assert type(func(x)) == type(func(x.nominal_value)) # The same exceptions should be generated when numbers with uncertainties # are used: ## !! The Nose testing framework seems to catch an exception when ## it is aliased: "exc = OverflowError; ... except exc:..." ## surprisingly catches OverflowError. So, tests are written in a ## version-specific manner (until the Nose issue is resolved). if sys.version_info < (2, 6): try: math.log(0) except OverflowError, err_math: # "as", for Python 2.6+ pass else: raise Exception('OverflowError exception expected') try: umath.log(0) except OverflowError, err_ufloat: # "as", for Python 2.6+ assert err_math.args == err_ufloat.args
def main(): # setup the command line parser options parser = argparse.ArgumentParser(description='Plot Raw MC Equilibration Data for Scalar Estimators.') parser.add_argument('fileNames', help='Scalar estimator files', nargs='+') parser.add_argument('--estimator','-e', help='A list of estimator names that \ are to be plotted.', type=str) parser.add_argument('--skip','-s', help='Number of measurements to be skipped \ in the average plot.', type=int, default=0) parser.add_argument('--period','-p', help='Period of the simple moving \ average. default=50', type=int, default=50) args = parser.parse_args() fileNames = args.fileNames if len(fileNames) < 1: parser.error("Need to specify at least one scalar estimator file") toSort = True for fileName in fileNames: if fileName.find('/') != -1: toSort = False if toSort: fileNames.sort() ffile = open(fileNames[0],'r') headers = ffile.readline().lstrip('#').split() headers += ['srt'] print headers # If we don't choose an estimator, provide a list of possible ones if (not args.estimator) or (args.estimator not in headers): errorString = "Need to specify one of:\n" for head,index in headers.iteritems(): errorString += "\"%s\"" % head + " " parser.error(errorString) numFiles = len(fileNames) #colors = loadgmt.getColorList('cw/1','cw1-029',max(numFiles,2)) colors = ["#66CAAE", "#CF6BDD", "#E27844", "#7ACF57", "#92A1D6", "#E17597", "#C1B546",'b'] fig = figure(1,figsize=(13,6)) ax = subplot(111) connect('key_press_event',kevent.press) #rcParams.update(mplrc.aps['params']) n = 0 E0 = 0 Es = [] dEs = [] srt = False if args.estimator=='srt': srt=True for i,fileName in enumerate(fileNames): dataFile = open(fileName,'r'); dataLines = dataFile.readlines(); ffile = open(fileName,'r') headers = ffile.readline().lstrip('#').split() headers += ['srt'] if len(dataLines) > 2: #params = GetFileParams(fileName) if srt and not('ALRatio' in headers): col = GetHeaderNumber(fileName,'nAred') dataR = loadtxt(fileName,usecols=col) col = GetHeaderNumber(fileName,'nAext') dataE = loadtxt(fileName,usecols=col) daveR = amax(MCstat.bin(dataR[args.skip:]),axis=0) aveR = average(dataR[args.skip:]) daveE = amax(MCstat.bin(dataE[args.skip:]),axis=0) aveE = average(dataE[args.skip:]) #S2 = -umath.log(ufloat(aveE,daveE)/ufloat(aveR,daveR)) S2 = -1.0*umath.log(ufloat(aveE,daveE)/ufloat(aveR,daveR)) print 'Entropy = ', S2 Es += [S2.n] dEs += [S2.s] else: if srt: col = GetHeaderNumber(fileName,'ALRatio') else : col = GetHeaderNumber(fileName,args.estimator) data = loadtxt(fileName,usecols=col) ID = fileName[-14:-4] if size(data) > 1: sma = simpleMovingAverage(args.period,data[args.skip:]) ax.plot(sma,color=colors[i%len(colors)],linewidth=3,linestyle='-') bins = MCstat.bin(data[args.skip:]) dataErr = amax(bins,axis=0) dataAve = average(data[args.skip:]) if srt or (args.estimator=='ALRatio'): S2 = -1.0*umath.log(ufloat(dataAve,dataErr)) print 'Entropy = ', S2 Es += [S2.n] dEs += [S2.s] #ax.plot(bins,color=colors[i%len(colors)],linewidth=1,marker='None',linestyle='-') #if E0 == 0: E0 = dataAve print '%0.6f +/- %0.6f ' %(dataAve-E0,dataErr) #print dataAve-E0 else: print '%s contains no measurements' %fileName xlabel('MC bins (p=%s)' %args.period) ylabel(args.estimator) #tight_layout() print Es print dEs #legend() show()
def assymetric_erorrs(p0, p1): P = (p0*(1-p1)+p1*(1-p0))/ ((1-p0)+(1-p1)) return P def inverse_assymetric_errors(P_total, p0): p1 = -(P_total*(p0-2)+p0)/(P_total-2*p0 + 1) return p1 print(inverse_assymetric_errors(assymetric_erorrs(0, 0.2), 0)) t_rest = 4.25e-6 T1_PSD = ufloat(22.7e-6, 3e-6) # T1 = ufloat(19.3e-6, 2.1825e-6) p0 = 0.0 p1 = 1-np.e**(-t_rest/T1_PSD) # p1-1 = -e**() # 1- p1 = e**() # log(1-p1) = -t_rest/T1_PSD p_naive = 1-np.e**(-t_rest/(2*T1_PSD)) print('P_assymetric: {:.4f}'.format(assymetric_erorrs(p0=p0, p1=p1)*100)) P_total = ufloat(0.117, 0.01) # P_total = .117 p1 = inverse_assymetric_errors(P_total=P_total, p0=p0) T1 = -t_rest/(log(1-p1)) print('PSD T1: {:.4f} us, CV: {:.4f}'.format(T1_PSD*1e6, T1_PSD.std_dev/T1_PSD.nominal_value)) print('expected T1 from model fit: {:.4f} us, CV:{:.4f}'.format(T1*1e6, T1.std_dev/T1.nominal_value))
def fit( self, sO2, pO2, pCO2, pH, T=37, FCOHb=0.004, FMetHb=0.004, p50st=None): """Evaluate ODC position for specific blood sample. .. note:: The reference position of the ODC was chosen to be the one that corresponds to the default value for p50(st) = 3.578 kPa, which is traditionally considered the most likely value of p50 for adult humans under standard conditions, namely: pH = 7.40 pCO2 = 5.33 # kPa FCOHb, FMetHb, FHbF = (0, 0, 0) cDPG = 5 # mmol/L Pass measured parameters to this function. .. note:: For some devices [1]: If the sO2 value for establishing the ODC is greater than 0.97, the calculation of the some parameter is not performed unless the p50(st) value is keyed in. Enter measured parameters to fit curve in it. """ self.FCOHb = FCOHb self.FMetHb = FMetHb self.sO2 = sO2 self.pO2 = pO2 self.pCO2 = pCO2 self.pH = pH self.T = T self.p50st = p50st # Eq. 46.3 self.y_0 = math.log(s_0 / (1 - s_0)) ####################################################################### # Determining actual displacement 'a'. It includes: # * 'ac' - an guess, by measured parameters # * 'a6' - an additional shift a1 = -0.88 * (pH - 7.40) a2 = 0.048 * math.log(pCO2 / 5.33) # 5.33 pCO2 a3 = -0.7 * FMetHb a4 = (0.06 - 0.02 * FHbF) * (cDPG - 5) a5 = -0.25 * FHbF ac = a1 + a2 + a3 + a4 + a5 if sO2 <= 0.97 and not p50st: # I # Рассчитать P0S0 по измеренным значениям # На основе измеренных параметров рассчитать сдвиг 'ac' # Использовать 46.3, 46.4? # Определить 'a6' кривой reference position при которых она # будет проходить через измеренную точку P0S0 P0 = pO2 + (pO2 / sO2) * (FCOHb / (1 - FCOHb - FMetHb)) # 46.9 x_measured = math.log(P0) S0 = (sO2 * (1 - FCOHb - FMetHb) + FCOHb) / (1 - FMetHb) # 46.11 y_measured = math.log(S0 / (1 - S0)) # print('P0', P0, 'S0', S0) # print('x_measured', x_measured, 'y_measured', y_measured) # Newtom-Rapson method # http://web.mit.edu/10.001/Web/Course_Notes/NLAE/node6.html a = 0 # Start value, as described in paper while True: x_0i = eval_x_0(a=a, T=T) # n ~ 2.7 according to paper y_i = haldane_odc(x=x_measured, x_0=x_0i, y_0=self.y_0, a=a) if abs(y_measured - y_i) < epsilon: break n = haldane_odc_diff(x=x_measured, x_0=x_0i, y_0=self.y_0, a=a) a = a + (y_measured - y_i) / ( -n + math.tanh(k_0 * (x_measured - x_0i))) # Brackets self.ac = ac self.a = a self.a6 = a - ac else: if p50st is not None: # II # Experimental for pO2(T)? # 46.9, sO2 = 0.5 P0 = p50st + (p50st / 0.5) * (FCOHb / (1 - FCOHb - FMetHb)) x_measured = math.log(P0) # 46.11 S0 = (0.5 * (1 - FCOHb - FMetHb) + FCOHb) / (1 - FMetHb) y_measured = math.log(S0 / (1 - S0)) # *Кривая при стандартных условиях p50st для данного пациента* # Рассчитать точку P0S0 по давлению p50st, сатурации 0.5 # Итеративно определаить `a6` (без учёта ac) при котором кривая # проходиn через рассчитанную точку P0S0 a6 = 0 # Start value, as described in paper while True: x_0i = eval_x_0(a=a6, T=T) # n ~ 2.7 according to paper y_i = haldane_odc( x=x_measured, x_0=x_0i, y_0=self.y_0, a=a6) if abs(y_measured - y_i) < epsilon: break n = haldane_odc_diff( x=x_measured, x_0=x_0i, y_0=self.y_0, a=a6) a6 = a6 + (y_measured - y_i) / ( -n + math.tanh(k_0 * (x_measured - x_0i))) # Brackets # *Расчёт кривой p50act* # К рассчитанному для p50st `a6` прибавить рассчитанный по # измеряемым параметрам сдвиг 'ac' # So `a6` it's shift from reference to keyed standard cond. # `ac` is shift from standard conditions to patient body cond. self.a6 = a6 self.ac = ac self.a = a6 + ac else: # III, ошибочный или зашкаливающий sO2, p50st неизвестно. # Из-за зашкалиающего pO2 кривая будет расчитана приблизительно # Рассчитать по измеряемым параметрам (pH, pCO2, FCOHb, FMetHb, # FHbF) сдвиг 'ac' # Кривая пациента приблизительно соответсвует reference-кривой, # сдвинутой на рассчитанный 'ac' # a = ac # `a6` не нужно определять self.ac = ac self.a = ac self.a6 = 0
def alpha(flux1, flux2, freq1=ufloat(144e6, 24e6), freq2=ufloat(1400e6, 0)): """Get spectral index with error. Default is LDR2 and FIRST. """ return log(flux1 / flux2) / log(freq1 / freq2)
def calc_error_contrib(ar40, ar39, ar38, ar37, ar36, s40, s39, s38, s37, s36, J, constants): # fraction of ar36err from s36,ar37,ar38 fe36_36, fe36_37, fe36_38 = acalc_fractional_error(s36, ca3637 * s37, cl3638 * s38, ar36) # fraction of ar40err from 40signal, 36signal fe40_40, fe40_36 = acalc_fractional_error(s40, constants.atm4036_v * ar36, ar40) R = ar40 / ar39 # fraction of R error from ar40 and ar39 fe40, fe39 = mcalc_fractional_error(ar40, ar39, R) # JR.std_dev equals total error JR = J * R k = constants.lambda_k k.set_std_dev(0) IlambdaK = 1 / k M = JR + 1 # print constants.lambda_k.std_dev() / constants.lambda_k.nominal_value # print IlambdaK.std_dev() / IlambdaK.nominal_value a = umath.log(M) c = IlambdaK * a # print IlambdaK, a # print c.nominal_value * ((IlambdaK.std_dev() / IlambdaK.nominal_value) ** 2 + (a.std_dev() / a.nominal_value) ** 2) ** 0.5 # print c feLambdaK, feJR = mcalc_fractional_error(IlambdaK, a, c) # print feLambdaK, feJR, feLambdaK + feJR # af = (IlambdaK.std_dev() / IlambdaK.nominal_value) ** 2 * (M.std_dev() / M.nominal_value) ** 2 # errLambdaK = a.std_dev() * feLambdaK # errJR = a.std_dev() * feJR # #fraction of JR from J and R Je, Re = mcalc_fractional_error(J, R, JR) # print Je, Re # fractional error from ar40. e40=F40+F36 err = fe40 * Re * feJR # error in ar40 is sum of s40err and s36err err40 = fe40_40 * err err = fe40_36 * err # error in ar36 is sum of s40err and s36err err36 = fe36_36 * err err37 = fe36_37 * err err38 = fe36_38 * err # fractional error from ar39 err39 = fe39 * Re * feJR errJ = Je * feJR errLambdaK = feLambdaK # print 'exception', err40, err36, err39, errJ # print 'exception', err36 + err40 + err39 + errJ # print 'exception', err36 + err37 + err38 + err40 + err39 + errJ + errLambdaK - 1 assert abs(err36 + err37 + err38 + err40 + err39 + errJ + errLambdaK - 1) < 1e-10 return err40, err39, err38, err37, err36, errJ, errLambdaK
results["ΔX(τ)/X"] = [Xgsv.n, Xgsv.s, "%"] del results["ΔX(τ)"] # temp variation T = [] invT = [] lsig = [] lXp = [] lXpm = [] sig = [] for sec in sections: if sec["id"] in tempvar: try: T.append(ufloat(*sec["T"]) + 273.15) invT.append(1 / (ufloat(*sec["T"]) + 273.15)) lsig.append(umath.log(ufloat(*sec["σ"]))) lXp.append(umath.log(ufloat(*sec["Xp"]))) lXpm.append(umath.log(ufloat(*sec["Xp/m"]))) sig.append(ufloat(*sec["σ"])) except ValueError: continue if len(sig) == len(tempvar): for prop, tag, unit in [[lsig, "EA(σ)", "kJ/mol"], [lXp, "EA(X)", "kJ/mol"], [lXpm, "EA(X/m)", "kJ/mol"]]: popt, pcov = curve_fit(linear, [i.n for i in invT], [i.n for i in prop], sigma=[i.s for i in prop], absolute_sigma=True) perr = np.sqrt(np.diag(pcov)) results[tag] = [
def CalcG(te, k12, k21, k13, k31, k23, k32, pB, pC, rettype="list"): # Recast exchange rates as ufloats k12 = ufloat(k12.n, k12.std_dev) k13 = ufloat(k13.n, k13.std_dev) k21 = ufloat(k21.n, k21.std_dev) k31 = ufloat(k31.n, k31.std_dev) k23 = ufloat(k23.n, k23.std_dev) k32 = ufloat(k32.n, k32.std_dev) # Unpack numpy arrays to ufloats pB = ufloat(pB[0], pB[1]) pC = ufloat(pC[0], pC[1]) pA = 1. - (pB + pC) # Calc kcals kcal = calorie * 1e3 # Delta G's of ESs (dG) and transition barriers (ddG) dG12, dG13 = ufloat(0., 0.), ufloat(0., 0.) ddG12, ddG13 = ufloat(0., 0.), ufloat(0., 0.) ddG21, ddG31 = ufloat(0., 0.), ufloat(0., 0.) ddG23, ddG32 = ufloat(0., 0.), ufloat(0., 0.) # Calculate energies of excited states if k12 != 0. and k21 != 0.: dG12 = (-umath.log((k12*hC)/(kB*te))*rG*te) - (-umath.log((k21*hC)/(kB*te))*rG*te) dG12 = dG12 / kcal elif pB != 0.: dG12 = -rG * te * umath.log(pB/pA) dG12 = dG12 / kcal if k13 != 0. and k31 != 0.: dG13 = (-umath.log((k13*hC)/(kB*te))*rG*te) - (-umath.log((k31*hC)/(kB*te))*rG*te) dG13 = dG13 / kcal elif pC != 0.: dG13 = -rG * te * umath.log(pC/pA) dG13 = dG13 / kcal # Calculate forward and reverse barriers (Joules/mol) # Then convert to kcal/mol if k12 != 0.: ddG12 = -umath.log((k12*hC)/(kB*te))*rG*te ddG12 = ddG12 / kcal # Convert to kcal/mol if k21 != 0.: ddG21 = -umath.log((k21*hC)/(kB*te))*rG*te ddG21 = ddG21 / kcal # Convert to kcal/mol if k13 != 0.: ddG13 = -umath.log((k13*hC)/(kB*te))*rG*te ddG13 = ddG13 / kcal # Convert to kcal/mol if k31 != 0.: ddG31 = -umath.log((k31*hC)/(kB*te))*rG*te ddG31 = ddG31 / kcal # Convert to kcal/mol if k23 != 0.: ddG23 = -umath.log((k23*hC)/(kB*te))*rG*te ddG23 = ddG23 / kcal # Convert to kcal/mol if k32 != 0.: ddG32 = -umath.log((k32*hC)/(kB*te))*rG*te ddG32 = ddG32 / kcal # Convert to kcal/mol if rettype == "list": return dG12, ddG12, ddG21, dG13, ddG13, ddG31, ddG23, ddG32 elif rettype == "dict": # Get separate dictionaries of errors and parameter values # then combine and return the master dict parD = {"dG12":dG12.n, "dG13":dG13.n, "ddG12":ddG12.n, "ddG21":ddG21.n, "ddG13":ddG13.n, "ddG31":ddG31.n, "ddG23":ddG23.n, "ddG32":ddG32.n} parErr = {"dG12_err":dG12.std_dev, "dG13_err":dG13.std_dev, "ddG12_err":ddG12.std_dev, "ddG21_err":ddG21.std_dev, "ddG13_err":ddG13.std_dev, "ddG31_err":ddG31.std_dev, "ddG23_err":ddG23.std_dev, "ddG32_err":ddG32.std_dev} retDict = parD.copy() retDict.update(parErr) return retDict
def calc_error_contrib(ar40, ar39, ar38, ar37, ar36, s40, s39, s38, s37, s36, J, constants): # fraction of ar36err from s36,ar37,ar38 fe36_36, fe36_37, fe36_38 = acalc_fractional_error(s36, ca3637 * s37, cl3638 * s38, ar36) # fraction of ar40err from 40signal, 36signal fe40_40, fe40_36 = acalc_fractional_error(s40, constants.atm4036_v * ar36, ar40) R = ar40 / ar39 # fraction of R error from ar40 and ar39 fe40, fe39 = mcalc_fractional_error(ar40, ar39, R) # JR.std_dev equals total error JR = J * R k = constants.lambda_k k.set_std_dev(0) IlambdaK = 1 / k M = JR + 1 # print constants.lambda_k.std_dev() / constants.lambda_k.nominal_value # print IlambdaK.std_dev() / IlambdaK.nominal_value a = umath.log(M) c = IlambdaK * a # print IlambdaK, a # print c.nominal_value * ((IlambdaK.std_dev() / IlambdaK.nominal_value) ** 2 + (a.std_dev() / a.nominal_value) ** 2) ** 0.5 # print c feLambdaK, feJR = mcalc_fractional_error(IlambdaK, a, c) # print feLambdaK, feJR, feLambdaK + feJR # af = (IlambdaK.std_dev() / IlambdaK.nominal_value) ** 2 * (M.std_dev() / M.nominal_value) ** 2 # errLambdaK = a.std_dev() * feLambdaK # errJR = a.std_dev() * feJR # #fraction of JR from J and R Je, Re = mcalc_fractional_error(J, R, JR) # print Je, Re # fractional error from ar40. e40=F40+F36 err = fe40 * Re * feJR # error in ar40 is sum of s40err and s36err err40 = fe40_40 * err err = fe40_36 * err # error in ar36 is sum of s40err and s36err err36 = fe36_36 * err err37 = fe36_37 * err err38 = fe36_38 * err # fractional error from ar39 err39 = fe39 * Re * feJR errJ = Je * feJR errLambdaK = feLambdaK # print err40, err36, err39, errJ # print err36 + err40 + err39 + errJ # print err36 + err37 + err38 + err40 + err39 + errJ + errLambdaK - 1 assert abs(err36 + err37 + err38 + err40 + err39 + errJ + errLambdaK - 1) < 1e-10 return err40, err39, err38, err37, err36, errJ, errLambdaK
def test_math_module(): "Operations with the math module" x = ufloat(-1.5, 0.1) # The exponent must not be differentiated, when calculating the # following (the partial derivative with respect to the exponent # is not defined): assert (x**2).nominal_value == 2.25 # Regular operations are chosen to be unchanged: assert isinstance(umath.sin(3), float) # factorial() must not be "damaged" by the umath module, so as # to help make it a drop-in replacement for math (even though # factorial() does not work on numbers with uncertainties # because it is restricted to integers, as for # math.factorial()): assert umath.factorial(4) == 24 # fsum is special because it does not take a fixed number of # variables: assert umath.fsum([x, x]).nominal_value == -3 # Functions that give locally constant results are tested: they # should give the same result as their float equivalent: for name in umath.locally_cst_funcs: try: func = getattr(umath, name) except AttributeError: continue # Not in the math module, so not in umath either assert func(x) == func(x.nominal_value) # The type should be left untouched. For example, isnan() # should always give a boolean: assert type(func(x)) == type(func(x.nominal_value)) # The same exceptions should be generated when numbers with uncertainties # are used: ## !! The Nose testing framework seems to catch an exception when ## it is aliased: "exc = OverflowError; ... except exc:..." ## surprisingly catches OverflowError. So, tests are written in a ## version-specific manner (until the Nose issue is resolved). try: math.log(0) except ValueError as err_math: # Python 3 does not make exceptions local variables: they are # restricted to their except block: err_math_args = err_math.args else: raise Exception('ValueError exception expected') try: umath.log(0) except ValueError as err_ufloat: assert err_math_args == err_ufloat.args else: raise Exception('ValueError exception expected') try: umath.log(ufloat(0, 0)) except ValueError as err_ufloat: assert err_math_args == err_ufloat.args else: raise Exception('ValueError exception expected') try: umath.log(ufloat(0, 1)) except ValueError as err_ufloat: assert err_math_args == err_ufloat.args else: raise Exception('ValueError exception expected')
def estimate_logg(numax, teff, numax_err=None, teff_err=None): """Calculates the log of the surface gravity using the asteroseismic scaling relations. The two global observable seismic parameters, numax and deltanu, along with temperature, scale with fundamental stellar properties (Brown et al. 1991; Kjeldsen & Bedding 1995). These scaling relations can be rearranged to calculate a stellar surface gravity as g = gsol * (numax/numax_sol)(Teff/Teffsol)^0.5 where g is the surface gravity and Teff is the effective temperature, and the suffix 'sol' indicates a solar value. In this method we use the solar values for numax as given in Huber et al. (2011) and for Teff as given in Prsa et al. (2016). The solar surface gravity is calcluated from the astropy constants for solar mass and radius and does not have an error. The solar surface gravity is returned as log10(g) with units in dex, as is common in the astrophysics literature. This code structure borrows from work done in Bellinger et al. (2019), which also functions as an accessible explanation of seismic scaling relations. If no value of effective temperature is given, this function will check the meta data of the `Periodogram` object used to create the `Seismology` object. These data will often contain an effective tempearture from the Kepler Input Catalogue (KIC, https://ui.adsabs.harvard.edu/abs/2011AJ....142..112B/abstract), or from the EPIC or TIC for K2 and TESS respectively. The temperature values in these catalogues are estimated using photometry, and so have large associated uncertainties (roughly 200 K, see KIC). For more better results, spectroscopic measurements of temperature are often more precise. NOTE: These scaling relations are scaled to the Sun, and therefore do not always produce an entirely accurate result for more evolved stars. Parameters ---------- numax : float The frequency of maximum power of the seismic mode envelope. If not given an astropy unit, assumed to be in units of microhertz. teff : float The effective temperature of the star. In units of Kelvin. numax_err : float Error on numax. Assumed to be same units as numax teff_err : float Error on teff. Assumed to be same units as teff. Returns ------- logg : `.SeismologyQuantity` The log10 of the surface gravity of the star. """ numax = u.Quantity(numax, u.microhertz).value teff = u.Quantity(teff, u.Kelvin).value if all(b is not None for b in [numax_err, teff_err]): numax_err = u.Quantity(numax_err, u.microhertz).value teff_err = u.Quantity(teff_err, u.Kelvin).value unumax = ufloat(numax, numax_err) uteff = ufloat(teff, teff_err) else: unumax = ufloat(numax, 0) uteff = ufloat(teff, 0) ug = G_SOL.value * (unumax / NUMAX_SOL) * (uteff / TEFF_SOL)**0.5 ulogg = umath.log(ug, 10) result = SeismologyQuantity(ulogg.n * u.dex, error=ulogg.s * u.dex, name="logg", method="Uncorrected Scaling Relations") return result
def reg2(): """ The day we saw the hawk On a churchyard tree A kite too Was in the far sky. - Hekigodo """ data2 = np.load("./data/measure4_1.npy")[2:] x2 = np.arange(0,len(data2),1) fit = True redistribute = True #x2 = 1.3149710372035508*x2 -22.617788714272098 c2 = np.where(x2 < 135) data = data2[c2] x = x2[c2] print("datapoints:",len(data)) mass = 79/251/6080*52658 if redistribute == True: # conserving the mass total_mass = mass * len(data) remaining = (data > 0) while True: print("new redistributing ...") print("total mass:",total_mass) # find those which are smaller q = (data[remaining] <= mass) remaining = ~q if len(np.nonzero(q)[0]) == 0: data[remaining] -= mass break print("number of smaller values:",len(np.nonzero(q)[0]),"\n") # subtract the mass of this data total_mass -= np.sum(data[q]) mass = total_mass / len(np.nonzero(~remaining)[0]) data[q] = 0 # redistribute total remaining mass to single channels print("number of nonzero:",len(np.nonzero(data)[0])) c = np.nonzero(data) data = data[c] x = x[c] #scaling to time units x = 6.3149710372035508*x -22.617788714272098 c = (x>0) x = x[c] data = data[c] x = x[::-1] - min(x) error = np.sqrt(data) # only fit for x < 135 fig = plt.figure() ax = plt.subplot(111) plt.grid(True) if fit==True: def func(x, *p): a,b,c = p return a + b * c**x # p0 is the initial guess for the fitting coefficients p0 = [1., 1., 1.] p, cov = curve_fit(func, x, data, p0=p0, sigma = error) p_uc = uc.correlated_values(p, cov) c = p_uc[2] T12_lit = 98 lamb_lit = -(np.log(2)/T12_lit) print("lit",lamb_lit) lamb = umath.log(c) print(lamb) T12 = -np.log(2) /lamb print("t12=",T12) x_fit = np.linspace(min(x),max(x)) data_fit = func(x_fit,*p) pmin = (p - np.sqrt(np.diag(cov))) pmax = (p + np.sqrt(np.diag(cov))) data_fit_min = func(x_fit, *pmin) data_fit_max = func(x_fit, *pmax) plt.plot(x_fit,data_fit) plt.plot(x_fit,90*np.exp(x_fit * lamb_lit)) plt.fill_between(x_fit, data_fit_min , data_fit_max,facecolor="r", color="b", alpha=0.3 ) # place a text box in upper left in axes coords props = dict(boxstyle='round', facecolor='white', alpha=0.5) textstr = '$a + b \cdot c^x$ with\n$a=%.2f$\n$b=%.2f$\n$c=%.2f$'%(p[0], p[1],p[2]) ax.text(0.6, 0.85, textstr, transform=ax.transAxes, fontsize=18, va='top', bbox=props) ax.xaxis.set_tick_params(labelsize = 14) ax.yaxis.set_tick_params(labelsize = 14) ax.add_patch(plt.Rectangle((0,0.1),155,100,alpha = 0.2)) plt.errorbar(x,data, yerr=error,fmt="x") #plt.scatter(x,data,c="blue",alpha = 0.9,s=100, marker="x") plt.ylim(min(data)*0.8,max(data)) #plt.yscale("log") plt.xlim(min(x)*0.8,max(x)) plt.xlabel("time in $ns$", fontsize = 14) plt.ylabel("counts", fontsize = 14) make_fig(fig,1,1,name="plot4_1_reg")