diff --git a/stitch_rigid.py b/stitch_rigid.py index d1c4c8f..8824fc0 100644 --- a/stitch_rigid.py +++ b/stitch_rigid.py @@ -22,12 +22,14 @@ for every tile based on cross-correlation between tile overlaps. """ +import collections from typing import Any, Mapping +import jax import jax.numpy as jnp import numpy as np +from scipy import fftpack from scipy import ndimage - from sofima import flow_field from sofima import mesh @@ -101,6 +103,513 @@ def _estimate_offset_vert( ) +def _dyn_range_2d(img: jax.Array, filter_size: int) -> jax.Array: + """Computes 2D max-min dynamic range matching scipy.ndimage reflect mode.""" + img_f32 = img.astype(jnp.float32) + if filter_size <= 1: + return jnp.zeros_like(img_f32) + pad_lo = filter_size // 2 + pad_hi = filter_size - 1 - pad_lo + padded = jnp.pad( + img_f32, ((pad_lo, pad_hi), (pad_lo, pad_hi)), mode='symmetric' + ) + mx = jax.lax.reduce_window( + padded, -jnp.inf, jax.lax.max, (filter_size, 1), (1, 1), 'VALID' + ) + mx = jax.lax.reduce_window( + mx, -jnp.inf, jax.lax.max, (1, filter_size), (1, 1), 'VALID' + ) + mn = jax.lax.reduce_window( + padded, jnp.inf, jax.lax.min, (filter_size, 1), (1, 1), 'VALID' + ) + mn = jax.lax.reduce_window( + mn, jnp.inf, jax.lax.min, (1, filter_size), (1, 1), 'VALID' + ) + return mx - mn + + +_batched_dyn_range_jit = jax.jit( + jax.vmap(_dyn_range_2d, in_axes=(0, None)), + static_argnames=('filter_size',), +) + + +@jax.jit +def _batched_coarse_offset_peaks_jit( + a_b: jax.Array, + b_b: jax.Array, + a_dr_b: jax.Array, + b_dr_b: jax.Array, + ma_in: jax.Array | None, + mb_in: jax.Array | None, + range_limit: jax.Array, +) -> jax.Array: + """Computes full-overlap masked ZNCC peaks for a batch of tile seams.""" + a_b = a_b.astype(jnp.float32) + b_b = b_b.astype(jnp.float32) + ma_b = a_dr_b < range_limit + mb_b = b_dr_b < range_limit + if ma_in is not None and mb_in is not None: + ma_b = ma_b | ma_in + mb_b = mb_b | mb_in + + too_masked = (jnp.mean(ma_b, axis=(-2, -1)) >= 0.75) | ( + jnp.mean(mb_b, axis=(-2, -1)) >= 0.75 + ) + + def _single_xcorr(a_i, b_i, ma_i, mb_i): + pm = jnp.nanmean(jnp.where(ma_i, jnp.nan, a_i)) + cm = jnp.nanmean(jnp.where(mb_i, jnp.nan, b_i)) + return flow_field.masked_xcorr( + a_i - pm, b_i - cm, ma_i, mb_i, use_jax=True, dim=2 + ) + + xc = jax.vmap(_single_xcorr)(a_b, b_b, ma_b, mb_b) + h, w = a_b.shape[1], a_b.shape[2] + peaks = flow_field._batched_peaks( # pylint: disable=protected-access + xc, + np.array([h - 1, w - 1]), # pyrefly: ignore[bad-argument-type] + min_distance=2, + threshold_rel=0.5, + peak_radius=5, + ) + return jnp.where(too_masked[:, jnp.newaxis], jnp.nan, peaks) + + +_BATCH_BUCKETS = (1, 4, 16, 64, 256) +_MAX_WORKING_SET_BYTES = 1024 * 1024 * 1024 # 1 GiB +_XCORR_BYTES_PER_FFT_ELEM = 8 * 4 # ~8 live float32/complex64 FFT surfaces +_DYN_RANGE_BYTES_PER_ELEM = 4 * 4 # img_f32, padded, mx, mn in _dyn_range_2d + + +def _max_batch_for_seam_bytes(seam_bytes: int) -> int: + """Returns the largest bucket in _BATCH_BUCKETS within the memory budget.""" + cap = max(1, _MAX_WORKING_SET_BYTES // max(1, seam_bytes)) + return max((b for b in _BATCH_BUCKETS if b <= cap), default=1) + + +def _max_xcorr_batch(h: int, w: int) -> int: + """Estimates the max seam batch size for masked_xcorr on (h, w) overlaps.""" + fast_h = fftpack.next_fast_len(2 * h - 1) + fast_w = fftpack.next_fast_len(2 * w - 1) + return _max_batch_for_seam_bytes(fast_h * fast_w * _XCORR_BYTES_PER_FFT_ELEM) + + +def _max_seam_chunk_size( + h: int, + overlaps: tuple[int, ...], + img_itemsize: int, + has_masks: bool, +) -> int: + """Returns the max outer seam chunk keeping resident buffers within budget.""" + max_ov = max(overlaps) + sum_ov = sum(overlaps) + img_ov = max_ov + sum(ov for ov in overlaps if ov != max_ov) + # Resident per seam across a_max_dev/b_max_dev, per-ov slices, float32 + # a_dr/b_dr, and optional bool masks (ma_max_dev/mb_max_dev + per-ov masks). + bytes_per_seam = 2 * h * ( + img_ov * img_itemsize + + sum_ov * 4 + + ((max_ov + sum_ov) if has_masks else 0) + ) + return max(1, _MAX_WORKING_SET_BYTES // max(1, bytes_per_seam)) + + +def _bucket_pad_chunks( + indices: np.ndarray, max_batch: int = _BATCH_BUCKETS[-1] +) -> list[tuple[jax.Array, int]]: + """Splits seam indices into <=max_batch chunks padded to _BATCH_BUCKETS.""" + max_bucket = max((b for b in _BATCH_BUCKETS if b <= max_batch), default=1) + chunks = [] + for st in range(0, indices.size, max_bucket): + chunk = indices[st : st + max_bucket] + c_len = int(chunk.size) + b_pad = next(b for b in _BATCH_BUCKETS if b >= c_len) + if c_len < b_pad: + chunk = np.pad(chunk, (0, b_pad - c_len), mode='edge') + chunks.append((jnp.asarray(chunk, dtype=jnp.int32), c_len)) + return chunks + + +def _chunked_dyn_range(x_dev: jax.Array, filter_size: int) -> jax.Array: + """Computes batched dynamic range using memory-capped bucket-padded chunks.""" + h, w = int(x_dev.shape[1]), int(x_dev.shape[2]) + max_batch = _max_batch_for_seam_bytes(h * w * _DYN_RANGE_BYTES_PER_ELEM) + chunks = [ + _batched_dyn_range_jit(x_dev[ids_dev], filter_size)[:c_len] + for ids_dev, c_len in _bucket_pad_chunks( + np.arange(x_dev.shape[0], dtype=np.int32), max_batch=max_batch + ) + ] + return chunks[0] if len(chunks) == 1 else jnp.concatenate(chunks, axis=0) + + +def _clear_all_true_masks(mask: jax.Array | None) -> jax.Array | None: + """Disables per-seam masking where the overlap region is completely masked.""" + if mask is None: + return None + return jnp.where(jnp.all(mask, axis=(-2, -1), keepdims=True), False, mask) + + +def _select_offset_for_range( + peaks_by_ov: np.ndarray, + overlaps: tuple[int, ...], + axis: int, + min_overlap: float, + max_ortho_shift: float, +) -> list[float] | None: + """Selects the best offset across overlap candidates for one min_range pass.""" + max_idx = -1 + max_pr = 0.0 + estimates: list[list[float]] = [] + for ov_idx, overlap in enumerate(overlaps): + px, py, _, pr_raw = peaks_by_ov[ov_idx] + off = [float(px), float(py)] if axis == 0 else [float(py), float(px)] + off[axis] -= overlap + pr = abs(float(pr_raw)) + # If a single peak is found, terminate search. + if pr == 0.0: + return off + estimates.append(off) + # Record the valid offset with maximum peak ratio. + if ( + pr > max_pr + and abs(off[1 - axis]) < max_ortho_shift + and abs(off[axis]) >= min_overlap + ): + max_pr = pr + max_idx = len(estimates) - 1 + + min_diff = np.inf + min_idx = 0 + for i, (off0, off1) in enumerate(zip(estimates, estimates[1:])): + diff = abs(off1[axis] - off0[axis]) + if ( + diff < min_diff + and abs(off1[1 - axis]) < max_ortho_shift + and abs(off1[axis]) >= min_overlap + ): + min_diff = diff + min_idx = i + + # If we found an offset with good consistency between two consecutive + # estimates, prefer that; otherwise prefer the offset with maximum peak ratio. + if min_diff < 20: + return estimates[min_idx + 1] + if max_idx >= 0: + return estimates[max_idx] + return None + + +def _find_offset( + estimate_fn: Any, + pre: np.ndarray, + post: np.ndarray, + overlaps: tuple[int, ...], + min_range: tuple[Any, ...], + min_overlap: float, + filter_size: int, + max_ortho_shift: float, + axis: int, + masks: tuple[np.ndarray, np.ndarray] | None = None, +): + """Serial fallback offset search for a single tile seam.""" + + def _is_valid(offset): + return ( + abs(offset[1 - axis]) < max_ortho_shift + and abs(offset[axis]) >= min_overlap + ) + + done = False + offset: Any = (np.inf, np.inf) + + for range_limit in min_range: + if done: + break + max_idx = -1 + max_pr = 0 + estimates = [] + for overlap in overlaps: + # Mask overlaps if needed + ov_masks = None + if masks is not None: + ma = masks[0][:, -overlap:] if axis == 0 else masks[0][-overlap:, :] + mb = masks[1][:, :overlap] if axis == 0 else masks[1][:overlap, :] + # Disable ov masking if overlap region would be completely masked + ma = np.full_like(ma, fill_value=False) if np.all(ma) else ma + mb = np.full_like(mb, fill_value=False) if np.all(mb) else mb + ov_masks = (ma, mb) + + offset, pr = estimate_fn( + overlap, pre, post, range_limit, filter_size, ov_masks + ) + offset[axis] -= overlap + + # If a single peak is found, terminate search. + if pr == 0.0: + done = True + break + + estimates.append(offset) + + # Record the valid offset with maximum peak ratio. + if pr > max_pr and _is_valid(offset): + max_pr = pr + max_idx = len(estimates) - 1 + + if done: + break + + min_diff = np.inf + min_idx = 0 + for i, (off0, off1) in enumerate(zip(estimates, estimates[1:])): + diff = np.abs(off1[axis] - off0[axis]) + if diff < min_diff and _is_valid(off1): + min_diff = diff + min_idx = i + + # If we found an offset with good consistency between two consecutive + # estimates, prefer that. + if min_diff < 20: + offset = estimates[min_idx + 1] + done = True + # Otherwise prefer the offset with maximum peak ratio. + elif max_idx >= 0: + offset = estimates[max_idx] + done = True + + if not done or abs(offset[axis]) < min_overlap: + offset = np.inf, np.inf + + return offset + + +def _crop_overlap( + arr: np.ndarray, max_ov: int, axis: int, is_post: bool +) -> np.ndarray: + if axis == 0: + return arr[:, :max_ov] if is_post else arr[:, -max_ov:] + return arr[:max_ov, :].T if is_post else arr[-max_ov:, :].T + + +def _solve_seam_chunk( + chunk_seams: list[tuple[int, int, np.ndarray, np.ndarray, Any]], + overlaps: tuple[int, ...], + min_range: tuple[Any, ...], + min_overlap: float, + filter_size: int, + max_ortho_shift: float, + axis: int, + conn_out: np.ndarray, +) -> None: + """Solves one memory-bounded chunk of homogeneous-shape seams on device.""" + max_ov = max(overlaps) + a_max_dev = jnp.asarray( + np.stack([ + _crop_overlap(pre, max_ov, axis, is_post=False) + for _, _, pre, _, _ in chunk_seams + ]) + ) + b_max_dev = jnp.asarray( + np.stack([ + _crop_overlap(post, max_ov, axis, is_post=True) + for _, _, _, post, _ in chunk_seams + ]) + ) + if chunk_seams[0][4] is not None: + ma_max_dev = jnp.asarray( + np.stack([ + _crop_overlap(m[0], max_ov, axis, is_post=False) + for _, _, _, _, m in chunk_seams + ]), + dtype=jnp.bool_, + ) + mb_max_dev = jnp.asarray( + np.stack([ + _crop_overlap(m[1], max_ov, axis, is_post=True) + for _, _, _, _, m in chunk_seams + ]), + dtype=jnp.bool_, + ) + else: + ma_max_dev = None + mb_max_dev = None + + ov_tensors = [] + for ov in overlaps: + a_dev = a_max_dev if ov == max_ov else a_max_dev[:, :, -ov:] + b_dev = b_max_dev if ov == max_ov else b_max_dev[:, :, :ov] + ma_sub = ( + None + if ma_max_dev is None + else (ma_max_dev if ov == max_ov else ma_max_dev[:, :, -ov:]) + ) + mb_sub = ( + None + if mb_max_dev is None + else (mb_max_dev if ov == max_ov else mb_max_dev[:, :, :ov]) + ) + ov_tensors.append(( + a_dev, + b_dev, + _chunked_dyn_range(a_dev, int(filter_size)), + _chunked_dyn_range(b_dev, int(filter_size)), + _clear_all_true_masks(ma_sub), + _clear_all_true_masks(mb_sub), + _max_xcorr_batch(int(a_dev.shape[1]), int(a_dev.shape[2])), + )) + del ma_max_dev, mb_max_dev + + n_grp = len(chunk_seams) + done_grp = np.zeros(n_grp, dtype=bool) + chosen_offsets = np.full((n_grp, 2), np.inf, dtype=np.float64) + + for range_limit in min_range: + act_local = np.flatnonzero(~done_grp) + if act_local.size == 0: + break + rl_dev = jnp.asarray(float(range_limit), dtype=jnp.float32) + act_i32 = act_local.astype(np.int32) + chunks_by_max: dict[int, list[tuple[jax.Array, int]]] = {} + + peaks_dev_per_ov = [] + for a_dev, b_dev, a_dr, b_dr, ma_dev, mb_dev, max_batch in ov_tensors: + id_chunks = chunks_by_max.get(max_batch) + if id_chunks is None: + id_chunks = _bucket_pad_chunks(act_i32, max_batch=max_batch) + chunks_by_max[max_batch] = id_chunks + ov_chunks = [ + _batched_coarse_offset_peaks_jit( + a_dev[ids_dev], + b_dev[ids_dev], + a_dr[ids_dev], + b_dr[ids_dev], + None if ma_dev is None else ma_dev[ids_dev], + None if mb_dev is None else mb_dev[ids_dev], + rl_dev, + )[:c_len] + for ids_dev, c_len in id_chunks + ] + peaks_dev_per_ov.append( + ov_chunks[0] + if len(ov_chunks) == 1 + else jnp.concatenate(ov_chunks, axis=0) + ) + all_peaks_np = np.asarray( + jax.device_get(jnp.stack(peaks_dev_per_ov, axis=0)) + ) + + for a_pos, g_i in enumerate(act_local): + off = _select_offset_for_range( + all_peaks_np[:, a_pos], overlaps, axis, min_overlap, max_ortho_shift + ) + if off is not None: + chosen_offsets[g_i] = off + done_grp[g_i] = True + + for g_i, (x, y, _, _, _) in enumerate(chunk_seams): + off_xy = chosen_offsets[g_i] + if (not done_grp[g_i]) or abs(off_xy[axis]) < min_overlap: + conn_out[:, 0, y, x] = (np.inf, np.inf) + else: + conn_out[:, 0, y, x] = off_xy + + +def _solve_seam_group( + group_seams: list[tuple[int, int, np.ndarray, np.ndarray, Any]], + overlaps: tuple[int, ...], + min_range: tuple[Any, ...], + min_overlap: float, + filter_size: int, + max_ortho_shift: float, + axis: int, + conn_out: np.ndarray, +) -> None: + """Solves a homogeneous-shape group of seams in batched JAX calls.""" + if not group_seams: + return + if not min_range: + for x, y, _, _, _ in group_seams: + conn_out[:, 0, y, x] = (np.inf, np.inf) + return + + h = int(group_seams[0][2].shape[axis]) + img_itemsize = max( + max(pre.dtype.itemsize, post.dtype.itemsize) + for _, _, pre, post, _ in group_seams + ) + has_masks = group_seams[0][4] is not None + chunk_size = _max_seam_chunk_size(h, overlaps, img_itemsize, has_masks) + for st in range(0, len(group_seams), chunk_size): + _solve_seam_chunk( + group_seams[st : st + chunk_size], + overlaps, + min_range, + min_overlap, + filter_size, + max_ortho_shift, + axis, + conn_out, + ) + + +def _solve_direction_batched( + seams: list[tuple[int, int, np.ndarray, np.ndarray, Any]], + overlaps: Any, + min_range: tuple[Any, ...], + min_overlap: float, + filter_size: int, + max_ortho_shift: float, + axis: int, + conn_out: np.ndarray, +) -> None: + """Groups compatible seams for batched JAX solving, with serial fallback.""" + overlaps_t = tuple(int(o) for o in overlaps) + est_fn = _estimate_offset_horiz if axis == 0 else _estimate_offset_vert + min_dim_req = max(1, int(filter_size)) + can_batch = bool(overlaps_t) and filter_size >= 1 + max_ov = max(overlaps_t) if can_batch else 0 + min_ov = min(overlaps_t) if can_batch else 0 + + groups: dict[tuple[int, int], list[Any]] = collections.defaultdict(list) + for seam in seams: + x, y, pre, post, masks = seam + if ( + can_batch + and pre.shape[axis] == post.shape[axis] >= min_dim_req + and min_ov >= min_dim_req + and pre.shape[1 - axis] >= max_ov + and post.shape[1 - axis] >= max_ov + ): + groups[(pre.shape[axis], max_ov)].append(seam) + else: + conn_out[:, 0, y, x] = _find_offset( + est_fn, + pre, + post, + overlaps_t, + min_range, + min_overlap, + filter_size, + max_ortho_shift, + axis, + masks, + ) + + for group_seams in groups.values(): + _solve_seam_group( + group_seams, + overlaps_t, + min_range, + min_overlap, + filter_size, + max_ortho_shift, + axis, + conn_out, + ) + + def compute_coarse_offsets( yx_shape: tuple[int, int], tile_map: Mapping[tuple[int, int], np.ndarray], @@ -146,77 +655,16 @@ def compute_coarse_offsets( could not be obtained. Values that cannot be computed because of missing tiles are set to nan. """ - - def _find_offset(estimate_fn, pre, post, overlaps, max_ortho_shift, axis, masks=None): - def _is_valid_offset(offset, axis): - return ( - abs(offset[1 - axis]) < max_ortho_shift - and abs(offset[axis]) >= min_overlap - ) - - done = False - - for range_limit in min_range: - if done: - break - max_idx = -1 - max_pr = 0 - estimates = [] - for overlap in overlaps: - - # Mask overlaps if needed - ov_masks = None - if masks is not None: - ma = masks[0][:, -overlap:] if axis == 0 else masks[0][-overlap:, :] - mb = masks[1][:, :overlap] if axis == 0 else masks[1][:overlap, :] - # Disable ov masking if overlap region would be completely masked - ma = np.full_like(ma, fill_value=False) if np.all(ma) else ma - mb = np.full_like(mb, fill_value=False) if np.all(mb) else mb - ov_masks = (ma, mb) - - offset, pr = estimate_fn(overlap, pre, post, range_limit, filter_size, - ov_masks) - offset[axis] -= overlap - - # If a single peak is found, terminate search. - if pr == 0.0: - done = True - break - - estimates.append(offset) - - # Record the valid offset with maximum peak ratio. - if pr > max_pr and _is_valid_offset(offset, axis): - max_pr = pr - max_idx = len(estimates) - 1 - - if done: - break - - min_diff = np.inf - min_idx = 0 - for i, (off0, off1) in enumerate(zip(estimates, estimates[1:])): - diff = np.abs(off1[axis] - off0[axis]) - if diff < min_diff and _is_valid_offset(off1, axis): - min_diff = diff - min_idx = i - - # If we found an offset with good consistency between two consecutive - # estimates, perfer that. - if min_diff < 20: - offset = estimates[min_idx + 1] - done = True - # Otherwise prefer the offset with maximum peak ratio. - elif max_idx >= 0: - offset = estimates[max_idx] - done = True - - if not done or abs(offset[axis]) < min_overlap: # pyrefly: ignore[unbound-name] - offset = np.inf, np.inf - - return offset + min_range_t = tuple(min_range) + overlaps_x = tuple(int(o) for o in overlaps_xy[0]) + overlaps_y = tuple(int(o) for o in overlaps_xy[1]) + max_ortho_shifts = ( + max(overlaps_y) if overlaps_y else 0, + max(overlaps_x) if overlaps_x else 0, + ) conn_x = np.full((2, 1, yx_shape[0], yx_shape[1]), np.nan) + seams_x = [] for x in range(0, yx_shape[1] - 1): for y in range(0, yx_shape[0]): if not ((x, y) in tile_map and (x + 1, y) in tile_map): @@ -227,23 +675,26 @@ def _is_valid_offset(offset, axis): # Load and crop overlap masks masks_x = None - if mask_map is not None: - ov_width = max(overlaps_xy[0]) + if mask_map is not None and overlaps_x: + ov_width = max(overlaps_x) ov_ma = mask_map[(x, y)][:, -ov_width:] ov_mb = mask_map[(x + 1, y)][:, :ov_width] masks_x = (ov_ma, ov_mb) - conn_x[:, 0, y, x] = _find_offset( - _estimate_offset_horiz, - left, - right, - overlaps_xy[0], - max(overlaps_xy[1]), - 0, - masks_x - ) + seams_x.append((x, y, left, right, masks_x)) + _solve_direction_batched( + seams_x, + overlaps_x, + min_range_t, + min_overlap, + filter_size, + max_ortho_shifts[0], + 0, + conn_x, + ) conn_y = np.full((2, 1, yx_shape[0], yx_shape[1]), np.nan) + seams_y = [] for y in range(0, yx_shape[0] - 1): for x in range(0, yx_shape[1]): if not ((x, y) in tile_map and (x, y + 1) in tile_map): @@ -254,21 +705,23 @@ def _is_valid_offset(offset, axis): # Load and crop overlap masks masks_y = None - if mask_map is not None: - ov_width = max(overlaps_xy[1]) + if mask_map is not None and overlaps_y: + ov_width = max(overlaps_y) ov_ma = mask_map[(x, y)][-ov_width:] ov_mb = mask_map[(x, y + 1)][:ov_width] masks_y = (ov_ma, ov_mb) - conn_y[:, 0, y, x] = _find_offset( - _estimate_offset_vert, - top, - bot, - overlaps_xy[1], - max(overlaps_xy[0]), - 1, - masks_y - ) + seams_y.append((x, y, top, bot, masks_y)) + _solve_direction_batched( + seams_y, + overlaps_y, + min_range_t, + min_overlap, + filter_size, + max_ortho_shifts[1], + 1, + conn_y, + ) return conn_x, conn_y diff --git a/tests/mesh_test.py b/tests/mesh_test.py index 0bba94e..0358aa5 100644 --- a/tests/mesh_test.py +++ b/tests/mesh_test.py @@ -23,6 +23,7 @@ import jax.numpy as jnp import numpy as np from sofima import mesh +from sofima import stitch_rigid class MeshTest(absltest.TestCase): @@ -661,5 +662,162 @@ def test_traced_spring_constant_k(self): atol=1e-6, ) + def test_stitch_rigid_compute_coarse_offsets(self): + rng = np.random.default_rng(123) + canvas = rng.integers(20, 235, size=(260, 340), dtype=np.uint8) + tile_map = { + (0, 0): canvas[0:160, 0:160], + (1, 0): canvas[2:162, 80:240], + (2, 0): canvas[4:164, 160:320], + (0, 1): canvas[78:238, 3:163], + (1, 1): canvas[80:240, 83:243], + (2, 1): canvas[82:242, 163:323], + } + mask_map = {k: np.zeros_like(v, dtype=bool) for k, v in tile_map.items()} + # Mask a block inside both X and Y overlap strips of (0, 0) and mark all of + # (1, 1) masked to exercise custom masking and the all-True mask fallback. + mask_map[(0, 0)][-20:, -20:] = True + mask_map[(1, 1)][:, :] = True + + cx, cy = stitch_rigid.compute_coarse_offsets( + (2, 3), + tile_map, + overlaps_xy=((75, 85), (75, 85)), + min_range=(250, 10, 0), + min_overlap=50, + filter_size=6, + mask_map=mask_map, + ) + for x, y in ((0, 0), (1, 0), (0, 1), (1, 1)): + self.assertTrue(np.all(np.isfinite(cx[:, 0, y, x]))) + np.testing.assert_allclose(cx[0, 0, y, x], -80.0, atol=2.0) + np.testing.assert_allclose(cx[1, 0, y, x], 2.0, atol=2.0) + for x, y in ((0, 0), (1, 0), (2, 0)): + self.assertTrue(np.all(np.isfinite(cy[:, 0, y, x]))) + np.testing.assert_allclose(cy[0, 0, y, x], 3.0, atol=2.0) + np.testing.assert_allclose(cy[1, 0, y, x], -82.0, atol=2.0) + + # Verify JIT cache reuse across different seam counts in the same bucket + # (4/3 seams vs 3/2 seams, all in bucket 4). + peaks_cache_after_full = ( + stitch_rigid._batched_coarse_offset_peaks_jit._cache_size() # pylint: disable=protected-access + ) + dr_cache_after_full = ( + stitch_rigid._batched_dyn_range_jit._cache_size() # pylint: disable=protected-access + ) + sub_tiles = {k: v for k, v in tile_map.items() if k != (2, 1)} + sub_masks = {k: v for k, v in mask_map.items() if k != (2, 1)} + cx_sub, cy_sub = stitch_rigid.compute_coarse_offsets( + (2, 3), + sub_tiles, + overlaps_xy=((75, 85), (75, 85)), + min_range=(10, 0), + min_overlap=50, + filter_size=6, + mask_map=sub_masks, + ) + for x, y in ((0, 0), (1, 0), (0, 1)): + np.testing.assert_allclose(cx_sub[:, 0, y, x], cx[:, 0, y, x], atol=1e-5) + for x, y in ((0, 0), (1, 0)): + np.testing.assert_allclose(cy_sub[:, 0, y, x], cy[:, 0, y, x], atol=1e-5) + self.assertTrue(np.all(np.isnan(cx_sub[:, 0, 1, 1]))) + self.assertTrue(np.all(np.isnan(cy_sub[:, 0, 0, 2]))) + self.assertEqual( + stitch_rigid._batched_coarse_offset_peaks_jit._cache_size(), # pylint: disable=protected-access + peaks_cache_after_full, + ) + self.assertEqual( + stitch_rigid._batched_dyn_range_jit._cache_size(), # pylint: disable=protected-access + dr_cache_after_full, + ) + + # Verify non-boolean integer masks (e.g. uint8 0/255) coerce cleanly to bool + # and multi-element NumPy arrays for overlaps_xy are accepted. + uint8_masks = { + k: (v.astype(np.uint8) * 255) for k, v in sub_masks.items() + } + cx_u8, cy_u8 = stitch_rigid.compute_coarse_offsets( + (2, 3), + sub_tiles, + overlaps_xy=(np.array([75, 85]), np.array([75, 85])), + min_range=(10, 0), + min_overlap=50, + filter_size=6, + mask_map=uint8_masks, + ) + np.testing.assert_allclose(cx_u8, cx_sub, atol=1e-5, equal_nan=True) + np.testing.assert_allclose(cy_u8, cy_sub, atol=1e-5, equal_nan=True) + + # Verify memory-capped chunking produces identical offsets when forced to + # outer seam chunk size 2 and batch size 1. + with ( + mock.patch.object(stitch_rigid, '_max_seam_chunk_size', return_value=2), + mock.patch.object( + stitch_rigid, + '_solve_seam_chunk', + wraps=stitch_rigid._solve_seam_chunk, # pylint: disable=protected-access + ) as mock_chunk, + ): + cx_chunk2, cy_chunk2 = stitch_rigid.compute_coarse_offsets( + (2, 3), + tile_map, + overlaps_xy=((75, 85), (75, 85)), + min_range=(250, 10, 0), + min_overlap=50, + filter_size=6, + mask_map=mask_map, + ) + # 4 X-seams -> 2 chunks of 2; 3 Y-seams -> chunks of 2 and 1. + self.assertEqual(mock_chunk.call_count, 4) + np.testing.assert_allclose(cx_chunk2, cx, atol=1e-5, equal_nan=True) + np.testing.assert_allclose(cy_chunk2, cy, atol=1e-5, equal_nan=True) + + with mock.patch.object(stitch_rigid, '_MAX_WORKING_SET_BYTES', 1): + cx_cap, cy_cap = stitch_rigid.compute_coarse_offsets( + (2, 3), + sub_tiles, + overlaps_xy=(np.array([75, 85]), np.array([75, 85])), + min_range=(10, 0), + min_overlap=50, + filter_size=6, + mask_map=sub_masks, + ) + np.testing.assert_allclose(cx_cap, cx_sub, atol=1e-5, equal_nan=True) + np.testing.assert_allclose(cy_cap, cy_sub, atol=1e-5, equal_nan=True) + + def test_stitch_rigid_memory_capped_buckets(self): + self.assertEqual(stitch_rigid._max_xcorr_batch(2048, 300), 4) # pylint: disable=protected-access + self.assertEqual(stitch_rigid._max_xcorr_batch(4096, 300), 4) # pylint: disable=protected-access + self.assertEqual(stitch_rigid._max_xcorr_batch(8192, 300), 1) # pylint: disable=protected-access + + # Outer seam chunk sizing keeps resident device buffers within 1 GiB. + self.assertEqual( + stitch_rigid._max_seam_chunk_size(2048, (200, 300), 1, False), 104 # pylint: disable=protected-access + ) + self.assertEqual( + stitch_rigid._max_seam_chunk_size(4096, (200, 300), 1, False), 52 # pylint: disable=protected-access + ) + self.assertEqual( + stitch_rigid._max_seam_chunk_size(8192, (200, 300), 1, False), 26 # pylint: disable=protected-access + ) + self.assertEqual( + stitch_rigid._max_seam_chunk_size(8192, (200, 300), 4, False), 16 # pylint: disable=protected-access + ) + self.assertEqual( + stitch_rigid._max_seam_chunk_size(8192, (200, 300), 4, True), 13 # pylint: disable=protected-access + ) + + idx = np.arange(7, dtype=np.int32) + chunks_4 = stitch_rigid._bucket_pad_chunks(idx, max_batch=4) # pylint: disable=protected-access + self.assertEqual( + [(int(ids.shape[0]), c_len) for ids, c_len in chunks_4], + [(4, 4), (4, 3)], + ) + chunks_1 = stitch_rigid._bucket_pad_chunks(idx, max_batch=1) # pylint: disable=protected-access + self.assertEqual( + [(int(ids.shape[0]), c_len) for ids, c_len in chunks_1], + [(1, 1)] * 7, + ) + if __name__ == '__main__': absltest.main()