コード例 #1
0
ファイル: lls_literature.py プロジェクト: ntejos/xastropy
def kacprzak12():
    '''Kacprzak, G. et al. 2012, MNRAS, 427, 3029-3043
    TON 153
    Taken from Table 1 by JXP
    NHI from Churchill+2007
    RA/DEC from Simbad
    '''
    # Setup
    radec = xor.stod1('J131956.2209+272808.271')
    lls = LLSSystem(name='TON153_z1.002',
                    RA=radec[0],
                    Dec=radec[1],
                    zem=0.6610,
                    zabs=1.0023,
                    vlim=[-250., 200.] * u.km / u.s,
                    NHI=18.30,
                    sigNHI=np.array([0.30, 0.30]))
    # Table 1 (total)
    ion_dict = {}
    ion_dict['Mg II'] = dict(clm=13.11, sig_clm=0.07, flg_clm=1, Z=12, ion=2)
    ion_dict['Mg I'] = dict(clm=11.54, sig_clm=0.06, flg_clm=1, Z=12, ion=1)
    ion_dict['Si I'] = dict(clm=11.8, sig_clm=0.00, flg_clm=3, Z=14, ion=1)
    ion_dict['Si II'] = dict(clm=13.16, sig_clm=0.11, flg_clm=1, Z=14, ion=2)
    ion_dict['Si IV'] = dict(clm=12.4, sig_clm=0.0, flg_clm=3, Z=14, ion=4)
    ion_dict['C II'] = dict(clm=13.39, sig_clm=0.0, flg_clm=2, Z=6, ion=2)
    ion_dict['C III'] = dict(clm=14.20, sig_clm=0.05, flg_clm=1, Z=6, ion=3)
    ion_dict['C III'] = dict(clm=14.41, sig_clm=0.05, flg_clm=1, Z=6, ion=4)
    ion_dict['O VI'] = dict(clm=14.49, sig_clm=0.05, flg_clm=1, Z=8, ion=6)
    # Finish
    lls._ionclms = IonClms(idict=ion_dict)
    lls.Refs.append('Kcz12')
    return lls
コード例 #2
0
ファイル: lls_literature.py プロジェクト: ntejos/xastropy
def zonak2004():
    '''Zoank, S. et al. 2004, ApJ, 2004, 606, 196
    PG1634+706
    HST+Keck spectra
    MgII, SiIV, SiIII from Table 2.  Summing Subsystems A (Model 2) and B
       Errors estimated by JXP (not reported)
       SiIII in A may be a model
       SiIV in B may be a model
    Total NHI from LL. Taken from Fig 3 caption.  
       Error estimated by JXP 
    Not all EWs in Table 1 included
    Adopting their M/H
    '''
    # Setup
    radec = xor.stod1('J163428.9897+703132.422')  # SIMBAD
    lls = LLSSystem(name='PG1634+706_z1.041',
                    RA=radec[0],
                    Dec=radec[1],
                    zem=1.337,
                    zabs=1.0414,
                    vlim=[-200., 30.] * u.km / u.s,
                    NHI=17.23,
                    MH=-1.4,
                    sigNHI=np.array([0.15, 0.15]))
    # SubSystems
    lls.mk_subsys(2)
    # Abundances
    adict = dict(MgII={
        'clm': log_sum([11.45, 11.90, 12.02, 11.68]),
        'sig_clm': 0.05,
        'flg_clm': 1
    },
                 SiIII={
                     'clm': log_sum([12.5, 12.5, 12.8, 12.7]),
                     'sig_clm': 0.25,
                     'flg_clm': 1
                 },
                 SiIV={
                     'clm': log_sum([10.9, 10.8, 11.2, 11.1]),
                     'sig_clm': 0.15,
                     'flg_clm': 1
                 })
    lls.subsys['A']._ionclms = IonClms(idict=adict)
    bdict = dict(SiIII={
        'clm': log_sum([11.8, 12.8, 12.4]),
        'sig_clm': 0.15,
        'flg_clm': 1
    },
                 SiIV={
                     'clm': log_sum([11.2, 12.2, 11.8]),
                     'sig_clm': 0.15,
                     'flg_clm': 1
                 })
    lls.subsys['B']._ionclms = IonClms(idict=bdict)
    # Total
    lls._ionclms = lls.subsys['A']._ionclms.sum(lls.subsys['B']._ionclms)
    lls.Refs.append('Zon04')
    # Return
    return lls
コード例 #3
0
    def get_qso(self,inp):
        '''Grab a QSO from the SDSS database
        Similar to sdss_objinf in XIDL

        Parameters:
        ----------
        inp: tuple or str
          tuple: (PLATE,FIBER)
          string (JXXXXXX.X+XXXXXX.X format)

        Returns:
        ----------
        row: QTable
          Single line from SDSS DR7 table
        '''
        # Branch on inp
        if isinstance(inp,tuple):
            mt = np.where( (self._data['PLATE']==inp[0]) & 
                (self._data['FIBERID']==inp[1]))[0]
        elif isinstance(inp,basestring):
            # Get RA/DEC
            radec = xor.stod1(inp)
            # Match
            mt = np.where( (np.abs(self._data['RAOBJ']-radec[0].value)<5e-3) & 
                (np.abs(self._data['DECOBJ']-radec[1].value)<5e-3))[0]
        else:
            raise ValueError('SDSS_QUASAR: Bad input type')

        # Parse and return
        if len(mt) == 0:
            if isinstance(inp,tuple):
                if self.verbose:
                    print('Plate={:d}, FIBERID={:d} not found in SDSS-{:s}'.format(
                        inp[0],inp[1],self._version))
            elif isinstance(inp,basestring):
                if self.verbose:
                    print('Quasar {:s} not found in SDSS-{:s}'.format(inp,self._version))
            return
        elif len(mt) == 1:
            self.index = mt[0] # Useful for SdssQso class
            return self._data[mt]
        else:
            raise ValueError('Not expecting this')
コード例 #4
0
ファイル: quasars.py プロジェクト: banados/xastropy
    def get_qso(self, inp):
        """Grab a QSO from the SDSS database
        Similar to sdss_objinf in XIDL

        Parameters:
        ----------
        inp: tuple or str
          tuple: (PLATE,FIBER)
          string (JXXXXXX.X+XXXXXX.X format)

        Returns:
        ----------
        row: QTable
          Single line from SDSS DR7 table
        """
        # Branch on inp
        if isinstance(inp, tuple):
            mt = np.where((self._data["PLATE"] == inp[0]) & (self._data["FIBERID"] == inp[1]))[0]
        elif isinstance(inp, basestring):
            # Get RA/DEC
            radec = xor.stod1(inp)
            # Match
            mt = np.where(
                (np.abs(self._data["RAOBJ"] - radec[0].value) < 5e-3)
                & (np.abs(self._data["DECOBJ"] - radec[1].value) < 5e-3)
            )[0]
        else:
            raise ValueError("SDSS_QUASAR: Bad input type")

        # Parse and return
        if len(mt) == 0:
            if isinstance(inp, tuple):
                if self.verbose:
                    print("Plate={:d}, FIBERID={:d} not found in SDSS-{:s}".format(inp[0], inp[1], self._version))
            elif isinstance(inp, basestring):
                if self.verbose:
                    print("Quasar {:s} not found in SDSS-{:s}".format(inp, self._version))
            return
        elif len(mt) == 1:
            self.index = mt[0]  # Useful for SdssQso class
            return self._data[mt]
        else:
            raise ValueError("Not expecting this")
コード例 #5
0
ファイル: lls_literature.py プロジェクト: ntejos/xastropy
def peroux06a():
    '''Peroux, C. et al. 2006a, MNRAS, 372, 369
    SDSS J0134+0051
    One of her sample
    Metal columns taken by JXP from Table 2 (no online data)
    Total NHI from damping wings
    '''
    # Setup
    radec = xor.stod1('J013405.75+005109.4')  # SDSS Name
    lls = LLSSystem(name='SDSSJ0134+0051_z0.842',
                    RA=radec[0],
                    Dec=radec[1],
                    zem=1.522,
                    zabs=0.842,
                    vlim=[-150., 150.] * u.km / u.s,
                    NHI=19.93,
                    sigNHI=np.array([0.15, 0.15]))
    #  Table 2
    ion_dict = {}
    N = np.sum(np.array([5.56, 12.6, 13.7, 23.5, 61.4, 39.8, 6, 9.14]) * 1e10)
    sig = np.sqrt(
        np.sum((np.array([2.32, 3.1, 3.68, 4.13, 8.02, 6.65, 3.37, 2.82]) *
                1e10)**2))
    ion_dict['Mg I'] = dict(clm=np.log10(N),
                            sig_clm=sig / N / np.log(10),
                            flg_clm=1,
                            Z=12,
                            ion=1)
    ion_dict['Mg II'] = dict(clm=np.log10(5e13),
                             sig_clm=0.,
                             flg_clm=2,
                             Z=12,
                             ion=2)
    N = np.sum(
        np.array([8.17, 4.28, 32.1, 125, 710, 301, 893, 600, 263, 65.7]) *
        1e11)
    sig = np.sqrt(
        np.sum((np.array(
            [2.63, 1.40, 2.37, 8.6, 53.2, 28.4, 73.5, 61.7, 14.0, 2.95]) *
                1e11)**2))
    ion_dict['Fe II'] = dict(clm=np.log10(N),
                             sig_clm=sig / N / np.log(10),
                             flg_clm=1,
                             Z=26,
                             ion=2)
    sig = np.sqrt(np.sum((np.array([3.72, 1.84, 2.36, 3.83]) * 1e11)**2))
    ion_dict['Zn II'] = dict(clm=np.log10(2 * sig),
                             sig_clm=0.,
                             flg_clm=3,
                             Z=30,
                             ion=2)
    sig = np.sqrt(np.sum((np.array([19.4, 9.79]) * 1e11)**2))
    ion_dict['Cr II'] = dict(clm=np.log10(2 * sig),
                             sig_clm=0.,
                             flg_clm=3,
                             Z=24,
                             ion=2)
    # Not including MnII.  Appears as a detection but also given as a limit..

    # Finish
    lls._ionclms = IonClms(idict=ion_dict)
    lls.Refs.append('Prx06a')
    return lls
コード例 #6
0
ファイル: lls_literature.py プロジェクト: ntejos/xastropy
def tripp2005():
    '''Tripp, T. et al. 2005, ApJ, 2005, 619, 714
    PG 1216+069 (LLS in Virgo)
    HST/STIS, FUSE
    Metal columns parsed from Tables 2 and 3
    Total NHI from damping wings
    M/H from O/H
    '''
    # Grab ASCII files from ApJ
    tab_fils = [
        xa_path + "/data/LLS/tripp2005.tb3.ascii",
        xa_path + "/data/LLS/tripp2005.tb2.ascii"
    ]
    urls = [
        'http://iopscience.iop.org/0004-637X/619/2/714/fulltext/60797.tb3.txt',
        'http://iopscience.iop.org/0004-637X/619/2/714/fulltext/60797.tb2.txt'
    ]
    for jj, tab_fil in enumerate(tab_fils):
        chk_fil = glob.glob(tab_fil)
        if len(chk_fil) > 0:
            tab_fil = chk_fil[0]
        else:
            url = urls[jj]
            print('LLSSurvey: Grabbing table file from {:s}'.format(url))
            f = urllib2.urlopen(url)
            with open(tab_fil, "wb") as code:
                code.write(f.read())
    # Setup
    radec = xor.stod1('J121920.9320+063838.476')  # SIMBAD
    lls = LLSSystem(name='PG1216+069_z0.006',
                    RA=radec[0],
                    Dec=radec[1],
                    zem=0.3313,
                    zabs=0.00632,
                    vlim=[-100., 100.] * u.km / u.s,
                    NHI=19.32,
                    MH=-1.6,
                    sigNHI=np.array([0.03, 0.03]))
    #lls.mk_subsys(2)

    # Columns
    # Start with Table 3 (VPFIT)
    with open(tab_fils[0], 'r') as f:
        flines3 = f.readlines()
    ion_dict = {}
    for iline in flines3:
        if (len(iline.strip()) == 0):
            continue
        isplit = iline.split('\t')
        # Ion
        flg = 2
        if (len(isplit[0].strip()) > 0):  # & (isplit[0][0] not in ['1','2']):
            ipos = isplit[0].find('1')
            ionc = isplit[0][0:ipos - 1].strip()
            try:
                Zion = xai.name_ion(ionc)
            except KeyError:
                xdb.set_trace()
            flg = 1
        # Column
        csplit = isplit[3].split(' ')
        clm = float(csplit[0])
        sig = float(csplit[2])
        if flg == 1:
            ion_dict[ionc] = dict(clm=clm,
                                  sig_clm=sig,
                                  flg_clm=1,
                                  Z=Zion[0],
                                  ion=Zion[1])
        else:  # Add it in
            tmp_dict = dict(clm=clm,
                            sig_clm=sig,
                            flg_clm=1,
                            Z=Zion[0],
                            ion=Zion[1])
            logN, siglogN = xiai.sum_logN(ion_dict[ionc], tmp_dict)
            ion_dict[ionc]['clm'] = logN
            ion_dict[ionc]['sig_clm'] = siglogN
    ions = ion_dict.keys()

    # Now Table 2 for the extras
    with open(tab_fils[1], 'r') as f:
        flines2 = f.readlines()
    # Trim the first 10 lines
    flines2 = flines2[10:]
    # Loop
    for iline in flines2:
        isplit = iline.split('\t')
        #
        ionc = isplit[0].strip()
        if (len(ionc) == 0) or (ionc in ions):
            continue
        #
        Zion = xai.name_ion(ionc)
        ion_dict[ionc] = dict(Z=Zion[0], ion=Zion[1], sig_clm=0.)
        if isplit[4][0] == '<':
            ion_dict[ionc]['clm'] = float(isplit[4][1:])
            ion_dict[ionc]['flg_clm'] = 3
        else:
            raise ValueError('Should not get here')

    # Finish
    lls._ionclms = IonClms(idict=ion_dict)
    lls.Refs.append('Tri05')
    return lls
コード例 #7
0
ファイル: lls_literature.py プロジェクト: ntejos/xastropy
def battisti12():
    '''Battisti, A. et al. 2012, ApJ, 744, 93
    HST/COS
    QSO info from Table 1
    Metal columns parsed from Table 3
    NHI from Lya
    '''
    all_lls = []
    # Grab ASCII files from ApJ
    tab_fils = [
        xa_path + "/data/LLS/battisti12.tb1.ascii",
        xa_path + "/data/LLS/battisti12.tb3.ascii"
    ]
    urls = [
        'http://iopscience.iop.org/0004-637X/744/2/93/suppdata/apj413924t1_ascii.txt',
        'http://iopscience.iop.org/0004-637X/744/2/93/suppdata/apj413924t3_ascii.txt'
    ]
    for jj, tab_fil in enumerate(tab_fils):
        chk_fil = glob.glob(tab_fil)
        if len(chk_fil) > 0:
            tab_fil = chk_fil[0]
        else:
            url = urls[jj]
            print('LLSSurvey: Grabbing table file from {:s}'.format(url))
            f = urllib2.urlopen(url)
            with open(tab_fil, "wb") as code:
                code.write(f.read())
    # QSO info
    with open(tab_fils[0], 'r') as f:
        flines1 = f.readlines()
    # Grab RA/DEC
    all_idict = []
    for iline in flines1:
        if iline[0:2] != 'SD':
            continue
        # Parse
        isplit = iline.split('\t')
        name = isplit[0].split(' ')[1]
        radec = xor.stod1(name)
        zem = float(isplit[1].strip())
        zabs = float(isplit[2].strip())
        NHI = float(isplit[3].strip()[0:4])
        sigNHI = np.array([float(isplit[3].strip()[11:])] * 2)
        # Save
        lls = LLSSystem(name=name,
                        RA=radec[0],
                        Dec=radec[1],
                        zem=zem,
                        zabs=zabs,
                        NHI=NHI,
                        sigNHI=sigNHI)
        #
        all_lls.append(lls)
        all_idict.append({})

    # Abundances
    with open(tab_fils[1], 'r') as f:
        flines3 = f.readlines()
    flines3 = flines3[5:]
    ion = None
    for iline in flines3:
        if ion == 'Ni II':
            break
        isplit = iline.split('\t')
        if isplit[0] == 'C II*':  # Skipping CII*
            continue
        # ion
        ipos = -1
        while (isplit[0][ipos] not in ['I', 'V']):
            ipos -= 1
        ion = isplit[0][0:ipos + 1 + len(isplit[0])]
        Zion = xai.name_ion(ion)
        # Loop on systems
        for kk, iis in enumerate(isplit[1:-1]):
            if iis.strip()[0] == '.':
                continue
            all_idict[kk][ion] = dict(Z=Zion[0], ion=Zion[1], sig_clm=0.)
            if iis[0] == '>':
                all_idict[kk][ion]['flg_clm'] = 2
                all_idict[kk][ion]['clm'] = float(iis[1:6])
            elif iis[0] == '<':
                all_idict[kk][ion]['flg_clm'] = 3
                all_idict[kk][ion]['clm'] = float(iis[1:])
            else:
                all_idict[kk][ion]['flg_clm'] = 1
                all_idict[kk][ion]['clm'] = float(iis[0:5])
                all_idict[kk][ion]['sig_clm'] = float(iis[-4:])

    # Return SLLS only
    for kk, lls in enumerate(all_lls):
        try:
            lls._ionclms = IonClms(idict=all_idict[kk])
        except ValueError:
            xdb.set_trace()
        lls.Refs.append('Bat12')
    fin_slls = [ills for ills in all_lls if ills.NHI < 20.3]
    return fin_slls
コード例 #8
0
ファイル: lls_literature.py プロジェクト: ntejos/xastropy
def tumlinson11():
    '''Tumlinson, J. et al. 2011, ApJ, 733, 111
    J1009+0713
    HST/COS
    Metal columns parsed from Table 1
    NHI from LL+Lyman series (uncertain)
    '''
    # Grab ASCII file from ApJ
    tab_fil = xa_path + "/data/LLS/tumlinson11.tb1.ascii"
    url = 'http://iopscience.iop.org/0004-637X/733/2/111/suppdata/apj388927t1_ascii.txt'
    chk_fil = glob.glob(tab_fil)
    if len(chk_fil) > 0:
        tab_fil = chk_fil[0]
    else:
        print('LLSSurvey: Grabbing table file from {:s}'.format(url))
        f = urllib2.urlopen(url)
        with open(tab_fil, "wb") as code:
            code.write(f.read())
    # Setup
    radec = xor.stod1('J100902.06+071343.8')  # From paper
    lls = LLSSystem(name='J1009+0713_z0.356',
                    RA=radec[0],
                    Dec=radec[1],
                    zem=0.456,
                    zabs=0.3558,
                    vlim=[-200., 250.] * u.km / u.s,
                    NHI=18.4,
                    sigNHI=np.array([0.41, 0.41]))
    #lls.mk_subsys(2)

    # Columns
    # Start with Table 3 (VPFIT)
    with open(tab_fil, 'r') as f:
        flines1 = f.readlines()
    # Trim
    flines1 = flines1[18:]
    #
    ion_dict = {}
    line_dict = dict(OI='1302',
                     OVI='1038',
                     MgII='2803^b',
                     SiII='1190',
                     CaII='3934',
                     FeII='2586')
    ion = None
    for iline in flines1:
        isplit = iline.split('\t')
        if ion == 'FeIII':  # Last line
            break
        # Ion
        is2 = isplit[0].split(' ')
        ion = is2[0] + is2[1]
        try:
            gdl = line_dict[ion]
        except:
            pass
            #print('Taking {:s}'.format(isplit[0]))
        else:
            if is2[2] != gdl:
                continue
        Zion = xai.name_ion(ion)
        ion_dict[ion] = dict(clm=0.,
                             sig_clm=0.,
                             flg_clm=0,
                             Z=Zion[0],
                             ion=Zion[1])
        # Combine components [could replace with SubSystems some day]
        for iis in isplit[1:-1]:
            # Upper limit
            if (iis.strip()[0] == '<') & (ion_dict[ion]['flg_clm'] == 0):
                ion_dict[ion]['flg_clm'] = 3
                ion_dict[ion]['clm'] = float(iis[1:])
            elif (iis.strip()[0] == '>'):  # Saturated
                ion_dict[ion]['flg_clm'] = 2
                ion_dict[ion]['clm'] = log_sum(
                    [ion_dict[ion]['clm'],
                     float(iis[1:5])])
            elif iis.strip()[0] in ['.', '<']:
                pass
            else:
                if ion_dict[ion]['flg_clm'] == 2:  # Add to saturated
                    ion_dict[ion]['clm'] = log_sum(
                        [ion_dict[ion]['clm'],
                         float(iis[0:4])])
                else:
                    ion_dict[ion]['flg_clm'] = 1
                    obj = dict(clm=float(iis[0:4]), sig_clm=float(iis[-4:]))
                    # Add
                    N, sig = xiai.sum_logN(ion_dict[ion], obj)
                    ion_dict[ion]['clm'] = N
                    ion_dict[ion]['sig_clm'] = sig
    # Finish
    lls._ionclms = IonClms(idict=ion_dict)
    lls.Refs.append('Tum11')
    return lls
コード例 #9
0
ファイル: lls_literature.py プロジェクト: ntejos/xastropy
def meiring09():
    '''Meiring et al. 2009, MNRAS, 393, 1513
    SLLS with Magellan
    Abundances from Table 3 from astro-ph (LateX) by JXP [AODM]
    RA/DEC from Table 1
    '''
    all_lls = []
    # Table 1
    tab_fil = xa_path + "/data/LLS/meiring09.tb1.ascii"
    with open(tab_fil, 'r') as f:
        flines1 = f.readlines()
    # Grab RA/DEC
    qso_dict = {}
    for iline in flines1:
        if iline[0:3] in [' QS', '\hl', '$\\c', ' J2', '   ']:
            continue
        # Parse
        isplit = iline.split('&')
        #xdb.set_trace()
        if '$' in isplit[3].strip():
            isplit[3] = '-' + (isplit[3].strip())[3:]
        radec = xor.stod1((isplit[2], isplit[3]))
        # zem
        zem = float(isplit[5].strip())
        # Save
        qso_dict[isplit[0].strip()] = dict(RA=radec[0], Dec=radec[1], zem=zem)

    # Abundances (AODM)
    # Table 3
    tab_fil = xa_path + "/data/LLS/meiring09.tb3.ascii"
    with open(tab_fil, 'r') as f:
        flines3 = f.readlines()
    #
    ion_dict = {}
    for iline in flines3:
        if iline[0:2] in ['\h', '  ']:
            continue
        # Parse
        isplit = iline.split('&')
        # Ions
        if iline[0:2] == 'QS':
            ioncs = []
            Zions = []
            for iis in isplit[3:-1]:  # Skipping HI
                # Parse
                #is2 = iis.split('\\')
                #ip2 = is2[2].find('}')
                ionc = iis.strip()
                # Zion
                Zion = xai.name_ion(ionc)
                # Append
                ioncs.append(ionc)
                Zions.append(Zion)
            continue
        if iline[0] == 'Q':
            # QSO
            qso = isplit[0].strip()
            if qso[-1] in ['A', 'B', 'C']:
                qso = qso[0:-1]
            # zabs and name
            zabs = float(isplit[1].strip())
            qso_dict[qso]['name'] = qso + 'z_{:.3f}'.format(zabs)
            qso_dict[qso]['zabs'] = zabs
            # NHI
            is2 = isplit[2].strip()
            if is2[0] == '$':
                qso_dict[qso]['NHI'] = 99.99  # THROW OUT Q1436-0051B
                qso_dict[qso]['sigNHI'] = np.array([0., 0.])
            else:
                qso_dict[qso]['NHI'] = float(is2[0:5])
                qso_dict[qso]['sigNHI'] = np.array([float(is2[10:])] * 2)
            #if qso_dict[qso]['NHI'] >= 20.3:
            #    print('Uh oh.  DLA')
            # Generate LLS
            lls = LLSSystem(**qso_dict[qso])
            continue
        else:
            # ADOM Columns
            ion_dict = {}
            for kk, iis in enumerate(isplit[3:-1]):
                is2 = iis.strip()
                if is2[0:3] == '$>$':
                    ion_dict[ioncs[kk]] = dict(sig_clm=0.,
                                               flg_clm=2,
                                               Z=Zions[kk][0],
                                               ion=Zions[kk][1])
                    ion_dict[ioncs[kk]]['clm'] = float(is2[3:])
                elif is2[0:3] == '$<$':
                    ion_dict[ioncs[kk]] = dict(sig_clm=0.,
                                               flg_clm=3,
                                               Z=Zions[kk][0],
                                               ion=Zions[kk][1])
                    ion_dict[ioncs[kk]]['clm'] = float(is2[3:])
                elif len(is2) == 0:
                    pass
                else:
                    ion_dict[ioncs[kk]] = dict(flg_clm=1,
                                               Z=Zions[kk][0],
                                               ion=Zions[kk][1])
                    ion_dict[ioncs[kk]]['clm'] = float(is2[0:5])
                    ion_dict[ioncs[kk]]['sig_clm'] = float(is2[10:])
            # Finish
            lls._ionclms = IonClms(idict=ion_dict)
            lls.Refs.append('Mei09')
            all_lls.append(lls)

    # Return SLLS only
    fin_slls = [ills for ills in all_lls if ills.NHI < 20.3]
    return fin_slls
コード例 #10
0
ファイル: test_obs.py プロジェクト: ntejos/xastropy
def test_tocoord():
    from astropy.coordinates import SkyCoord
    radec = x_r.stod1('J103138.87+255902.3')
    coord = x_r.to_coord(radec)
    #
    assert isinstance(coord, SkyCoord)
コード例 #11
0
ファイル: test_obs.py プロジェクト: ntejos/xastropy
def test_stod():
    radec = x_r.stod1('J103138.87+255902.3')
    np.testing.assert_allclose(radec[0].value, 157.91195833333336)
    assert radec[0].unit == u.deg
コード例 #12
0
def main(inp, survey='2r', radec=None, deci=None, fpath=None, show_circ=True,
         EPOCH=0., DSS=None, BW=False, imsize=5.*astrou.arcmin, show_spec=False,
         OUT_TYPE='PDF'):
    '''
    Parameters:
    ---------
    inp: Input
       string or List of strings or List of several items
       'ra_dec_list.txt' -- ASCII file with columns of Name,RA,DEC and RA,DEC are string or float (deg)
        ['NAME_OF_TARG', '10:31:38.87', '+25:59:02.3']
        ['NAME_OF_TARG', 124.24*u.deg, -23.244*u.deg]
        ['NAME_OF_TARG', SkyCoord]
    radec: integer (0) [DEPRECATED!]
       Flag indicating type of input
       0 = ASCII file with columns of Name,RA,DEC and RA,DEC are string or float (deg)
       1 = List of string ['Name', 'RA', 'DEC']  
       2 = ['Name', ra_deg, dec_deg]
    BW: bool (False)
       B&W image?
    show_circ: bool (True)
       Show a yellow circle on the target
    show_spec: bool (False)
       Try to grab and show an SDSS spectrum 
    imsize: Quantity, optional
       Image size 
    OUT_TYPE: str, optional  
       File type -- 'PDF', 'PNG'
    '''
    reload(x_r)
    reload(xgs)
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm

    # Init
    if fpath is None:
        fpath = './'
    try:
        imsize=imsize.to('arcmin').value
    except AttributeError:
        raise AttributeError('finder: Input imsize needs to be an Angle')
    cradius = imsize / 50. 

    # Read in the Target list
    if isinstance(inp,basestring):
        ra_tab = get_coord(targ_file, radec=radec)
    else:
        ira_tab = {}
        ira_tab['Name'] = inp[0]
        if isinstance(inp[1],basestring):
            ra, dec = x_r.stod1((inp[1],inp[2]))
            ira_tab['RA'] = ra
            ira_tab['DEC'] = dec
        elif isinstance(inp[1],float):
            ira_tab['RA'] = inp[1] * astrou.deg
            ira_tab['DEC'] = inp[2]* astrou.deg
        elif isinstance(inp[1],SkyCoord):
            ira_tab['RA'] = inp[1].ra.deg
            ira_tab['DEC'] = inp[1].dec.deg
        else: # Should check it is a Quantity
            ira_tab['RA'] = inp[1]
            ira_tab['DEC'] = inp[2]
        # Strings
        ras,decs = x_r.dtos1((ira_tab['RA'],ira_tab['DEC']))
        ira_tab['RAS'] = ras
        ira_tab['DECS'] = decs
        # Make a list
        ra_tab = [ira_tab]

    # Grab ra, dec in decimal degrees
    if deci is not None: 
        return

    #xdb.set_trace()
    #x_r.stod(ra_tab) #ra_tab['RA'][q], ra_tab['DEC'][q], TABL)

    # Precess (as necessary)
    if EPOCH > 1000.:
        from astropy import units as u
        from astropy.coordinates import FK5
        from astropy.time import Time
        # Precess to 2000.
        tEPOCH = Time(EPOCH, format='jyear', scale='utc')
        # Load into astropy
        fk5c = FK5(ra=ra_tab['RA'], dec=ra_tab['DEC'], equinox=tEPOCH, unit=(u.degree,u.degree))
        # Precess
        newEPOCH = Time(2000., format='jyear', scale='utc')
        newfk5 = fk5c.precess_to(newEPOCH)
        # Save
        ra_tab['RA'] = newfk5.ra.degree
        ra_tab['DEC'] = newfk5.dec.degree
        # Strings too?
        ra_tab['RAS'] = str(newfk5.ra.to_string(unit=u.hour,sep=':'))
        ra_tab['DECS'] = str(newfk5.dec.to_string(unit=u.hour,sep=':'))
            
    
    ## 
    # Main Loop
    for obj in ra_tab: 

        # Outfil
        nm = "".join(obj['Name'].split()) 
        if OUT_TYPE=='PNG':
            outfil = fpath+ nm + '.png'
        else:
            outfil = fpath+ nm + '.pdf'
        print(outfil)

        # Grab the Image
        reload(xgs)
        img, oBW = xgs.getimg(obj['RA'], obj['DEC'], imsize, BW=BW,DSS=DSS)

        # Generate the plot
        plt.clf()
        fig = plt.figure(dpi=1200)
        fig.set_size_inches(8.0,10.5)

        # Font
        plt.rcParams['font.family']= 'times new roman'
        ticks_font = matplotlib.font_manager.FontProperties(family='times new roman', 
           style='normal', size=16, weight='normal', stretch='normal')
        ax = plt.gca()
        for label in ax.get_yticklabels() :
            label.set_fontproperties(ticks_font)
        for label in ax.get_xticklabels() :
            label.set_fontproperties(ticks_font)

        # Image
        if oBW == 1: 
            cmm = cm.Greys_r
        else: 
            cmm = None 
        plt.imshow(img,cmap=cmm,aspect='equal',extent=(-imsize/2., imsize/2, -imsize/2.,imsize/2))

        # Axes
        plt.xlim(-imsize/2., imsize/2.)
        plt.ylim(-imsize/2., imsize/2.)

        # Label
        plt.xlabel('Relative ArcMin', fontsize=20)
        xpos = 0.12*imsize
        ypos = 0.02*imsize
        plt.text(-imsize/2.-xpos, 0., 'EAST', rotation=90.,fontsize=20)
        plt.text(0.,imsize/2.+ypos, 'NORTH', fontsize=20, horizontalalignment='center')

        # Title
        plt.text(0.5,1.24, str(nm), fontsize=32, 
            horizontalalignment='center',transform=ax.transAxes)
        plt.text(0.5,1.16, 'RA (J2000) = '+str(obj['RAS']), fontsize=28, 
            horizontalalignment='center',transform=ax.transAxes)
        plt.text(0.5,1.10, 'DEC (J2000) = '+str(obj['DECS']), fontsize=28, 
            horizontalalignment='center',transform=ax.transAxes)
        #import pdb; pdb.set_trace()

        # Circle
        if show_circ:
            circle=plt.Circle((0,0),cradius,color='y', fill=False)
            plt.gca().add_artist(circle)

        # Spectrum??
        if show_spec:
            spec_img = xgs.get_spec_img(obj['RA'], obj['DEC']) 
            plt.imshow(spec_img,extent=(-imsize/2.1, imsize*(-0.1), -imsize/2.1, imsize*(-0.2)))

        # Write
        if show_spec:
            plt.savefig(outfil, dpi=300)
        else:
            plt.savefig(outfil)
        print 'finder: Wrote '+outfil
        plt.close()
        #xdb.set_trace()

    print 'finder: All done.'
    return oBW
コード例 #13
0
def main(inp,
         survey='2r',
         radec=None,
         deci=None,
         fpath=None,
         show_circ=True,
         EPOCH=0.,
         DSS=None,
         BW=False,
         imsize=5. * astrou.arcmin,
         show_spec=False,
         OUT_TYPE='PDF',
         show_another=None):
    '''
    Parameters:
    ---------
    inp: Input
       string or List of strings or List of several items
       'ra_dec_list.txt' -- ASCII file with columns of Name,RA,DEC and RA,DEC are string or float (deg)
        ['NAME_OF_TARG', '10:31:38.87', '+25:59:02.3']
        ['NAME_OF_TARG', 124.24*u.deg, -23.244*u.deg]
        ['NAME_OF_TARG', SkyCoord]
    radec: integer (0) [DEPRECATED!]
       Flag indicating type of input
       0 = ASCII file with columns of Name,RA,DEC and RA,DEC are string or float (deg)
       1 = List of string ['Name', 'RA', 'DEC']  
       2 = ['Name', ra_deg, dec_deg]
    BW: bool (False)
       B&W image?
    show_circ: bool (True)
       Show a yellow circle on the target
    show_another : tuple, optional
       RA,DEC for another target to circle (e.g. offset star)
    show_spec: bool (False)
       Try to grab and show an SDSS spectrum 
    imsize: Quantity, optional
       Image size 
    OUT_TYPE: str, optional  
       File type -- 'PDF', 'PNG'
    '''
    reload(x_r)
    reload(xgs)
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm

    # Init
    if fpath is None:
        fpath = './'
    try:
        imsize = imsize.to('arcmin').value
    except AttributeError:
        raise AttributeError('finder: Input imsize needs to be an Angle')
    cradius = imsize / 50.

    # Read in the Target list
    if isinstance(inp, basestring):
        raise NotImplementedError("No longer implemented")
        #ra_tab = get_coord(targ_file, radec=radec)
    else:
        ira_tab = {}
        ira_tab['Name'] = inp[0]
        if isinstance(inp[1], basestring):
            ra, dec = x_r.stod1((inp[1], inp[2]))
            ira_tab['RA'] = ra
            ira_tab['DEC'] = dec
        elif isinstance(inp[1], float):
            ira_tab['RA'] = inp[1] * astrou.deg
            ira_tab['DEC'] = inp[2] * astrou.deg
        elif isinstance(inp[1], SkyCoord):
            ira_tab['RA'] = inp[1].ra.deg
            ira_tab['DEC'] = inp[1].dec.deg
        else:  # Should check it is a Quantity
            ira_tab['RA'] = inp[1]
            ira_tab['DEC'] = inp[2]
        # Strings
        ras, decs = x_r.dtos1((ira_tab['RA'], ira_tab['DEC']))
        ira_tab['RAS'] = ras
        ira_tab['DECS'] = decs
        # Make a list
        ra_tab = [ira_tab]

    # Grab ra, dec in decimal degrees
    if deci is not None:
        return

    #xdb.set_trace()
    #x_r.stod(ra_tab) #ra_tab['RA'][q], ra_tab['DEC'][q], TABL)

    # Precess (as necessary)
    if EPOCH > 1000.:
        from astropy import units as u
        from astropy.coordinates import FK5
        from astropy.time import Time
        # Precess to 2000.
        tEPOCH = Time(EPOCH, format='jyear', scale='utc')
        # Load into astropy
        fk5c = FK5(ra=ra_tab['RA'],
                   dec=ra_tab['DEC'],
                   equinox=tEPOCH,
                   unit=(u.degree, u.degree))
        # Precess
        newEPOCH = Time(2000., format='jyear', scale='utc')
        newfk5 = fk5c.precess_to(newEPOCH)
        # Save
        ra_tab['RA'] = newfk5.ra.degree
        ra_tab['DEC'] = newfk5.dec.degree
        # Strings too?
        ra_tab['RAS'] = str(newfk5.ra.to_string(unit=u.hour, sep=':'))
        ra_tab['DECS'] = str(newfk5.dec.to_string(unit=u.hour, sep=':'))

    ##
    # Main Loop
    for obj in ra_tab:

        # Outfil
        nm = "".join(obj['Name'].split())
        if OUT_TYPE == 'PNG':
            outfil = fpath + nm + '.png'
        else:
            outfil = fpath + nm + '.pdf'
        print(outfil)

        # Grab the Image
        reload(xgs)
        img, oBW = xgs.getimg(obj['RA'], obj['DEC'], imsize, BW=BW, DSS=DSS)

        # Generate the plot
        plt.clf()
        fig = plt.figure(dpi=1200)
        fig.set_size_inches(8.0, 10.5)

        # Font
        plt.rcParams['font.family'] = 'times new roman'
        ticks_font = matplotlib.font_manager.FontProperties(
            family='times new roman',
            style='normal',
            size=16,
            weight='normal',
            stretch='normal')
        ax = plt.gca()
        for label in ax.get_yticklabels():
            label.set_fontproperties(ticks_font)
        for label in ax.get_xticklabels():
            label.set_fontproperties(ticks_font)

        # Image
        if oBW == 1:
            cmm = cm.Greys_r
        else:
            cmm = None
        plt.imshow(img,
                   cmap=cmm,
                   aspect='equal',
                   extent=(-imsize / 2., imsize / 2, -imsize / 2., imsize / 2))

        # Axes
        plt.xlim(-imsize / 2., imsize / 2.)
        plt.ylim(-imsize / 2., imsize / 2.)

        # Label
        plt.xlabel('Relative ArcMin', fontsize=20)
        xpos = 0.12 * imsize
        ypos = 0.02 * imsize
        plt.text(-imsize / 2. - xpos, 0., 'EAST', rotation=90., fontsize=20)
        plt.text(0.,
                 imsize / 2. + ypos,
                 'NORTH',
                 fontsize=20,
                 horizontalalignment='center')

        #import pdb; pdb.set_trace()

        # Circle
        if show_circ:
            circle = plt.Circle((0, 0), cradius, color='y', fill=False)
            plt.gca().add_artist(circle)

        # Second Circle
        if show_another is not None:
            # Coordinates
            cobj = x_r.to_coord((obj['RA'], obj['DEC']))
            canother = x_r.to_coord(show_another)
            # Offsets
            off, PA = x_r.offsets(cobj, canother)
            xanother = -1 * off[0].to('arcmin').value
            yanother = off[1].to('arcmin').value
            square = matplotlib.patches.Rectangle(
                (xanother - cradius, yanother - cradius),
                cradius * 2,
                cradius * 2,
                color='cyan',
                fill=False)
            plt.gca().add_artist(square)
            plt.text(0.5,
                     1.24,
                     str(nm),
                     fontsize=32,
                     horizontalalignment='center',
                     transform=ax.transAxes)
            plt.text(0.5,
                     1.18,
                     'RA (J2000) = ' + str(obj['RAS']) + '  DEC (J2000) = ' +
                     str(obj['DECS']),
                     fontsize=22,
                     horizontalalignment='center',
                     transform=ax.transAxes)
            plt.text(0.5,
                     1.12,
                     'RA(offset) = {:s}  DEC(offset) = {:s}'.format(
                         canother.ra.to_string(unit=astrou.hour,
                                               pad=True,
                                               sep=':',
                                               precision=2),
                         canother.dec.to_string(pad=True,
                                                alwayssign=True,
                                                sep=':',
                                                precision=1)),
                     fontsize=22,
                     horizontalalignment='center',
                     transform=ax.transAxes,
                     color='blue')
            plt.text(
                0.5,
                1.06,
                'RA(offset to obj) = {:g}  DEC(offset to obj) = {:g}'.format(
                    -1 * off[0].to('arcsec'), -1 * off[1].to('arcsec')),
                fontsize=18,
                horizontalalignment='center',
                transform=ax.transAxes)
        else:
            # Title
            plt.text(0.5,
                     1.24,
                     str(nm),
                     fontsize=32,
                     horizontalalignment='center',
                     transform=ax.transAxes)
            plt.text(0.5,
                     1.16,
                     'RA (J2000) = ' + str(obj['RAS']),
                     fontsize=28,
                     horizontalalignment='center',
                     transform=ax.transAxes)
            plt.text(0.5,
                     1.10,
                     'DEC (J2000) = ' + str(obj['DECS']),
                     fontsize=28,
                     horizontalalignment='center',
                     transform=ax.transAxes)

        # Spectrum??
        if show_spec:
            spec_img = xgs.get_spec_img(obj['RA'], obj['DEC'])
            plt.imshow(spec_img,
                       extent=(-imsize / 2.1, imsize * (-0.1), -imsize / 2.1,
                               imsize * (-0.2)))

        # Write
        if show_spec:
            plt.savefig(outfil, dpi=300)
        else:
            plt.savefig(outfil)
        print 'finder: Wrote ' + outfil
        plt.close()
        #xdb.set_trace()

    print 'finder: All done.'
    return oBW
コード例 #14
0
def mmt_targets(field, path=None):
    """Read files related to MMT targets

    Parameters:
    -----------
    field: tuple
      (Name, ra, dec)

    Returns:
    ----------
    Target and observing info 
    """
    if path is None:
        path = "/Galx_Spectra/MMT/"

    # Targets
    targ_path = field[0] + path

    # Target file
    targ_file = glob.glob(targ_path + "*.targ")
    if len(targ_file) != 1:
        raise ValueError("Wrong number of MMT target files")
    else:
        targ_file = targ_file[0]

    # Read PI, program info [NOT IMPLEMENTED]
    # f = open(msk_file, 'r')
    # lines = f.readlines()
    # f.close()

    # Read target table
    tab = ascii.read(targ_file, comment="#")
    # Restrict to targets
    itarg = np.where(tab["type"] == "TARGET")
    targs = tab[itarg]
    # Polish
    nrow = len(targs)
    targs.rename_column("ra", "RAS")
    targs.rename_column("dec", "DECS")
    targs.add_column(Column([0.0] * nrow, name="TARG_RA"))
    targs.add_column(Column([0.0] * nrow, name="TARG_DEC"))
    # Get RA/DEC in degrees
    for k, row in enumerate(targs):
        rad, decd = xra.stod1((row["RAS"], row["DECS"]))
        targs[k]["TARG_RA"] = rad.value
        targs[k]["TARG_DEC"] = decd.value
    targs.rename_column("objid", "TARG_ID")
    targs.rename_column("mag", "TARG_MAG")
    targs.add_column(Column([0.0] * nrow, name="EPOCH"))
    targs.add_column(Column(["SDSS"] * nrow, name="TARG_IMG"))
    targs.add_column(Column(["HECTOSPEC"] * nrow, name="INSTR"))

    targ_mask = {}
    cnames = ["MASK_NAME", "MASK_ID"]
    smsk = "--"
    msk_val = [smsk] * len(cnames)
    for kk, cname in enumerate(cnames):
        targ_mask[cname] = [msk_val[kk]] * nrow

    # Now the 'mask' files
    mask_files = glob.glob(targ_path + "*.cat")
    all_obs = []
    all_masks = []
    for mask_file in mask_files:
        print("Reading MMT mask file: {:s}".format(mask_file))
        i0 = mask_file.rfind("/")
        mask_nm = mask_file[i0 + 1 : mask_file.find(".cat")]
        # Grab info from spectrum file
        # xdb.set_trace()
        spec_fil = glob.glob(mask_file[: i0 + 1] + "spHect-" + mask_nm + "*.fits.gz")
        if len(spec_fil) != 1:
            print("spec_fil -- Not found!".format(spec_fil))
            ras, decs = xra.dtos1((field[1], field[2]))
            pa = 0.0
        else:
            header = fits.open(spec_fil[0])[0].header
            if header["APERTURE"] != mask_nm:
                raise ValueError("Mask doesnt match!")
            pa = header["POSANGLE"]
            ras = header["CAT-RA"]
            decs = header["CAT-DEC"]
        # Continuing
        mask_dict = dict(
            INSTR="HECTOSPEC", MASK_NAME=mask_nm, MASK_RA=ras, MASK_DEC=decs, MASK_EPOCH=2000.0, MASK_PA=pa
        )  # SHOULD GRAB PA, RA, DEC FROM SPECTRA FITS HEADER
        all_masks.append(mask_dict)
        # Read obs
        f = open(mask_file, "r")
        lines = f.readlines()
        f.close()
        iall_obs = []
        for line in lines:
            if "OBS" in line:
                prs = line.strip().split(" ")
                gdprs = [iprs for iprs in prs if len(iprs) > 0]
                obs_dict = {}
                obs_dict["DATE"] = gdprs[2]
                obs_dict["TEXP"] = float(gdprs[3])
                obs_dict["DISPERSER"] = gdprs[4]
                obs_dict["CONDITIONS"] = gdprs[5]
                #
                iall_obs.append(obs_dict)
        obs_tab = xxul.dict_list_to_table(iall_obs)
        obs_tab["TEXP"].unit = u.s
        # Read observed targets
        obs_targ = ascii.read(mask_file, comment="#")
        gdt = np.where(obs_targ["flag"] == 1)[0]
        for gdi in gdt:
            mtt = np.where(targs["TARG_ID"] == int(obs_targ["objid"][gdi]))[0]
            if len(mtt) != 1:
                raise ValueError("Multiple matches?!")
            targ_mask["MASK_NAME"][mtt[0]] = mask_nm
        all_obs.append(obs_tab)
    # Finish
    mask = np.array([False] * len(targs))
    bad = np.where(np.array(targ_mask["names"]) == "--")[0]
    if len(bad) > 0:
        mask[bad] = True
    #
    clm = MaskedColumn(targ_mask["names"], name="MASK_NAME", mask=mask)
    targs.add_column(clm)

    return all_masks, all_obs, targs
コード例 #15
0
def main(inp,
         survey='2r',
         radec=None,
         deci=None,
         fpath=None,
         EPOCH=0.,
         DSS=None,
         BW=False,
         imsize=5.,
         show_spec=False):
    '''
    Parameters:
    ---------
    inp: Input
       string or List of strings or List of several items
       'ra_dec_list.txt' -- ASCII file with columns of Name,RA,DEC and RA,DEC are string or float (deg)
        ['NAME_OF_TARG', '10:31:38.87', '+25:59:02.3']
        ['NAME_OF_TARG', 124.24*u.deg, -23.244*u.deg]
    radec: integer (0) [DEPRECATED!]
       Flag indicating type of input
       0 = ASCII file with columns of Name,RA,DEC and RA,DEC are string or float (deg)
       1 = List of string ['Name', 'RA', 'DEC']  
       2 = ['Name', ra_deg, dec_deg]
    BW: bool (False)
       B&W image?
    show_spec: bool (False)
       Try to grab and show an SDSS spectrum 
    imsize: float
       Image size in arcmin
    '''
    reload(x_r)
    reload(xgs)
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm

    # Init
    if fpath is None:
        fpath = './'
    cradius = imsize / 50.

    # Read in the Target list
    if isinstance(inp, basestring):
        ra_tab = get_coord(targ_file, radec=radec)
    else:
        ira_tab = {}
        ira_tab['Name'] = inp[0]
        if isinstance(inp[1], basestring):
            ra, dec = x_r.stod1((inp[1], inp[2]))
            ira_tab['RA'] = ra
            ira_tab['DEC'] = dec
        elif isinstance(inp[1], float):
            ira_tab['RA'] = inp[1] * astrou.deg
            ira_tab['DEC'] = inp[2] * astrou.deg
        else:  # Should check it is a Quantity
            ira_tab['RA'] = inp[1]
            ira_tab['DEC'] = inp[2]
        # Strings
        ras, decs = x_r.dtos1((ira_tab['RA'], ira_tab['DEC']))
        ira_tab['RAS'] = ras
        ira_tab['DECS'] = decs
        # Make a list
        ra_tab = [ira_tab]

    # Grab ra, dec in decimal degrees
    if deci is not None:
        return

    #xdb.set_trace()
    #x_r.stod(ra_tab) #ra_tab['RA'][q], ra_tab['DEC'][q], TABL)

    # Precess (as necessary)
    if EPOCH > 1000.:
        from astropy import units as u
        from astropy.coordinates import FK5
        from astropy.time import Time
        # Precess to 2000.
        tEPOCH = Time(EPOCH, format='jyear', scale='utc')
        # Load into astropy
        fk5c = FK5(ra=ra_tab['RA'],
                   dec=ra_tab['DEC'],
                   equinox=tEPOCH,
                   unit=(u.degree, u.degree))
        # Precess
        newEPOCH = Time(2000., format='jyear', scale='utc')
        newfk5 = fk5c.precess_to(newEPOCH)
        # Save
        ra_tab['RA'] = newfk5.ra.degree
        ra_tab['DEC'] = newfk5.dec.degree
        # Strings too?
        ra_tab['RAS'] = str(newfk5.ra.to_string(unit=u.hour, sep=':'))
        ra_tab['DECS'] = str(newfk5.dec.to_string(unit=u.hour, sep=':'))

    ##
    # Main Loop
    for obj in ra_tab:

        # Outfil
        nm = "".join(obj['Name'].split())
        outfil = fpath + nm + '.pdf'
        print(outfil)

        # Grab the Image
        reload(xgs)
        img, oBW = xgs.getimg(obj['RA'], obj['DEC'], imsize, BW=BW, DSS=DSS)

        # Generate the plot
        plt.clf()
        fig = plt.figure(dpi=1200)
        fig.set_size_inches(8.0, 10.5)

        # Font
        plt.rcParams['font.family'] = 'times new roman'
        ticks_font = matplotlib.font_manager.FontProperties(
            family='times new roman',
            style='normal',
            size=16,
            weight='normal',
            stretch='normal')
        ax = plt.gca()
        for label in ax.get_yticklabels():
            label.set_fontproperties(ticks_font)
        for label in ax.get_xticklabels():
            label.set_fontproperties(ticks_font)

        # Image
        if oBW == 1:
            cmm = cm.Greys_r
        else:
            cmm = None
        plt.imshow(img,
                   cmap=cmm,
                   aspect='equal',
                   extent=(-imsize / 2., imsize / 2, -imsize / 2., imsize / 2))

        # Axes
        plt.xlim(-imsize / 2., imsize / 2.)
        plt.ylim(-imsize / 2., imsize / 2.)

        # Label
        plt.xlabel('Relative ArcMin', fontsize=20)
        xpos = 0.12 * imsize
        ypos = 0.02 * imsize
        plt.text(-imsize / 2. - xpos, 0., 'EAST', rotation=90., fontsize=20)
        plt.text(0.,
                 imsize / 2. + ypos,
                 'NORTH',
                 fontsize=20,
                 horizontalalignment='center')

        # Title
        plt.text(0.5,
                 1.24,
                 str(nm),
                 fontsize=32,
                 horizontalalignment='center',
                 transform=ax.transAxes)
        plt.text(0.5,
                 1.16,
                 'RA (J2000) = ' + str(obj['RAS']),
                 fontsize=28,
                 horizontalalignment='center',
                 transform=ax.transAxes)
        plt.text(0.5,
                 1.10,
                 'DEC (J2000) = ' + str(obj['DECS']),
                 fontsize=28,
                 horizontalalignment='center',
                 transform=ax.transAxes)
        #import pdb; pdb.set_trace()

        # Circle
        circle = plt.Circle((0, 0), cradius, color='y', fill=False)
        plt.gca().add_artist(circle)

        # Spectrum??
        if show_spec:
            spec_img = xgs.get_spec_img(obj['RA'], obj['DEC'])
            plt.imshow(spec_img,
                       extent=(-imsize / 2.1, imsize * (-0.1), -imsize / 2.1,
                               imsize * (-0.2)))

        # Write
        if show_spec:
            plt.savefig(outfil, dpi=300)
        else:
            plt.savefig(outfil)
        print 'finder: Wrote ' + outfil
        #xdb.set_trace()

    print 'finder: All done.'
    return oBW
コード例 #16
0
ファイル: test_obs.py プロジェクト: tiffanyhsyu/xastropy
def test_stod():
	radec = x_r.stod1('J103138.87+255902.3')
	np.testing.assert_allclose(radec[0].value, 157.91195833333336)
	assert radec[0].unit == u.deg
コード例 #17
0
ファイル: lls_literature.py プロジェクト: ntejos/xastropy
def peroux06b():
    '''Peroux, C. et al. 2006b, A&A, 450, 53
    SDSS J1323-0021
    Metal rich
    Metal columns copied by JXP from Table 1 
    Total NHI from damping wings
    '''
    # Setup
    radec = xor.stod1('J132323.78-002155.2')  # SDSS Name
    lls = LLSSystem(name='SDSSJ1323-0021_z0.716',
                    RA=radec[0],
                    Dec=radec[1],
                    zem=1.390,
                    zabs=0.716,
                    vlim=[-200., 200.] * u.km / u.s,
                    NHI=20.21,
                    sigNHI=np.array([0.20, 0.20]))
    # Parse table file
    tab_fil = xa_path + "/data/LLS/peroux06b.tb1.ascii"
    with open(tab_fil, 'r') as f:
        flines = f.readlines()
    ion_dict = {}
    for iline in flines:
        isplit = iline.split('\t')
        if len(isplit[0]) == 0:
            # Grab ions and init
            ions = isplit[3:10]
            for ion in ions:
                Zion = xai.name_ion(ion)
                ion_dict[ion] = dict(clm=0.,
                                     sig_clm=0.,
                                     flg_clm=1,
                                     Z=Zion[0],
                                     ion=Zion[1])
            continue
        # Column or sigma?
        if isplit[0][0] == 'N':  # Column
            for kk, iis in enumerate(isplit[3:10]):
                ion = ions[kk]
                if iis[0] == '>':
                    ion_dict[ion]['flg_clm'] = 2
                    ion_dict[ion]['clm'] += float(iis[1:])
                elif iis[0] == '<':
                    pass
                elif iis[0] == '.':
                    pass
                else:
                    ion_dict[ion]['clm'] += float(iis)
        else:  # Sigma
            for kk, iis in enumerate(isplit[3:10]):
                ion = ions[kk]
                if iis[0] == '.':
                    pass
                else:
                    ion_dict[ion]['sig_clm'] += float(iis)**2
    # Convert to log
    for ion in ions:
        N = ion_dict[ion]['clm']
        sig = np.sqrt(ion_dict[ion]['sig_clm'])
        #
        ion_dict[ion]['clm'] = np.log10(N)
        if ion_dict[ion]['flg_clm'] == 2:
            ion_dict[ion]['sig_clm'] = 0.
        else:
            ion_dict[ion]['sig_clm'] = sig / N / np.log(10)
    # Finish
    lls._ionclms = IonClms(idict=ion_dict)
    lls.Refs.append('Prx06b')
    return lls
コード例 #18
0
ファイル: test_obs.py プロジェクト: tiffanyhsyu/xastropy
def test_tocoord():
	from astropy.coordinates import SkyCoord
	radec = x_r.stod1('J103138.87+255902.3')
	coord = x_r.to_coord(radec)
	# 
	assert isinstance(coord,SkyCoord)
コード例 #19
0
ファイル: lls_literature.py プロジェクト: ntejos/xastropy
def dessauges09():
    '''Dessauges-Zavadsky et al. 2009, MNRAS, 396, L96
    SLLS with UVES
    Zn,Fe abundances from Table 1 from astro-ph (LateX) by JXP [AODM]
     Taken from the Zn/H and Fe/H assuming *no* ionization corrections
    RA/DEC from the 'other' name 
    '''
    # Solar abundances
    eZn = 4.63
    eFe = 7.45
    sol = [eFe, eZn]
    #
    all_lls = []
    # Table 1
    tab_fil = xa_path + "/data/LLS/dessauges09.tb1.ascii"
    with open(tab_fil, 'r') as f:
        flines1 = f.readlines()
    # Trim the first few lines
    flines1 = flines1[3:]
    ion_dict = {}
    for iline in flines1:
        # Parse
        isplit = iline.split('&')
        # QSO
        if iline[0:2] == 'QS':
            # QSO, RA/DEC, zem
            qso = isplit[0][4:].strip()
            radec = xor.stod1(isplit[1].strip().replace('$', ''))
            zem = float(isplit[3].strip())
        # NHI, zabs
        zabs = float(isplit[4].strip())
        is2 = isplit[6].strip()
        NHI = float(is2[1:6])
        sigNHI = np.array([float(is2[10:14])] * 2)
        # name
        name = qso + 'z_{:.3f}'.format(zabs)
        lls = LLSSystem(name=name,
                        RA=radec[0],
                        Dec=radec[1],
                        zem=zem,
                        zabs=zabs,
                        NHI=NHI,
                        sigNHI=sigNHI)
        # ADOM Columns
        ion_dict = {}
        for kk, ion in enumerate(['Fe II', 'Zn II']):
            Zion = xai.name_ion(ion)
            is2 = isplit[7 + kk].strip()
            if is2[0:2] == '$>':
                ion_dict[ion] = dict(sig_clm=0.,
                                     flg_clm=2,
                                     Z=Zion[0],
                                     ion=Zion[1])
                ion_dict[ion]['clm'] = float(is2[2:7]) + NHI - 12 + sol[kk]
            elif is2[0:2] == '$<':
                ion_dict[ion] = dict(sig_clm=0.,
                                     flg_clm=3,
                                     Z=Zion[0],
                                     ion=Zion[1])
                ion_dict[ion]['clm'] = float(is2[2:7]) + NHI - 12 + sol[kk]
            elif is2[0:2] == '..':
                pass
            else:
                ion_dict[ion] = dict(flg_clm=1, Z=Zion[0], ion=Zion[1])
                ion_dict[ion]['clm'] = float(is2[1:6]) + NHI - 12 + sol[kk]
                ion_dict[ion]['sig_clm'] = float(is2[10:14])
        #xdb.set_trace()
        # Finish
        lls._ionclms = IonClms(idict=ion_dict)
        lls.Refs.append('DZ09')
        all_lls.append(lls)

    # Return SLLS only
    fin_slls = [ills for ills in all_lls if ills.NHI < 20.3]
    return fin_slls
コード例 #20
0
ファイル: lls_literature.py プロジェクト: ntejos/xastropy
def jenkins2005():
    '''Jenkins, E. et al. 2005, ApJ, 2005, 623, 767
    PHL 1811
    HST/STIS, FUSE
    Metals parsed from Table 1
      OI taken from text
      Had to input error on columns by hand (JXP)
    Total NHI from Lyman series. see Fig 3
    M/H from O/H
    '''
    # Grab ASCII file from ApJ
    tab_fil = xa_path + "/data/LLS/jenkins2005.tb1.ascii"
    chk_fil = glob.glob(tab_fil)
    if len(chk_fil) > 0:
        tab_fil = chk_fil[0]
    else:
        url = 'http://iopscience.iop.org/0004-637X/623/2/767/fulltext/61520.tb1.txt'
        print('LLSSurvey: Grabbing table file from {:s}'.format(url))
        f = urllib2.urlopen(url)
        with open(tab_fil, "wb") as code:
            code.write(f.read())
    # Setup
    radec = xor.stod1('J215501.5152-092224.688')  # SIMBAD
    lls = LLSSystem(name='PHL1811_z0.081',
                    RA=radec[0],
                    Dec=radec[1],
                    zem=0.192,
                    zabs=0.080923,
                    vlim=[-100., 100.] * u.km / u.s,
                    NHI=17.98,
                    MH=-0.19,
                    sigNHI=np.array([0.05, 0.05]))

    # AbsLines
    ism = LineList('ISM')
    Nsig = {
        'C IV': 0.4,
        'N II': 0.4,
        'Si II': 0.05,
        'Si IV': 0.25,
        'S II': 0.2,
        'Fe II': 0.12,
        'H I': 0.05,
        'S III': 0.06
    }

    # Parse Table
    with open(tab_fil, 'r') as f:
        flines = f.readlines()
    ion_dict = {}
    for iline in flines:
        iline = iline.strip()
        if (len(iline) == 0):
            continue
        # Split on tabs
        isplit = iline.split('\t')
        # Offset?
        ioff = 0
        if isplit[0][0] in ['1', '2']:
            ioff = -1
        # Catch bad lines
        if (isplit[1 + ioff][0:6]
                in ['1442.0', '1443.7',
                    '1120.9']):  # Skip goofy CII line and CII*
            continue
        if len(isplit[2 + ioff]) == 0:
            continue
        # Ion
        if (len(isplit[0].strip()) > 0) & (isplit[0][0] not in ['1', '2']):
            ionc = isplit[0].strip()
            try:
                Zion = xai.name_ion(ionc)
            except KeyError:
                xdb.set_trace()
        # Generate the Line
        try:
            newline = AbsLine(float(isplit[2 + ioff]) * u.AA,
                              linelist=ism,
                              closest=True)
        except ValueError:
            xdb.set_trace()
        newline.attrib['z'] = lls.zabs
        # Spectrum
        newline.analy['datafile'] = 'STIS' if 'S' in isplit[1] else 'FUSE'
        # EW
        try:
            EWvals = isplit[4 + ioff].split(' ')
        except IndexError:
            xdb.set_trace()
        newline.attrib['EW'] = float(EWvals[0]) * u.AA / 1e3
        newline.attrib['EWsig'] = float(EWvals[2]) * u.AA / 1e3
        newline.attrib['flgEW'] = 1
        if len(isplit) < (5 + ioff + 1):
            continue
        # Colm?
        #xdb.set_trace()
        if (len(isplit[5 + ioff].strip()) > 0) & (isplit[5 + ioff].strip() !=
                                                  '\\ldots'):
            if isplit[5 + ioff][0] == '\\':
                ipos = isplit[5 + ioff].find(' ')
                newline.attrib['N'] = float(isplit[5 + ioff][ipos + 1:])
                newline.attrib['flagN'] = 2
            elif isplit[5 + ioff][0] == '<':
                ipos = 0
                newline.attrib['N'] = float(isplit[5 + ioff][ipos + 1:])
                newline.attrib['flagN'] = 3
            elif isplit[5 + ioff][0] == '1':
                try:
                    newline.attrib['N'] = float(isplit[5 + ioff][0:5])
                except ValueError:
                    xdb.set_trace()
                newline.attrib['flagN'] = 1
                try:
                    newline.attrib['Nsig'] = Nsig[ionc]
                except KeyError:
                    print('No error for {:s}'.format(ionc))
            else:
                raise ValueError('Bad character')
            # ion_dict
            ion_dict[ionc] = dict(clm=newline.attrib['N'],
                                  sig_clm=newline.attrib['Nsig'],
                                  flg_clm=newline.attrib['flagN'],
                                  Z=Zion[0],
                                  ion=Zion[1])
        # Append
        lls.lines.append(newline)
    # Fix NI, OI
    ion_dict['O I']['clm'] = 14.47
    ion_dict['O I']['sig_clm'] = 0.05
    ion_dict['N I']['flg_clm'] = 3
    lls._ionclms = IonClms(idict=ion_dict)

    lls.Refs.append('Jen05')
    # Return
    return lls
コード例 #21
0
def mmt_targets(field, path=None):
    '''Read files related to MMT targets

    Parameters:
    -----------
    field: tuple
      (Name, ra, dec)

    Returns:
    ----------
    Target and observing info 
    '''
    if path is None:
        path = '/Galx_Spectra/MMT/'

    # Targets
    targ_path = field[0] + path

    # Target file
    targ_file = glob.glob(targ_path + '*.targ')
    if len(targ_file) != 1:
        raise ValueError('Wrong number of MMT target files')
    else:
        targ_file = targ_file[0]

    # Read PI, program info [NOT IMPLEMENTED]
    #f = open(msk_file, 'r')
    #lines = f.readlines()
    #f.close()

    # Read target table
    tab = ascii.read(targ_file, comment='#')
    # Restrict to targets
    itarg = np.where(tab['type'] == 'TARGET')
    targs = tab[itarg]
    # Polish
    nrow = len(targs)
    targs.rename_column('ra', 'RAS')
    targs.rename_column('dec', 'DECS')
    targs.add_column(Column([0.] * nrow, name='TARG_RA'))
    targs.add_column(Column([0.] * nrow, name='TARG_DEC'))
    # Get RA/DEC in degrees
    for k, row in enumerate(targs):
        rad, decd = xra.stod1((row['RAS'], row['DECS']))
        targs[k]['TARG_RA'] = rad.value
        targs[k]['TARG_DEC'] = decd.value
    targs.rename_column('objid', 'TARG_ID')
    targs.rename_column('mag', 'TARG_MAG')
    targs.add_column(Column([0.] * nrow, name='EPOCH'))
    targs.add_column(Column(['SDSS'] * nrow, name='TARG_IMG'))
    targs.add_column(Column(['HECTOSPEC'] * nrow, name='INSTR'))

    targ_mask = {}
    cnames = ['MASK_NAME', 'MASK_ID']
    smsk = '--'
    msk_val = [smsk] * len(cnames)
    for kk, cname in enumerate(cnames):
        targ_mask[cname] = [msk_val[kk]] * nrow

    # Now the 'mask' files
    mask_files = glob.glob(targ_path + '*.cat')
    all_obs = []
    all_masks = []
    for mask_file in mask_files:
        print('Reading MMT mask file: {:s}'.format(mask_file))
        i0 = mask_file.rfind('/')
        mask_nm = mask_file[i0 + 1:mask_file.find('.cat')]
        # Grab info from spectrum file
        #xdb.set_trace()
        spec_fil = glob.glob(mask_file[:i0 + 1] + 'spHect-' + mask_nm +
                             '*.fits.gz')
        if len(spec_fil) != 1:
            print('spec_fil -- Not found!'.format(spec_fil))
            ras, decs = xra.dtos1((field[1], field[2]))
            pa = 0.
        else:
            header = fits.open(spec_fil[0])[0].header
            if header['APERTURE'] != mask_nm:
                raise ValueError('Mask doesnt match!')
            pa = header['POSANGLE']
            ras = header['CAT-RA']
            decs = header['CAT-DEC']
        # Continuing
        mask_dict = dict(
            INSTR='HECTOSPEC',
            MASK_NAME=mask_nm,
            MASK_RA=ras,
            MASK_DEC=decs,
            MASK_EPOCH=2000.,
            MASK_PA=pa)  # SHOULD GRAB PA, RA, DEC FROM SPECTRA FITS HEADER
        all_masks.append(mask_dict)
        # Read obs
        f = open(mask_file, 'r')
        lines = f.readlines()
        f.close()
        iall_obs = []
        for line in lines:
            if 'OBS' in line:
                prs = line.strip().split(' ')
                gdprs = [iprs for iprs in prs if len(iprs) > 0]
                obs_dict = {}
                obs_dict['DATE'] = gdprs[2]
                obs_dict['TEXP'] = float(gdprs[3])
                obs_dict['DISPERSER'] = gdprs[4]
                obs_dict['CONDITIONS'] = gdprs[5]
                #
                iall_obs.append(obs_dict)
        obs_tab = xxul.dict_list_to_table(iall_obs)
        obs_tab['TEXP'].unit = u.s
        # Read observed targets
        obs_targ = ascii.read(mask_file, comment='#')
        gdt = np.where(obs_targ['flag'] == 1)[0]
        for gdi in gdt:
            mtt = np.where(targs['TARG_ID'] == int(obs_targ['objid'][gdi]))[0]
            if len(mtt) != 1:
                raise ValueError('Multiple matches?!')
            targ_mask['MASK_NAME'][mtt[0]] = mask_nm
        all_obs.append(obs_tab)
    # Finish
    mask = np.array([False] * len(targs))
    bad = np.where(np.array(targ_mask['names']) == '--')[0]
    if len(bad) > 0:
        mask[bad] = True
    #
    clm = MaskedColumn(targ_mask['names'], name='MASK_NAME', mask=mask)
    targs.add_column(clm)

    return all_masks, all_obs, targs
コード例 #22
0
ファイル: survey_figs.py プロジェクト: ntejos/xastropy
def deimos_targets(field, gc=None, outfil=None, replot=True,
    reset_layers=False):
    '''
    Call with gc to speed things up
    '''

    import matplotlib.cm as cm
    import matplotlib.patches as patches
    reload(xra)

    # Init
    # Mask dimensions
    smsk_dim = (7., 16.6) # arcmin (approximate)
    smsk_ang = np.arctan(smsk_dim[0]/smsk_dim[1])
    smsk_diag = np.sqrt(smsk_dim[0]**2 + smsk_dim[1]**2)/2.
    all_smsk_ang = [-1.*smsk_ang, smsk_ang, np.pi-smsk_ang, np.pi+smsk_ang]

    # Coordinates
    fcoord = SkyCoord(ra=field[1],dec=field[2])
    if outfil is None:
        outfil = xcasu.get_filename(field,'DEIMOS_TARG_FIG')
    # Load field
    lfield = xcasl.load_field(field)
    targ_coord = SkyCoord(ra=lfield.targets['TARG_RA']*u.deg,
        dec=lfield.targets['TARG_DEC']*u.deg)
    all_pa = fcoord.position_angle(targ_coord)
    all_sep = fcoord.separation(targ_coord).to('arcmin')

    # Targets
    deimos_targ = np.where(lfield.targets['INSTR'] == 'DEIMOS')[0]
    #dra =  all_sep[deimos_targ]*np.sin(all_pa[deimos_targ])
    #ddec = all_sep[deimos_targ]*np.cos(all_pa[deimos_targ])

    # Image
    path = os.getenv('CASBAH_GALAXIES')
    img_fil = path+'/'+field[0]+'/'+lfield.targets[deimos_targ]['TARG_IMG'][0]
    gfil = glob.glob(img_fil+'*')
    if len(gfil) != 1:
        raise ValueError('Image not found! {:s}'.format(img_fil))
    else:
        img_fil = gfil[0]
    #hdu = fits.open(img_fil)
    #w = wcs.WCS(hdu[0].header,fix=True)
    #img = hdu[0].data
    '''
    # Size
    pix_qso = w.wcs_world2pix(np.array([[field[1].value,field[2].value]]), 1)
    corners = [ [0.,0.], [0.,img.shape[0]], [img.shape[1],0.], [img.shape[1],img.shape[0]]]
    rad_corners =  w.wcs_pix2world(np.array(corners), 1) # deg but no units
    mx_rad = [0.,0.]
    for rad in rad_corners:
        c_off, _ = xra.offsets(fcoord, tuple(rad))
        for ii in range(2):
            mx_rad[ii] = np.maximum(
                mx_rad[ii],np.abs(c_off[ii].to('arcmin').value))
    imsize = 2.*np.maximum(mx_rad[0],mx_rad[1])
    '''

    # Start the plot
    #if outfil is not None: 
    #    pp = PdfPages(outfil)

    # Targets only
    plt.figure(figsize=(8, 4.9))
    plt.clf()

    plt.suptitle('{:s}: DEIMOS Targets (from LBT imaging)'.format(field[0])
        ,fontsize=19.)

    # Plot the Image
    if gc is None:
        gc = aplpy.FITSFigure(img_fil)

    radius = 25./60/2. #0.01 # deg
    if replot:
        gc.recenter(field[1].value, field[2].value,radius=radius)
        # This next one is a bit expensive
        gc.show_grayscale(vmin=300., vmax=3000.,stretch='arcsinh',invert='True')

    # Masks
    msk_clrs = ['blue', 'red', 'green', 'orange']
    deimos_obs = lfield.observing[np.where(
        lfield.observing['INSTR']=='DEIMOS')[0]]
    unimsk = np.unique(np.array(deimos_obs['MASK_NAME']))
    for ii,msk in enumerate(unimsk):
        mt = np.where(deimos_obs['MASK_NAME'] == msk)[0]
        if not deimos_obs['DATE_OBS'].mask[mt[0]]:
            # RA,DEC offset of center
            mask_rad = xra.stod1((deimos_obs['MASK_RA'][mt[0]],
                deimos_obs['MASK_DEC'][mt[0]]))
            mask_pa = deimos_obs['MASK_PA'][mt[0]]*np.pi/180.
            # RA/DEC offsets of corners
            rect_x = [smsk_diag*np.sin(smsk_ang+mask_pa) for smsk_ang in all_smsk_ang]
            rect_y = [smsk_diag*np.cos(smsk_ang+mask_pa) for smsk_ang in all_smsk_ang]
            #xdb.set_trace()
            prect_y = mask_rad[1].value + np.array(rect_y+[rect_y[0]])/60.
            prect_x = mask_rad[0].value + np.array(rect_x+[rect_x[0]])/60./np.cos(prect_y*np.pi/180.)
            '''
            coord0 = SkyCoord(ra=prect_x[0]*u.deg,dec=prect_y[0]*u.deg)            
            coord2 = SkyCoord(ra=prect_x[2]*u.deg,dec=prect_y[2]*u.deg)
            rcoord0 = SkyCoord(ra=rect_x[0]*u.arcmin,dec=rect_y[0]*u.arcmin)            
            rcoord2 = SkyCoord(ra=rect_x[2]*u.arcmin,dec=rect_y[2]*u.arcmin)
            sep02 = coord0.separation(coord2).to('arcmin')
            rsep02 = rcoord0.separation(rcoord2).to('arcmin')
            print(sep02)
            print(rsep02)
            print(smsk_diag*2.)
            xdb.set_trace()
            '''
            # Reshape
            xy = np.zeros((2,5))
            xy[0,:] = prect_x
            xy[1,:] = prect_y
            #xdb.set_trace()
            gc.show_lines([xy],color=msk_clrs[ii])#,alpha=0.5)

            # Markers
            # Observed targets
            sub_targ = np.where((lfield.targets['MASK_NAME']==msk)
                & (lfield.targets['INSTR']=='DEIMOS'))[0]
            obs_targ_tab, obs_dict, obs_idx = lfield.get_observed(radius*u.deg,
                subtab=lfield.targets[sub_targ])
            ra_obs_targ = lfield.targets[sub_targ[obs_idx]]['TARG_RA']
            dec_obs_targ = lfield.targets[sub_targ[obs_idx]]['TARG_DEC']
            gc.show_markers(ra_obs_targ, dec_obs_targ, edgecolor=msk_clrs[ii],
                facecolor='none', marker='o', s=50)#, alpha=0.5)
    # QSO
    gc.show_markers(field[1].value, field[2].value, edgecolor='lightgreen', facecolor='none',
        marker='s', s=10, alpha=0.5)
    # Label
    #gc.add_label(field[1].value, field[2].value, 'Q', color='green')

    if outfil != None:
        gc.save(outfil) 

    '''