drizzle 2.0.0__cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of drizzle might be problematic. Click here for more details.

@@ -0,0 +1,193 @@
1
+ import os
2
+
3
+ import numpy as np
4
+ import pytest
5
+ from numpy.testing import assert_almost_equal, assert_equal
6
+
7
+ from astropy import wcs
8
+ from astropy.io import fits
9
+ from drizzle.utils import (
10
+ _estimate_pixel_scale,
11
+ calc_pixmap,
12
+ decode_context,
13
+ estimate_pixel_scale_ratio,
14
+ )
15
+
16
+ TEST_DIR = os.path.abspath(os.path.dirname(__file__))
17
+ DATA_DIR = os.path.join(TEST_DIR, 'data')
18
+
19
+
20
+ def test_map_rectangular():
21
+ """
22
+ Make sure the initial index array has correct values
23
+ """
24
+ naxis1 = 1000
25
+ naxis2 = 10
26
+
27
+ pixmap = np.indices((naxis1, naxis2), dtype='float32')
28
+ pixmap = pixmap.transpose()
29
+
30
+ assert_equal(pixmap[5, 500], (500, 5))
31
+
32
+
33
+ def test_map_to_self():
34
+ """
35
+ Map a pixel array to itself. Should return the same array.
36
+ """
37
+ input_file = os.path.join(DATA_DIR, 'input1.fits')
38
+ input_hdu = fits.open(input_file)
39
+
40
+ input_wcs = wcs.WCS(input_hdu[1].header)
41
+ naxis1, naxis2 = input_wcs.pixel_shape
42
+ input_hdu.close()
43
+
44
+ ok_pixmap = np.indices((naxis1, naxis2), dtype='float32')
45
+ ok_pixmap = ok_pixmap.transpose()
46
+
47
+ pixmap = calc_pixmap(input_wcs, input_wcs)
48
+
49
+ # Got x-y transpose right
50
+ assert_equal(pixmap.shape, ok_pixmap.shape)
51
+
52
+ # Mapping an array to itself
53
+ assert_almost_equal(pixmap, ok_pixmap, decimal=5)
54
+
55
+ # user-provided shape
56
+ pixmap = calc_pixmap(input_wcs, input_wcs, (12, 34))
57
+ assert_equal(pixmap.shape, (12, 34, 2))
58
+
59
+ # Check that an exception is raised for WCS without pixel_shape or
60
+ # bounding_box:
61
+ input_wcs.pixel_shape = None
62
+ with pytest.raises(ValueError):
63
+ calc_pixmap(input_wcs, input_wcs)
64
+
65
+ # user-provided shape when array_shape is not set:
66
+ pixmap = calc_pixmap(input_wcs, input_wcs, (12, 34))
67
+ assert_equal(pixmap.shape, (12, 34, 2))
68
+
69
+ # from bounding box:
70
+ input_wcs.bounding_box = ((5.3, 33.5), (2.8, 11.5))
71
+ pixmap = calc_pixmap(input_wcs, input_wcs)
72
+ assert_equal(pixmap.shape, (12, 34, 2))
73
+
74
+ # from bounding box and pixel_shape (the later takes precedence):
75
+ input_wcs.pixel_shape = (naxis1, naxis2)
76
+ pixmap = calc_pixmap(input_wcs, input_wcs)
77
+ assert_equal(pixmap.shape, ok_pixmap.shape)
78
+
79
+
80
+ def test_translated_map():
81
+ """
82
+ Map a pixel array to at translated array.
83
+ """
84
+ first_file = os.path.join(DATA_DIR, 'input1.fits')
85
+ first_hdu = fits.open(first_file)
86
+ first_header = first_hdu[1].header
87
+
88
+ first_wcs = wcs.WCS(first_header)
89
+ naxis1, naxis2 = first_wcs.pixel_shape
90
+ first_hdu.close()
91
+
92
+ second_file = os.path.join(DATA_DIR, 'input3.fits')
93
+ second_hdu = fits.open(second_file)
94
+ second_header = second_hdu[1].header
95
+
96
+ second_wcs = wcs.WCS(second_header)
97
+ second_hdu.close()
98
+
99
+ ok_pixmap = np.indices((naxis1, naxis2), dtype='float32') - 2.0
100
+ ok_pixmap = ok_pixmap.transpose()
101
+
102
+ pixmap = calc_pixmap(first_wcs, second_wcs)
103
+
104
+ # Got x-y transpose right
105
+ assert_equal(pixmap.shape, ok_pixmap.shape)
106
+ # Mapping an array to a translated array
107
+ assert_almost_equal(pixmap, ok_pixmap, decimal=5)
108
+
109
+
110
+ def test_estimate_pixel_scale_ratio():
111
+ input_file = os.path.join(DATA_DIR, 'j8bt06nyq_flt.fits')
112
+
113
+ with fits.open(input_file) as h:
114
+ w = wcs.WCS(h[1].header)
115
+
116
+ pscale = estimate_pixel_scale_ratio(w, w, w.wcs.crpix, (0, 0))
117
+
118
+ assert abs(pscale - 0.9999999916964737) < 1.0e-9
119
+
120
+
121
+ def test_estimate_pixel_scale_no_refpix():
122
+ # create a WCS without higher order (polynomial) distortions:
123
+ fits_file = os.path.join(DATA_DIR, 'input1.fits')
124
+ with fits.open(fits_file) as h:
125
+ w = wcs.WCS(h[1].header, h)
126
+ w.sip = None
127
+ w.det2im1 = None
128
+ w.det2im2 = None
129
+ w.cpdis1 = None
130
+ w.cpdis2 = None
131
+ pixel_shape = w.pixel_shape[:]
132
+
133
+ ref_pscale = _estimate_pixel_scale(w, w.wcs.crpix)
134
+
135
+ if hasattr(w, 'bounding_box'):
136
+ del w.bounding_box
137
+ pscale1 = _estimate_pixel_scale(w, None)
138
+ assert np.allclose(ref_pscale, pscale1, atol=0.0, rtol=1.0e-8)
139
+
140
+ w.bounding_box = None
141
+ w.pixel_shape = None
142
+ pscale2 = _estimate_pixel_scale(w, None)
143
+ assert np.allclose(pscale1, pscale2, atol=0.0, rtol=1.0e-8)
144
+
145
+ w.pixel_shape = pixel_shape
146
+ pscale3 = _estimate_pixel_scale(w, None)
147
+ assert np.allclose(pscale1, pscale3, atol=0.0, rtol=1.0e-14)
148
+
149
+ w.bounding_box = ((-0.5, pixel_shape[0] - 0.5), (-0.5, pixel_shape[1] - 0.5))
150
+ pscale4 = _estimate_pixel_scale(w, None)
151
+ assert np.allclose(pscale3, pscale4, atol=0.0, rtol=1.0e-8)
152
+
153
+
154
+ def test_decode_context():
155
+ ctx = np.array(
156
+ [[[0, 0, 0, 0, 0, 0],
157
+ [0, 0, 0, 36196864, 0, 0],
158
+ [0, 0, 0, 0, 0, 0],
159
+ [0, 0, 0, 0, 0, 0],
160
+ [0, 0, 537920000, 0, 0, 0]],
161
+ [[0, 0, 0, 0, 0, 0,],
162
+ [0, 0, 0, 67125536, 0, 0],
163
+ [0, 0, 0, 0, 0, 0],
164
+ [0, 0, 0, 0, 0, 0],
165
+ [0, 0, 163856, 0, 0, 0]],
166
+ [[0, 0, 0, 0, 0, 0],
167
+ [0, 0, 0, 8203, 0, 0],
168
+ [0, 0, 0, 0, 0, 0],
169
+ [0, 0, 0, 0, 0, 0],
170
+ [0, 0, 32865, 0, 0, 0]]],
171
+ dtype=np.int32
172
+ )
173
+
174
+ idx1, idx2 = decode_context(ctx, [3, 2], [1, 4])
175
+
176
+ assert sorted(idx1) == [9, 12, 14, 19, 21, 25, 37, 40, 46, 58, 64, 65, 67, 77]
177
+ assert sorted(idx2) == [9, 20, 29, 36, 47, 49, 64, 69, 70, 79]
178
+
179
+ # context array must be 3D:
180
+ with pytest.raises(ValueError):
181
+ decode_context(ctx[0], [3, 2], [1, 4])
182
+
183
+ # pixel coordinates must be integer:
184
+ with pytest.raises(ValueError):
185
+ decode_context(ctx, [3.0, 2], [1, 4])
186
+
187
+ # coordinate lists must be equal in length:
188
+ with pytest.raises(ValueError):
189
+ decode_context(ctx, [3, 2], [1, 4, 5])
190
+
191
+ # coordinate lists must be 1D:
192
+ with pytest.raises(ValueError):
193
+ decode_context(ctx, [[3, 2]], [[1, 4]])
drizzle/util.py ADDED
@@ -0,0 +1,34 @@
1
+ """
2
+ Module ``util`` has been deprecated.
3
+ """
4
+ import warnings
5
+
6
+ warnings.warn(
7
+ "Module 'drizzle.util' has been deprecated since version 2.0.0 "
8
+ "and it will be removed in a future release. "
9
+ "Please replace calls to 'util.is_blank()' with alternative "
10
+ "implementation.",
11
+ DeprecationWarning
12
+ )
13
+
14
+
15
+ def is_blank(value):
16
+ """
17
+ Determines whether or not a value is considered 'blank'.
18
+
19
+ Parameters
20
+ ----------
21
+ value : str
22
+ The value to check
23
+
24
+ Returns
25
+ -------
26
+ True or False
27
+ """
28
+ warnings.warn(
29
+ "'is_blank()' has been deprecated since version 2.0.0 "
30
+ "and it will be removed in a future release. "
31
+ "Please replace calls to 'is_blank()' with alternative implementation.",
32
+ DeprecationWarning
33
+ )
34
+ return value.strip() == ""
drizzle/utils.py ADDED
@@ -0,0 +1,239 @@
1
+ import math
2
+
3
+ import numpy as np
4
+
5
+ __all__ = ["calc_pixmap", "decode_context", "estimate_pixel_scale_ratio"]
6
+
7
+ _DEG2RAD = math.pi / 180.0
8
+
9
+
10
+ def calc_pixmap(wcs_from, wcs_to, shape=None):
11
+ """
12
+ Calculate a discretized on a grid mapping between the pixels of two images
13
+ using provided WCS of the original ("from") image and the destination ("to")
14
+ image.
15
+
16
+ .. note::
17
+ This function assumes that output frames of ``wcs_from`` and ``wcs_to``
18
+ WCS have the same units.
19
+
20
+ Parameters
21
+ ----------
22
+ wcs_from : wcs
23
+ A WCS object representing the coordinate system you are
24
+ converting from. This object's ``array_shape`` (or ``pixel_shape``)
25
+ property will be used to define the shape of the pixel map array.
26
+ If ``shape`` parameter is provided, it will take precedence
27
+ over this object's ``array_shape`` value.
28
+
29
+ wcs_to : wcs
30
+ A WCS object representing the coordinate system you are
31
+ converting to.
32
+
33
+ shape : tuple, None, optional
34
+ A tuple of integers indicating the shape of the output array in the
35
+ ``numpy.ndarray`` order. When provided, it takes precedence over the
36
+ ``wcs_from.array_shape`` property.
37
+
38
+ Returns
39
+ -------
40
+ pixmap : numpy.ndarray
41
+ A three dimensional array representing the transformation between
42
+ the two. The last dimension is of length two and contains the x and
43
+ y coordinates of a pixel center, repectively. The other two coordinates
44
+ correspond to the two coordinates of the image the first WCS is from.
45
+
46
+ Raises
47
+ ------
48
+ ValueError
49
+ A `ValueError` is raised when output pixel map shape cannot be
50
+ determined from provided inputs.
51
+
52
+ Notes
53
+ -----
54
+ When ``shape`` is not provided and ``wcs_from.array_shape`` is not set
55
+ (i.e., it is `None`), `calc_pixmap` will attempt to determine pixel map
56
+ shape from the ``bounding_box`` property of the input ``wcs_from`` object.
57
+ If ``bounding_box`` is not available, a `ValueError` will be raised.
58
+
59
+ """
60
+ if shape is None:
61
+ shape = wcs_from.array_shape
62
+ if shape is None:
63
+ if (bbox := getattr(wcs_from, "bounding_box", None)) is not None:
64
+ if (nd := np.ndim(bbox)) == 1:
65
+ bbox = (bbox, )
66
+ if nd > 1:
67
+ shape = tuple(
68
+ int(math.ceil(lim[1] + 0.5)) for lim in bbox[::-1]
69
+ )
70
+
71
+ if shape is None:
72
+ raise ValueError(
73
+ 'The "from" WCS must have pixel_shape property set.'
74
+ )
75
+
76
+ y, x = np.indices(shape, dtype=np.float64)
77
+ x, y = wcs_to.world_to_pixel_values(*wcs_from.pixel_to_world_values(x, y))
78
+ pixmap = np.dstack([x, y])
79
+ return pixmap
80
+
81
+
82
+ def estimate_pixel_scale_ratio(wcs_from, wcs_to, refpix_from=None, refpix_to=None):
83
+ """
84
+ Compute the ratio of the pixel scale of the "to" WCS at the ``refpix_to``
85
+ position to the pixel scale of the "from" WCS at the ``refpix_from``
86
+ position. Pixel scale ratio,
87
+ when requested, is computed near the centers of the bounding box
88
+ (a property of the WCS object) or near ``refpix_*`` coordinates
89
+ if supplied.
90
+
91
+ Pixel scale is estimated as the square root of pixel's area, i.e.,
92
+ pixels are assumed to have a square shape at the reference
93
+ pixel position. If input reference pixel position for a WCS is `None`,
94
+ it will be taken as the center of the bounding box
95
+ if ``wcs_*`` has a bounding box defined, or as the center of the box
96
+ defined by the ``pixel_shape`` attribute of the input WCS if
97
+ ``pixel_shape`` is defined (not `None`), or at pixel coordinates
98
+ ``(0, 0)``.
99
+
100
+ Parameters
101
+ ----------
102
+ wcs_from : wcs
103
+ A WCS object representing the coordinate system you are
104
+ converting from. This object *must* have ``pixel_shape`` property
105
+ defined.
106
+
107
+ wcs_to : wcs
108
+ A WCS object representing the coordinate system you are
109
+ converting to.
110
+
111
+ refpix_from : numpy.ndarray, tuple, list
112
+ Image coordinates of the reference pixel near which pixel scale should
113
+ be computed in the "from" image. In FITS WCS this could be, for example,
114
+ the value of CRPIX of the ``wcs_from`` WCS.
115
+
116
+ refpix_to : numpy.ndarray, tuple, list
117
+ Image coordinates of the reference pixel near which pixel scale should
118
+ be computed in the "to" image. In FITS WCS this could be, for example,
119
+ the value of CRPIX of the ``wcs_to`` WCS.
120
+
121
+ Returns
122
+ -------
123
+ pixel_scale_ratio : float
124
+ Estimate the ratio of "to" to "from" WCS pixel scales. This value is
125
+ returned only when ``estimate_pixel_scale_ratio`` is `True`.
126
+
127
+ """
128
+ pscale_ratio = (_estimate_pixel_scale(wcs_to, refpix_to) /
129
+ _estimate_pixel_scale(wcs_from, refpix_from))
130
+ return pscale_ratio
131
+
132
+
133
+ def _estimate_pixel_scale(wcs, refpix):
134
+ # estimate pixel scale (in rad) using approximate algorithm
135
+ # from https://trs.jpl.nasa.gov/handle/2014/40409
136
+ if refpix is None:
137
+ if hasattr(wcs, 'bounding_box') and wcs.bounding_box is not None:
138
+ refpix = np.mean(wcs.bounding_box, axis=-1)
139
+ else:
140
+ if wcs.pixel_shape:
141
+ refpix = np.array([(i - 1) // 2 for i in wcs.pixel_shape])
142
+ else:
143
+ refpix = np.zeros(wcs.pixel_n_dim)
144
+
145
+ else:
146
+ refpix = np.asarray(refpix)
147
+
148
+ l1, phi1 = wcs.pixel_to_world_values(*(refpix - 0.5))
149
+ l2, phi2 = wcs.pixel_to_world_values(*(refpix + [-0.5, 0.5]))
150
+ l3, phi3 = wcs.pixel_to_world_values(*(refpix + 0.5))
151
+ l4, phi4 = wcs.pixel_to_world_values(*(refpix + [0.5, -0.5]))
152
+ area = _DEG2RAD * abs(
153
+ 0.5 * (
154
+ (l4 - l2) * (math.sin(_DEG2RAD * phi1) - math.sin(_DEG2RAD * phi3)) +
155
+ (l1 - l3) * (math.sin(_DEG2RAD * phi2) - math.sin(_DEG2RAD * phi4))
156
+ )
157
+ )
158
+ return math.sqrt(area)
159
+
160
+
161
+ def decode_context(context, x, y):
162
+ """Get 0-based indices of input images that contributed to (resampled)
163
+ output pixel with coordinates ``x`` and ``y``.
164
+
165
+ Parameters
166
+ ----------
167
+ context: numpy.ndarray
168
+ A 3D `~numpy.ndarray` of integral data type.
169
+
170
+ x: int, list of integers, numpy.ndarray of integers
171
+ X-coordinate of pixels to decode (3rd index into the ``context`` array)
172
+
173
+ y: int, list of integers, numpy.ndarray of integers
174
+ Y-coordinate of pixels to decode (2nd index into the ``context`` array)
175
+
176
+ Returns
177
+ -------
178
+ A list of `numpy.ndarray` objects each containing indices of input images
179
+ that have contributed to an output pixel with coordinates ``x`` and ``y``.
180
+ The length of returned list is equal to the number of input coordinate
181
+ arrays ``x`` and ``y``.
182
+
183
+ Examples
184
+ --------
185
+ An example context array for an output image of array shape ``(5, 6)``
186
+ obtained by resampling 80 input images.
187
+
188
+ >>> import numpy as np
189
+ >>> from drizzle.utils import decode_context
190
+ >>> ctx = np.array(
191
+ ... [[[0, 0, 0, 0, 0, 0],
192
+ ... [0, 0, 0, 36196864, 0, 0],
193
+ ... [0, 0, 0, 0, 0, 0],
194
+ ... [0, 0, 0, 0, 0, 0],
195
+ ... [0, 0, 537920000, 0, 0, 0]],
196
+ ... [[0, 0, 0, 0, 0, 0,],
197
+ ... [0, 0, 0, 67125536, 0, 0],
198
+ ... [0, 0, 0, 0, 0, 0],
199
+ ... [0, 0, 0, 0, 0, 0],
200
+ ... [0, 0, 163856, 0, 0, 0]],
201
+ ... [[0, 0, 0, 0, 0, 0],
202
+ ... [0, 0, 0, 8203, 0, 0],
203
+ ... [0, 0, 0, 0, 0, 0],
204
+ ... [0, 0, 0, 0, 0, 0],
205
+ ... [0, 0, 32865, 0, 0, 0]]],
206
+ ... dtype=np.int32
207
+ ... )
208
+ >>> decode_context(ctx, [3, 2], [1, 4])
209
+ [array([ 9, 12, 14, 19, 21, 25, 37, 40, 46, 58, 64, 65, 67, 77]),
210
+ array([ 9, 20, 29, 36, 47, 49, 64, 69, 70, 79])]
211
+
212
+ """
213
+ if context.ndim != 3:
214
+ raise ValueError("'context' must be a 3D array.")
215
+
216
+ x = np.atleast_1d(x)
217
+ y = np.atleast_1d(y)
218
+
219
+ if x.size != y.size:
220
+ raise ValueError("Coordinate arrays must have equal length.")
221
+
222
+ if x.ndim != 1:
223
+ raise ValueError("Coordinates must be scalars or 1D arrays.")
224
+
225
+ if not (np.issubdtype(x.dtype, np.integer) and
226
+ np.issubdtype(y.dtype, np.integer)):
227
+ raise ValueError('Pixel coordinates must be integer values')
228
+
229
+ nbits = 8 * context.dtype.itemsize
230
+ one = np.array(1, context.dtype)
231
+ flags = np.array([one << i for i in range(nbits)])
232
+
233
+ idx = []
234
+ for xi, yi in zip(x, y):
235
+ idx.append(
236
+ np.flatnonzero(np.bitwise_and.outer(context[:, yi, xi], flags))
237
+ )
238
+
239
+ return idx
@@ -0,0 +1,31 @@
1
+ Copyright (C) 2011,2014 Association of Universities for Research in
2
+ Astronomy (AURA)
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions
6
+ are met:
7
+
8
+ 1. Redistributions of source code must retain the above
9
+ copyright notice, this list of conditions and the following
10
+ disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above
13
+ copyright notice, this list of conditions and the following
14
+ disclaimer in the documentation and/or other materials
15
+ provided with the distribution.
16
+
17
+ 3. The name of AURA and its representatives may not be used to
18
+ endorse or promote products derived from this software without
19
+ specific prior written permission.
20
+
21
+ THIS SOFTWARE IS PROVIDED BY AURA ``AS IS'' AND ANY EXPRESS OR
22
+ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24
+ ARE DISCLAIMED. IN NO EVENT SHALL AURA BE LIABLE FOR ANY DIRECT,
25
+ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28
+ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29
+ STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31
+ OF THE POSSIBILITY OF SUCH DAMAGE.