def run_fxcor(lstl, lstu, tpl, tpu, chip):
    if chip == 'l':
        templ = tpl
        lst = lstl
    else:
        templ = tpu
        lst = lstu
    lista = '@' + lst
    chip_par = 'rvout_' + chip
    iraf.noao()
    iraf.rv()
    iraf.fxcor(lista,
               templ,
               output=chip_par,
               verbose='txtonly',
               interac='no',
               observa='paranal')
    rv = []
    rvlist = open(chip_par + '.txt', "r")
    for cols in (raw.strip().split() for raw in rvlist):
        vobs_index = len(cols) - 3
        if cols[0][0] != '#':
            rv.append(float(cols[vobs_index]))
    rvlist.close()
    return rv
Beispiel #2
0
def ImportPackages():
	iraf.noao(_doprint=0)
	iraf.rv(_doprint=0)
	iraf.imred(_doprint=0)
	iraf.kpnoslit(_doprint=0)	
	iraf.ccdred(_doprint=0)
	iraf.astutil(_doprint=0)
	
	iraf.keywpars.setParam('ra','CAT-RA') 
	iraf.keywpars.setParam('dec','CAT-DEC')
	iraf.keywpars.setParam('ut','UT')
	iraf.keywpars.setParam('utmiddl','UT-M_E')
	iraf.keywpars.setParam('exptime','EXPTIME')
	iraf.keywpars.setParam('epoch','CAT-EPOC')
	iraf.keywpars.setParam('date_ob','DATE-OBS')
	iraf.keywpars.setParam('hjd','HJD')
	iraf.keywpars.setParam('mjd_obs','MJD-OBS')
	iraf.keywpars.setParam('vobs','VOBS')
	iraf.keywpars.setParam('vrel','VREL')
	iraf.keywpars.setParam('vhelio','VHELIO')
	iraf.keywpars.setParam('vlsr','VLSR')
	iraf.keywpars.setParam('vsun','VSUN')
	iraf.keywpars.setParam('mode','ql')
	iraf.fxcor.setParam('continu','both')
	iraf.fxcor.setParam('filter','none')
	iraf.fxcor.setParam('rebin','smallest')
	iraf.fxcor.setParam('pixcorr','no')
	iraf.fxcor.setParam('apodize','0.2')
	iraf.fxcor.setParam('function','gaussian')
	iraf.fxcor.setParam('width','INDEF')
	iraf.fxcor.setParam('height','0.')
	iraf.fxcor.setParam('peak','no')
	iraf.fxcor.setParam('minwidt','3.')
	iraf.fxcor.setParam('maxwidt','21.')
	iraf.fxcor.setParam('weights','1.')
	iraf.fxcor.setParam('backgro','0.')
	iraf.fxcor.setParam('window','INDEF')
	iraf.fxcor.setParam('wincent','INDEF')
	iraf.fxcor.setParam('verbose','long')
	iraf.fxcor.setParam('imupdat','no')
	iraf.fxcor.setParam('graphic','stdgraph')
	iraf.fxcor.setParam('interac','yes')
	iraf.fxcor.setParam('autowri','yes')
	iraf.fxcor.setParam('autodra','yes')
	iraf.fxcor.setParam('ccftype','image')
	iraf.fxcor.setParam('observa','lapalma')
	iraf.fxcor.setParam('mode','ql')
	return 0
def fxcor(spec, task, template_spec, spec_list_file, fxcor_output_file, fxcor_range="4173-5447", interactive='no'):
    """
    Run fxcor on the binned spectra to determine the relative velocity (with respect to the template spectra)
    INPUT: BIN_SCI, FXCOR_TEMPLATE
    OUTPUT: FXCOR_BIN_LIST, FXCOR_FILE(s)

    Note: make sure you select the parameters for your desired use. Refer to the IRAF rv package help for description
    of what each parameter is/does
    """

    if os.path.exists(fxcor_output_file + '.txt'):
        print('File {} already exists'.format(fxcor_output_file + '.txt'))
        return

    assert task == "abs" or task == "ems", "'task' is neight 'ab' or 'ems'"

    spec_list = []
    for i in range(len(glob.glob(spec.format('*')))):
        spec_list.append(spec.format(i))
    assert len(spec_list) > 0, 'Input files {} do not exist'.format(spec.format('*'))
    np.array(spec_list).tofile(spec_list_file, sep='\n')

    from pyraf import iraf

    iraf.noao()
    iraf.rv()

    if task == 'ems':
        iraf.fxcor('@{}'.format(spec_list_file), spec.format(template_spec), output=fxcor_output_file, continuum="both",
                   interactive=interactive, order=1, high_rej=2, low_rej=2, osample=fxcor_range, rsample=fxcor_range,
                   rebin="smallest", imupdate="no", pixcorr="no", filter="both", f_type="welch", cuton=20, cutoff=1000,
                   fullon=30, fulloff=800, ra="RA", dec="DEC", ut="UTSTART", epoch="EQUINOX", verbose="txtonly")

    elif task == 'abs':
        # Run interactively to make sure not fitting noise features, adapet osample/rsample to avoid such noise
        iraf.fxcor('@{}'.format(spec_list_file), spec.format(template_spec), output=fxcor_output_file, continuum="both",
                   interactive=interactive, order=1, high_rej=2, low_rej=2, osample=fxcor_range, rsample=fxcor_range,
                   rebin="smallest", imupdate="no", pixcorr="no", filter="both", f_type="welch", cuton=20, cutoff=800,
                   fullon=30, fulloff=800, ra="RA", dec="DEC", ut="UTSTART", epoch="EQUINOX", verbose="txtonly")

    assert os.path.exists(fxcor_output_file + '.txt'), 'Error in iraf.fxcor: File {} was not created'.format(
        fxcor_output_file + '.txt')
def run_fxcor(st_names, templ, setup):
    arq = open(setup + '/' + 'speclist', 'w')
    for i in range(len(st_names)):
        arq.write(st_names[i] + '.fits\n')
    arq.close()
    lista = '@' + setup + '/' + 'speclist'
    clean_cr(lista)
    outname = setup + '/' + 'rvout_' + setup
    iraf.noao()
    iraf.rv()
    iraf.fxcor(lista,
               templ,
               output=outname,
               verbose='txtonly',
               interac='no',
               observa='paranal')
    rv = []
    rvlist = open(outname + '.txt', "r")
    for cols in (raw.strip().split() for raw in rvlist):
        vobs_index = len(cols) - 3
        if cols[0][0] != '#':
            rv.append(float(cols[vobs_index]))
    rvlist.close()
    return rv
Beispiel #5
0
def ImportPackages():
    iraf.noao(_doprint=0)
    iraf.rv(_doprint=0)
    iraf.keywpars.setParam("ra", "CAT-RA")
    iraf.keywpars.setParam("dec", "CAT-DEC")
    # must use UT as UT mid exposure for RV correct or it
    # messes up the HJD values by a lot
    iraf.keywpars.setParam("ut", "UT-M_E")
    iraf.keywpars.setParam("utmiddl", "")
    iraf.keywpars.setParam("exptime", "EXPTIME")
    iraf.keywpars.setParam("epoch", "CAT-EPOC")
    iraf.keywpars.setParam("date_ob", "DATE-OBS")
    iraf.keywpars.setParam("hjd", "HJD")
    iraf.keywpars.setParam("mjd_obs", "MJD-OBS")
    iraf.keywpars.setParam("vobs", "VOBS")
    iraf.keywpars.setParam("vrel", "VREL")
    iraf.keywpars.setParam("vhelio", "VHELIO")
    iraf.keywpars.setParam("vlsr", "VLSR")
    iraf.keywpars.setParam("vsun", "VSUN")
    iraf.keywpars.setParam("mode", "ql")
    iraf.rvcorrect.setParam("imupdat", "yes")
    iraf.rvcorrect.setParam("observa", "lapalma")

    return 0
import glob
import pyfits
from pyraf import iraf
import shutil
import numpy as np
import matplotlib.pyplot as plt
from datetime import date
import operator
import time
import traceback
from lmfit import minimize, Parameters, report_fit

#import cosmics

iraf.noao(_doprint=0,Stdout="/dev/null")
iraf.rv(_doprint=0,Stdout="/dev/null")
iraf.imred(_doprint=0,Stdout="/dev/null")
iraf.ccdred(_doprint=0,Stdout="/dev/null")
iraf.images(_doprint=0,Stdout="/dev/null")
iraf.immatch(_doprint=0,Stdout="/dev/null")
iraf.onedspec(_doprint=0,Stdout="/dev/null")
iraf.twodspec(_doprint=0,Stdout="/dev/null")
iraf.apextract(_doprint=0,Stdout="/dev/null")
iraf.imutil(_doprint=0,Stdout="/dev/null")
iraf.echelle(_doprint=0,Stdout="/dev/null")
iraf.astutil(_doprint=0,Stdout="/dev/null")
iraf.apextract.dispaxi=1
iraf.echelle.dispaxi=1
#fixes a bug with latest versions of iraf
iraf.ccdred.instrum='blank.txt'
Beispiel #7
0
Created on 25/03/16

@author: Carlos Eduardo Barbosa

Using pyraf to calculate VHELIO correction

"""
import os

import pyfits as pf
from pyraf import iraf

from config import *

iraf.rv(_doprint=0)

if __name__ == "__main__":
    os.chdir(data_dir)
    fits = sorted([x for x in os.listdir(".") if x.endswith(".fits")])
    table = "VHELIO"
    for img in fits:
        h = pf.getheader(img)
        print img,
        if "VHELIO" not in h.keys():
            print
            continue
        # try:
        #     iraf.hedit (images=img, fields="EPOCH", value=2000., add=True,
        #                 delete=False, verify=False, show=False,
        #                 update=True)
Beispiel #8
0
from astropy.io import fits
import numpy as np
from astropy.io import ascii
from astroplan import Observer
import astropy.coordinates
from pytz import timezone
from astropy.time import Time
from astropy import units as u
from pyraf import iraf
from astropy.table import Table
import time
import pandas as pd


iraf.noao()
iraf.rv()
iraf.oned()

LaSilla=Observer.at_site("lasilla", timezone="America/Santiago")

def info_s1d(s1d):
    with fits.open(s1d) as image:
        t_MJD=Time(image[0].header['MJD-OBS'], format='mjd')
        info = pd.DataFrame({"NAME_S1D":[s1d[s1d.find('untar/')+6:len(s1d)]],
                        "MJD":[image[0].header['MJD-OBS']],
                        "EXPTIME":[image[0].header['EXPTIME']],
                        "RA":[image[0].header['RA']],
                        "DEC":[image[0].header['DEC']],
                        "RADVEL":[image[0].header['HIERARCH ESO TEL TARG RADVEL']],
                        "NAME":[image[0].header['HIERARCH ESO OBS TARG NAME']],
                        "PROG_ID":[image[0].header['HIERARCH ESO OBS PROG ID']],
Beispiel #9
0
def fxcor(spectrum, template, wl_start, wl_end):
    
    try:
        # [TODO] Destroy IRAF
        from pyraf import iraf
        
    except NameError:
        iraf.noao()
        iraf.noao.onedspec()
        iraf.rv()
    
    if not os.path.exists(spectrum):
        raise IOError('Spectrum file "%s" does not exist.' % (spectrum, ))
    
    if not os.path.exists(template):
        raise IOError('Template file "%s" does not exist.' % (template, ))
        
    
    # Check whether the spectrum and template are ASCII files. If they are we
    # need them into FITS to continue.
    to_remove = [] # for cleaning up later
    
    spectrum_base, spectrum_ext = os.path.splitext(spectrum)
    spectrum_ext = spectrum_ext[1:]
    if spectrum_ext not in ('txt', 'ascii', 'fits'):
        logging.warn("Don't know what format the spectrum provided is in. Assuming ASCII..")
    
    if spectrum_ext != 'fits':
        wave = np.loadtxt(spectrum, usecols=(0, ))
        
        spectrum_fits = '.'.join([spectrum_base, '_tmp.fits'])
        iraf.onedspec.rspectext(input = spectrum,
                                output = spectrum_fits,
                                dtype = 'linear',
                                crval1 = np.min(wave),
                                cdelt1 = np.median(np.diff(wave)))
        to_remove.append(spectrum_fits)
    else: spectrum_fits = spectrum
    
    template_base, template_ext = os.path.splitext(template)
    template_ext = template_ext[1:]
    if template_ext not in ('txt', 'ascii', 'fits'):
        logging.warn("Don't know what format the template provided is in. Assuming ASCII..")
    
    if template_ext != 'fits':
        wave = np.loadtxt(spectrum, usecols=(0, ))
        template_fits = '.'.join([template_base, '_tmp.fits'])
        iraf.onedspec.rspectext(input = template,
                                output = template_fits,
                                dtype = 'linear',
                                crval1 = np.min(wave),
                                cdelt1 = np.median(np.diff(wave)))
        to_remove.append(template_fits)
    else: template_fits = template
    
    sample = ':'.join(map(str, [wl_start, wl_end]))
    output_filename = 'fxcor'
    
    try:
    
        iraf.rv.fxcor(objects=spectrum_fits, templates=template_fits, rebin='template',
            osample=sample, rsample=sample, output=output_filename, verbose='long', interactive=0, Stdout=1)
    
    except:
        raise
    
    else:
        
        fxcor_log = []
        with open(output_filename + '.log', 'r') as output:
            fxcor_log.extend(output.readlines())
        
        fxcor_out = []
        with open(output_filename + '.txt', 'r') as output:
            fxcor_out.extend(output.readlines())
        
        fxcor_log = ''.join(fxcor_log)
        fxcor_out = ''.join(fxcor_out)
        
        fxcor_output = np.loadtxt(output_filename + '.txt', comments='#', dtype=str)
        fxcor_hght, fxcor_fwhm, fxcor_tdr, fxcor_obs, fxcor_rel, fxcor_helio, fxcor_err = fxcor_output[-7::]
            
        # Translate
        if 'INDEF' in [fxcor_hght, fxcor_rel, fxcor_err]:
            v_rad = fxcor_rel.replace('INDEF', '0')
            correlation = fxcor_hght.replace('INDEF', '0')
            v_err = fxcor_rel.replace('INDEF', '-999')
            
        v_rad, correlation, v_err = map(float, [fxcor_rel, fxcor_hght, fxcor_err])
    
        os.system('rm -f %s fxcor.txt fxcor.log fxcor.gki' % (' '.join(to_remove), ))
    
        return (v_rad, v_err, correlation, )
Beispiel #10
0
import sys
import os
import string
from numpy import *
import functions
import spectype_functions
import spectype_numerical_functions
import matplotlib
import matplotlib.pyplot as plt
import pyfits
from pyraf import iraf
from scipy import interpolate

iraf.kpnoslit()
iraf.noao()
iraf.rv()

###################
### Description ###
###################

### Take input spectrum

### Find chisq in logg - teff space for every reddenining
### Add over reddening 
### Find min chisq 

### usage: python spectype_main.py file_path file_name
### Takes input params from config_file

#################