MOSAIC / spatial.py
Astaxanthin's picture
Upload 15 files
8850d81 verified
Raw History Blame Contribute Delete
7.57 kB
"""Evaluation-only spatial preparation copied from WSI_Data_v2.
Default range (64,100) and fixed 80-patch crops reproduce the source settings.
"""
import math
import numpy as np
class SpatialViews:
def __init__(self):
self.ssl_train = False
self.vl_train = False
self.eval_crop_size_range = (64, 100)
def _infer_patch_step(self, coords):
all_diffs = []
for axis in [0, 1]:
uniq = np.unique(coords[:, axis])
diffs = np.diff(np.sort(uniq))
diffs = diffs[diffs > 1]
if len(diffs) > 0:
all_diffs.append(diffs)
if len(all_diffs) == 0:
return 1
all_diffs = np.concatenate(all_diffs)
values, counts = np.unique(all_diffs, return_counts=True)
return int(values[np.argmax(counts)])
def _crop_2d_features(self, features, coords, crop_size=100, start_h=None, start_w=None):
features = np.asarray(features)
coords = np.asarray(coords).astype(np.int64)
M, D = features.shape
patch_step = self._infer_patch_step(coords)
coord_min = coords.min(axis=0, keepdims=True)
grid_coords = ((coords - coord_min) // patch_step).astype(np.int64)
grid_h = int(grid_coords[:, 0].max()) + 1
grid_w = int(grid_coords[:, 1].max()) + 1
if start_h is None:
if self.ssl_train or self.vl_train:
if grid_h >= crop_size:
start_h = np.random.randint(0, grid_h - crop_size + 1)
else:
start_h = -np.random.randint(0, crop_size - grid_h + 1)
else:
start_h = (grid_h - crop_size) // 2
if start_w is None:
if self.ssl_train or self.vl_train:
if grid_w >= crop_size:
start_w = np.random.randint(0, grid_w - crop_size + 1)
else:
start_w = -np.random.randint(0, crop_size - grid_w + 1)
else:
start_w = (grid_w - crop_size) // 2
end_h = start_h + crop_size
end_w = start_w + crop_size
keep = (
(grid_coords[:, 0] >= start_h) & (grid_coords[:, 0] < end_h) &
(grid_coords[:, 1] >= start_w) & (grid_coords[:, 1] < end_w)
)
crop_features = np.zeros((crop_size * crop_size, D), dtype=features.dtype)
crop_h = np.arange(start_h, end_h)
crop_w = np.arange(start_w, end_w)
mesh_h, mesh_w = np.meshgrid(crop_h, crop_w, indexing="ij")
crop_grid_coords = np.stack(
[mesh_h.reshape(-1), mesh_w.reshape(-1)],
axis=1
)
crop_coords = coord_min + crop_grid_coords * patch_step
crop_coords = crop_coords.astype(coords.dtype)
if keep.any():
kept_grid = grid_coords[keep]
local_h = kept_grid[:, 0] - start_h
local_w = kept_grid[:, 1] - start_w
flat_idx = local_h * crop_size + local_w
crop_features[flat_idx] = features[keep]
return crop_features, crop_coords
@staticmethod
def _coverage_starts(grid_size, crop_size):
if grid_size <= crop_size:
return [0]
num_views = int(math.ceil(float(grid_size) / float(crop_size)))
return np.linspace(0, grid_size - crop_size, num_views).round().astype(np.int64).tolist()
def _cover_eval_2d_views(self, features, coords, crop_size):
features = np.asarray(features)
coords = np.asarray(coords).astype(np.int64)
patch_step = self._infer_patch_step(coords)
coord_min = coords.min(axis=0, keepdims=True)
grid_coords = ((coords - coord_min) // patch_step).astype(np.int64)
grid_h = int(grid_coords[:, 0].max()) + 1
grid_w = int(grid_coords[:, 1].max()) + 1
h_starts = self._coverage_starts(grid_h, crop_size)
w_starts = self._coverage_starts(grid_w, crop_size)
feat_views, coord_views = [], []
for start_h in h_starts:
for start_w in w_starts:
crop_features, crop_coords = self._crop_2d_features(
features,
coords,
crop_size=crop_size,
start_h=int(start_h),
start_w=int(start_w),
)
feat_views.append(crop_features)
coord_views.append(crop_coords)
return np.stack(feat_views, axis=0), np.stack(coord_views, axis=0)
def _pad_to_min_square(self, features, coords, target_side=None):
features = np.asarray(features)
coords = np.asarray(coords).astype(np.int64)
M, D = features.shape
min_side = int(math.ceil(math.sqrt(M)))
side = min_side if target_side is None else max(int(target_side), min_side)
target_num = side * side
if target_num == M:
return features, coords
padded_features = np.zeros((target_num, D), dtype=features.dtype)
padded_coords = np.zeros((target_num, 2), dtype=coords.dtype)
padded_features[:M] = features
padded_coords[:M] = coords
patch_step = self._infer_patch_step(coords)
coord_min = coords.min(axis=0, keepdims=True)
grid_coords = ((coords - coord_min) // patch_step).astype(np.int64)
grid_h = int(grid_coords[:, 0].max()) + 1
grid_w = int(grid_coords[:, 1].max()) + 1
used = set((int(x), int(y)) for x, y in grid_coords)
fill_idx = M
for x in range(max(side, grid_h)):
for y in range(max(side, grid_w)):
if fill_idx >= target_num:
break
if (x, y) in used:
continue
padded_coords[fill_idx] = coord_min.reshape(2) + np.array([x, y], dtype=coords.dtype) * patch_step
fill_idx += 1
if fill_idx >= target_num:
break
if fill_idx < target_num:
padded_coords[fill_idx:] = coords[-1]
return padded_features, padded_coords
def _prepare_eval_2d_features(self, features, coords):
# if self.eval_crop_size is None:
# return self._pad_to_min_square(features, coords)
coords_np = np.asarray(coords).astype(np.int64)
patch_step = self._infer_patch_step(coords_np)
coord_min = coords_np.min(axis=0, keepdims=True)
grid_coords = ((coords_np - coord_min) // patch_step).astype(np.int64)
grid_h = int(grid_coords[:, 0].max()) + 1
grid_w = int(grid_coords[:, 1].max()) + 1
if self.eval_crop_size_range is not None:
min_eval_crop_size = int(self.eval_crop_size_range[0]) # 80 for no varying setting
if grid_h <= min_eval_crop_size and grid_w <= min_eval_crop_size:
return self._pad_to_min_square(features, coords)
crop_size = 80 #self._best_eval_crop_size(grid_h, grid_w) # best size for variant size training, bad performance
if grid_h > crop_size or grid_w > crop_size:
return self._cover_eval_2d_views(
features,
coords,
crop_size=crop_size,
)
else:
target_side = crop_size if self.eval_crop_size_range is not None else None
return self._pad_to_min_square(features, coords, target_side=target_side)