summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--defsetup.py18
-rw-r--r--distribute_setup.py485
-rw-r--r--lib/stwcs/__init__.py (renamed from lib/__init__.py)2
-rw-r--r--lib/stwcs/distortion/__init__.py (renamed from distortion/__init__.py)0
-rw-r--r--lib/stwcs/distortion/coeff_converter.py (renamed from distortion/coeff_converter.py)0
-rw-r--r--lib/stwcs/distortion/models.py (renamed from distortion/models.py)0
-rw-r--r--lib/stwcs/distortion/mutil.py (renamed from distortion/mutil.py)2
-rw-r--r--lib/stwcs/distortion/utils.py (renamed from distortion/utils.py)2
-rw-r--r--lib/stwcs/updatewcs/__init__.py (renamed from updatewcs/__init__.py)6
-rw-r--r--lib/stwcs/updatewcs/apply_corrections.py (renamed from updatewcs/apply_corrections.py)2
-rw-r--r--lib/stwcs/updatewcs/corrections.py (renamed from updatewcs/corrections.py)2
-rw-r--r--lib/stwcs/updatewcs/det2im.py (renamed from updatewcs/det2im.py)2
-rw-r--r--lib/stwcs/updatewcs/makewcs.py (renamed from updatewcs/makewcs.py)96
-rw-r--r--lib/stwcs/updatewcs/npol.py (renamed from updatewcs/npol.py)2
-rw-r--r--lib/stwcs/updatewcs/utils.py (renamed from updatewcs/utils.py)0
-rw-r--r--lib/stwcs/wcsutil/__init__.py (renamed from wcsutil/__init__.py)4
-rw-r--r--lib/stwcs/wcsutil/altwcs.py (renamed from wcsutil/altwcs.py)0
-rw-r--r--lib/stwcs/wcsutil/convertwcs.py (renamed from wcsutil/convertwcs.py)2
-rw-r--r--lib/stwcs/wcsutil/getinput.py (renamed from wcsutil/getinput.py)2
-rw-r--r--lib/stwcs/wcsutil/headerlet.py (renamed from wcsutil/headerlet.py)2
-rw-r--r--lib/stwcs/wcsutil/hstwcs.py (renamed from wcsutil/hstwcs.py)4
-rw-r--r--lib/stwcs/wcsutil/instruments.py (renamed from wcsutil/instruments.py)0
-rw-r--r--lib/stwcs/wcsutil/mappings.py (renamed from wcsutil/mappings.py)0
-rw-r--r--lib/stwcs/wcsutil/mosaic.py (renamed from wcsutil/mosaic.py)2
-rw-r--r--lib/stwcs/wcsutil/wcscorr.py (renamed from wcsutil/wcscorr.py)2
-rw-r--r--setup.cfg33
-rwxr-xr-x[-rw-r--r--]setup.py35
27 files changed, 617 insertions, 88 deletions
diff --git a/defsetup.py b/defsetup.py
deleted file mode 100644
index 2e6d782..0000000
--- a/defsetup.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from __future__ import division # confidence high
-
-import sys
-
-pkg = ["stwcs", 'stwcs.updatewcs', 'stwcs.wcsutil', 'stwcs.distortion']
-
-setupargs = {
- 'version' : "0.8",
- 'description' : "Recomputes the WCS of an HST observation and puts all istortion corrections in the headers.",
- 'package_dir': {'stwcs':'lib', 'stwcs.updatewcs': 'updatewcs',
- 'stwcs.wcsutil': 'wcsutil', 'stwcs.distortion': 'distortion'},
-
- 'author' : "Nadia Dencheva, Warren Hack",
- 'author_email' : "help@stsci.edu",
- 'license' : "http://www.stsci.edu/resources/software_hardware/pyraf/LICENSE",
- 'platforms' : ["Linux","Solaris","Mac OS X", "Windows"],
-}
-
diff --git a/distribute_setup.py b/distribute_setup.py
new file mode 100644
index 0000000..bbb6f3c
--- /dev/null
+++ b/distribute_setup.py
@@ -0,0 +1,485 @@
+#!python
+"""Bootstrap distribute installation
+
+If you want to use setuptools in your package's setup.py, just include this
+file in the same directory with it, and add this to the top of your setup.py::
+
+ from distribute_setup import use_setuptools
+ use_setuptools()
+
+If you want to require a specific version of setuptools, set a download
+mirror, or use an alternate download directory, you can do so by supplying
+the appropriate options to ``use_setuptools()``.
+
+This file can also be run as a script to install or upgrade setuptools.
+"""
+import os
+import sys
+import time
+import fnmatch
+import tempfile
+import tarfile
+from distutils import log
+
+try:
+ from site import USER_SITE
+except ImportError:
+ USER_SITE = None
+
+try:
+ import subprocess
+
+ def _python_cmd(*args):
+ args = (sys.executable,) + args
+ return subprocess.call(args) == 0
+
+except ImportError:
+ # will be used for python 2.3
+ def _python_cmd(*args):
+ args = (sys.executable,) + args
+ # quoting arguments if windows
+ if sys.platform == 'win32':
+ def quote(arg):
+ if ' ' in arg:
+ return '"%s"' % arg
+ return arg
+ args = [quote(arg) for arg in args]
+ return os.spawnl(os.P_WAIT, sys.executable, *args) == 0
+
+DEFAULT_VERSION = "0.6.19"
+DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/"
+SETUPTOOLS_FAKED_VERSION = "0.6c11"
+
+SETUPTOOLS_PKG_INFO = """\
+Metadata-Version: 1.0
+Name: setuptools
+Version: %s
+Summary: xxxx
+Home-page: xxx
+Author: xxx
+Author-email: xxx
+License: xxx
+Description: xxx
+""" % SETUPTOOLS_FAKED_VERSION
+
+
+def _install(tarball):
+ # extracting the tarball
+ tmpdir = tempfile.mkdtemp()
+ log.warn('Extracting in %s', tmpdir)
+ old_wd = os.getcwd()
+ try:
+ os.chdir(tmpdir)
+ tar = tarfile.open(tarball)
+ _extractall(tar)
+ tar.close()
+
+ # going in the directory
+ subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
+ os.chdir(subdir)
+ log.warn('Now working in %s', subdir)
+
+ # installing
+ log.warn('Installing Distribute')
+ if not _python_cmd('setup.py', 'install'):
+ log.warn('Something went wrong during the installation.')
+ log.warn('See the error message above.')
+ finally:
+ os.chdir(old_wd)
+
+
+def _build_egg(egg, tarball, to_dir):
+ # extracting the tarball
+ tmpdir = tempfile.mkdtemp()
+ log.warn('Extracting in %s', tmpdir)
+ old_wd = os.getcwd()
+ try:
+ os.chdir(tmpdir)
+ tar = tarfile.open(tarball)
+ _extractall(tar)
+ tar.close()
+
+ # going in the directory
+ subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
+ os.chdir(subdir)
+ log.warn('Now working in %s', subdir)
+
+ # building an egg
+ log.warn('Building a Distribute egg in %s', to_dir)
+ _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
+
+ finally:
+ os.chdir(old_wd)
+ # returning the result
+ log.warn(egg)
+ if not os.path.exists(egg):
+ raise IOError('Could not build the egg.')
+
+
+def _do_download(version, download_base, to_dir, download_delay):
+ egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg'
+ % (version, sys.version_info[0], sys.version_info[1]))
+ if not os.path.exists(egg):
+ tarball = download_setuptools(version, download_base,
+ to_dir, download_delay)
+ _build_egg(egg, tarball, to_dir)
+ sys.path.insert(0, egg)
+ import setuptools
+ setuptools.bootstrap_install_from = egg
+
+
+def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
+ to_dir=os.curdir, download_delay=15, no_fake=True):
+ # making sure we use the absolute path
+ to_dir = os.path.abspath(to_dir)
+ was_imported = 'pkg_resources' in sys.modules or \
+ 'setuptools' in sys.modules
+ try:
+ try:
+ import pkg_resources
+ if not hasattr(pkg_resources, '_distribute'):
+ if not no_fake:
+ _fake_setuptools()
+ raise ImportError
+ except ImportError:
+ return _do_download(version, download_base, to_dir, download_delay)
+ try:
+ pkg_resources.require("distribute>="+version)
+ return
+ except pkg_resources.VersionConflict:
+ e = sys.exc_info()[1]
+ if was_imported:
+ sys.stderr.write(
+ "The required version of distribute (>=%s) is not available,\n"
+ "and can't be installed while this script is running. Please\n"
+ "install a more recent version first, using\n"
+ "'easy_install -U distribute'."
+ "\n\n(Currently using %r)\n" % (version, e.args[0]))
+ sys.exit(2)
+ else:
+ del pkg_resources, sys.modules['pkg_resources'] # reload ok
+ return _do_download(version, download_base, to_dir,
+ download_delay)
+ except pkg_resources.DistributionNotFound:
+ return _do_download(version, download_base, to_dir,
+ download_delay)
+ finally:
+ if not no_fake:
+ _create_fake_setuptools_pkg_info(to_dir)
+
+def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
+ to_dir=os.curdir, delay=15):
+ """Download distribute from a specified location and return its filename
+
+ `version` should be a valid distribute version number that is available
+ as an egg for download under the `download_base` URL (which should end
+ with a '/'). `to_dir` is the directory where the egg will be downloaded.
+ `delay` is the number of seconds to pause before an actual download
+ attempt.
+ """
+ # making sure we use the absolute path
+ to_dir = os.path.abspath(to_dir)
+ try:
+ from urllib.request import urlopen
+ except ImportError:
+ from urllib2 import urlopen
+ tgz_name = "distribute-%s.tar.gz" % version
+ url = download_base + tgz_name
+ saveto = os.path.join(to_dir, tgz_name)
+ src = dst = None
+ if not os.path.exists(saveto): # Avoid repeated downloads
+ try:
+ log.warn("Downloading %s", url)
+ src = urlopen(url)
+ # Read/write all in one block, so we don't create a corrupt file
+ # if the download is interrupted.
+ data = src.read()
+ dst = open(saveto, "wb")
+ dst.write(data)
+ finally:
+ if src:
+ src.close()
+ if dst:
+ dst.close()
+ return os.path.realpath(saveto)
+
+def _no_sandbox(function):
+ def __no_sandbox(*args, **kw):
+ try:
+ from setuptools.sandbox import DirectorySandbox
+ if not hasattr(DirectorySandbox, '_old'):
+ def violation(*args):
+ pass
+ DirectorySandbox._old = DirectorySandbox._violation
+ DirectorySandbox._violation = violation
+ patched = True
+ else:
+ patched = False
+ except ImportError:
+ patched = False
+
+ try:
+ return function(*args, **kw)
+ finally:
+ if patched:
+ DirectorySandbox._violation = DirectorySandbox._old
+ del DirectorySandbox._old
+
+ return __no_sandbox
+
+def _patch_file(path, content):
+ """Will backup the file then patch it"""
+ existing_content = open(path).read()
+ if existing_content == content:
+ # already patched
+ log.warn('Already patched.')
+ return False
+ log.warn('Patching...')
+ _rename_path(path)
+ f = open(path, 'w')
+ try:
+ f.write(content)
+ finally:
+ f.close()
+ return True
+
+_patch_file = _no_sandbox(_patch_file)
+
+def _same_content(path, content):
+ return open(path).read() == content
+
+def _rename_path(path):
+ new_name = path + '.OLD.%s' % time.time()
+ log.warn('Renaming %s into %s', path, new_name)
+ os.rename(path, new_name)
+ return new_name
+
+def _remove_flat_installation(placeholder):
+ if not os.path.isdir(placeholder):
+ log.warn('Unkown installation at %s', placeholder)
+ return False
+ found = False
+ for file in os.listdir(placeholder):
+ if fnmatch.fnmatch(file, 'setuptools*.egg-info'):
+ found = True
+ break
+ if not found:
+ log.warn('Could not locate setuptools*.egg-info')
+ return
+
+ log.warn('Removing elements out of the way...')
+ pkg_info = os.path.join(placeholder, file)
+ if os.path.isdir(pkg_info):
+ patched = _patch_egg_dir(pkg_info)
+ else:
+ patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO)
+
+ if not patched:
+ log.warn('%s already patched.', pkg_info)
+ return False
+ # now let's move the files out of the way
+ for element in ('setuptools', 'pkg_resources.py', 'site.py'):
+ element = os.path.join(placeholder, element)
+ if os.path.exists(element):
+ _rename_path(element)
+ else:
+ log.warn('Could not find the %s element of the '
+ 'Setuptools distribution', element)
+ return True
+
+_remove_flat_installation = _no_sandbox(_remove_flat_installation)
+
+def _after_install(dist):
+ log.warn('After install bootstrap.')
+ placeholder = dist.get_command_obj('install').install_purelib
+ _create_fake_setuptools_pkg_info(placeholder)
+
+def _create_fake_setuptools_pkg_info(placeholder):
+ if not placeholder or not os.path.exists(placeholder):
+ log.warn('Could not find the install location')
+ return
+ pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1])
+ setuptools_file = 'setuptools-%s-py%s.egg-info' % \
+ (SETUPTOOLS_FAKED_VERSION, pyver)
+ pkg_info = os.path.join(placeholder, setuptools_file)
+ if os.path.exists(pkg_info):
+ log.warn('%s already exists', pkg_info)
+ return
+
+ log.warn('Creating %s', pkg_info)
+ f = open(pkg_info, 'w')
+ try:
+ f.write(SETUPTOOLS_PKG_INFO)
+ finally:
+ f.close()
+
+ pth_file = os.path.join(placeholder, 'setuptools.pth')
+ log.warn('Creating %s', pth_file)
+ f = open(pth_file, 'w')
+ try:
+ f.write(os.path.join(os.curdir, setuptools_file))
+ finally:
+ f.close()
+
+_create_fake_setuptools_pkg_info = _no_sandbox(_create_fake_setuptools_pkg_info)
+
+def _patch_egg_dir(path):
+ # let's check if it's already patched
+ pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
+ if os.path.exists(pkg_info):
+ if _same_content(pkg_info, SETUPTOOLS_PKG_INFO):
+ log.warn('%s already patched.', pkg_info)
+ return False
+ _rename_path(path)
+ os.mkdir(path)
+ os.mkdir(os.path.join(path, 'EGG-INFO'))
+ pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
+ f = open(pkg_info, 'w')
+ try:
+ f.write(SETUPTOOLS_PKG_INFO)
+ finally:
+ f.close()
+ return True
+
+_patch_egg_dir = _no_sandbox(_patch_egg_dir)
+
+def _before_install():
+ log.warn('Before install bootstrap.')
+ _fake_setuptools()
+
+
+def _under_prefix(location):
+ if 'install' not in sys.argv:
+ return True
+ args = sys.argv[sys.argv.index('install')+1:]
+ for index, arg in enumerate(args):
+ for option in ('--root', '--prefix'):
+ if arg.startswith('%s=' % option):
+ top_dir = arg.split('root=')[-1]
+ return location.startswith(top_dir)
+ elif arg == option:
+ if len(args) > index:
+ top_dir = args[index+1]
+ return location.startswith(top_dir)
+ if arg == '--user' and USER_SITE is not None:
+ return location.startswith(USER_SITE)
+ return True
+
+
+def _fake_setuptools():
+ log.warn('Scanning installed packages')
+ try:
+ import pkg_resources
+ except ImportError:
+ # we're cool
+ log.warn('Setuptools or Distribute does not seem to be installed.')
+ return
+ ws = pkg_resources.working_set
+ try:
+ setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools',
+ replacement=False))
+ except TypeError:
+ # old distribute API
+ setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools'))
+
+ if setuptools_dist is None:
+ log.warn('No setuptools distribution found')
+ return
+ # detecting if it was already faked
+ setuptools_location = setuptools_dist.location
+ log.warn('Setuptools installation detected at %s', setuptools_location)
+
+ # if --root or --preix was provided, and if
+ # setuptools is not located in them, we don't patch it
+ if not _under_prefix(setuptools_location):
+ log.warn('Not patching, --root or --prefix is installing Distribute'
+ ' in another location')
+ return
+
+ # let's see if its an egg
+ if not setuptools_location.endswith('.egg'):
+ log.warn('Non-egg installation')
+ res = _remove_flat_installation(setuptools_location)
+ if not res:
+ return
+ else:
+ log.warn('Egg installation')
+ pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
+ if (os.path.exists(pkg_info) and
+ _same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
+ log.warn('Already patched.')
+ return
+ log.warn('Patching...')
+ # let's create a fake egg replacing setuptools one
+ res = _patch_egg_dir(setuptools_location)
+ if not res:
+ return
+ log.warn('Patched done.')
+ _relaunch()
+
+
+def _relaunch():
+ log.warn('Relaunching...')
+ # we have to relaunch the process
+ # pip marker to avoid a relaunch bug
+ if sys.argv[:3] == ['-c', 'install', '--single-version-externally-managed']:
+ sys.argv[0] = 'setup.py'
+ args = [sys.executable] + sys.argv
+ sys.exit(subprocess.call(args))
+
+
+def _extractall(self, path=".", members=None):
+ """Extract all members from the archive to the current working
+ directory and set owner, modification time and permissions on
+ directories afterwards. `path' specifies a different directory
+ to extract to. `members' is optional and must be a subset of the
+ list returned by getmembers().
+ """
+ import copy
+ import operator
+ from tarfile import ExtractError
+ directories = []
+
+ if members is None:
+ members = self
+
+ for tarinfo in members:
+ if tarinfo.isdir():
+ # Extract directories with a safe mode.
+ directories.append(tarinfo)
+ tarinfo = copy.copy(tarinfo)
+ tarinfo.mode = 448 # decimal for oct 0700
+ self.extract(tarinfo, path)
+
+ # Reverse sort directories.
+ if sys.version_info < (2, 4):
+ def sorter(dir1, dir2):
+ return cmp(dir1.name, dir2.name)
+ directories.sort(sorter)
+ directories.reverse()
+ else:
+ directories.sort(key=operator.attrgetter('name'), reverse=True)
+
+ # Set correct owner, mtime and filemode on directories.
+ for tarinfo in directories:
+ dirpath = os.path.join(path, tarinfo.name)
+ try:
+ self.chown(tarinfo, dirpath)
+ self.utime(tarinfo, dirpath)
+ self.chmod(tarinfo, dirpath)
+ except ExtractError:
+ e = sys.exc_info()[1]
+ if self.errorlevel > 1:
+ raise
+ else:
+ self._dbg(1, "tarfile: %s" % e)
+
+
+def main(argv, version=DEFAULT_VERSION):
+ """Install or upgrade setuptools and EasyInstall"""
+ tarball = download_setuptools()
+ _install(tarball)
+
+
+if __name__ == '__main__':
+ main(sys.argv[1:])
diff --git a/lib/__init__.py b/lib/stwcs/__init__.py
index e2380a8..a32f8b9 100644
--- a/lib/__init__.py
+++ b/lib/stwcs/__init__.py
@@ -13,7 +13,7 @@ from __future__ import division # confidence high
import distortion
import pywcs
-from pytools import fileutil
+from stsci.tools import fileutil
__docformat__ = 'restructuredtext'
diff --git a/distortion/__init__.py b/lib/stwcs/distortion/__init__.py
index e69de29..e69de29 100644
--- a/distortion/__init__.py
+++ b/lib/stwcs/distortion/__init__.py
diff --git a/distortion/coeff_converter.py b/lib/stwcs/distortion/coeff_converter.py
index f2eb4ad..f2eb4ad 100644
--- a/distortion/coeff_converter.py
+++ b/lib/stwcs/distortion/coeff_converter.py
diff --git a/distortion/models.py b/lib/stwcs/distortion/models.py
index 96d5d72..96d5d72 100644
--- a/distortion/models.py
+++ b/lib/stwcs/distortion/models.py
diff --git a/distortion/mutil.py b/lib/stwcs/distortion/mutil.py
index 2934d17..ab9eac2 100644
--- a/distortion/mutil.py
+++ b/lib/stwcs/distortion/mutil.py
@@ -1,6 +1,6 @@
from __future__ import division # confidence high
-from pytools import fileutil
+from stsci.tools import fileutil
import numpy as np
import string
import calendar
diff --git a/distortion/utils.py b/lib/stwcs/distortion/utils.py
index a99e227..7f937f7 100644
--- a/distortion/utils.py
+++ b/lib/stwcs/distortion/utils.py
@@ -5,7 +5,7 @@ import pywcs
import pyfits
from stwcs import wcsutil
from numpy import sqrt, arctan2
-from pytools import fileutil
+from stsci.tools import fileutil
def output_wcs(list_of_wcsobj, ref_wcs=None, owcs=None, undistort=True):
"""
diff --git a/updatewcs/__init__.py b/lib/stwcs/updatewcs/__init__.py
index ab852d0..53e1c21 100644
--- a/updatewcs/__init__.py
+++ b/lib/stwcs/updatewcs/__init__.py
@@ -10,7 +10,7 @@ import pywcs
import utils, corrections, makewcs
import npol, det2im
-from pytools import parseinput, fileutil
+from stsci.tools import parseinput, fileutil
import apply_corrections
import time
@@ -43,7 +43,7 @@ def updatewcs(input, vacorr=True, tddcorr=True, npolcorr=True, d2imcorr=True,
Dependencies
------------
- `pytools`
+ `stsci.tools`
`pyfits`
`pywcs`
@@ -314,7 +314,7 @@ def checkFiles(input):
Checks that input files are in the correct format.
Converts geis and waiver fits files to multiextension fits.
"""
- from pytools.check_files import geis2mef, waiver2mef, checkFiles
+ from stsci.tools.check_files import geis2mef, waiver2mef, checkFiles
logger.info("\n\tChecking files %s" % input)
removed_files = []
newfiles = []
diff --git a/updatewcs/apply_corrections.py b/lib/stwcs/updatewcs/apply_corrections.py
index 881e5d1..fbcb502 100644
--- a/updatewcs/apply_corrections.py
+++ b/lib/stwcs/updatewcs/apply_corrections.py
@@ -3,7 +3,7 @@ from __future__ import division # confidence high
import os
import pyfits
import time
-from pytools import fileutil
+from stsci.tools import fileutil
import os.path
from stwcs.wcsutil import altwcs
diff --git a/updatewcs/corrections.py b/lib/stwcs/updatewcs/corrections.py
index 2bbdfb1..b227d05 100644
--- a/updatewcs/corrections.py
+++ b/lib/stwcs/updatewcs/corrections.py
@@ -3,7 +3,7 @@ from __future__ import division # confidence high
import datetime
import numpy as np
from numpy import linalg
-from pytools import fileutil
+from stsci.tools import fileutil
from utils import diff_angles
import makewcs, npol
diff --git a/updatewcs/det2im.py b/lib/stwcs/updatewcs/det2im.py
index b59ca17..fe683b4 100644
--- a/updatewcs/det2im.py
+++ b/lib/stwcs/updatewcs/det2im.py
@@ -2,7 +2,7 @@ from __future__ import division # confidence high
import time
import pyfits
-from pytools import fileutil
+from stsci.tools import fileutil
import utils
import logging
diff --git a/updatewcs/makewcs.py b/lib/stwcs/updatewcs/makewcs.py
index f23da7e..bb86be9 100644
--- a/updatewcs/makewcs.py
+++ b/lib/stwcs/updatewcs/makewcs.py
@@ -4,47 +4,47 @@ from stwcs import DEGTORAD, RADTODEG
import numpy as np
from math import sin, sqrt, pow, cos, asin, atan2,pi
import utils
-from pytools import fileutil
+from stsci.tools import fileutil
import logging, time
-logger = logging.getLogger("stwcs.updatewcs.makewcs")
+logger = logging.getLogger(__name__)
class MakeWCS(object):
"""
Recompute basic WCS keywords based on PA_V3 and distortion model.
-
+
Notes
-----
- Compute the reference chip WCS:
-
+
-- CRVAL: transform the model XREF/YREF to the sky
- -- PA_V3 is calculated at the target position and adjusted
+ -- PA_V3 is calculated at the target position and adjusted
for each chip orientation
-- CD: PA_V3 and the model scale are used to cnstruct a CD matrix
-
+
- Compute the second chip WCS:
- -- CRVAL: - the distance between the zero points of the two
+ -- CRVAL: - the distance between the zero points of the two
chip models on the sky
- -- CD matrix: first order coefficients are added to the components
- of this distance and transfered on the sky. The difference
+ -- CD matrix: first order coefficients are added to the components
+ of this distance and transfered on the sky. The difference
between CRVAL and these vectors is the new CD matrix for each chip.
-- CRPIX: chip's model zero point in pixel space (XREF/YREF)
-
+
- Time dependent distortion correction is applied to both chips' V2/V3 values.
-
+
"""
tdd_xyref = {1: [2048, 3072], 2:[2048, 1024]}
- def updateWCS(cls, ext_wcs, ref_wcs):
+ def updateWCS(cls, ext_wcs, ref_wcs):
"""
- recomputes the basic WCS kw
+ recomputes the basic WCS kw
"""
logger.info("\n\tStarting MakeWCS: %s" % time.asctime())
ltvoff, offshift = cls.getOffsets(ext_wcs)
-
+
v23_corr = cls.zero_point_corr(ext_wcs)
rv23_corr = cls.zero_point_corr(ref_wcs)
-
+
cls.uprefwcs(ext_wcs, ref_wcs, rv23_corr, ltvoff, offshift)
cls.upextwcs(ext_wcs, ref_wcs, v23_corr, rv23_corr, ltvoff, offshift)
@@ -59,13 +59,13 @@ class MakeWCS(object):
'IDCTAB': ext_wcs.idctab,
}
return kw2update
-
+
updateWCS = classmethod(updateWCS)
-
+
def upextwcs(cls, ext_wcs, ref_wcs, v23_corr, rv23_corr, loff, offsh):
"""
updates an extension wcs
- """
+ """
ltvoffx, ltvoffy = loff[0], loff[1]
offshiftx, offshifty = offsh[0], offsh[1]
ltv1 = ext_wcs.ltv1
@@ -76,61 +76,61 @@ class MakeWCS(object):
fx,fy = ext_wcs.idcmodel.shift(ext_wcs.idcmodel.cx,ext_wcs.idcmodel.cy,offsetx,offsety)
else:
fx, fy = ext_wcs.idcmodel.cx, ext_wcs.idcmodel.cy
-
+
tddscale = (ref_wcs.pscale/fx[1,1])
v2 = ext_wcs.idcmodel.refpix['V2REF'] + v23_corr[0,0] * tddscale
v3 = ext_wcs.idcmodel.refpix['V3REF'] - v23_corr[1,0] * tddscale
v2ref = ref_wcs.idcmodel.refpix['V2REF'] + rv23_corr[0,0] * tddscale
v3ref = ref_wcs.idcmodel.refpix['V3REF'] - rv23_corr[1,0] * tddscale
-
+
R_scale = ref_wcs.idcmodel.refpix['PSCALE']/3600.0
off = sqrt((v2-v2ref)**2 + (v3-v3ref)**2)/(R_scale*3600.0)
-
+
if v3 == v3ref:
theta=0.0
else:
theta = atan2(ext_wcs.parity[0][0]*(v2-v2ref), ext_wcs.parity[1][1]*(v3-v3ref))
-
+
if ref_wcs.idcmodel.refpix['THETA']: theta += ref_wcs.idcmodel.refpix['THETA']*pi/180.0
dX=(off*sin(theta)) + offshiftx
dY=(off*cos(theta)) + offshifty
-
+
px = np.array([[dX,dY]])
newcrval = ref_wcs.wcs.p2s(px, 1)['world'][0]
- newcrpix = np.array([ext_wcs.idcmodel.refpix['XREF'] + ltvoffx,
+ newcrpix = np.array([ext_wcs.idcmodel.refpix['XREF'] + ltvoffx,
ext_wcs.idcmodel.refpix['YREF'] + ltvoffy])
ext_wcs.wcs.crval = newcrval
ext_wcs.wcs.crpix = newcrpix
ext_wcs.wcs.set()
-
+
# Create a small vector, in reference image pixel scale
delmat = np.array([[fx[1,1], fy[1,1]], \
[fx[1,0], fy[1,0]]]) / R_scale/3600.
-
+
# Account for subarray offset
# Angle of chip relative to chip
if ext_wcs.idcmodel.refpix['THETA']:
dtheta = ext_wcs.idcmodel.refpix['THETA'] - ref_wcs.idcmodel.refpix['THETA']
else:
- dtheta = 0.0
-
+ dtheta = 0.0
+
rrmat = fileutil.buildRotMatrix(dtheta)
# Rotate the vectors
dxy = np.dot(delmat, rrmat)
wc = ref_wcs.wcs.p2s((px + dxy), 1)['world']
-
+
# Calculate the new CDs and convert to degrees
cd11 = utils.diff_angles(wc[0,0],newcrval[0])*cos(newcrval[1]*pi/180.0)
cd12 = utils.diff_angles(wc[1,0],newcrval[0])*cos(newcrval[1]*pi/180.0)
cd21 = utils.diff_angles(wc[0,1],newcrval[1])
cd22 = utils.diff_angles(wc[1,1],newcrval[1])
cd = np.array([[cd11, cd12], [cd21, cd22]])
- ext_wcs.wcs.cd = cd
+ ext_wcs.wcs.cd = cd
ext_wcs.wcs.set()
upextwcs = classmethod(upextwcs)
-
+
def uprefwcs(cls, ext_wcs, ref_wcs, rv23_corr_tdd, loff, offsh):
"""
Updates the reference chip
@@ -139,12 +139,12 @@ class MakeWCS(object):
offshift = offsh
dec = ref_wcs.wcs.crval[1]
tddscale = (ref_wcs.pscale/ext_wcs.idcmodel.cx[1,1])
- rv23 = [ref_wcs.idcmodel.refpix['V2REF'] + (rv23_corr_tdd[0,0] *tddscale),
+ rv23 = [ref_wcs.idcmodel.refpix['V2REF'] + (rv23_corr_tdd[0,0] *tddscale),
ref_wcs.idcmodel.refpix['V3REF'] - (rv23_corr_tdd[1,0] * tddscale)]
# Get an approximate reference position on the sky
- rref = np.array([[ref_wcs.idcmodel.refpix['XREF']+ltvoffx ,
+ rref = np.array([[ref_wcs.idcmodel.refpix['XREF']+ltvoffx ,
ref_wcs.idcmodel.refpix['YREF']+ltvoffy]])
-
+
crval = ref_wcs.wcs.p2s(rref, 1)['world'][0]
# Convert the PA_V3 orientation to the orientation at the aperture
# This is for the reference chip only - we use this for the
@@ -154,8 +154,8 @@ class MakeWCS(object):
# Add the chip rotation angle
if ref_wcs.idcmodel.refpix['THETA']:
pv += ref_wcs.idcmodel.refpix['THETA']
-
-
+
+
# Set values for the rest of the reference WCS
ref_wcs.wcs.crval = crval
ref_wcs.wcs.crpix = np.array([0.0,0.0])+offsh
@@ -165,13 +165,13 @@ class MakeWCS(object):
cd12 = parity[0][0] * -sin(pv*pi/180.0)*R_scale
cd21 = parity[1][1] * sin(pv*pi/180.0)*R_scale
cd22 = parity[1][1] * cos(pv*pi/180.0)*R_scale
-
+
rcd = np.array([[cd11, cd12], [cd21, cd22]])
ref_wcs.wcs.cd = rcd
ref_wcs.wcs.set()
-
+
uprefwcs = classmethod(uprefwcs)
-
+
def zero_point_corr(cls,hwcs):
try:
alpha = hwcs.idcmodel.refpix['TDDALPHA']
@@ -182,23 +182,23 @@ class MakeWCS(object):
v23_corr = np.array([[0.],[0.]])
logger.debug("\n\tTDD Zero point correction for chip %s defaulted to: %s" % (hwcs.chip, v23_corr))
return v23_corr
-
+
tdd = np.array([[beta, alpha], [alpha, -beta]])
mrotp = fileutil.buildRotMatrix(2.234529)/2048.
xy0 = np.array([[cls.tdd_xyref[hwcs.chip][0]-2048.], [cls.tdd_xyref[hwcs.chip][1]-2048.]])
v23_corr = np.dot(mrotp,np.dot(tdd,xy0)) * 0.05
logger.debug("\n\tTDD Zero point correction for chip %s: %s" % (hwcs.chip, v23_corr))
- return v23_corr
-
+ return v23_corr
+
zero_point_corr = classmethod(zero_point_corr)
-
+
def getOffsets(cls, ext_wcs):
ltv1 = ext_wcs.ltv1
ltv2 = ext_wcs.ltv2
-
+
offsetx = ext_wcs.wcs.crpix[0] - ltv1 - ext_wcs.idcmodel.refpix['XREF']
offsety = ext_wcs.wcs.crpix[1] - ltv2 - ext_wcs.idcmodel.refpix['YREF']
-
+
shiftx = ext_wcs.idcmodel.refpix['XREF'] + ltv1
shifty = ext_wcs.idcmodel.refpix['YREF'] + ltv2
if ltv1 != 0. or ltv2 != 0.:
@@ -211,13 +211,13 @@ class MakeWCS(object):
ltvoffy = 0.
offshiftx = 0.
offshifty = 0.
-
+
ltvoff = np.array([ltvoffx, ltvoffy])
offshift = np.array([offshiftx, offshifty])
return ltvoff, offshift
-
+
getOffsets = classmethod(getOffsets)
-
+
def troll(roll, dec, v2, v3):
""" Computes the roll angle at the target position based on:
diff --git a/updatewcs/npol.py b/lib/stwcs/updatewcs/npol.py
index 62c44bd..db928bf 100644
--- a/updatewcs/npol.py
+++ b/lib/stwcs/updatewcs/npol.py
@@ -1,7 +1,7 @@
from __future__ import division # confidence high
import pyfits
-from pytools import fileutil
+from stsci.tools import fileutil
import utils
import numpy as np
diff --git a/updatewcs/utils.py b/lib/stwcs/updatewcs/utils.py
index 29ba5f3..29ba5f3 100644
--- a/updatewcs/utils.py
+++ b/lib/stwcs/updatewcs/utils.py
diff --git a/wcsutil/__init__.py b/lib/stwcs/wcsutil/__init__.py
index 9c12aa2..9b7ed8c 100644
--- a/wcsutil/__init__.py
+++ b/lib/stwcs/wcsutil/__init__.py
@@ -22,12 +22,12 @@ def help():
3. Create an HSTWCS object using a file name and an extension number. \n
Example:\n
w = wcsutil.HSTWCS('j9irw4b1q_flt.fits', ext=2)\n\n
-
+
4. Create an HSTWCS object from WCS with key 'O'.\n
Example:\n
w = wcsutil.HSTWCS('j9irw4b1q_flt.fits', ext=2, wcskey='O')\n\n
-
+
5. Create a template HSTWCS object for a DEFAULT object.\n
Example:\n
w = wcsutil.HSTWCS(instrument='DEFAULT')\n\n
diff --git a/wcsutil/altwcs.py b/lib/stwcs/wcsutil/altwcs.py
index d250b52..d250b52 100644
--- a/wcsutil/altwcs.py
+++ b/lib/stwcs/wcsutil/altwcs.py
diff --git a/wcsutil/convertwcs.py b/lib/stwcs/wcsutil/convertwcs.py
index 2a53d57..80276c3 100644
--- a/wcsutil/convertwcs.py
+++ b/lib/stwcs/wcsutil/convertwcs.py
@@ -5,7 +5,7 @@ try:
except:
stwcs = None
-from pytools import fileutil
+from stsci.tools import fileutil
OPUS_WCSKEYS = ['OCRVAL1','OCRVAL2','OCRPIX1','OCRPIX2',
'OCD1_1','OCD1_2','OCD2_1','OCD2_2',
diff --git a/wcsutil/getinput.py b/lib/stwcs/wcsutil/getinput.py
index a2d9781..2f64f46 100644
--- a/wcsutil/getinput.py
+++ b/lib/stwcs/wcsutil/getinput.py
@@ -1,5 +1,5 @@
import pyfits
-from pytools import irafglob, fileutil, parseinput
+from stsci.tools import irafglob, fileutil, parseinput
def parseSingleInput(f=None, ext=None):
if isinstance(f, str):
diff --git a/wcsutil/headerlet.py b/lib/stwcs/wcsutil/headerlet.py
index a30f06b..0318bf2 100644
--- a/wcsutil/headerlet.py
+++ b/lib/stwcs/wcsutil/headerlet.py
@@ -14,7 +14,7 @@ import altwcs
import wcscorr
from hstwcs import HSTWCS
from mappings import basic_wcs
-from pytools.fileutil import countExtn
+from stsci.tools.fileutil import countExtn
module_logger = logging.getLogger('headerlet')
diff --git a/wcsutil/hstwcs.py b/lib/stwcs/wcsutil/hstwcs.py
index 26dad5d..11c1f42 100644
--- a/wcsutil/hstwcs.py
+++ b/lib/stwcs/wcsutil/hstwcs.py
@@ -7,8 +7,8 @@ import instruments
from stwcs.distortion import models, coeff_converter
import altwcs
import numpy as np
-from pytools import fileutil
-from pytools.fileutil import DEGTORAD, RADTODEG
+from stsci.tools import fileutil
+from stsci.tools.fileutil import DEGTORAD, RADTODEG
import getinput
import mappings
diff --git a/wcsutil/instruments.py b/lib/stwcs/wcsutil/instruments.py
index 997bdc8..997bdc8 100644
--- a/wcsutil/instruments.py
+++ b/lib/stwcs/wcsutil/instruments.py
diff --git a/wcsutil/mappings.py b/lib/stwcs/wcsutil/mappings.py
index 24038bf..24038bf 100644
--- a/wcsutil/mappings.py
+++ b/lib/stwcs/wcsutil/mappings.py
diff --git a/wcsutil/mosaic.py b/lib/stwcs/wcsutil/mosaic.py
index d4ee660..0c02265 100644
--- a/wcsutil/mosaic.py
+++ b/lib/stwcs/wcsutil/mosaic.py
@@ -4,7 +4,7 @@ from matplotlib import pyplot as plt
import pyfits
import string
-from pytools import parseinput, irafglob
+from stsci.tools import parseinput, irafglob
from stwcs.distortion import utils
from stwcs import updatewcs, wcsutil
from stwcs.wcsutil import altwcs
diff --git a/wcsutil/wcscorr.py b/lib/stwcs/wcsutil/wcscorr.py
index bab0964..a6b1f94 100644
--- a/wcsutil/wcscorr.py
+++ b/lib/stwcs/wcsutil/wcscorr.py
@@ -2,7 +2,7 @@ import os,copy
import pyfits
import numpy as np
-from pytools import fileutil
+from stsci.tools import fileutil
import stwcs
from stwcs.wcsutil import altwcs
import convertwcs
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000..4db0ee5
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,33 @@
+[metadata]
+name = stwcs
+version = 0.8
+author = Nadia Dencheva, Warren Hack
+author-email = help@stsci.edu
+summary = Recomputes the WCS of an HST observation and puts all distortion
+ corrections in the headers
+home-page = http://www.stsci.edu/resources/software_hardware/stsci_python
+classifier =
+ Intended Audience :: Science/Research
+ License :: OSI Approved :: BSD License
+ Operating System :: OS Independent
+ Programming Language :: Python
+ Topic :: Scientific/Engineering :: Astronomy
+ Topic :: Software Development :: Libraries :: Python Modules
+requires-python = >=2.5
+requires-dist =
+ stsci.tools (==2.9)
+ pywcs (==1.10-4.7)
+
+[files]
+packages_root = lib
+packages =
+ stwcs
+ stwcs.distortion
+ stwcs.updatewcs
+ stwcs.wcsutil
+
+[global]
+commands = stsci.distutils.command.easier_install.easier_install
+
+[easy_install]
+find-links = ..
diff --git a/setup.py b/setup.py
index f0b76ab..ac634f2 100644..100755
--- a/setup.py
+++ b/setup.py
@@ -1,5 +1,34 @@
#!/usr/bin/env python
-from __future__ import division # confidence high
-import pytools.stsci_distutils_hack
-pytools.stsci_distutils_hack.run(pytools_version = "3.0")
+try:
+ from setuptools import setup
+except ImportError:
+ from distribute_setup import use_setuptools
+ use_setuptools()
+ from setuptools import setup
+
+try:
+ from stsci.distutils.command.easier_install import easier_install
+except ImportError:
+ import os
+ import sys
+ stsci_distutils = os.path.abspath(os.path.join('..', 'distutils', 'lib'))
+ if os.path.exists(stsci_distutils) and stsci_distutils not in sys.path:
+ sys.path.append(stsci_distutils)
+ try:
+ from stsci.distutils.command.easier_install import easier_install
+ import setuptools.command.easy_install
+ except ImportError:
+ # If even this failed, we're not in an stsci_python source checkout,
+ # so there's nothing gained from using easier_install
+ from setuptools.command.easy_install import easy_install
+ easier_install = easy_install
+# This is required so that easier_install can be used for setup_requires
+import setuptools
+setuptools.command.easy_install.easy_install = easier_install
+
+setup(
+ setup_requires=['d2to1>=0.2.2', 'stsci.distutils>=0.2dev'],
+ d2to1=True,
+ use_2to3=True
+)