summaryrefslogtreecommitdiff
path: root/stwcs/updatewcs/__init__.py
diff options
context:
space:
mode:
Diffstat (limited to 'stwcs/updatewcs/__init__.py')
-rw-r--r--stwcs/updatewcs/__init__.py112
1 files changed, 61 insertions, 51 deletions
diff --git a/stwcs/updatewcs/__init__.py b/stwcs/updatewcs/__init__.py
index eb5e850..72d2961 100644
--- a/stwcs/updatewcs/__init__.py
+++ b/stwcs/updatewcs/__init__.py
@@ -1,14 +1,14 @@
-from __future__ import absolute_import, division, print_function # confidence high
-
+from __future__ import absolute_import, division, print_function
+import atexit
from astropy.io import fits
-from stwcs import wcsutil
-from stwcs.wcsutil import HSTWCS
-import stwcs
+from .. import wcsutil
+from ..wcsutil import HSTWCS
+from .. import __version__
from astropy import wcs as pywcs
import astropy
-from . import utils, corrections, makewcs
+from . import utils, corrections
from . import npol, det2im
from stsci.tools import parseinput, fileutil
from . import apply_corrections
@@ -17,10 +17,10 @@ import time
import logging
logger = logging.getLogger('stwcs.updatewcs')
-import atexit
atexit.register(logging.shutdown)
-#Note: The order of corrections is important
+# Note: The order of corrections is important
+
def updatewcs(input, vacorr=True, tddcorr=True, npolcorr=True, d2imcorr=True,
checkfiles=True, verbose=False):
@@ -62,7 +62,7 @@ def updatewcs(input, vacorr=True, tddcorr=True, npolcorr=True, d2imcorr=True,
geis and waiver fits files will be converted to MEF format.
Default value is True for standalone mode.
"""
- if verbose == False:
+ if not verbose:
logger.setLevel(100)
else:
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
@@ -74,12 +74,12 @@ def updatewcs(input, vacorr=True, tddcorr=True, npolcorr=True, d2imcorr=True,
logger.setLevel(verbose)
args = "vacorr=%s, tddcorr=%s, npolcorr=%s, d2imcorr=%s, checkfiles=%s, \
" % (str(vacorr), str(tddcorr), str(npolcorr),
- str(d2imcorr), str(checkfiles))
+ str(d2imcorr), str(checkfiles))
logger.info('\n\tStarting UPDATEWCS: %s', time.asctime())
files = parseinput.parseinput(input)[0]
logger.info("\n\tInput files: %s, " % [i for i in files])
- logger.info("\n\tInput arguments: %s" %args)
+ logger.info("\n\tInput arguments: %s" % args)
if checkfiles:
files = checkFiles(files)
if not files:
@@ -87,8 +87,8 @@ def updatewcs(input, vacorr=True, tddcorr=True, npolcorr=True, d2imcorr=True,
return
for f in files:
- acorr = apply_corrections.setCorrections(f, vacorr=vacorr, \
- tddcorr=tddcorr,npolcorr=npolcorr, d2imcorr=d2imcorr)
+ acorr = apply_corrections.setCorrections(f, vacorr=vacorr, tddcorr=tddcorr,
+ npolcorr=npolcorr, d2imcorr=d2imcorr)
if 'MakeWCS' in acorr and newIDCTAB(f):
logger.warning("\n\tNew IDCTAB file detected. All current WCSs will be deleted")
cleanWCS(f)
@@ -97,6 +97,7 @@ def updatewcs(input, vacorr=True, tddcorr=True, npolcorr=True, d2imcorr=True,
return files
+
def makecorr(fname, allowed_corr):
"""
Purpose
@@ -111,11 +112,11 @@ def makecorr(fname, allowed_corr):
"""
logger.info("Allowed corrections: {0}".format(allowed_corr))
f = fits.open(fname, mode='update')
- #Determine the reference chip and create the reference HSTWCS object
+ # Determine the reference chip and create the reference HSTWCS object
nrefchip, nrefext = getNrefchip(f)
wcsutil.restoreWCS(f, nrefext, wcskey='O')
rwcs = HSTWCS(fobj=f, ext=nrefext)
- rwcs.readModel(update=True,header=f[nrefext].header)
+ rwcs.readModel(update=True, header=f[nrefext].header)
if 'DET2IMCorr' in allowed_corr:
kw2update = det2im.DET2IMCorr.updateWCS(f)
@@ -127,16 +128,16 @@ def makecorr(fname, allowed_corr):
if 'extname' in extn.header:
extname = extn.header['extname'].lower()
- if extname == 'sci':
+ if extname == 'sci':
wcsutil.restoreWCS(f, ext=i, wcskey='O')
sciextver = extn.header['extver']
ref_wcs = rwcs.deepcopy()
hdr = extn.header
ext_wcs = HSTWCS(fobj=f, ext=i)
- ### check if it exists first!!!
+ # check if it exists first!!!
# 'O ' can be safely archived again because it has been restored first.
wcsutil.archiveWCS(f, ext=i, wcskey="O", wcsname="OPUS", reusekey=True)
- ext_wcs.readModel(update=True,header=hdr)
+ ext_wcs.readModel(update=True, header=hdr)
for c in allowed_corr:
if c != 'NPOLCorr' and c != 'DET2IMCorr':
corr_klass = corrections.__getattribute__(c)
@@ -147,14 +148,14 @@ def makecorr(fname, allowed_corr):
idcname = f[0].header.get('IDCTAB', " ")
if idcname.strip() and 'idc.fits' in idcname:
wname = ''.join(['IDC_',
- utils.extract_rootname(idcname,suffix='_idc')])
+ utils.extract_rootname(idcname, suffix='_idc')])
else: wname = " "
hdr['WCSNAME'] = wname
elif extname in ['err', 'dq', 'sdq', 'samp', 'time']:
cextver = extn.header['extver']
if cextver == sciextver:
- hdr = f[('SCI',sciextver)].header
+ hdr = f[('SCI', sciextver)].header
w = pywcs.WCS(hdr, f)
copyWCS(w, extn.header)
@@ -167,14 +168,14 @@ def makecorr(fname, allowed_corr):
f[1].header[kw] = kw2update[kw]
# Finally record the version of the software which updated the WCS
if 'HISTORY' in f[0].header:
- f[0].header.set('UPWCSVER', value=stwcs.__version__,
+ f[0].header.set('UPWCSVER', value=__version__,
comment="Version of STWCS used to updated the WCS",
before='HISTORY')
f[0].header.set('PYWCSVER', value=astropy.__version__,
comment="Version of PYWCS used to updated the WCS",
before='HISTORY')
elif 'ASN_MTYP' in f[0].header:
- f[0].header.set('UPWCSVER', value=stwcs.__version__,
+ f[0].header.set('UPWCSVER', value=__version__,
comment="Version of STWCS used to updated the WCS",
after='ASN_MTYP')
f[0].header.set('PYWCSVER', value=astropy.__version__,
@@ -185,20 +186,21 @@ def makecorr(fname, allowed_corr):
for i in range(len(f[0].header) - 1, 0, -1):
if f[0].header[i].strip() != '':
break
- f[0].header.set('UPWCSVER', stwcs.__version__,
+ f[0].header.set('UPWCSVER', __version__,
"Version of STWCS used to updated the WCS",
after=i)
f[0].header.set('PYWCSVER', astropy.__version__,
"Version of PYWCS used to updated the WCS",
after=i)
# add additional keywords to be used by headerlets
- distdict = utils.construct_distname(f,rwcs)
+ distdict = utils.construct_distname(f, rwcs)
f[0].header['DISTNAME'] = distdict['DISTNAME']
f[0].header['SIPNAME'] = distdict['SIPNAME']
# Make sure NEXTEND keyword remains accurate
- f[0].header['NEXTEND'] = len(f)-1
+ f[0].header['NEXTEND'] = len(f) - 1
f.close()
+
def copyWCS(w, ehdr):
"""
This is a convenience function to copy a WCS object
@@ -214,6 +216,7 @@ def copyWCS(w, ehdr):
key = k[:7]
ehdr[key] = hwcs[k]
+
def getNrefchip(fobj):
"""
@@ -235,15 +238,15 @@ def getNrefchip(fobj):
if instrument == 'WFPC2':
chipkw = 'DETECTOR'
- extvers = [("SCI",img.header['EXTVER']) for img in
- fobj[1:] if img.header['EXTNAME'].lower()=='sci']
+ extvers = [("SCI", img.header['EXTVER']) for img in
+ fobj[1:] if img.header['EXTNAME'].lower() == 'sci']
detectors = [img.header[chipkw] for img in fobj[1:] if
- img.header['EXTNAME'].lower()=='sci']
+ img.header['EXTNAME'].lower() == 'sci']
fitsext = [i for i in range(len(fobj))[1:] if
- fobj[i].header['EXTNAME'].lower()=='sci']
- det2ext=dict(list(zip(detectors, extvers)))
- ext2det=dict(list(zip(extvers, detectors)))
- ext2fitsext=dict(list(zip(extvers, fitsext)))
+ fobj[i].header['EXTNAME'].lower() == 'sci']
+ 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])
@@ -256,15 +259,15 @@ def getNrefchip(fobj):
elif (instrument == 'ACS' and fobj[0].header['DETECTOR'] == 'WFC') or \
(instrument == 'WFC3' and fobj[0].header['DETECTOR'] == 'UVIS'):
chipkw = 'CCDCHIP'
- extvers = [("SCI",img.header['EXTVER']) for img in
- fobj[1:] if img.header['EXTNAME'].lower()=='sci']
+ extvers = [("SCI", img.header['EXTVER']) for img in
+ fobj[1:] if img.header['EXTNAME'].lower() == 'sci']
detectors = [img.header[chipkw] for img in fobj[1:] if
- img.header['EXTNAME'].lower()=='sci']
+ img.header['EXTNAME'].lower() == 'sci']
fitsext = [i for i in range(len(fobj))[1:] if
- fobj[i].header['EXTNAME'].lower()=='sci']
- det2ext=dict(list(zip(detectors, extvers)))
- ext2det=dict(list(zip(extvers, detectors)))
- ext2fitsext=dict(list(zip(extvers, fitsext)))
+ fobj[i].header['EXTNAME'].lower() == 'sci']
+ 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])
@@ -276,12 +279,13 @@ def getNrefchip(fobj):
else:
for i in range(len(fobj)):
extname = fobj[i].header.get('EXTNAME', None)
- if extname != None and extname.lower == 'sci':
+ if extname is not None and extname.lower == 'sci':
nrefext = i
break
return nrefchip, nrefext
+
def checkFiles(input):
"""
Checks that input files are in the correct format.
@@ -292,13 +296,14 @@ def checkFiles(input):
removed_files = []
newfiles = []
if not isinstance(input, list):
- input=[input]
+ input = [input]
for file in input:
try:
- imgfits,imgtype = fileutil.isFits(file)
+ imgfits, imgtype = fileutil.isFits(file)
except IOError:
- logger.warning( "\n\tFile %s could not be found, removing it from the input list.\n" %file)
+ logger.warning("File {0} could not be found, removing it from the"
+ "input list.".format(file))
removed_files.append(file)
continue
# Check for existence of waiver FITS input, and quit if found.
@@ -306,8 +311,9 @@ def checkFiles(input):
if imgfits:
if imgtype == 'waiver':
newfilename = waiver2mef(file, convert_dq=True)
- if newfilename == None:
- logger.warning("\n\tRemoving file %s from input list - could not convert waiver to mef" %file)
+ if newfilename is None:
+ logger.warning("Could not convert waiver to mef."
+ "Removing file {0} from input list".format(file))
removed_files.append(file)
else:
newfiles.append(newfilename)
@@ -319,24 +325,26 @@ def checkFiles(input):
# Convert the corresponding data quality file if present
if not imgfits:
newfilename = geis2mef(file, convert_dq=True)
- if newfilename == None:
- logger.warning("\n\tRemoving file %s from input list - could not convert geis to mef" %file)
+ if newfilename is None:
+ logger.warning("Could not convert file {0} from geis to mef, removing it from input list".format(file))
removed_files.append(file)
else:
newfiles.append(newfilename)
if removed_files:
- logger.warning('\n\tThe following files will be removed from the list of files to be processed %s' % removed_files)
+ logger.warning('\n\tThe following files will be removed from the list of files',
+ 'to be processed %s' % removed_files)
newfiles = checkFiles(newfiles)[0]
logger.info("\n\tThese files passed the input check and will be processed: %s" % newfiles)
return newfiles
+
def newIDCTAB(fname):
- #When this is called we know there's a kw IDCTAB in the header
+ # When this is called we know there's a kw IDCTAB in the header
hdul = fits.open(fname)
idctab = fileutil.osfn(hdul[0].header['IDCTAB'])
try:
- #check for the presence of IDCTAB in the first extension
+ # check for the presence of IDCTAB in the first extension
oldidctab = fileutil.osfn(hdul[1].header['IDCTAB'])
except KeyError:
return False
@@ -345,6 +353,7 @@ def newIDCTAB(fname):
else:
return True
+
def cleanWCS(fname):
# A new IDCTAB means all previously computed WCS's are invalid
# We are deleting all of them except the original OPUS WCS.
@@ -363,6 +372,7 @@ def cleanWCS(fname):
# Some extensions don't have the alternate (or any) WCS keywords
continue
+
def getCorrections(instrument):
"""
Print corrections available for an instrument
@@ -373,4 +383,4 @@ 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])
+ for c in acorr: print(c, ': ', apply_corrections.cnames[c])