File size: 16,400 Bytes
56d74b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import abc

import numpy as np

__all__ = ['BaseLowLevelWCS', 'validate_physical_types']


class BaseLowLevelWCS(metaclass=abc.ABCMeta):
    """
    Abstract base class for the low-level WCS interface.

    This is described in `APE 14: A shared Python interface for World Coordinate
    Systems <https://doi.org/10.5281/zenodo.1188875>`_.
    """

    @property
    @abc.abstractmethod
    def pixel_n_dim(self):
        """
        The number of axes in the pixel coordinate system.
        """

    @property
    @abc.abstractmethod
    def world_n_dim(self):
        """
        The number of axes in the world coordinate system.
        """

    @property
    @abc.abstractmethod
    def world_axis_physical_types(self):
        """
        An iterable of strings describing the physical type for each world axis.

        These should be names from the VO UCD1+ controlled Vocabulary
        (http://www.ivoa.net/documents/latest/UCDlist.html). If no matching UCD
        type exists, this can instead be ``"custom:xxx"``, where ``xxx`` is an
        arbitrary string.  Alternatively, if the physical type is
        unknown/undefined, an element can be `None`.
        """

    @property
    @abc.abstractmethod
    def world_axis_units(self):
        """
        An iterable of strings given the units of the world coordinates for each
        axis.

        The strings should follow the `IVOA VOUnit standard
        <http://ivoa.net/documents/VOUnits/>`_ (though as noted in the VOUnit
        specification document, units that do not follow this standard are still
        allowed, but just not recommended).
        """

    @abc.abstractmethod
    def pixel_to_world_values(self, *pixel_arrays):
        """
        Convert pixel coordinates to world coordinates.

        This method takes `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` scalars or arrays as
        input, and pixel coordinates should be zero-based. Returns
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` scalars or arrays in units given by
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_units`. Note that pixel coordinates are
        assumed to be 0 at the center of the first pixel in each dimension. If a
        pixel is in a region where the WCS is not defined, NaN can be returned.
        The coordinates should be specified in the ``(x, y)`` order, where for
        an image, ``x`` is the horizontal coordinate and ``y`` is the vertical
        coordinate.

        If `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` is ``1``, this
        method returns a single scalar or array, otherwise a tuple of scalars or
        arrays is returned.
        """

    @abc.abstractmethod
    def array_index_to_world_values(self, *index_arrays):
        """
        Convert array indices to world coordinates.

        This is the same as `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_to_world_values` except that
        the indices should be given in ``(i, j)`` order, where for an image
        ``i`` is the row and ``j`` is the column (i.e. the opposite order to
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_to_world_values`).

        If `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` is ``1``, this
        method returns a single scalar or array, otherwise a tuple of scalars or
        arrays is returned.
        """

    @abc.abstractmethod
    def world_to_pixel_values(self, *world_arrays):
        """
        Convert world coordinates to pixel coordinates.

        This method takes `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` scalars or arrays as
        input in units given by `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_units`. Returns
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` scalars or arrays. Note that pixel
        coordinates are assumed to be 0 at the center of the first pixel in each
        dimension. If a world coordinate does not have a matching pixel
        coordinate, NaN can be returned.  The coordinates should be returned in
        the ``(x, y)`` order, where for an image, ``x`` is the horizontal
        coordinate and ``y`` is the vertical coordinate.

        If `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` is ``1``, this
        method returns a single scalar or array, otherwise a tuple of scalars or
        arrays is returned.
        """

    @abc.abstractmethod
    def world_to_array_index_values(self, *world_arrays):
        """
        Convert world coordinates to array indices.

        This is the same as `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_to_pixel_values` except that
        the indices should be returned in ``(i, j)`` order, where for an image
        ``i`` is the row and ``j`` is the column (i.e. the opposite order to
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_to_world_values`). The indices should be
        returned as rounded integers.

        If `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` is ``1``, this
        method returns a single scalar or array, otherwise a tuple of scalars or
        arrays is returned.
        """

    @property
    @abc.abstractmethod
    def world_axis_object_components(self):
        """
        A list with `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim` elements giving information
        on constructing high-level objects for the world coordinates.

        Each element of the list is a tuple with three items:

        * The first is a name for the world object this world array
          corresponds to, which *must* match the string names used in
          `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_object_classes`. Note that names might
          appear twice because two world arrays might correspond to a single
          world object (e.g. a celestial coordinate might have both “ra” and
          “dec” arrays, which correspond to a single sky coordinate object).

        * The second element is either a string keyword argument name or a
          positional index for the corresponding class from
          `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_object_classes`.

        * The third argument is a string giving the name of the property
          to access on the corresponding class from
          `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_object_classes` in order to get numerical
          values.

        See the document
        `APE 14: A shared Python interface for World Coordinate Systems
        <https://doi.org/10.5281/zenodo.1188875>`_ for examples.
        """

    @property
    @abc.abstractmethod
    def world_axis_object_classes(self):
        """
        A dictionary giving information on constructing high-level objects for
        the world coordinates.

        Each key of the dictionary is a string key from
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_object_components`, and each value is a
        tuple with three elements:

        * The first element of the tuple must be a class or a string specifying
          the fully-qualified name of a class, which will specify the actual
          Python object to be created.

        * The second element, should be a tuple specifying the positional
          arguments required to initialize the class. If
          `~astropy.wcs.wcsapi.BaseLowLevelWCS.world_axis_object_components` specifies that the
          world coordinates should be passed as a positional argument, this this
          tuple should include `None` placeholders for the world coordinates.

        * The last tuple element must be a dictionary with the keyword
          arguments required to initialize the class.

        Note that we don't require the classes to be Astropy classes since there
        is no guarantee that Astropy will have all the classes to represent all
        kinds of world coordinates. Furthermore, we recommend that the output be
        kept as human-readable as possible.

        The classes used here should have the ability to do conversions by
        passing an instance as the first argument to the same class with
        different arguments (e.g. ``Time(Time(...), scale='tai')``). This is
        a requirement for the implementation of the high-level interface.

        The second and third tuple elements for each value of this dictionary
        can in turn contain either instances of classes, or if necessary can
        contain serialized versions that should take the same form as the main
        classes described above (a tuple with three elements with the fully
        qualified name of the class, then the positional arguments and the
        keyword arguments). For low-level API objects implemented in Python, we
        recommend simply returning the actual objects (not the serialized form)
        for optimal performance. Implementations should either always or never
        use serialized classes to represent Python objects, and should indicate
        which of these they follow using the
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.serialized_classes` attribute.

        See the document
        `APE 14: A shared Python interface for World Coordinate Systems
        <https://doi.org/10.5281/zenodo.1188875>`_ for examples .
        """

    # The following three properties have default fallback implementations, so
    # they are not abstract.

    @property
    def array_shape(self):
        """
        The shape of the data that the WCS applies to as a tuple of length
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` in ``(row, column)``
        order (the convention for arrays in Python).

        If the WCS is valid in the context of a dataset with a particular
        shape, then this property can be used to store the shape of the
        data. This can be used for example if implementing slicing of WCS
        objects. This is an optional property, and it should return `None`
        if a shape is not known or relevant.
        """
        return None

    @property
    def pixel_shape(self):
        """
        The shape of the data that the WCS applies to as a tuple of length
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` in ``(x, y)``
        order (where for an image, ``x`` is the horizontal coordinate and ``y``
        is the vertical coordinate).

        If the WCS is valid in the context of a dataset with a particular
        shape, then this property can be used to store the shape of the
        data. This can be used for example if implementing slicing of WCS
        objects. This is an optional property, and it should return `None`
        if a shape is not known or relevant.

        If you are interested in getting a shape that is comparable to that of
        a Numpy array, you should use
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.array_shape` instead.
        """
        return None

    @property
    def pixel_bounds(self):
        """
        The bounds (in pixel coordinates) inside which the WCS is defined,
        as a list with `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` ``(min, max)`` tuples.

        The bounds should be given in ``[(xmin, xmax), (ymin, ymax)]``
        order. WCS solutions are sometimes only guaranteed to be accurate
        within a certain range of pixel values, for example when defining a
        WCS that includes fitted distortions. This is an optional property,
        and it should return `None` if a shape is not known or relevant.
        """
        return None

    @property
    def axis_correlation_matrix(self):
        """
        Returns an (`~astropy.wcs.wcsapi.BaseLowLevelWCS.world_n_dim`,
        `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim`) matrix that indicates using booleans
        whether a given world coordinate depends on a given pixel coordinate.

        This defaults to a matrix where all elements are `True` in the absence of
        any further information. For completely independent axes, the diagonal
        would be `True` and all other entries `False`.
        """
        return np.ones((self.world_n_dim, self.pixel_n_dim), dtype=bool)

    @property
    def serialized_classes(self):
        """
        Indicates whether Python objects are given in serialized form or as
        actual Python objects.
        """
        return False

    def __str__(self):

        # Overall header

        s = '{0} Transformation\n\n'.format(self.__class__.__name__)
        s += ('This transformation has {0} pixel and {1} world dimensions\n\n'
              .format(self.pixel_n_dim, self.world_n_dim))
        s += 'Array shape (Numpy order): {0}\n\n'.format(self.array_shape)

        # Pixel dimensions table

        array_shape = self.array_shape or (0,)
        pixel_shape = self.pixel_shape or (None,) * self.pixel_n_dim

        # Find largest between header size and value length
        pixel_dim_width = max(9, len(str(self.pixel_n_dim)))
        pixel_siz_width = max(9, len(str(max(array_shape))))

        s += (('{0:' + str(pixel_dim_width) + 's}').format('Pixel Dim') + '  ' +
              ('{0:' + str(pixel_siz_width) + 's}').format('Data size') + '  ' +
              'Bounds\n')

        for ipix in range(self.pixel_n_dim):
            s += (('{0:' + str(pixel_dim_width) + 'd}').format(ipix) + '  ' +
                  (" "*5 + str(None) if pixel_shape[ipix] is None else
                   ('{0:' + str(pixel_siz_width) + 'd}').format(pixel_shape[ipix])) + '  ' +
                  '{0:s}'.format(str(None if self.pixel_bounds is None else self.pixel_bounds[ipix]) + '\n'))

        s += '\n'

        # World dimensions table

        # Find largest between header size and value length
        world_dim_width = max(9, len(str(self.world_n_dim)))
        world_typ_width = max(13, max(len(x) if x is not None else 0 for x in self.world_axis_physical_types))

        s += (('{0:' + str(world_dim_width) + 's}').format('World Dim') + '  ' +
              ('{0:' + str(world_typ_width) + 's}').format('Physical Type') + '  ' +
               'Units\n')

        for iwrl in range(self.world_n_dim):

            if self.world_axis_physical_types[iwrl] is not None:
                s += (('{0:' + str(world_dim_width) + 'd}').format(iwrl) + '  ' +
                      ('{0:' + str(world_typ_width) + 's}').format(self.world_axis_physical_types[iwrl]) + '  ' +
                      '{0:s}'.format(self.world_axis_units[iwrl] + '\n'))
            else:
                s += (('{0:' + str(world_dim_width) + 'd}').format(iwrl) + '  ' +
                      ('{0:' + str(world_typ_width) + 's}').format('None') + '  ' +
                      '{0:s}'.format('unknown' + '\n'))
        s += '\n'

        # Axis correlation matrix

        pixel_dim_width = max(3, len(str(self.world_n_dim)))

        s += 'Correlation between pixel and world axes:\n\n'

        s += (' ' * world_dim_width + '  ' +
              ('{0:^' + str(self.pixel_n_dim * 5 - 2) + 's}').format('Pixel Dim') +
              '\n')

        s += (('{0:' + str(world_dim_width) + 's}').format('World Dim') +
              ''.join(['  ' + ('{0:' + str(pixel_dim_width) + 'd}').format(ipix)
                       for ipix in range(self.pixel_n_dim)]) +
              '\n')

        matrix = self.axis_correlation_matrix
        matrix_str = np.empty(matrix.shape, dtype='U3')
        matrix_str[matrix] = 'yes'
        matrix_str[~matrix] = 'no'

        for iwrl in range(self.world_n_dim):
            s += (('{0:' + str(world_dim_width) + 'd}').format(iwrl) +
                  ''.join(['  ' + ('{0:>' + str(pixel_dim_width) + 's}').format(matrix_str[iwrl, ipix])
                           for ipix in range(self.pixel_n_dim)]) +
                  '\n')

        # Make sure we get rid of the extra whitespace at the end of some lines
        return '\n'.join([l.rstrip() for l in s.splitlines()])

    __repr__ = __str__


UCDS_FILE = os.path.join(os.path.dirname(__file__), 'data', 'ucds.txt')
with open(UCDS_FILE) as f:
    VALID_UCDS = set([x.strip() for x in f.read().splitlines()[1:]])


def validate_physical_types(physical_types):
    """
    Validate a list of physical types against the UCD1+ standard
    """
    for physical_type in physical_types:
        if (physical_type is not None and
            physical_type not in VALID_UCDS and
                not physical_type.startswith('custom:')):
            raise ValueError("Invalid physical type: {0}".format(physical_type))