Beispiel #1
0
def calculate_cbase(pH, pCO2, ctHb=3):
    """Calculate base excess.

    Calculate standard base excess, known as SBE, cBase(Ecf) or
    actual base excess, known as ABE, cBase(B) if ctHb is given.


    References
    ----------
    [1] Radiometer ABL800 Flex Reference Manual English US.
        chapter 6-29, p. 265, equation 5.

    [2] Siggaard-Andersen O. The acid-base status of the blood.
        4th revised ed. Copenhagen: Munksgaard, 1976.
        http://www.cabdirect.org/abstracts/19751427824.html

    :param float pH:
    :param float pCO2: kPa
    :param float ctHb: Concentration of total hemoglobin in blood, mmol/L
        If given, calculates ABE, if not - SBE.
    :return: Standard base excess (SBE) or actual base excess (ABE), mEq/L.
    :rtype: float
    """
    a = 4.04 * 10**-3 + 4.25 * 10**-4 * ctHb
    pHHb = 4.06 * 10**-2 * ctHb + 5.98 - 1.92 * 10**(-0.16169 * ctHb)
    log_pCO2Hb = -1.7674 * (10**
                            -2) * ctHb + 3.4046 + 2.12 * 10**(-0.15158 * ctHb)
    pHst = pH + math.log10(5.33 / pCO2) * (
        (pHHb - pH) / (log_pCO2Hb - math.log10(7.5006 * pCO2)))
    cHCO3_533 = 0.23 * 5.33 * 10**((pHst - 6.161) / 0.9524)
    # There is no comments, as there is no place for weak man
    cBase = 0.5 * ((8 * a - 0.919) / a) + 0.5 * math.sqrt(((
        (0.919 - 8 * a) / a)**2) - 4 * ((24.47 - cHCO3_533) / a))
    return cBase
Beispiel #2
0
 def get_tigerstripe_CO2(self, logform=False):
     """
     Return the CO2 activity as estimated by the tiger stripe temperature.
     (Glein and Waite 2020)
     """
     if logform:
         return umath.log10(self.mixingratios['CO2']/100)+9.429-(2574/self.tigerstripeT)
     else:
         return umath.pow(10, (umath.log10(self.mixingratios['CO2']/100)+9.429-(2574/self.tigerstripeT)))
Beispiel #3
0
def calculate_hco3p(pH, pCO2):
    """Calculate actual bicarbonate aka cHCO3(P) concentration in plasma.

    Also known as cHCO3(P), HCO3act [1].

    Sophisticated calculation by [1]. Good for water solutions,
    lower precision in lipemia cases.


    References
    ----------
    [1] Radiometer ABL800 Flex Reference Manual English US.
        chapter 6-28, p. 264, equation 4.
    [2] Siggaard-Andersen O, Wimberley PD, Fogh-Andersen N, Gøthgen IH.
        Measured and derived quantities with modern pH and blood gas equipment:
        calculation algorithms with 54 equations. Scand J Clin Lab Invest 1988;
        48, Suppl 189: 7-15. p. 11, equations 6, 7.

    :param float pH:
    :param float pCO2: kPa
    :return: cHCO3(P), mmol/L.
    :rtype: float
    """
    pKp = 6.125 - math.log10(1 + 10**(pH - 8.7))  # Dissociation constant
    # aCO2(P) solubility coefficient for 37 °C = 0.230 mmol/L/kPa
    return 0.230 * pCO2 * 10**(pH - pKp)
Beispiel #4
0
def Mgas(mgas, z, dmgas=0, dz=0, radius='500c', scaling='okabe10'):
    """
    Estiamte the mass from the gas mass, generally estimated through X-ray
    observations. Input units are Msun.

    Available scalings:
        Okabe et al. (2010, ApJ, 721, 875) -- Assuming self-similar slope
        Mahdavi et al. (2012, arXiv)

    """

    if dmgas > 0:
        mgas = ufloat((mgas, dmgas))
    if dz > 0:
        z = ufloat((z, dz))

    if scaling == 'okabe10':
        if radius == '500c':
            A = umath.log10(ufloat((13.10, 0.77)))
            #B = ufloat((1.00, 0.15))
            B = 1
    elif scaling == 'mahdavi12':
        if radius == '500c':
            A = ufloat((0.90, 0.02))
            B = ufloat((1.04, 0.10))

    m = 10 ** A * mgas ** B
    return m.nominal_value, m.std_dev()
Beispiel #5
0
def calculate_hco3p(pH, pCO2):
    """Concentration of HCO3 in plasma (actual bicarbonate).

    May be known as HCO3act, cHCO3(P)) [1].

    Sophisticated calculation by [1]. Good for water solutions,
    lower precision in lipemia cases.


    References
    ----------

    [1] Radiometer ABL800 Flex Reference Manual English US.
        chapter 6-28, p. 264, equation 4.
    [2] Siggaard-Andersen O, Wimberley PD, Fogh-Andersen N, Gøthgen IH.
        Measured and derived quantities with modern pH and blood gas equipment:
        calculation algorithms with 54 equations. Scand J Clin Lab Invest 1988;
        48, Suppl 189: 7-15. p. 11, equations 6, 7.

    :param float pH:
    :param float pCO2: kPa
    :return:
        cHCO3(P) mmol/L.
    :rtype: float
    """
    pKp = 6.125 - math.log10(1 + 10 ** (pH - 8.7))  # Dissociation constant
    # 1 mmHg = 0.133322368 kPa
    # aCO2(P) solubility coefficient for 37 °С = 0.230 mmol/L/kPa
    # pCO2 *= 0.133322368  # mmHg to kPa
    return 0.230 * pCO2 * 10 ** (pH - pKp)
def convertTo12logScale(df, objRef, variable, ext):

        value_natural = df.loc[objRef, variable + ext]

        if not umath.isnan(value_natural):
                if ('HeII' not in variable) and ('Ymass' not in variable) and ('ICF' not in variable):
                        value_log12 = 12.0 + umath.log10(value_natural)
                        newFormat = [value_log12.nominal_value, value_log12.std_dev]
                else:
                        newFormat = [value_natural.nominal_value, value_natural.std_dev]
        else:
                newFormat = [None, None]

        return newFormat
Beispiel #7
0
def calculate_cbase(pH, pCO2, ctHb=3):
    """Calculate base excess.

    Calculate standard base excess, known as SBE, cBase(Ecf) or
    actual base excess known as ABE, cBase(B).


    References
    ----------

    [1] Radiometer ABL800 Flex Reference Manual English US.
        chapter 6-29, p. 265, equation 5.

    [2] Siggaard-Andersen O. The acid-base status of the blood.
        4th revised ed. Copenhagen: Munksgaard, 1976.
        http://www.cabdirect.org/abstracts/19751427824.html

    :param float pH:
    :param float pCO2: kPa
    :param float ctHb: Concentration of total hemoglobin in blood, mmol/L
        If not given, calculate cBase(Ecf), otherwise cBase(B).
    :return:
        Standard base excess (SBE) or actual base excess (ABE), mEq/L.
    :rtype: float
    """
    # pCO2 *= 0.133322368  # mmHg to kPa
    a = 4.04 * 10 ** -3 + 4.25 * 10 ** -4 * ctHb
    pHHb = 4.06 * 10 ** -2 * ctHb + 5.98 - 1.92 * 10 ** (-0.16169 * ctHb)
    log_pCO2Hb = -1.7674 * (10 ** -2) * ctHb + 3.4046 + 2.12 * 10 ** (
        -0.15158 * ctHb)
    pHst = pH + math.log10(5.33 / pCO2) * (
        (pHHb - pH) / (log_pCO2Hb - math.log10(7.5006 * pCO2)))
    cHCO3_533 = 0.23 * 5.33 * 10 ** ((pHst - 6.161) / 0.9524)
    # There is no comments, as there is no place for weak man
    cBase = 0.5 * ((8 * a - 0.919) / a) + 0.5 * math.sqrt(
        (((0.919 - 8 * a) / a) ** 2) - 4 * ((24.47 - cHCO3_533) / a))
    return cBase
Beispiel #8
0
def fo2_cal_single(P,T,PV,r,method='earth',flag=False,fit='fit3'):
    """
    calculate fo2 for a single P,T point
    P : pressure, GPa, P is actually not used, it is included in PV integration info
    T : temperature, K
    PV : term int\{P0 to P0, deltaV}, it requires to get the dV at every single pressure
         and temperature, and then integrate. This could be very time demanding.
    r : Fe3/Fe2 ratio
    method : earth, mars, moon, specify the composition, default is earth
    flag : boolean, uncertainty flag, default is False
    fit3 : W model, default is fit3
    
    Note
    ----

    
    Term int\{P0 to P0, deltaV}, deltaV is at reference temperature, not along geotherm.
    That means, to calcualte this term, for every point in geotherm, P,T, one needs to
    calculate the dV from P0 to P along T, and then integrate.
    Note this is different from just calculate dV along the goetherm, then integrate.
    
    Typically, the 2nd method will underestimate the PV term since goetherm is T0 to T,
    whereas here we need keep T as T.
 
     Nevertheless,  `cal_PV_geo` function in the package solve this problem. The obtained
     PV term along the geotherm is then used as input and kept in the excel eos.xlsx
    """
    
    Fe2 = (1-r)*planets.loc[method]['FeO']
    Fe3 = r*planets.loc[method]['FeO']
    Si = planets.loc[method]['SiO2'];
    Mg = planets.loc[method]['MgO'];
    Al = planets.loc[method]['Al2O3'];
    Ca = planets.loc[method]['CaO'];
    K  = planets.loc[method]['K2O'];
    Na = planets.loc[method]['Na2O'];
    Ph = planets.loc[method]['P2O5'];
    Ti = planets.loc[method]['TiO2'];
    
    a,b,W_Fe,W_Mg,W_Si,W_Al,W_Ca,W_Na,W_K,W_Ph,W_Ti = unpack_par(W.loc[fit],flag)
    
    Gterm = np.array(tl.Gr_janaf(T,flag))/R/T
    Wterm = (W_Fe*(Fe2 - Fe3) + W_Mg*Mg + W_Al*Al + W_Si*Si +
             W_Ca*Ca +W_Na*Na + W_K*K + W_Ph*Ph + W_Ti*Ti)/R/T
    tmp   = (PV + Gterm + Wterm)*4
    lnXfe3_Xfe2 = np.log(Fe3/Fe2)*4
    fg = umath.exp(tmp+lnXfe3_Xfe2)
    log10fg = (umath.log10(fg))
    return log10fg
Beispiel #9
0
def candid_grid(input_data,
                step=10,
                rmin=20,
                rmax=400,
                diam=0,
                obs=['cp', 'v2'],
                extra_error_cp=0,
                err_scale=1,
                extra_error_v2=0,
                instruments=None,
                doNotFit=[
                    'diam*',
                ],
                ncore=1,
                verbose=False):
    """ This function is an user friendly interface between the users of amical
    pipeline and the CANDID analysis package (https://github.com/amerand/CANDID).

    Parameters:
    -----------
    `input_data` {str or list}:
        oifits file names or list of oifits files,\n
    `step` {int}:
        step used to compute the binary grid positions,\n
    `rmin`, `rmax` {float}:
        Bounds of the grid [mas],\n
    `diam` {float}:
        Stellar diameter of the primary star [mas] (default=0),\n
    `obs` {list}:
        List of observables to be fitted (default: ['cp', 'v2']),\n
    `doNotFit` {list}:
        Parameters not fitted (default: ['diam*']),\n
    `verbose` {boolean}:
        print some informations {default: False}.

    Outputs:
    --------
    `res` {dict}:
        Dictionnary of the results ('best'), uncertainties ('uncer'),
        reduced chi2 ('chi2') and sigma detection ('nsigma').
    """

    cprint(' | --- Start CANDID fitting --- :', 'green')
    o = candid.Open(input_data,
                    extra_error=extra_error_cp,
                    err_scale=err_scale,
                    extra_error_v2=extra_error_v2,
                    instruments=instruments)

    o.observables = obs

    o.fitMap(rmax=rmax,
             rmin=rmin,
             ncore=ncore,
             fig=0,
             step=step,
             addParam={"diam*": diam},
             doNotFit=doNotFit,
             verbose=verbose)

    fit = o.bestFit["best"]
    e_fit = o.bestFit["uncer"]
    chi2 = o.bestFit['chi2']
    nsigma = o.bestFit['nsigma']

    f = fit["f"] / 100.0
    e_f = e_fit["f"] / 100.0
    if (e_f < 0) or (e_fit["x"] < 0) or (e_fit["y"] < 0):
        print('Warning: error dm is negative.')
        e_f = abs(e_f)
        e_fit["x"] = 0
        e_fit["y"] = 0

    f_u = ufloat(f, e_f)
    x, y = fit["x"], fit["y"]
    x_u = ufloat(x, e_fit["x"])
    y_u = ufloat(y, e_fit["y"])

    dm = -2.5 * umath.log10(f_u)
    s = (x_u**2 + y_u**2)**0.5
    posang = ((umath.atan2(x_u, y_u) * 180 / np.pi))
    if posang.nominal_value < 0:
        posang = 360 + posang

    cr = 1 / f_u
    cprint("\nResults binary fit (χ2 = %2.1f, nσ = %2.1f):" % (chi2, nsigma),
           "cyan")
    cprint("-------------------", "cyan")

    print("Sep = %2.1f +/- %2.1f mas" % (s.nominal_value, s.std_dev))
    print("Theta = %2.1f +/- %2.1f deg" %
          (posang.nominal_value, posang.std_dev))
    print("CR = %2.1f +/- %2.1f" % (cr.nominal_value, cr.std_dev))
    print("dm = %2.2f +/- %2.2f" % (dm.nominal_value, dm.std_dev))
    res = {
        'best': {
            'model': 'binary_res',
            'dm': dm.nominal_value,
            'theta': posang.nominal_value,
            'sep': s.nominal_value,
            'diam': fit["diam*"],
            'x0': 0,
            'y0': 0
        },
        'uncer': {
            'dm': dm.std_dev,
            'theta': posang.std_dev,
            'sep': s.std_dev
        },
        'chi2': chi2,
        'nsigma': nsigma,
        'comp': o.bestFit["best"]
    }

    return res
replicate_measurements = pd.DataFrame()

# Estimate the uncertainty from technical replicates of the same experiments.
# This is done by averaging over multiple injections of the same solution and calculating the standard deviation.
for (compound, dset, repeat, solv), df_exp in table.groupby([
        "Sample Name",
        "Set",
        "Repeat",
        "Solvent",
]):
    mean = df_exp["Area/Volume"].mean()
    # Multiply by sqrt(3) since replicate measurements not independent
    uncertainty = df_exp["Area/Volume"].std() * math.sqrt(3.0)

    # Store the log base 10 of the measurement.
    measurement = log10(ufloat(mean, uncertainty, tag="replicate"))
    replicate_measurements = replicate_measurements.append(
        {
            "Compound": compound,
            "Solvent": solv,
            "Log10 Area/Volume (Uncertainty)": measurement,
            "Experiment": "{}-{}".format(dset, repeat)
        },
        ignore_index=True)

# Log D estimates are tabulated in a new dataframe.
experiments = pd.DataFrame()

# Calculate the log D of each individual repeat experiment
for (compound, measurement), estimates in replicate_measurements.groupby(
    ["Compound", "Experiment"]):
    try:
        popt, pcov = curve_fit(Brune, freq, spec, bounds=((0,0), (100., 1000.)))
    except RuntimeError:
        print "Cannot converge on an answer for event: " + event[i]
        error +=1
        continue
        
    fc_fit, omega0_fit = popt
    fc_std, omega0_std = np.sqrt(np.diag(pcov))
    
    fc = ufloat(fc_fit, fc_std)
    omega0 = ufloat(omega0_fit, omega0_std)
    
    M0 = (omega0*4.*np.pi*rho*beta**3.)/U
    stressdrop = ((fc/beta)**3.)*(8.47*M0)
    stressdrop_log = umath.log10(stressdrop/1e6)

#    print stressdrop/1e6
    
#    stressdropup = (((fc_fit+fc_std)/beta)**3.)*(8.47*M0)
#    stressdroplb = 
    
    M = (2./3.)*(umath.log10(M0) - 9.05)
    if M > 3:
        ml = M
    else:
        ml = (M - 0.884)/.667
    

    s.append(stressdrop_log.nominal_value)
    s_w.append(1./stressdrop_log.std_dev**2)
def table_key_format(key, Ratios_dict):

    #Treatment for the line ratios
    if key in ['O3_ratio', 'N2_ratio', 'S3_ratio']:
        
        value                       = pv.format_for_table(Ratios_dict[key])
        
        if value != None:
            color                   = RatiosColor_dict[key]
            formated_abundance      = pv.format_for_table(value)
            formated_abundance      = r'\textcolor{' + color + '}{' + formated_abundance + '}'
        else:
            formated_abundance  = None
     
    #Treatment for the physical conditions
    elif key in ['TOIII', 'TOII', 'TSIII', 'TSII', 'nSII', 'cHBeta_stellar']:
        
        value                       = pv.GetParameter_ObjLog(CodeName, FileFolder, key, 'string', sigfig=5, strformat= '{:.2f}')
        
        if value != None:
            formated_abundance      = pv.format_for_table(value)
        else:
            formated_abundance      = None
    
    #Treatment for metallic abundances
    elif key in ['OI_HI', 'NI_HI', 'SI_HI', 'SI_HI_ArCorr']:
        
        value                       = pv.GetParameter_ObjLog(CodeName, FileFolder, key, 'float')
        
        if value != None:
            abund_log               = 12 + umath.log10(value)
            formated_abundance      = pv.format_for_table(abund_log)
        else:
            formated_abundance      = None
    
    #Treatment for Helium abundances
    elif key in ['HeI_HI', 'HeII_HII', 'HeIII_HII', 'Y_Mass_O', 'Y_Inference_O', 'Y_Mass_S', 'Y_Inference_S']:
       
        value                       = pv.GetParameter_ObjLog(CodeName, FileFolder, key, 'float')

        if value != None:
            formated_abundance      = pv.format_for_table(value, 3)
        else:
            formated_abundance      = None
                
    #Treatment for the inference parameters
    elif key in ['y_plus_inf','Te_inf','ne_inf','cHbeta_inf','ftau_inf','Xi_inf']:
        
        value                       = pv.GetParameter_ObjLog(CodeName, FileFolder, key, 'float')
        

        
        if value != None:
            error_type              = key[0:key.find('_inf')] + '_SD'
            error                   = pv.GetParameter_ObjLog(CodeName, FileFolder, error_type, 'float')
            value                   = ufloat(value,error)
            color                   = pv.colorEvaluator(key, value, CodeName, FileFolder)                   
            formated_abundance      = pv.format_for_table(value, 3)
            formated_abundance      = r'\textcolor{' + color + '}{' + formated_abundance + '}'
        else:
            formated_abundance      = None   

    else:
        formated_abundance = 'NotFound'

    return formated_abundance
# c = a/b
# print(c)
# print(c.nominal_value, c.std_dev)

a_value = 10.50
b_value = 2.00
a_error = a_value * 0.02
b_error = b_value * 0.02

a = ufloat(a_value, a_value * 0.02)
b = ufloat(b_value, b_value * 0.02)

print(a)
print(b)

a_log = umath.log10(a)
b_log = umath.log10(b)

print(a_log)
print(b_log)
print('Umath: a ->', a_log.nominal_value, a_log.std_dev)
print('Umath: b ->', b_log.nominal_value, b_log.std_dev)

a_conv = umath.pow(10, a_log)
b_conv = umath.pow(10, b_log)

print(a_conv)
print(b_conv)

a_mine = [np.log10(a_value), np.log10(1.0 + (a_value * 0.02) / a_value)]
b_mine = [np.log10(b_value), np.log10(1.0 + (b_value * 0.02) / b_value)]
Beispiel #14
0
def candid_grid(
    input_data: Union[str, List[str]],
    step: int = 10,
    rmin: float = 20,
    rmax: float = 400,
    diam: float = 0,
    obs: Optional[List[str]] = None,
    extra_error_cp: float = 0,
    err_scale: float = 1,
    extra_error_v2: float = 0,
    instruments=None,
    doNotFit=None,
    ncore: int = 1,
    save: bool = False,
    outputfile: Optional[str] = None,
    verbose: bool = False,
):
    """This function is an user friendly interface between the users of amical
    pipeline and the CANDID analysis package (https://github.com/amerand/CANDID).

    Parameters:
    -----------
    `input_data`:
        oifits file names or list of oifits files,\n
    `step`:
        step used to compute the binary grid positions,\n
    `rmin`, `rmax`:
        Bounds of the grid [mas],\n
    `diam`:
        Stellar diameter of the primary star [mas] (default=0),\n
    `obs`:
        List of observables to be fitted (default: ['cp', 'v2']),\n
    `doNotFit`:
        Parameters not fitted (default: ['diam*']),\n
    `verbose`:
        print some informations {default: False}.

    Outputs:
    --------
    `res` {dict}:
        Dictionnary of the results ('best'), uncertainties ('uncer'),
        reduced chi2 ('chi2') and sigma detection ('nsigma').
    """
    if obs is None:
        obs = ["cp", "v2"]
    if doNotFit is None:
        doNotFit = ["diam*"]

    cprint(" | --- Start CANDID fitting --- :", "green")
    o = candid.Open(
        input_data,
        extra_error=extra_error_cp,
        err_scale=err_scale,
        extra_error_v2=extra_error_v2,
        instruments=instruments,
    )

    o.observables = obs

    o.fitMap(
        rmax=rmax,
        rmin=rmin,
        ncore=ncore,
        fig=0,
        step=step,
        addParam={"diam*": diam},
        doNotFit=doNotFit,
        verbose=verbose,
    )

    if save:
        if isinstance(input_data, list):
            first_input = input_data[0]
        else:
            first_input = input_data
        filename = os.path.basename(first_input) + "_detection_map_candid.pdf"
        if outputfile is not None:
            filename = outputfile
        plt.savefig(filename, dpi=300)

    fit = o.bestFit["best"]
    e_fit = o.bestFit["uncer"]
    chi2 = o.bestFit["chi2"]
    nsigma = o.bestFit["nsigma"]

    f = fit["f"] / 100.0
    e_f = e_fit["f"] / 100.0
    if (e_f < 0) or (e_fit["x"] < 0) or (e_fit["y"] < 0):
        print("Warning: error dm is negative.")
        e_f = abs(e_f)
        e_fit["x"] = 0
        e_fit["y"] = 0

    f_u = ufloat(f, e_f)
    x, y = fit["x"], fit["y"]
    x_u = ufloat(x, e_fit["x"])
    y_u = ufloat(y, e_fit["y"])

    dm = -2.5 * umath.log10(f_u)
    s = (x_u ** 2 + y_u ** 2) ** 0.5
    posang = umath.atan2(x_u, y_u) * 180 / np.pi
    if posang.nominal_value < 0:
        posang = 360 + posang

    cr = 1 / f_u
    cprint(f"\nResults binary fit (χ2 = {chi2:2.1f}, nσ = {nsigma:2.1f}):", "cyan")
    cprint("-------------------", "cyan")

    print(f"Sep = {s.nominal_value:2.1f} +/- {s.std_dev:2.1f} mas")
    print(f"Theta = {posang.nominal_value:2.1f} +/- {posang.std_dev:2.1f} deg")
    print(f"CR = {cr.nominal_value:2.1f} +/- {cr.std_dev:2.1f}")
    print(f"dm = {dm.nominal_value:2.2f} +/- {dm.std_dev:2.2f}")
    res = {
        "best": {
            "model": "binary_res",
            "dm": dm.nominal_value,
            "theta": posang.nominal_value,
            "sep": s.nominal_value,
            "diam": fit["diam*"],
            "x0": 0,
            "y0": 0,
        },
        "uncer": {"dm": dm.std_dev, "theta": posang.std_dev, "sep": s.std_dev},
        "chi2": chi2,
        "nsigma": nsigma,
        "comp": o.bestFit["best"],
    }

    return res
      ' dom error)')
df = pd.read_csv('/home/sean/Downloads/csv.download.csv')
cd, lcd = [], []

for name, core, total, tot_err, unresolved in zip(df['Name'],
                                                  df['Raw core calculation'],
                                                  df['Total_flux'],
                                                  df['E_Total_flux'],
                                                  df['Compact']):
    if unresolved:
        print(f'{name}, -, -, -, -')
        continue
    S_core = ufloat(core, core * (tot_err / total))
    S_int = ufloat(total, tot_err)
    core_dom = S_core / (S_int - S_core)
    log_core_dom = log10(core_dom)
    # print(S_core, S_int, core_dom)
    print(f'{name}, {core_dom.n}, {core_dom.s}, {log_core_dom.n},'
          f'{log_core_dom.s}')
    cd.append(core_dom)
    lcd.append(log_core_dom)

print(np.sum(cd) / len(cd))
print(np.sum(lcd) / len(lcd))
print(len(cd), len(lcd))
import sys
sys.exit()
def alpha(flux1, flux2, freq1=ufloat(144e6, 24e6),
          freq2=ufloat(1400e6, 0)):
    """Get spectral index with error. Default is LDR2 and FIRST.
    """
Beispiel #16
0
def calc_bpt_points(rp, plot_type='NII'):
    def get_SII_fluxes(fluxes, bptPoints):
        if 'SII-6717A' not in fluxes:
            xNumerator = fluxes['SII-6731A']
            bptPoints['SII_label'] = r"$\log(\mathrm{[SII]6731\AA / H\alpha})$"
        elif 'SII-6731A' not in fluxes:
            xNumerator = fluxes['SII-6717A']
            bptPoints['SII_label'] = r"$\log(\mathrm{[SII]6717\AA / H\alpha})$"
        else:
            xNumerator = sum_dict_values(fluxes['SII-6717A'],
                                         fluxes['SII-6731A'])
            bptPoints[
                'SII_label'] = r"$\log(\mathrm{([SII]6717\AA + [SII]6731\AA) / H\alpha})$"
        return xNumerator, bptPoints

    bptPoints = {}
    try:
        fluxes = get_bpt_fluxes(rp, plot_type)
    except (KeyError, ValueError):
        print("Ion not defined for BPT plot:", plot_type)
        bptPoints['global'] = {'x': 0, 'xErr': 0, 'y': 0, 'yErr': 0}
        return bptPoints

    if plot_type == 'NII':
        xNumerator = fluxes['NII-6584A']
        xDenominator = fluxes['H-Alpha']
        yNumerator = fluxes['OIII-5007A']
        yDenominator = fluxes['H-Beta']
    elif plot_type == 'SII':
        xNumerator, bptPoints = get_SII_fluxes(fluxes, bptPoints)
        xDenominator = fluxes['H-Alpha']
        yNumerator = fluxes['OIII-5007A']
        yDenominator = fluxes['H-Beta']
    elif plot_type == 'OI':
        xNumerator = fluxes['OI-6300A']
        xDenominator = fluxes['H-Alpha']
        yNumerator = fluxes['OIII-5007A']
        yDenominator = fluxes['H-Beta']
    elif plot_type == 'NIIvsSII':
        xNumerator, bptPoints = get_SII_fluxes(fluxes, bptPoints)
        xDenominator = fluxes['H-Alpha']
        yNumerator = fluxes['NII-6584A']
        yDenominator = fluxes['H-Alpha']
    else:
        warnings.warn(
            "Invalid BPT plot_type {}, using plot_type 'NII' instead.".format(
                plot_type))
        xNumerator = fluxes['NII-6584A']

    compList = ['global'] + list(fluxes['H-Alpha'].keys())
    for comp in compList:
        bptPoints[comp] = {}
        if xNumerator[comp] >= 0 and xDenominator[comp] >= 0 and yNumerator[
                comp] >= 0 and yDenominator[comp] >= 0:
            ratioX = umath.log10(xNumerator[comp] / xDenominator[comp])
            ratioY = umath.log10(yNumerator[comp] / yDenominator[comp])
            bptPoints[comp]['x'] = ratioX.nominal_value
            bptPoints[comp]['xErr'] = ratioX.std_dev
            bptPoints[comp]['y'] = ratioY.nominal_value
            bptPoints[comp]['yErr'] = ratioY.std_dev
        else:
            warnings.warn(
                "Cannot compute BPT diagram as some component fluxes are negative"
            )
            bptPoints[comp]['x'] = None
            bptPoints[comp]['xErr'] = None
            bptPoints[comp]['y'] = None
            bptPoints[comp]['yErr'] = None

    return bptPoints
pin532_1 = ufloat(1470, 20)
pin532_2 = ufloat(2800, 30)
pout532_1 = ufloat(156, 2)
pout532_2 = ufloat(320, 2)

l633_1 = ufloat(293.5, 0.5)
l633_2 = ufloat(289.2, 0.5)
l532_1 = ufloat(291.3, 0.5)
l532_2 = ufloat(287.1, 0.5)

lamb = [633, 532]
lamb_n = [850, 1300]
atten_n = [ufloat(4, 0.1), ufloat(1.5, 0.1)]
atten_1 = array([
    um.log10(pin633_1 / pout633_1) / l633_1,
    um.log10(pin532_1 / pout532_1) / l532_1
]) * 10000
atten_2 = array([
    um.log10(pin633_2 / pout633_2) / l633_2,
    um.log10(pin532_2 / pout532_2) / l532_2
]) * 10000
print('attenuazione1 532 = %s' % xe(atten_1[1].n, atten_1[1].s))
print('attenuazione2 532 = %s' % xe(atten_2[1].n, atten_2[1].s))
print('attenuazione1 633 = %s' % xe(atten_1[0].n, atten_1[0].s))
print('attenuazione2 633 = %s' % xe(atten_2[0].n, atten_2[0].s))

sigma633 = std(array([
    atten_1[0].n,
    atten_2[0].n,
]), ddof=1)
def table_key_format(key, Ratios_dict):

    #Treatment for the line ratios
    if key in ['O3_ratio', 'N2_ratio', 'S3_ratio']:

        value = pv.format_for_table(Ratios_dict[key])

        if value != None:
            color = RatiosColor_dict[key]
            formated_abundance = pv.format_for_table(value)
            formated_abundance = r'\textcolor{' + color + '}{' + formated_abundance + '}'
        else:
            formated_abundance = None

    #Treatment for the physical conditions
    elif key in ['TOIII', 'TOII', 'TSIII', 'TSII', 'nSII', 'cHBeta_stellar']:

        value = pv.GetParameter_ObjLog(CodeName,
                                       FileFolder,
                                       key,
                                       'string',
                                       sigfig=5,
                                       strformat='{:.2f}')

        if value != None:
            formated_abundance = pv.format_for_table(value)
        else:
            formated_abundance = None

    #Treatment for metallic abundances
    elif key in ['OI_HI', 'NI_HI', 'SI_HI', 'SI_HI_ArCorr']:

        value = pv.GetParameter_ObjLog(CodeName, FileFolder, key, 'float')

        if value != None:
            abund_log = 12 + umath.log10(value)
            formated_abundance = pv.format_for_table(abund_log)
        else:
            formated_abundance = None

    #Treatment for Helium abundances
    elif key in [
            'HeI_HI', 'HeII_HII', 'HeIII_HII', 'Y_Mass_O', 'Y_Inference_O',
            'Y_Mass_S', 'Y_Inference_S'
    ]:

        value = pv.GetParameter_ObjLog(CodeName, FileFolder, key, 'float')

        if value != None:
            formated_abundance = pv.format_for_table(value, 3)
        else:
            formated_abundance = None

    #Treatment for the inference parameters
    elif key in [
            'y_plus_inf', 'Te_inf', 'ne_inf', 'cHbeta_inf', 'ftau_inf',
            'Xi_inf'
    ]:

        value = pv.GetParameter_ObjLog(CodeName, FileFolder, key, 'float')

        if value != None:
            error_type = key[0:key.find('_inf')] + '_SD'
            error = pv.GetParameter_ObjLog(CodeName, FileFolder, error_type,
                                           'float')
            value = ufloat(value, error)
            color = pv.colorEvaluator(key, value, CodeName, FileFolder)
            formated_abundance = pv.format_for_table(value, 3)
            formated_abundance = r'\textcolor{' + color + '}{' + formated_abundance + '}'
        else:
            formated_abundance = None

    else:
        formated_abundance = 'NotFound'

    return formated_abundance
# Final output file
output = open("logD_final.txt", "w")

# Store results in new dataframe
replicate_measurements = pd.DataFrame()

# Estimate the uncertainty from technical replicates of the same experiments.
# This is done by averaging over multiple injections of the same solution and calculating the standard deviation.
for (compound, dset, repeat, solv), df_exp in table.groupby(["Sample Name", "Set", "Repeat", "Solvent"]):
    mean = df_exp["Area/Volume"].mean()
    # Multiply by sqrt(3) since replicate measurements not independent
    uncertainty = df_exp["Area/Volume"].std() * math.sqrt(3.0)

    # Store the log base 10 of the measurement.
    measurement = log10(ufloat(mean, uncertainty, tag="replicate"))
    replicate_measurements = replicate_measurements.append(
        {
            "Compound": compound,
            "Solvent": solv,
            "Log10 Area/Volume (Uncertainty)": measurement,
            "Experiment": "{}-{}".format(dset, repeat),
        },
        ignore_index=True,
    )

# Log D estimates are tabulated in a new dataframe.
experiments = pd.DataFrame()

# Calculate the log D of each individual repeat experiment
for (compound, measurement), estimates in replicate_measurements.groupby(["Compound", "Experiment"]):