Skip to content

Commit a0d436a

Browse files
committed
Fix cropping when a world point is exactly on a pixel edge
1 parent de3533f commit a0d436a

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
@@ -177,20 +177,16 @@ def get_crop_item_from_points(points, wcs, crop_by_values, keepdims):
177177
sliced_wcs, sliced_point = low_level_wcs, np.array(point, dtype=object)
178178
# Derive the array indices of the input point and place each index
179179
# in the list corresponding to its axis.
180+
# Use the to_pixel methods to preserve fractional indices for future rounding.
180181
if crop_by_values:
181-
point_array_indices = sliced_wcs.world_to_array_index_values(*sliced_point)
182-
# If returned value is a 0-d array, convert to a length-1 tuple.
183-
if isinstance(point_array_indices, np.ndarray) and point_array_indices.ndim == 0:
184-
point_array_indices = (point_array_indices.item(),)
185-
else:
186-
# Convert from scalar arrays to scalars
187-
point_array_indices = tuple(a.item() for a in point_array_indices)
182+
point_pixel_indices = sliced_wcs.world_to_pixel_values(*sliced_point)
183+
else:
184+
point_pixel_indices = HighLevelWCSWrapper(sliced_wcs).world_to_pixel(*sliced_point)
185+
# Switch from pixel ordering to array ordering
186+
if sliced_wcs.pixel_n_dim == 1:
187+
point_array_indices = (point_pixel_indices,)
188188
else:
189-
point_array_indices = HighLevelWCSWrapper(sliced_wcs).world_to_array_index(
190-
*sliced_point)
191-
# If returned value is a 0-d array, convert to a length-1 tuple.
192-
if isinstance(point_array_indices, np.ndarray) and point_array_indices.ndim == 0:
193-
point_array_indices = (point_array_indices.item(),)
189+
point_array_indices = point_pixel_indices[::-1]
194190
for axis, index in zip(array_axes_with_input, point_array_indices):
195191
combined_points_array_idx[axis] = combined_points_array_idx[axis] + [index]
196192
# Define slice item with which to slice cube.
@@ -201,8 +197,11 @@ def get_crop_item_from_points(points, wcs, crop_by_values, keepdims):
201197
result_is_scalar = False
202198
item.append(slice(None))
203199
else:
204-
min_idx = min(axis_indices)
205-
max_idx = max(axis_indices) + 1
200+
# Correctly round up/down the fractional indices
201+
min_idx = int(np.floor(min(axis_indices) + 0.5))
202+
max_idx = int(np.ceil(max(axis_indices) - 0.5)) + 1
203+
if min_idx == max_idx:
204+
raise ValueError("Input points cause cube to be cropped to zero size along a pixel axis.")
206205
if max_idx - min_idx == 1 and not keepdims:
207206
item.append(min_idx)
208207
else:

0 commit comments

Comments
 (0)