Skip to content

Commit ea81427

Browse files
committed
Fix cropping when a world point is exactly on a pixel edge
1 parent 58c8075 commit ea81427

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

ndcube/utils/cube.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -174,20 +174,16 @@ def get_crop_item_from_points(points, wcs, crop_by_values, keepdims):
174174
sliced_point = np.array(point, dtype=object)[np.array(point_indices_with_inputs)]
175175
# Derive the array indices of the input point and place each index
176176
# in the list corresponding to its axis.
177+
# Use the to_pixel methods to preserve fractional indices for future rounding.
177178
if crop_by_values:
178-
point_array_indices = sliced_wcs.world_to_array_index_values(*sliced_point)
179-
# If returned value is a 0-d array, convert to a length-1 tuple.
180-
if isinstance(point_array_indices, np.ndarray) and point_array_indices.ndim == 0:
181-
point_array_indices = (point_array_indices.item(),)
182-
else:
183-
# Convert from scalar arrays to scalars
184-
point_array_indices = tuple(a.item() for a in point_array_indices)
179+
point_pixel_indices = sliced_wcs.world_to_pixel_values(*sliced_point)
180+
else:
181+
point_pixel_indices = HighLevelWCSWrapper(sliced_wcs).world_to_pixel(*sliced_point)
182+
# Switch from pixel ordering to array ordering
183+
if sliced_wcs.pixel_n_dim == 1:
184+
point_array_indices = (point_pixel_indices,)
185185
else:
186-
point_array_indices = HighLevelWCSWrapper(sliced_wcs).world_to_array_index(
187-
*sliced_point)
188-
# If returned value is a 0-d array, convert to a length-1 tuple.
189-
if isinstance(point_array_indices, np.ndarray) and point_array_indices.ndim == 0:
190-
point_array_indices = (point_array_indices.item(),)
186+
point_array_indices = point_pixel_indices[::-1]
191187
for axis, index in zip(array_axes_with_input, point_array_indices):
192188
combined_points_array_idx[axis] = combined_points_array_idx[axis] + [index]
193189
# Define slice item with which to slice cube.
@@ -198,8 +194,11 @@ def get_crop_item_from_points(points, wcs, crop_by_values, keepdims):
198194
result_is_scalar = False
199195
item.append(slice(None))
200196
else:
201-
min_idx = min(axis_indices)
202-
max_idx = max(axis_indices) + 1
197+
# Correctly round up/down the fractional indices
198+
min_idx = int(np.floor(min(axis_indices) + 0.5))
199+
max_idx = int(np.ceil(max(axis_indices) - 0.5)) + 1
200+
if min_idx == max_idx:
201+
raise ValueError("Input points cause cube to be cropped to zero size along a pixel axis.")
203202
if max_idx - min_idx == 1 and not keepdims:
204203
item.append(min_idx)
205204
else:

0 commit comments

Comments
 (0)