예제 #1
0
    def genEmisGrid(self, linesList, teRange, neRange):

        # Hbeta data
        H1 = pn.RecAtom('H', 1)
        HBeta = H1.getEmissivity(teRange, neRange, wave=4861, product=False)

        # Generate the emissivity grids for all the ions
        emis_dict = {'HBeta': HBeta}

        # Loop through the lines list:
        for i in range(len(linesList)):

            element, ionization, wave = linesList[i][0][:-1], linesList[i][0][
                -1], linesList[i][1]
            line_label = '{}{}_{}A'.format(element, ionization, wave)
            if element in ['H', 'He']:
                ion = pn.RecAtom(element, ionization)
                if element == 'H':
                    emis_dict[line_label] = ion.getEmissivity(
                        teRange, neRange, wave=wave, product=False) / HBeta
                if element == 'He':
                    emis_dict[line_label] = ion.getEmissivity(
                        teRange, neRange, wave=wave, product=False) / HBeta

            else:
                ion = pn.Atom(element, ionization)
                emis_dict[line_label] = np.log10(
                    ion.getEmissivity(
                        teRange, neRange, wave=wave, product=False) / HBeta)

        return emis_dict
예제 #2
0
def test_line_labels():
    """
    This tool scans all the lines from pn.LINE_LABEL_LIST, extract the wavelength and compare with the 
    wavelength given by the corresponding atom for the corresponding transition. Is the difference is greater 
    than 1AA for optical or 0.1mu for IR, it prints the information
    """
    for atom_str in pn.LINE_LABEL_LIST:
        try:
            if atom_str[0] == '3':
                atom = None
            elif atom_str[-1] == 'r':
                atom = pn.RecAtom(atom=atom_str)
            else:
                atom = pn.Atom(atom=atom_str)
        except:
            atom = None
        if atom is not None:
            if atom.NLevels != 0:
                for line in pn.LINE_LABEL_LIST[atom_str]:
                    if line[-1] == 'm':
                        wavelength = float(line[:-1]) * 1e4
                    else:
                        wavelength = float(line[:-1])
                    i, j = atom.getTransition(wavelength)
                    wave = atom.wave_Ang[i - 1, j - 1]
                    if wave < 1e4:
                        dif = np.abs(wavelength - wave)
                    else:
                        dif = np.abs(wavelength - wave) / 1e3
                    if dif > 1.0:
                        print(atom, line)
                        assert dif < 1.0
예제 #3
0
파일: orl.py 프로젝트: bbergerud/Nebularium
    def __init__(self, atom, ion, wave_label):

        if not isinstance(wave_label, tuple):
            if isinstance(wave_label, list):
                wave_label = tuple(wave_label)
            else:
                wave_label = tuple([wave_label])

        self.wave = wave_label
        self.atom = pn.RecAtom(atom, ion)
예제 #4
0
def test_HbEmissivity(max_error=5e-4):
    H1 = pn.RecAtom('H', 1)
    tem = np.array([.5, 1, 1.5, 2., 3.]) * 1e4
    den = 1e2
    Hb_expected = np.array([2.2e-25, 1.235e-25, 8.6e-26, 6.58e-26, 4.440e-26])
    Hb_computed = H1.getEmissivity(tem, den, label='4_2')
    for i in range(len(tem)):
        assert (rel_error(H1.getEmissivity(tem[i], den, label='4_2'),
                          Hb_expected[i]) < max_error)
        assert (rel_error((Hb_computed[i]), Hb_expected[i]) < max_error)
예제 #5
0
 def addDiagsFromObs(self, obs):
     """
     Add all the possible diagnostics that can be computed from an Observation object
     
     Usage:
         diags.addDiagsFromObs(obs)
         
     Parameter:
         obs     an Observation object
     """
     
     if not isinstance(obs, pn.Observation):
         pn.log_.error('The argument must be an Observation object', calling=self.calling + 'addDiagsFromObs')
     old_level = pn.log_.level
     def I(i, j):
         wave = atom.wave_Ang[i - 1, j - 1]
         corrIntens = obs.getLine(sym, spec, wave).corrIntens
         return corrIntens
     def L(wave):
         corrIntens = obs.getLine(sym, spec, wave).corrIntens
         return corrIntens
     def B(label):
         full_label = atom + '_' + label
         corrIntens = obs.getLine(label=full_label).corrIntens
         return corrIntens
     def S(label):
         full_label = atom + '_' + label + 'A'
         corrIntens = obs.getLine(label=full_label).corrIntens
         return corrIntens
         
     for label in diags_dict:
         atom, diag_expression, error = diags_dict[label]
         sym, spec, rec = parseAtom2(atom)
         if label == '[OII] 3727+/7325+c':
             try:
                 diag_value = eval(diag_expression)
             except Exception as ex:
                 pn.log_.level = old_level
                 pn.log_.debug('Diag not valid {} {}'.format(label, diag_expression))
         try:
             pn.log_.level = 1
             diag_value = eval(diag_expression)
             pn.log_.level = old_level
             if atom not in self.atomDict:
                 if rec == 'r':
                     self.atomDict[atom] = pn.RecAtom(atom=sym+spec)
                 else:
                     self.atomDict[atom] = pn.Atom(atom=atom, NLevels=self.NLevels)
             self.addDiag(label)
         except Exception as ex:
             pn.log_.level = old_level
             pn.log_.debug('Diag not valid {} {}'.format(label, diag_expression))
예제 #6
0
def interp_caseb(flux_Hb, flux_Hg, line):

    temp = np.logspace(np.log10(500.), np.log10(30000.), 10000)[1:-1]
    den = 10.

    H1 = pn.RecAtom('H', 1)
    model_Hb = H1.getEmissivity(temp, den, 4, 2)
    model_Hg = H1.getEmissivity(temp, den, 5, 2)

    if line == 'Hd':
        model_line = H1.getEmissivity(temp, den, 6, 2)
    elif line == 'He':
        model_line = H1.getEmissivity(temp, den, 7, 2)
    else:
        raise Exception

    flux_HgHb = flux_Hg / flux_Hb
    model_HgHb = model_Hg / model_Hb
    model_lineHb = model_line / model_Hb
    flux_lineHb = np.interp(flux_HgHb, model_HgHb, model_lineHb)
    flux_line = flux_lineHb * flux_Hb

    return flux_line
'He1_4388A':dz.colorVector['skin'],
'He1_4438A':dz.colorVector['cyan'],
'He1_4472A':dz.colorVector['olive'],
'He1_4713A':dz.colorVector['green'],
'He1_4922A':dz.colorVector['iron'],
'He1_5016A':dz.colorVector['yellow'],
'He1_5876A':dz.colorVector['orangish'],
'He1_6678A':dz.colorVector['dark blue'],
'He1_7065A':'black',
'He1_7281A':'#CC79A7'}

#Atomic dictionaries
pn.atomicData.setDataFile('s_iii_coll_HRS12.dat')
O3 = pn.Atom('O', 3)
S3 = pn.Atom('S', 3)
N2 = pn.Atom('N', 2)
He1 = pn.RecAtom('He', 1)

S3_9000_ratio = S3.getEmissivity(10000, 1000, wave = 9531) / S3.getEmissivity(10000, 1000, wave = 9069)
O3_5000_ratio = O3.getEmissivity(10000, 1000, wave = 5007) / O3.getEmissivity(10000, 1000, wave = 4959)
N2_6500_ratio = N2.getEmissivity(10000, 1000, wave = 6584) / N2.getEmissivity(10000, 1000, wave = 6548)

# plot_helium_relation(catalogue_df, element = 'Helium', color = '#bcbd22', label = 'Helium abundance per line')
# plot_metallic_relation(catalogue_df, ['O3_5007A', 'O3_4959A'], O3_5000_ratio, 'Oxygen', color='#009E73', label  = r'Oxygen $\frac{[OIII]50007\AA}{[OIII]4959\AA}$')
plot_metallic_relation(catalogue_df, ['S3_9531A', 'S3_9069A'], S3_9000_ratio, 'Sulfur', color='#D55E00', label = r'Sulfur $\frac{[SIII]9531\AA}{[SIII]9069\AA}$')
# plot_metallic_relation(catalogue_df, ['N2_6584A', 'N2_6548A'], N2_6500_ratio, 'Nitrogen', color='#0072B2', label = r'Oxygen $\frac{[NII]6584\AA}{[NII]6548\AA}$')

dz.display_fig()

print 'Data treated'
    
예제 #8
0
    def get_continuum(self,
                      tem,
                      den,
                      He1_H=0.,
                      He2_H=0.,
                      wl=np.array([3500, 3600, 3700, 3800, 3900]),
                      cont_HI=True,
                      cont_HeI=True,
                      cont_HeII=True,
                      cont_2p=True,
                      cont_ff=True,
                      HI_label='11_2'):
        """
        
        Type of continuum to take into acount defined a boolean, defaults are True
        
        Parameters:
            tem: temperature [K]. May be a float or an iterable.
            den: density [cm-3]. May be a float or an iterable. If iterable, must have same size than tem.
            He1_H (float):  He+/H+ abundance. Default = 0.0
            He2_H (float): He++/H+ abundances.  Default = 0.0
            wl (np.array): Wavelengths Default = np.array([3500, 3600, 3700, 3800, 3900])
            cont_HI (bool): using B. Ercolano 2006 data. Default: True
            cont_HeI (bool): using B. Ercolano 2006 data. Default: True
            cont_HeII (bool): using B. Ercolano 2006 data. Default: True
            cont_2p (bool): 2 photons, using D. Pequignot fit to Osterbrock. Default: True
            cont_ff (bool): from Storey & Hummer 1991. Default: True
            
            HI_label (str): HI label to normalize the continuum. If None, no normalization is done. Default: '11_2'
            
        Returns:
            The resulting continuum. Unit [A-1] if normalized, [erg/s.cm3/A] otherwise
        
        Exemple of use:
            C = pn.Continuum()
            wl = np.arange(3500, 4000, 1)
            cont = C.get_continuum(tem=1e4, den=1e2, He1_H=0.08, He2_H=0.02, wl=wl)
            plt.plot(wl, cont)
        """
        try:
            _ = (e for e in tem)
            T_iterable = True
            try:
                _ = (e for e in den)
            except:
                den = np.ones_like(tem) * den
            try:
                _ = (e for e in He1_H)
            except:
                He1_H = np.ones_like(tem) * He1_H
            try:
                _ = (e for e in He2_H)
            except:
                He2_H = np.ones_like(tem) * He2_H

        except TypeError:
            T_iterable = False
        if HI_label is None:
            norm = 1.0
        else:
            if self.HI is None:
                self.HI = pn.RecAtom('H', 1)
            norm = self.HI.getEmissivity(tem,
                                         den,
                                         label=HI_label,
                                         product=False)

        if T_iterable:
            cont = np.array(
                list(
                    map(
                        lambda t, d, He1_H_1, He2_H_1: self._get_continuum1(
                            t,
                            d,
                            He1_H=He1_H_1,
                            He2_H=He2_H_1,
                            wl=wl,
                            cont_HI=cont_HI,
                            cont_HeI=cont_HeI,
                            cont_HeII=cont_HeII,
                            cont_2p=cont_2p,
                            cont_ff=cont_ff), tem, den, He1_H, He2_H))).T
            return cont.squeeze() / norm
        else:
            cont = self._get_continuum1(tem,
                                        den,
                                        He1_H=He1_H,
                                        He2_H=He2_H,
                                        wl=wl,
                                        cont_HI=cont_HI,
                                        cont_HeI=cont_HeI,
                                        cont_HeII=cont_HeII,
                                        cont_2p=cont_2p,
                                        cont_ff=cont_ff)
            return cont / norm
예제 #9
0
# Declare data and files location
obsConf = sr.loadConfData('J0838_cubes.ini')
fitsFolder = Path(obsConf['data_location']['fits_folder'])
dataFolder = Path(obsConf['data_location']['data_folder'])
resultsFolder = Path(obsConf['data_location']['results_folder'])

fileList = obsConf['data_location']['file_list']
objList = obsConf['data_location']['object_list']
z_list = obsConf['sample_data']['z_array']
norm_flux = obsConf['sample_data']['norm_flux']
percentil_array = obsConf['sample_data']['percentil_array']
voxel_grid_size = obsConf['sample_data']['grid_shape_array']

# Store emissivity ratios at standard conditions
H1 = pn.RecAtom('H', 1)
temp, den = 10000.0, 100.0

theoEmis_dict = {}
for chemLabel, plotLabel in label_Conver.items():
    ion, wave, latexLabel = sr.label_decomposition(chemLabel,
                                                   scalar_output=True)
    dict_label = f'{plotLabel}/Hdelta'
    theoRatio = H1.getEmissivity(temp, den, wave=wave) / H1.getEmissivity(
        temp, den, wave=4102)
    theoEmis_dict[dict_label] = theoRatio
red_model = sr.ExtinctionModel(Rv=obsConf['extinction']['R_v'],
                               red_curve=obsConf['extinction']['red_law'])

# Data location
objFolder = resultsFolder
예제 #10
0
def getIonAb(obs_file, Ne_O2, Ne_Ar4, T_N2, T_O3, printIonAb = True):
    ### General settings
    # define an Observation object and assign it to name 'obs'
    obs = pn.Observation()
    # fill obs with data read from file obs_data, with lines varying across rows and a default percent error on line intensities
    obs.readData(obs_file, fileFormat='lines_in_rows', err_default=0.05, corrected=True)
    
    if 'H1_4.1m' in obs.lineLabels:
        temp = 14000
        dens = 10**3.5
        # Compute theoretical H5-4/Hbeta ratio from Hummer and Storey
        # Instatiate the H1 recombination atom
        H1 = pn.RecAtom('H', 1)
        IR2Opt_theo = H1.getEmissivity(temp, dens, label='5_4') / H1.getEmissivity(temp, dens, label='4_2')
        IR2Opt_obs = obs.getLine(label='H1_4.1m').corrIntens / obs.getLine(label='H1_4861A').corrIntens
        for line in obs.lines: 
            if line.label[-1] == 'm':
                line.corrIntens *= IR2Opt_theo/IR2Opt_obs
                
    # instanciation of all the needed Atom objects
    all_atoms = pn.getAtomDict(atom_list=obs.getUniqueAtoms())
    
    # define a dictionnary for the ionic abundances
    ab_dic = {}
    # we  use the following lines to determine the ionic abundances
    ab_labels = ['C3_1907A', 'C3_1909A',
                 'N2_6583A', 'N3_57.4m', 'N4_1487A', 
                 'O2_3726A', 'O2_3729A', 'O3_5007A', 'O4_25.9m',
                 'S2_6731A', 'S3_9069A', 'S4_10.5m',
                 'Ar3_7136A', 'Ar4_4740A', 'Ar5_7006A', 'Ar6_4.5m', 
                 'Ne2_12.8m', 'Ne3_3869A', 'Ne5_3426A', 'Ne6_7.6m', 
                 'Cl3_5518A', 'Cl3_5538A', 'Cl4_5323A', 
                 'Mg4_4.5m', 'Mg5_5.6m']
    # loop on the observed lines to determine the corresponding ionic abundances
    for line in obs.getSortedLines():
        # this is one way to define temp and dens in each zone
        # must be adapted to each case
        if (line.atom in all_atoms) and (line.label in ab_labels):
            IP_cut = 30. #
            if IP[line.atom] > IP_cut:
                temp = T_O3
                dens = Ne_Ar4
                IP_used = 'H'
            else:
                temp = T_N2
                dens = Ne_O2
                IP_used = 'L'                 
            ab = all_atoms[line.atom].getIonAbundance(line.corrIntens, temp, dens, to_eval=line.to_eval, Hbeta=100)
            if printIonAb:
                print('{0:13s} {1} '.format(line.label, IP_used) + ' '.join(['{0:>8.4f}'.format(t) for t in ab * 1e6]))
            if line.atom not in ab_dic:
                ab_dic[line.atom] = []
            ab_dic[line.atom].append(ab)
    
    He1 = pn.RecAtom('He', 1)
    He2 = pn.RecAtom('He', 2)
    ab_dic['He2']= He1.getIonAbundance(obs.getLine(label='He1_5876A').corrIntens, 
                                 T_N2, Ne_O2, wave=5876.0)
    ab_dic['He3'] = He2.getIonAbundance(obs.getLine(label='He2_4686A').corrIntens, 
                                 T_O3, Ne_Ar4, lev_i= 4, lev_j= 3)
    for atom in ab_dic:
        mean = np.mean(np.asarray(ab_dic[atom]))
        ab_dic[atom] = mean
    
    for ion in np.sort(ab_dic.keys()):
        if printIonAb:
            print('{0} = {1:.3}'.format(ion, np.log10(ab_dic[ion])+12))

    return ab_dic
def compute_cHbeta(line_df,
                   reddening_curve,
                   R_v,
                   temp=10000.0,
                   den=100.0,
                   ref_wave='H1_4861A',
                   compMode='auto'):

    assert ref_wave in line_df.index, f'- ERROR: Reference line {ref_wave} is not in input dataframe index'

    # Create hydrogen recombination atom for emissivities calculation
    H1 = pn.RecAtom('H', 1)

    # Use all the lines from the input data frame
    line_labels = line_df.index.values
    ion_ref, waves_ref, latexLabels_ref = label_decomposition(
        ref_wave, scalar_output=True)
    ion_array, waves_array, latexLabels_array = label_decomposition(
        line_labels)

    # Mode 1: Distinguish between single (intg_flux) and  blended (gauss_flux) lines
    if compMode == 'auto':
        Href_flux, Href_err = line_df.loc[ref_wave,
                                          'intg_flux'], line_df.loc[ref_wave,
                                                                    'intg_err']

        obsFlux, obsErr = np.empty(line_labels.size), np.empty(
            line_labels.size)
        idcs_intg = (line_df.blended == 'None')

        obsFlux[idcs_intg], obsErr[idcs_intg] = line_df.loc[
            idcs_intg, ['intg_flux', 'intg_err']].values
        obsFlux[~idcs_intg], obsErr[~idcs_intg] = line_df.loc[
            ~idcs_intg, ['gauss_flux', 'gauss_err']].values

    # Mode 2: Use always the gaussian flux
    elif compMode == 'gauss':
        Href_flux, Href_err = line_df.loc[ref_wave, 'gauss_flux'], line_df.loc[
            ref_wave, 'gauss_err']
        obsFlux, obsErr = line_df['gauss_flux'].values, line_df[
            'gauss_err'].values

    # Ratio propagating the uncertainty between the lines
    obsFlux_norm = obsFlux / Href_flux
    obsErr_norm = obsFlux_norm * np.sqrt(
        np.square(obsErr / obsFlux) + np.square(Href_err / Href_flux))

    assert not np.any(
        np.isnan(obsFlux)
    ) in obsFlux, '- ERROR: nan entry in input fluxes for c(Hbeta) calculation'
    assert not np.any(
        np.isnan(obsErr)
    ) in obsErr, '- ERROR: nan entry in input uncertainties for c(Hbeta) calculation'

    # Theoretical ratios
    refEmis = H1.getEmissivity(tem=temp, den=den, wave=waves_ref)
    emisIterable = (H1.getEmissivity(tem=temp, den=den, wave=wave)
                    for wave in waves_array)
    linesEmis = np.fromiter(emisIterable, float)
    theoRatios = linesEmis / refEmis

    # Reddening law
    rc = pn.RedCorr(R_V=R_v, law=reddening_curve)
    Xx_ref, Xx = rc.X(waves_ref), rc.X(waves_array)
    f_lines = Xx / Xx_ref - 1
    f_ref = Xx_ref / Xx_ref - 1

    # cHbeta slope fit axes
    x_fred = f_lines - f_ref
    y_flux = np.log10(theoRatios) - np.log10(obsFlux_norm)
    y_err = (obsErr_norm / obsFlux_norm) * (1.0 / np.log(10))

    # Perform fit
    lineModel = LinearModel()
    pars = lineModel.make_params(intercept=y_flux.min(), slope=0)
    output = lineModel.fit(y_flux, pars, x=x_fred, weights=1 / np.sqrt(y_err))
    cHbeta, cHbeta_err = output.params['slope'].value, output.params[
        'slope'].stderr
    intercept, intercept_err = output.params['intercept'].value, output.params[
        'intercept'].stderr

    # Store the results
    output_dict = dict(cHbeta=cHbeta,
                       cHbeta_err=cHbeta_err,
                       intercept=intercept,
                       intercept_err=intercept_err,
                       obsRecomb=obsFlux_norm,
                       obsRecombErr=obsErr_norm,
                       y=y_flux,
                       y_err=y_err,
                       x=x_fred,
                       line_labels=latexLabels_array,
                       ref_line=latexLabels_ref)

    return output_dict
    def cHbeta_from_log(self, line_df, line_labels='all', temp=10000.0, den=100.0, ref_wave='H1_4861A',
                        comp_mode='auto', plot_address=False):

        # Use all hydrogen lines if none are defined
        if line_labels == 'all':
            idcs_H1 = line_df.ion == 'H1'
            line_labels = line_df.loc[idcs_H1].index.values
        assert line_labels.size > 0, f'- ERROR: No H1 ion transition lines were found in log. Check dataframe data.'

        # Loop through the input lines
        assert ref_wave in line_df.index, f'- ERROR: {ref_wave} not found in input lines log dataframe for c(Hbeta) calculation'

        # Label the lines which are found in the lines log
        idcs_lines = line_df.index.isin(line_labels) & (line_df.intg_flux > 0) & (line_df.gauss_flux > 0)
        line_labels = line_df.loc[idcs_lines].index.values
        ion_ref, waves_ref, latexLabels_ref = label_decomposition(ref_wave, scalar_output=True)
        ion_array, waves_array, latexLabels_array = label_decomposition(line_labels)

        # Observed ratios
        if comp_mode == 'auto':
            Href_flux, Href_err = line_df.loc[ref_wave, 'intg_flux'], line_df.loc[ref_wave, 'intg_err']
            obsFlux, obsErr = np.empty(line_labels.size), np.empty(line_labels.size)
            slice_df = line_df.loc[idcs_lines]
            idcs_intg = slice_df.blended_label == 'None'
            obsFlux[idcs_intg] = slice_df.loc[idcs_intg, 'intg_flux'].values
            obsErr[idcs_intg] = slice_df.loc[idcs_intg, 'intg_err'].values
            obsFlux[~idcs_intg] = slice_df.loc[~idcs_intg, 'gauss_flux'].values
            obsErr[~idcs_intg] = slice_df.loc[~idcs_intg, 'gauss_err'].values
            obsRatio_uarray = unumpy.uarray(obsFlux, obsErr) / ufloat(Href_flux, Href_err) # TODO unumpy this with your own model

        elif comp_mode == 'gauss':
            Href_flux, Href_err = line_df.loc[ref_wave, 'gauss_flux'], line_df.loc[ref_wave, 'gauss_err']
            obsFlux, obsErr = line_df.loc[idcs_lines, 'gauss_flux'], line_df.loc[idcs_lines, 'gauss_err']
            obsRatio_uarray = unumpy.uarray(obsFlux, obsErr) / ufloat(Href_flux, Href_err)

        else:
            Href_flux, Href_err = line_df.loc[ref_wave, 'intg_flux'], line_df.loc[ref_wave, 'intg_err']
            obsFlux, obsErr = line_df.loc[idcs_lines, 'intg_flux'], line_df.loc[idcs_lines, 'intg_err']
            obsRatio_uarray = unumpy.uarray(obsFlux, obsErr) / ufloat(Href_flux, Href_err)

        assert not np.any(np.isnan(obsFlux)) in obsFlux, '- ERROR: nan entry in input fluxes for c(Hbeta) calculation'
        assert not np.any(np.isnan(obsErr)) in obsErr, '- ERROR: nan entry in input uncertainties for c(Hbeta) calculation'

        # Theoretical ratios
        H1 = pn.RecAtom('H', 1)
        refEmis = H1.getEmissivity(tem=temp, den=den, wave=waves_ref)
        emisIterable = (H1.getEmissivity(tem=temp, den=den, wave=wave) for wave in waves_array)
        linesEmis = np.fromiter(emisIterable, float)
        theoRatios = linesEmis / refEmis

        # Reddening law
        rc = pn.RedCorr(R_V=self.R_v, law=self.red_curve)
        Xx_ref, Xx = rc.X(waves_ref), rc.X(waves_array)
        f_lines = Xx / Xx_ref - 1
        f_ref = Xx_ref / Xx_ref - 1

        # cHbeta linear fit values
        x_values = f_lines - f_ref
        y_values = np.log10(theoRatios) - unumpy.log10(obsRatio_uarray)

        # Perform fit
        lineModel = LinearModel()
        y_nom, y_std = unumpy.nominal_values(y_values), unumpy.std_devs(y_values)
        pars = lineModel.make_params(intercept=y_nom.min(), slope=0)
        output = lineModel.fit(y_nom, pars, x=x_values, weights=1 / np.sqrt(y_std))
        cHbeta, cHbeta_err = output.params['slope'].value, output.params['slope'].stderr
        intercept, intercept_err = output.params['intercept'].value, output.params['intercept'].stderr

        if plot_address:

            STANDARD_PLOT = {'figure.figsize': (14, 7), 'axes.titlesize': 12, 'axes.labelsize': 14,
                             'legend.fontsize': 10, 'xtick.labelsize': 10, 'ytick.labelsize': 10}

            axes_dict = {'xlabel': r'$f_{\lambda} - f_{H\beta}$',
                         'ylabel': r'$ \left(\frac{I_{\lambda}}{I_{\H\beta}}\right)_{Theo} - \left(\frac{F_{\lambda}}{F_{\H\beta}}\right)_{Obs}$',
                         'title': f'Logaritmic extinction coefficient calculation'}

            rcParams.update(STANDARD_PLOT)

            fig, ax = plt.subplots(figsize=(8, 4))
            fig.subplots_adjust(bottom=-0.7)

            # Data ratios
            err_points = ax.errorbar(x_values, y_nom, y_std, fmt='o')

            # Linear fitting
            linear_fit = cHbeta * x_values + intercept
            linear_label = r'$c(H\beta)={:.2f}\pm{:.2f}$'.format(cHbeta, cHbeta_err)
            ax.plot(x_values, linear_fit, linestyle='--', label=linear_label)
            ax.update(axes_dict)

            # Legend
            ax.legend(loc='best')
            ax.set_ylim(-0.5, 0.5)

            # Generate plot
            plt.tight_layout()
            if isinstance(plot_address, (str, pathlib.WindowsPath, pathlib.PosixPath)):
                # crs = mplcursors.cursor(ax, hover=True)
                # crs.connect("add", lambda sel: sel.annotation.set_text(sel.annotation))
                plt.savefig(plot_address, dpi=200, bbox_inches='tight')
            else:
                mplcursors.cursor(ax).connect("add", lambda sel: sel.annotation.set_text(latexLabels_array[sel.target.index]))
                plt.show()

        return cHbeta, cHbeta_err
from CodeTools.PlottingManager              import myPickle
from Plotting_Libraries.dazer_plotter       import Plot_Conf
from numpy                                  import linspace
import seaborn as sns
import pyneb as pn

#Declare Classes
pv      = myPickle()
dz      = Plot_Conf() 

#Define figure format
dz.FigConf()

# Atom creation and definition of physical conditions
H1      = pn.RecAtom('H',1)
HeI     = pn.RecAtom('He', 1)

#Define physical conditions
tem = 10000
tem_range = linspace(10000, 25000, 100)
 
den = 0
den_range = linspace(0, 300, 200)

# Comment the second if you want all the lines to be plotted
HeI_Lines=[3889.0, 4026.0, 4471.0, 5876.0, 6678.0, 7065.0, 10830.0]


print 'Emissivity', HeI.getEmissivity(tem, 1, wave=3889.0)

#--------------------------Density case----------------------------------
예제 #14
0
from numpy import array, linspace, zeros, pi

from CodeTools.PlottingManager import myPickle
import pyneb as pn

S4 = pn.RecAtom('He', 1)

He1_Emis_pyneb = S4.getEmissivity(tem=10000.0, den=100.0, label='3889.0')

He_Emis_article = 1.4005 * 1e-25  #Units: 4 Pi j / n_e / n_He+ (erg cm^3 s^-1).

#Emissivity coefficient
print 'Emissivity ratio', He1_Emis_pyneb / He_Emis_article

#Load script support classes
pv = myPickle()

#Declare Figure format
pv.FigFormat_One(ColorConf='Night1')

#Load pyneb atom
H1 = pn.RecAtom('H', 1)
S4 = pn.RecAtom('He', 1)
Helium_Labels = ['3889.0', '4026.0', '4471.0', '5876.0', '6678.0', '7065.0']

#Declare initial conditions
Te_vector = linspace(8000, 25000, 100)  #K
ne_vector = linspace(10, 1000, 100)  #cm^-3

Te_0 = 10000
ne_0 = 100
예제 #15
0
import pyneb as pn
import numpy as np
import src.specsiser as sr


def corO2_7319(emis_ratio, cHbeta, flambda, O2_abund, O3_abund, Te_high):
    fluxCorr = np.power(10, O2_abund + emis_ratio - flambda * cHbeta - 12) + \
               np.power(10, O3_abund + 0.9712758487381 + np.log10(np.power(Te_high/10000.0, 0.44)) - flambda * cHbeta - 12)

    return fluxCorr


Te, ne = 10000.0, 100.0
cHbeta = 0.255
H1_ion = pn.RecAtom('H', 1)
O2_ion = pn.Atom('O', 2)
O3_ion = pn.Atom('O', 3)
cHbeta = 0.12
flambda = -0.55

O2_abund = 0.00000648
O3_abund = 0.00004578

logO2abund = 12 + np.log10(O2_abund)
logO3abund = 12 + np.log10(O3_abund)

Hbeta_emis = H1_ion.getEmissivity(tem=Te, den=ne, wave=4861)
O2_emis = (O2_ion.getEmissivity(tem=Te, den=ne, wave=7319) +
           O2_ion.getEmissivity(tem=Te, den=ne, wave=7319)) / Hbeta_emis
logO2_emis = np.log10(O2_emis)
예제 #16
0
S2 = pn.Atom('S', 2)
#S2.printIonic()
S2_6718 = AIR(1 / (S2.getEnergy(S2.getTransition(6718)[0]) -
                   S2.getEnergy(S2.getTransition(6718)[1])))
S2_6732 = AIR(1 / (S2.getEnergy(S2.getTransition(6732)[0]) -
                   S2.getEnergy(S2.getTransition(6732)[1])))

Ar3 = pn.Atom('Ar', 3)
#Ar3.printIonic()
Ar3_7137 = AIR(1 / (Ar3.getEnergy(Ar3.getTransition(7137)[0]) -
                    Ar3.getEnergy(Ar3.getTransition(7137)[1])))

# Wavelengths from pyNeb RecAtoms are in A in Air like the SDSS spectra. Conversion needed.

H1 = pn.RecAtom('H', 1)  # Hydrogen Balmer series
H1_3970 = H1.getWave(7, 2)
H1_4102 = H1.getWave(6, 2)
H1_4341 = H1.getWave(5, 2)
H1_4862 = H1.getWave(4, 2)
H1_6564 = H1.getWave(3, 2)

H1 = pn.RecAtom('H', 1)  # Hydrogen Lyman series
H1_1216 = H1.getWave(2, 1)

He1 = pn.RecAtom('He', 1)  # Helium

He2 = pn.RecAtom('He', 2)  # Helium
He2_4686 = He2.getWave(4, 3)
He2_5411 = He2.getWave(7, 4)
예제 #17
0
# The_Ratio               = Abund * Line_dict['10.51m'] / Line_dict['4861.36A']
# S3_abund_pyneb          = S4.getIonAbundance(int_ratio = The_Ratio, tem = Te_test, den = ne_test, wave = 105000, Hbeta = 1)
# Abun_formula            = log10(The_Ratio) + 6.3956 + 0.0416/t4_test - 0.4216 * log10(t4_test) - 12
# Emis_formula            = 12 + p_1[0] + p_1[1]/t4_range + p_1[2] * log10(t4_range)
# print 'Comparing abund', S3_abund_pyneb, 10**Abun_formula
#
#
# #Display figure
# dz.display_fig()


#--------------------------------Helium I Lines--------------------------------

#The formula has the shape: E_HeII / E_Hbeta = A * t_4 ^ B

HI = pn.RecAtom('H', 1)
He1 = pn.RecAtom('He', 1)

A_0 = 1 / 2.04
B_0 = - 0.13

C_0 = 1 / 0.783
D_0 = - 0.23

E_0 = 1 / 2.58
F_0 = - 0.25

# #Declare Classes
# dz = Plot_Conf()
#
# #Define figure format
예제 #18
0
def intrinsic_ratios(t0, n0, r_type='HaHb', product=False, silent=True,
                     verbose=False):
    '''
    Function to obtain Ha/Hb, Hg/Hb, or Hd/Hb flux ratios

    Parameters
    ----------
    t0 : array like
      Array of electron temperatures in units of K

    n0 : array like
      Array of electron densities in units of cm^-3

    r_type : string
      'HaHb', 'HgHb', or 'HdHb' to indicate which line ratio to calculate

    product : boolean
      If True, all the combination of (t0, n0) are used. 
      If False (default), t0 and n0 must have the same size and are joined.

    silent : boolean
      Turns off stdout messages. Default: True

    verbose : boolean
      Turns on additional stdout messages. Default: False

    Returns
    -------
     ratio0 : float or array like
       Intrinsic Balmer decrement ratios, Ha/Hb, Hg/Hb, Hd/Hb

     recFitsFile : string
       Name of FITS file containing recombination coefficients

    Notes
    -----
    Created by Chun Ly, 21 November 2016
    Modified by Chun Ly, 22 November 2016
     - Previously called HaHb() function
     - Fix to allow for other balmer decrement options
    '''

    if silent == False:
        print '### Begin balmer_decrement.intrinsic_ratios | '+systime()

    # + on 22/11/2016
    if r_type != 'HaHb' and r_type != 'HgHb' and r_type != 'HdHb':
        print "Invalid [r_type]"
        print "Options are 'HaHb', 'HgHb', 'HdHb'"
        print "Exiting!!!"
        return
    #endif

    H1 = pn.RecAtom('H', 1)

    if silent == False:
        print '### Using the following atomic data'
        print H1.recFitsFullPath
        
    Hbeta = H1.getEmissivity(tem=t0, den=n0, lev_i=4, lev_j=2, product=product)

    # Mod on 22/11/2016
    if r_type == 'HaHb': 
        Halpha = H1.getEmissivity(tem=t0, den=n0, lev_i=3, lev_j=2, product=product)
        ratio0 = Halpha/Hbeta

    if r_type == 'HgHb':
        Hgamma = H1.getEmissivity(tem=t0, den=n0, lev_i=5, lev_j=2, product=product)
        ratio0 = Hgamma/Hbeta

    if r_type == 'HdHb':
        Hdelta = H1.getEmissivity(tem=t0, den=n0, lev_i=6, lev_j=2, product=product)
        ratio0 = Hdelta/Hbeta
    
    if silent == False:
        print '### End balmer_decrement.intrinsic_ratios | '+systime()

    return ratio0, H1.recFitsFile