Wuhuwill commited on
Commit
0a027c9
·
verified ·
1 Parent(s): 2946f88

Upload ProDiff/utils/utils.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. ProDiff/utils/utils.py +374 -0
ProDiff/utils/utils.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import sin, cos, sqrt, atan2, radians, asin
2
+ import numpy as np
3
+ import torch
4
+ import os
5
+ from torch.distributed import init_process_group, destroy_process_group
6
+ import torch.nn.functional as F
7
+ import random
8
+ def resample_trajectory(x, length=200):
9
+ """
10
+ Resamples a trajectory to a new length.
11
+
12
+ Parameters:
13
+ x (np.ndarray): original trajectory, shape (N, 2)
14
+ length (int): length of resampled trajectory
15
+
16
+ Returns:
17
+ np.ndarray: resampled trajectory, shape (length, 2)
18
+ """
19
+ len_x = len(x)
20
+ time_steps = np.arange(length) * (len_x - 1) / (length - 1)
21
+ x = x.T
22
+ resampled_trajectory = np.zeros((2, length))
23
+ for i in range(2):
24
+ resampled_trajectory[i] = np.interp(time_steps, np.arange(len_x), x[i])
25
+ return resampled_trajectory.T
26
+
27
+
28
+ def time_warping(x, length=200):
29
+ """
30
+ Resamples a trajectory to a new length.
31
+ """
32
+ len_x = len(x)
33
+ time_steps = np.arange(length) * (len_x - 1) / (length - 1)
34
+ x = x.T
35
+ warped_trajectory = np.zeros((2, length))
36
+ for i in range(2):
37
+ warped_trajectory[i] = np.interp(time_steps, np.arange(len_x), x[i])
38
+ return warped_trajectory.T
39
+
40
+
41
+ def gather(consts: torch.Tensor, t: torch.Tensor):
42
+ """
43
+ Gather consts for $t$ and reshape to feature map shape
44
+ :param consts: (N, 1, 1)
45
+ :param t: (N, H, W)
46
+ :return: (N, H, W)
47
+ """
48
+ c = consts.gather(-1, t)
49
+ return c.reshape(-1, 1, 1)
50
+
51
+
52
+ def q_xt_x0(x0, t, alpha_bar):
53
+ # get mean and variance of xt given x0
54
+ mean = gather(alpha_bar, t) ** 0.5 * x0
55
+ var = 1 - gather(alpha_bar, t)
56
+ # sample xt from q(xt | x0)
57
+ eps = torch.randn_like(x0).to(x0.device)
58
+ xt = mean + (var ** 0.5) * eps
59
+ return xt, eps # also return noise
60
+
61
+
62
+ def compute_alpha(beta, t):
63
+ beta = torch.cat([torch.zeros(1).to(beta.device), beta], dim=0)
64
+ a = (1 - beta).cumprod(dim=0).index_select(0, t + 1).view(-1, 1, 1)
65
+ return a
66
+
67
+
68
+ def p_xt(xt, noise, t, next_t, beta, eta=0):
69
+ at = compute_alpha(beta.cuda(), t.long())
70
+ at_next = compute_alpha(beta, next_t.long())
71
+ x0_t = (xt - noise * (1 - at).sqrt()) / at.sqrt()
72
+ c1 = (eta * ((1 - at / at_next) * (1 - at_next) / (1 - at)).sqrt())
73
+ c2 = ((1 - at_next) - c1 ** 2).sqrt()
74
+ eps = torch.randn(xt.shape, device=xt.device)
75
+ xt_next = at_next.sqrt() * x0_t + c1 * eps + c2 * noise
76
+ return xt_next
77
+
78
+
79
+ def divide_grids(boundary, grids_num):
80
+ lati_min, lati_max = boundary['lati_min'], boundary['lati_max']
81
+ long_min, long_max = boundary['long_min'], boundary['long_max']
82
+ # Divide the latitude and longitude into grids_num intervals.
83
+ lati_interval = (lati_max - lati_min) / grids_num
84
+ long_interval = (long_max - long_min) / grids_num
85
+ # Create arrays of latitude and longitude values.
86
+ latgrids = np.arange(lati_min, lati_max, lati_interval)
87
+ longrids = np.arange(long_min, long_max, long_interval)
88
+ return latgrids, longrids
89
+
90
+
91
+ # calculate the distance between two points
92
+ def distance(lat1, lon1, lat2, lon2):
93
+ """
94
+ Calculate the great circle distance between two points
95
+ on the earth (specified in decimal degrees)
96
+ """
97
+ # convert decimal degrees to radians
98
+ lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
99
+ # haversine formula
100
+ dlon = lon2 - lon1
101
+ dlat = lat2 - lat1
102
+ a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
103
+ c = 2 * asin(sqrt(a))
104
+ r = 6371 # Radius of earth in kilometers. Use 3956 for miles
105
+ return c * r * 1000
106
+
107
+ def set_seed(seed):
108
+ random.seed(seed)
109
+ np.random.seed(seed)
110
+ torch.manual_seed(seed)
111
+ if torch.cuda.is_available():
112
+ torch.cuda.manual_seed(seed)
113
+ torch.cuda.manual_seed_all(seed)
114
+ torch.backends.cudnn.deterministic = True
115
+ torch.backends.cudnn.benchmark = False
116
+
117
+ def ddp_setup():
118
+ init_process_group(backend="nccl")
119
+ torch.cuda.set_device(int(os.environ['LOCAL_RANK']))
120
+
121
+
122
+ def destroy_process_group():
123
+ destroy_process_group()
124
+
125
+
126
+ import torch
127
+
128
+ class IterativeKMeans:
129
+ def __init__(self, num_clusters, device, num_iters=100, tol=1e-4):
130
+ self.num_clusters = num_clusters
131
+ self.num_iters = num_iters
132
+ self.tol = tol
133
+ self.cluster_centers = None
134
+ self.labels = None
135
+ self.device = device
136
+
137
+ def fit(self, X):
138
+ # X = torch.tensor(X, dtype=torch.float32).to(self.device)
139
+ X = X.clone().detach().to(self.device)
140
+ num_samples, num_features = X.shape
141
+ indices = torch.randperm(num_samples)[:self.num_clusters]
142
+ self.cluster_centers = X[indices].clone().detach()
143
+ self.labels = torch.argmin(torch.cdist(X, self.cluster_centers), dim=1).cpu().numpy()
144
+
145
+ for _ in range(self.num_iters):
146
+ distances = torch.cdist(X, self.cluster_centers)
147
+ labels = torch.argmin(distances, dim=1)
148
+ # new_cluster_centers = torch.stack([X[labels == i].mean(dim=0) for i in range(self.num_clusters)])
149
+ new_cluster_centers = torch.stack([X[labels == i].mean(dim=0) if (labels == i).sum() > 0 else self.cluster_centers[i] for i in range(self.num_clusters)])
150
+ center_shift = torch.norm(new_cluster_centers - self.cluster_centers, dim=1).sum().item()
151
+ if center_shift < self.tol:
152
+ break
153
+ self.cluster_centers = new_cluster_centers
154
+
155
+ self.labels = labels.cpu().numpy()
156
+ return self.cluster_centers, self.labels
157
+
158
+ def update(self, new_X, original_X):
159
+ combined_X = torch.cat([original_X, new_X], dim=0)
160
+ combined_X = combined_X.clone().detach().to(self.device)
161
+
162
+ for _ in range(self.num_iters):
163
+ distances = torch.cdist(combined_X, self.cluster_centers)
164
+ labels = torch.argmin(distances, dim=1)
165
+ new_cluster_centers = torch.stack([combined_X[labels == i].mean(dim=0) if (labels == i).sum() > 0 else self.cluster_centers[i] for i in range(self.num_clusters)])
166
+ center_shift = torch.norm(new_cluster_centers - self.cluster_centers, dim=1).sum().item()
167
+ if center_shift < self.tol:
168
+ break
169
+ self.cluster_centers = new_cluster_centers
170
+
171
+ self.labels = labels.cpu().numpy()
172
+ return self.cluster_centers, self.labels
173
+
174
+ def predict(self, X):
175
+ # X = torch.tensor(X, dtype=torch.float32).to(self.device)
176
+ X = X.clone().detach().to(self.device)
177
+ distances = torch.cdist(X, self.cluster_centers)
178
+ labels = torch.argmin(distances, dim=1)
179
+ return labels
180
+
181
+ def to(self, device):
182
+ self.device = device
183
+ if self.cluster_centers is not None:
184
+ self.cluster_centers = self.cluster_centers.to(device)
185
+ return self
186
+
187
+
188
+ def assign_labels(prototypes, features):
189
+ # Calculate pairwise distances between all features and prototypes
190
+ distances = F.pairwise_distance(features.unsqueeze(1), prototypes.unsqueeze(0))
191
+ # Find the index of the prototype with the minimum distance (on the second dimension)
192
+ labels = torch.argmin(distances, dim=-1)
193
+
194
+ return labels
195
+
196
+
197
+ def get_positive_negative_pairs(prototypes, samples):
198
+ positive_pairs = []
199
+ negative_pairs = []
200
+ for sample in samples:
201
+ distances = F.pairwise_distance(sample.unsqueeze(0), prototypes)
202
+ pos_idx = torch.argmin(distances).item()
203
+ neg_idx = torch.argmax(distances).item()
204
+ positive_pairs.append(prototypes[pos_idx])
205
+ negative_pairs.append(prototypes[neg_idx])
206
+ return torch.stack(positive_pairs), torch.stack(negative_pairs)
207
+
208
+
209
+
210
+ def mask_data_general(x: torch.Tensor):
211
+ """Mask the input data"""
212
+ mask = torch.ones_like(x)
213
+ mask[:, :, 1:-1] = 0
214
+ return x * mask.float()
215
+
216
+
217
+ def continuous_mask_data(x: torch.Tensor, mask_ratio: float = 0.5):
218
+ """
219
+ Mask a continuous block of the input data.
220
+ It keeps the first and last elements unmasked.
221
+ """
222
+ mask = torch.ones_like(x)
223
+
224
+ traj_length = x.shape[2]
225
+ if traj_length <= 2:
226
+ return x * mask.float()
227
+
228
+ masked_length = int((traj_length - 2) * mask_ratio)
229
+ if masked_length == 0:
230
+ return x * mask.float()
231
+
232
+ # The start of the mask is between the first and the last but one element.
233
+ # The selection ensures that the mask does not run over the second to last element.
234
+ mask_start = random.randint(1, traj_length - 2 - masked_length)
235
+ mask_end = mask_start + masked_length
236
+
237
+ mask[:, :, mask_start:mask_end] = 0
238
+ return x * mask.float()
239
+
240
+
241
+ def update_npy(file_path, data):
242
+ if os.path.exists(file_path):
243
+ existing_data = np.load(file_path, allow_pickle=True).item()
244
+ existing_data.update(data)
245
+ else:
246
+ existing_data = data
247
+ np.save(file_path, existing_data)
248
+
249
+
250
+ def haversine(lat1, lon1, lat2, lon2):
251
+ # Convert degrees to radians
252
+ lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2])
253
+
254
+ # Haversine formula
255
+ dlat = lat2 - lat1
256
+ dlon = lon2 - lon1
257
+ a = np.sin(dlat / 2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2.0)**2
258
+ c = 2 * np.arcsin(np.sqrt(a))
259
+ r = 6371 # Radius of Earth in kilometers
260
+ return c * r * 1000 # Return distance in meters
261
+
262
+
263
+ def continuous_time_based_mask(x: torch.Tensor, points_to_mask: int):
264
+ """
265
+ Mask a continuous block of the input data based on a fixed number of points.
266
+ It keeps the first and last elements unmasked.
267
+
268
+ Args:
269
+ x (torch.Tensor): Input tensor of shape (batch, features, length).
270
+ points_to_mask (int): The number of continuous points to mask.
271
+ """
272
+ mask = torch.ones_like(x)
273
+
274
+ traj_length = x.shape[2]
275
+ # 确保有足够的点可以遮蔽 (首尾点+遮蔽段)
276
+ if traj_length <= points_to_mask + 2:
277
+ # 如果轨迹太短,无法满足遮蔽要求,则不进行遮蔽
278
+ return x * mask.float()
279
+
280
+ # 随机选择遮蔽的起始位置
281
+ # 起始位置必须在第一个点之后,并确保遮蔽段不会超出倒数第二个点
282
+ mask_start = random.randint(1, traj_length - 1 - points_to_mask)
283
+ mask_end = mask_start + points_to_mask
284
+
285
+ mask[:, :, mask_start:mask_end] = 0
286
+ return x * mask.float()
287
+
288
+
289
+ def mask_multiple_segments(x: torch.Tensor, points_per_segment: list):
290
+ """
291
+ Mask multiple non-overlapping continuous segments in the input data.
292
+ Keeps the first and last elements unmasked.
293
+
294
+ Args:
295
+ x (torch.Tensor): Input tensor of shape (batch, features, length).
296
+ points_per_segment (list of int): List containing the length of each segment to mask.
297
+ """
298
+ mask = torch.ones_like(x)
299
+ traj_length = x.shape[2]
300
+
301
+ # Sort segments by length, descending, to place larger gaps first
302
+ segments = sorted(points_per_segment, reverse=True)
303
+ total_mask_points = sum(segments)
304
+
305
+ # Check if there's enough space for all masks and endpoints
306
+ if traj_length < total_mask_points + 2:
307
+ return x * mask.float()
308
+
309
+ # Generate a list of all possible start indices for masking
310
+ # Exclude first and last points: [1, ..., traj_length-2]
311
+ possible_indices = list(range(1, traj_length - 1))
312
+
313
+ masked_intervals = []
314
+
315
+ for seg_length in segments:
316
+ # Find valid start positions for the current segment
317
+ valid_starts = []
318
+ for i in possible_indices:
319
+ # A start is valid if the segment [i, i + seg_length) does not overlap with existing masked intervals
320
+ # and does not go out of bounds
321
+ if i + seg_length > traj_length - 1:
322
+ continue
323
+
324
+ is_valid = True
325
+ for start, end in masked_intervals:
326
+ # Check for overlap: [i, i+seg_length) vs [start, end)
327
+ if not (i + seg_length <= start or i >= end):
328
+ is_valid = False
329
+ break
330
+ if is_valid:
331
+ valid_starts.append(i)
332
+
333
+ if not valid_starts:
334
+ # Not enough space for this segment, continue to next (smaller) one
335
+ continue
336
+
337
+ # Choose a random start position and apply the mask
338
+ start_pos = random.choice(valid_starts)
339
+ end_pos = start_pos + seg_length
340
+ mask[:, :, start_pos:end_pos] = 0
341
+
342
+ # Record the masked interval and remove these indices from possible choices
343
+ masked_intervals.append((start_pos, end_pos))
344
+
345
+ # Update possible_indices by removing the masked range
346
+ indices_to_remove = set(range(start_pos, end_pos))
347
+ possible_indices = [idx for idx in possible_indices if idx not in indices_to_remove]
348
+
349
+ return x * mask.float()
350
+
351
+ def get_data_paths(data_config, for_train=True):
352
+ """Get the file paths for training or testing data for TKY-like structure.
353
+ Assumes data_config.traj_path1 points to a directory containing train.h5 and test.h5.
354
+ """
355
+
356
+ base_path = data_config.traj_path1
357
+ if not isinstance(base_path, str):
358
+ base_path = str(base_path)
359
+
360
+ # Check if we're using temporal split data
361
+ if hasattr(data_config, 'dataset') and 'temporal' in data_config.dataset:
362
+ if for_train:
363
+ file_path = os.path.join(base_path, "train_temporal.h5")
364
+ else:
365
+ file_path = os.path.join(base_path, "test_temporal.h5")
366
+ else:
367
+ # Use the original file names
368
+ if for_train:
369
+ file_path = os.path.join(base_path, "train.h5")
370
+ else:
371
+ file_path = os.path.join(base_path, "test.h5")
372
+
373
+
374
+ return [file_path]