drizzle 2.2.0__cp313-cp313-win_amd64.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.
File without changes
@@ -0,0 +1,215 @@
1
+ import os
2
+
3
+ import gwcs
4
+ import numpy as np
5
+ from gwcs.coordinate_frames import CelestialFrame, Frame2D
6
+
7
+ from astropy import coordinates as coord
8
+ from astropy import units
9
+ from astropy import wcs as fits_wcs
10
+ from astropy.io import fits
11
+ from astropy.modeling.models import (
12
+ Mapping,
13
+ Pix2Sky_TAN,
14
+ Polynomial2D,
15
+ RotateNative2Celestial,
16
+ Shift,
17
+ )
18
+ from astropy.modeling.projections import AffineTransformation2D
19
+
20
+ __all__ = ["wcs_from_file"]
21
+
22
+ TEST_DIR = os.path.abspath(os.path.dirname(__file__))
23
+ DATA_DIR = os.path.join(TEST_DIR, "data")
24
+
25
+
26
+ def wcs_from_file(filename, ext=None, return_data=False, crpix_shift=None, wcs_type="fits"):
27
+ """
28
+ Read the WCS from a ".fits" file.
29
+
30
+ Parameters
31
+ ----------
32
+ filename : str
33
+ Name of the file to load WCS from.
34
+
35
+ ext : int, None, optional
36
+ Extension number to load the WCS from. When `None`, the WCS will be
37
+ loaded from the first extension containing a WCS.
38
+
39
+ return_data : bool, optional
40
+ When `True`, this function will return a tuple with first item
41
+ being the WCS and the second item being the image data array.
42
+
43
+ crpix_shift : tuple, None, optional
44
+ A tuple of two values to be added to header CRPIX values before
45
+ creating the WCS. This effectively introduces a constant shift
46
+ in the image coordinate system.
47
+
48
+ wcs_type : {"fits", "gwcs"}, optional
49
+ Return either a FITS WCS or a gwcs.
50
+
51
+ Returns
52
+ -------
53
+ WCS or tuple of WCS and image data
54
+
55
+ """
56
+ full_file_name = os.path.join(DATA_DIR, filename)
57
+ path = os.path.join(DATA_DIR, full_file_name)
58
+
59
+ def get_shape(hdr):
60
+ naxis1 = hdr.get("WCSNAX1", hdr.get("NAXIS1"))
61
+ naxis2 = hdr.get("WCSNAX2", hdr.get("NAXIS2"))
62
+ if naxis1 is None or naxis2 is None:
63
+ return None
64
+ return (naxis2, naxis1)
65
+
66
+ def data_from_hdr(hdr, data=None, shape=None):
67
+ if data is not None:
68
+ return data
69
+ bitpix = hdr.get("BITPIX", -32)
70
+ dtype = fits.hdu.BITPIX2DTYPE[bitpix]
71
+ shape = get_shape(hdr) or shape
72
+ if shape is None:
73
+ return None
74
+ return np.zeros(shape, dtype=dtype)
75
+
76
+ if os.path.splitext(filename)[1] in [".hdr", ".txt"]:
77
+ hdul = None
78
+ hdr = fits.Header.fromfile(path, sep="\n", endcard=False, padding=False)
79
+
80
+ else:
81
+ with fits.open(path) as fits_hdul:
82
+ hdul = fits.HDUList([hdu.copy() for hdu in fits_hdul])
83
+
84
+ if ext is None and hdul is not None:
85
+ for k, u in enumerate(hdul):
86
+ if "CTYPE1" in u.header:
87
+ ext = k
88
+ break
89
+
90
+ hdr = hdul[ext].header
91
+
92
+ if crpix_shift is not None and "CRPIX1" in hdr:
93
+ hdr["CRPIX1"] += crpix_shift[0]
94
+ hdr["CRPIX2"] += crpix_shift[1]
95
+
96
+ # this is to avoid warnings about naxis mismatch
97
+ # "FITSFixedWarning: The WCS transformation has more axes (2) than the
98
+ # image it is associated with (0)" which, unfortunately, we cannot turn off.
99
+ if hdul and hdul[ext].data is None:
100
+ hdul[ext].data = np.empty(get_shape(hdr)[::-1], dtype=np.float32)
101
+
102
+ result = fits_wcs.WCS(hdr, hdul)
103
+
104
+ shape = get_shape(hdr)
105
+ result.array_shape = shape
106
+
107
+ if wcs_type == "gwcs":
108
+ result = _gwcs_from_hst_fits_wcs(result)
109
+
110
+ if return_data:
111
+ if hdul is None:
112
+ data = data_from_hdr(hdr, data=None, shape=shape)
113
+ return (result, data)
114
+
115
+ result = (result,)
116
+ if not isinstance(return_data, (list, tuple)):
117
+ return_data = [ext]
118
+ for ext in return_data:
119
+ data = data_from_hdr(hdul[ext].header, data=hdul[ext].data, shape=shape)
120
+ result = result + (data,)
121
+
122
+ return result
123
+
124
+
125
+ def _gwcs_from_hst_fits_wcs(w):
126
+ # NOTE: this function ignores table distortions
127
+ def coeffs_to_poly(mat, degree):
128
+ pol = Polynomial2D(degree=degree)
129
+ for i in range(mat.shape[0]):
130
+ for j in range(mat.shape[1]):
131
+ if 0 < i + j <= degree:
132
+ setattr(pol, f"c{i}_{j}", mat[i, j])
133
+ return pol
134
+
135
+ nx, ny = w.pixel_shape
136
+ x0, y0 = w.wcs.crpix - 1
137
+
138
+ cd = w.wcs.piximg_matrix
139
+
140
+ if w.sip is None:
141
+ # construct GWCS:
142
+ det2sky = (
143
+ (Shift(-x0) & Shift(-y0)) | Pix2Sky_TAN() | RotateNative2Celestial(*w.wcs.crval, 180)
144
+ )
145
+ else:
146
+ cfx, cfy = np.dot(cd, [w.sip.a.ravel(), w.sip.b.ravel()])
147
+ a = np.reshape(cfx, w.sip.a.shape)
148
+ b = np.reshape(cfy, w.sip.b.shape)
149
+ a[1, 0] = cd[0, 0]
150
+ a[0, 1] = cd[0, 1]
151
+ b[1, 0] = cd[1, 0]
152
+ b[0, 1] = cd[1, 1]
153
+
154
+ polx = coeffs_to_poly(a, w.sip.a_order)
155
+ poly = coeffs_to_poly(b, w.sip.b_order)
156
+
157
+ sip = Mapping((0, 1, 0, 1)) | (polx & poly)
158
+
159
+ # construct GWCS:
160
+ det2sky = (
161
+ (Shift(-x0) & Shift(-y0))
162
+ | sip
163
+ | Pix2Sky_TAN()
164
+ | RotateNative2Celestial(*w.wcs.crval, 180)
165
+ )
166
+
167
+ detector_frame = Frame2D(name="detector", axes_names=("x", "y"), unit=(units.pix, units.pix))
168
+ sky_frame = CelestialFrame(
169
+ reference_frame=getattr(coord, w.wcs.radesys).__call__(),
170
+ name=w.wcs.radesys,
171
+ unit=(units.deg, units.deg),
172
+ )
173
+ pipeline = [(detector_frame, det2sky), (sky_frame, None)]
174
+ gw = gwcs.wcs.WCS(pipeline)
175
+ gw.array_shape = w.array_shape
176
+ gw.bounding_box = ((-0.5, nx - 0.5), (-0.5, ny - 0.5))
177
+
178
+ if w.sip is not None:
179
+ # compute inverse SIP and re-create output GWCS
180
+
181
+ # compute inverse SIP:
182
+ hdr = gw.to_fits_sip(
183
+ max_inv_pix_error=1e-5,
184
+ inv_degree=None,
185
+ npoints=64,
186
+ crpix=w.wcs.crpix,
187
+ projection="TAN",
188
+ verbose=False,
189
+ )
190
+ winv = fits_wcs.WCS(hdr)
191
+ ap = winv.sip.ap.copy()
192
+ bp = winv.sip.bp.copy()
193
+ ap[1, 0] += 1
194
+ bp[0, 1] += 1
195
+ polx_inv = coeffs_to_poly(ap, winv.sip.ap_order)
196
+ poly_inv = coeffs_to_poly(bp, winv.sip.bp_order)
197
+ af = AffineTransformation2D(matrix=np.linalg.inv(winv.wcs.piximg_matrix))
198
+
199
+ # set analytical inverses:
200
+ sip.inverse = af | Mapping((0, 1, 0, 1)) | (polx_inv & poly_inv)
201
+
202
+ # construct GWCS:
203
+ det2sky = (
204
+ (Shift(-x0) & Shift(-y0))
205
+ | sip
206
+ | Pix2Sky_TAN()
207
+ | RotateNative2Celestial(*w.wcs.crval, 180)
208
+ )
209
+
210
+ pipeline = [(detector_frame, det2sky), (sky_frame, None)]
211
+ gw = gwcs.wcs.WCS(pipeline)
212
+ gw.array_shape = w.array_shape
213
+ gw.bounding_box = ((-0.5, nx - 0.5), (-0.5, ny - 0.5))
214
+
215
+ return gw
@@ -0,0 +1,29 @@
1
+ import numpy as np
2
+
3
+ from drizzle import cdrizzle
4
+
5
+
6
+ def test_cdrizzle():
7
+ """
8
+ Call C unit tests for cdrizzle, which are in the src/tests directory
9
+ """
10
+
11
+ size = 100
12
+ data = np.zeros((size, size), dtype="float32")
13
+ weights = np.ones((size, size), dtype="float32")
14
+
15
+ pixmap = np.indices((size, size), dtype="float64")
16
+ pixmap = pixmap.transpose()
17
+
18
+ output_data = np.zeros((size, size), dtype="float32")
19
+ output_counts = np.zeros((size, size), dtype="float32")
20
+ output_context = np.zeros((size, size), dtype="int32")
21
+
22
+ cdrizzle.test_cdrizzle(
23
+ data,
24
+ weights,
25
+ pixmap,
26
+ output_data,
27
+ output_counts,
28
+ output_context,
29
+ )
@@ -0,0 +1,287 @@
1
+ from itertools import product
2
+ from math import sqrt
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from drizzle.cdrizzle import clip_polygon, invert_pixmap
8
+
9
+ SQ2 = 1.0 / sqrt(2.0)
10
+
11
+
12
+ def _is_poly_eq(p1, p2, rtol=0, atol=4e-12):
13
+ if len(p1) != len(p2):
14
+ return False
15
+
16
+ p1 = p1[:]
17
+ for _ in p1:
18
+ p1.append(p1.pop(0))
19
+ if np.allclose(p1, p2, rtol=rtol, atol=atol):
20
+ return True
21
+ return False
22
+
23
+
24
+ def _coord_mapping(xin, yin):
25
+ crpix = (289, 348) # center of distortions
26
+ shift = (1000, 1000)
27
+ rmat = 2.0 * np.array([[0.78103169, 0.66712321], [-0.63246699, 0.74091539]])
28
+ x = xin - crpix[0]
29
+ y = yin - crpix[1]
30
+
31
+ # add non-linear distortions
32
+ x += 2.4e-6 * x**2 - 1.0e-7 * x * y + 3.1e-6 * y**2
33
+ y += 1.2e-6 * x**2 - 2.0e-7 * x * y + 1.1e-6 * y**2
34
+
35
+ x, y = np.dot(rmat, [x, y])
36
+ x += shift[0]
37
+ y += shift[1]
38
+
39
+ return x, y
40
+
41
+
42
+ def _roll_vertices(polygon, n=1):
43
+ n = n % len(polygon)
44
+ return polygon[n:] + polygon[:n]
45
+
46
+
47
+ def test_invert_pixmap():
48
+ yin, xin = np.indices((1000, 1200), dtype=float)
49
+ xin = xin.flatten()
50
+ yin = yin.flatten()
51
+
52
+ xout, yout = _coord_mapping(xin, yin)
53
+ xout = xout.reshape((1000, 1200))
54
+ yout = yout.reshape((1000, 1200))
55
+ pixmap = np.dstack([xout, yout])
56
+
57
+ test_coords = [
58
+ (300, 600),
59
+ (0, 0),
60
+ (1199, 999),
61
+ (0, 999),
62
+ (1199, 0),
63
+ (200, 0),
64
+ (0, 438),
65
+ (1199, 432),
66
+ ]
67
+
68
+ for xr, yr in test_coords:
69
+ xout_t, yout_t = _coord_mapping(xr, yr)
70
+ xyin = invert_pixmap(pixmap, [xout_t, yout_t], [[-0.5, 1199.5], [-0.5, 999.5]])
71
+ assert np.allclose(xyin, [xr, yr], atol=0.05)
72
+
73
+
74
+ def test_invert_small_pixmap():
75
+ yin, xin = np.indices((2, 2), dtype=float)
76
+ pixmap = np.dstack([xin, yin])
77
+
78
+ test_coords = list(product(*(2 * [[-0.5, 1.5]])))
79
+
80
+ for xr, yr in test_coords:
81
+ xyin = invert_pixmap(pixmap, [xr, yr], [[-0.5, 1.5], [-0.5, 1.5]])
82
+ assert np.allclose(xyin, [xr, yr], atol=0.05)
83
+
84
+
85
+ def test_poly_intersection_with_self():
86
+ p = [(0, 0), (1, 0), (1, 1), (0, 1)]
87
+
88
+ for k in range(4):
89
+ q = _roll_vertices(p, k)
90
+
91
+ pq = clip_polygon(q, p)
92
+ assert _is_poly_eq(pq, q)
93
+
94
+
95
+ @pytest.mark.parametrize(
96
+ "shift",
97
+ [(0.25, 0.1), (-0.25, -0.1), (-0.25, 0.1), (0.25, -0.1)],
98
+ )
99
+ def test_poly_intersection_shifted(shift):
100
+ p = [(0, 0), (1, 0), (1, 1), (0, 1)]
101
+ sx, sy = shift
102
+ pq_ref = sorted(
103
+ [
104
+ (max(0, sx), max(0, sy)),
105
+ (min(1, sx + 1), max(0, sy)),
106
+ (min(1, sx + 1), min(1, sy + 1)),
107
+ (max(0, sx), min(1, sy + 1)),
108
+ ],
109
+ )
110
+
111
+ for k in range(4):
112
+ q = [(x + sx, y + sy) for x, y in p]
113
+ q = _roll_vertices(q, k)
114
+ pq = clip_polygon(q, p)
115
+ assert np.allclose(sorted(pq), pq_ref)
116
+
117
+
118
+ @pytest.mark.parametrize(
119
+ "shift",
120
+ [(0, 70), (70, 0), (0, -70), (-70, 0)],
121
+ )
122
+ def test_poly_intersection_shifted_large(shift):
123
+ p = [(-0.5, -0.5), (99.5, -0.5), (99.5, 99.5), (-0.5, 99.5)]
124
+ sx, sy = shift
125
+ pq_ref = sorted(
126
+ [
127
+ (max(-0.5, -0.5 + sx), max(-0.5, -0.5 + sy)),
128
+ (min(99.5, 99.5 + sx), max(-0.5, -0.5 + sy)),
129
+ (min(99.5, 99.5 + sx), min(99.5, 99.5 + sy)),
130
+ (max(-0.5, -0.5 + sx), min(99.5, 99.5 + sy)),
131
+ ],
132
+ )
133
+
134
+ for k in range(4):
135
+ q = [(x + sx, y + sy) for x, y in p]
136
+ q = _roll_vertices(q, k)
137
+ pq = clip_polygon(p, q)
138
+ assert len(pq) == 4
139
+ assert np.allclose(sorted(pq), pq_ref)
140
+
141
+
142
+ def test_poly_intersection_rotated45():
143
+ p = [(0, 0), (1, 0), (1, 1), (0, 1)]
144
+ q = [(0, 0), (SQ2, -SQ2), (2.0 * SQ2, 0), (SQ2, SQ2)]
145
+ pq_ref = [(0, 0), (SQ2, SQ2), (1, 0), (1, SQ2 / (1.0 + SQ2))]
146
+
147
+ for k in range(4):
148
+ q = _roll_vertices(q, k)
149
+ pq = clip_polygon(p, q)
150
+ assert np.allclose(sorted(pq), pq_ref)
151
+
152
+
153
+ @pytest.mark.parametrize(
154
+ "axis",
155
+ [0, 1],
156
+ )
157
+ def test_poly_intersection_flipped_axis(axis):
158
+ p = [(0, 0), (1, 0), (1, 1), (0, 1)]
159
+ # (flipped wrt X-axis or Y-axis). Also change direction:
160
+ if axis == 0:
161
+ q = [(i, -j) for i, j in p][::-1]
162
+ else:
163
+ q = [(-i, j) for i, j in p][::-1]
164
+
165
+ for k in range(4):
166
+ q = _roll_vertices(q, k)
167
+ pq = clip_polygon(p, q)
168
+ assert len(pq) == 0
169
+
170
+
171
+ def test_poly_intersection_reflect_origin():
172
+ p = [(0, 0), (1, 0), (1, 1), (0, 1)]
173
+ # reflect wrt origin:
174
+ q = [(-i, -j) for i, j in p]
175
+
176
+ for k in range(4):
177
+ q = _roll_vertices(q, k)
178
+ pq = clip_polygon(p, q)
179
+ assert not pq
180
+
181
+
182
+ @pytest.mark.parametrize(
183
+ "q,small",
184
+ [
185
+ ([(0.1, 0.1), (0.9, 0.1), (0.9, 0.9), (0.1, 0.9)], True),
186
+ ([(0.0, 0.0), (1.0, 0.0), (1.0, 0.4), (0.0, 0.4)], True),
187
+ ([(-0.1, -0.1), (1.1, -0.1), (1.1, 1.1), (-0.1, 1.1)], False),
188
+ ],
189
+ )
190
+ def test_poly_includes_the_other(q, small):
191
+ wnd = [(0, 0), (1, 0), (1, 1), (0, 1)]
192
+
193
+ for k in range(4):
194
+ q = _roll_vertices(q, k)
195
+ qp = clip_polygon(q, wnd)
196
+
197
+ assert _is_poly_eq(qp, q if small else wnd)
198
+
199
+
200
+ @pytest.mark.parametrize(
201
+ "q",
202
+ [
203
+ [(0, 0), (1, 0), (0.5, 0.6)],
204
+ [(0.1, 0), (0.9, 0), (0.5, 0.6)],
205
+ ],
206
+ )
207
+ def test_poly_triangle_common_side(q):
208
+ p = [(0, 0), (1, 0), (1, 1), (0, 1)]
209
+ sq = sorted(q)
210
+
211
+ for k in range(3):
212
+ q = _roll_vertices(q, k)
213
+ pq = clip_polygon(p, q)
214
+ assert np.allclose(sq, sorted(pq))
215
+
216
+
217
+ def test_poly_triangle_common_side_lg():
218
+ p = [(0, 0), (1, 0), (1, 1), (0, 1)]
219
+ q = [(-0.1, 0), (1.1, 0), (0.5, 0.6)]
220
+ ref_pq = [(0, 0), (0, 0.1), (0.5, 0.6), (1, 0), (1, 0.1)]
221
+
222
+ for k in range(3):
223
+ q = _roll_vertices(q, k)
224
+ pq = clip_polygon(p, q)
225
+ assert np.allclose(ref_pq, sorted(pq))
226
+
227
+
228
+ def test_poly_intersection_with_self_extra_vertices():
229
+ p = [(0, 0), (1, 0), (1, 1), (0, 1)]
230
+ p_ref = [(0, 0), (0, 1), (1, 0), (1, 1)]
231
+ # Q is same as P with extra vertices places along P's edges
232
+ q = [(0, 0), (0.5, 0), (1, 0), (1, 0.4), (1, 1), (0.7, 1), (0, 1), (0, 0.2)]
233
+
234
+ for k in range(4):
235
+ q = _roll_vertices(q, k)
236
+
237
+ pq = clip_polygon(p, q)
238
+ assert sorted(pq) == p_ref
239
+
240
+ pq = clip_polygon(q, p)
241
+ assert sorted(pq) == p_ref
242
+
243
+
244
+ def test_intersection_case01():
245
+ # a real case of failure of the code from PR #104
246
+ p = [
247
+ (4517.377385, 8863.424319),
248
+ (5986.279535, 12966.888023),
249
+ (1917.908619, 14391.538506),
250
+ (453.893145, 10397.019260),
251
+ ]
252
+
253
+ wnd = [(-0.5, -0.5), (5224.5, -0.5), (5224.5, 15999.5), (-0.5, 15999.5)]
254
+
255
+ cp_ref = [
256
+ (4517.377385, 8863.424319),
257
+ (5224.5, 10838.812526396974),
258
+ (5224.5, 13233.64580022457),
259
+ (1917.908619, 14391.538506),
260
+ (453.893145, 10397.01926),
261
+ ]
262
+
263
+ cp = clip_polygon(p, wnd)
264
+
265
+ assert _is_poly_eq(cp, cp_ref)
266
+
267
+
268
+ def test_intersection_case02():
269
+ # a real case of failure reported in #189
270
+ p = [
271
+ (-0.04000000000000009104, 1.5),
272
+ (2.73499999999999943157, 1.5),
273
+ (1.83500000000000018652, -0.5),
274
+ (-0.03999999999999998002, -0.5),
275
+ ]
276
+ wnd = [(-0.5, -0.5), (3.5, -0.5), (3.5, 3.5), (-0.5, 3.5)]
277
+
278
+ cp_ref = [
279
+ (-0.04, 1.5),
280
+ (-0.04, -0.5),
281
+ (1.835, -0.5),
282
+ (2.735, 1.5),
283
+ ]
284
+
285
+ cp = clip_polygon(p, wnd)
286
+
287
+ assert _is_poly_eq(cp, cp_ref)