diff options
Diffstat (limited to 'lib/stwcs')
26 files changed, 277 insertions, 255 deletions
diff --git a/lib/stwcs/__init__.py b/lib/stwcs/__init__.py index d48931a..208644f 100644 --- a/lib/stwcs/__init__.py +++ b/lib/stwcs/__init__.py @@ -14,10 +14,10 @@ transformation. wcsutil also provides functions for manipulating alternate WCS descriptions in the headers. """ -from __future__ import division # confidence high +from __future__ import absolute_import, print_function # confidence high import os -import distortion +from . import distortion from stsci.tools import fileutil from stsci.tools import teal @@ -28,6 +28,6 @@ from .version import * try: import gui teal.print_tasknames(gui.__name__, os.path.dirname(gui.__file__)) - print '\n' + print('\n') except: - print 'No TEAL-based tasks available for this package!' + print('No TEAL-based tasks available for this package!') diff --git a/lib/stwcs/distortion/coeff_converter.py b/lib/stwcs/distortion/coeff_converter.py index aace72f..415b512 100644 --- a/lib/stwcs/distortion/coeff_converter.py +++ b/lib/stwcs/distortion/coeff_converter.py @@ -1,4 +1,4 @@ -from __future__ import division # confidence high +from __future__ import division, print_function # confidence high import numpy as np from astropy.io import fits @@ -20,7 +20,7 @@ def sip2idc(wcs): order = wcs.get('A_ORDER', None) sipa, sipb = _read_sip_kw(wcs) if None in [ocx10, ocx11, ocy10, ocy11, sipa, sipb]: - print 'Cannot convert SIP to IDC coefficients.\n' + print('Cannot convert SIP to IDC coefficients.\n') return None, None elif isinstance(wcs, pywcs.WCS): try: @@ -29,29 +29,29 @@ def sip2idc(wcs): ocy10 = wcs.ocy10 ocy11 = wcs.ocy11 except AttributeError: - print 'First order IDCTAB coefficients are not available.\n' - print 'Cannot convert SIP to IDC coefficients.\n' + print('First order IDCTAB coefficients are not available.\n') + print('Cannot convert SIP to IDC coefficients.\n') return None, None try: sipa = wcs.sip.a sipb = wcs.sip.b except AttributeError: - print 'SIP coefficients are not available.' - print 'Cannot convert SIP to IDC coefficients.\n' + print('SIP coefficients are not available.') + print('Cannot convert SIP to IDC coefficients.\n') return None, None try: order = wcs.sip.a_order except AttributeError: - print 'SIP model order unknown, exiting ...\n' + print('SIP model order unknown, exiting ...\n') return None, None else: - print 'Input to sip2idc must be a PyFITS header or a wcsutil.HSTWCS object\n' + print('Input to sip2idc must be a PyFITS header or a wcsutil.HSTWCS object\n') return if None in [ocx10, ocx11, ocy10, ocy11]: - print 'First order IDC coefficients not found, exiting ...\n' + print('First order IDC coefficients not found, exiting ...\n') return None, None idc_coeff = np.array([[ocx11, ocx10], [ocy11, ocy10]]) cx = np.zeros((order+1,order+1), dtype=np.double) diff --git a/lib/stwcs/distortion/models.py b/lib/stwcs/distortion/models.py index 3e7d2b4..231a9f1 100644 --- a/lib/stwcs/distortion/models.py +++ b/lib/stwcs/distortion/models.py @@ -1,11 +1,11 @@ -from __future__ import division # confidence high +from __future__ import absolute_import, division, print_function # confidence high + -import types -# Import PyDrizzle utility modules -import mutil import numpy as np -import mutil -from mutil import combin + +# Import PyDrizzle utility modules +from . import mutil +from .mutil import combin yes = True no = False @@ -76,14 +76,14 @@ class GeometryModel: _cys = np.zeros(shape=self.cy.shape,dtype=self.cy.dtype) _k = self.norder + 1 # loop over each input coefficient - for m in xrange(_k): - for n in xrange(_k): + for m in range(_k): + for n in range(_k): if m >= n: # For this coefficient, shift by xs/ys. - _ilist = range(m, _k) + _ilist = list(range(m, _k)) # sum from m to k for i in _ilist: - _jlist = range(n, i - (m-n)+1) + _jlist = list(range(n, i - (m-n)+1)) # sum from n to i-(m-n) for j in _jlist: _cxs[m,n] += self.cx[i,j]*combin(j,n)*combin((i-j),(m-n))*pow(xs,(j-n))*pow(ys,((i-j)-(m-n))) @@ -156,7 +156,7 @@ class GeometryModel: elif self.norder==5: lines.append('quintic\n') else: - raise ValueError, "Drizzle cannot handle poly distortions of order %d"%self.norder + raise ValueError("Drizzle cannot handle poly distortions of order %d" % self.norder) str = '%16.8f %16.8g %16.8g %16.8g %16.8g \n'% (x0,cx[1,1],cx[1,0],cx[2,2],cx[2,1]) lines.append(str) @@ -219,7 +219,7 @@ class GeometryModel: _cx[0,0] = 0. _cy[0,0] = 0. - if isinstance(_p,types.ListType) or isinstance(_p,types.TupleType): + if isinstance(_p, list) or isinstance(_p, tuple): _p = np.array(_p,dtype=np.float64) _convert = yes diff --git a/lib/stwcs/distortion/mutil.py b/lib/stwcs/distortion/mutil.py index d116bbf..aa9d167 100644 --- a/lib/stwcs/distortion/mutil.py +++ b/lib/stwcs/distortion/mutil.py @@ -1,4 +1,4 @@ -from __future__ import division # confidence high +from __future__ import division, print_function # confidence high from stsci.tools import fileutil import numpy as np @@ -34,7 +34,7 @@ def readIDCtab (tabname, chip=1, date=None, direction='forward', # Return a default geometry model if no IDCTAB filename # is given. This model will not distort the data in any way. if tabname == None: - print 'Warning: No IDCTAB specified! No distortion correction will be applied.' + print('Warning: No IDCTAB specified! No distortion correction will be applied.') return defaultModel() # Implement default values for filters here to avoid the default @@ -62,7 +62,7 @@ def readIDCtab (tabname, chip=1, date=None, direction='forward', err_str += "present run will continue using the old coefficients provided in \n" err_str += "the Dither Package (ca. 1995-1998). \n" err_str += "------------------------------------------------------------------------ \n" - raise IOError,err_str + raise IOError(err_str) #First thing we need, is to read in the coefficients from the IDC # table and populate the Fx and Fy matrices. @@ -108,7 +108,7 @@ def readIDCtab (tabname, chip=1, date=None, direction='forward', # Loop over all the rows looking for the one which corresponds # to the value of CCDCHIP we are working on... - for i in xrange(fshape[0]): + for i in range(fshape[0]): try: # Match FILTER combo to appropriate row, @@ -178,9 +178,9 @@ def readIDCtab (tabname, chip=1, date=None, direction='forward', err_str += ' FILTERS: '+filtstr+'\n' ftab.close() del ftab - raise LookupError,err_str + raise LookupError(err_str) else: - print '- IDCTAB: Distortion model from row',str(row+1),'for chip',detchip,':',filtstr + print('- IDCTAB: Distortion model from row',str(row+1),'for chip',detchip,':',filtstr) # Read in V2REF and V3REF: this can either come from current table, # or from an OFFTAB if time-dependent (i.e., for WFPC2) @@ -227,9 +227,9 @@ def readIDCtab (tabname, chip=1, date=None, direction='forward', cxstr = 'A' cystr = 'B' - for i in xrange(norder+1): + for i in range(norder+1): if i > 0: - for j in xrange(i+1): + for j in range(i+1): xcname = cxstr+str(i)+str(j) ycname = cystr+str(i)+str(j) fx[i,j] = ftab[1].data.field(xcname)[row] @@ -307,7 +307,7 @@ def read_tdd_coeffs(phdr, chip=1): if "TDDORDER" in phdr: n = int(phdr["TDDORDER"]) else: - print ('TDDORDER kw not present, using default TDD correction') + print('TDDORDER kw not present, using default TDD correction') return None a = np.zeros((n+1,), np.float64) @@ -316,7 +316,7 @@ def read_tdd_coeffs(phdr, chip=1): a[i] = phdr.get(("TDD_A%d" % i), 0.0) b[i] = phdr.get(("TDD_B%d" % i), 0.0) if (a==0).all() and (b==0).all(): - print ('Warning: TDD_A and TDD_B coeffiecients have values of 0, \n \ + print('Warning: TDD_A and TDD_B coeffiecients have values of 0, \n \ but TDDORDER is %d.' % TDDORDER) skew_coeffs['TDDORDER'] = n @@ -346,7 +346,7 @@ def readOfftab(offtab, date, chip=None): try: ftab = fileutil.openImage(offtab) except: - raise IOError,"Offset table '%s' not valid as specified!" % offtab + raise IOError("Offset table '%s' not valid as specified!" % offtab) #Determine row from which to get the coefficients. # How many rows do we have in the table... @@ -365,7 +365,7 @@ def readOfftab(offtab, date, chip=None): num_date = convertDate(date) # Loop over all the rows looking for the one which corresponds # to the value of CCDCHIP we are working on... - for ri in xrange(fshape[0]): + for ri in range(fshape[0]): i = fshape[0] - ri - 1 if 'DETCHIP' in colnames: detchip = ftab[1].data.field('DETCHIP')[i] @@ -405,12 +405,12 @@ def readOfftab(offtab, date, chip=None): del ftab if row_start == None and row_end == None: - print 'Row corresponding to DETCHIP of ',detchip,' was not found!' + print('Row corresponding to DETCHIP of ',detchip,' was not found!') raise LookupError elif row_start == None: - print '- OFFTAB: Offset defined by row',str(row_end+1) + print('- OFFTAB: Offset defined by row',str(row_end+1)) else: - print '- OFFTAB: Offset interpolated from rows',str(row_start+1),'and',str(row_end+1) + print('- OFFTAB: Offset interpolated from rows',str(row_start+1),'and',str(row_end+1)) # Now, do the interpolation for v2ref, v3ref, and theta if row_start == None or row_end == row_start: @@ -476,16 +476,16 @@ def readWCSCoeffs(header): cxstr = 'A_' cystr = 'B_' # Read coeffs into their own matrix - for i in xrange(_xorder+1): - for j in xrange(i+1): + for i in range(_xorder+1): + for j in range(i+1): xcname = cxstr+str(j)+'_'+str(i-j) if xcname in header: fx[i,j] = header[xcname] # Extract Y coeffs separately as a different order may # have been used to fit it. - for i in xrange(_yorder+1): - for j in xrange(i+1): + for i in range(_yorder+1): + for j in range(i+1): ycname = cystr+str(j)+'_'+str(i-j) if ycname in header: fy[i,j] = header[ycname] diff --git a/lib/stwcs/distortion/utils.py b/lib/stwcs/distortion/utils.py index 5e0bf79..449bc18 100644 --- a/lib/stwcs/distortion/utils.py +++ b/lib/stwcs/distortion/utils.py @@ -1,4 +1,5 @@ -from __future__ import division # confidence high +from __future__ import division, print_function # confidence high + import os import numpy as np from astropy import wcs as pywcs @@ -92,7 +93,7 @@ def undistortWCS(wcsobj): plate scale in the undistorted frame. """ assert isinstance(wcsobj, pywcs.WCS) - import coeff_converter + from . import coeff_converter cx, cy = coeff_converter.sip2idc(wcsobj) # cx, cy can be None because either there is no model available @@ -103,9 +104,9 @@ def undistortWCS(wcsobj): Run updatewcs() to update the headers or pass 'undistort=False' keyword to output_wcs().\n """ - raise RuntimeError, m + raise RuntimeError(m) else: - print 'Distortion model is not available, using input reference image for output WCS.\n' + print('Distortion model is not available, using input reference image for output WCS.\n') return wcsobj.copy() crpix1 = wcsobj.wcs.crpix[0] crpix2 = wcsobj.wcs.crpix[1] @@ -128,7 +129,7 @@ def undistortWCS(wcsobj): # Check the determinant for singularity _det = (am * dm) - (bm * cm) if ( _det == 0.0): - print 'Singular matrix in updateWCS, aborting ...' + print('Singular matrix in updateWCS, aborting ...') return lin_wcsobj = pywcs.WCS() @@ -160,10 +161,10 @@ def apply_idc(pixpos, cx, cy, pixref, pscale= None, order=None): return pixpos if order is None: - print 'Unknown order of distortion model \n' + print('Unknown order of distortion model \n') return pixpos if pscale is None: - print 'Unknown model plate scale\n' + print('Unknown model plate scale\n') return pixpos # Apply in the same way that 'drizzle' would... diff --git a/lib/stwcs/gui/__init__.py b/lib/stwcs/gui/__init__.py index 559d361..cd21bf6 100644 --- a/lib/stwcs/gui/__init__.py +++ b/lib/stwcs/gui/__init__.py @@ -4,16 +4,16 @@ This package defines the TEAL interfaces for public, file-based operations provided by the STWCS package. """ -from __future__ import division # confidence high +from __future__ import absolute_import # confidence high __docformat__ = 'restructuredtext' # import modules which define the TEAL interfaces -import write_headerlet -import extract_headerlet -import attach_headerlet -import delete_headerlet -import headerlet_summary -import archive_headerlet -import restore_headerlet -import apply_headerlet -import updatewcs +from . import write_headerlet +from . import extract_headerlet +from . import attach_headerlet +from . import delete_headerlet +from . import headerlet_summary +from . import archive_headerlet +from . import restore_headerlet +from . import apply_headerlet +from . import updatewcs diff --git a/lib/stwcs/gui/archive_headerlet.py b/lib/stwcs/gui/archive_headerlet.py index 70dbc89..3cc29e3 100644 --- a/lib/stwcs/gui/archive_headerlet.py +++ b/lib/stwcs/gui/archive_headerlet.py @@ -1,3 +1,4 @@ +from __future__ import print_function import os import string @@ -35,11 +36,11 @@ def getHelpAsString(docstring=False): def run(configObj=None): if configObj['hdrname'] in ['',' ','INDEF']: - print '='*60 - print 'ERROR:' - print ' No valid "hdrname" parameter value provided!' - print ' Please restart this task and provide a value for this parameter.' - print '='*60 + print('='*60) + print('ERROR:') + print(' No valid "hdrname" parameter value provided!') + print(' Please restart this task and provide a value for this parameter.') + print('='*60) return str_kw = ['wcsname','destim','sipname','npolfile','d2imfile', diff --git a/lib/stwcs/gui/delete_headerlet.py b/lib/stwcs/gui/delete_headerlet.py index 96d3ed1..b3df5a7 100644 --- a/lib/stwcs/gui/delete_headerlet.py +++ b/lib/stwcs/gui/delete_headerlet.py @@ -1,3 +1,4 @@ +from __future__ import print_function import os from stsci.tools import teal @@ -34,11 +35,11 @@ def run(configObj=None): if configObj['hdrname'] == '' and configObj['hdrext'] is None and \ configObj['distname'] == '': - print '='*60 - print 'ERROR:' - print ' No valid "hdrname", "hdrext" or "distname" parameter value provided!' - print ' Please restart this task and provide a value for one of these parameters.' - print '='*60 + print('='*60) + print('ERROR:') + print(' No valid "hdrname", "hdrext" or "distname" parameter value provided!') + print(' Please restart this task and provide a value for one of these parameters.') + print('='*60) return filename = parseinput.parseinput(configObj['filename'])[0] # Call function with properly interpreted input parameters diff --git a/lib/stwcs/gui/extract_headerlet.py b/lib/stwcs/gui/extract_headerlet.py index 972f5c7..02ecd7a 100644 --- a/lib/stwcs/gui/extract_headerlet.py +++ b/lib/stwcs/gui/extract_headerlet.py @@ -1,3 +1,4 @@ +from __future__ import print_function import os from stsci.tools import teal @@ -33,11 +34,11 @@ def getHelpAsString(docstring=False): def run(configObj=None): if configObj['output'] in ['',' ',None]: - print '='*60 - print 'ERROR:' - print ' No valid "output" parameter value provided!' - print ' Please restart this task and provide a value for this parameter.' - print '='*60 + print('='*60) + print('ERROR:') + print(' No valid "output" parameter value provided!') + print(' Please restart this task and provide a value for this parameter.') + print('='*60) return # create dictionary of remaining parameters, deleting extraneous ones diff --git a/lib/stwcs/gui/updatewcs.py b/lib/stwcs/gui/updatewcs.py index f8f10d7..3dacb67 100644 --- a/lib/stwcs/gui/updatewcs.py +++ b/lib/stwcs/gui/updatewcs.py @@ -1,3 +1,4 @@ +from __future__ import print_function import os from astropy.io import fits @@ -68,7 +69,7 @@ def run(configObj=None): # Check to insure that there is a valid reference file to be used idctab = fits.getval(file, 'idctab') if not os.path.exists(fileutil.osfn(idctab)): - print 'No valid distortion reference file ',idctab,' found in ',file,'!' + print('No valid distortion reference file ',idctab,' found in ',file,'!') raise ValueError # Re-define 'cdict' to only have switches for steps supported by that instrument diff --git a/lib/stwcs/gui/write_headerlet.py b/lib/stwcs/gui/write_headerlet.py index 353e32b..e18bed8 100644 --- a/lib/stwcs/gui/write_headerlet.py +++ b/lib/stwcs/gui/write_headerlet.py @@ -1,3 +1,4 @@ +from __future__ import print_function import os from stsci.tools import teal @@ -34,19 +35,19 @@ def getHelpAsString(docstring=False): def run(configObj=None): flist,oname = parseinput.parseinput(configObj['filename']) if len(flist) == 0: - print '='*60 - print 'ERROR:' - print ' No valid "filename" parameter value provided!' - print ' Please check the working directory and restart this task.' - print '='*60 + print('='*60) + print('ERROR:') + print(' No valid "filename" parameter value provided!') + print(' Please check the working directory and restart this task.') + print('='*60) return if configObj['hdrname'] in ['',' ','INDEF']: - print '='*60 - print 'ERROR:' - print ' No valid "hdrname" parameter value provided!' - print ' Please restart this task and provide a value for this parameter.' - print '='*60 + print('='*60) + print('ERROR:') + print(' No valid "hdrname" parameter value provided!') + print(' Please restart this task and provide a value for this parameter.') + print('='*60) return if configObj['output'] in ['',' ','INDEF']: diff --git a/lib/stwcs/updatewcs/__init__.py b/lib/stwcs/updatewcs/__init__.py index aca33f7..a7f9a3e 100644 --- a/lib/stwcs/updatewcs/__init__.py +++ b/lib/stwcs/updatewcs/__init__.py @@ -1,11 +1,10 @@ -from __future__ import division # confidence high +from __future__ import division, print_function # confidence high -import os from astropy.io import fits -import numpy as np from stwcs import wcsutil from stwcs.wcsutil import HSTWCS import stwcs + from astropy import wcs as pywcs import astropy @@ -84,7 +83,7 @@ def updatewcs(input, vacorr=True, tddcorr=True, npolcorr=True, d2imcorr=True, if checkfiles: files = checkFiles(files) if not files: - print 'No valid input, quitting ...\n' + print('No valid input, quitting ...\n') return for f in files: @@ -242,9 +241,9 @@ def getNrefchip(fobj): img.header['EXTNAME'].lower()=='sci'] fitsext = [i for i in range(len(fobj))[1:] if fobj[i].header['EXTNAME'].lower()=='sci'] - det2ext=dict(map(None, detectors,extvers)) - ext2det=dict(map(None, extvers, detectors)) - ext2fitsext=dict(map(None, extvers, fitsext)) + det2ext=dict(list(zip(detectors, extvers))) + ext2det=dict(list(zip(extvers, detectors))) + ext2fitsext=dict(list(zip(extvers, fitsext))) if 3 not in detectors: nrefchip = ext2det.pop(extvers[0]) @@ -263,9 +262,9 @@ def getNrefchip(fobj): img.header['EXTNAME'].lower()=='sci'] fitsext = [i for i in range(len(fobj))[1:] if fobj[i].header['EXTNAME'].lower()=='sci'] - det2ext=dict(map(None, detectors,extvers)) - ext2det=dict(map(None, extvers, detectors)) - ext2fitsext=dict(map(None, extvers, fitsext)) + det2ext=dict(list(zip(detectors, extvers))) + ext2det=dict(list(zip(extvers, detectors))) + ext2fitsext=dict(list(zip(extvers, fitsext))) if 2 not in detectors: nrefchip = ext2det.pop(extvers[0]) @@ -356,7 +355,7 @@ def cleanWCS(fname): keys.remove(' ') except ValueError: pass - fext = range(len(f)) + fext = list(range(len(f))) for key in keys: wcsutil.deleteWCS(fname, ext=fext, wcskey=key) @@ -369,5 +368,5 @@ def getCorrections(instrument): """ acorr = apply_corrections.allowed_corrections[instrument] - print "The following corrections will be performed for instrument %s\n" % instrument - for c in acorr: print c,': ' , apply_corrections.cnames[c] + print("The following corrections will be performed for instrument %s\n" % instrument) + for c in acorr: print(c,': ' , apply_corrections.cnames[c]) diff --git a/lib/stwcs/updatewcs/apply_corrections.py b/lib/stwcs/updatewcs/apply_corrections.py index b7e41b2..2871a46 100644 --- a/lib/stwcs/updatewcs/apply_corrections.py +++ b/lib/stwcs/updatewcs/apply_corrections.py @@ -1,4 +1,4 @@ -from __future__ import division # confidence high +from __future__ import division, print_function # confidence high import os from astropy.io import fits @@ -198,7 +198,7 @@ def applyD2ImCorr(fname, d2imcorr): msg = """\n\tKw D2IMFILE exists in primary header but file %s not found\n Detector to image correction will not be applied\n""" % fd2im0 logger.critical(msg) - print msg + print(msg) applyD2IMCorr = False return applyD2IMCorr try: @@ -220,6 +220,6 @@ def applyD2ImCorr(fname, d2imcorr): # in first extension header applyD2IMCorr = True except KeyError: - print 'D2IMFILE keyword not found in primary header' + print('D2IMFILE keyword not found in primary header') applyD2IMCorr = False return applyD2IMCorr diff --git a/lib/stwcs/updatewcs/corrections.py b/lib/stwcs/updatewcs/corrections.py index f44b73b..e36dcd6 100644 --- a/lib/stwcs/updatewcs/corrections.py +++ b/lib/stwcs/updatewcs/corrections.py @@ -1,14 +1,16 @@ -from __future__ import division # confidence high +from __future__ import division, print_function # confidence high import copy import datetime +import logging, time import numpy as np from numpy import linalg from stsci.tools import fileutil -from utils import diff_angles -import makewcs, npol -import logging, time +from . import npol +from . import makewcs +from .utils import diff_angles + logger=logging.getLogger('stwcs.updatewcs.corrections') MakeWCS = makewcs.MakeWCS @@ -221,7 +223,7 @@ class TDDCorr(object): err_str += " The pre-SM4 time-dependent skew solution will be used by default.\n" err_str += " Please update IDCTAB with new reference file from HST archive. \n" err_str += "------------------------------------------------------------------------ \n" - print err_str + print(err_str) # Using default pre-SM4 coefficients skew_coeffs = {'TDD_A':[0.095,0.090/2.5], 'TDD_B':[-0.029,-0.030/2.5], diff --git a/lib/stwcs/updatewcs/det2im.py b/lib/stwcs/updatewcs/det2im.py index 902deaa..dfda9d1 100644 --- a/lib/stwcs/updatewcs/det2im.py +++ b/lib/stwcs/updatewcs/det2im.py @@ -1,9 +1,10 @@ -from __future__ import division # confidence high +from __future__ import absolute_import, division # confidence high +import numpy as np from astropy.io import fits from stsci.tools import fileutil -import utils -import numpy as np + +from . import utils import logging, time logger = logging.getLogger('stwcs.updatewcs.d2im') @@ -223,7 +224,7 @@ class DET2IMCorr(object): kw_comm1 = {} kw_val1 = {} - for key in kw.keys(): + for key in kw: for i in range(1, naxis+1): si = str(i) kw_comm1[key+si] = kw[key] @@ -254,9 +255,9 @@ class DET2IMCorr(object): 'CCDCHIP': ccdchip, } cdl = [] - for key in kw_comm0.keys(): + for key in kw_comm0: cdl.append((key, kw_val0[key], kw_comm0[key])) - for key in kw_comm1.keys(): + for key in kw_comm1: cdl.append((key, kw_val1[key], kw_comm1[key])) # Now add keywords from NPOLFILE header to document source of calibration # include all keywords after and including 'FILENAME' from header diff --git a/lib/stwcs/updatewcs/makewcs.py b/lib/stwcs/updatewcs/makewcs.py index 68ceded..06c6f9c 100644 --- a/lib/stwcs/updatewcs/makewcs.py +++ b/lib/stwcs/updatewcs/makewcs.py @@ -1,13 +1,14 @@ -from __future__ import division # confidence high +from __future__ import absolute_import, division # confidence high import datetime import numpy as np +import logging, time from math import sin, sqrt, pow, cos, asin, atan2,pi -import utils + from stsci.tools import fileutil +from . import utils -import logging, time logger = logging.getLogger(__name__) class MakeWCS(object): diff --git a/lib/stwcs/updatewcs/npol.py b/lib/stwcs/updatewcs/npol.py index cee7b9b..4e109ae 100644 --- a/lib/stwcs/updatewcs/npol.py +++ b/lib/stwcs/updatewcs/npol.py @@ -1,11 +1,13 @@ -from __future__ import division # confidence high +from __future__ import absolute_import, division # confidence high +import logging, time + +import numpy as np from astropy.io import fits + from stsci.tools import fileutil -import utils -import numpy as np +from . import utils -import logging, time logger = logging.getLogger('stwcs.updatewcs.npol') class NPOLCorr(object): @@ -264,7 +266,7 @@ class NPOLCorr(object): kw_comm1 = {} kw_val1 = {} - for key in kw.keys(): + for key in kw: for i in range(1, naxis+1): si = str(i) kw_comm1[key+si] = kw[key] @@ -297,9 +299,9 @@ class NPOLCorr(object): 'CCDCHIP': ccdchip, } cdl = [] - for key in kw_comm0.keys(): + for key in kw_comm0: cdl.append((key, kw_val0[key], kw_comm0[key])) - for key in kw_comm1.keys(): + for key in kw_comm1: cdl.append((key, kw_val1[key], kw_comm1[key])) # Now add keywords from NPOLFILE header to document source of calibration # include all keywords after and including 'FILENAME' from header diff --git a/lib/stwcs/wcsutil/__init__.py b/lib/stwcs/wcsutil/__init__.py index b92299e..65280be 100644 --- a/lib/stwcs/wcsutil/__init__.py +++ b/lib/stwcs/wcsutil/__init__.py @@ -1,12 +1,11 @@ -from __future__ import division # confidence high +from __future__ import absolute_import, print_function # confidence high -from altwcs import * -from hstwcs import HSTWCS +from .altwcs import * +from .hstwcs import HSTWCS def help(): - print 'How to create an HSTWCS object:\n\n' - print """ \ + doc = """ \ 1. Using a `astropy.io.fits.HDUList` object and an extension number \n Example:\n from astropy.io improt fits @@ -31,3 +30,5 @@ def help(): w = wcsutil.HSTWCS(instrument='DEFAULT')\n\n """ + print('How to create an HSTWCS object:\n\n') + print(doc) diff --git a/lib/stwcs/wcsutil/altwcs.py b/lib/stwcs/wcsutil/altwcs.py index 7719ce7..15123b7 100644 --- a/lib/stwcs/wcsutil/altwcs.py +++ b/lib/stwcs/wcsutil/altwcs.py @@ -1,4 +1,4 @@ -from __future__ import division # confidence high +from __future__ import division, print_function # confidence high import os import string @@ -80,7 +80,7 @@ def archiveWCS(fname, ext, wcskey=" ", wcsname=" ", reusekey=False): Alternatively choose another wcskey with altwcs.available_wcskeys()." %wcskey) elif wcskey == " ": # wcsname exists, overwrite it if reuse is True or get the next key - if wcsname.strip() in wcsnames(f[wcsext].header).values(): + if wcsname.strip() in wcsnames(f[wcsext].header): if reusekey: # try getting the key from an existing WCS with WCSNAME wkey = getKeyFromName(f[wcsext].header, wcsname) @@ -132,8 +132,8 @@ def archiveWCS(fname, ext, wcskey=" ", wcsname=" ", reusekey=False): old_wcsname=hwcs.pop('WCSNAME') except: pass - for k in hwcs.keys(): - + + for k in hwcs: key = k[:7] + wkey f[e].header[key] = hwcs[k] closefobj(fname, f) @@ -202,7 +202,7 @@ def restore_from_to(f, fromext=None, toext=None, wcskey=" ", wcsname=" "): raise KeyError("Could not get a key from wcsname %s ." % wcsname) else: if wcskey not in wcskeys(fobj, ext=wcskeyext): - print "Could not find alternate WCS with key %s in this file" % wcskey + print("Could not find alternate WCS with key %s in this file" % wcskey) closefobj(f, fobj) return wkey = wcskey @@ -322,7 +322,7 @@ def deleteWCS(fname, ext, wcskey=" ", wcsname=" "): ext = _buildExtlist(fobj, ext) # Do not allow deleting the original WCS. if wcskey == 'O': - print "Wcskey 'O' is reserved for the original WCS and should not be deleted." + print("Wcskey 'O' is reserved for the original WCS and should not be deleted.") closefobj(fname, fobj) return @@ -349,14 +349,14 @@ def deleteWCS(fname, ext, wcskey=" ", wcsname=" "): hwcs = readAltWCS(fobj,i,wcskey=wkey) if hwcs is None: continue - for k in hwcs.keys(): + for k in hwcs: del hdr[k] #del hdr['ORIENT'+wkey] prexts.append(i) if prexts != []: - print 'Deleted all instances of WCS with key %s in extensions' % wkey, prexts + print('Deleted all instances of WCS with key %s in extensions' % wkey, prexts) else: - print "Did not find WCS with key %s in any of the extensions" % wkey + print("Did not find WCS with key %s in any of the extensions" % wkey) closefobj(fname, fobj) def _buildExtlist(fobj, ext): @@ -419,9 +419,9 @@ def _restore(fobj, ukey, fromextnum, if hwcs is None: return - for k in hwcs.keys(): + for k in hwcs: key = k[:-1] - if key in fobj[toextension].header.keys(): + if key in fobj[toextension].header: #fobj[toextension].header.update(key=key, value = hwcs[k]) fobj[toextension].header[key] = hwcs[k] else: @@ -484,8 +484,8 @@ def readAltWCS(fobj, ext, wcskey=' ',verbose=False): nwcs = pywcs.WCS(hdr, fobj=fobj, key=wcskey) except KeyError: if verbose: - print 'readAltWCS: Could not read WCS with key %s' %wcskey - print ' Skipping %s[%s]' % (fobj.filename(), str(ext)) + print('readAltWCS: Could not read WCS with key %s' %wcskey) + print(' Skipping %s[%s]' % (fobj.filename(), str(ext))) return None hwcs = nwcs.to_header() @@ -693,7 +693,7 @@ def _parpasscheck(fobj, ext, wcskey, fromext=None, toext=None, reusekey=False): A flag which indicates whether to reuse a wcskey in the header """ if not isinstance(fobj, fits.HDUList): - print "First parameter must be a fits file object or a file name." + print("First parameter must be a fits file object or a file name.") return False # first one covers the case of an object created in memory @@ -703,27 +703,27 @@ def _parpasscheck(fobj, ext, wcskey, fromext=None, toext=None, reusekey=False): else: # an HDUList object with associated file if fobj.fileinfo(0)['filemode'] is not 'update': - print "First parameter must be a file name or a file object opened in 'update' mode." + print("First parameter must be a file name or a file object opened in 'update' mode.") return False if not isinstance(ext, int) and not isinstance(ext, tuple) \ and not isinstance(ext,str) \ and not isinstance(ext, list) and ext is not None: - print "Ext must be integer, tuple, string,a list of int extension numbers, \n\ - or a list of tuples representing a fits extension, for example ('sci', 1)." + print("Ext must be integer, tuple, string,a list of int extension numbers, \n\ + or a list of tuples representing a fits extension, for example ('sci', 1).") return False if not isinstance(fromext, str) and fromext is not None: - print "fromext must be a string representing a valid extname" + print("fromext must be a string representing a valid extname") return False if not isinstance(toext, list) and not isinstance(toext, str) and \ toext is not None : - print "toext must be a string or a list of strings representing extname" + print("toext must be a string or a list of strings representing extname") return False if len(wcskey) != 1: - print 'Parameter wcskey must be a character - one of "A"-"Z" or " "' + print('Parameter wcskey must be a character - one of "A"-"Z" or " "') return False return True diff --git a/lib/stwcs/wcsutil/convertwcs.py b/lib/stwcs/wcsutil/convertwcs.py index 7ece2a0..a384eb1 100644 --- a/lib/stwcs/wcsutil/convertwcs.py +++ b/lib/stwcs/wcsutil/convertwcs.py @@ -1,4 +1,4 @@ -from astropy.io import fits +from __future__ import print_function try: import stwcs from stwcs import wcsutil @@ -23,9 +23,9 @@ def archive_prefix_OPUS_WCS(fobj,extname='SCI'): """ if stwcs is None: - print '=====================' - print 'The STWCS package is needed to convert an old-style OPUS WCS to an alternate WCS' - print '=====================' + print('=====================') + print('The STWCS package is needed to convert an old-style OPUS WCS to an alternate WCS') + print('=====================') raise ImportError @@ -41,7 +41,7 @@ def archive_prefix_OPUS_WCS(fobj,extname='SCI'): numextn = fileutil.countExtn(fobj) extlist = [] - for e in xrange(1,numextn+1): + for e in range(1,numextn+1): extlist.append(('sci',e)) # Insure that the 'O' alternate WCS is present @@ -57,10 +57,10 @@ def archive_prefix_OPUS_WCS(fobj,extname='SCI'): # create HSTWCS object from PRIMARY WCS wcsobj = wcsutil.HSTWCS(fobj,ext=ext,wcskey='O') # get list of WCS keywords - wcskeys = wcsobj.wcs2header().keys() + wcskeys = list(wcsobj.wcs2header().keys()) # For each SCI extension... - for e in xrange(1,numextn+1): + for e in range(1,numextn+1): # Now, look for any WCS keywords with a prefix of 'O' for key in wcskeys: okey = 'O'+key[:7] @@ -98,7 +98,7 @@ def create_prefix_OPUS_WCS(fobj,extname='SCI'): else: # check to make sure this FITS obj has been opened in update mode if fobj.fileinfo(0)['filemode'] != 'update': - print 'File not opened with "mode=update". Quitting...' + print('File not opened with "mode=update". Quitting...') raise IOError # check for existance of O-prefix WCS @@ -108,7 +108,7 @@ def create_prefix_OPUS_WCS(fobj,extname='SCI'): numextn = fileutil.countExtn(fobj,extname=extname) if numextn == 0: extname = '' - for extn in xrange(1,numextn+1): + for extn in range(1,numextn+1): hdr = fobj[(extname,extn)].header for okey in owcskeys: hdr[okey] = hdr[okey[1:]+'O'] diff --git a/lib/stwcs/wcsutil/getinput.py b/lib/stwcs/wcsutil/getinput.py index dbd240f..8ee1123 100644 --- a/lib/stwcs/wcsutil/getinput.py +++ b/lib/stwcs/wcsutil/getinput.py @@ -24,7 +24,7 @@ def parseSingleInput(f=None, ext=None): hdr0 = phdu[0].header try: ehdr = phdu[extnum].header - except (IndexError, KeyError), e: + except (IndexError, KeyError) as e: raise e.__class__('Unable to get extension %s.' % extnum) elif isinstance(f, fits.HDUList): diff --git a/lib/stwcs/wcsutil/headerlet.py b/lib/stwcs/wcsutil/headerlet.py index aaca6b9..6b3e752 100644 --- a/lib/stwcs/wcsutil/headerlet.py +++ b/lib/stwcs/wcsutil/headerlet.py @@ -10,10 +10,11 @@ when only the WCS information has been updated. """ -from __future__ import division +from __future__ import absolute_import, division, print_function +import os +import sys import functools import logging -import os import textwrap import copy import time @@ -24,16 +25,16 @@ from astropy.io import fits from astropy import wcs as pywcs from astropy.utils import lazyproperty -import altwcs -import wcscorr -from hstwcs import HSTWCS -from mappings import basic_wcs -from stwcs.updatewcs import utils - from stsci.tools.fileutil import countExtn from stsci.tools import fileutil as fu from stsci.tools import parseinput +from stwcs.updatewcs import utils +from . import altwcs +from . import wcscorr +from .hstwcs import HSTWCS +from .mappings import basic_wcs + #### Logging support functions class FuncNameLoggingFormatter(logging.Formatter): def __init__(self, fmt=None, datefmt=None): @@ -108,8 +109,12 @@ def with_logging(func): level = kw.get('logging', 100) mode = kw.get('logmode', 'w') func_args = kw.copy() - for argname, arg in zip(func.func_code.co_varnames, args): - func_args[argname] = arg + if sys.version_info[0] < 3: + for argname, arg in zip(func.func_code.co_varnames, args): + func_args[argname] = arg + else: + for argname, arg in zip(func.__code__.co_varnames, args): + func_args[argname] = arg init_logging(func.__name__, level, mode, **func_args) return func(*args, **kw) return wrapped @@ -152,7 +157,11 @@ def parse_filename(fname, mode='readonly'): """ close_fobj = False if not isinstance(fname, list): - if isinstance(fname, basestring): + if sys.version > '3': + is_string = isinstance(fname, str) + else: + is_string = isinstance(fname, basestring) + if is_string: fname = fu.osfn(fname) fobj = fits.open(fname, mode=mode) close_fobj = True @@ -400,7 +409,7 @@ def print_summary(summary_cols, summary_dict, pad=2, maxwidth=None, idcol=None, outstr += COLUMN_FMT.format(val, width=column_widths[kw]) outstr += '\n' if not quiet: - print outstr + print(outstr) # If specified, write info to separate text file write_file = False @@ -411,9 +420,9 @@ def print_summary(summary_cols, summary_dict, pad=2, maxwidth=None, idcol=None, if clobber: os.remove(output) else: - print 'WARNING: Not writing results to file!' - print ' Output text file ', output, ' already exists.' - print ' Set "clobber" to True or move file before trying again.' + print('WARNING: Not writing results to file!') + print(' Output text file ', output, ' already exists.') + print(' Set "clobber" to True or move file before trying again.') write_file = False if write_file: fout = open(output, mode='w') @@ -1139,7 +1148,7 @@ def apply_headerlet_as_primary(filename, hdrlet, attach=True, archive=True, "{0:d} filenames and {1:d} headerlets specified".format(len(filename),len(hdrlet))) for fname,h in zip(filename,hdrlet): - print "Applying {0} as Primary WCS to {1}".format(h,fname) + print("Applying {0} as Primary WCS to {1}".format(h,fname)) hlet = Headerlet.fromfile(h, logging=logging, logmode=logmode) hlet.apply_as_primary(fname, attach=attach, archive=archive, force=force) @@ -1181,7 +1190,7 @@ def apply_headerlet_as_alternate(filename, hdrlet, attach=True, wcskey=None, "{0:d} filenames and {1:d} headerlets specified".format(len(filename),len(hdrlet))) for fname,h in zip(filename,hdrlet): - print 'Applying {0} as an alternate WCS to {1}'.format(h,fname) + print('Applying {0} as an alternate WCS to {1}'.format(h,fname)) hlet = Headerlet.fromfile(h, logging=logging, logmode=logmode) hlet.apply_as_alternate(fname, attach=attach, wcsname=wcsname, wcskey=wcskey) @@ -1211,7 +1220,7 @@ def attach_headerlet(filename, hdrlet, logging=False, logmode='a'): "{0:d} filenames and {1:d} headerlets specified".format(len(filename),len(hdrlet))) for fname,h in zip(filename,hdrlet): - print 'Attaching {0} as Headerlet extension to {1}'.format(h,fname) + print('Attaching {0} as Headerlet extension to {1}'.format(h,fname)) hlet = Headerlet.fromfile(h, logging=logging, logmode=logmode) hlet.attach_to_file(fname,archive=True) @@ -1252,7 +1261,7 @@ def delete_headerlet(filename, hdrname=None, hdrext=None, distname=None, filename = [filename] for f in filename: - print "Deleting Headerlet from ",f + print("Deleting Headerlet from ",f) _delete_single_headerlet(f, hdrname=hdrname, hdrext=hdrext, distname=distname, logging=logging, logmode='a') @@ -1386,8 +1395,8 @@ def headerlet_summary(filename, columns=None, pad=2, maxwidth=None, for key in COLUMN_DICT: summary_dict[kw][key].extend(ext_summary[kw][key]) except: - print "Skipping headerlet" - print "Could not read Headerlet from extension ", hdrlet_indx + print("Skipping headerlet") + print("Could not read Headerlet from extension ", hdrlet_indx) if close_fobj: fobj.close() @@ -1484,7 +1493,7 @@ def restore_from_headerlet(filename, hdrname=None, hdrext=None, archive=True, priwcs_name = None scihdr = extlist[0].header - sci_wcsnames = altwcs.wcsnames(scihdr).values() + #sci_wcsnames = altwcs.wcsnames(scihdr).values() if 'hdrname' in scihdr: priwcs_hdrname = scihdr['hdrname'] else: diff --git a/lib/stwcs/wcsutil/hstwcs.py b/lib/stwcs/wcsutil/hstwcs.py index 7618412..cb61f1c 100644 --- a/lib/stwcs/wcsutil/hstwcs.py +++ b/lib/stwcs/wcsutil/hstwcs.py @@ -1,19 +1,18 @@ -from __future__ import division # confidence high +from __future__ import absolute_import, division, print_function # confidence high import os from astropy.wcs import WCS from astropy.io import fits -import instruments from stwcs.distortion import models, coeff_converter -import altwcs import numpy as np from stsci.tools import fileutil -import getinput -import mappings -from mappings import inst_mappings, ins_spec_kw -from mappings import basic_wcs - +from . import altwcs +from . import getinput +from . import mappings +from . import instruments +from .mappings import inst_mappings, ins_spec_kw +from .mappings import basic_wcs __docformat__ = 'restructuredtext' @@ -138,7 +137,7 @@ class HSTWCS(WCS): ext=ext) self.filename = filename instrument_name = hdr0.get('INSTRUME', 'DEFAULT') - if instrument_name == 'DEFAULT' or instrument_name not in inst_mappings.keys(): + if instrument_name == 'DEFAULT' or instrument_name not in inst_mappings: #['IRAF/ARTDATA','',' ','N/A']: self.instrument = 'DEFAULT' else: @@ -204,7 +203,7 @@ class HSTWCS(WCS): extension header """ - if self.instrument in inst_mappings.keys(): + if self.instrument in inst_mappings: inst_kl = inst_mappings[self.instrument] inst_kl = instruments.__dict__[inst_kl] insobj = inst_kl(prim_hdr, ext_hdr) @@ -221,7 +220,7 @@ class HSTWCS(WCS): pass else: - raise KeyError, "Unsupported instrument - %s" %self.instrument + raise KeyError("Unsupported instrument - %s" %self.instrument) def setPscale(self): """ @@ -233,9 +232,9 @@ class HSTWCS(WCS): self.pscale = np.sqrt(np.power(cd11,2)+np.power(cd21,2)) * 3600. except AttributeError: if self.wcs.has_cd(): - print "This file has a PC matrix. You may want to convert it \n \ + print("This file has a PC matrix. You may want to convert it \n \ to a CD matrix, if reasonable, by running pc2.cd() method.\n \ - The plate scale can be set then by calling setPscale() method.\n" + The plate scale can be set then by calling setPscale() method.\n") self.pscale = None def setOrient(self): @@ -248,9 +247,9 @@ class HSTWCS(WCS): self.orientat = np.rad2deg(np.arctan2(cd12,cd22)) except AttributeError: if self.wcs.has_cd(): - print "This file has a PC matrix. You may want to convert it \n \ + print("This file has a PC matrix. You may want to convert it \n \ to a CD matrix, if reasonable, by running pc2.cd() method.\n \ - The orientation can be set then by calling setOrient() method.\n" + The orientation can be set then by calling setOrient() method.\n") self.pscale = None def updatePscale(self, scale): @@ -283,20 +282,20 @@ class HSTWCS(WCS): if header is not None and 'IDCSCALE' in header: self._readModelFromHeader(header) else: - print "Distortion model is not available: IDCTAB=None\n" + print("Distortion model is not available: IDCTAB=None\n") self.idcmodel = None elif not os.path.exists(fileutil.osfn(self.idctab)): if header is not None and 'IDCSCALE' in header: self._readModelFromHeader(header) else: - print 'Distortion model is not available: IDCTAB file %s not found\n' % self.idctab + print('Distortion model is not available: IDCTAB file %s not found\n' % self.idctab) self.idcmodel = None else: self.readModelFromIDCTAB(header=header, update=update) def _readModelFromHeader(self, header): # Recreate idc model from SIP coefficients and header kw - print 'Restoring IDC model from SIP coefficients\n' + print('Restoring IDC model from SIP coefficients\n') model = models.GeometryModel() cx, cy = coeff_converter.sip2idc(self) model.cx = cx @@ -331,7 +330,7 @@ class HSTWCS(WCS): """ if self.date_obs == None: - print 'date_obs not available\n' + print('date_obs not available\n') self.idcmodel = None return if self.filter1 == None and self.filter2 == None: @@ -349,7 +348,7 @@ class HSTWCS(WCS): if update: if header==None: - print 'Update header with IDC model kw requested but header was not provided\n.' + print('Update header with IDC model kw requested but header was not provided\n.') else: self._updatehdr(header) @@ -776,7 +775,7 @@ adaptive=False, detect_divergence=False, quiet=False) dn2 = dn2prev # prepare for iterative process - iterlist = range(1, maxiter+1) + iterlist = list(range(1, maxiter+1)) accuracy2 = accuracy**2 ind = None inddiv = None @@ -839,7 +838,7 @@ adaptive=False, detect_divergence=False, quiet=False) ##################################################################### if adaptive: if ind is None: - ind = np.asarray(range(npts), dtype=np.int64) + ind = np.asarray(list(range(npts)), dtype=np.int64) for k in iterlist: # check convergence: @@ -953,11 +952,11 @@ adaptive=False, detect_divergence=False, quiet=False) """ Print the basic WCS keywords. """ - print 'WCS Keywords\n' - print 'CD_11 CD_12: %r %r' % (self.wcs.cd[0,0], self.wcs.cd[0,1]) - print 'CD_21 CD_22: %r %r' % (self.wcs.cd[1,0], self.wcs.cd[1,1]) - print 'CRVAL : %r %r' % (self.wcs.crval[0], self.wcs.crval[1]) - print 'CRPIX : %r %r' % (self.wcs.crpix[0], self.wcs.crpix[1]) - print 'NAXIS : %d %d' % (self.naxis1, self.naxis2) - print 'Plate Scale : %r' % self.pscale - print 'ORIENTAT : %r' % self.orientat + print('WCS Keywords\n') + print('CD_11 CD_12: %r %r' % (self.wcs.cd[0,0], self.wcs.cd[0,1])) + print('CD_21 CD_22: %r %r' % (self.wcs.cd[1,0], self.wcs.cd[1,1])) + print('CRVAL : %r %r' % (self.wcs.crval[0], self.wcs.crval[1])) + print('CRPIX : %r %r' % (self.wcs.crpix[0], self.wcs.crpix[1])) + print('NAXIS : %d %d' % (self.naxis1, self.naxis2)) + print('Plate Scale : %r' % self.pscale) + print('ORIENTAT : %r' % self.orientat) diff --git a/lib/stwcs/wcsutil/instruments.py b/lib/stwcs/wcsutil/instruments.py index 8641e51..45da046 100644 --- a/lib/stwcs/wcsutil/instruments.py +++ b/lib/stwcs/wcsutil/instruments.py @@ -1,6 +1,6 @@ -from __future__ import division # confidence high +from __future__ import absolute_import, division, print_function # confidence high -from mappings import ins_spec_kw +from .mappings import ins_spec_kw class InstrWCS(object): """ @@ -157,7 +157,7 @@ class ACSWCS(InstrWCS): try: self.detector = self.primhdr['DETECTOR'] except KeyError: - print 'ERROR: Detector kw not found.\n' + print('ERROR: Detector kw not found.\n') raise def set_parity(self): @@ -165,7 +165,7 @@ class ACSWCS(InstrWCS): 'HRC':[[-1.0,0.0],[0.0,1.0]], 'SBC':[[-1.0,0.0],[0.0,1.0]]} - if self.detector not in parity.keys(): + if self.detector not in parity: parity = InstrWCS.set_parity(self) else: self.parity = parity[self.detector] @@ -208,7 +208,7 @@ class WFPC2WCS(InstrWCS): try: self.detector = self.exthdr['DETECTOR'] except KeyError: - print 'ERROR: Detector kw not found.\n' + print('ERROR: Detector kw not found.\n') raise @@ -227,7 +227,7 @@ class WFC3WCS(InstrWCS): try: self.detector = self.primhdr['DETECTOR'] except KeyError: - print 'ERROR: Detector kw not found.\n' + print('ERROR: Detector kw not found.\n') raise def set_filter1(self): @@ -243,7 +243,7 @@ class WFC3WCS(InstrWCS): parity = {'UVIS':[[-1.0,0.0],[0.0,1.0]], 'IR':[[-1.0,0.0],[0.0,1.0]]} - if self.detector not in parity.keys(): + if self.detector not in parity: parity = InstrWCS.set_parity(self) else: self.parity = parity[self.detector] @@ -278,7 +278,7 @@ class NICMOSWCS(InstrWCS): try: self.detector = self.primhdr['CAMERA'] except KeyError: - print 'ERROR: Detector kw not found.\n' + print('ERROR: Detector kw not found.\n') raise class STISWCS(InstrWCS): @@ -309,7 +309,7 @@ class STISWCS(InstrWCS): try: self.detector = self.primhdr['DETECTOR'] except KeyError: - print 'ERROR: Detector kw not found.\n' + print('ERROR: Detector kw not found.\n') raise def set_date_obs(self): diff --git a/lib/stwcs/wcsutil/mosaic.py b/lib/stwcs/wcsutil/mosaic.py index 7efefc3..9d2d0a3 100644 --- a/lib/stwcs/wcsutil/mosaic.py +++ b/lib/stwcs/wcsutil/mosaic.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, print_function import numpy as np from matplotlib import pyplot as plt from astropy.io import fits @@ -86,10 +86,10 @@ def updatehdr(fname, wcsobj, wkey, wcsname, ext=1, clobber=False): hdr = fits.getheader(fname, ext=ext) all_keys = list(string.ascii_uppercase) if wkey.upper() not in all_keys: - raise KeyError, "wkey must be one character: A-Z" + raise KeyError("wkey must be one character: A-Z") if wkey not in altwcs.available_wcskeys(hdr): if not clobber: - raise ValueError, "wkey %s is already in use. Use clobber=True to overwrite it or specify a different key." %wkey + raise ValueError("wkey %s is already in use. Use clobber=True to overwrite it or specify a different key." %wkey) else: altwcs.deleteWCS(fname, ext=ext, wcskey='V') f = fits.open(fname, mode='update') @@ -97,7 +97,7 @@ def updatehdr(fname, wcsobj, wkey, wcsname, ext=1, clobber=False): hwcs = wcs2header(wcsobj) wcsnamekey = 'WCSNAME' + wkey f[ext].header[wcsnamekey] = wcsname - for k in hwcs.keys(): + for k in hwcs: f[ext].header[k[:7]+wkey] = hwcs[k] f.close() @@ -164,17 +164,17 @@ def readWCS(input, exts=None, extname=None): continue fobj.close() if fomited != []: - print "These files were skipped:" + print("These files were skipped:") for f in fomited: - print f + print(f) return wcso def validateExt(ext): if not isinstance(ext, int) and not isinstance(ext, tuple) \ and not isinstance(ext, list): - print "Ext must be integer, tuple, a list of int extension numbers, \ - or a list of tuples representing a fits extension, for example ('sci', 1)." + print("Ext must be integer, tuple, a list of int extension numbers, \ + or a list of tuples representing a fits extension, for example ('sci', 1).") return False else: return True diff --git a/lib/stwcs/wcsutil/wcscorr.py b/lib/stwcs/wcsutil/wcscorr.py index fedc2b2..3f9b7d5 100644 --- a/lib/stwcs/wcsutil/wcscorr.py +++ b/lib/stwcs/wcsutil/wcscorr.py @@ -1,12 +1,14 @@ +from __future__ import absolute_import, division, print_function + import os,copy -from astropy.io import fits import numpy as np +from astropy.io import fits -from stsci.tools import fileutil import stwcs from stwcs.wcsutil import altwcs from stwcs.updatewcs import utils -import convertwcs +from stsci.tools import fileutil +from . import convertwcs DEFAULT_WCS_KEYS = ['CRVAL1','CRVAL2','CRPIX1','CRPIX2', 'CD1_1','CD1_2','CD2_1','CD2_2', @@ -51,7 +53,7 @@ def init_wcscorr(input, force=False): return else: del fimg['wcscorr'] - print 'Initializing new WCSCORR table for ',fimg.filename() + print('Initializing new WCSCORR table for ',fimg.filename()) used_wcskeys = altwcs.wcskeys(fimg['SCI', 1].header) @@ -73,7 +75,7 @@ def init_wcscorr(input, force=False): idc2header = True if wcs1.idcscale is None: idc2header = False - wcs_keywords = wcs1.wcs2header(idc2hdr=idc2header).keys() + wcs_keywords = list(wcs1.wcs2header(idc2hdr=idc2header).keys()) prihdr = fimg[0].header prihdr_keys = DEFAULT_PRI_KEYS @@ -82,7 +84,7 @@ def init_wcscorr(input, force=False): 'D2IMNAME':stwcs.updatewcs.utils.build_d2imname} # Now copy original OPUS values into table - for extver in xrange(1, numsci + 1): + for extver in range(1, numsci + 1): rowind = find_wcscorr_row(wcsext.data, {'WCS_ID': 'OPUS', 'EXTVER': extver, 'WCS_key':'O'}) @@ -107,7 +109,7 @@ def init_wcscorr(input, force=False): if wcsext.data.field('CRVAL1')[rownum] != 0: # If we find values for these keywords already in the table, do not # overwrite them again - print 'WCS keywords already updated...' + print('WCS keywords already updated...') break for key in wcs_keywords: if key in wcsext.data.names: @@ -129,7 +131,7 @@ def init_wcscorr(input, force=False): # TODO: Much of this appears to be redundant with update_wcscorr; consider # merging them... for uwkey in used_wcskeys: - for extver in xrange(1, numsci + 1): + for extver in range(1, numsci + 1): hdr = fimg['SCI', extver].header wcs = stwcs.wcsutil.HSTWCS(fimg, ext=('SCI', extver), wcskey=uwkey) @@ -146,7 +148,7 @@ def init_wcscorr(input, force=False): if len(rows[0]) > 0: rownum = np.where(rowind)[0][0] else: - print 'No available rows found for updating. ' + print('No available rows found for updating. ') # Update selection columns for this row with relevant values wcsext.data.field('WCS_ID')[rownum] = wcsid @@ -294,7 +296,7 @@ def update_wcscorr(dest, source=None, extname='SCI', wcs_id=None, active=True): for colname in wcscorr_cols: if colname not in old_table.data.columns.names: - print "WARNING: Replacing outdated WCSCORR table..." + print("WARNING: Replacing outdated WCSCORR table...") outdated_table = old_table.copy() del dest['WCSCORR'] init_wcscorr(dest) @@ -305,7 +307,7 @@ def update_wcscorr(dest, source=None, extname='SCI', wcs_id=None, active=True): # extension version; if this should not be assumed then this can be # modified... wcs_keys = altwcs.wcskeys(source[(extname, 1)].header) - wcs_keys = filter(None, wcs_keys) + wcs_keys = [kk for kk in wcs_keys if kk] if ' ' not in wcs_keys: wcs_keys.append(' ') # Insure that primary WCS gets used # apply logic for only updating WCSCORR table with specified keywords # corresponding to the WCS with WCSNAME=wcs_id @@ -319,7 +321,7 @@ def update_wcscorr(dest, source=None, extname='SCI', wcs_id=None, active=True): wkeys.remove(' ') wcs_keys = wkeys wcshdr = stwcs.wcsutil.HSTWCS(source, ext=(extname, 1)).wcs2header() - wcs_keywords = wcshdr.keys() + wcs_keywords = list(wcshdr.keys()) if 'O' in wcs_keys: wcs_keys.remove('O') # 'O' is reserved for original OPUS WCS @@ -368,7 +370,7 @@ def update_wcscorr(dest, source=None, extname='SCI', wcs_id=None, active=True): wcshdr = wcs.wcs2header() # Update selection column values - for key, val in selection.iteritems(): + for key, val in selection.items(): if key in new_table.data.names: new_table.data.field(key)[idx] = val @@ -521,7 +523,7 @@ def create_wcscorr(descrip=False, numrows=1, padding=0): array=np.array(['OPUS'] * numrows + [''] * padding, dtype='S24')) extver_col = fits.Column(name='EXTVER', format='I', - array=np.array(range(1, numrows + 1), + array=np.array(list(range(1, numrows + 1)), dtype=np.int16)) wcskey_col = fits.Column(name='WCS_key', format='A', array=np.array(['O'] * numrows + [''] * padding, @@ -572,16 +574,16 @@ def delete_wcscorr_row(wcstab,selections=None,rows=None): """ if selections is None and rows is None: - print 'ERROR: Some row selection information must be provided!' - print ' Either a row numbers or "selections" must be provided.' + print('ERROR: Some row selection information must be provided!') + print(' Either a row numbers or "selections" must be provided.') raise ValueError delete_rows = None if rows is None: if 'wcs_id' in selections and selections['wcs_id'] == 'OPUS': delete_rows = None - print 'WARNING: OPUS WCS information can not be deleted from WCSCORR table.' - print ' This row will not be deleted!' + print('WARNING: OPUS WCS information can not be deleted from WCSCORR table.') + print(' This row will not be deleted!') else: rowind = find_wcscorr_row(wcstab, selections=selections) delete_rows = np.where(rowind)[0].tolist() @@ -626,8 +628,8 @@ def update_wcscorr_column(wcstab, column, values, selections=None, rows=None): of the value of 'selections' """ if selections is None and rows is None: - print 'ERROR: Some row selection information must be provided!' - print ' Either a row numbers or "selections" must be provided.' + print('ERROR: Some row selection information must be provided!') + print(' Either a row numbers or "selections" must be provided.') raise ValueError if not isinstance(values, list): @@ -637,8 +639,8 @@ def update_wcscorr_column(wcstab, column, values, selections=None, rows=None): if rows is None: if 'wcs_id' in selections and selections['wcs_id'] == 'OPUS': update_rows = None - print 'WARNING: OPUS WCS information can not be deleted from WCSCORR table.' - print ' This row will not be deleted!' + print('WARNING: OPUS WCS information can not be deleted from WCSCORR table.') + print(' This row will not be deleted!') else: rowind = find_wcscorr_row(wcstab, selections=selections) update_rows = np.where(rowind)[0].tolist() @@ -652,11 +654,11 @@ def update_wcscorr_column(wcstab, column, values, selections=None, rows=None): # Expand single input value to apply to all selected rows if len(values) > 1 and len(values) < len(update_rows): - print 'ERROR: Number of new values',len(values) - print ' does not match number of rows',len(update_rows),' to be updated!' - print ' Please enter either 1 value or the same number of values' - print ' as there are rows to be updated.' - print ' Table will not be updated...' + print('ERROR: Number of new values',len(values)) + print(' does not match number of rows',len(update_rows),' to be updated!') + print(' Please enter either 1 value or the same number of values') + print(' as there are rows to be updated.') + print(' Table will not be updated...') raise ValueError if len(values) == 1 and len(values) < len(update_rows): |