summaryrefslogtreecommitdiff
path: root/lib/skyline.py
blob: 1170d4d4645567e7917516f2478a38e1ffccf243 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
"""Manage outlines on the sky.

This module provides support for working with footprints
on the sky. Primary use case would use the following
generalized steps::

    #. Initialize SkyLine objects for each input image.
       This object would be the union of all the input
       image's individual chips WCS footprints.

    #. Determine overlap between all images. The
       determination would employ a recursive operation
       to return the extended list of all overlap values
       computed as [img1 vs [img2,img3,...,imgN],img2 vs
       [img3,...,imgN],...]

    #. Select the pair with the largest overlap, or the
       pair which produces the largest overlap with the
       first input image. This defines the initial
       reference SkyLine object.

    #. Perform some operation on the 2 images: for example,
       match sky in intersecting regions, or aligning
       second image with the first (reference) image.

    #. Update the second image, either apply the sky value
       or correct the WCS, then generate a new SkyLine
       object for that image.

    #. Create a new reference SkyLine object as the union
       of the initial reference object and the newly
       updated SkyLine object.

    #. Repeat Steps 2-6 for all remaining input images.

This process will work reasonably fast as most operations
are performed using the SkyLine objects and WCS information
solely, not image data itself.

.. note:: Requires Python 2.7 or later.

:Authors: Pey Lian Lim, W. Hack

:Organization: Space Telescope Science Institute

:History:
    * 2012-05-25 PLL updated doc. Original class structure by WJH.

Examples
--------
>>> from sphere import SkyLine

"""
from __future__ import division, print_function, absolute_import

# STDLIB
import os
from copy import copy, deepcopy

# THIRD-PARTY
import pyfits
from stwcs import wcsutil

# LOCAL
from .polygon import SphericalPolygon

__all__ = ['SkyLine']
__version__ = '0.1a'
__vdate__ = '05-Jun-2012'

class SkyLineMember(object):

    def __init__(self, fname, ext):
        """Container for SkyLine members.

        Given FITS image and extension, will store its SphericalPolygon
        instance from WCS under `polygon`.

        self: obj
            SkyLineMember instance.

        fname: str
            FITS image.

        ext: int
            Image extension.

        """
        self._fname = fname
        self._ext = ext
        self._polygon = SphericalPolygon.from_wcs(
            wcsutil.HSTWCS(fname, ext=ext))

    def __repr__(self):
        return 'SkyLineMember(%r, %r, %r)' % (self.fname, self.ext,
                                              self.polygon)

    @property
    def fname(self):
        return self._fname

    @property
    def ext(self):
        return self._ext

    @property
    def polygon(self):
        return self._polygon

class SkyLine(SphericalPolygon):

    def __init__(self, fname, extname='SCI'):
        """Initialize SkyLine object instance.

        Parameters
        ----------
        self: obj
            SkyLine instance.

        fname: str
            FITS image. None to create empty SkyLine.

        extname: str
            EXTNAME to use. SCI is recommended for normal
            HST images. PRIMARY if image is single ext.

        """
        SphericalPolygon.__init__(self, [])

        # Convert SCI data to SkyLineMember
        if fname is not None:
            with pyfits.open(fname) as pf:
                poly_list = [SkyLineMember(fname, i)
                             for i,ext in enumerate(pf)
                             if extname in ext.name.upper()]
        else:
            poly_list = []

        # Put mosaic of all the chips in SkyLine
        if len(poly_list) > 0:
            self._update(SphericalPolygon.multi_union(
                [m.polygon for m in poly_list]), poly_list)

        # Empty class
        else:
            self._update(self, None)

    def __repr__(self):
        return 'SkyLine(%r, %r, %r)' % (self.points, self.inside, self.members)

    def _update(self, new_polygon, new_members):
        """
        Update *self* attributes to use given polygon and
        new members.

        Parameters
        ----------
        self: obj
            SkyLine instance to update.

        new_polygon: obj
            SphericalPolygon instance to use.

        new_members: list
            List of SkyLineMember associated with `new_polygon`.

        """
        self._points = new_polygon.points
        self._inside = new_polygon.inside
        self._members = new_members  

    def _find_new_members(self, other):
        """
        Find SkyLineMember that is in *other* but not in *self*.

        This is used internally to make sure there are no duplicate
        SkyLineMember entries. Order is preserved, with *self*
        listed first, followed by each new member from *other*.

        Parameters
        ----------
        self, other: obj
            `SkyLine` instance.

        Returns
        -------
        List of SkyLineMember that qualifies.
        
        """
        if others.members is None:
            out_members = []
        elif self.members is None:
            out_members = others.members
        else:
            out_members = [m for m in other.members if m not in self.members]

        return out_members

    def _add_members(self, new_members):
        """Return current SkyLineMember list + new SkyLineMember list."""
        if new_members is None:
            out_members = self.members
        elif self.members is None:
            out_members = new_members
        else:
            out_members = self.members + new_members
            
        return out_members

    @property
    def members(self):
        """List of SkyLineMember objects."""
        return self._members

    @property
    def polygons(self):
        """List of SkyLineMember polygons."""
        if self.members is not None:
            return [m.polygon for m in self.members]
        else:
            return []

    @property
    def polygon(self):
        """SphericalPolygon portion of SkyLine."""
        return SphericalPolygon(self.points, self.inside)

    @classmethod
    def _overload_parentcls(cls, func, *args, **kwargs):
        """Call SphericalPolygon class method but return SkyLine."""
        newcls = cls(None)
        newcls._update(func(*args, **kwargs), None)
        return newcls

    @classmethod
    def from_radec(cls, *args, **kwargs):
        """
        Create a new `SkyLine` from a list of (*ra*, *dec*)
        points.

        See also
        --------
        sphere.polygon.SphericalPolygon.from_radec
        
        """
        return cls._overload_parentcls(SphericalPolygon.from_radec,
                                       *args, **kwargs)

    @classmethod
    def from_cone(cls, *args, **kwargs):
        """
        Create a new `SkyLine` from a cone (otherwise known
        as a 'small circle') defined using (*ra*, *dec*, *radius*).

        See also
        --------
        sphere.polygon.SphericalPolygon.from_cone

        """
        return cls._overload_parentcls(SphericalPolygon.from_cone,
                                       *args, **kwargs)

    @classmethod
    def from_wcs(cls, *args, **kwargs):
        """
        Create a new `SkyLine` from the footprint of a FITS
        WCS specification.

        See also
        --------
        sphere.polygon.SphericalPolygon.from_wcs

        """
        return cls._overload_parentcls(SphericalPolygon.from_wcs,
                                       *args, **kwargs)

    @classmethod
    def multi_union(cls, *args, **kwargs):
        """
        Return a new `SkyLine` that is the union of all of the
        polygons in *polygons*.

        See also
        --------
        sphere.polygon.SphericalPolygon.multi_union

        """
        return cls._overload_parentcls(SphericalPolygon.multi_union,
                                       *args, **kwargs)

    @classmethod
    def multi_intersection(cls, *args, **kwargs):
        """
        Return a new `SkyLine` that is the intersection of
        all of the polygons in *polygons*.

        See also
        --------
        sphere.polygon.SphericalPolygon.multi_intersection

        """
        return cls._overload_parentcls(SphericalPolygon.multi_intersection,
                                       *args, **kwargs)

    def union(self, other):
        """
        Return a new `SkyLine` that is the union of *self* and *other*.
        Skips *other* members that are already in *self*.

        Parameters
        ----------
        self, other: obj
            `SkyLine` instance.

        Returns
        -------
        out_skyline: obj
            `SkyLine` instance.

        Examples
        --------
        >>> s1 = SkyLine('image1.fits')
        >>> s2 = SkyLine('image2.fits')
        >>> s3 = s1.union(s2)

        See also
        --------
        sphere.polygon.SphericalPolygon.union

        """
        out_skyline = copy(self)
        new_members = self._find_new_members(other)

        if len(new_members) > 0:
            out_skyline._update(self.polygon.union(other.polygon),
                                self._add_members(new_members))

        return out_skyline

    def intersection(self, other):
        """
        Return a new `SkyLine` that is the intersection of
        *self* and *other*.

        Parameters
        ----------
        self, other: obj
            `SkyLine` instance.

        Returns
        -------
        out_skyline: obj
            `SkyLine` instance.

        Examples
        --------
        >>> s1 = SkyLine('image1.fits')
        >>> s2 = SkyLine('image2.fits')
        >>> s3 = s1.intersection(s2)

        See also
        --------
        sphere.polygon.SphericalPolygon.intersection

        """
        out_skyline = copy(self)
        new_members = self._find_new_members(other)
        out_sph = self.polygon.intersection(other.polygon)

        if len(out_sph.points) == 0:
            new_members = None
        else:
            new_members = [m for m in self._add_members(new_members) if
                           out_sph.contains_point(m.polygon.inside)]

        out_skyline._update(out_sph, new_members)

        return out_skyline


def test():
    """Basic use case."""
    pass