示例#1
0
def p3(obs, Tlow, Tmid, Thigh, mean_dens, verbose=True):
    #we associate the Te with each ion
    Te_dic = {
        'N2': Tlow,
        'O2': Tlow,
        'S2': Tlow,
        'S3': Tmid,
        'Ar3': Tmid,
        'O3': Thigh,
        'Ne3': Thigh
    }

    all_atoms = pn.getAtomDict(atom_list=obs.getUniqueAtoms())

    # This is the dictionnary which will contain the ionic abundances
    ab_dic = {}

    # we  use the following lines to determine the ionic abundances
    ab_labels = [
        'N2_6584A', 'O2_3727A+', 'O3_5007A', 'S2_6716A', 'S3_9069A',
        'Ar3_7136A', 'Ne3_3869A'
    ]
    for line in obs.getSortedLines():
        if line.label in ab_labels:
            ab = all_atoms[line.atom].getIonAbundance(line.corrIntens,
                                                      Te_dic[line.atom],
                                                      mean_dens,
                                                      to_eval=line.to_eval,
                                                      Hbeta=100)
            if verbose:
                print '{0:9s}'.format(line.label) + ' '.join(
                    ['{0:>8.2f}'.format(t) for t in 12 + np.log10(ab)])
            ab_dic[line.atom] = ab
    return ab_dic
    def printAllSources(self, at_set=None, predef=None):
        """
        Print bibliographic sources of the adopted data sets of a list of atoms.
        
        Usage:
        pn.atomicData.printAllSources(['O3', 'Ar4', 'S2'])
        pn.atomicData.printAllSources([O, S])
        pn.atomicData.printAllSources()

        Parameters: 
            - at_set   a list or tuple containing the atoms. If not set, 
                       print bibliographic sources for all the atoms in PyNeb's default dictionary
                       
        """
        self.calling = 'printAllSources'
        if (type(at_set) == list) or (type(at_set) == tuple) or at_set == '':
            at_dict = {}
            for item in at_set:
                atom = parseAtom(item)[0]
                spec = parseAtom(item)[1]
                if spec is '':
                    for ispec in SPEC_LIST:
                        try:
                            at_dict[atom + ispec] = pn.Atom(atom, ispec)
                        except:
                            pass
                else:
                    at_dict[item] = pn.Atom(atom, spec)
        elif at_set is not None:
            pn.log_.error('The argument at_set must be a list or a tuple',
                          calling=self.calling)
            return None
        elif (at_set is None) and (predef is None):
            at_dict = pn.getAtomDict()
        elif predef in pn.atomicData.getAllPredefinedDict():
            current = pn.atomicData.predefined
            pn.atomicData.setDataFileDict(predef)
            at_dict = pn.getAtomDict()
            pn.atomicData.setDataFileDict(current)
        else:
            pn.log_.error(
                'The argument predef must be the label of a predefined dictionary',
                calling=self.calling)

        for item in sorted(at_dict):
            at_dict[item].printSources()
示例#3
0
文件: py.py 项目: Delosari/X_Bin
def LM_GetPyNebAtoms():
    
    PyNeb_Atoms = list(pn.getAtomDict())
    
    PyNeb_Atoms.append("He1")
    PyNeb_Atoms.append("He2")
    PyNeb_Atoms.append("H1")
        
    PyNeb_Atoms.sort()
          
    return PyNeb_Atoms
示例#4
0
def plot_all(save=False):
    pn.log_.level = 1
    AA = pn.getAtomDict(OmegaInterp='Linear')
    for diag in pn.diags_dict:
        atom, diag_eval, err = pn.diags_dict[diag]
        if atom in AA:
            plt.figure()
            grid = pn.EmisGrid(atomObj=AA[atom])
            grid.plotContours(to_eval=diag_eval)
            if save:
                plt.savefig('{0}_{1}.pdf'.format(atom,
                                                 diag_eval.replace('/', '_')))
示例#5
0
def plot_all(save=False):
    pn.log_.level = 1
    AA = pn.getAtomDict(OmegaInterp='Linear')
    # Loop over all the diags stored in pn.core.diags.diags_dict
    for diag in diags_dict:
        atom, diag_eval, err = diags_dict[diag]
        # Skip Fe III as they are so many
        if (atom in AA) and (atom != 'Fe3'):
            print atom
            plt.figure()
            grid = pn.EmisGrid(atomObj=AA[atom])
            grid.plotContours(to_eval=diag_eval)
            if save:
                plt.savefig('{0}_{1}.pdf'.format(atom,
                                                 diag_eval.replace('/', '_')))
示例#6
0
def _print_LINE_LABEL_LIST(*args, **kwargs):
    """
    The parameters are passed to getAtomDict. May be the fits directory.
    """
    ##
    # @todo we have to check what are the differences in LINE_LABEL_LIST when changing the fits files
    all_atoms = pn.getAtomDict(*args, **kwargs)
    print("LINE_LABEL_LIST = {}")
    for atom in np.sort(all_atoms.keys()):
        wave = all_atoms[atom].lineList
        opt = (wave < 10000.)
        ir = (wave >= 10000.)
        lines_opt = ["'%.0fA'" % line for line in np.sort(wave[opt])]
        lines_ir = ["'%.1fm'" % line for line in np.sort(wave[ir]) / 1.e4]
        lines = lines_opt + lines_ir
        print("LINE_LABEL_LIST['" + atom + "'] = [" + ', '.join(lines) + "]")
    def get_ions_dict(self,
                      ions_list,
                      recomb_atoms=('H1', 'He1', 'He2'),
                      atomic_references=pn.atomicData.defaultDict):

        # Check if the atomic dataset is the default one
        if atomic_references == pn.atomicData.defaultDict:
            pn.atomicData.resetDataFileDict()
            pn.atomicData.removeFitsPath()
        else:
            pn.atomicData.includeFitsPath()
            pn.atomicData.setDataFileDict(atomic_references)

        # Generate the dictionary with pyneb ions
        ionDict = pn.getAtomDict(ions_list)

        # Remove r extension from recom 'H1', 'He1', 'He2' emissions
        for ion_r in recomb_atoms:
            recomb_key = f'{ion_r}r'
            if recomb_key in ionDict:
                ionDict[ion_r] = ionDict.pop(recomb_key)

        return ionDict
示例#8
0
pn.atomicData.getAllDataFilePaths()
# Remove it if you gave the wrong dir
pn.atomicData.removeDataFilePath('./')
# Set 'o_iii_TEST.fits' to be the OIII atom file
pn.atomicData.setDataFile('o_iii_TEST.fits', 'O3', 'atom')
# Check that it is read from the right place
pn.atomicData.getDirForFile('o_ii_atom_TEST.fits')
# Summarize all data used
pn.atomicData.printDirForAllFiles()

# define an atom with the new data
O2test = pn.Atom("O", 2)

# define all atoms at once and put them in a dictionary
# (all of them defined with the latest dataset selected)
atoms = pn.getAtomDict(
)  #this generates a lot of warnings as not all element-spectrum combination exist
# see what atoms have been built
atoms
# build only some atoms
atoms = pn.getAtomDict(atom_list=['O1', 'O2', 'O3', 'N2', 'N3'])

# explore some specific atom in the atoms collection
atoms['N2'].elem

# if you want to be able to access them directly rather than through a dictionary:
for key in atoms.keys():
    vars()[key] = atoms[key]

# for example
O2.elem
示例#9
0
    def import_atomic_data(self,
                           atomic_data=None,
                           ftau_coefficients=None,
                           tempGrid=None,
                           denGrid=None):

        # Load nebular continuum constants
        self.loadNebCons(self.externalDataFolder)

        # # Import default database with line labels if not provided # TODO not the right place for loading this file
        # if atomic_data is not None:
        #     linesDataFile = atomic_data if atomic_data is not None else path.join(self.externalDataFolder, self.config['linesData_file'])
        #     self.linesDb = read_excel(linesDataFile, sheet_name=0, header=0, index_col=0)

        # Additional code to adapt to old lines log labelling
        self.linesDb['pyneb_code'] = self.linesDb['pyneb_code'].astype(str)
        idx_numeric_pynebCode = ~self.linesDb['pyneb_code'].str.contains('A+')
        self.linesDb.loc[idx_numeric_pynebCode,
                         'pyneb_code'] = self.linesDb.loc[
                             idx_numeric_pynebCode,
                             'pyneb_code']  #.astype(int)
        self.linesDb['ion'].apply(str)

        print('\n-- Loading atoms data with PyNeb')

        # Load user atomic data references
        # TODO is the atomic data really changing?
        for reference in self.config['atomic_data_list']:
            pn.atomicData.setDataFile(reference)

        # Generate the dictionary with pyneb ions
        self.ionDict = pn.getAtomDict(
            atom_list=np.unique(self.linesDb.ion.values.astype(str)))

        # Preparing Hbeta references
        self.Hbeta_label = 'H1_4861A'
        self.Hbeta_wave = 4862.683
        self.Hbeta_pynebCode = '4_2'

        # Import Optical depth function
        ftauFile = ftau_coefficients if ftau_coefficients is not None else path.join(
            self.externalDataFolder, self.config['ftau_file'])
        self.ftau_coeffs = self.import_optical_depth_coeff_table(ftauFile)

        # Declare diagnostic ratios
        self.diagnosDict = {
            'ROIII': {
                'num': np.array([4363]),
                'den': np.array([4959, 5007])
            },
            'RSIII': {
                'num': np.array([6312]),
                'den': np.array([9069, 9531])
            },
            'RSII': {
                'num': np.array([6716]),
                'den': np.array([6731])
            }
        }

        # Defining temperature and density grids(These are already define at init)
        if (tempGrid is not None) and (denGrid is not None):
            self.tempRange = np.linspace(tempGrid[0], tempGrid[1], tempGrid[2])
            self.denRange = np.linspace(denGrid[0], denGrid[1], denGrid[2])
            X, Y = np.meshgrid(self.tempRange, self.denRange)
            self.tempGridFlatten, self.denGridFlatten = X.flatten(), Y.flatten(
            )

        return
示例#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
示例#11
0
	if not os.path.exists(filepath):
		os.mkdir(filepath)
		
	### Plot
	# Create the contour plot as the intersection of tem-den emission maps with dereddened line ratios
	diags.plot(emisgrids, obs)
	# Place the title
	plt.title(title)
	# Display the plot
	plt.show()
	# To save, click on the icon
	plt.close()

	# Define all atoms to make calculations (etAtomDict is overkill, but worth 
	# given the large number of ions required)
	all_atoms = pn.getAtomDict()
	
	# Simultaneously determine T(OIII) and N(SII)
	try:
		tem_O3, den_S2 = diags.getCrossTemDen('[OIII] 4363/5007', '[SII] 6731/6716', obs=obs)
	except:
		tem_O3 = 'NA'
		den_S2 = 'NA'
		pass
		
	# Simultaneously determine T(NII) and N(SII)
	try:
		tem_N2, den_tmp = diags.getCrossTemDen('[NII] 5755/6548', '[SII] 6731/6716', obs=obs)
	except:
		tem_N2 = 'NA'
		pass
示例#12
0
"""
Sample PyNeb script
Plots the [O III] 4363/5007 ratio as a function of Te for several Ne values
"""

# Import relevant packages
import numpy as np
import matplotlib.pyplot as plt
import pyneb as pn

# Set high verbosity level to keep track of atom creation
pn.log_.level = 3

# Create a collection of atoms - a bit overkill if we just need O III
adict = pn.getAtomDict()

# Lower verbosity level
pn.log_.level = 2

# Function to compute line ratio
def line_ratio(atom, wave1, wave2, tem, den):
    emis1 = adict[atom].getEmissivity(tem, den, wave = wave1)
    emis2 = adict[atom].getEmissivity(tem, den, wave = wave2)
    return emis1 / emis2

# Define array of Te 
tem = np.arange(5000, 18000, 30)

# Plot
plt.figure(1)
for den in [1e2, 1e3, 1e4, 1e5]:
示例#13
0
    if not os.path.exists(filepath):
        os.mkdir(filepath)
        
    ### Plot
    # Create the contour plot as the intersection of tem-den emission maps with dereddened line ratios
    diags.plot(emisgrids, obs)
    # Place the title
    plt.title(title)
    # Display the plot
    plt.show()
    # To save, click on the icon
    plt.close()

    # Define all atoms to make calculations (etAtomDict is overkill, but worth 
    # given the large number of ions required)
    all_atoms = pn.getAtomDict()
    
    # Simultaneously determine T(OIII) and N(SII)
    try:
        tem_O3, den_S2 = diags.getCrossTemDen('[OIII] 4363/5007', '[SII] 6731/6716', obs=obs)
    except:
        tem_O3 = 'NA'
        den_S2 = 'NA'
        pass
        
    # Simultaneously determine T(NII) and N(SII)
    try:
        tem_N2, den_tmp = diags.getCrossTemDen('[NII] 5755/6548', '[SII] 6731/6716', obs=obs)
    except:
        tem_N2 = 'NA'
        pass
示例#14
0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from inspect import getargspec
from collections import OrderedDict
from scipy.optimize import curve_fit
from inferenceModel import SpectraSynthesizer
from Astro_Libraries.spectrum_fitting.gasEmission_functions import EmissionComponents
from lib.Astro_Libraries.spectrum_fitting.plot_tools import MCMC_printer

# Tools for printing
mcPrinter = MCMC_printer()
outputFolder = 'E:\\Research\\article_YpBayesian\\'

# Generate the dictionary with pyneb ions
ionDict = pn.getAtomDict(atom_list=['H1r', 'He1r'])
pynebcode_list = np.array(['4471', '5876', '6678'])
ions_list = np.array(['He1r', 'He1r', 'He1r'])
labels_list = np.array(['He1_4471A', 'He1_5876A', 'He1_6678A'])
epm2017_emisCoeffs = {
    'He1_3889A': np.array([0.173, 0.00054, 0.904, 1e-5]),
    'He1_4026A': np.array([-0.09, 0.0000063, 4.297, 1e-5]),
    'He1_4471A': np.array([-0.1463, 0.0005, 2.0301, 1.5e-5]),
    'He1_5876A': np.array([-0.226, 0.0011, 0.745, -5.1e-5]),
    'He1_6678A': np.array([-0.2355, 0.0016, 2.612, 0.000146]),
    'He1_7065A': np.array([0.368, 0.0017, 4.329, 0.0024]),
    'He1_10830A': np.array([0.14, 0.00189, 0.337, -0.00027])
}

porter2007_emisCoeffs = {
    'He1_4471A': np.array([-3.5209E+04, -4.5168E+02, 8.5367E+03, 9.1635E+03]),