summaryrefslogtreecommitdiff
path: root/lib/stwcs/wcsutil
diff options
context:
space:
mode:
Diffstat (limited to 'lib/stwcs/wcsutil')
-rw-r--r--lib/stwcs/wcsutil/__init__.py11
-rw-r--r--lib/stwcs/wcsutil/altwcs.py40
-rw-r--r--lib/stwcs/wcsutil/convertwcs.py18
-rw-r--r--lib/stwcs/wcsutil/getinput.py2
-rw-r--r--lib/stwcs/wcsutil/headerlet.py53
-rw-r--r--lib/stwcs/wcsutil/hstwcs.py59
-rw-r--r--lib/stwcs/wcsutil/instruments.py18
-rw-r--r--lib/stwcs/wcsutil/mosaic.py16
-rw-r--r--lib/stwcs/wcsutil/wcscorr.py56
9 files changed, 142 insertions, 131 deletions
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):