File size: 7,565 Bytes
8850d81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""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)