Ejemplo n.º 1
0
def deg2sex(value,coord):
   '''Convert degrees to sexagesimal, unless it is already in sexagesimal'''
   
   try:
      tmp = map(float,str(value).split(':'))
   except ValueError:
      nlclib.error('Invalid string given for conversion to sexagesimal: %s' %value)

   n = len(tmp)
   if n == 1: # assume it was in degrees
      junk = tmp[0]
      if coord == 'ra':
         junk = junk/15.0
      hours = int(junk)
      junk = 60*(abs(junk) - abs(hours))
      minutes = int(junk)
      if abs(minutes - 60) < 1e-7:
         minutes = 0
         hours += 1
      junk = 60*(junk - minutes)
      seconds = float(junk)
      if abs(seconds - 60) < 1e-7:
         seconds = 0
         minutes += 1
      if abs(minutes - 60) < 1e-7:
         minutes = 0
         hours += 1
      tmp[0] = hours
      tmp.append(minutes)
      tmp.append(seconds)
   elif n == 2: # assume it was already sexagesimal, but no seconds given
      tmp.append(0.0)
   return tmp
Ejemplo n.º 2
0
def makeout(outroot,diridx):
   """Make output directory with error checking for pre-existing files"""
   outdir = '%s%d' %(outroot,diridx)
   if os.path.exists(outdir):
      nlclib.error('Fatal Error!  Output directory %s already exists!' %outdir)
   os.mkdir(outdir)
   return outdir
Ejemplo n.º 3
0
def getstepoffset(offset,coord):
   """Get stepdec and declabel given the range in declination plotted"""

   # label steps in arcseconds
   offlabel = array([1  ,5,10,15,20,30,60,300,600,900,1200,1800,3600,18000,36000])
   offstep  = array([0.5,1, 5, 5, 5,10,20, 60,300,300, 300, 600,1200, 3600,18000])
   tmp = abs(offset[1] - offset[0])

   if coord == 'so': # arcsecond offset
      tmp = 3600*tmp
   elif coord == 'mo': # arcminute offset
      offlabel = offlabel/60.
      offstep  = offsetep/60.
      tmp = 60*tmp
   elif coord == 'do': # degree offset
      offlabel = offlabel/3600.
      offstep  = offstep/3600.
   else:
      nlclib.error("getstepoffset(): coord keyword must be one of: so, mo, do!")

   guess = tmp/6. # aim for about 6 labels
   diff  = [abs(guess-a) for a in offlabel]
   idx   = diff.index(min(diff))

   return offstep[idx],offlabel[idx]
Ejemplo n.º 4
0
def deg2sex(value, coord):
    '''Convert degrees to sexagesimal, unless it is already in sexagesimal'''

    try:
        tmp = map(float, str(value).split(':'))
    except ValueError:
        nlclib.error('Invalid string given for conversion to sexagesimal: %s' %
                     value)

    n = len(tmp)
    if n == 1:  # assume it was in degrees
        junk = tmp[0]
        if coord == 'ra':
            junk = junk / 15.0
        hours = int(junk)
        junk = 60 * (abs(junk) - abs(hours))
        minutes = int(junk)
        if abs(minutes - 60) < 1e-7:
            minutes = 0
            hours += 1
        junk = 60 * (junk - minutes)
        seconds = float(junk)
        if abs(seconds - 60) < 1e-7:
            seconds = 0
            minutes += 1
        if abs(minutes - 60) < 1e-7:
            minutes = 0
            hours += 1
        tmp[0] = hours
        tmp.append(minutes)
        tmp.append(seconds)
    elif n == 2:  # assume it was already sexagesimal, but no seconds given
        tmp.append(0.0)
    return tmp
Ejemplo n.º 5
0
def deg2sex(value, coord):
    '''Convert degrees to sexagesimal, unless it is already in sexagesimal
   
      Returns a tuple of HMS or DMS, depending on if coord is 'ra' or not.'''

    try:
        tmp = map(float, str(value).split(':'))
    except ValueError:
        nlclib.error('Invalid string given for conversion to sexagesimal: %s' %
                     value)

    n = len(tmp)
    if n == 1:  # assume it was in degrees
        junk = tmp[0]
        if coord == 'ra':
            junk = junk / 15.0
        hours = int(junk)
        junk = 60 * (numpy.abs(junk) - numpy.abs(hours))
        minutes = int(junk)
        junk = 60 * (junk - minutes)
        seconds = float(junk)
        tmp[0] = hours
        tmp.append(minutes)
        tmp.append(seconds)
    elif n == 2:  # assume it was already sexagesimal, but no seconds given
        tmp.append(0.0)
    return tmp
Ejemplo n.º 6
0
def deg2sex(value,coord):
   '''Convert degrees to sexagesimal, unless it is already in sexagesimal
   
      Returns a tuple of HMS or DMS, depending on if coord is 'ra' or not.'''
   
   try:
      tmp = map(float,str(value).split(':'))
   except ValueError:
      nlclib.error('Invalid string given for conversion to sexagesimal: %s' %value)

   n = len(tmp)
   if n == 1: # assume it was in degrees
      junk = tmp[0]
      if coord == 'ra':
         junk = junk/15.0
      hours = int(junk)
      junk = 60*(numpy.abs(junk) - numpy.abs(hours))
      minutes = int(junk)
      junk = 60*(junk - minutes)
      seconds = float(junk)
      tmp[0] = hours
      tmp.append(minutes)
      tmp.append(seconds)
   elif n == 2: # assume it was already sexagesimal, but no seconds given
      tmp.append(0.0)
   return tmp
Ejemplo n.º 7
0
def getTickLocs(pixels,coords,stepsize,wcsrange=(0,360)):
   """Get tickmark locations in pixel coordinates."""

   if not all(diff(coords) > 0):
      nlclib.error("coords passed to getTickLocs() must be monotonically increasing!")
   minval = amin(coords)
   maxval = amax(coords)
   tickmark = arange(wcsrange[0],wcsrange[1]+stepsize,stepsize)
   mask = where((tickmark >= minval) & (tickmark <= maxval))
   tickmark = tickmark[mask]
   tickpix  = interp(tickmark,coords,pixels)
   return tickpix,tickmark
Ejemplo n.º 8
0
def _initialTemp(flux1,flux2,wave1,wave2,beta):
   """Estimate of initial temp based on where changes sign"""
   
   start = 1000
   for t in range(1,1000):
      f = _func(t,flux1,flux2,wave1,wave2,beta)
      if isfinite(f):
         sign = f/abs(f)
         start = t
         break
   for t in range(start,10000):
      f = _func(t,flux1,flux2,wave1,wave2,beta)
      s = f/abs(f)
      if sign*s == -1:
         return t
   nlclib.error('Could not estimate initial temperature for wavelengths %f,%f!' %(wave1,wave2))
Ejemplo n.º 9
0
   def apply(self):
      """Action to take when user clicks on 'Show' button"""

      global _circsize,_circlecolor
      _circsize = self.size.get()
      _circlecolor = self.color.get()
      os.system('xpaset -p %s regions format ds9' %self.window)
      blah = nlclib.createtempname()
      try:
         fp = open(blah,'w')
         ds9.makeRegion(fp,_all.ra,_all.dec,self.color.get(),float(self.size.get()),
            self.number.get())
         fp.close()
      except IOError, value:
         if "Permission denied" in value:
            nlclib.error('You do not have write permissions for %s' %os.getcwd())
         else:
            nlclib.error('Unknown problem with opening temp. region file!')
Ejemplo n.º 10
0
def findExt(fname, extname):
    """Try to match extname, which is a either an integer or string, with
      the extension in fname (the filename as a string)
      
      returns the extension number as an integer (starting from zero)"""

    if isinstance(fname, str):  # string with filename, so open
        img = pyfits.open(fname)
    elif isinstance(fname, pyfits.HDUList):
        img = fname
    else:
        nlclib.error("findExt(): fname must be a string or pyfits.HDUList")
    n = len(img)  # number of HDUs

    # first check if string of a integer, e.g. '1'
    try:
        ext = int(extname)
    except:
        ext = extname

    if isinstance(ext, int):
        if 1 <= ext <= n:
            tmp = ext - 1
        else:
            img.close()
            nlclib.error("Extension number must be in range %d-%d for %s!" %
                         (1, n, img.filename()))
    elif isinstance(ext, str):
        ext = ext.lower()
        junk = [img[i].header['extname'].strip().lower() for i in xrange(1, n)]
        if 'EXTNAME' in img[0].header.keys():
            junk.insert(0, img[0].header['extname'].strip().lower())
        else:
            junk.insert(0, 'primary')
        if ext in junk:
            tmp = junk.index(ext)
        else:
            img.close()
            nlclib.error("Extension name '%s' not found in %s!" %
                         (ext, img.filename()))
    elif isinstance(ext, (list, tuple)):
        tmp = []
        for tmpext in ext:
            blah = findExt(img, tmpext)
            tmp.append(blah)
    else:
        img.close()
        nlclib.error("Extension must be an integer or string!")
    if isinstance(fname, str):  # string with filename, so close
        img.close()
    return tmp
Ejemplo n.º 11
0
def findExt(fname,extname):
   """Try to match extname, which is a either an integer or string, with
      the extension in fname (the filename as a string)
      
      returns the extension number as an integer (starting from zero)"""
   
   if isinstance(fname,str): # string with filename, so open
      img = pyfits.open(fname)
   elif isinstance(fname,pyfits.HDUList):
      img = fname
   else:
      nlclib.error("findExt(): fname must be a string or pyfits.HDUList")
   n = len(img) # number of HDUs

   # first check if string of a integer, e.g. '1'
   try:
      ext = int(extname)
   except:
      ext = extname
   
   if isinstance(ext,int):
      if 1 <= ext <= n:
         tmp = ext - 1
      else:
         img.close()
         nlclib.error("Extension number must be in range %d-%d for %s!" %(1,n,img.filename()))
   elif isinstance(ext,str):
      ext = ext.lower()
      junk = [img[i].header['extname'].strip().lower() for i in xrange(1,n)]
      if 'EXTNAME' in img[0].header.keys():
         junk.insert(0,img[0].header['extname'].strip().lower())
      else:
         junk.insert(0,'primary')
      if ext in junk:
         tmp = junk.index(ext)
      else:
         img.close()
         nlclib.error("Extension name '%s' not found in %s!" %(ext,img.filename()))
   elif isinstance(ext,(list,tuple)):
      tmp = []
      for tmpext in ext:
         blah = findExt(img,tmpext)
         tmp.append(blah)
   else:
      img.close()
      nlclib.error("Extension must be an integer or string!")
   if isinstance(fname,str): # string with filename, so close
      img.close()
   return tmp
Ejemplo n.º 12
0
def dobin(image,offset,bin,unit):
   """Combine all steps for reading a fits image and binning radially"""
   
   junk    = nlclib.createtempname() # list of pixel values with distances in arcsecs
   outdata = nlclib.createtempname() # binned data

   # read fits header to get crpix and cdelt
   crpix1 = crpix2 = -1
   cdelt1 = cdelt2 = -1
   header = iraf.imheader(image,Stdout=1)
   for line in header:
      if re.match(r'^CRPIX1',line):
         crpix1 = float(line.split()[2])
      elif re.match(r'^CRPIX2',line):
         crpix2 = float(line.split()[2])
      elif re.match(r'^CDELT1',line):
         cdelt1 = float(line.split()[2])
      elif re.match(r'^CDELT2',line):
         cdelt2 = float(line.split()[2])
   if crpix1 == -1 or crpix2 == -1:
      nlclib.error("Couldn't read crpix values!")
   if cdelt1 == -1 or cdelt2 == -1:
      nlclib.error("Couldn't read cdelt values!")

   # Add in offsets
   fac = abs(cdelt1)*3600 # convert pixel distances to arcsecs
   crpix1 = crpix1 - offset[0]/fac
   crpix2 = crpix2 + offset[1]/fac


   # figure out binning
   if unit == 'step':
      count = int((bin[1] - bin[0])/bin[2])
   elif unit == 'nbin':
      count = bin[2]
   if count < 0:
      nlclib.error('Number of bins is negative!')

   # get pixel values
   fp = open(junk,'w')
   x = iraf.listpixels(image,Stdout=1)
   for line in x:
      t = map(float,line.split())
      dist = fac*math.sqrt((t[0] - crpix1)**2 + (t[1] - crpix2)**2)
      fp.write('%f %f\n' %(dist,t[3]))
   fp.close()

   # bin data
   cmd = 'dobin in=%s bin=%f:%f:%d > %s' %(junk,bin[0],bin[1],count,outdata)
   os.system(cmd)
   nlclib.remove(junk)
   return outdata
Ejemplo n.º 13
0
def _convert(value,coord,precision=0):
   """Convert a single value in deg to sexagesimal.  Use in conjunction with
      deg2sex() below.

      Returns sexagesimal value as a string

      value     = sexagesimal or degrees as a string
      coord     = either 'ra' or 'dec' to specify coordinate type
      precision = number of decimal places for rounding seconds"""

   negFlag = False # set to true if value is negative
   try:
      tmp = map(float,value.split(':'))
      if tmp[0] < 0:
         negFlag = True
         tmp[0] = abs(tmp[0])
   except ValueError:
      nlclib.error('Invalid string given for conversion to sexagesimal: %s' %value)

   n = len(tmp)
   if n == 1: # assume it was in degrees
      junk = tmp[0]
      if coord == 'ra':
         junk = junk/15.0
      hours = int(junk)
      try:
         junk = 60*(junk%hours)
         minutes = int(junk)
      except ZeroDivisionError:
         minutes = int(60*junk)
      try:
         seconds = 60*(junk%minutes)
      except ZeroDivisionError:
         seconds = 60*junk
      while seconds >= 60:
         seconds = seconds - 60
         minutes += 1
      while minutes >= 60:
         minutes = minutes - 60
         hours += 1
      tmp = [hours,minutes,seconds]
   elif n == 2: # assume it was already sexagesimal, but no seconds given
      tmp.append(0.0)

   # now convert to a string
   seconds = round(tmp[2],precision)
   if precision == 0:
      seconds = int(seconds)
   while seconds >= 60:
      seconds -= 60
      tmp[1] += 1
   minutes = tmp[1]
   while minutes >= 60:
      minutes -= 60
      tmp[0] += 1
   if seconds < 10:
      tmp = "%d:%02d:0%s" %(tmp[0],minutes,str(seconds))
   else:
      tmp = "%d:%02d:%s" %(tmp[0],minutes,str(seconds))
   if negFlag: # catch cases where deg. is neg
      tmp = '-' + tmp

   return tmp
Ejemplo n.º 14
0
   seterr(over='ignore')
   # some constants
   sun_lum  = 3.826e33      # solar luminosity in ergs/s
   parsec   = 3.08567802e18 # 1 parsec in cm
   planck   = 6.62618e-27   # Planck's constant in erg s
   light    = 2.99792458e10 # speed of light in cm/s
   boltz    = 1.38066e-16   # Boltzmann's constant in K^-1
   hck      = planck*light/boltz

   data = loadtxt(infile)
   wave = data[:,0]*1e-4 # wavelengths in cm

   ncol = data.shape[1]
   nsources = (ncol - 1)/2
   if ncol%2 == 0: # even number of columns
      nlclib.error('You must have an odd number of columns: wave f1 df1...')
   elif ncol < 3:
      nlclib.error('You must have at least 3 columns!')

   print '#id  Luminosity (L_solar)'

   for i in range(nsources):
      flux  = data[:,2*i+1]
      dflux = data[:,2*i+2]
      wtemp = wave
      mask  = where(flux != 0)
      flux  = flux[mask]
      dflux = dflux[mask]
      wtemp = wtemp[mask]

      flux1 = flux[:-1]
Ejemplo n.º 15
0
from readcmd import ReadCmd

spec = """in  = ??? # Input FITS file
          tol = 3   # Round to this many decimal places before NaN conversion"""

arg = ReadCmd(spec,__doc__)
fitsfile = arg.getstr('in',exist=True)
tol      = arg.getint('tol')

import pyfits,numpy
import nlclib

fimg = pyfits.open(fitsfile,mode='update')
data = fimg[0].data
hdr  = fimg[0].header
if hdr['bitpix'] != -32:
   fimg.close()
   nlclib.error("Bitpix is not -32, NaNs will not work!")

if hdr['naxis'] == 3:
   mask = numpy.where(data[0,:,:].round(tol) == 0)
   data[mask] = numpy.nan
elif hdr['naxis'] == 2:
   mask = numpy.where(data.round(tol) == 0)
   data[mask] = numpy.nan
else:
   fimg.close()
   nlclib.error("NAXIS is not 2 or 3.  I don't know what to do!")
fimg.close()
Ejemplo n.º 16
0
fp = pyfits.open(infile) #,ignore_missing_end=True)
data = fp[ext].data
header = fp[ext].header
fp.close()

shape = data.shape
if len(shape) == 3:
   nrows = shape[1]
   ncols = shape[2]
   data = data[0,:,:].flatten() # only read first plane of cube
elif len(shape) == 2:
   nrows = shape[0]
   ncols = shape[1]
   data = data.flatten()
else:
   nlclib.error("Input file must have 2-D or 3-D data!")

points = meshgrid(arange(ncols),arange(nrows))
x,y = (points[0].flatten() + 1, points[1].flatten() + 1)

fp = nlclib.nlcopen(outFile,'w')

if wcsFlag:
   wcs = pywcs.WCS(header)
   ra,dec = wcs.wcs_pix2sky(x,y,1)
   fp.write("# RA  DEC  data\n")
   savetxt(fp,column_stack((ra,dec,data)),fmt='%lf  %lf  %lf')
else:
   fp.write("#x y data\n")
   savetxt(fp,column_stack((x,y,data)),fmt='%d  %d  %lf')
fp.close()
Ejemplo n.º 17
0
   errFlag = True
   if len(errFiles) == 1:
      errFiles = nimages*errFiles

import pyfits
from numpy import zeros,isfinite,where,sqrt

for i in range(nimages):
   img = pyfits.open(inFiles[i])
   data = img[0].data
   if i == 0: # take shape and header from first file
      header1 = img[0].header
      shape  = data.shape
   elif data.shape != shape:
      img.close()
      nlclib.error("Shape mismatch between %s and %s" %(inFiles[0],inFiles[i]))   
   img.close()
   if oper == 'avg':
      if errFlag:
         img = pyfits.open(errFiles[i])
         junk = img[0].data**2
         if i == 0:
            header2 = img[0].header
         img.close()
      else:
         junk = zeros(shape)
         mask = where(isfinite(data))
         junk[mask] = 1

      if i == 0:
         total = data
Ejemplo n.º 18
0
outroot = arg.getstr('out')
pad     = arg.getint('pad')

fileidx = 1 # filenumber index
diridx  = 1 # output directory index
count   = 0 # number of files moved to outdir

f,r = makefiles(inroot,fileidx,pad)
outdir = makeout(outroot,diridx)

while os.path.exists(f):
   try:
      os.rename(f,'%s/%s' %(outdir,f))
      os.rename(r,'%s/%s' %(outdir,r))
   except OSError:
      nlclib.error('Problem moving %s and %s to %s' %(f,r,outdir))
   
   count += 1
   fileidx += 1
   f,r = makefiles(inroot,fileidx,pad)
   if count == 720:
      print "moved %d files to %s..." %(count,outdir)
      diridx += 1
      outdir = makeout(outroot,diridx)
      count = 0 # number of files moved to outdir

if count == 0: # empty final directory
   os.system('rm -r %s' %outdir)
else:
   print "moved %d files to %s..." %(count,outdir)
Ejemplo n.º 19
0
#      all the drag-and-drop code since I didn't need it.  Also greatly 
#      simplified the readin module to make it easier to add arbitrary file 
#      formats

spec = """# View a source file using DS9
          in      = None # Input data file
          window  = ds9  # Name of DS9 window
          nframes = 1    # Number of frames in DS9 window"""

from readcmd import ReadCmd
import os,ds9
import readin,nlclib
try:
   from Tkinter import *
except ImportError:
   nlclib.error('You need Tkinter installed in python to use p6_ds9.py')
try:
   from pywip import *
   _plotFlag = True
except ImportError:
   nlclib.warning('Cannot find module pywip.  Plotting is disabled.')
   _plotFlag = False

from tkMessageBox import showwarning
from tkMessageBox import askokcancel
from tkSimpleDialog import askinteger
from mytkinter import genericDialog
from mytkinter import inputFile
from mytkinter import myOptionMenu
from mytkinter import _HIGHLIGHT_COLOR
from mytkinter import _THEME_COLOR