jasonkena commited on
Commit
d4c5d25
·
verified ·
1 Parent(s): b1bc056

Upload dataloader.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. dataloader.py +366 -0
dataloader.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List, Optional, Callable
3
+ from functools import partial
4
+
5
+ import numpy as np
6
+ import torch
7
+ from scipy.interpolate import UnivariateSpline
8
+
9
+
10
+ def smooth_3d_array(points, num=None, **kwargs):
11
+ x, y, z = points[:, 0], points[:, 1], points[:, 2]
12
+ points = np.zeros((num, 3))
13
+ if num is None:
14
+ num = len(x)
15
+ w = np.arange(0, len(x), 1)
16
+ sx = UnivariateSpline(w, x, **kwargs)
17
+ sy = UnivariateSpline(w, y, **kwargs)
18
+ sz = UnivariateSpline(w, z, **kwargs)
19
+ wnew = np.linspace(0, len(x), num)
20
+ points[:, 0] = sx(wnew)
21
+ points[:, 1] = sy(wnew)
22
+ points[:, 2] = sz(wnew)
23
+ return points
24
+
25
+
26
+ def calculate_tnb_frame(curve, epsilon=1e-8):
27
+ curve = np.asarray(curve)
28
+
29
+ # Calculate T (tangent)
30
+ T = np.gradient(curve, axis=0)
31
+ T_norms = np.linalg.norm(T, axis=1)
32
+ T = T / T_norms[:, np.newaxis]
33
+
34
+ # Identify straight segments
35
+ is_straight = T_norms < epsilon
36
+
37
+ # Calculate N (normal) for non-straight parts
38
+ dT = np.gradient(T, axis=0)
39
+ N = dT - np.sum(dT * T, axis=1)[:, np.newaxis] * T
40
+ N_norms = np.linalg.norm(N, axis=1)
41
+
42
+ # Handle points where the normal is undefined or in straight segments
43
+ undefined_N = (N_norms < epsilon) | is_straight
44
+
45
+ if np.all(undefined_N):
46
+ # print("the entire curve is straight")
47
+ # If the entire curve is straight, choose an arbitrary normal
48
+ N = np.zeros_like(T)
49
+ N[:, 0] = T[:, 1]
50
+ N[:, 1] = -T[:, 0]
51
+ N = N / np.linalg.norm(N, axis=1)[:, np.newaxis]
52
+ elif np.any(undefined_N):
53
+ # print("handling straight parts")
54
+ # Only proceed with interpolation if there are any straight parts
55
+ # Find segments of curved and straight parts
56
+ segment_changes = np.where(np.diff(undefined_N))[0] + 1
57
+ segments = np.split(np.arange(len(curve)), segment_changes)
58
+
59
+ for segment in segments:
60
+ if undefined_N[segment[0]]:
61
+ # This is a straight segment
62
+ left_curved = np.where(~undefined_N[: segment[0]])[0]
63
+ right_curved = (
64
+ np.where(~undefined_N[segment[-1] + 1 :])[0] + segment[-1] + 1
65
+ )
66
+
67
+ if len(left_curved) > 0 and len(right_curved) > 0:
68
+ # Interpolate between left and right curved parts
69
+ left_N = N[left_curved[-1]]
70
+ right_N = N[right_curved[0]]
71
+ t = np.linspace(0, 1, len(segment))
72
+ N[segment] = (1 - t[:, np.newaxis]) * left_N + t[
73
+ :, np.newaxis
74
+ ] * right_N
75
+ elif len(left_curved) > 0:
76
+ # Use normal from left curved part
77
+ N[segment] = N[left_curved[-1]]
78
+ elif len(right_curved) > 0:
79
+ # Use normal from right curved part
80
+ N[segment] = N[right_curved[0]]
81
+ else:
82
+ # No curved parts found, use arbitrary normal
83
+ N[segment] = np.array([T[segment[0]][1], -T[segment[0]][0], 0])
84
+
85
+ # Ensure N is perpendicular to T
86
+ N[segment] = (
87
+ N[segment]
88
+ - np.sum(N[segment] * T[segment], axis=1)[:, np.newaxis]
89
+ * T[segment]
90
+ )
91
+ N[segment] = (
92
+ N[segment] / np.linalg.norm(N[segment], axis=1)[:, np.newaxis]
93
+ )
94
+ else:
95
+ # print("no straight parts")
96
+ pass
97
+
98
+ # If there are no straight parts, N is already calculated correctly for all points
99
+
100
+ # Calculate B (binormal) ensuring orthogonality
101
+ B = np.cross(T, N)
102
+
103
+ # Ensure perfect orthogonality through Gram-Schmidt
104
+ N = N - np.sum(N * T, axis=1)[:, np.newaxis] * T
105
+ N = N / np.linalg.norm(N, axis=1)[:, np.newaxis]
106
+
107
+ B = B - np.sum(B * T, axis=1)[:, np.newaxis] * T
108
+ B = B - np.sum(B * N, axis=1)[:, np.newaxis] * N
109
+ B = B / np.linalg.norm(B, axis=1)[:, np.newaxis]
110
+
111
+ return T, N, B
112
+
113
+
114
+ def get_closest(pc_a, pc_b):
115
+ """
116
+ For each point in pc_a, find the closest point in pc_b
117
+ Returns the distance and index of the closest point in pc_b for each point in pc_a
118
+ Parameters
119
+ ----------
120
+ pc_a : [Mx3]
121
+ pc_b : [Nx3]
122
+ """
123
+ tree = KDTree(pc_b)
124
+ dist, idx = tree.query(pc_a, workers=-1)
125
+
126
+ if np.max(idx) >= pc_b.shape[0]:
127
+ raise ValueError("idx is out of range")
128
+
129
+ return dist, idx
130
+
131
+
132
+ def straighten_using_frenet(helix, points):
133
+ """
134
+ Straighten the structure based on the helix (skeleton) using the Frenet frame.
135
+
136
+ Args:
137
+ - helix (numpy array): Points forming the helix (skeleton).
138
+ - points (numpy array): Points surrounding the helix.
139
+
140
+ Returns:
141
+ - straightened_helix (numpy array): Straightened version of the helix.
142
+ - straightened_points (numpy array): Transformed surrounding points.
143
+ """
144
+ # Compute the Frenet frame for the helix
145
+ T, N, B = calculate_tnb_frame(helix)
146
+
147
+ # Parameterize the helix based on cumulative distance (arclength)
148
+ deltas = np.diff(helix, axis=0)
149
+ distances = np.linalg.norm(deltas, axis=1)
150
+ cumulative_distances = np.insert(np.cumsum(distances), 0, 0)
151
+
152
+ # Map helix to a straight line along Z-axis
153
+ straightened_helix = np.column_stack(
154
+ (
155
+ np.zeros_like(cumulative_distances),
156
+ np.zeros_like(cumulative_distances),
157
+ cumulative_distances,
158
+ )
159
+ )
160
+
161
+ distances_to_helix, closest_idxs = get_closest(points, helix)
162
+ vectors = points - helix[closest_idxs]
163
+ r = distances_to_helix
164
+ T_closest = T[closest_idxs]
165
+ N_closest = N[closest_idxs]
166
+ B_closest = B[closest_idxs]
167
+ theta = np.arctan2(
168
+ np.einsum("ij,ij->i", vectors, N_closest),
169
+ np.einsum("ij,ij->i", vectors, B_closest),
170
+ )
171
+ phi = np.arccos(np.einsum("ij,ij->i", vectors, T_closest) / r)
172
+ x = r * np.sin(phi) * np.cos(theta)
173
+ y = r * np.sin(phi) * np.sin(theta)
174
+ z = cumulative_distances[closest_idxs] + r * np.cos(phi)
175
+ straightened_points = np.column_stack((x, y, z))
176
+
177
+ return straightened_helix, np.array(straightened_points)
178
+
179
+
180
+ def frenet_transformation(pc, skel, lb):
181
+ skel_smooth = smooth_3d_array(skel, num=skel.shape[0] * 100, s=200000)
182
+ skel_trans, pc_trans = straighten_using_frenet(skel_smooth, pc)
183
+ return pc_trans, skel_trans, lb
184
+
185
+
186
+ def transformation(trunk_id, pc, trunk_pc, label, frenet: bool):
187
+ """
188
+ Normalize the point cloud to unit sphere
189
+ do frenet transformation
190
+
191
+ Parameters
192
+ ----------
193
+ trunk_id : int
194
+ pc
195
+ trunk_pc
196
+ label
197
+ frenet : whether not to do FreNet transformation
198
+ """
199
+
200
+ unmodified_pc = pc.copy()
201
+ if frenet:
202
+ pc, trunk_pc, label = frenet_transformation(pc, trunk_pc, label)
203
+
204
+ # NOTE: trunk_pc has variable length and cannot be collated using default_collate
205
+ # normalize [N, 3] to unit sphere
206
+ pc = pc - np.mean(pc, axis=0)
207
+ m = np.max(np.sqrt(np.sum(pc**2, axis=1)))
208
+ pc = pc / m
209
+
210
+ # cast to int
211
+ label = label.astype(int)
212
+
213
+ return trunk_id, pc, label, unmodified_pc
214
+
215
+
216
+ class CachedDataset:
217
+ def __init__(
218
+ self,
219
+ output_path: str,
220
+ num_points: int,
221
+ folds: List[List[int]],
222
+ fold: int,
223
+ is_train: bool,
224
+ transform: Optional[Callable] = None,
225
+ ):
226
+ self.num_points = num_points
227
+ self.transform = transform
228
+ self.spanning_paths = np.load(
229
+ os.path.join(output_path, "spanning_paths.npz"), allow_pickle=True
230
+ )["spanning_paths"].item()
231
+
232
+ if fold == -1:
233
+ print("Loading all folds, ignoring is_train")
234
+ trunk_ids = self.spanning_paths.keys()
235
+ else:
236
+ if is_train:
237
+ trunk_ids = [
238
+ item
239
+ for idx, sublist in enumerate(folds)
240
+ if idx != fold
241
+ for item in sublist
242
+ ]
243
+ else:
244
+ trunk_ids = folds[fold]
245
+ self.trunk_ids = sorted(trunk_ids)
246
+
247
+ files = []
248
+ i = 0
249
+ for id in sorted(self.spanning_paths.keys()):
250
+ for path in self.spanning_paths[id]:
251
+ if id in self.trunk_ids:
252
+ files.append(os.path.join(output_path, f"{i}.npz"))
253
+ assert os.path.exists(files[-1])
254
+ i += 1
255
+ self.files = files
256
+
257
+ def __len__(self):
258
+ return len(self.files)
259
+
260
+ def __getitem__(self, idx):
261
+ data = np.load(self.files[idx])
262
+ trunk_id, pc, trunk_pc, label = (
263
+ data["trunk_id"],
264
+ data["pc"],
265
+ data["trunk_pc"],
266
+ data["label"],
267
+ )
268
+ assert trunk_id in self.trunk_ids
269
+
270
+ # PC is [N, 3], downsample to [num_points, 3]
271
+ random_permutation = np.random.permutation(pc.shape[0])
272
+ pc = pc[random_permutation[: self.num_points]]
273
+ label = label[random_permutation[: self.num_points]]
274
+
275
+ if self.transform is None:
276
+ return trunk_id, pc, trunk_pc, label
277
+ else:
278
+ return self.transform(trunk_id, pc, trunk_pc, label)
279
+
280
+
281
+ def get_dataloader(
282
+ species: str,
283
+ num_points: int,
284
+ fold: int,
285
+ is_train: bool,
286
+ batch_size: int,
287
+ num_workers: int,
288
+ frenet: bool,
289
+ distributed: bool = False,
290
+ collate_fn: Optional[Callable] = None,
291
+ path_length=10000,
292
+ ):
293
+ """
294
+ Returns FreSeg dataloader for the given species and fold
295
+
296
+ Parameters
297
+ ----------
298
+ species: one of ["seg_den", "mouse", "human"]
299
+ num_points: number of points to sample from the point cloud
300
+ fold: -1 to fetch all folds, 0-4 for seg_den
301
+ is_train: bool
302
+ batch_size
303
+ num_workers
304
+ frenet: whether to do FreNet transformation
305
+ distributed: bool
306
+ collate_fn
307
+ path_length : fixed length of skeleton path (not configurable)
308
+ """
309
+
310
+ assert species in ["seg_den", "mouse", "human"]
311
+ seg_den_folds = [
312
+ [3, 5, 11, 12, 23, 28, 29, 32, 39, 42],
313
+ [8, 15, 19, 27, 30, 34, 35, 36, 46, 49],
314
+ [9, 14, 16, 17, 21, 26, 31, 33, 43, 44],
315
+ [2, 6, 7, 13, 18, 24, 25, 38, 41, 50],
316
+ [1, 4, 10, 20, 22, 37, 40, 45, 47, 48],
317
+ ]
318
+
319
+ if species != "seg_den":
320
+ assert (
321
+ fold == -1
322
+ ), "Fold must be -1 for mouse and human datasets, since no splits"
323
+
324
+ dataset = CachedDataset(
325
+ f"{species}_1000000_{path_length}",
326
+ num_points=num_points,
327
+ folds=seg_den_folds if species == "seg_den" else [],
328
+ fold=fold,
329
+ is_train=is_train,
330
+ transform=partial(transformation, frenet=frenet),
331
+ )
332
+
333
+ dataloader = torch.utils.data.DataLoader(
334
+ dataset,
335
+ batch_size=batch_size,
336
+ shuffle=is_train and not distributed,
337
+ num_workers=num_workers,
338
+ pin_memory=True,
339
+ drop_last=is_train,
340
+ sampler=torch.utils.data.DistributedSampler(dataset) if distributed else None,
341
+ collate_fn=collate_fn,
342
+ )
343
+
344
+ return dataloader, dataset.files
345
+
346
+
347
+ if __name__ == "__main__":
348
+ human_loader, _ = get_dataloader(
349
+ species="human",
350
+ num_points=1024,
351
+ fold=-1,
352
+ is_train=True,
353
+ batch_size=32,
354
+ num_workers=8,
355
+ frenet=False,
356
+ )
357
+ for i, data in enumerate(human_loader):
358
+ trunk_id, pc, label, original_pc = data
359
+ """
360
+ trunk_id: array of trunk ids of length batch_size
361
+ pc: point cloud in isotropic coordinates, modified using transformation(), shape [batch, num_points, 3]
362
+ label: corresponding value of seg volume at that point, shape [batch, num_points]
363
+ will be 0 if part of trunk, unique spine segment id otherwise
364
+ original_pc: point cloud in isotropic coordinates, unmodified, shape [batch, num_points, 3]
365
+ """
366
+ pass