drizzle 1.15.3__cp310-cp310-macosx_11_0_arm64.whl → 2.0.0__cp310-cp310-macosx_11_0_arm64.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.

drizzle/resample.py ADDED
@@ -0,0 +1,702 @@
1
+ """
2
+ The `drizzle` module defines the `Drizzle` class, for combining input
3
+ images into a single output image using the drizzle algorithm.
4
+ """
5
+ import numpy as np
6
+
7
+ from drizzle import cdrizzle
8
+
9
+ __all__ = ["blot_image", "Drizzle"]
10
+
11
+ SUPPORTED_DRIZZLE_KERNELS = [
12
+ "square",
13
+ "gaussian",
14
+ "point",
15
+ "turbo",
16
+ "lanczos2",
17
+ "lanczos3",
18
+ ]
19
+
20
+ CTX_PLANE_BITS = 32
21
+
22
+
23
+ class Drizzle:
24
+ """
25
+ A class for managing resampling and co-adding of multiple images onto a
26
+ common output grid. The main method of this class is :py:meth:`add_image`.
27
+ The main functionality of this class is to resample and co-add multiple
28
+ images onto one output image using the "drizzle" algorithm described in
29
+ `Fruchter and Hook, PASP 2002 <https://doi.org/10.1086/338393>`_.
30
+ In the simplest terms, it redistributes flux
31
+ from input pixels to one or more output pixels based on the chosen kernel,
32
+ supplied weights, and input-to-output coordinate transformations as defined
33
+ by the ``pixmap`` argument. For more details, see :ref:`main-user-doc`.
34
+
35
+ This class keeps track of the total exposure time of all co-added images
36
+ and also of which input images have contributed to an output (resampled)
37
+ pixel. This is accomplished via *context image*.
38
+
39
+ Main outputs of :py:meth:`add_image` can be accessed as class properties
40
+ ``out_img``, ``out_wht``, ``out_ctx``, and ``exptime``.
41
+
42
+ .. warning::
43
+ Output arrays (``out_img``, ``out_wht``, and ``out_ctx``) can be
44
+ pre-allocated by the caller and be passed to the initializer or the
45
+ class initializer can allocate these arrays based on other input
46
+ parameters such as ``output_shape``. If caller-supplied output arrays
47
+ have the correct type (`numpy.float32` for ``out_img`` and ``out_wht``
48
+ and `numpy.int32` for the ``out_ctx`` array) and if ``out_ctx`` is
49
+ large enough not to need to be resized, these arrays will be used as is
50
+ and may be modified by the :py:meth:`add_image` method. If not,
51
+ a copy of these arrays will be made when converting to the expected
52
+ type (or expanding the context array).
53
+
54
+ Output Science Image
55
+ --------------------
56
+
57
+ Output science image is obtained by adding input pixel fluxes according to
58
+ equations (4) and (5) in
59
+ `Fruchter and Hook, PASP 2002 <https://doi.org/10.1086/338393>`_.
60
+ The weights and coefficients in those equations will depend on the chosen
61
+ kernel, input image weights, and pixel overlaps computed from ``pixmap``.
62
+
63
+ Output Weight Image
64
+ -------------------
65
+
66
+ Output weight image stores the total weight of output science pixels
67
+ according to equation (4) in
68
+ `Fruchter and Hook, PASP 2002 <https://doi.org/10.1086/338393>`_.
69
+ It depends on the chosen kernel, input image weights, and pixel overlaps
70
+ computed from ``pixmap``.
71
+
72
+ Output Context Image
73
+ --------------------
74
+
75
+ Each pixel in the context image is a bit field that encodes
76
+ information about which input image has contributed to the corresponding
77
+ pixel in the resampled data array. Context image uses 32 bit integers to
78
+ encode this information and hence it can keep track of only 32 input images.
79
+ First bit corresponds to the first input image, second bit corrsponds to the
80
+ second input image, and so on. We call this (0-indexed) order "context ID"
81
+ which is represented by the ``ctx_id`` parameter/property. If the number of
82
+ input images exceeds 32, then it is necessary to have multiple context
83
+ images ("planes") to hold information about all input images with the first
84
+ plane encoding which of the first 32 images contributed to the output data
85
+ pixel, second plane representing next 32 input images (number 33-64), etc.
86
+ For this reason, context array is either a 2D array (if the total number
87
+ of resampled images is less than 33) of the type `numpy.int32` and shape
88
+ ``(ny, nx)`` or a a 3D array of shape ``(np, ny, nx)`` where ``nx`` and
89
+ ``ny`` are dimensions of image's data. ``np`` is the number of "planes"
90
+ equal to ``(number of input images - 1) // 32 + 1``. If a bit at position
91
+ ``k`` in a pixel with coordinates ``(p, y, x)`` is 0 then input image number
92
+ ``32 * p + k`` (0-indexed) did not contribute to the output data pixel
93
+ with array coordinates ``(y, x)`` and if that bit is 1 then input image
94
+ number ``32 * p + k`` did contribute to the pixel ``(y, x)`` in the
95
+ resampled image.
96
+
97
+ As an example, let's assume we have 8 input images. Then, when ``out_ctx``
98
+ pixel values are displayed using binary representation (and decimal in
99
+ parenthesis), one could see values like this::
100
+
101
+ 00000001 (1) - only first input image contributed to this output pixel;
102
+ 00000010 (2) - 2nd input image contributed;
103
+ 00000100 (4) - 3rd input image contributed;
104
+ 10000000 (128) - 8th input image contributed;
105
+ 10000100 (132=128+4) - 3rd and 8th input images contributed;
106
+ 11001101 (205=1+4+8+64+128) - input images 1, 3, 4, 7, 8 have contributed
107
+ to this output pixel.
108
+
109
+ In order to test if a specific input image contributed to an output pixel,
110
+ one needs to use bitwise operations. Using the example above, to test
111
+ whether input images number 4 and 5 have contributed to the output pixel
112
+ whose corresponding ``out_ctx`` value is 205 (11001101 in binary form) we
113
+ can do the following:
114
+
115
+ >>> bool(205 & (1 << (5 - 1))) # (205 & 16) = 0 (== 0 => False): did NOT contribute
116
+ False
117
+ >>> bool(205 & (1 << (4 - 1))) # (205 & 8) = 8 (!= 0 => True): did contribute
118
+ True
119
+
120
+ In general, to get a list of all input images that have contributed to an
121
+ output resampled pixel with image coordinates ``(x, y)``, and given a
122
+ context array ``ctx``, one can do something like this:
123
+
124
+ .. doctest-skip::
125
+
126
+ >>> import numpy as np
127
+ >>> np.flatnonzero([v & (1 << k) for v in ctx[:, y, x] for k in range(32)])
128
+
129
+ For convenience, this functionality was implemented in the
130
+ :py:func:`~drizzle.utils.decode_context` function.
131
+
132
+ References
133
+ ----------
134
+ A full description of the drizzling algorithm can be found in
135
+ `Fruchter and Hook, PASP 2002 <https://doi.org/10.1086/338393>`_.
136
+
137
+ Examples
138
+ --------
139
+ .. highlight:: python
140
+ .. code-block:: python
141
+
142
+ # wcs1 - WCS of the input image usually with distortions (to be resampled)
143
+ # wcs2 - WCS of the output image without distortions
144
+
145
+ import numpy as np
146
+ from drizzle.resample import Drizzle
147
+ from drizzle.utils import calc_pixmap
148
+
149
+ # simulate some data and a pixel map:
150
+ data = np.ones((240, 570))
151
+ pixmap = calc_pixmap(wcs1, wcs2)
152
+ # or simulate a mapping from input image to output image frame:
153
+ # y, x = np.indices((240, 570), dtype=np.float64)
154
+ # pixmap = np.dstack([x, y])
155
+
156
+ # initialize Drizzle object
157
+ d = Drizzle(out_shape=(240, 570))
158
+ d.add_image(data, exptime=15, pixmap=pixmap)
159
+
160
+ # access outputs:
161
+ d.out_img
162
+ d.out_ctx
163
+ d.out_wht
164
+
165
+ """
166
+
167
+ def __init__(self, kernel="square", fillval=None, out_shape=None,
168
+ out_img=None, out_wht=None, out_ctx=None, exptime=0.0,
169
+ begin_ctx_id=0, max_ctx_id=None, disable_ctx=False):
170
+ """
171
+ kernel: str, optional
172
+ The name of the kernel used to combine the input. The choice of
173
+ kernel controls the distribution of flux over the kernel. The kernel
174
+ names are: "square", "gaussian", "point", "turbo",
175
+ "lanczos2", and "lanczos3". The square kernel is the default.
176
+
177
+ .. warning::
178
+ The "gaussian" and "lanczos2/3" kernels **DO NOT**
179
+ conserve flux.
180
+
181
+ out_shape : tuple, None, optional
182
+ Shape (`numpy` order ``(Ny, Nx)``) of the output images (context
183
+ image will have a third dimension of size proportional to the number
184
+ of input images). This parameter is helpful when neither
185
+ ``out_img``, ``out_wht``, nor ``out_ctx`` images are provided.
186
+
187
+ fillval: float, None, str, optional
188
+ The value of output pixels that did not have contributions from
189
+ input images' pixels. When ``fillval`` is either `None` or
190
+ ``"INDEF"`` and ``out_img`` is provided, the values of ``out_img``
191
+ will not be modified. When ``fillval`` is either `None` or
192
+ ``"INDEF"`` and ``out_img`` is **not provided**, the values of
193
+ ``out_img`` will be initialized to `numpy.nan`. If ``fillval``
194
+ is a string that can be converted to a number, then the output
195
+ pixels with no contributions from input images will be set to this
196
+ ``fillval`` value.
197
+
198
+ out_img : 2D array of float32, None, optional
199
+ A 2D numpy array containing the output image produced by
200
+ drizzling. On the first call the array values should be set to zero.
201
+ Subsequent calls it will hold the intermediate results.
202
+
203
+ out_wht : 2D array of float32, None, optional
204
+ A 2D numpy array containing the output counts. On the first
205
+ call it should be set to zero. On subsequent calls it will
206
+ hold the intermediate results.
207
+
208
+ out_ctx : 2D or 3D array of int32, None, optional
209
+ A 2D or 3D numpy array holding a bitmap of which image was an input
210
+ for each output pixel. Should be integer zero on first call.
211
+ Subsequent calls hold intermediate results. This parameter is
212
+ ignored when ``disable_ctx`` is `True`.
213
+
214
+ exptime : float, optional
215
+ Exposure time of previously resampled images when provided via
216
+ parameters ``out_img``, ``out_wht``, ``out_ctx``.
217
+
218
+ begin_ctx_id : int, optional
219
+ The context ID number (0-based) of the first image that will be
220
+ resampled (using `add_image`). Subsequent images will be asigned
221
+ consecutively increasing ID numbers. This parameter is ignored
222
+ when ``disable_ctx`` is `True`.
223
+
224
+ max_ctx_id : int, None, optional
225
+ The largest integer context ID that is *expected* to be used for
226
+ an input image. When it is a non-negative number and ``out_ctx`` is
227
+ `None`, it allows to pre-allocate the necessary array for the output
228
+ context image. If the actual number of input images that will be
229
+ resampled will exceed initial allocation for the context image,
230
+ additional context planes will be added as needed (context array
231
+ will "grow" in the third dimention as new input images are added.)
232
+ The default value of `None` is equivalent to setting ``max_ctx_id``
233
+ equal to ``begin_ctx_id``. This parameter is ignored either when
234
+ ``out_ctx`` is provided or when ``disable_ctx`` is `True`.
235
+
236
+ disable_ctx : bool, optional
237
+ Indicates to not create a context image. If ``disable_ctx`` is set
238
+ to `True`, parameters ``out_ctx``, ``begin_ctx_id``, and
239
+ ``max_ctx_id`` will be ignored.
240
+
241
+ """
242
+ self._disable_ctx = disable_ctx
243
+
244
+ if disable_ctx:
245
+ self._ctx_id = None
246
+ self._max_ctx_id = None
247
+ else:
248
+ if begin_ctx_id < 0:
249
+ raise ValueError("Invalid context image ID")
250
+ self._ctx_id = begin_ctx_id # the ID of the *last* image to be resampled
251
+ if max_ctx_id is None:
252
+ max_ctx_id = begin_ctx_id
253
+ elif max_ctx_id < begin_ctx_id:
254
+ raise ValueError("'max_ctx_id' cannot be smaller than 'begin_ctx_id'.")
255
+ self._max_ctx_id = max_ctx_id
256
+
257
+ if exptime < 0.0:
258
+ raise ValueError("Exposure time must be non-negative.")
259
+
260
+ if (exptime > 0.0 and out_img is None and out_ctx is None and out_wht is None):
261
+ raise ValueError(
262
+ "Exposure time must be 0.0 for the first resampling "
263
+ "(when no ouput resampled images have been provided)."
264
+ )
265
+
266
+ if (
267
+ exptime == 0.0 and
268
+ (
269
+ (out_ctx is not None and np.sum(out_ctx) > 0) or
270
+ (out_wht is not None and np.sum(out_wht) > 0)
271
+ )
272
+ ):
273
+ raise ValueError(
274
+ "Inconsistent exposure time and context and/or weight images: "
275
+ "Exposure time cannot be 0 when context and/or weight arrays "
276
+ "are non-zero."
277
+ )
278
+
279
+ self._texptime = exptime
280
+
281
+ if kernel.lower() not in SUPPORTED_DRIZZLE_KERNELS:
282
+ raise ValueError(f"Kernel '{kernel}' is not supported.")
283
+ self._kernel = kernel
284
+
285
+ if fillval is None:
286
+ fillval = "INDEF"
287
+
288
+ elif isinstance(fillval, str):
289
+ fillval = fillval.strip()
290
+ if fillval.upper() in ["", "INDEF"]:
291
+ fillval = "INDEF"
292
+ else:
293
+ float(fillval)
294
+ fillval = str(fillval)
295
+
296
+ else:
297
+ fillval = str(fillval)
298
+
299
+ if out_img is None and fillval == "INDEF":
300
+ fillval = "NaN"
301
+
302
+ self._fillval = fillval
303
+
304
+ # shapes will collect user specified 'out_shape' and shapes of
305
+ # out_* arrays (if provided) in order to check all shapes are the same.
306
+ shapes = set()
307
+
308
+ if out_img is not None:
309
+ out_img = np.asarray(out_img, dtype=np.float32)
310
+ shapes.add(out_img.shape)
311
+
312
+ if out_wht is not None:
313
+ out_wht = np.asarray(out_wht, dtype=np.float32)
314
+ shapes.add(out_wht.shape)
315
+
316
+ if out_ctx is not None:
317
+ out_ctx = np.asarray(out_ctx, dtype=np.int32)
318
+ if out_ctx.ndim == 2:
319
+ out_ctx = out_ctx[None, :, :]
320
+ elif out_ctx.ndim != 3:
321
+ raise ValueError("'out_ctx' must be either a 2D or 3D array.")
322
+ shapes.add(out_ctx.shape[1:])
323
+
324
+ if out_shape is not None:
325
+ shapes.add(tuple(out_shape))
326
+
327
+ if len(shapes) == 1:
328
+ self._out_shape = shapes.pop()
329
+ self._alloc_output_arrays(
330
+ out_shape=self._out_shape,
331
+ max_ctx_id=max_ctx_id,
332
+ out_img=out_img,
333
+ out_wht=out_wht,
334
+ out_ctx=out_ctx,
335
+ )
336
+ elif len(shapes) > 1:
337
+ raise ValueError(
338
+ "Inconsistent data shapes specified: 'out_shape' and/or "
339
+ "out_img, out_wht, out_ctx have different shapes."
340
+ )
341
+ else:
342
+ self._out_shape = None
343
+ self._out_img = None
344
+ self._out_wht = None
345
+ self._out_ctx = None
346
+
347
+ @property
348
+ def fillval(self):
349
+ """Fill value for output pixels without contributions from input images."""
350
+ return self._fillval
351
+
352
+ @property
353
+ def kernel(self):
354
+ """Resampling kernel."""
355
+ return self._kernel
356
+
357
+ @property
358
+ def ctx_id(self):
359
+ """Context image "ID" (0-based ) of the next image to be resampled."""
360
+ return self._ctx_id
361
+
362
+ @property
363
+ def out_img(self):
364
+ """Output resampled image."""
365
+ return self._out_img
366
+
367
+ @property
368
+ def out_wht(self):
369
+ """Output weight image."""
370
+ return self._out_wht
371
+
372
+ @property
373
+ def out_ctx(self):
374
+ """Output "context" image."""
375
+ return self._out_ctx
376
+
377
+ @property
378
+ def total_exptime(self):
379
+ """Total exposure time of all resampled images."""
380
+ return self._texptime
381
+
382
+ def _alloc_output_arrays(self, out_shape, max_ctx_id, out_img, out_wht,
383
+ out_ctx):
384
+ # allocate arrays as needed:
385
+ if out_wht is None:
386
+ self._out_wht = np.zeros(out_shape, dtype=np.float32)
387
+ else:
388
+ self._out_wht = out_wht
389
+
390
+ if self._disable_ctx:
391
+ self._out_ctx = None
392
+ else:
393
+ if out_ctx is None:
394
+ n_ctx_planes = max_ctx_id // CTX_PLANE_BITS + 1
395
+ ctx_shape = (n_ctx_planes, ) + out_shape
396
+ self._out_ctx = np.zeros(ctx_shape, dtype=np.int32)
397
+ else:
398
+ self._out_ctx = out_ctx
399
+
400
+ if not (out_wht is None and out_ctx is None):
401
+ # check that input data make sense: weight of pixels with
402
+ # non-zero context values must be different from zero:
403
+ if np.any(
404
+ np.bitwise_xor(
405
+ self._out_wht > 0.0,
406
+ np.sum(self._out_ctx, axis=0) > 0
407
+ )
408
+ ):
409
+ raise ValueError(
410
+ "Inconsistent values of supplied 'out_wht' and "
411
+ "'out_ctx' arrays. Pixels with non-zero context "
412
+ "values must have positive weights and vice-versa."
413
+ )
414
+
415
+ if out_img is None:
416
+ self._out_img = np.zeros(out_shape, dtype=np.float32)
417
+ else:
418
+ self._out_img = out_img
419
+
420
+ def _increment_ctx_id(self):
421
+ """
422
+ Returns a pair of the *current* plane number and bit number in that
423
+ plane and increments context image ID
424
+ (after computing the return value).
425
+ """
426
+ if self._disable_ctx:
427
+ return None, 0
428
+
429
+ self._plane_no = self._ctx_id // CTX_PLANE_BITS
430
+ depth = self._out_ctx.shape[0]
431
+
432
+ if self._plane_no >= depth:
433
+ # Add a new plane to the context image if planeid overflows
434
+ plane = np.zeros((1, ) + self._out_shape, np.int32)
435
+ self._out_ctx = np.append(self._out_ctx, plane, axis=0)
436
+
437
+ plane_info = (self._plane_no, self._ctx_id % CTX_PLANE_BITS)
438
+ # increment ID for the *next* image to be added:
439
+ self._ctx_id += 1
440
+
441
+ return plane_info
442
+
443
+ def add_image(self, data, exptime, pixmap, scale=1.0,
444
+ weight_map=None, wht_scale=1.0, pixfrac=1.0, in_units='cps',
445
+ xmin=None, xmax=None, ymin=None, ymax=None):
446
+ """
447
+ Resample and add an image to the cumulative output image. Also, update
448
+ output total weight image and context images.
449
+
450
+ Parameters
451
+ ----------
452
+ data : 2D numpy.ndarray
453
+ A 2D numpy array containing the input image to be drizzled.
454
+
455
+ exptime : float
456
+ The exposure time of the input image, a positive number. The
457
+ exposure time is used to scale the image if the units are counts.
458
+
459
+ pixmap : 3D array
460
+ A mapping from input image (``data``) coordinates to resampled
461
+ (``out_img``) coordinates. ``pixmap`` must be an array of shape
462
+ ``(Ny, Nx, 2)`` where ``(Ny, Nx)`` is the shape of the input image.
463
+ ``pixmap[..., 0]`` forms a 2D array of X-coordinates of input
464
+ pixels in the ouput frame and ``pixmap[..., 1]`` forms a 2D array of
465
+ Y-coordinates of input pixels in the ouput coordinate frame.
466
+
467
+ scale : float, optional
468
+ The pixel scale of the input image. Conceptually, this is the
469
+ linear dimension of a side of a pixel in the input image, but it
470
+ is not limited to this and can be set to change how the drizzling
471
+ algorithm operates.
472
+
473
+ weight_map : 2D array, None, optional
474
+ A 2D numpy array containing the pixel by pixel weighting.
475
+ Must have the same dimensions as ``data``.
476
+
477
+ When ``weight_map`` is `None`, the weight of input data pixels will
478
+ be assumed to be 1.
479
+
480
+ wht_scale : float
481
+ A scaling factor applied to the pixel by pixel weighting.
482
+
483
+ pixfrac : float, optional
484
+ The fraction of a pixel that the pixel flux is confined to. The
485
+ default value of 1 has the pixel flux evenly spread across the image.
486
+ A value of 0.5 confines it to half a pixel in the linear dimension,
487
+ so the flux is confined to a quarter of the pixel area when the square
488
+ kernel is used.
489
+
490
+ in_units : str
491
+ The units of the input image. The units can either be "counts"
492
+ or "cps" (counts per second.)
493
+
494
+ xmin : float, optional
495
+ This and the following three parameters set a bounding rectangle
496
+ on the input image. Only pixels on the input image inside this
497
+ rectangle will have their flux added to the output image. Xmin
498
+ sets the minimum value of the x dimension. The x dimension is the
499
+ dimension that varies quickest on the image. If the value is zero,
500
+ no minimum will be set in the x dimension. All four parameters are
501
+ zero based, counting starts at zero.
502
+
503
+ xmax : float, optional
504
+ Sets the maximum value of the x dimension on the bounding box
505
+ of the input image. If the value is zero, no maximum will
506
+ be set in the x dimension, the full x dimension of the output
507
+ image is the bounding box.
508
+
509
+ ymin : float, optional
510
+ Sets the minimum value in the y dimension on the bounding box. The
511
+ y dimension varies less rapidly than the x and represents the line
512
+ index on the input image. If the value is zero, no minimum will be
513
+ set in the y dimension.
514
+
515
+ ymax : float, optional
516
+ Sets the maximum value in the y dimension. If the value is zero, no
517
+ maximum will be set in the y dimension, the full x dimension
518
+ of the output image is the bounding box.
519
+
520
+ Returns
521
+ -------
522
+ nskip : float
523
+ The number of lines from the box defined by
524
+ ``((xmin, xmax), (ymin, ymax))`` in the input image that were
525
+ ignored and did not contribute to the output image.
526
+
527
+ nmiss : float
528
+ The number of pixels from the box defined by
529
+ ``((xmin, xmax), (ymin, ymax))`` in the input image that were
530
+ ignored and did not contribute to the output image.
531
+
532
+ """
533
+ # this enables initializer to not need output image shape at all and
534
+ # set output image shape based on output coordinates from the pixmap.
535
+ #
536
+ if self._out_shape is None:
537
+ pmap_xmin = int(np.floor(np.nanmin(pixmap[:, :, 0])))
538
+ pmap_xmax = int(np.ceil(np.nanmax(pixmap[:, :, 0])))
539
+ pmap_ymin = int(np.floor(np.nanmin(pixmap[:, :, 1])))
540
+ pmap_ymax = int(np.ceil(np.nanmax(pixmap[:, :, 1])))
541
+ pixmap = pixmap.copy()
542
+ pixmap[:, :, 0] -= pmap_xmin
543
+ pixmap[:, :, 1] -= pmap_ymin
544
+ self._out_shape = (
545
+ pmap_xmax - pmap_xmin + 1,
546
+ pmap_ymax - pmap_ymin + 1
547
+ )
548
+
549
+ self._alloc_output_arrays(
550
+ out_shape=self._out_shape,
551
+ max_ctx_id=max(self._max_ctx_id, self._ctx_id),
552
+ out_img=None,
553
+ out_wht=None,
554
+ out_ctx=None,
555
+ )
556
+
557
+ plane_no, id_in_plane = self._increment_ctx_id()
558
+
559
+ if exptime <= 0.0:
560
+ raise ValueError("'exptime' *must* be a strictly positive number.")
561
+
562
+ # Ensure that the fillval parameter gets properly interpreted
563
+ # for use with tdriz
564
+ if in_units == 'cps':
565
+ expscale = 1.0
566
+ else:
567
+ expscale = exptime
568
+
569
+ self._texptime += exptime
570
+
571
+ data = np.asarray(data, dtype=np.float32)
572
+ pixmap = np.asarray(pixmap, dtype=np.float64)
573
+ in_ymax, in_xmax = data.shape
574
+
575
+ if pixmap.shape[:2] != data.shape:
576
+ raise ValueError(
577
+ "'pixmap' shape is not consistent with 'data' shape."
578
+ )
579
+
580
+ if xmin is None or xmin < 0:
581
+ xmin = 0
582
+
583
+ if ymin is None or ymin < 0:
584
+ ymin = 0
585
+
586
+ if xmax is None or xmax > in_xmax - 1:
587
+ xmax = in_xmax - 1
588
+
589
+ if ymax is None or ymax > in_ymax - 1:
590
+ ymax = in_ymax - 1
591
+
592
+ if weight_map is not None:
593
+ weight_map = np.asarray(weight_map, dtype=np.float32)
594
+ else: # TODO: this should not be needed after C code modifications
595
+ weight_map = np.ones_like(data)
596
+
597
+ pixmap = np.asarray(pixmap, dtype=np.float64)
598
+
599
+ if self._disable_ctx:
600
+ ctx_plane = None
601
+ else:
602
+ if self._out_ctx.ndim == 2:
603
+ raise AssertionError("Context image is expected to be 3D")
604
+ ctx_plane = self._out_ctx[plane_no]
605
+
606
+ # TODO: probably tdriz should be modified to not return version.
607
+ # we should not have git, Python, C, ... versions
608
+
609
+ # TODO: While drizzle code in cdrizzlebox.c supports weight_map=None,
610
+ # cdrizzleapi.c does not. It should be modified to support this
611
+ # for performance reasons.
612
+
613
+ _vers, nmiss, nskip = cdrizzle.tdriz(
614
+ input=data,
615
+ weights=weight_map,
616
+ pixmap=pixmap,
617
+ output=self._out_img,
618
+ counts=self._out_wht,
619
+ context=ctx_plane,
620
+ uniqid=id_in_plane + 1,
621
+ xmin=xmin,
622
+ xmax=xmax,
623
+ ymin=ymin,
624
+ ymax=ymax,
625
+ scale=scale, # scales image intensity. usually equal to pixel scale
626
+ pixfrac=pixfrac,
627
+ kernel=self._kernel,
628
+ in_units=in_units,
629
+ expscale=expscale,
630
+ wtscale=wht_scale,
631
+ fillstr=self._fillval,
632
+ )
633
+ self._cversion = _vers # TODO: probably not needed
634
+
635
+ return nmiss, nskip
636
+
637
+
638
+ def blot_image(data, pixmap, pix_ratio, exptime, output_pixel_shape,
639
+ interp='poly5', sinscl=1.0):
640
+ """
641
+ Resample the ``data`` input image onto an output grid defined by
642
+ the ``pixmap`` array. ``blot_image`` performs resampling using one of
643
+ the several interpolation algorithms and, unlike the "drizzle" algorithm
644
+ with 'square', 'turbo', and 'point' kernels, this resampling is not
645
+ flux-conserving.
646
+
647
+ This method works best for with well sampled images and thus it is
648
+ typically used to resample the output of :py:class:`Drizzle` back to the
649
+ coordinate grids of input images of :py:meth:`Drizzle.add_image`.
650
+ The output of :py:class:`Drizzle` are usually well sampled images especially
651
+ if it was created from a set of dithered images.
652
+
653
+ Parameters
654
+ ----------
655
+ data : 2D array
656
+ Input numpy array of the source image in units of 'cps'.
657
+
658
+ pixmap : 3D array
659
+ A mapping from input image (``data``) coordinates to resampled
660
+ (``out_img``) coordinates. ``pixmap`` must be an array of shape
661
+ ``(Ny, Nx, 2)`` where ``(Ny, Nx)`` is the shape of the input image.
662
+ ``pixmap[..., 0]`` forms a 2D array of X-coordinates of input
663
+ pixels in the ouput frame and ``pixmap[..., 1]`` forms a 2D array of
664
+ Y-coordinates of input pixels in the ouput coordinate frame.
665
+
666
+ output_pixel_shape : tuple of int
667
+ A tuple of two integer numbers indicating the dimensions of the output
668
+ image ``(Nx, Ny)``.
669
+
670
+ pix_ratio : float
671
+ Ratio of the input image pixel scale to the ouput image pixel scale.
672
+
673
+ exptime : float
674
+ The exposure time of the input image.
675
+
676
+ interp : str, optional
677
+ The type of interpolation used in the resampling. The
678
+ possible values are:
679
+
680
+ - "nearest" (nearest neighbor interpolation);
681
+ - "linear" (bilinear interpolation);
682
+ - "poly3" (cubic polynomial interpolation);
683
+ - "poly5" (quintic polynomial interpolation);
684
+ - "sinc" (sinc interpolation);
685
+ - "lan3" (3rd order Lanczos interpolation); and
686
+ - "lan5" (5th order Lanczos interpolation).
687
+
688
+ sincscl : float, optional
689
+ The scaling factor for "sinc" interpolation.
690
+
691
+ Returns
692
+ -------
693
+ out_img : 2D numpy.ndarray
694
+ A 2D numpy array containing the resampled image data.
695
+
696
+ """
697
+ out_img = np.zeros(output_pixel_shape[::-1], dtype=np.float32)
698
+
699
+ cdrizzle.tblot(data, pixmap, out_img, scale=pix_ratio, kscale=1.0,
700
+ interp=interp, exptime=exptime, misval=0.0, sinscl=sinscl)
701
+
702
+ return out_img