Exemplo n.º 1
0
    def M_halo(self,
               alpha=-0.5,
               alpha_upper=-0.475,
               alpha_lower=-0.575,
               beta=0,
               logx0=10.4,
               gamma=1,
               logy0=1.61,
               logy0_lower=1.49,
               logy0_upper=1.75):

        exists = 'halo_mass' in self.__dict__
        if exists is False:

            stellar_mass = self.M_bulge + self.M_disc

            alpha = uf(alpha,
                       np.max([alpha_upper - alpha, alpha - alpha_lower]))
            beta = uf(beta, 0)
            x0 = uf(10**logx0, 0)
            gamma = uf(gamma, 0)
            y0 = uf(
                10**logy0,
                np.max(
                    [10**logy0_upper - 10**logy0,
                     10**logy0 - 10**logy0_lower]))

            a = y0 * (stellar_mass / x0)**alpha
            b = 1 / 2 + 1 / 2 * ((stellar_mass / x0)**gamma)
            c = (beta - alpha) / gamma
            y = a * (b**c)
            self.halo_mass = y * stellar_mass

        return self.halo_mass
def get_salty_Enc(E, salttype, CO2unc=0.0, H2Ounc=0.0):
    """Get a salty, nominal or less-salty enceladus with the activities as ufloats.
    """
    QE = deepcopy(E)#nc(name='En', pH=ocean_pH, CO2origin='pH', T=T, workoutID=False)

    CO2salt, H2Osalt = Enc.get_CO2_from_HTHeating(QE.env.T, QE.ocean_pH, salts=True)
    CO2salt273, H2Osalt273 = Enc.get_CO2_from_HTHeating(273.15, QE.ocean_pH, salts=True)
    aCO2, aH20, aH2, aCH4 = 0,0,0,0
    if salttype == 'nom':
        aCO2 = CO2salt[0]
        aH2O = H2Osalt[0]
        aH2 = QE.calc_mol_H2(CO2salt273[0])
        aCH4 = QE.calc_mol_CH4(CO2salt273[0])
    elif salttype =='high':
        aCO2 = CO2salt[1]
        aH2O = H2Osalt[1]
        aH2 = QE.calc_mol_H2(CO2salt273[1])
        aCH4 = QE.calc_mol_CH4(CO2salt273[1])
    elif salttype == 'low':
        aCO2 = CO2salt[2]
        aH2O = H2Osalt[2]
        aH2 = QE.calc_mol_H2(CO2salt273[2])
        aCH4 = QE.calc_mol_CH4(CO2salt273[2])
    else:
        raise ValueError('Unknown salt type sent to Q_salty')

    QE.composition['CO2(aq)'].activity = uf(aCO2, aCO2*CO2unc)
    QE.composition['H2(aq)'].activity = aH2
    QE.composition['Methane(aq)'].activity = aCH4
    QE.composition['H2O(l)'].activity = uf(aH2O, aH2O*H2Ounc)

    return QE
Exemplo n.º 3
0
    def get_CO2_from_HTHeating(T, pH, nominals=False, salts=False, CO2unc=0.):
        """
        Return the CO2 activity and H2O activity as ufloats from the carbonate
        speciation model, or as a list with upper and lower bounds
        (when salts==True)

        Attributes
        ----------
        T : float
            Temperature of your position in the ocean
        pH : float
            pH that the ocean would be at 273 K.
        salts : boolean, optional
            if True, use the carbonate speciation model and return
            nominal, upper and lower bounds for both.
        """
        aCO2, aH2O = Enceladus.interpo_CO2_H2O(T, pH)
        if aCO2<0:
            print('WARNING: negative CO2 at pH ', pH, 'Temperature', T, 'setting to 1e10 M')
            if nominals:
                return 1e-10, aH2O
            elif salts:
                aCO2_hs, aH2O_hs = Enceladus.interpo_CO2_H2O(T, pH, salt='highsalt')
                aCO2_ls, aH2O_ls = Enceladus.interpo_CO2_H2O(T, pH, salt='lowsalt')
                return [1e-10, 1e-10, 1e-10], [aH2O, aH2O_hs, aH2O_ls]
            else:
                return uf(1e-10, 2e-11), uf(aH2O,0)
        if nominals:
            return aCO2, aH2O
        elif salts:
            aCO2_hs, aH2O_hs = Enceladus.interpo_CO2_H2O(T, pH, salt='highsalt')
            aCO2_ls, aH2O_ls = Enceladus.interpo_CO2_H2O(T, pH, salt='lowsalt')
            return [aCO2, aCO2_hs, aCO2_ls], [aH2O, aH2O_hs, aH2O_ls]
        else:
            return uf(aCO2, CO2unc*aCO2), uf(aH2O,0)
Exemplo n.º 4
0
 def get_CO2_from_pH(self):
     """
     Return the CO2 activity as estimated from the pH in (Waite et al. 2017).
     Note only really valid at 273 K.
     """
     absCO2 = 10**(-0.1213*(self.pH*self.pH) + (0.9832*self.pH) -3.1741)
     unc = 0.2*absCO2
     if self.nominals:
         return uf(absCO2, unc).n
     else:
         return uf(absCO2, unc)
Exemplo n.º 5
0
    def __init__(self, name, pH=8.5, depth=0., T=273.15,
      mixingratios={},
      CO2origin='pH',
      tigerstripeT=uf(197,20),
      Pconc=uf(1e-6,0), workoutID=False,
      nominals=False,
      saltlevel='nom',
      **kwargs):
        self.depth=depth
        self.env.T=T
        self.env.P=(1+(99*self.depth))*100000 #100 at bottom, 1 at top, linear in between. Pressure has minimal effect on standard free energies.
        self.ocean_pH = pH # the pH of the 'bulk ocean' e.g. at 273 K.
        self.pH = pH # the pH at this section of the ocean, not nec. same as above.
        self.mixingratios=Waite2017ratios
        self.mixingratios.update(mixingratios)
        self.tigerstripeT = tigerstripeT
        self.nominals=nominals

        mol_CO2 = 0.
        aH2O=1.
        oceanvals=False

        if CO2origin=='tigerstripe':
            mol_CO2 = self.get_tigerstripe_CO2()
            self.initial_conditions(self.pH, mol_CO2, Pconc, H2Oact=aH2O, oceanvals=oceanvals)
        elif CO2origin=='pH':
            mol_CO2 = self.get_CO2_from_pH()
            self.initial_conditions(self.pH, mol_CO2, Pconc, H2Oact=aH2O, oceanvals=oceanvals)
        elif CO2origin=='HTHeating':
            mol_CO2, aH2O = Enceladus.get_CO2_from_HTHeating(T=self.env.T, pH=self.ocean_pH, nominals=self.nominals)
            oceanvals=True
            self.initial_conditions(self.pH, mol_CO2, Pconc, H2Oact=aH2O, oceanvals=oceanvals)
        elif CO2origin=='HTHeating20':
            mol_CO2, aH2O = Enceladus.get_CO2_from_HTHeating(T=self.env.T, pH=self.ocean_pH, nominals=self.nominals, CO2unc=0.2)
            oceanvals=True
            self.initial_conditions(self.pH, mol_CO2, Pconc, H2Oact=aH2O, oceanvals=oceanvals)
        elif CO2origin=='HTHeatingSalts':
            mol_CO2lst, aH2Olst = Enceladus.get_CO2_from_HTHeating(T=self.env.T, pH=self.ocean_pH, nominals=self.nominals, CO2unc=0., salts=True)
            # mol_CO2, aH2O = mol_CO2lst[0], aH2Olst[0]
            oceanvals=True
            if saltlevel == 'nom':
                self.initial_conditions(self.pH, mol_CO2lst[0], Pconc, H2Oact=aH2Olst[0], oceanvals=oceanvals)
            elif saltlevel == 'high':
                self.initial_conditions(self.pH, mol_CO2lst[1], Pconc, H2Oact=aH2Olst[1], oceanvals=oceanvals)
            elif saltlevel == 'low':
                self.initial_conditions(self.pH, mol_CO2lst[2], Pconc, H2Oact=aH2Olst[2], oceanvals=oceanvals)

        reactor.__init__(self, name, env=self.env,
          reactionlist=self.reactionlist,
          composition=self.composition,
          workoutID=workoutID, **kwargs)
Exemplo n.º 6
0
    def hi_scalelength(self,m=0.86,m_error=0.04,c=0.79,c_error=0.02,
                        k=0.19,k_error=0.03): # Wang+14, Lelli+16
        exists = 'R_hi' in self.__dict__
        if exists is False:
            m_param = uf(m,m_error)
            c_param = uf(c,c_error)
            k_param = uf(k,k_error)

            r_d = self.R_disc
            log_r_d = unp.log10(r_d)
            logr_hi = m_param * log_r_d + c_param
            r_hi = 10**logr_hi
            self.R_hi = k_param * r_hi
        return self.R_hi
Exemplo n.º 7
0
    def pitch_angle(self, y=1, halo='hernquist', relation='michikoshi'):
        Gamma = self.total_shear(y, halo)
        #tanpsi = 1.932 - 5.186*(0.5*Gamma) + 4.704*(0.5*Gamma)**2
        if relation == 'michikoshi':
            tanpsi = 2 / 7 * unp.sqrt(4 - 2 * Gamma) / Gamma
            self.psi = unp.arctan(tanpsi) * 360 / (2 * math.pi)
        elif relation == 'fuchs':
            tanpsi = 1.932 - 5.186 * (0.5 * Gamma) + 4.704 * (0.5 * Gamma)**2
            self.psi = unp.arctan(tanpsi) * 360 / (2 * math.pi)
        elif relation == 'seigar':
            m = uf(-36.62, 2.77)
            c = uf(64.25, 2.87)
            self.psi = m * Gamma + c

        return self.psi
Exemplo n.º 8
0
    def runFit(self, Koff, Kon, N, Na0, Nn0, plot=True):
        
        uKoff = uf(Koff, self.Koff_err)
        uN = uf(N, self.N_err)
        uNa0 = uf(Na0, self.Na0_err)
        uNn0 = uf(Nn0, self.Nn0_err)
        uKon = uf(Kon, self.Kon_err)
        self.lg1 = f"Kon: {uKon:.2uP}, Na: {uNa0:.2uP}, Nn: {uNn0:.2uP}"
        self.lg2 = f"Koff: {uKoff:.2uP}, N: {uN:.2uP}"

        self.ax0.legend(labels=[self.lg1, self.lg2], title=f"Mass: {self.mass[0]}u, Res: {self.t_res}V, B0: {self.t_b0}ms", fontsize=5, title_fontsize=7)
        self.get_depletion_fit(Koff, N, uKoff, uN, Na0, Nn0, Kon, uNa0, uNn0, uKon, plot)
        self.get_relative_abundance_fit(plot)

        self.ax1.legend(["Fitted", f"A: {self.uA:.3uP}", "Experiment"], fontsize=5, title_fontsize=7)
Exemplo n.º 9
0
    def runFit(self, Koff, Kon, N, Na0, Nn0, plot=True):

        uKoff = uf(Koff, self.Koff_err)
        uN = uf(N, self.N_err)
        uNa0 = uf(Na0, self.Na0_err)
        uNn0 = uf(Nn0, self.Nn0_err)
        uKon = uf(Kon, self.Kon_err)

        lg1 = f"Kon: {uKon:.2uP}, Na: {uNa0:.2uP}, Nn: {uNn0:.2uP}"
        lg2 = f"Koff: {uKoff:.2uP}, N: {uN:.2uP}"

        self.get_depletion_fit(Koff, N, uKoff, uN, Na0, Nn0, Kon, uNa0, uNn0, uKon, plot)
        self.get_relative_abundance_fit(plot)

        self.fig.update_layout(title_text=f"ON: {self.resOnFile.stem}[{self.powerOn}mJ], OFF: {self.resOffFile.stem}[{self.powerOff}mJ];\
            A: {self.uA*100:.2uP}%; [Kon: {uKon:.2uP}, Koff: {uKoff:.2uP}]")
Exemplo n.º 10
0
    def get_relative_abundance_fit(self, plot=True):

        self.depletion_fitted = 1 - (self.fitted_counts["resOn"]/self.fitted_counts["resOff"])
        depletion_fitted_with_err = 1 - (unp.uarray(self.fitted_counts["resOn"], self.fitted_counts_error["resOn"])/unp.uarray(self.fitted_counts["resOff"], self.fitted_counts_error["resOff"]))
        self.depletion_fitted_err = unp.std_devs(depletion_fitted_with_err)

        self.depletion_exp = 1 - (self.counts["resOn"]/self.counts["resOff"])
        depletion_exp_with_err = 1 - (unp.uarray(self.counts["resOn"], self.error["resOn"])/unp.uarray(self.counts["resOff"], self.error["resOff"]))
        self.depletion_exp_err = unp.std_devs(depletion_exp_with_err)
        
        A_init = 0.5
        pop_depletion, popc_depletion = curve_fit(
            self.Depletion, self.fitX, self.depletion_fitted,
            sigma=self.depletion_fitted_err,
            absolute_sigma=True,
            p0=[A_init],
            bounds=[(0), (1)]
        )

        perr_depletion = np.sqrt(np.diag(popc_depletion))

        A = pop_depletion
        A_err = perr_depletion
        self.uA = uf(A, A_err)
        print(f"A: {self.uA:.3uP}")

        self.relative_abundance = self.Depletion(self.fitX, A)

        if plot:
            self.ax1.errorbar(self.power["resOn"], self.depletion_exp, yerr=self.depletion_exp_err, fmt="k.")
            self.fit_plot, = self.ax1.plot(self.fitX, self.depletion_fitted)

            self.relativeFit_plot, = self.ax1.plot(self.fitX, self.relative_abundance)
    def __init__(self, x, y):

        # Gaussian model with guessing init. values
        model = GaussianModel()
        guess = model.guess(y, x=x)
        guess_values = guess.valuesdict()

        # Fitting gaussian curve with guessed values
        fit = model.fit(y,
                        x=x,
                        amplitude=guess_values['amplitude'],
                        center=guess_values['center'],
                        sigma=guess_values['sigma'])

        # Fitted datas: Line freq, sigma and A
        fit_data = fit.best_fit
        line_freq_fit = fit.best_values['center']
        sigma = fit.best_values['sigma']
        A = fit.best_values['amplitude']

        # FWHM and Amplitude from fitted sigma
        fwhm = 2 * sigma * np.sqrt(2 * np.log(2))
        amplitude = A / (sigma * np.sqrt(2 * np.pi))

        # Gettign error value for sig, freq and A from fit
        covar_matrix = fit.covar
        varience = np.diag(covar_matrix)
        perr = np.sqrt(varience)

        sigma_err, line_freq_err, A_err = perr

        # Making uncertainties float for sig., A and freq
        usigma = uf(sigma, sigma_err)
        uA = uf(A, A_err)
        uline_freq = uf(line_freq_fit, line_freq_err)

        # Calculating FWHM and Amplitude
        ufwhm = 2 * usigma * np.sqrt(2 * np.log(2))
        uamplitude = uA / (usigma * np.sqrt(2 * np.pi))

        # Deriving error from calculated FWHM and Amplitude

        amplitude_err = uamplitude.std_dev
        fwhm_err = ufwhm.std_dev

        self.fit_data, self.uline_freq, self.usigma, self.uamplitude, self.ufwhm = fit_data, uline_freq, usigma, uamplitude, ufwhm
Exemplo n.º 12
0
    def __init__(self, value=1, error=None):
        value = float(value)
        if value.is_integer():
            value = int(value)

        if error == None:
            self.value = value
        else:
            self.value = uf(value, error)
Exemplo n.º 13
0
    def __init__(self, dT: int, h_len: float, h_max: float, v_len: float,
                 v_max: int, h_cyc: float, v_cyc: float, displ: float):
        """Setup experiment conditions
        ---------------------------
        dT: temperature difference (K)
        h_len: length of height axis (cm)
        h_max: maximum value of height axis (m)
        v_len: length of pressure axis (cm)
        v_max: maximum value of pressure axis (Pa)
        h_cyc: measurement of cycle on height axis (cm)
        v_cyc: measurement of cycle on pressure axis (cm)
        displ: measurement of displacement of piston during B->C (cm)
        -----------------------------
        self.dT: temperature difference (K)
        self.hu: height scale units (m/cm)
        self.vu: pressure scale units (Pa/cm)
        self.height: height change of cycle (m)
        self.volume: volume change of cycle (m^3)
        self.pressure: pressure change of cycle (Pa)
        self.displ: displacement of piston/mass (m)
        self.cyc_work: work done by cycle (Nm)
        self.useful_work: useful work done moving mass (Nm)
        """
        self.dT = dT

        self.hu = h_max / uf(h_len, 0.01)
        self.vu = v_max / uf(v_len, 0.01)

        self.height = self.hu * uf(h_cyc, 0.01)
        self.volume = self.height * area
        self.pressure = self.vu * uf(v_cyc, 0.01)

        self.displ = self.hu * uf(displ, 0.01)

        self.cyc_work = self.volume * self.pressure
        self.useful_work = F * self.displ
Exemplo n.º 14
0
def eDensity(solvent=(18,10),solute=[],mass_density=(1,0)):
    '''
    Parameters
    ----------
    solute: list of solvents with each component in the form of tuple containing
             molecular weight, electrons per molecule and concentration of that component
             e.g. 10e-4 DHDP (546.85,306,1e-4), 0.5M HEH[EHP] (306.4,170,0.5)...
             the mixture of DHDP and HEH[EHP]: [(546.85,306,1e-4),(306.4,170,0.5)]
             Note: concentration in unit of mole/L
    solvent: tuple of the molecular weight and electrons per molecule for the solvent.
            e.g. water (18,10), dodecane(170.34,98)
    mass_density: mass density of the solution and the uncertainty of the measurement , in g/ml
    
    Notes
    -----
    Calculation, multi-component solutions likewise
    rho_e = (Ne_solute + Ne_solvent)/V # Ne is the number of electrons in the solution
    Ne_solute = N_A * Cons * V * ne_solute # ne is the electrons per mlecule
    Ne_solvent = N_A * (mdens*V-cons*V*mwght1)/mwght2 * ne_solvent
    ==> rho_e = N_A*(cons*ne_solute+(mdens-cons*mwght1)/mwght2*ne_solvent)
    
    10e-4 DHDP in dodecane: -> 0.2596 A^-3
    eDensity(solvent=(170.34,98),solute=[(546.85,306,1e-4)],mass_density=(0.7495,0))
    3M HNO3 in water:  -> 0.3618 A^-3
    eDensity(solvent=(18,10),solute=[(63,32,3)],mass_density=(1.098,0)) 
    0.5M HEH[EHP] and 10mM Eu in dodecane:  -> 0.2672
    eDensity(solvent=(170.34,98),solute=[(306.4,170,0.5),(151.96,63,0.01)],mass_density=(0.7774,0))
    0.5M citrate in water:  -> 0.348
    eDensity(solvent=(18,10),solute=[(192.12,100,0.5)],mass_density=(1.047,0)) 
    Return
    ------
    eDensity: electron density of that solution, in A^-3
    '''
    mdens = uf(mass_density[0]*1e-24,mass_density[1]*1e-24)# convert to g/A^3
    # mdens = mass_density * 1e-24  # convert to g/A^3
    c_n = sum([k[1]*k[2]*1e-27 for k in solute])
    c_m = sum([k[0]*k[2]*1e-27 for k in solute])
    rho_e = N_A*(c_n + (mdens-c_m)/solvent[0]*solvent[1])
    return rho_e
Exemplo n.º 15
0
    def get_relative_abundance_fit(self, plot=True):

        self.depletion_fitted = 1 - (self.fitted_counts["resOn"]/self.fitted_counts["resOff"])
        depletion_fitted_with_err = 1 - (unp.uarray(self.fitted_counts["resOn"], self.fitted_counts_error["resOn"])/unp.uarray(self.fitted_counts["resOff"], self.fitted_counts_error["resOff"]))
        self.depletion_fitted_err = unp.std_devs(depletion_fitted_with_err)

        self.depletion_exp = 1 - (self.counts["resOn"]/self.counts["resOff"])
        depletion_exp_with_err = 1 - (unp.uarray(self.counts["resOn"], self.error["resOn"])/unp.uarray(self.counts["resOff"], self.error["resOff"]))
        self.depletion_exp_err = unp.std_devs(depletion_exp_with_err)
        
        A_init = 0.5
        pop_depletion, popc_depletion = curve_fit(
            self.Depletion, self.fitX, self.depletion_fitted,
            sigma=self.depletion_fitted_err,
            absolute_sigma=True,
            p0=[A_init],
            bounds=[(0), (1)]
        )

        perr_depletion = np.sqrt(np.diag(popc_depletion))

        A = pop_depletion
        A_err = perr_depletion

        self.uA = uf(A, A_err)
        print(f"A: {self.uA:.3uP}")

        self.relative_abundance = self.Depletion(self.fitX, A)

        if plot:
            error_data = dict(type="data", array=self.depletion_exp_err, visible=True)
            trace1 = go.Scatter(x=self.power["resOn"], y=self.depletion_exp, mode="markers", marker=dict(color=f"black"), name="Exp", error_y=error_data)
            trace2 = go.Scatter(x=self.fitX, y=self.depletion_fitted, mode="lines+markers", marker=dict(color=f"rgb{colors[0]}"), name="Fitted")
            trace3 = go.Scatter(x=self.fitX, y=self.relative_abundance, mode="lines+markers", marker=dict(color=f"rgb{colors[2]}"), name="Relative")
            self.fig.add_trace(trace1, row=1, col=2)
            self.fig.add_trace(trace2, row=1, col=2)
            self.fig.add_trace(trace3, row=1, col=2)
            st.subheader(f"Relative abundance: {self.uA*100:.3uP} %")
Exemplo n.º 16
0
    def __init__(self,
                 M_b,
                 delta_M_b,
                 M_d,
                 delta_M_d,
                 a_b,
                 delta_a_b,
                 R_d,
                 delta_R_d,
                 M_hi,
                 delta_M_hi,
                 scale=1.5,
                 scale_error=0.2):

        self.M_b = M_b.to(u.Msun)
        self.delta_M_b = delta_M_b.to(u.Msun)
        self.M_d = M_d.to(u.Msun)
        self.delta_M_d = delta_M_d.to(u.Msun)
        self.a_b = a_b.to(u.kpc)
        self.delta_a_b = delta_a_b.to(u.kpc)
        self.R_d = R_d.to(u.kpc)
        self.delta_R_d = delta_R_d.to(u.kpc)
        self.M_hi = M_hi.to(u.Msun)
        self.delta_M_hi = delta_M_hi.to(u.Msun)

        self.scaler = uf(scale, scale_error)

        self.M_bulge = unp.uarray(self.M_b.value, self.delta_M_b.value)
        self.M_disc = unp.uarray(self.M_d.value, self.delta_M_d.value)
        self.R_bulge = (unp.uarray(self.a_b.value, self.delta_a_b.value) /
                        self.scaler)
        self.R_disc = (unp.uarray(self.R_d.value, self.delta_R_d.value) /
                       self.scaler)
        self.M_hi = unp.uarray(self.M_hi.value, self.delta_M_hi.value)

        H0 = 70 * u.km / u.s / u.Mpc
        rho_crit = (3 * H0**2) / (8 * math.pi * const.G)
        self.rho_crit = (rho_crit.to(u.kg / u.m**3))
Exemplo n.º 17
0
 def __init__(self,M_b,delta_M_b,M_d,delta_M_d,a_b,delta_a_b,
              R_d,delta_R_d,M_hi,delta_M_hi,M_h=None,delta_M_h=None,
              R_h=None,delta_R_h=None,scale=1.5,scale_error=0.2,
              fix_halo=False):
     
     self.M_b = M_b.to(u.Msun)
     self.delta_M_b = delta_M_b.to(u.Msun)
     self.M_d = M_d.to(u.Msun)
     self.delta_M_d = delta_M_d.to(u.Msun)
     self.a_b = a_b.to(u.kpc)
     self.delta_a_b = delta_a_b.to(u.kpc)
     self.R_d = R_d.to(u.kpc)
     self.delta_R_d = delta_R_d.to(u.kpc)
     self.M_hi = M_hi.to(u.Msun)
     self.delta_M_hi = delta_M_hi.to(u.Msun)
     
     self.M_h = M_h.to(u.Msun) if M_h is not None else None
     self.delta_M_h = (delta_M_h.to(u.Msun) if delta_M_h is not None 
                       else None)
     self.R_h = R_h.to(u.kpc) if R_h is not None else None
     self.delta_R_h = (delta_R_h.to(u.kpc) if delta_R_h is not None
                       else None)
     
     self.scaler = uf(scale,scale_error)
     
     self.M_bulge = unp.uarray(self.M_b.value,self.delta_M_b.value)
     self.M_disc = unp.uarray(self.M_d.value,self.delta_M_d.value)
     self.R_bulge = (unp.uarray(self.a_b.value,self.delta_a_b.value)
                    / self.scaler)
     self.R_disc = (unp.uarray(self.R_d.value,self.delta_R_d.value)
                   / self.scaler)
     self.M_hi = unp.uarray(self.M_hi.value,self.delta_M_hi.value)
     
     self.fix_halo = fix_halo
     
     H0 = 70 * u.km/u.s/u.Mpc
     rho_crit = (3 * H0**2) / (8*math.pi*const.G)
     self.rho_crit = (rho_crit.to(u.kg/u.m**3))
Exemplo n.º 18
0
# -*- encoding: utf-8 -* 
import numpy as np
import matplotlib.pyplot as plt

from uncertainties import ufloat as uf
R = uf(10000, 500)
R1 = uf(50000, 2500)
G = R/R1
print(G)

data = np.genfromtxt("../dati/scope_1.csv", delimiter=",", skip_header=2)

t = data[:,0] * 1000
vout = data[:,1] / 2.0 - 0.1
vin = data[:,2] / 2.0

f = plt.figure(figsize=(8, 5))
ax = f.add_subplot(111)
f.suptitle("Sommatore pesato di tensioni")

v1 = ax.errorbar([-2.5, 2.5], [1, 1], linewidth=2, fmt="-", c="gray")
v2 = ax.errorbar(t, vin, linewidth=2, fmt="--", c="black")
vo = ax.errorbar(t, vout, linewidth=2, fmt="-", c="black")
adc = ax.errorbar([-2.5, 2.5], [-0.2, -0.2], fmt="-", c="black")

ax.set_xlabel("Tempo [ms]")
ax.set_ylabel("Tensione [V]")

ax.set_xlim((-2.5, 2.5))
ax.set_ylim((-0.7, 1.2))
Exemplo n.º 19
0
from uncertainties import ufloat as uf
from math import pi

diam = uf(32 / 1000, 1 / 1000)
area = ((diam / 2)**2) * pi
F = 0.1 * 9.81


class Experiment:
    def __init__(self, dT: int, h_len: float, h_max: float, v_len: float,
                 v_max: int, h_cyc: float, v_cyc: float, displ: float):
        """Setup experiment conditions
        ---------------------------
        dT: temperature difference (K)
        h_len: length of height axis (cm)
        h_max: maximum value of height axis (m)
        v_len: length of pressure axis (cm)
        v_max: maximum value of pressure axis (Pa)
        h_cyc: measurement of cycle on height axis (cm)
        v_cyc: measurement of cycle on pressure axis (cm)
        displ: measurement of displacement of piston during B->C (cm)
        -----------------------------
        self.dT: temperature difference (K)
        self.hu: height scale units (m/cm)
        self.vu: pressure scale units (Pa/cm)
        self.height: height change of cycle (m)
        self.volume: volume change of cycle (m^3)
        self.pressure: pressure change of cycle (Pa)
        self.displ: displacement of piston/mass (m)
        self.cyc_work: work done by cycle (Nm)
        self.useful_work: useful work done moving mass (Nm)
Exemplo n.º 20
0
from math import sqrt
from numpy import array, mean


def unc(arr, syst):
    stat = arr.std(ddof=1) / sqrt(len(arr))
    return sqrt(stat**2 + syst**2)


def out(what, howmuch):
    print("{} = {:L}".format(what, howmuch))
    print()


# ----- METODA KYVŮ -----
k_m = uf(148, 0.1) / 1000
k_l = uf(234, 3) / 1000
g = 9.81
k_a_10T = array([24.54, 24.52, 24.43, 24.43, 24.45])
k_a_T = k_a_10T / 10

k_10T = uf(mean(k_a_10T), unc(k_a_10T, 0.01))

k_T = uf(mean(k_a_T), unc(k_a_T, 0.001))
out("k_10T", k_10T)
out("k_T", k_T)

k_I = k_m * k_l * ((g * k_T**2) / (4 * pi**2) - k_l)

out("I", k_I)
Exemplo n.º 21
0
from uncertainties import ufloat as uf
from math import pi
import numpy as np

# ----- DRÁT -----
r = uf(19.28, 0.01) * 0.001
n_0 = uf(147, 0.5) * 0.001
n = uf(116, 0.5) * 0.001
L = uf(810, 1) * 0.001
l_0 = uf(1156.14, 1.2) * 0.001
m = uf(1.4, 0)
d = uf(0.51, 0.01) * 0.001

delta_l = (r * (n_0 - n)) / (2 * L)

E = (4 * l_0 * m * 9.81) / (delta_l * pi * d**2)

print("delta_l:", delta_l)
print("E:", E)

# ----- TRÁMEK -----
l = uf(412, 1) * 0.001
a_o = uf(11.98, 0.02) * 0.001
b_o = uf(1.95, 0.01) * 0.001
a_m = uf(11.84, 0.03) * 0.001
b_m = uf(1.98, 0.01) * 0.001
y_o = uf(1, 0.05) * 0.001
y_m = uf(1.83, 0.05) * 0.001
m = uf(0.1, 0)

E_o = (m * 9.81 * l**3) / (4 * y_o * a_o * b_o**3)
Exemplo n.º 22
0
    def initial_conditions(self, pH, mol_CO2, Pconc, H2Oact=1.0, oceanvals=False, mol_CO2_oc=None):
        """
        Set up the initial conditions of the ocean in the configuration
        defined in the initialisation.

        Attributes
        ----------
        pH : float
            wider ocean (273 K) pH
        mol_CO2 : float
            Calculated activity of CO2 at this ocean location.
        Pconc : ufloat
            Concentration of phosphorus
        H2Oact : float, optional
            water activity, default 1.0.
        oceanvals : boolean, optional
            whether computing the wider ocean CO2 activity is needed.
        mol_CO2_oc : float, optional
            wider ocean CO2 activity. Default is None (then calculated here)
        """
        if mol_CO2_oc == None:
            mol_CO2_oc = mol_CO2
        if oceanvals:
            #get wider ocean CO_2
            mol_CO2_oc = Enceladus.get_CO2_from_HTHeating(T=273.15, pH=pH)[0]

        mol_CH4 = (self.mixingratios['CH4']/self.mixingratios['CO2'])*mol_CO2_oc#2.75*mol_CO2 #0.34*mol_CO2
        mol_H2 = (self.mixingratios['H2']/self.mixingratios['CO2'])*mol_CO2_oc#11*mol_CO2 #103*mol_CO2
        mol_NH3 = (self.mixingratios['NH3']/self.mixingratios['CO2'])*mol_CO2_oc
        mol_H2S = (self.mixingratios['H2S']/self.mixingratios['CO2'])*mol_CO2_oc
        # ^ from the ratios in the plumes, hence are upper limits
        mol_H=uf(10**(-pH),0)
        if self.nominals:
            mol_CH4 = mol_CH4.n
            mol_H2 = mol_H2.n
            mol_NH3 = mol_NH3.n
            mol_H2S = mol_H2S.n
            mol_H=uf(10**(-pH),0).n

        # reagents
        CO2 = reaction.reagent('CO2(aq)', self.env, phase='g', conc=mol_CO2,
          activity=mol_CO2)
        H2aq = reaction.reagent('H2(aq)', self.env, phase='aq', conc=mol_H2,
          activity=mol_H2)
        CH4aq = reaction.reagent('Methane(aq)', self.env, phase='g', conc=mol_CH4,
          activity=mol_CH4)
        H2O = reaction.reagent('H2O(l)', self.env, phase='l', conc=uf(55.5, 0), activity=uf(H2Oact,0))
        el = reaction.reagent('e-', self.env, charge=-1)
        H = reaction.reagent('H+', self.env, charge=1, conc=mol_H,
          phase='aq', activity=mol_H)

        self.composition = {CO2.name:CO2, H2aq.name:H2aq,
          CH4aq.name:CH4aq, H2O.name:H2O, H.name:H}

        # overall
        r = {self.composition['CO2(aq)']:1, self.composition['H2(aq)']:4}
        p = {self.composition['Methane(aq)']:1, self.composition['H2O(l)']:2}
        thermaloa = reaction.reaction(r,p,self.env)

        # redox
        fr = {self.composition['CO2(aq)']:1, self.composition['H+']:8, el:8}
        fp = {self.composition['Methane(aq)']:1, self.composition['H2O(l)']:2}
        fwd = reaction.redox_half(fr, fp, self.env, 8, -0.244)

        rr = {self.composition['H+']:8, el:8}
        rp = {self.composition['H2(aq)']:4}

        # E ref: Karp, Gerald, Cell and Molecular Biology, 5th Ed., Wiley, 2008
        rvs = reaction.redox_half(rr, rp, self.env, 8, -0.421)

        # redox cell reaction is thermal overall
        rx = reaction.redox(fwd, rvs, thermaloa, 8, self.env)

        self.reactionlist = {thermaloa.equation:{type(thermaloa):thermaloa,
          type(rx):rx}}

        # add in CHNOPS, in elemental form for now
        # we already have C in the form of CO2 and CH4
        self.composition['NH3(aq)'] = reaction.reagent('NH3(aq)', self.env, phase='aq', conc=mol_NH3,
          activity=mol_NH3) # from Glein, Baross, Waite 2015
        # P and S we don't actually know.
        self.composition['P(aq)'] = reaction.reagent('P(aq)', self.env, phase='aq', conc=Pconc,
          activity=Pconc, thermo=False)
        self.composition['H2S(aq)'] = reaction.reagent('H2S(aq)', self.env, phase='aq', conc=mol_H2S,
          activity=mol_H2S, thermo=False)
Exemplo n.º 23
0
dip_indices = signal.find_peaks(-data['Voltage (uV)'], prominence=10)[0]
dips = data.iloc[dip_indices]

# Split dips into P and R bands
# This also resets the indices so we can use them as quantum number L later
p_band = dips[dips['Wavelength (nm)'] <= 3255].reset_index(drop=True)
r_band = dips[dips['Wavelength (nm)'] >= 3350].reset_index(drop=True)

# Find dv values and average, with error
p_diff = p_band.diff().abs()
r_diff = r_band.diff().abs()
p_mean = p_diff['Wavenumber (cm^-1)'].mean()
p_sem = p_diff['Wavenumber (cm^-1)'].sem()
r_mean = r_diff['Wavenumber (cm^-1)'].mean()
r_sem = r_diff['Wavenumber (cm^-1)'].sem()
p_mean = uf(p_mean, p_sem)
r_mean = uf(r_mean, r_sem)

# Find B from 2B=dv estimate
pb = p_mean / 2
rb = r_mean / 2
b_from_dv = (pb + rb) / 2
print('B estimated from dv in P band: {} cm^-1'.format(pb))
print('B estimated from dv in R band: {} cm^-1'.format(rb))
print('Average B estimate from dv: {} cm^-1'.format(b_from_dv))

# Find linear fits for trendlines
p_trend = linregress(p_band.index, p_band['Energy (J)'])
r_trend = linregress(r_band.index, r_band['Energy (J)'])
# Gradient m = +/-2hcB so ZB = +/- m/(2hc)
rt = abs(uf(r_trend.slope, r_trend.stderr) * (10 ** -2) / (2 * const.Planck * const.speed_of_light))
Exemplo n.º 24
0
from uncertainties import ufloat as uf
from math import pi, sqrt

# harmonic oscillator with original values
dt = uf(6.30, 0.01)*1e-3
w = 2*pi/dt
print("\nHarmonic oscillator with original values\n")
print("w0 = {}\n".format(w))

# harmonic oscillator with modified inverting gain
dt = uf(4.26, 0.01)*1e-3
w = 2*pi/dt
w_teo = 1e3*sqrt(2)
print("Harmonic oscillator with modified inverting gain")
print("R1 = 10k\t R2 = 22k\t w0 = {}\n".format(w))
print("Expected w = {}\n". format(w_teo))

# harmonic oscillator with different C
dt = uf(617e-6, 0.01e-6)
w = 2*pi/dt
print("w0 = {}\n".format(w))
Exemplo n.º 25
0
def main():

    # Set up command line switches
    parser = argparse.ArgumentParser(
        description='Weighted mean and error allowing for external noise',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog = textwrap.dedent(f'''\

        This is version {__version__}

        Reads a table of values with standard error estimates and calculates
        the weighted mean and error, allowing for the possibility that there
        is an additional source of uncertainty.

        The input table can be any format suitable for reading with the
        command astropy.table.Table.read(), e.g., CSV.
        
        By default, the calculation is done using columns 1 and 2 in the
        table. Use the flag --val_col and --err_col to specify alternative
        column names or numbers.

        If --val_col is used and --err-col is not specified, the program will ..
         - use the column val_col+1 if val_col is an integer
         - look for a column named "e_"+val_col
         - look for a column named val_col+"_err"
         - give up...

        '''))

    parser.add_argument('table', nargs='?',
        help='Table of values and errors'
    )

    parser.add_argument('-f', '--format',
        help='Table format - passed to Table.read()'
    )

    parser.add_argument('-v', '--val_col', 
        default=1, 
        help='''Column with values
        (default: %(default)d)
        '''
    )

    parser.add_argument('-e', '--err_col', 
        default=None, 
        help='Column with errors'
    )

    parser.add_argument('-1', '--one_line',  
        action='store_const',
        dest='one_line',
        const=True,
        default=False,
        help='Output results on one line'
    )

    parser.add_argument('-p', '--precise', 
        action='store_const',
        dest='precise',
        const=True,
        default=False,
        help='More precise (but slower) calculation'
    )

    args = parser.parse_args()

    if args.table is None:
        parser.print_usage()
        exit(1)

    table = Table.read(args.table, format=args.format)

    try:
        val_col = int(args.val_col) - 1
        name = 'y'
    except ValueError:
        val_col = str(args.val_col)
        name = args.val_col
    y = table[val_col][:]

    if args.err_col is None:
        if isinstance(val_col, int):
            yerr = table[val_col+1][:]
        else:
            try:
                err_col = 'e_'+str(args.val_col)
                yerr = table[err_col][:]
            except KeyError:
                err_col = str(args.val_col)+'_err'
                yerr = table[err_col][:]
    else:
        yerr = table[args.err_col][:]


    if args.precise:
        nw, ns, nb, sf = 128, 1500, 500, 2
    else:
        nw, ns, nb, sf = 64, 150, 50, 1

    mu, e_mu, sig, e_sig, sampler = combine(y, yerr, 
            walkers=nw, steps=ns, discard=nb)

    if not args.one_line:
        n = len(y)
        print (f'\nRead {n} values from {args.table}')
        print (up(uf(y.max(), yerr[np.argmax(y)]),
            f'Maximum value of {name}', sf=sf))
        print (up(uf(y.min(), yerr[np.argmin(y)]),
            f'Minimum value of {name}', sf=sf))

        wt = 1/yerr**2
        wsum = wt.sum()
        wmean = (y*wt).sum()/wsum
        chisq = ((y-wmean)**2*wt).sum()
        e_int = np.sqrt(1/wsum)
        e_ext = np.sqrt(chisq/(n-1)/wsum)
        print(f' Weighted mean = {wmean:0.4f}')
        print (up(uf(wmean, e_int),f'{name}', sf=sf), '(Internal error)')
        print (up(uf(wmean, e_ext),f'{name}', sf=sf), '(External error)')
        print(f' Chi-square = {chisq:0.2f}')

        p = 1-gammainc(0.5*(n-1),0.5*chisq)
        print(f' P(chi-sq. > observed chi-sq. if mean is constant) = {p:0.2}')
        print ("--")
    
    print(up(uf(mu,e_mu), name, sf=sf) + '; ' +
            up(uf(sig, e_sig),'sigma_ext', sf=sf))
Exemplo n.º 26
0
def mean_error(arr):
    mean = arr.mean()
    std = arr.std(ddof=1)
    meandev = std / len(arr)
    error = (meandev**2 + 0.1**2)**(1 / 2)
    return mean, error


v1_x1_mean, v1_x1_error = mean_error(vrstva1["x1"])
v1_x2_mean, v1_x2_error = mean_error(vrstva1["x2"].dropna())
v2_x1_mean, v2_x1_error = mean_error(vrstva2["x1"])
v2_x2_mean, v2_x2_error = mean_error(vrstva2["x2"].dropna())

from uncertainties import ufloat as uf
t1 = (
    uf(v1_x1_mean, v1_x1_error) / uf(v1_x2_mean, v1_x2_error)
) * (
    LAMBDA / 2
)
t2 = (
    uf(v2_x1_mean, v2_x1_error) / uf(v2_x2_mean, v2_x2_error)
) * (
    LAMBDA / 2
)

# ----- ÚKOL 2 ----- #

newton = dataframe_from_csv("../data/newton.csv")
newton = newton * 1e-6

Exemplo n.º 27
0
    ax.set_xlabel(r"$U_F [\si{V}]$")
    ax.set_ylabel(r"$I_F [\si{A}]$")

    ax.legend()
    fig.tight_layout()

    if show:
        plt.show()
    if save:
        plt.savefig("../plot/red.pdf")

    return fit.params, fit.errors


param_red_VA, err_red_VA = plot_red_VA_char()
R_d_red = 1 / uf(param_red_VA[0], err_red_VA[0])
U_star_red = uf(param_red_VA[1], err_red_VA[1]) / \
    uf(param_red_VA[0], err_red_VA[0])


def plot_blue_VA_char(show=False, save=False):
    fig = plt.figure()
    ax = fig.add_subplot(111)

    lin_start = 60
    fit = FitCurve(f_line, blue["U_F"][lin_start:], blue["I_F"][lin_start:])

    ax.plot(blue["U_F"],
            blue["I_F"],
            "k+",
            ms=3,
# make a reactor object
rtr = Enceladus('EncT')
# make an organism, for this example, use the preset methanogen.
org = TOM(rtr)
# org.dry_mass=29e-18 # set volume to 1 cubic micron.

TE = nm.apps_theory_estimates(org, rtr)
Tijhuis, TijhuisAerobe, TijhuisAnaerobe = [], [], []
Lever10pc, Lever2pc, Lever1AA = [], [], []  # in-built energy
Lever10pc_ces, Lever2pc_ces, Lever1AA_ces = [], [], []  # constant energy

for i, T in enumerate(Ts):
    TE.loc.change_T(T)
    TE.org.get_ESynth(AA=True)  # update the synthesis energy
    td = TE.temperature_defenses(T)
    Tijhuis.append(uf(td['Tijhuis'], 0.29 * td['Tijhuis']))
    TijhuisAerobe.append(uf(td['TijhuisAerobe'], 0.41 * td['TijhuisAerobe']))
    TijhuisAnaerobe.append(
        uf(td['TijhuisAnaerobe'], 0.32 * td['TijhuisAnaerobe']))
    Lever1AA.append(td['Lever1/250'])
    Lever10pc.append(td['Lever10pc'])
    Lever2pc.append(td['Lever2pc'])
    print(T, TE.org.E_synth / (1000 * org.dry_mass),
          1.7e-11 * (org.dry_mass / 29e-18) / (1000 * org.dry_mass))
    TE.org.E_synth = 1.7e-11 * (org.dry_mass / 29e-18
                                )  # convert so dry mass matches this organism
    td = TE.temperature_defenses(T)
    Lever1AA_ces.append(td['Lever1/250'])
    Lever10pc_ces.append(td['Lever10pc'])
    Lever2pc_ces.append(td['Lever2pc'])
Exemplo n.º 29
0
sys.path.append(os.path.dirname(__file__))

import math
from NutMEG.environment import *
from NutMEG.reactor import reactor
import NutMEG.reaction as reaction
from itertools import chain

from uncertainties import ufloat as uf
import uncertainties.umath as umath
import numpy as np
from scipy import interpolate



Waite2017ratios = {'CO2': uf(0.55, 0.25), 'CH4': uf(0.2, 0.1), 'NH3': uf(0.85, 0.45), 'H2': uf(0.9,0.5), 'H2S':uf(0.0021,0.001)}

class Enceladus(reactor):

    """
    The chemically active evirionment of the Enceladean ocean.
    It has a few unique attributes, and at the moment does not take
    kwargs for reactors. This may be added in the future when the
    NutMEG is a little more flexible.

    This is a saved instance of reactor, which contains the
    methanogenesis and environmental data for the moon. Initial composition
    can be estimated using mixing ratios from Waite et al. (2017) or
    user-specified ones. Concentration of CO2 and pH can be estimated at
    elevated temperatures using data from Higgins et al. (2021).
Exemplo n.º 30
0
from uncertainties import ufloat as uf
import math 

# units
mev = 1.
gev = 1e3 * mev
ev  = 1e-6 * mev
s  = 1. / ( 6.582119569e-16 * ev )
ps = 1e-12 * s

# constants
GF = uf(1.16673787,0.0000006)*1e-5 / (gev**2) #Fermi's constant
m_t = uf(1776.86,0.12)*mev
m_mu = uf(105.6583745,0.0000024)*mev
m_e = uf(0.5109989461,0.0000000031)*mev

br_tau2mu = uf(0.1739,0.0004)
br_tau2e  = uf(0.1782,0.0004)

def BR_P2LNU(m_p, f_p, t_p, vckm, m_l = m_t):
    f0 = GF**2 * m_p * m_l**2 / ( 8. * math.pi )
    f1 = ( 1. - m_l**2 / m_p**2 )**2 * f_p**2 * vckm**2 * t_p
    return f0*f1

# some examples
m_bc = uf(6274.9,0.8)*mev
t_bc = uf(0.510,0.009)*ps
v_cb = uf(0.0412,0.0009)
f_bc = uf(434.,15.)*mev

br_bc2taunu = BR_P2LNU(m_bc, f_bc, t_bc, v_cb)