drizzle 2.0.1__cp312-cp312-macosx_10_13_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,1100 @@
1
+ import math
2
+ import os
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from astropy import wcs
8
+ from drizzle import cdrizzle, resample, utils
9
+
10
+ from .helpers import wcs_from_file
11
+
12
+ TEST_DIR = os.path.abspath(os.path.dirname(__file__))
13
+ DATA_DIR = os.path.join(TEST_DIR, 'data')
14
+
15
+
16
+ def bound_image(image):
17
+ """
18
+ Compute region where image is non-zero
19
+ """
20
+ coords = np.nonzero(image)
21
+ ymin = coords[0].min()
22
+ ymax = coords[0].max()
23
+ xmin = coords[1].min()
24
+ xmax = coords[1].max()
25
+ return (ymin, ymax, xmin, xmax)
26
+
27
+
28
+ def centroid(image, size, center):
29
+ """
30
+ Compute the centroid of a rectangular area
31
+ """
32
+ ylo = int(center[0] - size / 2)
33
+ yhi = min(ylo + size, image.shape[0])
34
+ xlo = int(center[1] - size / 2)
35
+ xhi = min(xlo + size, image.shape[1])
36
+
37
+ yx1 = np.mgrid[ylo:yhi, xlo:xhi, 1:2]
38
+ center = (yx1[..., 0] * image[ylo:yhi, xlo:xhi]).sum(
39
+ axis=(1, 2),
40
+ dtype=np.float64,
41
+ )
42
+
43
+ if center[2] == 0.0:
44
+ return None
45
+
46
+ center[0] /= center[2]
47
+ center[1] /= center[2]
48
+ return center
49
+
50
+
51
+ def centroid_close(list_of_centroids, size, point):
52
+ """
53
+ Find if any centroid is close to a point
54
+ """
55
+ for i in range(len(list_of_centroids) - 1, -1, -1):
56
+ if (abs(list_of_centroids[i][0] - point[0]) < int(size / 2) and
57
+ abs(list_of_centroids[i][1] - point[1]) < int(size / 2)):
58
+ return 1
59
+
60
+ return 0
61
+
62
+
63
+ def centroid_compare(centroid):
64
+ return centroid[1]
65
+
66
+
67
+ def centroid_distances(image1, image2, amp, size):
68
+ """
69
+ Compute a list of centroids and the distances between them in two images
70
+ """
71
+ distances = []
72
+ list_of_centroids = centroid_list(image2, amp, size)
73
+ for center2 in list_of_centroids:
74
+ center1 = centroid(image1, size, center2)
75
+ if center1 is None:
76
+ continue
77
+
78
+ disty = center2[0] - center1[0]
79
+ distx = center2[1] - center1[1]
80
+ dist = math.sqrt(disty * disty + distx * distx)
81
+ dflux = abs(center2[2] - center1[2])
82
+ distances.append([dist, dflux, center1, center2])
83
+
84
+ distances.sort(key=centroid_compare)
85
+ return distances
86
+
87
+
88
+ def centroid_list(image, amp, size):
89
+ """
90
+ Find the next centroid
91
+ """
92
+ list_of_centroids = []
93
+ points = np.transpose(np.nonzero(image > amp))
94
+ for point in points:
95
+ if not centroid_close(list_of_centroids, size, point):
96
+ center = centroid(image, size, point)
97
+ list_of_centroids.append(center)
98
+
99
+ return list_of_centroids
100
+
101
+
102
+ def centroid_statistics(title, fname, image1, image2, amp, size):
103
+ """
104
+ write centroid statistics to compare differences btw two images
105
+ """
106
+ stats = ("minimum", "median", "maximum")
107
+ images = (None, None, image1, image2)
108
+ im_type = ("", "", "test", "reference")
109
+
110
+ diff = []
111
+ distances = centroid_distances(image1, image2, amp, size)
112
+ indexes = (0, int(len(distances) / 2), len(distances) - 1)
113
+ fd = open(fname, 'w')
114
+ fd.write(f"*** {title:s} ***\n")
115
+
116
+ if len(distances) == 0:
117
+ diff = [0.0, 0.0, 0.0]
118
+ fd.write("No matches!!\n")
119
+
120
+ elif len(distances) == 1:
121
+ diff = [distances[0][0], distances[0][0], distances[0][0]]
122
+
123
+ fd.write("1 match\n")
124
+ fd.write(
125
+ f"distance = {distances[0][0]:f} "
126
+ f"flux difference = {distances[0][1]:f}\n"
127
+ )
128
+
129
+ for j in range(2, 4):
130
+ ylo = int(distances[0][j][0]) - 1
131
+ yhi = int(distances[0][j][0]) + 2
132
+ xlo = int(distances[0][j][1]) - 1
133
+ xhi = int(distances[0][j][1]) + 2
134
+ subimage = images[j][ylo:yhi, xlo:xhi]
135
+ fd.write(
136
+ f"\n{im_type[j]} image centroid = "
137
+ f"({distances[0][j][0]:f}, {distances[0][j][1]:f}) "
138
+ f"image flux = {distances[0][j][2]:f}\n"
139
+ )
140
+ fd.write(str(subimage) + "\n")
141
+
142
+ else:
143
+ fd.write(f"{len(distances)} matches\n")
144
+
145
+ for k in range(3):
146
+ i = indexes[k]
147
+ diff.append(distances[i][0])
148
+ fd.write(
149
+ f"\n{stats[k]} distance = {distances[i][0]:f} "
150
+ f"flux difference = {distances[i][1]:f}\n"
151
+ )
152
+
153
+ for j in range(2, 4):
154
+ ylo = int(distances[i][j][0]) - 1
155
+ yhi = int(distances[i][j][0]) + 2
156
+ xlo = int(distances[i][j][1]) - 1
157
+ xhi = int(distances[i][j][1]) + 2
158
+ subimage = images[j][ylo:yhi, xlo:xhi]
159
+ fd.write(
160
+ f"\n{stats[k]} {im_type[j]} image centroid = "
161
+ f"({distances[i][j][0]:f}, {distances[i][j][1]:f}) "
162
+ f"image flux = {distances[i][j][2]:f}\n"
163
+ )
164
+ fd.write(str(subimage) + "\n")
165
+
166
+ fd.close()
167
+ return tuple(diff)
168
+
169
+
170
+ def make_point_image(shape, point, value):
171
+ """
172
+ Create an image with a single point set
173
+ """
174
+ output_image = np.zeros(shape, dtype=np.float32)
175
+ output_image[point] = value
176
+ return output_image
177
+
178
+
179
+ def make_grid_image(shape, spacing, value):
180
+ """
181
+ Create an image with points on a grid set
182
+ """
183
+ output_image = np.zeros(shape, dtype=np.float32)
184
+
185
+ shape = output_image.shape
186
+ half_space = int(spacing / 2)
187
+ for y in range(half_space, shape[0], spacing):
188
+ for x in range(half_space, shape[1], spacing):
189
+ output_image[y, x] = value
190
+
191
+ return output_image
192
+
193
+
194
+ def test_drizzle_defaults():
195
+ n = 200
196
+ in_shape = (n, n)
197
+
198
+ # input coordinate grid:
199
+ y, x = np.indices(in_shape, dtype=np.float64)
200
+
201
+ # simulate data:
202
+ in_sci = np.ones(in_shape, dtype=np.float32)
203
+ in_wht = np.ones(in_shape, dtype=np.float32)
204
+
205
+ # create a Drizzle object using all default parameters (except for 'kernel')
206
+ driz = resample.Drizzle(
207
+ kernel='square',
208
+ )
209
+
210
+ assert driz.out_img is None
211
+ assert driz.out_wht is None
212
+ assert driz.out_ctx is None
213
+ assert driz.total_exptime == 0.0
214
+
215
+ driz.add_image(
216
+ in_sci,
217
+ exptime=1.0,
218
+ pixmap=np.dstack([x, y]),
219
+ weight_map=in_wht,
220
+ )
221
+
222
+ pixmap = np.dstack([x + 1, y + 2])
223
+ driz.add_image(
224
+ 3 * in_sci,
225
+ exptime=1.0,
226
+ pixmap=pixmap,
227
+ weight_map=in_wht,
228
+ )
229
+
230
+ assert driz.out_img[0, 0] == 1
231
+ assert driz.out_img[1, 0] == 1
232
+ assert driz.out_img[2, 0] == 1
233
+ assert driz.out_img[1, 1] == 1
234
+ assert driz.out_img[1, 2] == 1
235
+ assert (driz.out_img[2, 1] - 2.0) < 1.0e-14
236
+
237
+ @pytest.mark.parametrize(
238
+ 'kernel,test_image_type,max_diff_atol',
239
+ [
240
+ ("square", "point", 1.0e-5),
241
+ ("square", "grid", 1.0e-5),
242
+ ('point', "grid", 1.0e-5),
243
+ ("turbo", "grid", 1.0e-5),
244
+ ('lanczos3', "grid", 1.0e-5),
245
+ ("gaussian", "grid", 2.0e-5),
246
+ ],
247
+ )
248
+ def test_resample_kernel(tmpdir, kernel, test_image_type, max_diff_atol):
249
+ """
250
+ Test do_driz square kernel with point
251
+ """
252
+ output_difference = str(
253
+ tmpdir.join(f"difference_{kernel}_{test_image_type}.txt")
254
+ )
255
+
256
+ inwcs = wcs_from_file("j8bt06nyq_flt.fits", ext=1)
257
+ if test_image_type == "point":
258
+ insci = make_point_image(inwcs.array_shape, (500, 200), 100.0)
259
+ else:
260
+ insci = make_grid_image(inwcs.array_shape, 64, 100.0)
261
+ inwht = np.ones_like(insci)
262
+ output_wcs, template_data = wcs_from_file(
263
+ f"reference_{kernel}_{test_image_type}.fits",
264
+ ext=1,
265
+ return_data=True
266
+ )
267
+
268
+ pixmap = utils.calc_pixmap(
269
+ inwcs,
270
+ output_wcs,
271
+ )
272
+
273
+ if kernel == "point":
274
+ pscale_ratio = 1.0
275
+ else:
276
+ pscale_ratio = utils.estimate_pixel_scale_ratio(
277
+ inwcs,
278
+ output_wcs,
279
+ refpix_from=inwcs.wcs.crpix,
280
+ refpix_to=output_wcs.wcs.crpix,
281
+ )
282
+
283
+ # ignore previous pscale and compute it the old way (only to make
284
+ # tests work with old truth files and thus to show that new API gives
285
+ # same results when equal definitions of the pixel scale is used):
286
+ pscale_ratio = np.sqrt(
287
+ np.sum(output_wcs.wcs.pc**2, axis=0)[0] /
288
+ np.sum(inwcs.wcs.cd**2, axis=0)[0]
289
+ )
290
+
291
+ driz = resample.Drizzle(
292
+ kernel=kernel,
293
+ out_shape=output_wcs.array_shape,
294
+ fillval=0.0,
295
+ )
296
+
297
+ if kernel in ["square", "turbo", "point"]:
298
+ driz.add_image(
299
+ insci,
300
+ exptime=1.0,
301
+ pixmap=pixmap,
302
+ weight_map=inwht,
303
+ scale=pscale_ratio,
304
+ )
305
+ else:
306
+ with pytest.warns(Warning):
307
+ driz.add_image(
308
+ insci,
309
+ exptime=1.0,
310
+ pixmap=pixmap,
311
+ weight_map=inwht,
312
+ scale=pscale_ratio,
313
+ )
314
+
315
+ _, med_diff, max_diff = centroid_statistics(
316
+ f"{kernel} with {test_image_type}",
317
+ output_difference,
318
+ driz.out_img,
319
+ template_data,
320
+ 20.0,
321
+ 8,
322
+ )
323
+
324
+ assert med_diff < 1.0e-6
325
+ assert max_diff < max_diff_atol
326
+
327
+
328
+ @pytest.mark.parametrize(
329
+ 'kernel,max_diff_atol',
330
+ [
331
+ ("square", 1.0e-5),
332
+ ("turbo", 1.0e-5),
333
+ ],
334
+ )
335
+ def test_resample_kernel_image(tmpdir, kernel, max_diff_atol):
336
+ """
337
+ Test do_driz square kernel with point
338
+ """
339
+ inwcs, insci = wcs_from_file(
340
+ "j8bt06nyq_flt.fits",
341
+ ext=1,
342
+ return_data=True
343
+ )
344
+ inwht = np.ones_like(insci)
345
+
346
+ outwcs, ref_sci, ref_ctx, ref_wht = wcs_from_file(
347
+ f"reference_{kernel}_image.fits",
348
+ ext=1,
349
+ return_data=["SCI", "CTX", "WHT"]
350
+ )
351
+ ref_ctx = np.array(ref_ctx, dtype=np.int32)
352
+
353
+ pixmap = utils.calc_pixmap(
354
+ inwcs,
355
+ outwcs,
356
+ )
357
+
358
+ pscale_ratio = np.sqrt(
359
+ np.sum(outwcs.wcs.cd**2, axis=0)[0] /
360
+ np.sum(inwcs.wcs.cd**2, axis=0)[0]
361
+ )
362
+
363
+ driz = resample.Drizzle(
364
+ kernel=kernel,
365
+ out_shape=ref_sci.shape,
366
+ fillval=0.0,
367
+ )
368
+
369
+ driz.add_image(
370
+ insci,
371
+ exptime=1.0,
372
+ pixmap=pixmap,
373
+ weight_map=inwht,
374
+ scale=pscale_ratio,
375
+ )
376
+ outctx = driz.out_ctx[0]
377
+
378
+ # in order to avoid small differences in the staircase in the outline
379
+ # of the input image in the output grid, select a subset:
380
+ sl = np.s_[125: -125, 5: -5]
381
+
382
+ assert np.allclose(driz.out_img[sl], ref_sci[sl], atol=0, rtol=1.0e-6)
383
+ assert np.allclose(driz.out_wht[sl], ref_wht[sl], atol=0, rtol=1.0e-6)
384
+ assert np.all(outctx[sl] == ref_ctx[sl])
385
+
386
+
387
+ @pytest.mark.parametrize(
388
+ 'kernel,fc',
389
+ [
390
+ ('square', True),
391
+ ('point', True),
392
+ ('turbo', True),
393
+ ('lanczos2', False),
394
+ ('lanczos3', False),
395
+ ('gaussian', False),
396
+ ],
397
+ )
398
+ def test_zero_input_weight(kernel, fc):
399
+ """
400
+ Test do_driz square kernel with grid
401
+ """
402
+ # initialize input:
403
+ insci = np.ones((200, 400), dtype=np.float32)
404
+ inwht = np.ones((200, 400), dtype=np.float32)
405
+ inwht[:, 150:155] = 0
406
+
407
+ # initialize output:
408
+ outsci = np.zeros((210, 410), dtype=np.float32)
409
+ outwht = np.zeros((210, 410), dtype=np.float32)
410
+ outctx = np.zeros((210, 410), dtype=np.int32)
411
+
412
+ # define coordinate mapping:
413
+ pixmap = np.moveaxis(np.mgrid[1:201, 1:401][::-1], 0, -1)
414
+
415
+ # resample:
416
+ if fc:
417
+ cdrizzle.tdriz(
418
+ insci,
419
+ inwht,
420
+ pixmap,
421
+ outsci,
422
+ outwht,
423
+ outctx,
424
+ uniqid=1,
425
+ xmin=0,
426
+ xmax=400,
427
+ ymin=0,
428
+ ymax=200,
429
+ pixfrac=1,
430
+ kernel=kernel,
431
+ in_units='cps',
432
+ expscale=1,
433
+ wtscale=1,
434
+ fillstr='INDEF',
435
+ )
436
+ else:
437
+ with pytest.warns(Warning):
438
+ cdrizzle.tdriz(
439
+ insci,
440
+ inwht,
441
+ pixmap,
442
+ outsci,
443
+ outwht,
444
+ outctx,
445
+ uniqid=1,
446
+ xmin=0,
447
+ xmax=400,
448
+ ymin=0,
449
+ ymax=200,
450
+ pixfrac=1,
451
+ kernel=kernel,
452
+ in_units='cps',
453
+ expscale=1,
454
+ wtscale=1,
455
+ fillstr='INDEF',
456
+ )
457
+ # pytest.xfail("Not a flux-conserving kernel")
458
+
459
+ # check that no pixel with 0 weight has any counts:
460
+ assert np.sum(np.abs(outsci[(outwht == 0)])) == 0.0
461
+
462
+
463
+ @pytest.mark.parametrize(
464
+ 'interpolator,test_image_type',
465
+ [
466
+ ("poly5", "point"),
467
+ ("default", "grid"),
468
+ ('lan3', "grid"),
469
+ ("lan5", "grid"),
470
+ ],
471
+ )
472
+ def test_blot_interpolation(tmpdir, interpolator, test_image_type):
473
+ """
474
+ Test do_driz square kernel with point
475
+ """
476
+ output_difference = str(
477
+ tmpdir.join(f"difference_blot_{interpolator}_{test_image_type}.txt")
478
+ )
479
+
480
+ outwcs = wcs_from_file("j8bt06nyq_flt.fits", ext=1)
481
+ if test_image_type == "point":
482
+ outsci = make_point_image(outwcs.array_shape, (500, 200), 40.0)
483
+ ref_fname = "reference_blot_point.fits"
484
+ else:
485
+ outsci = make_grid_image(outwcs.array_shape, 64, 100.0)
486
+ ref_fname = f"reference_blot_{interpolator}.fits"
487
+ inwcs, template_data = wcs_from_file(ref_fname, ext=1, return_data=True)
488
+
489
+ pixmap = utils.calc_pixmap(inwcs, outwcs)
490
+
491
+ # compute pscale the old way (only to make
492
+ # tests work with old truth files and thus to show that new API gives
493
+ # same results when equal definitions of the pixel scale is used):
494
+ pscale_ratio = np.sqrt(
495
+ np.sum(inwcs.wcs.pc**2, axis=0)[0] /
496
+ np.sum(outwcs.wcs.cd**2, axis=0)[0]
497
+ )
498
+
499
+ if interpolator == "default":
500
+ kwargs = {}
501
+ else:
502
+ kwargs = {"interp": interpolator}
503
+
504
+ blotted_image = resample.blot_image(
505
+ outsci,
506
+ pixmap=pixmap,
507
+ pix_ratio=pscale_ratio,
508
+ exptime=1.0,
509
+ output_pixel_shape=inwcs.pixel_shape,
510
+ **kwargs
511
+ )
512
+
513
+ _, med_diff, max_diff = centroid_statistics(
514
+ "blot with '{interpolator}' and '{test_image_type}'",
515
+ output_difference,
516
+ blotted_image,
517
+ template_data,
518
+ 20.0,
519
+ 16,
520
+ )
521
+ assert med_diff < 1.0e-6
522
+ assert max_diff < 1.0e-5
523
+
524
+
525
+ def test_context_planes():
526
+ """Reproduce error seen in issue #50"""
527
+ shape = (10, 10)
528
+ output_wcs = wcs.WCS()
529
+ output_wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
530
+ output_wcs.wcs.pc = [[1, 0], [0, 1]]
531
+ output_wcs.pixel_shape = shape
532
+ driz = resample.Drizzle(out_shape=tuple(shape))
533
+
534
+ image = np.ones(shape)
535
+ inwcs = wcs.WCS()
536
+ inwcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
537
+ inwcs.wcs.cd = [[1, 0], [0, 1]]
538
+ inwcs.pixel_shape = shape
539
+
540
+ pixmap = utils.calc_pixmap(inwcs, output_wcs)
541
+
542
+ # context image must be 2D or 3D:
543
+ with pytest.raises(ValueError) as err_info:
544
+ resample.Drizzle(
545
+ kernel='point',
546
+ exptime=0.0,
547
+ out_shape=shape,
548
+ out_ctx=[0, 0, 0],
549
+ )
550
+ assert str(err_info.value).startswith(
551
+ "'out_ctx' must be either a 2D or 3D array."
552
+ )
553
+
554
+ driz = resample.Drizzle(
555
+ kernel='square',
556
+ out_shape=output_wcs.array_shape,
557
+ fillval=0.0,
558
+ )
559
+
560
+ for i in range(32):
561
+ assert driz.ctx_id == i
562
+ driz.add_image(image, exptime=1.0, pixmap=pixmap)
563
+ assert driz.out_ctx.shape == (1, 10, 10)
564
+
565
+ driz.add_image(image, exptime=1.0, pixmap=pixmap)
566
+ assert driz.out_ctx.shape == (2, 10, 10)
567
+
568
+
569
+ def test_no_context_image():
570
+ """Reproduce error seen in issue #50"""
571
+ shape = (10, 10)
572
+ output_wcs = wcs.WCS()
573
+ output_wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
574
+ output_wcs.wcs.pc = [[1, 0], [0, 1]]
575
+ output_wcs.pixel_shape = shape
576
+ driz = resample.Drizzle(
577
+ out_shape=tuple(shape),
578
+ begin_ctx_id=-1,
579
+ disable_ctx=True
580
+ )
581
+ assert driz.out_ctx is None
582
+ assert driz.ctx_id is None
583
+
584
+ image = np.ones(shape)
585
+ inwcs = wcs.WCS()
586
+ inwcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
587
+ inwcs.wcs.cd = [[1, 0], [0, 1]]
588
+ inwcs.pixel_shape = shape
589
+
590
+ pixmap = utils.calc_pixmap(inwcs, output_wcs)
591
+
592
+ for i in range(33):
593
+ driz.add_image(image, exptime=1.0, pixmap=pixmap)
594
+ assert driz.out_ctx is None
595
+ assert driz.ctx_id is None
596
+
597
+
598
+ def test_init_ctx_id():
599
+ # starting context ID must be positive
600
+ with pytest.raises(ValueError) as err_info:
601
+ resample.Drizzle(
602
+ kernel='square',
603
+ exptime=0.0,
604
+ begin_ctx_id=-1,
605
+ out_shape=(10, 10),
606
+ )
607
+ assert str(err_info.value).startswith(
608
+ "Invalid context image ID"
609
+ )
610
+
611
+ with pytest.raises(ValueError) as err_info:
612
+ resample.Drizzle(
613
+ kernel='square',
614
+ exptime=0.0,
615
+ out_shape=(10, 10),
616
+ begin_ctx_id=1,
617
+ max_ctx_id=0,
618
+ )
619
+ assert str(err_info.value).startswith(
620
+ "'max_ctx_id' cannot be smaller than 'begin_ctx_id'."
621
+ )
622
+
623
+
624
+ def test_context_agrees_with_weight():
625
+ n = 200
626
+ out_shape = (n, n)
627
+
628
+ # allocate output arrays:
629
+ out_img = np.zeros(out_shape, dtype=np.float32)
630
+ out_ctx = np.zeros(out_shape, dtype=np.int32)
631
+ out_wht = np.zeros(out_shape, dtype=np.float32)
632
+
633
+ # previous data in weight and context must agree:
634
+ with pytest.raises(ValueError) as err_info:
635
+ out_ctx[0, 0] = 1
636
+ out_ctx[0, 1] = 1
637
+ out_wht[0, 0] = 0.1
638
+ resample.Drizzle(
639
+ kernel='square',
640
+ out_shape=out_shape,
641
+ out_img=out_img,
642
+ out_ctx=out_ctx,
643
+ out_wht=out_wht,
644
+ exptime=1.0,
645
+ )
646
+ assert str(err_info.value).startswith(
647
+ "Inconsistent values of supplied 'out_wht' and 'out_ctx' "
648
+ )
649
+
650
+
651
+ @pytest.mark.parametrize(
652
+ 'kernel,fc',
653
+ [
654
+ ('square', True),
655
+ ('point', True),
656
+ ('turbo', True),
657
+ ('lanczos2', False),
658
+ ('lanczos3', False),
659
+ ('gaussian', False),
660
+ ],
661
+ )
662
+ def test_flux_conservation_nondistorted(kernel, fc):
663
+ n = 200
664
+ in_shape = (n, n)
665
+
666
+ # input coordinate grid:
667
+ y, x = np.indices(in_shape, dtype=np.float64)
668
+
669
+ # simulate a gaussian "star":
670
+ fwhm = 2.9
671
+ x0 = 50.0
672
+ y0 = 68.0
673
+ sig = fwhm / (2.0 * np.sqrt(2.0 * np.log(2.0 * fwhm)))
674
+ sig2 = sig * sig
675
+ star = np.exp(-0.5 / sig2 * ((x.astype(np.float32) - x0)**2 + (y.astype(np.float32) - y0)**2))
676
+ in_sci = (star / np.sum(star)).astype(np.float32) # normalize to 1
677
+ in_wht = np.ones(in_shape, dtype=np.float32)
678
+
679
+ # linear shift:
680
+ xp = x + 0.5
681
+ yp = y + 0.2
682
+
683
+ pixmap = np.dstack([xp, yp])
684
+
685
+ out_shape = (int(yp.max()) + 1, int(xp.max()) + 1)
686
+ # make sure distorion is not moving flux out of the image towards negative
687
+ # coordinates (just because of the simple way of how we account for output
688
+ # image size)
689
+ assert np.min(xp) > -0.5 and np.min(yp) > -0.5
690
+
691
+ out_img = np.zeros(out_shape, dtype=np.float32)
692
+ out_ctx = np.zeros(out_shape, dtype=np.int32)
693
+ out_wht = np.zeros(out_shape, dtype=np.float32)
694
+
695
+ if fc:
696
+ cdrizzle.tdriz(
697
+ in_sci,
698
+ in_wht,
699
+ pixmap,
700
+ out_img,
701
+ out_wht,
702
+ out_ctx,
703
+ pixfrac=1.0,
704
+ scale=1.0,
705
+ kernel=kernel,
706
+ in_units="cps",
707
+ expscale=1.0,
708
+ wtscale=1.0,
709
+ )
710
+ else:
711
+ with pytest.warns(Warning):
712
+ cdrizzle.tdriz(
713
+ in_sci,
714
+ in_wht,
715
+ pixmap,
716
+ out_img,
717
+ out_wht,
718
+ out_ctx,
719
+ pixfrac=1.0,
720
+ scale=1.0,
721
+ kernel=kernel,
722
+ in_units="cps",
723
+ expscale=1.0,
724
+ wtscale=1.0,
725
+ )
726
+ pytest.xfail("Not a flux-conserving kernel")
727
+
728
+ assert np.allclose(
729
+ np.sum(out_img * out_wht),
730
+ np.sum(in_sci),
731
+ atol=0.0,
732
+ rtol=0.0001,
733
+ )
734
+
735
+
736
+ @pytest.mark.parametrize(
737
+ 'kernel,fc',
738
+ [
739
+ ('square', True),
740
+ ('point', True),
741
+ ('turbo', True),
742
+ ('lanczos2', False),
743
+ ('lanczos3', False),
744
+ ('gaussian', False),
745
+ ],
746
+ )
747
+ def test_flux_conservation_distorted(kernel, fc):
748
+ n = 200
749
+ in_shape = (n, n)
750
+
751
+ # input coordinate grid:
752
+ y, x = np.indices(in_shape, dtype=np.float64)
753
+
754
+ # simulate a gaussian "star":
755
+ fwhm = 2.9
756
+ x0 = 50.0
757
+ y0 = 68.0
758
+ sig = fwhm / (2.0 * np.sqrt(2.0 * np.log(2.0 * fwhm)))
759
+ sig2 = sig * sig
760
+ star = np.exp(-0.5 / sig2 * ((x.astype(np.float32) - x0)**2 + (y.astype(np.float32) - y0)**2))
761
+ in_sci = (star / np.sum(star)).astype(np.float32) # normalize to 1
762
+ in_wht = np.ones(in_shape, dtype=np.float32)
763
+
764
+ # linear shift:
765
+ xp = x + 0.5
766
+ yp = y + 0.2
767
+ # add distortion:
768
+ xp += 1e-4 * x**2 + 1e-5 * x * y
769
+ yp += 1e-3 * y**2 - 2e-5 * x * y
770
+
771
+ pixmap = np.dstack([xp, yp])
772
+
773
+ out_shape = (int(yp.max()) + 1, int(xp.max()) + 1)
774
+ # make sure distorion is not moving (pixels with) flux out of the image
775
+ # towards negative coordinates (just because of the simple way of how we
776
+ # account for output image size):
777
+ assert np.min(xp) > -0.5 and np.min(yp) > -0.5
778
+
779
+ out_img = np.zeros(out_shape, dtype=np.float32)
780
+ out_ctx = np.zeros(out_shape, dtype=np.int32)
781
+ out_wht = np.zeros(out_shape, dtype=np.float32)
782
+
783
+ if fc:
784
+ cdrizzle.tdriz(
785
+ in_sci,
786
+ in_wht,
787
+ pixmap,
788
+ out_img,
789
+ out_wht,
790
+ out_ctx,
791
+ pixfrac=1.0,
792
+ scale=1.0,
793
+ kernel=kernel,
794
+ in_units="cps",
795
+ expscale=1.0,
796
+ wtscale=1.0,
797
+ )
798
+ else:
799
+ with pytest.warns(Warning):
800
+ cdrizzle.tdriz(
801
+ in_sci,
802
+ in_wht,
803
+ pixmap,
804
+ out_img,
805
+ out_wht,
806
+ out_ctx,
807
+ pixfrac=1.0,
808
+ scale=1.0,
809
+ kernel=kernel,
810
+ in_units="cps",
811
+ expscale=1.0,
812
+ wtscale=1.0,
813
+ )
814
+ pytest.xfail("Not a flux-conserving kernel")
815
+
816
+ assert np.allclose(
817
+ np.sum(out_img * out_wht),
818
+ np.sum(in_sci),
819
+ atol=0.0,
820
+ rtol=0.0001,
821
+ )
822
+
823
+
824
+ def test_drizzle_exptime():
825
+ n = 200
826
+ in_shape = (n, n)
827
+
828
+ # input coordinate grid:
829
+ y, x = np.indices(in_shape, dtype=np.float64)
830
+
831
+ # simulate data:
832
+ in_sci = np.ones(in_shape, dtype=np.float32)
833
+ in_wht = np.ones(in_shape, dtype=np.float32)
834
+
835
+ pixmap = np.dstack([x, y])
836
+
837
+ # allocate output arrays:
838
+ out_shape = (int(y.max()) + 1, int(x.max()) + 1)
839
+ out_img = np.zeros(out_shape, dtype=np.float32)
840
+ out_ctx = np.zeros(out_shape, dtype=np.int32)
841
+ out_wht = np.zeros(out_shape, dtype=np.float32)
842
+
843
+ # starting exposure time must be non-negative:
844
+ with pytest.raises(ValueError) as err_info:
845
+ driz = resample.Drizzle(
846
+ kernel='square',
847
+ out_shape=out_shape,
848
+ fillval="indef",
849
+ exptime=-1.0,
850
+ )
851
+ assert str(err_info.value) == "Exposure time must be non-negative."
852
+
853
+ driz = resample.Drizzle(
854
+ kernel='turbo',
855
+ out_shape=out_shape,
856
+ fillval="",
857
+ out_img=out_img,
858
+ out_ctx=out_ctx,
859
+ out_wht=out_wht,
860
+ exptime=1.0,
861
+ )
862
+ assert driz.kernel == 'turbo'
863
+
864
+ driz.add_image(in_sci, weight_map=in_wht, exptime=1.03456, pixmap=pixmap)
865
+ assert np.allclose(driz.total_exptime, 2.03456, rtol=0, atol=1.0e-14)
866
+
867
+ driz.add_image(in_sci, weight_map=in_wht, exptime=3.1415926, pixmap=pixmap)
868
+ assert np.allclose(driz.total_exptime, 5.1761526, rtol=0, atol=1.0e-14)
869
+
870
+ with pytest.raises(ValueError) as err_info:
871
+ driz.add_image(in_sci, weight_map=in_wht, exptime=-1, pixmap=pixmap)
872
+ assert str(err_info.value) == "'exptime' *must* be a strictly positive number."
873
+
874
+ # exptime cannot be 0 when output data has data:
875
+ with pytest.raises(ValueError) as err_info:
876
+ out_ctx[0, 0] = 1
877
+ driz = resample.Drizzle(
878
+ kernel='square',
879
+ out_shape=out_shape,
880
+ fillval="indef",
881
+ out_img=out_img,
882
+ out_ctx=out_ctx,
883
+ out_wht=out_wht,
884
+ exptime=0.0,
885
+ )
886
+ assert str(err_info.value).startswith(
887
+ "Inconsistent exposure time and context and/or weight images:"
888
+ )
889
+
890
+ # exptime must be 0 when output arrays are not provided:
891
+ with pytest.raises(ValueError) as err_info:
892
+ driz = resample.Drizzle(
893
+ kernel='square',
894
+ out_shape=out_shape,
895
+ exptime=1.0,
896
+ )
897
+ assert str(err_info.value).startswith(
898
+ "Exposure time must be 0.0 for the first resampling"
899
+ )
900
+
901
+
902
+ def test_drizzle_unsupported_kernel():
903
+ with pytest.raises(ValueError) as err_info:
904
+ resample.Drizzle(
905
+ kernel='magic_image_improver',
906
+ out_shape=(10, 10),
907
+ exptime=0.0,
908
+ )
909
+ assert str(err_info.value) == "Kernel 'magic_image_improver' is not supported."
910
+
911
+
912
+ def test_pixmap_shape_matches_image():
913
+ n = 200
914
+ in_shape = (n, n)
915
+
916
+ # input coordinate grid:
917
+ y, x = np.indices((n + 1, n), dtype=np.float64)
918
+
919
+ # simulate data:
920
+ in_sci = np.ones(in_shape, dtype=np.float32)
921
+ in_wht = np.ones(in_shape, dtype=np.float32)
922
+
923
+ pixmap = np.dstack([x, y])
924
+
925
+ driz = resample.Drizzle(
926
+ kernel='square',
927
+ fillval=0.0,
928
+ exptime=0.0,
929
+ )
930
+
931
+ # last two sizes of the pixelmap must match those of input images:
932
+ with pytest.raises(ValueError) as err_info:
933
+ driz.add_image(
934
+ in_sci,
935
+ exptime=1.0,
936
+ pixmap=pixmap,
937
+ weight_map=in_wht,
938
+ )
939
+ assert str(err_info.value) == "'pixmap' shape is not consistent with 'data' shape."
940
+
941
+
942
+ def test_drizzle_fillval():
943
+ n = 200
944
+ in_shape = (n, n)
945
+
946
+ # input coordinate grid:
947
+ y, x = np.indices(in_shape, dtype=np.float64)
948
+
949
+ # simulate a gaussian "star":
950
+ fwhm = 2.9
951
+ x0 = 50.0
952
+ y0 = 68.0
953
+ sig = fwhm / (2.0 * np.sqrt(2.0 * np.log(2.0 * fwhm)))
954
+ sig2 = sig * sig
955
+ star = np.exp(-0.5 / sig2 * ((x.astype(np.float32) - x0)**2 + (y.astype(np.float32) - y0)**2))
956
+ in_sci = (star / np.sum(star)).astype(np.float32) # normalize to 1
957
+ in_wht = np.zeros(in_shape, dtype=np.float32)
958
+ mask = np.where((x.astype(np.float32) - x0)**2 + (y.astype(np.float32) - y0)**2 <= 10)
959
+ in_wht[mask] = 1.0
960
+
961
+ # linear shift:
962
+ xp = x + 50
963
+ yp = y + 50
964
+
965
+ pixmap = np.dstack([xp, yp])
966
+
967
+ out_shape = (int(yp.max()) + 1, int(xp.max()) + 1)
968
+ # make sure distorion is not moving flux out of the image towards negative
969
+ # coordinates (just because of the simple way of how we account for output
970
+ # image size)
971
+ assert np.min(xp) > -0.5 and np.min(yp) > -0.5
972
+
973
+ out_img = np.zeros(out_shape, dtype=np.float32) - 1.11
974
+ out_ctx = np.zeros((1, ) + out_shape, dtype=np.int32)
975
+ out_wht = np.zeros(out_shape, dtype=np.float32)
976
+
977
+ driz = resample.Drizzle(
978
+ kernel='square',
979
+ out_shape=out_shape,
980
+ fillval="indef",
981
+ exptime=0.0,
982
+ )
983
+
984
+ driz.add_image(in_sci, weight_map=in_wht, exptime=1.0, pixmap=pixmap)
985
+ assert np.isnan(driz.out_img[0, 0])
986
+ assert driz.out_img[int(y0) + 50, int(x0) + 50] > 0.0
987
+
988
+ driz = resample.Drizzle(
989
+ kernel='square',
990
+ out_shape=out_shape,
991
+ fillval="-1.11",
992
+ out_img=out_img.copy(),
993
+ out_ctx=out_ctx.copy(),
994
+ out_wht=out_wht.copy(),
995
+ exptime=0.0,
996
+ )
997
+ driz.add_image(in_sci, weight_map=in_wht, exptime=1.0, pixmap=pixmap)
998
+ assert np.allclose(driz.out_img[0, 0], -1.11, rtol=0.0, atol=1.0e-7)
999
+ assert driz.out_img[int(y0) + 50, int(x0) + 50] > 0.0
1000
+ assert set(driz.out_ctx.ravel().tolist()) == {0, 1}
1001
+
1002
+ # test same with numeric fillval:
1003
+ driz = resample.Drizzle(
1004
+ kernel='square',
1005
+ out_shape=out_shape,
1006
+ fillval=-1.11,
1007
+ out_img=out_img.copy(),
1008
+ out_ctx=out_ctx.copy(),
1009
+ out_wht=out_wht.copy(),
1010
+ exptime=0.0,
1011
+ )
1012
+ driz.add_image(in_sci, weight_map=in_wht, exptime=1.0, pixmap=pixmap)
1013
+ assert np.allclose(driz.out_img[0, 0], -1.11, rtol=0.0, atol=1.0e-7)
1014
+ assert np.allclose(float(driz.fillval), -1.11, rtol=0.0, atol=np.finfo(float).eps)
1015
+
1016
+ # make sure code raises exception for unsuported fillval:
1017
+ with pytest.raises(ValueError) as err_info:
1018
+ resample.Drizzle(
1019
+ kernel='square',
1020
+ out_shape=out_shape,
1021
+ fillval="fillval",
1022
+ exptime=0.0,
1023
+ )
1024
+ assert str(err_info.value) == "could not convert string to float: 'fillval'"
1025
+
1026
+
1027
+ def test_resample_get_shape_from_pixmap():
1028
+ n = 200
1029
+ in_shape = (n, n)
1030
+
1031
+ # input coordinate grid:
1032
+ y, x = np.indices(in_shape, dtype=np.float64)
1033
+
1034
+ # simulate constant data:
1035
+ in_sci = np.ones(in_shape, dtype=np.float32)
1036
+ in_wht = np.ones(in_shape, dtype=np.float32)
1037
+
1038
+ pixmap = np.dstack([x, y])
1039
+
1040
+ driz = resample.Drizzle(
1041
+ kernel='point',
1042
+ exptime=0.0,
1043
+ )
1044
+
1045
+ driz.add_image(in_sci, weight_map=in_wht, exptime=1.0, pixmap=pixmap)
1046
+ assert driz.out_img.shape == in_shape
1047
+
1048
+
1049
+ def test_resample_counts_units():
1050
+ n = 200
1051
+ in_shape = (n, n)
1052
+
1053
+ # input coordinate grid:
1054
+ y, x = np.indices(in_shape, dtype=np.float64)
1055
+ pixmap = np.dstack([x, y])
1056
+
1057
+ # simulate constant data:
1058
+ in_sci = np.ones(in_shape, dtype=np.float32)
1059
+ in_wht = np.ones(in_shape, dtype=np.float32)
1060
+
1061
+ driz = resample.Drizzle()
1062
+ driz.add_image(in_sci, weight_map=in_wht, exptime=1.0, pixmap=pixmap, in_units='cps')
1063
+ cps_max_val = driz.out_img.max()
1064
+
1065
+ driz = resample.Drizzle()
1066
+ driz.add_image(in_sci, weight_map=in_wht, exptime=2.0, pixmap=pixmap, in_units='counts')
1067
+ counts_max_val = driz.out_img.max()
1068
+
1069
+ assert abs(counts_max_val - cps_max_val / 2.0) < 1.0e-14
1070
+
1071
+
1072
+ def test_resample_inconsistent_output():
1073
+ n = 200
1074
+ out_shape = (n, n)
1075
+
1076
+ # different shapes:
1077
+ out_img = np.zeros((n, n), dtype=np.float32)
1078
+ out_ctx = np.zeros((1, n, n + 1), dtype=np.int32)
1079
+ out_wht = np.zeros((n + 1, n + 1), dtype=np.float32)
1080
+
1081
+ # shape from out_img:
1082
+ driz = resample.Drizzle(
1083
+ kernel='point',
1084
+ exptime=0.0,
1085
+ out_img=out_img,
1086
+ )
1087
+ assert driz.out_img.shape == out_shape
1088
+
1089
+ # inconsistent shapes:
1090
+ out_shape = (n + 1, n)
1091
+ with pytest.raises(ValueError) as err_info:
1092
+ resample.Drizzle(
1093
+ kernel='point',
1094
+ exptime=0.0,
1095
+ out_shape=out_shape,
1096
+ out_img=out_img,
1097
+ out_ctx=out_ctx,
1098
+ out_wht=out_wht,
1099
+ )
1100
+ assert str(err_info.value).startswith("Inconsistent data shapes specified")