Wuhuwill commited on
Commit
07335f2
·
verified ·
1 Parent(s): 57710e5

Upload ProDiff/Experiments/trajectory_exp_may_data_TKY_len3_ddpm_20250724-100624/code_snapshot/utils.py with huggingface_hub

Browse files
ProDiff/Experiments/trajectory_exp_may_data_TKY_len3_ddpm_20250724-100624/code_snapshot/utils.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def update_npy(file_path, data):
217
+ if os.path.exists(file_path):
218
+ existing_data = np.load(file_path, allow_pickle=True).item()
219
+ existing_data.update(data)
220
+ else:
221
+ existing_data = data
222
+ np.save(file_path, existing_data)
223
+
224
+
225
+ def haversine(lat1, lon1, lat2, lon2):
226
+ # Convert degrees to radians
227
+ lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2])
228
+
229
+ # Haversine formula
230
+ dlat = lat2 - lat1
231
+ dlon = lon2 - lon1
232
+ a = np.sin(dlat / 2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2.0)**2
233
+ c = 2 * np.arcsin(np.sqrt(a))
234
+ r = 6371 # Radius of Earth in kilometers
235
+ return c * r * 1000 # Return distance in meters
236
+
237
+ def get_data_paths(data_config, for_train=True):
238
+ """Get the file paths for training or testing data for TKY-like structure.
239
+ Assumes data_config.traj_path1 points to a directory containing train.h5 and test.h5.
240
+ """
241
+ base_path = data_config.traj_path1
242
+ if not isinstance(base_path, str):
243
+ base_path = str(base_path)
244
+
245
+ if for_train:
246
+
247
+ file_path = os.path.join(base_path, "train.h5")
248
+ else:
249
+ file_path = os.path.join(base_path, "test.h5")
250
+
251
+
252
+ return [file_path]