File: utils.rst

package info (click to toggle)
astropy 5.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 41,972 kB
  • sloc: python: 219,331; ansic: 147,297; javascript: 13,556; lex: 8,496; sh: 3,319; xml: 1,622; makefile: 185
file content (358 lines) | stat: -rw-r--r-- 12,486 bytes parent folder | download | duplicates (3)
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
.. _nddata_utils:

Image Utilities
***************

Overview
========

The `astropy.nddata.utils` module includes general utility functions
for array operations.

.. _cutout_images:

2D Cutout Images
================

Getting Started
---------------

The `~astropy.nddata.utils.Cutout2D` class can be used to create a
postage stamp cutout image from a 2D array. If an optional
`~astropy.wcs.WCS` object is input to
`~astropy.nddata.utils.Cutout2D`, then the
`~astropy.nddata.utils.Cutout2D` object will contain an updated
`~astropy.wcs.WCS` corresponding to the cutout array.

First, we simulate a single source on a 2D data array. If you would like to
simulate many sources, see :ref:`bounding-boxes`.

Note: The pair convention is different for **size** and **position**! The
position is specified as (x,y), but the size is specified as (y,x).

    >>> import numpy as np
    >>> from astropy.modeling.models import Gaussian2D
    >>> y, x = np.mgrid[0:500, 0:500]
    >>> data = Gaussian2D(1, 50, 100, 10, 5, theta=0.5)(x, y)

Now, we can display the image:

.. doctest-skip::

    >>> import matplotlib.pyplot as plt
    >>> plt.imshow(data, origin='lower')

.. plot::

    import numpy as np
    import matplotlib.pyplot as plt
    from astropy.modeling.models import Gaussian2D
    y, x = np.mgrid[0:500, 0:500]
    data = Gaussian2D(1, 50, 100, 10, 5, theta=0.5)(x, y)
    plt.imshow(data, origin='lower')

Next we can create a cutout for the single object in this image. We
create a cutout centered at position ``(x, y) = (49.7, 100.1)`` with a
size of ``(ny, nx) = (41, 51)`` pixels::

    >>> from astropy.nddata import Cutout2D
    >>> from astropy import units as u
    >>> position = (49.7, 100.1)
    >>> size = (41, 51)     # pixels
    >>> cutout = Cutout2D(data, position, size)

The ``size`` keyword can also be a `~astropy.units.Quantity` object::

    >>> size = u.Quantity((41, 51), u.pixel)
    >>> cutout = Cutout2D(data, position, size)

Or contain `~astropy.units.Quantity` objects::

    >>> size = (41*u.pixel, 51*u.pixel)
    >>> cutout = Cutout2D(data, position, size)

A square cutout image can be generated by passing an integer or
a scalar `~astropy.units.Quantity`::

    >>> size = 41
    >>> cutout2 = Cutout2D(data, position, size)

    >>> size = 41 * u.pixel
    >>> cutout2 = Cutout2D(data, position, size)

The cutout array is stored in the ``data`` attribute of the
`~astropy.nddata.utils.Cutout2D` instance. If the ``copy`` keyword is
`False` (default), then ``cutout.data`` will be a view into the
original ``data`` array. If ``copy=True``, then ``cutout.data`` will
hold a copy of the original ``data``. Now we display the cutout
image:

.. doctest-skip::

    >>> cutout = Cutout2D(data, position, (41, 51))
    >>> plt.imshow(cutout.data, origin='lower')

.. plot::

    import numpy as np
    import matplotlib.pyplot as plt
    from astropy.modeling.models import Gaussian2D
    from astropy.nddata import Cutout2D
    y, x = np.mgrid[0:500, 0:500]
    data = Gaussian2D(1, 50, 100, 10, 5, theta=0.5)(x, y)
    position = (49.7, 100.1)
    cutout = Cutout2D(data, position, (41, 51))
    plt.imshow(cutout.data, origin='lower')

The cutout object can plot its bounding box on the original data using
the :meth:`~astropy.nddata.utils.Cutout2D.plot_on_original` method:

.. doctest-skip::

    >>> plt.imshow(data, origin='lower')
    >>> cutout.plot_on_original(color='white')

.. plot::

    import numpy as np
    import matplotlib.pyplot as plt
    from astropy.modeling.models import Gaussian2D
    from astropy.nddata import Cutout2D
    y, x = np.mgrid[0:500, 0:500]
    data = Gaussian2D(1, 50, 100, 10, 5, theta=0.5)(x, y)
    position = (49.7, 100.1)
    size = (41, 51)
    cutout = Cutout2D(data, position, size)
    plt.imshow(data, origin='lower')
    cutout.plot_on_original(color='white')

Many properties of the cutout array are also stored as attributes,
including::

    >>> # shape of the cutout array
    >>> print(cutout.shape)
    (41, 51)

    >>> # rounded pixel index of the input position
    >>> print(cutout.position_original)
    (50, 100)

    >>> # corresponding position in the cutout array
    >>> print(cutout.position_cutout)
    (25, 20)

    >>> # (non-rounded) input position in both the original and cutout arrays
    >>> print((cutout.input_position_original, cutout.input_position_cutout))  # doctest: +FLOAT_CMP
    ((49.7, 100.1), (24.700000000000003, 20.099999999999994))

    >>> # the origin pixel in both arrays
    >>> print((cutout.origin_original, cutout.origin_cutout))
    ((25, 80), (0, 0))

    >>> # tuple of slice objects for the original array
    >>> print(cutout.slices_original)
    (slice(80, 121, None), slice(25, 76, None))

    >>> # tuple of slice objects for the cutout array
    >>> print(cutout.slices_cutout)
    (slice(0, 41, None), slice(0, 51, None))

There are also two `~astropy.nddata.utils.Cutout2D` methods to convert
pixel positions between the original and cutout arrays::

    >>> print(cutout.to_original_position((2, 1)))
    (27, 81)

    >>> print(cutout.to_cutout_position((27, 81)))
    (2, 1)


2D Cutout Modes
---------------

There are three modes for creating cutout arrays: ``'trim'``,
``'partial'``, and ``'strict'``. For the ``'partial'`` and ``'trim'``
modes, a partial overlap of the cutout array and the input ``data``
array is sufficient. For the ``'strict'`` mode, the cutout array has
to be fully contained within the ``data`` array, otherwise an
`~astropy.nddata.utils.PartialOverlapError` is raised. In all modes,
non-overlapping arrays will raise a
`~astropy.nddata.utils.NoOverlapError`. In ``'partial'`` mode,
positions in the cutout array that do not overlap with the ``data``
array will be filled with ``fill_value``. In ``'trim'`` mode only the
overlapping elements are returned, thus the resulting cutout array may
be smaller than the requested ``size``.

The default uses ``mode='trim'``, which can result in cutout arrays
that are smaller than the requested ``size``::

    >>> data2 = np.arange(20.).reshape(5, 4)
    >>> cutout1 = Cutout2D(data2, (0, 0), (3, 3), mode='trim')
    >>> print(cutout1.data)  # doctest: +FLOAT_CMP
    [[0. 1.]
     [4. 5.]]
    >>> print(cutout1.shape)
    (2, 2)
    >>> print((cutout1.position_original, cutout1.position_cutout))
    ((0, 0), (0, 0))

With ``mode='partial'``, the cutout will never be trimmed. Instead it
will be filled with ``fill_value`` (the default is ``numpy.nan``) if
the cutout is not fully contained in the data array::

    >>> cutout2 = Cutout2D(data2, (0, 0), (3, 3), mode='partial')
    >>> print(cutout2.data)  # doctest: +FLOAT_CMP
    [[nan nan nan]
     [nan  0.  1.]
     [nan  4.  5.]]

Note that for the ``'partial'`` mode, the positions (and several other
attributes) are calculated for on the *valid* (non-filled) cutout
values::

    >>> print((cutout2.position_original, cutout2.position_cutout))
    ((0, 0), (1, 1))
    >>> print((cutout2.origin_original, cutout2.origin_cutout))
    ((0, 0), (1, 1))
    >>> print(cutout2.slices_original)
    (slice(0, 2, None), slice(0, 2, None))
    >>> print(cutout2.slices_cutout)
    (slice(1, 3, None), slice(1, 3, None))

Using ``mode='strict'`` will raise an exception if the cutout is not
fully contained in the data array:

.. doctest-skip::

    >>> cutout3 = Cutout2D(data2, (0, 0), (3, 3), mode='strict')
    PartialOverlapError: Arrays overlap only partially.


2D Cutout from a `~astropy.coordinates.SkyCoord` Position
---------------------------------------------------------

The input ``position`` can also be specified as a
`~astropy.coordinates.SkyCoord`, in which case a `~astropy.wcs.WCS`
object must be input via the ``wcs`` keyword.

First, we define a `~astropy.coordinates.SkyCoord` position and a
`~astropy.wcs.WCS` object for our data (usually this would come from
your FITS header)::

    >>> from astropy.coordinates import SkyCoord
    >>> from astropy.wcs import WCS
    >>> position = SkyCoord('13h11m29.96s -01d19m18.7s', frame='icrs')
    >>> wcs = WCS(naxis=2)
    >>> rho = np.pi / 3.
    >>> scale = 0.05 / 3600.
    >>> wcs.wcs.cd = [[scale*np.cos(rho), -scale*np.sin(rho)],
    ...               [scale*np.sin(rho), scale*np.cos(rho)]]
    >>> wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
    >>> wcs.wcs.crval = [position.ra.to_value(u.deg),
    ...                  position.dec.to_value(u.deg)]
    >>> wcs.wcs.crpix = [50, 100]

Now we can create the cutout array using the
`~astropy.coordinates.SkyCoord` position and ``wcs`` object::

    >>> cutout = Cutout2D(data, position, (30, 40), wcs=wcs)
    >>> plt.imshow(cutout.data, origin='lower')   # doctest: +SKIP

.. plot::

    import numpy as np
    import matplotlib.pyplot as plt
    from astropy.modeling.models import Gaussian2D
    from astropy.nddata import Cutout2D
    from astropy.coordinates import SkyCoord
    from astropy.wcs import WCS
    y, x = np.mgrid[0:500, 0:500]
    data = Gaussian2D(1, 50, 100, 10, 5, theta=0.5)(x, y)
    position = SkyCoord('13h11m29.96s -01d19m18.7s', frame='icrs')
    wcs = WCS(naxis=2)
    rho = np.pi / 3.
    scale = 0.05 / 3600.
    wcs.wcs.cd = [[scale*np.cos(rho), -scale*np.sin(rho)],
                  [scale*np.sin(rho), scale*np.cos(rho)]]
    wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
    wcs.wcs.crval = [position.ra.value, position.dec.value]
    wcs.wcs.crpix = [50, 100]
    cutout = Cutout2D(data, position, (30, 40), wcs=wcs)
    plt.imshow(cutout.data, origin='lower')

The ``wcs`` attribute of the `~astropy.nddata.utils.Cutout2D` object now
contains the propagated `~astropy.wcs.WCS` for the cutout array.
Now we can find the sky coordinates for a given pixel in the cutout array.
Note that we need to use the ``cutout.wcs`` object for the cutout
positions::

    >>> from astropy.wcs.utils import pixel_to_skycoord
    >>> x_cutout, y_cutout = (5, 10)
    >>> pixel_to_skycoord(x_cutout, y_cutout, cutout.wcs)    # doctest: +FLOAT_CMP
    <SkyCoord (ICRS): (ra, dec) in deg
        ( 197.8747893, -1.32207626)>

We now find the corresponding pixel in the original ``data`` array and
its sky coordinates::

    >>> x_data, y_data = cutout.to_original_position((x_cutout, y_cutout))
    >>> pixel_to_skycoord(x_data, y_data, wcs)    # doctest: +FLOAT_CMP
    <SkyCoord (ICRS): (ra, dec) in deg
        ( 197.8747893, -1.32207626)>

As expected, the sky coordinates in the original ``data`` and the
cutout array agree.


2D Cutout Using an Angular ``size``
-----------------------------------

The input ``size`` can also be specified as a
`~astropy.units.Quantity` in angular units (e.g., degrees, arcminutes,
arcseconds, etc.). For this case, a `~astropy.wcs.WCS` object must be
input via the ``wcs`` keyword.

For this example, we will use the data, `~astropy.coordinates.SkyCoord`
position, and ``wcs`` object from above to create a cutout with size
1.5 x 2.5 arcseconds::

    >>> size = u.Quantity((1.5, 2.5), u.arcsec)
    >>> cutout = Cutout2D(data, position, size, wcs=wcs)
    >>> plt.imshow(cutout.data, origin='lower')   # doctest: +SKIP

.. plot::

    import numpy as np
    import matplotlib.pyplot as plt
    from astropy.modeling.models import Gaussian2D
    from astropy.nddata import Cutout2D
    from astropy.coordinates import SkyCoord
    from astropy.wcs import WCS
    from astropy import units as u
    y, x = np.mgrid[0:500, 0:500]
    data = Gaussian2D(1, 50, 100, 10, 5, theta=0.5)(x, y)
    position = SkyCoord('13h11m29.96s -01d19m18.7s', frame='icrs')
    wcs = WCS(naxis=2)
    rho = np.pi / 3.
    scale = 0.05 / 3600.
    wcs.wcs.cd = [[scale*np.cos(rho), -scale*np.sin(rho)],
                  [scale*np.sin(rho), scale*np.cos(rho)]]
    wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
    wcs.wcs.crval = [position.ra.value, position.dec.value]
    wcs.wcs.crpix = [50, 100]
    size = u.Quantity((1.5, 2.5), u.arcsec)
    cutout = Cutout2D(data, position, size, wcs=wcs)
    plt.imshow(cutout.data, origin='lower')


Saving a 2D Cutout to a FITS File with an Updated WCS
=====================================================

A `~astropy.nddata.utils.Cutout2D` object can be saved to a FITS file,
including the updated WCS object for the cutout region. In this example, we
download an example FITS image and create a cutout image. The resulting
`~astropy.nddata.utils.Cutout2D` object is then saved to a new FITS file with
the updated WCS for the cutout region.

.. literalinclude:: examples/cutout2d_tofits.py
   :language: python