Example #1
0
def psfmeasure(image,
               coords,
               radius,
               output='STDOUT',
               size='FWHM',
               pxscale=None):
    iraf.noao(_doprint=0)
    iraf.obsutil(_doprint=0)
    if size == 'all':
        sname = ['FWHM', 'GFWHM', 'MFWHM']
        tbls = []
        for s in sname:
            stbl = psfmeasure(image, coords, radius, output, s, pxscale)
            tbls.append(stbl)
        tbl = join(tbls[0], tbls[1])
        tbl = join(tbl, tbls[2])
        return tbl

    results = iraf.obsutil.psfmeasure(image,
                                      coords='mark1',
                                      size=size,
                                      imagecur=coords,
                                      display='no',
                                      radius=radius,
                                      logfile='',
                                      Stdout=1,
                                      StdoutG="dev$null",
                                      scale=1)
    #print results
    results = results[2:4]
    results[0] = results[0].strip()
    results = {k: v for k, v in zip(results[0].split(), results[1].split())}
    for k in results.keys():
        try:
            results[k] = np.float(results[k])
        except ValueError:
            continue
    tbl = Table([results])
    tbl = tbl[[k for k in P_COLMAP.keys() if k in tbl.colnames]]
    for k, v in P_COLMAP.iteritems():
        if k in tbl.colnames:
            tbl.rename_column(k, v)

    fwhmcol = tbl.colnames[-1]
    tbl[fwhmcol] /= 2.0  # make hwhm
    if pxscale:
        tbl.add_column(
            Column(tbl[fwhmcol] * u.pix * pxscale,
                   name='%s_s' % fwhmcol,
                   unit=u.arcsec,
                   format='%.3f'))
        tbl[fwhmcol].unit = u.pix

    return tbl
Example #2
0
def fwhm(directory,folders):
  iraf.noao(_doprint=0)
  iraf.obsutil(_doprint=0)
  iraf.unlearn("psfmeasure")
  
  rootdir = par.rootdir[0]
  
  dir_contents = os.listdir(directory+'/data')
  ds9s = [fn for fn in dir_contents if fn.startswith('ds9') and fn.endswith('.reg')]
  ds9 = directory+'/data/'+ds9s[0]

  print "\nMeasuring the fwhm of selected reference stars..."
  iraf.noao.obsutil.psfmeasure.coords = "mark1"
  iraf.noao.obsutil.psfmeasure.display = "no"
  iraf.noao.obsutil.psfmeasure.size = "FWHM"
  iraf.noao.obsutil.psfmeasure.scale = "1"
  iraf.noao.obsutil.psfmeasure.radius = "11"
  iraf.noao.obsutil.psfmeasure.swidth = "15"
  iraf.noao.obsutil.psfmeasure.iterati = "1"
  iraf.noao.obsutil.psfmeasure.imagecu = ds9
  iraf.noao.obsutil.psfmeasure.graphcur = rootdir+"/src/q.reg"
  iraf.noao.obsutil.psfmeasure.logfile = directory+"/data/fwhm.log"

  if os.path.isfile(directory+"/data/fwhm.log"):
    os.system("rm "+directory+"/data/fwhm.log")
    
  imgs = [fn for fn in dir_contents if fn.startswith(par.image_name[0]) and fn.endswith(par.image_name[1])]
  imgs = sorted(imgs)

  for i in range(len(imgs)):
    iraf.noao.obsutil.psfmeasure.imagecu = ds9
    iraf.noao.obsutil.psfmeasure(directory+'/data/'+imgs[i])
  
  N_stars = len(ds9)
  fwhm = [[] for _ in range(len(imgs))]
  values = [ line for line in open(directory+"/data/fwhm.log") if '.' in line and 'NOAO' not in line]
  j = 0
  for i in range(len(values)):
    if values[i][2:9] == 'Average':
      j += 1
    if values[i][2:9] != 'Average': 
      fwhm[j].append(float(values[i][41:47]))

  f = open(directory+'/data/fwhm.txt', 'w+')
  for i in range(len(imgs)):
    fwhm[i] = np.array(fwhm[i])
    print >> f, np.median(fwhm[i]), imgs[i]
  f.close()
Example #3
0
def init(iraf_dir=DEFAULT_IRAF_DIR):
    '''Initialize IRAF for use in photometry
    @param iraf_dir The home directory for iraf, i.e. where login.cl
    and uparm are located, slightly annoying that we need this, but not
    much we can do about it'''
    global _initialized
    if _initialized:
        #already initialized no need to run again
        return
    global iraf
    global yes
    global no
    with workingDirectory(iraf_dir):
        from pyraf import iraf
        yes = iraf.yes
        no = iraf.no
        #now load the packages we need
        iraf.noao()
        iraf.digiphot()
        iraf.daophot()
        iraf.obsutil()

        _initialized = True
        return
Example #4
0
def calculate_seeing(args):
    """ Program to estimate the seeing from an image and a list of estimates
    for the positions of stars. After calculating the seeing, some of the 
    stars might get recalculated centers. The list will be updated with the 
    """
    for im, im_cat in zip(args.input, args.cat):
        output = "output.txt"
        ignore = "ignore.txt"
        # Victor Terron, esto es horroroso, sugerencias?
        utilities.if_exists_remove("q.txt", output, ignore)
        q = open("q.txt", "w")
        q.write("q")
        q.close()
        iraf.noao()
        iraf.obsutil()
        iraf.module.psfmeasure(im, coords = "mark1", size = "MFWHM", 
                               sbuffer = 10, swidth=10,radius=10,
                               satura = 55000, ignore = "yes", 
                               imagecur = im_cat, display = "no", 
                               graphcur = "q.txt", Stdout=ignore, 
                               wcs = args.wcs, logfile=output)
        
        # Now we read the input im_cat and the output output.txt and compare
        # the location of stars. Those stars that have moved will not be 
        # trusted. 
        xout = np.array([])
        yout = np.array([])
        FWHM = np.array([])
        for line in open(output, 'r'):
            # First line is a description of the file, second is a newline \n
            # and third the description of the columns.
            if line != "\n" and line.split()[0] in im:
                xout = np.append(xout, float(line.split()[1]))
                yout = np.append(yout, float(line.split()[2]))
                FWHM = np.append(FWHM, float(line.split()[4]))
            else:
                try:
                   xout = np.append(xout, float(line.split()[0])) 
                   yout = np.append(yout, float(line.split()[1]))
                   FWHM = np.append(FWHM, float(line.split()[3]))
                except:
                   pass 
        xin, yin = np.genfromtxt(im_cat, dtype="float", unpack=True)
        xin, yin = np.array(xin), np.array(yin)  # case it is only one value


        # If args.wcs is "world" it means the input is in (RA, DEC), while 
        # the output is in pixels (X,Y). We need to convert one to the other
        # and we choose to follow the (RA,DEC) which, after all, is meaningful
        if args.wcs == "world":
            coords_xy = np.array(zip(xout, yout))
            hdr = fits.open(im)[0].header
            remove_keys = ["PC001001", "PC001002", "PC002001", "PC002002"]
            for keys in remove_keys:
                hdr.pop(keys,None)
            w = wcs.WCS(hdr)            
            coords_RADEC = w.all_pix2world(coords_xy,1)
            xout = coords_RADEC[:,0]
            yout = coords_RADEC[:,1]
           
        # find common stars using KDtrees    
        if xin.size > 1 : 
            tree_in = spatial.KDTree(zip(xin, yin))
        elif xin.size == 1:
            tree_in = spatial.KDTree([(float(xin), float(yin))])
        if xout.size > 1:
            tree_out = spatial.KDTree(zip(xout, yout))
        elif xout.size == 1:
            tree_out = spatial.KDTree([(float(xout), float(yout))]) 
        # If WCS use 0.001 degree (~3.6 arcsec) as limit. If not, assume 
        # pixels and say 4 pixels
        if args.wcs == "world":
            limit = 0.001
        else:
            limit = 4
        matches = tree_out.query_ball_tree(tree_in, limit) 
           
        # Two close stars in the original .cat could resolve into one  when 
        # the FWHM is calculated. This will appear as several hits in the 
        # matches with exactly the same numbers: [[0], [1,2], [1,2], [3]]
        # One solution is to erase one of them 
        for index, value in enumerate(matches):      
            if matches.count(value) > 1:
                matches[index] = []
                       
        # Now restrict to the common objects
        remove_indices = [ii for ii,jj in enumerate(matches) if jj == []]
        xout = np.delete(xout, remove_indices)
        yout = np.delete(yout, remove_indices)
        FWHM = np.delete(FWHM, remove_indices)
 
        # Finally, calculate the median FWHM of the image and rewrite valid
        # stars to the im_cat file. 
        median_fwhm = np.median(FWHM)
        utilities.header_update_keyword(im, "seeing", median_fwhm, "FWHM of image")
        f = open(im_cat, 'w') # write the "good" stars in the catalogue
        for ii in range(len(xout)):
            f.write(str(xout[ii]) + "  " + str(yout[ii]) + "\n")
        f.close()

        # And clean after yourself!
        utilities.if_exists_remove("q.txt", output, ignore)
Example #5
0
# modified by SV for lsc 
################################################################
import os, sys, shutil, subprocess
import time
from optparse import OptionParser
from pyraf import iraf
from astropy.io import fits
from astropy.io import fits
import lsc
import re
import string
import traceback
import numpy as np

iraf.noao(_doprint=0)
iraf.obsutil(_doprint=0)


def runsex(img, fwhm, thresh, pix_scale):  ## run_sextractor  fwhm in pixel
    import lsc

    mina = 5.
    seeing = fwhm * pix_scale

    cdef = open(lsc.__path__[0] + '/standard/sex/default2.param')
    riga = cdef.readlines()
    cparam = []
    for r in riga:
        if r[0] != '#' and len(r.strip()) > 0: \
                cparam.append(r.split()[0])
Example #6
0
import numpy as np
from scipy import interpolate
from scipy.optimize import leastsq
from astropy import wcs
from astropy.coordinates import ICRS, Galactic
from astropy import units
from astropy.io import fits,ascii
from astropy.modeling import models, fitting
from astropy.table import Table, Column
from astLib import astCoords
import matplotlib.pyplot as plt
import pyfits
import psycopg2

from pyraf import iraf
iraf.obsutil(_doprint=0)
iraf.digiphot(_doprint=0)
iraf.digiphot.daophot(_doprint=0)

import traceback

if ndmode in ['d','D','database','Database']:
	conn_string = "host='10.36.2.113' dbname='postgres' user='******' password='******'"
	print "Connecting to database\n ->%s" % (conn_string)
	conn = psycopg2.connect(conn_string)
	cursor = conn.cursor()

errlogname = 'ErrorPhot_'+time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())+'.log'
logerror = open(errlogname,'wa')

Example #7
0
import os
from pyraf import iraf

iraf.noao()
iraf.noao.onedspec()
iraf.obsutil()
iraf.imred()
iraf.ccdr()
iraf.ech()


def normalise_mike_spectra(filename):

    os.system(
        "rm -f red.fits red_multic.fits red_multicim.fits red_multicom.fits red_multicimcom.fits endred.fits a.fits b.fits c.fits d.fits e.fits f.fits *.par"
    )
    iraf.noao.onedspec.scopy(input=filename, output="red.fits", aperture="", bands=2, beams="1", format="multispec")
    iraf.noao.onedspec.cont(input="red.fits", output="red_multic.fits", order=6, overrid="yes", markrej="no")
    iraf.images.imutil.imarith(operand1="red.fits", op="/", operand2="red_multic.fits", result="red_multicim.fits")
    iraf.noao.onedspec.scombine("red.fits", "red_multicom.fits", combine="sum", group="images")
    iraf.noao.onedspec.scombine("red_multicim.fits", "red_multicimcom.fits", combine="sum", group="images")
    iraf.images.imutil.imarith(
        operand1="red_multicom.fits", op="/", operand2="red_multicimcom.fits", result="endred.fits"
    )
    os.system("cp endred.fits %s_norm.fits" % (filename.replace(".fits", ""),))
    iraf.noao.onedspec.wspectext(
        input="%s_norm.fits" % (filename.replace(".fits", ""),),
        output="%s_norm.txt" % (filename.replace(".fits", ""),),
        header="no",
    )
    os.system(