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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
| import argparse
from typing import Optional, Union
import torch
import torch.nn as nn
import yaml
from sssd.core.model_specs import MODEL_PATH_FORMAT, setup_model
from sssd.data.utils import get_dataloader
from sssd.inference.generator import DiffusionGenerator
from sssd.utils.logger import setup_logger
from sssd.utils.utils import calc_diffusion_hyperparams, display_current_time
import numpy as np
import torch
import torch.nn as nn
from scipy.integrate import quad
from scipy.sparse.linalg import eigsh
from typing import Optional, Union
LOGGER = setup_logger()
def fetch_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument(
"-m",
"--model_config",
type=str,
default="configs/model.yaml",
help="Model configuration",
)
parser.add_argument(
"-i",
"--inference_config",
type=str,
default="configs/inference_config.yaml",
help="Inference configuration",
)
parser.add_argument(
"-ckpt_iter",
"--ckpt_iter",
default="max",
help='Which checkpoint to use; assign a number or "max" to find the latest checkpoint',
)
return parser.parse_args()
# New function to load locations
def get_locations_loader(location_path, device: torch.device) -> torch.Tensor:
locations = np.load(location_path)
locations_tensor = torch.from_numpy(locations).float().to(device)
return locations_tensor
def run_job(
model_config: dict,
inference_config: dict,
device: Optional[Union[torch.device, str]],
ckpt_iter: Union[str, int],
) -> None:
trials = inference_config.get("trials")
batch_size = inference_config["batch_size"]
dataloader = get_dataloader(
inference_config["data"]["test_path"],
batch_size,
device=device,
)
local_path = MODEL_PATH_FORMAT.format(
T=model_config["diffusion"]["T"],
beta_0=model_config["diffusion"]["beta_0"],
beta_T=model_config["diffusion"]["beta_T"],
)
diffusion_hyperparams = calc_diffusion_hyperparams(
**model_config["diffusion"], device=device
)
LOGGER.info(display_current_time())
locs = get_locations_loader(inference_config["data"]["location_path"], device)
mrts = MRTS(locs=locs, k=locs.shape[0], device=device)
net = setup_model(inference_config["use_model"], model_config, mrts, device)
# Check if multiple GPUs are available
if torch.cuda.device_count() > 0:
net = nn.DataParallel(net)
data_names = ["imputation", "original", "mask"]
directory = inference_config["output_directory"]
if trials > 1:
directory += "_{trial}"
for trial in range(1, trials + 1):
LOGGER.info(f"The {trial}th inference trial")
saved_data_names = data_names if trial == 0 else data_names[0]
mses, mapes = DiffusionGenerator(
net=net,
device=device,
diffusion_hyperparams=diffusion_hyperparams,
dataloader=dataloader,
local_path=local_path,
output_directory=directory.format(trial=trial) if trials > 1 else directory,
ckpt_path=inference_config["ckpt_path"],
ckpt_iter=ckpt_iter,
batch_size=batch_size,
masking=inference_config["masking"],
missing_k=inference_config["missing_k"],
only_generate_missing=inference_config["only_generate_missing"],
saved_data_names=saved_data_names,
).generate()
LOGGER.info(f"Average MSE: {sum(mses) / len(mses)}")
LOGGER.info(f"Average MAPE: {sum(mapes) / len(mapes)}")
LOGGER.info(display_current_time())
class MRTS(nn.Module):
def __init__(self, locs: torch.Tensor,
k: int=None,
device: Optional[Union[torch.device, str]]=None,
calculate_with_spherical: bool=False,
standardize: bool=True,
unbiased_std: bool=False
):
"""
Multi-Resolution Thin-plate Spline basis function.
Args:
locs: [N, d] tensor of spatial locations.
k: (Optional) parameter for controlling resolution.
device: (Optional) PyTorch device to use.
calculate_with_spherical: (Optional) If True, use spherical coordinates for TPS calculation (default is False) (only supported when d == 2).
standardize: (Optional) If True, perform standardization on locs (Recommended).
unbiased_std: (Optional) If True, use unbiased standard deviation (dividing by N-1) (Recommended);
if False, use biased standard deviation (dividing by N).
"""
self.logger = LOGGER
logger = self.logger
super().__init__()
try:
if device is None:
self.device = torch.device('cpu')
logger.warning(f'Parameter "device" was not set. Default value "cpu" is used.')
else:
self.device = torch.device(device)
logger.info(f'Successfully using device "{self.device}".')
except (TypeError, ValueError) as e:
self.device = torch.device('cpu')
logger.warning(f'Parameter "device" is not a valid device ({device}). Default value "cpu" is used. Error: {e}')
self.register_buffer("locs", locs.to(self.device))
self.N, self.d = locs.shape
# number of basis
max_k = self.N + self.d
try:
if k is None:
self.k = max_k
logger.warning(f'Parameter "k" was not set. Default value {self.k} is used.')
elif 0 < k <= (max_k):
self.k = k
else:
self.k = max_k
logger.warning(f'Parameter "k" is out of valid range, it should be between 1 to {self.k}. Default value {self.k} is used.')
except TypeError:
self.k = max_k
logger.warning(f'Parameter "k" is not an integer, the type you input is "{type(k).__name__}." Default value {self.k} is used.')
self.calculate_with_spherical = calculate_with_spherical
if type(self.calculate_with_spherical) is not bool:
self.calculate_with_spherical = False
logger.warning(f'Parameter "calculate_with_spherical" should be a boolean, the type you input is "{type(calculate_with_spherical).__name__}". Default value False is used.')
elif self.calculate_with_spherical and self.d != 2:
self.calculate_with_spherical = False
logger.warning(f'Spherical TPS not implemented for d = {self.d}, only d = 2 is supported. Using rectangular coordinate system instead.')
if self.calculate_with_spherical:
logger.info(f'Calculate TPS with spherical coordinates.')
else:
logger.info(f'Calculate TPS with rectangular coordinates.')
self.standardize = standardize
if type(self.standardize) is not bool:
self.standardize = True
logger.warning(f'Parameter "standardize" should be a boolean, the type you input is "{type(standardize).__name__}". Default value True is used.')
self.unbiased_std = unbiased_std
if type(self.unbiased_std) is not bool:
self.unbiased_std = False
logger.warning(f'Parameter "unbiased_std" should be a boolean, the type you input is "{type(unbiased_std).__name__}". Default value False is used.')
def _tps_phi(self, locs: torch.Tensor, calculate_with_spherical: bool=False) -> torch.Tensor:
"""
Compute the Thin Plate Spline (TPS) radial basis matrix for input locations.
Args:
locs: [N, d] tensor of spatial locations.
calculate_with_spherical: (Optional) If True, use spherical coordinates for TPS calculation (default is False) (only supported when d == 2).
Returns:
A [N, N] tensor representing the TPS radial basis matrix.
"""
# rectangular coordinate system
if not calculate_with_spherical:
return self.__calculate_phi_by_rectangular_coordinate(locs)
# spherical coordinate system
else:
# convert to spherical coordinates
ret = torch.zeros((self.N, self.N), device=locs.device)
locs = locs * torch.pi / 180.0
x = locs[:, 0]
y = locs[:, 1]
for i in range(self.N):
for j in range(self.N):
ret[i, j] = self.__calculate_phi_by_spherical_coordinate(x[i], y[i], x[j], y[j])
return ret
def __calculate_phi_by_rectangular_coordinate(self, locs: torch.Tensor) -> torch.Tensor:
"""
Calculate the TPS radial basis matrix using rectangular (Euclidean) coordinates.
Args:
locs: [N, d] tensor of spatial locations.
Returns:
A [N, N] tensor representing the TPS radial basis matrix.
"""
dists = torch.cdist(locs, locs) # Euclidean distances
if self.d == 1:
return (dists ** 3) / 12
elif self.d == 2:
mask = dists != 0
ret = torch.zeros_like(dists)
ret[mask] = (dists[mask] ** 2) * torch.log(dists[mask]) / (8 * torch.pi)
return ret
elif self.d == 3:
return -dists / 8
else:
raise NotImplementedError(f"TPS not implemented for d = {self.d}")
def __calculate_phi_by_spherical_coordinate(self, x1: float, y1: float, x2: float, y2: float) -> float:
"""
Calculate the TPS radial basis function using spherical coordinates.
Args:
x1, y1: Spherical coordinates of the first point (in radians).
x2, y2: Spherical coordinates of the second point (in radians).
Returns:
A float representing the TPS radial basis function value.
"""
cos_theta = torch.sin(x1) * torch.sin(x2) + torch.cos(x1) * torch.cos(x2) * torch.cos(y1 - y2)
cos_theta = torch.clamp(cos_theta, -1.0, 1.0)
#theta = torch.acos(cos_theta)
ret = 1 - (torch.pi ** 2) / 6
if not torch.isclose(cos_theta, torch.tensor(-1.0, device=cos_theta.device)):
cos_theta = cos_theta.item()
upper = (cos_theta + 1) / 2
lower = 0
result, _ = quad(self.__integrand_for_spherical_in_tps, lower, upper, epsabs=1e-6, epsrel=1e-6, limit=50)
result = torch.tensor(result, dtype=torch.float32, device=self.device)
ret -= result
return ret
# # method by GPT can just use tenser to calculate and efficient
# # spherical coordinate system
# locs_rad = locs * torch.pi / 180.0 # convert to radians
# lat1 = locs_rad[:, 0].unsqueeze(1) # [N, 1]
# lon1 = locs_rad[:, 1].unsqueeze(1) # [N, 1]
# lat2 = locs_rad[:, 0].unsqueeze(0) # [1, N]
# lon2 = locs_rad[:, 1].unsqueeze(0) # [1, N]
# # Cosine of angular distance
# cos_theta = (
# torch.sin(lat1) @ torch.sin(lat2) + torch.cos(lat1) @ torch.cos(lat2) * torch.cos(lon1 - lon2)
# )
# cos_theta = torch.clamp(cos_theta, -1.0, 1.0)
# # Compute integral using trapezoidal rule
# N = 100 # Number of steps in the integral approximation
# x = torch.linspace(1e-6, 1.0, N, device=locs.device) # avoid x=0
# ln_term = torch.log(1 - x) / x # [N]
# def trapezoid_integrate(upper): # upper: [N, N]
# upper = torch.clamp(upper, 1e-6, 1.0)
# area = torch.zeros_like(upper)
# for i in range(N - 1):
# x0, x1 = x[i], x[i + 1]
# y0, y1 = ln_term[i], ln_term[i + 1]
# h = x1 - x0
# area += h * (y0 + y1) / 2 * ((upper >= x1).float()) # only add where upper > x1
# return area
# upper_bound = (cos_theta + 1) / 2 # [N, N]
# integral_vals = trapezoid_integrate(upper_bound) # [N, N]
# ret = 1 - (torch.pi ** 2) / 6 - integral_vals
# return ret
def __integrand_for_spherical_in_tps(self, x):
"""
Integrand function for the spherical TPS radial basis function.
Args:
x: The variable of integration.
Returns:
The value of the integrand at x.
"""
return np.log(1 - x) / x
def _standardize(self, x: torch.Tensor, unbiased_std: Optional[bool] = None) -> torch.Tensor:
"""
A function to standardize the input tensor x.
Args:
x: Input tensor to be standardized.
unbiased_std: (Optional) If True, use unbiased standard deviation (dividing by N-1);
if False, use biased standard deviation (dividing by N).
Default is None, which uses the class attribute self.unbiased_std.
Returns:
A standardized tensor with mean 0 and standard deviation 1.
"""
if unbiased_std is None:
unbiased_std = self.unbiased_std
mean = x.mean(dim=0, keepdim=True) # keepdim=True to keep the same shape
std = x.std(dim=0, unbiased=unbiased_std, keepdim=True) # unbiased=False for population std
std[std == 0] = 1.0
x = (x - mean) / std
return x
def forward(self) -> torch.Tensor:
"""
Forward pass to compute the basis functions. Constructs the basis functions based on the input locations and parameters.
Returns:
A tensor of shape [N, k] representing the basis functions.
"""
logger = self.logger
# Construct X = [1, x1, x2, ..., xd]
ones = torch.ones(self.N, 1, device=self.device)
X = torch.cat([ones, self.locs], dim=1) # [N, d+1]
if self.k == 1:
return ones
elif self.k <= self.d:
if self.standardize:
X[:, 1:self.k] = self._standardize(X[:, 1:self.k])
return X[:, :self.k]
# TPS basis
Phi = self._tps_phi(locs=self.locs, calculate_with_spherical=self.calculate_with_spherical) # [N, N]
# Q = I - X(XᵗX)⁻¹Xᵗ
try:
XtX_inv = torch.inverse(X.T @ X) # [(d+1), (d+1)]
except RuntimeError as e:
logger.warning(f'torch.inverse failed due to {e}, this implies "X.T @ X" didn\'t have inverse. Using torch.linalg.pinv instead.')
XtX_inv = torch.linalg.pinv(X.T @ X)
Q = torch.eye(self.N, device=self.device) - X @ XtX_inv @ X.T
# Eigen-decomposition
G = Q @ Phi @ Q
#eigenvalues, eigenvectors = torch.linalg.eigh(G) # ascending order
G = G.detach().cpu().numpy()
eigenvalues, eigenvectors = eigsh(G, k=self.k - self.d - 1, which='LM') # 'LM': Largest Magnitude, max k < N
eigenvalues = torch.from_numpy(eigenvalues).to(self.device)
eigenvectors = torch.from_numpy(eigenvectors).to(self.device)
# Filter out near-zero eigenvalues and sort descending
#valid = eigenvalues > 1e-10
#eigenvalues[~valid] *= -1.0 # make them positive
#eigenvectors[:, ~valid] *= -1.0 # make them positive
idx_desc = torch.argsort(eigenvalues, descending=True)
eigenvalues = eigenvalues[idx_desc]
eigenvectors = eigenvectors[:, idx_desc]
Basis_high = eigenvectors * torch.sqrt(torch.tensor(self.N, dtype=torch.float32))
# # Construct basis functions
# Basis_high = (Phi.T - Phi @ X @ XtX_inv @ X.T).T @ eigenvectors @ torch.diag(1.0 / eigenvalues).to(self.device)
# # the for loop
# Basis_high_1 = torch.zeros(self.N, self.N, device=self.locs.device)
# for i in range(self.N):
# phi_i = Phi[i, :]
# x_i = X[i, :]
# Phi_XXtXinv_x = (phi_i.T - Phi @ X @ XtX_inv @ x_i.T).T
# for j in range(self.N):
# lambda_j = 1 / eigenvalues[j]
# v_j = eigenvectors[:, j]
# Basis_high_1[i, j] = lambda_j * Phi_XXtXinv_x @ v_j
# print(f'Basis_high:\n{Basis_high}, \n\nBasis_high_1:\n{Basis_high_1}')
# print(torch.mean((Basis_high - Basis_high_1)**2))
# Concatenate [1, x1, ..., xd] and B_high
Basis_low = X # [N, d+1]
# Standardize
if self.standardize:
Basis_low[:, 1:(self.d + 1)] = self._standardize(Basis_low[:, 1:(self.d + 1)])
F = torch.cat([Basis_low, Basis_high], dim=1)
# Output k basis
F = F[:, :self.k]
# print('1')
# eigenvalues = eigenvalues[:self.k - self.d - 1] # Select top k - (d + 1) eigenvalues
# eigenvectors = eigenvectors[:, :self.k - self.d - 1] # Select top k - (d + 1) eigenvectors
# # compute BBBH and UZ
# BBB = XtX_inv @ X.T
# BBBH = BBB @ Phi
# BBB_gamma = BBB @ eigenvectors
# B_BBB_gamma = X @ BBB_gamma
# gammas = (eigenvectors - B_BBB_gamma) / eigenvalues.reshape(1, -1) * torch.sqrt(torch.tensor(self.N, dtype=torch.float32))
# print('2')
# col_sd = self.locs.std(dim=0, unbiased=True)
# adjustment = torch.sqrt(torch.tensor(self.N / (self.N - 1), dtype=col_sd.dtype, device=col_sd.device))
# diag_values = (adjustment / col_sd).cpu().numpy()
# xobs_diag = np.diag(diag_values)
# print('3')
# # 初始化组合矩阵
# UZ = np.zeros((self.N + self.d + 1, self.k))
# print('4')
# # 区块填充
# UZ[:self.N, :self.k - self.d - 1] = gammas # 左上区块
# UZ[self.N, self.k - self.d - 1] = 1.0 # 中心单位元素
# UZ[self.N + 1:, self.k - self.d:] = xobs_diag # 右下对角区块
return F # [N, d+1 + k]
if __name__ == "__main__":
args = fetch_args()
with open(args.model_config, "rt") as f:
model_config = yaml.safe_load(f.read())
with open(args.inference_config, "rt") as f:
inference_config = yaml.safe_load(f.read())
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if torch.cuda.device_count() > 0:
LOGGER.info(f"Using {torch.cuda.device_count()} GPUs!")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
run_job(model_config, inference_config, device, args.ckpt_iter)
|