def fill_lls_lines(self, bval=20.):
        """
        Generate an HI line list for an LLS.
        Goes into self.lls_lines 

        Parameters
        ----------
        bval : float (20.)  Doppler parameter in km/s
        """
        from barak import absorb as ba

        atom = ba.readatom()
        self.lls_lines = []
        for line in atom['HI']:
            tmp = abs_line.Abs_Line(line['wa']*u.AA,fill=False)
            # Atomic data
            tmp.atomic = {'fval': line['osc'], 'gamma': line['gam'],
                          'name': 'HI %s' % line['wa'], 'wrest': line['wa']}
            tmp.name = tmp.atomic['name']
            # Attributes
            tmp.attrib['N'] = self.NHI
            tmp.attrib['b'] = bval
            tmp.z = self.zabs

            self.lls_lines.append(tmp)
Exemple #2
0
from barak.pyvpfit import readf26
from barak.absorb import findtrans, readatom, find_tau
from barak.constants import c_kms
from barak.sed import make_constant_dv_wa_scale
from barak.convolve import convolve_constant_dv
from COS import convolve_with_COS_FOS
import barak.spec
from barak.utilities import between, adict
from barak.plot import puttext

import pylab as pl
import numpy as np
import matplotlib.transforms as mtransforms

atomdat = readatom(molecules=1)

def get_fig_axes(nrows, ncols, npar, width=11.7, height=None, aspect=0.5):
    """ Generate a figure with a number of subplots.

    Parameters
    ----------
    nrows : int
      Number of rows
    ncols : int
      Number of columns
    npar : int
      Number of plots in total
    width : float
      Width of the figure in inches
    aspect : float
      width / height of each sub-plot.
def mk_line_list_fits_table(outfil=None,XIDL=False):
    from barak import absorb as ba

    if XIDL is True:
        lindat =  os.getenv('XIDL_DIR')+'/Spec/Lines/Lists/grb.lst'
        finedat = os.getenv('XIDL_DIR')+'/Spec/Lines/Lists/fine_strct.lst'
    else:
        lindat = 'grb.lst'  # This pulls from xastropy/data/spec_lines first
        finedat = os.getenv('XIDL_DIR')+'/Spec/Lines/Lists/fine_strct.lst'
  
    # Read XIDL line list
    llist = Abs_Line_List(lindat)
    ndata = len(llist.data)

    # Add columns
    from astropy.table import Column
    gamma = Column(np.zeros(ndata),name='gamma')
    A = Column(np.zeros(ndata),name='A') # Einstein coefficient
    j = Column(np.zeros(ndata),name='j') # Tot ang mom (z projection)
    Ex = Column(np.zeros(ndata),name='Ex') # Excitation energy (cm^-1)
    Elow = Column(np.zeros(ndata),name='Elow') # Energy of lower level
    Eup = Column(np.zeros(ndata),name='Eup') # Energy of upper level
    Z = Column(np.zeros(ndata,dtype='int'),name='Z') # Atomic number
    ion = Column(np.zeros(ndata,dtype='int'),name='ion') # Ionic state

    llist.data.add_columns([gamma,A,j,Ex,Elow,Eup,Z,ion])

    # Z,ion
    for ii in range(ndata):
        nm = llist.data['name'][ii]
        # Z
        if nm[1] == 'I' or nm[1] == 'V': 
            ielm = 1
        else:
            ielm = 2
        elm = nm[:ielm]
        try:
            Zv = ELEMENTS[elm].number
        except KeyError:
            if elm in ['CO','CC','HH']: # Molecules
                Zv = 999
            elif elm in ['D']: # Deuterium
                Zv = 1
            else:
                xdb.set_trace()
        llist.data['Z'][ii] = Zv
        # ion
        ispc = nm.find(' ')
        cion = nm[ielm:ispc].strip('*')
        if len(cion) == 0:
            ionv =0
        else:
            ionv = roman.fromRoman(cion)
        llist.data['ion'][ii] = ionv

    # #######
    # Fill in matches
    
    # Read atom.dat using barak
    atom, atomflat = ba.readatom(flat=True)
    #pdb.set_trace()
    llist.sources.append('atom.dat') # I wish I could pull this from ba.readatom

    # Fine structure
    fdata = ascii.read(finedat)
    llist.sources.append(finedat)

    # Loop
    for ii in range(ndata):
        # Atom.dat
        mt = np.where(np.fabs(llist.data['wrest'][ii]-atomflat['wa']) < 1e-3)[0]
        if len(mt) > 0: llist.data['gamma'][ii] = atomflat['gam'][mt[0]] # Takes the first match

        # Fine structure
        mt = np.where(np.fabs(llist.data['wrest'][ii]-fdata['wrest']) < 1e-3)[0]
        if len(mt) > 0:
            llist.data['A'][ii] = fdata['A'][mt[0]] # Takes the first match
    
    # Output file
    if outfil is None:
        outfil = xa_path+'/data/atomic/spec_atomic_lines.fits'

    # Header
    '''
    prihdr = fits.Header()
    prihdr['COMMENT'] = "Above are the data sources"
    for ii in range(len(llist.sources)):
        card = 'SOURCE'+str(ii+1)
        prihdr[card] = llist.sources[ii]
    prihdu = fits.PrimaryHDU(header=prihdr)

    # Table
    table_hdu = fits.BinTableHDU.from_columns(np.array(llist.data.filled()))

    '''
    # Write
    llist.data.write(outfil, overwrite=True, format='fits')
    print('mk_line_list: Wrote {:s}'.format(outfil))
Exemple #4
0
def process_options(args):
    opt = adict()
    filename = os.path.abspath(__file__).rsplit('/', 1)[0] + '/default.cfg'
    opt = parse_config(filename)
    if os.path.lexists('./plot.cfg'):
        opt = parse_config('./plot.cfg', opt)

    opt.atom = readatom(molecules=True)

    if opt.Rfwhm is not None:
        if isinstance(opt.Rfwhm, basestring):
            if opt.Rfwhm == 'convolve_with_COS_FOS':
                if convolve_with_COS_FOS is None:
                    raise ValueError('convolve_with_COS_FOS() not available')
                print('Using tailored FWHM for COS/FOS data')
                opt.Rfwhm = 'convolve_with_COS_FOS'
            elif opt.Rfwhm.endswith('fits'):
                print('Reading Resolution FWHM from', opt.Rfwhm)
                res = readtabfits(opt.Rfwhm)
                opt.Rfwhm = res.res / 2.354
            else:
                print('Reading Resolution FWHM from', opt.Rfwhm)
                fh = open(opt.Rfwhm)
                opt.Rfwhm = 1 / 2.354 * np.array([float(r) for r in fh])
                fh.close()
        else:
            opt.Rfwhm = float(opt.Rfwhm)

    if opt.features is not None:
        print('Reading feature list from', opt.features)
        opt.features = readtabfits(opt.features)

    if opt.f26 is not None:
        name = opt.f26
        print('Reading ions and fitting regions from', name)
        opt.f26 = readf26(name)
        opt.f26.filename = name

    if opt.transitions is not None:
        print('Reading transitions from', opt.transitions)
        fh = open(opt.transitions)
        trans = list(fh)
        fh.close()
        temp = []
        for tr in trans:
            tr = tr.strip()
            if tr and not tr.startswith('#'):
                junk = tr.split()
                tr = junk[0] + ' ' + junk[1]
                t = findtrans(tr, atomdat=opt.atom)
                temp.append(dict(name=t[0], wa=t[1][0], tr=t[1]))
        opt.linelist = temp
    else:
        opt.linelist = readtxt(get_data_path() + 'linelists/qsoabs_lines',
                               names='wa,name,select')

    if opt.f26 is None and opt.taulines is not None:
        print('Reading ions from', opt.taulines)
        fh = open(opt.taulines)
        lines = []
        for row in fh:
            if row.lstrip().startswith('#'):
                continue
            items = row.split()
            lines.append([items[0]] + list(map(float, items[1:])))
        fh.close()
        opt.lines = lines

    if opt.show_regions is None:
        opt.show_regions = True

    if hasattr(opt, 'aodname'):
        opt.aod = Table.read(opt.aodname)

    return opt
Exemple #5
0
import barak.spec
from barak.plot import A4PORTRAIT
from barak.utilities import indexnear, stats, between, adict
from barak.convolve import convolve_psf
from barak.absorb import calc_Wr, findtrans, \
     calc_iontau, guess_logN_b, calc_N_AOD, readatom, split_trans_name
from barak.pyvpfit import readf26
from plotspec.utils import \
     process_options, plot_velocity_regions, process_Rfwhm, plot_tick_vel, \
     ATMOS, lines_from_f26

# expand continuum adjsutments this many Ang either side of the
# fitting region.

ATOMDAT = readatom()
HIwavs = ATOMDAT['HI']['wa'][::-1]

expand_cont_adjustment = 0

np.seterr(divide='ignore', invalid='ignore')
unrelated = []
#         ( 3863.451, 3865.529),
#         ( 3855.399, 3859.330),
#         ( 4075.662, 4076.668),
#         ( 4079.430, 4082.960),
#         ( 3906.116, 3908.287),
#         ( 3898.097, 3899.218),
#         ( 4509.955, 4512.281),
#         ( 4503.099, 4507.387),
#         ( 4532.218, 4544.106),
Exemple #6
0
    def mk_line_list_fits_table(outfil=None,XIDL=False):
        from barak import absorb as ba
    
        if XIDL is True:
            lindat =  os.getenv('XIDL_DIR')+'/Spec/Lines/Lists/grb.lst'
            finedat = os.getenv('XIDL_DIR')+'/Spec/Lines/Lists/fine_strct.lst'
        else:
            lindat = 'grb.lst'  # This pulls from xastropy/data/spec_lines first
            finedat = os.getenv('XIDL_DIR')+'/Spec/Lines/Lists/fine_strct.lst'
            
        # Read XIDL line list
        llist = Abs_Line_List(lindat)
        ndata = len(llist.data)
    
        # Add columns
        from astropy.table import Column
        gamma = Column(np.zeros(ndata),name='gamma')
        A = Column(np.zeros(ndata),name='A') # Einstein coefficient
        j = Column(np.zeros(ndata),name='j') # Tot ang mom (z projection)
        Ex = Column(np.zeros(ndata),name='Ex') # Excitation energy (cm^-1)
        Elow = Column(np.zeros(ndata),name='Elow') # Energy of lower level
        Eup = Column(np.zeros(ndata),name='Eup') # Energy of upper level
        Z = Column(np.zeros(ndata,dtype='int'),name='Z') # Atomic number
        ion = Column(np.zeros(ndata,dtype='int'),name='ion') # Ionic state
    
        llist.data.add_columns([gamma,A,j,Ex,Elow,Eup,Z,ion])
    
        # Z,ion
        for ii in range(ndata):
            nm = llist.data['name'][ii]
            # Z
            if nm[1] == 'I' or nm[1] == 'V': 
                ielm = 1
            else:
                ielm = 2
            elm = nm[:ielm]
            try:
                Zv = ELEMENTS[elm].number
            except KeyError:
                if elm in ['CO','CC','HH']: # Molecules
                    Zv = 999
                elif elm in ['D']: # Deuterium
                    Zv = 1
                else:
                    xdb.set_trace()
            llist.data['Z'][ii] = Zv
            # ion
            ispc = nm.find(' ')
            cion = nm[ielm:ispc].strip('*')
            if len(cion) == 0:
                ionv =0
            else:
                ionv = roman.fromRoman(cion)
            llist.data['ion'][ii] = ionv
    
        # #######
        # Fill in matches
        
        # Read atom.dat using barak
        atom, atomflat = ba.readatom(flat=True)
        #pdb.set_trace()
        llist.sources.append('atom.dat') # I wish I could pull this from ba.readatom
    
        # Fine structure
        fdata = ascii.read(finedat)
        llist.sources.append(finedat)

        # Loop
        for ii in range(ndata):
            # Atom.dat
            mt = np.where(np.fabs(llist.data['wrest'][ii]-atomflat['wa']) < 1e-3)[0]
            if len(mt) > 0: llist.data['gamma'][ii] = atomflat['gam'][mt[0]] # Takes the first match
    
            # Fine structure
            mt = np.where(np.fabs(llist.data['wrest'][ii]-fdata['wrest']) < 1e-3)[0]
            if len(mt) > 0:
                llist.data['A'][ii] = fdata['A'][mt[0]] # Takes the first match
        
        # Output file
        if outfil is None:
            outfil = xa_path+'/data/atomic/spec_atomic_lines.fits'
    
        # Header
        '''
        prihdr = fits.Header()
        prihdr['COMMENT'] = "Above are the data sources"
        for ii in range(len(llist.sources)):
        card = 'SOURCE'+str(ii+1)
        prihdr[card] = llist.sources[ii]
        prihdu = fits.PrimaryHDU(header=prihdr)
    
        # Table
        table_hdu = fits.BinTableHDU.from_columns(np.array(llist.data.filled()))
    
        '''
        # Write
        llist.data.write(outfil, overwrite=True, format='fits')
        print('mk_line_list: Wrote {:s}'.format(outfil))
Exemple #7
0
Fichier : model.py Projet : nhmc/H2
from barak.io import writetxt

import pylab as pl

pl.rc('xtick', labelsize=11)
pl.rc('xtick.major', size=3, pad=5)
pl.rc('xtick.minor', size=1.5)
pl.rc('ytick', labelsize=11)
pl.rc('ytick.major', size=3, pad=4)
pl.rc('ytick.minor', size=1.5)

# divide wavelength pixels into this many sub-pixels
nwadiv = 10
# cache for spectra
SPECTRA = {}
atom = readatom(molecules=True)
options = {}
options['wa_vary'] = True

###################################################################
# Read initial model parameters along with fitting regions from vpfit
# f26-style file
###################################################################


def readf26file(filename):
    """ Read a f26 style file, and return with regions sorted by
    minimum wavelength.
    """
    vpin = readf26(filename)
    isort = np.argsort([r.wmin for r in vpin.regions])
Exemple #8
0
def process_options(args):
    opt = adict()
    filename = os.path.abspath(__file__).rsplit('/', 1)[0] + '/default.cfg'
    opt = parse_config(filename)
    if os.path.lexists('./plot.cfg'):
        opt = parse_config('./plot.cfg', opt)

    opt.atom = readatom(molecules=True)

    if opt.Rfwhm is not None:
        if isinstance(opt.Rfwhm, basestring):
            if opt.Rfwhm == 'convolve_with_COS_FOS':
                if convolve_with_COS_FOS is None:
                    raise ValueError('convolve_with_COS_FOS() not available')
                print('Using tailored FWHM for COS/FOS data')
                opt.Rfwhm = 'convolve_with_COS_FOS'
            elif opt.Rfwhm.endswith('fits'):
                print('Reading Resolution FWHM from', opt.Rfwhm)
                res = readtabfits(opt.Rfwhm)
                opt.Rfwhm = res.res / 2.354
            else:
                print('Reading Resolution FWHM from', opt.Rfwhm)
                fh = open(opt.Rfwhm)
                opt.Rfwhm = 1 / 2.354 * np.array([float(r) for r in fh])
                fh.close()
        else:
            opt.Rfwhm = float(opt.Rfwhm)

    if opt.features is not None:
        print('Reading feature list from', opt.features)
        opt.features = readtabfits(opt.features)

    if opt.f26 is not None:
        name = opt.f26
        print('Reading ions and fitting regions from', name)
        opt.f26 = readf26(name)
        opt.f26.filename = name

    if opt.transitions is not None:
        print('Reading transitions from', opt.transitions)
        fh = open(opt.transitions)
        trans = list(fh)
        fh.close()
        temp = []
        for tr in trans:
            tr = tr.strip()
            if tr and not tr.startswith('#'):
                junk = tr.split()
                tr = junk[0] + ' ' + junk[1]
                t = findtrans(tr, atomdat=opt.atom)
                temp.append(dict(name=t[0], wa=t[1][0], tr=t[1]))
        opt.linelist = temp
    else:
        opt.linelist = readtxt(get_data_path() + 'linelists/qsoabs_lines',
                        names='wa,name,select')

    if opt.f26 is None and opt.taulines is not None:
        print('Reading ions from', opt.taulines)
        fh = open(opt.taulines)
        lines = []
        for row in fh:
            if row.lstrip().startswith('#'):
                continue
            items = row.split()
            lines.append([items[0]] + list(map(float, items[1:])))
        fh.close()
        opt.lines = lines

    if opt.show_regions is None:
        opt.show_regions = True

    if hasattr(opt, 'aodname'):
        opt.aod = Table.read(opt.aodname)

    return opt
Exemple #9
0
from barak.absorb import readatom, find_tau, findtrans, split_trans_name
from barak.sed import vel_from_wa, make_constant_dv_wa_scale
from barak.utilities import indexnear, between
from barak.plot import puttext, get_fig_axes
import barak.spec
from cStringIO import StringIO
from subprocess import call
 
import numpy as np
import pylab as plt

import velplot.velplot
reload(velplot.velplot)
from velplot.velplot import plot_tick_vel, read_transitions

ATOMDAT = readatom()

lw_model = 0.7
lw_data = 1

vzero = -219

#plt.ioff()
plt.rc('font', size=11)
plt.rc('xtick', labelsize=8.5)
plt.rc('ytick', labelsize=8.5)
plt.rc('xtick.major', size=3)      # major tick size in points
plt.rc('xtick.minor', size=1.5)      # minor tick size in points
plt.rc('xtick.major', pad=3.5)     # distance to major tick label in points
plt.rc('ytick.major', size=3)      # major tick size in points
plt.rc('ytick.minor', size=1.5)      # minor tick size in points
Exemple #10
0
# these are the upper and lower limits on the flat prior ranges. these
# will be used to generate guess positions for the sampler. If you get
# these wrong, the sampler can get confused (poor acceptance fractions
# or walkers getting lost in very low likelihood regions of parameter
# space). It will take some trial and error and inspection of the
# burn-in parameter distribution to find input ranges that give
# plausible results.

P.min = 2.4997, 12.5, 5, 2.500, 12.5, 5
P.max = 2.5003, 16.5, 70, 2.501, 15.5, 70

Npar = len(P.names)

# function to generate the model at each data point from parameters

atom = readatom()
trans = atom['HI']


def model(*par):
    tau = np.zeros_like(X)
    for i in xrange(len(par) // 3):
        z, logN, b = par[3 * i:3 * i + 3]
        tau += calc_iontau(X, trans, z + 1, logN, b)
    return np.exp(-tau)


def make_data(ptrue):
    """ Generate the data x, ydata, ysigma (in a real problem these
    would usually all be given)."""
Exemple #11
0
from barak.pyvpfit import readf26
from barak.absorb import findtrans, readatom, find_tau
from barak.constants import c_kms
from barak.spec import make_constant_dv_wa_scale, convolve_constant_dv
from barak.convolve import convolve_psf

import pylab as pl
import numpy as np

f26 = readf26(f26name)
atomdat = readatom(molecules=1)
spfilename = ''
trfilename = ''
vmin = vmax = 399
wadiv = None
Rfwhm = 6.6
osc = False
residuals = True
redshift = 0.56

unrelated = []
#         ( 3863.451, 3865.529), 
#         ( 3855.399, 3859.330), 
#         ( 4075.662, 4076.668), 
#         ( 4079.430, 4082.960), 
#         ( 3906.116, 3908.287), 
#         ( 3898.097, 3899.218), 
#         ( 4509.955, 4512.281), 
#         ( 4503.099, 4507.387), 
#         ( 4532.218, 4544.106), 
#         ( 4314.625, 4315.922), 
Exemple #12
0
# these are the upper and lower limits on the flat prior ranges. these
# will be used to generate guess positions for the sampler. If you get
# these wrong, the sampler can get confused (poor acceptance fractions
# or walkers getting lost in very low likelihood regions of parameter
# space). It will take some trial and error and inspection of the
# burn-in parameter distribution to find input ranges that give
# plausible results.

P.min = 2.4997, 12.5, 5, 2.500, 12.5, 5
P.max = 2.5003, 16.5, 70, 2.501, 15.5, 70

Npar = len(P.names)

# function to generate the model at each data point from parameters

atom = readatom()
trans = atom['HI']
def model(*par):
    tau = np.zeros_like(X)
    for i in xrange(len(par)//3):
        z,logN,b = par[3*i:3*i+3]
        tau += calc_iontau(X, trans, z+1, logN, b)
    return np.exp(-tau)


def make_data(ptrue):
    """ Generate the data x, ydata, ysigma (in a real problem these
    would usually all be given)."""

    # for generating the wavelength scale
    vrange = 500.
Exemple #13
0
from astropy.constants import c as C
from scipy.ndimage import uniform_filter as uf
from astro.sampledist import RanDist
from pyntejos.utils import find_edges, clean_array
from astropy import constants as const
import astropy.units as u
from barak.absorb import readatom
from linetools.analysis import absline as ltaa
from linetools.lists.linelist import LineList

#Constant
e2_me_c = ((const.e.esu)**2 / (const.c.to('cm/s') * const.m_e.to('g'))
           ).value  # from Draine (eq. 9.8 and 9.9)

#read atomic data
atomdat = readatom('/home/ntejos/software/vpfit10/atom.dat')


def get_tau0_peak(wa0, fosc, logN, b):
    """Get the value of the optical depth at the line center,
    tau0. From Draine 2011 (see Chapter 9). It neglects estimulated
    emission which is fine for IGM or ISM except for radio-frecuency
    transitions.
    
    Inputs
    ------
    wa0:   rest-frame wavelenght of the transition in A
    fosc:  oscillator strenght for the transition
    logN:  log10 of the column density in cm^-2
    b:     Doppler parameter in km/s
    
Exemple #14
0
import matplotlib.pyplot as pl
from astropy.constants import c as C
from scipy.ndimage import uniform_filter as uf
from astro.sampledist import RanDist
from pyntejos.utils import find_edges,clean_array
from astropy import constants as const
import astropy.units as u
from barak.absorb import readatom
from linetools.analysis import absline as ltaa
from linetools.lists.linelist import LineList

#Constant
e2_me_c = ((const.e.esu)**2/(const.c.to('cm/s')*const.m_e.to('g'))).value # from Draine (eq. 9.8 and 9.9)

#read atomic data
atomdat = readatom('/home/ntejos/software/vpfit10/atom.dat')


def get_tau0_peak(wa0,fosc,logN,b):
    """Get the value of the optical depth at the line center,
    tau0. From Draine 2011 (see Chapter 9). It neglects estimulated
    emission which is fine for IGM or ISM except for radio-frecuency
    transitions.
    
    Inputs
    ------
    wa0:   rest-frame wavelenght of the transition in A
    fosc:  oscillator strenght for the transition
    logN:  log10 of the column density in cm^-2
    b:     Doppler parameter in km/s