drizzle 1.15.2__cp311-cp311-win32.whl → 2.0.0__cp311-cp311-win32.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 CHANGED
@@ -1,138 +1,15 @@
1
- import numpy as np
1
+ """
2
+ Module ``util`` has been deprecated.
3
+ """
4
+ import warnings
2
5
 
3
-
4
- def find_keyword_extn(fimg, keyword, value=None):
5
- """
6
- This function will return the index of the extension in a multi-extension
7
- FITS file which contains the desired keyword with the given value.
8
-
9
- Parameters
10
- ----------
11
-
12
- fimg : hdulist
13
- A list of header data units
14
-
15
- keyword : str
16
- The keyword to search for
17
-
18
- value : str or number, optional
19
- If set, the value the keyword must have to match
20
-
21
- Returns
22
- -------
23
-
24
- The index of the extension
25
- """
26
-
27
- i = 0
28
- extnum = -1
29
- # Search through all the extensions in the FITS object
30
- for chip in fimg:
31
- hdr = chip.header
32
- # Check to make sure the extension has the given keyword
33
- if keyword in hdr:
34
- if value is not None:
35
- # If it does, then does the value match the desired value
36
- # MUST use 'str.strip' to match against any input string!
37
- if hdr[keyword].strip() == value:
38
- extnum = i
39
- break
40
- else:
41
- extnum = i
42
- break
43
- i += 1
44
- # Return the index of the extension which contained the
45
- # desired EXTNAME value.
46
- return extnum
47
-
48
-
49
- def get_extn(fimg, extn=''):
50
- """
51
- Returns the FITS extension corresponding to extension specified in
52
- filename. Defaults to returning the first extension with data or the
53
- primary extension, if none have data.
54
-
55
- Parameters
56
- ----------
57
-
58
- fimg : hdulist
59
- A list of header data units
60
-
61
- extn : str
62
- The extension name and version to match
63
-
64
- Returns
65
- -------
66
-
67
- The matching header data unit
68
- """
69
-
70
- if extn:
71
- try:
72
- _extn = parse_extn(extn)
73
- if _extn[0]:
74
- _e = fimg.index_of(_extn)
75
- else:
76
- _e = _extn[1]
77
-
78
- except KeyError:
79
- _e = None
80
-
81
- if _e is None:
82
- _extn = None
83
- else:
84
- _extn = fimg[_e]
85
-
86
- else:
87
- # If no extension is provided, search for first extension
88
- # in FITS file with data associated with it.
89
-
90
- # Set up default to point to PRIMARY extension.
91
- _extn = fimg[0]
92
- # then look for first extension with data.
93
- for _e in fimg:
94
- if _e.data is not None:
95
- _extn = _e
96
- break
97
-
98
- return _extn
99
-
100
-
101
- def get_keyword(fimg, keyword, default=None):
102
- """
103
- Return a keyword value from the header of an image,
104
- or the default if the keyword is not found.
105
-
106
- Parameters
107
- ----------
108
-
109
- fimg : hdulist
110
- A list of header data units
111
-
112
- keyword : hdulist
113
- The keyword value to search for
114
-
115
- default : str or number, optional
116
- The default value if not found
117
-
118
- Returns
119
- -------
120
-
121
- The value if found or default if not
122
- """
123
-
124
- value = None
125
- if keyword:
126
- _nextn = find_keyword_extn(fimg, keyword)
127
- try:
128
- value = fimg[_nextn].header[keyword]
129
- except KeyError:
130
- value = None
131
-
132
- if value is None and default is not None:
133
- value = default
134
-
135
- return value
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
+ )
136
13
 
137
14
 
138
15
  def is_blank(value):
@@ -141,116 +18,17 @@ def is_blank(value):
141
18
 
142
19
  Parameters
143
20
  ----------
144
-
145
21
  value : str
146
22
  The value to check
147
23
 
148
24
  Returns
149
25
  -------
150
-
151
26
  True or False
152
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
+ )
153
34
  return value.strip() == ""
154
-
155
-
156
- def parse_extn(extn=''):
157
- """
158
- Parse a string representing a qualified fits extension name as in the
159
- output of parse_filename and return a tuple (str(extname), int(extver)),
160
- which can be passed to pyfits functions using the 'ext' kw.
161
- Default return is the first extension in a fits file.
162
-
163
- Examples
164
- --------
165
- >>> parse_extn('sci,2')
166
- ('sci', 2)
167
- >>> parse_extn('2')
168
- ('', 2)
169
- >>> parse_extn('sci')
170
- ('sci', 1)
171
-
172
- Parameters
173
- ----------
174
- extn : str
175
- The extension name
176
-
177
- Returns
178
- -------
179
- A tuple of the extension name and value
180
- """
181
- if not extn:
182
- return ('', 0)
183
-
184
- try:
185
- lext = extn.split(',')
186
- except Exception:
187
- return ('', 1)
188
-
189
- if len(lext) == 1 and lext[0].isdigit():
190
- return ("", int(lext[0]))
191
- elif len(lext) == 2:
192
- return (lext[0], int(lext[1]))
193
- else:
194
- return (lext[0], 1)
195
-
196
-
197
- def parse_filename(filename):
198
- """
199
- Parse out filename from any specified extensions.
200
- Returns rootname and string version of extension name.
201
-
202
- Parameters
203
- ----------
204
-
205
- filename : str
206
- The filename to be parsed
207
-
208
- Returns
209
- -------
210
-
211
- A tuple with the filename root and extension
212
- """
213
- # Parse out any extension specified in filename
214
- _indx = filename.find('[')
215
- if _indx > 0:
216
- # Read extension name provided
217
- _fname = filename[:_indx]
218
- _extn = filename[_indx + 1:-1]
219
- else:
220
- _fname = filename
221
- _extn = ''
222
-
223
- return _fname, _extn
224
-
225
-
226
- def set_pscale(the_wcs):
227
- """
228
- Calculates the plate scale from cdelt and the pc matrix and adds
229
- it to the WCS. Plate scale is not part of the WCS standard, but is
230
- required by the drizzle code
231
-
232
- Parameters
233
- ----------
234
-
235
- the_wcs : wcs
236
- A WCS object
237
- """
238
- try:
239
- cdelt = the_wcs.wcs.get_cdelt()
240
- pc = the_wcs.wcs.get_pc()
241
-
242
- except Exception:
243
- try:
244
- # for non-celestial axes, get_cdelt doesnt work
245
- cdelt = the_wcs.wcs.cd * the_wcs.wcs.cdelt
246
- except AttributeError:
247
- cdelt = the_wcs.wcs.cdelt
248
-
249
- try:
250
- pc = the_wcs.wcs.pc
251
- except AttributeError:
252
- pc = 1
253
-
254
- pccd = np.array(cdelt * pc)
255
- scales = np.sqrt((pccd ** 2).sum(axis=0, dtype=float))
256
- the_wcs.pscale = scales[0]
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