Datasets:

ArXiv:
License:
S2NO commited on
Commit
ec08fab
·
verified ·
1 Parent(s): 9c4a9ea

Upload 16 files

Browse files
.gitattributes CHANGED
@@ -57,3 +57,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ result/S2NO_small_limb_36_with_box.pdf filter=lfs diff=lfs merge=lfs -text
FNO_pretrain.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytorch_lightning as pl
2
+ import torch
3
+ import wandb
4
+ import numpy as np
5
+ import math
6
+ import matplotlib.pyplot as plt
7
+ import torch.nn as nn
8
+ from torch import optim
9
+ import torch.nn.functional as F
10
+
11
+ from models.basics_model import get_grid2D,FC_nn
12
+ from scipy.io import loadmat
13
+ import os
14
+ ##################
15
+ #fourier convolution 2d block
16
+
17
+ class LpLoss(object):
18
+ def __init__(self, d=2, p=2, size_average=True, reduction=True):
19
+ super(LpLoss, self).__init__()
20
+ assert d > 0 and p > 0
21
+ self.d = d
22
+ self.p = p
23
+ self.reduction = reduction
24
+ self.size_average = size_average
25
+ def abs(self, x, y):
26
+ num_examples = x.size()[0]
27
+ h = 1.0 / (x.size()[1] - 1.0)
28
+ all_norms = (h**(self.d/self.p))*torch.norm(x.view(num_examples,-1) - y.view(num_examples,-1), self.p, 1)
29
+ if self.reduction:
30
+ if self.size_average:
31
+ return torch.mean(all_norms)
32
+ else:
33
+ return torch.sum(all_norms)
34
+ return all_norms
35
+
36
+ def rel(self, x, y):
37
+ num_examples = x.size()[0]
38
+
39
+ diff_norms = torch.norm(x.reshape(num_examples,-1) - y.reshape(num_examples,-1), self.p, 1)
40
+ y_norms = torch.norm(y.reshape(num_examples,-1), self.p, 1)
41
+
42
+ if self.reduction:
43
+ if self.size_average:
44
+ return torch.mean(diff_norms/y_norms)
45
+ else:
46
+ return torch.sum(diff_norms/y_norms)
47
+
48
+ return diff_norms/y_norms
49
+
50
+ def __call__(self, x, y):
51
+ return self.rel(x, y)
52
+
53
+
54
+ class RRMSE(object):
55
+ def __init__(self, ):
56
+ super(RRMSE, self).__init__()
57
+
58
+ def __call__(self, x, y):
59
+ num_examples = x.size()[0]
60
+ norm = torch.norm(x.view(num_examples,-1) - y.view(num_examples,-1), 2 , 1)**2
61
+ normy = torch.norm( y.view(num_examples,-1), 2 , 1)**2
62
+ mean_norm = torch.mean((norm/normy)**(1/2))
63
+ return mean_norm
64
+
65
+
66
+ class fourier_conv_2d(nn.Module):
67
+ def __init__(self, in_, out_, wavenumber1, wavenumber2):
68
+ super(fourier_conv_2d, self).__init__()
69
+ self.out_ = out_
70
+ self.wavenumber1 = wavenumber1
71
+ self.wavenumber2 = wavenumber2
72
+ scale = (1 / (in_ * out_))
73
+ self.weights1 = nn.Parameter(scale * torch.rand(in_, out_, wavenumber1, wavenumber2, 2 , dtype=torch.float32))
74
+ self.weights2 = nn.Parameter(scale * torch.rand(in_, out_, wavenumber1, wavenumber2, 2 , dtype=torch.float32))
75
+ # Complex multiplication
76
+ def compl_mul2d(self, input, weights):
77
+ # (batch, in_channel, x,y ,2), (in_channel, out_channel, x,y,2) -> (batch, out_channel, x,y)
78
+ return torch.einsum("bixyz,ioxyz->boxyz", input, weights)
79
+ def forward(self, x):
80
+ #input: batch,channel,x,y
81
+ #out: batch,channel,x,y
82
+ batchsize = x.shape[0]
83
+ #Compute Fourier coeffcients up to factor of e^(- something constant)
84
+ x_ft = torch.view_as_real(torch.fft.rfft2(x))#input: batch,channel,x,y->batch,channel,x,y,2
85
+ # Multiply relevant Fourier modes
86
+ out_ft = torch.zeros(batchsize, self.out_, x.size(-2), x.size(-1)//2 + 1,2, dtype=torch.float32, device=x.device)
87
+ out_ft[:, :, :self.wavenumber1, :self.wavenumber2,:] = \
88
+ self.compl_mul2d(x_ft[:, :, :self.wavenumber1, :self.wavenumber2,:], self.weights1)
89
+ out_ft[:, :, -self.wavenumber1:, :self.wavenumber2,:] = \
90
+ self.compl_mul2d(x_ft[:, :, -self.wavenumber1:, :self.wavenumber2,:], self.weights2)
91
+ #Return to physical space
92
+ x = torch.fft.irfft2(torch.view_as_complex(out_ft), s=(x.size(-2), x.size(-1)))
93
+ return x
94
+
95
+
96
+ ######################################################
97
+ #fourier convolution layer using fourier conv block and conv2d block
98
+ class Fourier_layer(nn.Module):
99
+ def __init__(self, features_, wavenumber, activation = 'relu', is_last = False):
100
+ super(Fourier_layer, self).__init__()
101
+ self.W = nn.Conv2d(features_, features_, 1)
102
+ self.fourier_conv = fourier_conv_2d(features_, features_ , *wavenumber)
103
+ if is_last== False:
104
+ self.act = F.relu
105
+ else:
106
+ self.act = nn.Identity()
107
+ def forward(self, x):
108
+ x1 = self.fourier_conv(x)
109
+ x2 = self.W(x)
110
+ return self.act(x1 + x2)
111
+
112
+ ######################################################
113
+ #fourier neural operator implementation
114
+ class FNO_pretrain(pl.LightningModule):
115
+ def __init__(self,
116
+ wavenumber=[128,128,128,128,128,128,128], features_=40,
117
+ padding = 6,
118
+ activation= 'relu',
119
+ lifting = None,
120
+ proj = None,
121
+ dim_input = 1,
122
+ source_type = 'theta',
123
+ add_term = False,
124
+ loss = "rel_l2",
125
+ learning_rate = 1e-3,
126
+ step_size= 100,
127
+ gamma= 0.5,
128
+ weight_decay= 1e-5,
129
+ eta_min = 5e-4,
130
+ val_exp = False,
131
+ src_path_breast = '',
132
+ gt_path_breast = '',
133
+ src_path_arm = '',
134
+ gt_path_arm = '',
135
+ src_path_limb = '',
136
+ gt_path_limb = ''
137
+ ):
138
+ super(FNO_pretrain, self).__init__()
139
+ self.with_grid = True
140
+ if self.with_grid == True:
141
+ dim_input +=2
142
+ self.source_type = source_type
143
+ if self.source_type == 'source':
144
+ dim_input +=2
145
+ elif self.source_type == 'theta':
146
+ dim_input +=2
147
+ self.padding = padding
148
+ self.layers = len(wavenumber)
149
+ self.learning_rate = learning_rate
150
+ self.step_size = step_size
151
+ self.gamma = gamma
152
+ self.weight_decay = weight_decay
153
+ self.eta_min = eta_min
154
+ self.add_term = add_term
155
+ if loss == 'l1':
156
+ self.criterion = nn.L1Loss()
157
+ self.criterion_val = LpLoss()
158
+ elif loss == 'l2':
159
+ self.criterion = nn.MSELoss()
160
+ self.criterion_val = LpLoss()
161
+ elif loss == 'smooth_l1':
162
+ self.criterion = nn.SmoothL1Loss()
163
+ self.criterion_val = LpLoss()
164
+ elif loss == "rel_l2":
165
+ self.criterion = LpLoss()
166
+ self.criterion_val = RRMSE()
167
+
168
+ if lifting is None:
169
+ self.lifting = FC_nn([dim_input, features_//2, features_],
170
+ activation = "relu",
171
+ outermost_norm=False
172
+ )
173
+ else:
174
+ self.lifting = lifting
175
+ if proj is None:
176
+ self.proj = FC_nn([features_, features_//2, 2],
177
+ activation = "relu",
178
+ outermost_norm=False
179
+ )
180
+ else:
181
+ self.proj = proj
182
+ self.fno = []
183
+ for l in range(self.layers-1):
184
+ self.fno.append(Fourier_layer(features_ = features_,
185
+ wavenumber=[wavenumber[l]]*2,
186
+ activation = activation))
187
+
188
+ self.fno.append(Fourier_layer(features_=features_,
189
+ wavenumber=[wavenumber[-1]]*2,
190
+ activation = activation,
191
+ is_last= True))
192
+ self.fno =nn.Sequential(*self.fno)
193
+ self.val_iter = 0
194
+
195
+ self.val_exp = val_exp
196
+ self.save_path = None
197
+ self.exp_name = None
198
+ self.src_path_breast = src_path_breast
199
+ self.gt_path_breast = gt_path_breast
200
+ self.src_path_arm = src_path_arm
201
+ self.src_path_limb = src_path_limb
202
+ self.gt_path_arm = gt_path_arm
203
+ self.gt_path_limb = gt_path_limb
204
+
205
+
206
+
207
+ if self.val_exp:
208
+ data = loadmat('/gpfs/share/home/2401112587/neuralFWI/resources/exp_speed/breast0718.mat')['image']
209
+ data = (1500/data-1)*30
210
+ sos = torch.tensor(data,dtype=torch.float).view(1,480,480,1)
211
+ sos = sos.repeat(64,1,1,1)
212
+ self.sos_exp_breast = sos
213
+ index_2 = np.arange(0,64).reshape(64,1,1,1)
214
+ src = np.load(self.src_path_breast)[:,:,:]*2e-3
215
+ src = np.concatenate((np.real(src)[:,:,:,np.newaxis],np.imag(src)[:,:,:,np.newaxis]),axis = -1)
216
+ self.src_exp_breast = torch.tensor(src,dtype=torch.float).view(64,480,480,2)
217
+ gt_np = loadmat(self.gt_path_breast)['u_all_single']
218
+ gt = torch.view_as_real(torch.tensor(gt_np))
219
+ self.gt_breast = torch.tensor(gt)
220
+
221
+ data = loadmat('/gpfs/share/home/2401112587/neuralFWI/resources/exp_speed/armcbs1022.mat')['speed']
222
+ data = (1500/data-1)*30
223
+ sos = torch.tensor(data,dtype=torch.float).view(1,480,480,1)
224
+ sos = sos.repeat(64,1,1,1)
225
+ self.sos_exp_arm = sos
226
+ index_2 = np.arange(0,64).reshape(64,1,1,1)
227
+ src = np.load(self.src_path_arm)[:,:,:]*2e-3
228
+ #theta = (index_2/64*2*np.pi)*np.ones((1,480,480,1))
229
+ src = np.concatenate((np.real(src)[:,:,:,np.newaxis],np.imag(src)[:,:,:,np.newaxis]),axis = -1)
230
+ self.src_exp_arm = torch.tensor(src,dtype=torch.float).view(64,480,480,2)
231
+ gt_np = loadmat(self.gt_path_arm)['u_all_single']
232
+ gt = torch.view_as_real(torch.tensor(gt_np))
233
+ self.gt_arm = torch.tensor(gt)
234
+
235
+ data = loadmat('/gpfs/share/home/2401112587/neuralFWI/resources/exp_speed/limb0718.mat')['image']
236
+ data = (1500/data-1)*30
237
+ sos = torch.tensor(data,dtype=torch.float).view(1,480,480,1)
238
+ sos = sos.repeat(64,1,1,1)
239
+ self.sos_exp_limb = sos
240
+ index_2 = np.arange(0,64).reshape(64,1,1,1)
241
+ src = np.load(self.src_path_limb)[:,:,:]*2e-3
242
+ #theta = (index_2/64*2*np.pi)*np.ones((1,480,480,1))
243
+ src = np.concatenate((np.real(src)[:,:,:,np.newaxis],np.imag(src)[:,:,:,np.newaxis]),axis = -1)
244
+ self.src_exp_limb = torch.tensor(src,dtype=torch.float).view(64,480,480,2)
245
+ gt_np = loadmat(self.gt_path_limb)['u_all_single']
246
+ gt = torch.view_as_real(torch.tensor(gt_np))
247
+ self.gt_limb = torch.tensor(gt)
248
+
249
+
250
+ def forward(self, sos,src):
251
+ # 100,960,960,2
252
+ #x = torch.cat((sos, src), dim=-1)
253
+ if self.source_type == 'theta':
254
+ src_input = src[:,:,:,:]
255
+ elif self.source_type == 'source':
256
+ src_input = src[:,:,:,0:2]
257
+ x = sos
258
+ field = src[...,:2].clone()
259
+ if self.with_grid == True:
260
+ grid = get_grid2D(x.shape, x.device)
261
+ x = torch.cat((x,grid,src_input), dim=-1) # 100,960,960,4
262
+ x = self.lifting(x) # 100,960,960,feature_
263
+ x = x.permute(0, 3, 1, 2)# batch,feature,x,y: 100,feature_,960,960
264
+ x = nn.functional.pad(x, [0,self.padding, 0,self.padding])
265
+ x = self.fno(x)# batch,feature,x,y: 100,feature_,960+pad,960+pad
266
+ x = x[..., :-self.padding, :-self.padding] # batch,feature,x,y: 100,feature_,960,960
267
+ x = x.permute(0, 2, 3, 1 )
268
+ x =self.proj(x) # batch,x,y,2: 100,960,960 ,2
269
+ if self.add_term == True:
270
+
271
+ x = torch.view_as_real(torch.view_as_complex(field.to(x.device))*(1+torch.view_as_complex(x)))
272
+ return x
273
+
274
+ def training_step(self, batch: torch.Tensor, batch_idx):
275
+ sos,src,y,index = batch
276
+ batch_size = sos.shape[0]
277
+ out = self(sos,src)
278
+ loss = self.criterion(out, y)
279
+ self.log("loss", loss, on_epoch=True, prog_bar=True, logger=True)
280
+ wandb.log({"loss": loss.item()})
281
+ return loss
282
+
283
+ def validation_step(self, val_batch: torch.Tensor, batch_idx):
284
+ sos, src, y, index = val_batch
285
+ split_index = (index[-1] + index[0])//2
286
+ batch_size = sos.shape[0]
287
+ out = self(sos, src)
288
+ val_loss = self.criterion_val(out.view(batch_size, -1), y.view(batch_size, -1))
289
+
290
+
291
+ return val_loss
292
+
293
+ # def on_validation_epoch_end(self):
294
+ # error = self.validation_exp_breast(device = self.device)
295
+ # #self.log('exp_loss_breast', error.item(), on_epoch=True, prog_bar=True, logger=True)
296
+ # error = self.validation_exp_arm(device = self.device)
297
+ # #self.log('exp_loss_arm', error.item(), on_epoch=True, prog_bar=True, logger=True)
298
+ # error = self.validation_exp_limb(device = self.device)
299
+ # #self.log('exp_loss_limb', error.item(), on_epoch=True, prog_bar=True, logger=True)
300
+
301
+
302
+ def configure_optimizers(self, optimizer=None, scheduler=None):
303
+ if optimizer is None:
304
+ optimizer = optim.AdamW(self.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay)
305
+ if scheduler is None:
306
+ #scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer,T_max = self.step_size, eta_min= self.eta_min)
307
+ scheduler = optim.lr_scheduler.StepLR(optimizer, step_size = 6, gamma = 0.1)# 6 0.5
308
+
309
+ return {
310
+ "optimizer": optimizer,
311
+ "lr_scheduler": {
312
+ "scheduler": scheduler
313
+ },
314
+ }
315
+
316
+
317
+
318
+
319
+
S2NO_pretrain.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import pytorch_lightning as pl
4
+ from torch import optim, nn
5
+ import torch.nn.functional as F
6
+
7
+ import wandb
8
+ import matplotlib.pyplot as plt
9
+ import math
10
+ import os
11
+ from scipy.io import loadmat
12
+
13
+ class LpLoss(object):
14
+ def __init__(self, d=2, p=2, size_average=True, reduction=True):
15
+ super(LpLoss, self).__init__()
16
+ assert d > 0 and p > 0
17
+ self.d = d
18
+ self.p = p
19
+ self.reduction = reduction
20
+ self.size_average = size_average
21
+ def abs(self, x, y):
22
+ num_examples = x.size()[0]
23
+ h = 1.0 / (x.size()[1] - 1.0)
24
+ all_norms = (h**(self.d/self.p))*torch.norm(x.view(num_examples,-1) - y.view(num_examples,-1), self.p, 1)
25
+ if self.reduction:
26
+ if self.size_average:
27
+ return torch.mean(all_norms)
28
+ else:
29
+ return torch.sum(all_norms)
30
+ return all_norms
31
+
32
+ def rel(self, x, y):
33
+ num_examples = x.size()[0]
34
+
35
+ diff_norms = torch.norm(x.reshape(num_examples,-1) - y.reshape(num_examples,-1), self.p, 1)
36
+ y_norms = torch.norm(y.reshape(num_examples,-1), self.p, 1)
37
+
38
+ if self.reduction:
39
+ if self.size_average:
40
+ return torch.mean(diff_norms/y_norms)
41
+ else:
42
+ return torch.sum(diff_norms/y_norms)
43
+
44
+ return diff_norms/y_norms
45
+
46
+ def __call__(self, x, y):
47
+ return self.rel(x, y)
48
+
49
+
50
+ class RRMSE(object):
51
+ def __init__(self, ):
52
+ super(RRMSE, self).__init__()
53
+
54
+ def __call__(self, x, y):
55
+ num_examples = x.size()[0]
56
+ norm = torch.norm(x.view(num_examples,-1) - y.view(num_examples,-1), 2 , 1)**2
57
+ normy = torch.norm( y.view(num_examples,-1), 2 , 1)**2
58
+ mean_norm = torch.mean((norm/normy)**(1/2))
59
+ return mean_norm
60
+
61
+
62
+ class SpectralConv2d_born(nn.Module):
63
+ '''
64
+ Input:
65
+ x: batch,in, x,y
66
+ x_eps: batch,in,x,y
67
+ Output: batch,out,x,y
68
+ '''
69
+ def __init__(self, in_channels, out_channels, modes1, modes2):
70
+ super(SpectralConv2d_born, self).__init__()
71
+
72
+ """
73
+ 2D Fourier layer. It does FFT, linear transform, and Inverse FFT.
74
+ """
75
+
76
+ self.in_channels = in_channels
77
+ self.out_channels = out_channels
78
+ self.modes1 = modes1 # Number of Fourier modes to multiply, at most floor(N/2) + 1
79
+ self.modes2 = modes2
80
+ self.scale = 1 / (in_channels * out_channels)
81
+ self.weights1 = nn.Parameter(
82
+ self.scale * torch.rand(in_channels, out_channels, self.modes1, self.modes2,2, dtype=torch.float32)
83
+ )
84
+ self.weights2 = nn.Parameter(
85
+ self.scale * torch.rand(in_channels, out_channels, self.modes1, self.modes2,2, dtype=torch.float32)
86
+ )
87
+ def compl_mul2d(self,input, weights):
88
+ #print(input.shape,weights.shape)
89
+ real = torch.einsum('bixy,ioxy->boxy',input[...,0],weights[...,0])-torch.einsum('bixy,ioxy->boxy',input[...,1],weights[...,1])
90
+ comp = torch.einsum('bixy,ioxy->boxy',input[...,0],weights[...,1])+torch.einsum('bixy,ioxy->boxy',input[...,1],weights[...,0])
91
+ output = torch.cat((real.unsqueeze(-1),comp.unsqueeze(-1)),dim = -1)
92
+
93
+ return output
94
+ # Complex multiplication
95
+ # def compl_mul2d(self, input, weights):
96
+ # # (batch, in_channel, x,y ), (in_channel, out_channel, x,y) -> (batch, out_channel, x,y)
97
+ # return torch.einsum("bixyz,ioxyz->boxyz", input, weights)
98
+
99
+ def forward(self, x, x_eps):
100
+ batchsize = x.shape[0]
101
+ # Compute Fourier coeffcients up to factor of e^(- something constant)
102
+ x_ft = torch.view_as_real(torch.fft.rfft2(x * x_eps))
103
+ # Multiply relevant Fourier modes
104
+ out_ft = torch.zeros(
105
+ batchsize, self.out_channels, x.size(-2), x.size(-1) // 2 + 1,2, dtype=torch.float32, device=x.device
106
+ )
107
+
108
+ out_ft[:, :, : self.modes1, : self.modes2] = self.compl_mul2d(
109
+ x_ft[:, :, : self.modes1, : self.modes2,:], self.weights1
110
+ )
111
+ out_ft[:, :, -self.modes1 :, : self.modes2] = self.compl_mul2d(
112
+ x_ft[:, :, -self.modes1 :, : self.modes2,:], self.weights2
113
+ )
114
+ # Return to physical space
115
+ x = torch.fft.irfft2(torch.view_as_complex(out_ft), s=(x.size(-2), x.size(-1)))
116
+ return x
117
+
118
+
119
+ class FNO_step(nn.Module):
120
+ def __init__(self, width, modes1, modes2 ):
121
+ super(FNO_step, self).__init__()
122
+ self.modes1 = modes1 # Truncate mode of FT in x
123
+ self.modes2 = modes2 # Truncate mode of FT in y
124
+ self.width = width #image size
125
+ self.conv0 = SpectralConv2d_born(self.width, self.width, self.modes1, self.modes2)
126
+ self.w0 = nn.Conv2d(self.width, self.width, 1)
127
+ self.w1 = nn.Conv2d(self.width, self.width, 1)
128
+ self.bn = nn.BatchNorm2d(self.width, eps=0, momentum=0.5, affine=True)
129
+ #self.coef = nn.Parameter(torch.ones(1)).cuda()
130
+ def forward(self,input):
131
+ # Qin Jiu Shao version
132
+ x,v_v,v_q,x_0, v_mq= input
133
+ x_n = x.clone()
134
+ x = self.conv0(x, v_v)
135
+ x = x * v_mq+ v_q * x_n
136
+ x = self.w1(F.leaky_relu(self.w0(x)))
137
+ x = F.leaky_relu(x)
138
+ x = x + x_0
139
+ x = self.bn(x)
140
+ return [x,v_v,v_q,x_0,v_mq]
141
+
142
+ class S2NO_step_wrap(nn.Module):
143
+ def __init__(self, model,width):
144
+ super(S2NO_step_wrap, self).__init__()
145
+ self.model = model
146
+ #self.DC = DC1(self.width, 8, self.width, 3)
147
+ self.bn = nn.BatchNorm2d(width, eps=0, momentum=0.5, affine=True)
148
+ #self.ln = torch.nn.LayerNorm(489, eps=1e-05, elementwise_affine=True)
149
+
150
+ def forward(self,input):
151
+ # Qin Jiu Shao version
152
+ #x = self.DC(x)
153
+ [x,v_v,v_q,x_0] = self.model(input)
154
+ x = self.bn(x)
155
+ return [x,v_v,v_q,x_0]
156
+
157
+
158
+ class S2NO_pretrain(pl.LightningModule):
159
+ def __init__(self,width=40,
160
+ modes1=128,
161
+ modes2=128,
162
+ layer_num=7,
163
+ padding = 6,
164
+ dim_input = 1,
165
+ source_type = 'theta',
166
+ loss = "rel_l2",
167
+ learning_rate = 1e-2,
168
+ step_size= 100,
169
+ gamma= 0.5,
170
+ weight_decay= 1e-5,
171
+ F_feature = False,
172
+ add_term = False,
173
+ eta_min = 2e-4,
174
+ val_exp = False,
175
+ src_path_breast = '',
176
+ gt_path_breast = '',
177
+ src_path_arm = '',
178
+ gt_path_arm = '',
179
+ src_path_limb = '',
180
+ gt_path_limb = ''
181
+ ):
182
+ super().__init__()
183
+ self.with_grid = True
184
+ if self.with_grid == True:
185
+ dim_input +=2
186
+ self.source_type = source_type
187
+ if self.source_type == 'source':
188
+ dim_input +=2
189
+ elif self.source_type == 'theta':
190
+ dim_input +=2
191
+ self.padding = padding
192
+ self.learning_rate = learning_rate
193
+ self.step_size = step_size
194
+ self.gamma = gamma
195
+ self.weight_decay = weight_decay
196
+ self.eta_min = eta_min
197
+ if loss == 'l1':
198
+ self.criterion = nn.L1Loss()
199
+ elif loss == 'l2':
200
+ self.criterion = nn.MSELoss()
201
+ self.criterion_val = LpLoss()
202
+ elif loss == "rel_l2":
203
+ self.criterion =LpLoss()
204
+ self.criterion_val = RRMSE()
205
+
206
+
207
+
208
+ self.modes1 = modes1 # Truncate mode of FT in x
209
+ self.modes2 = modes2 # Truncate mode of FT in y
210
+ self.width = width #image size
211
+ self.padding = padding # pad the domain if input is non-periodic
212
+ self.fc_c1 = nn.Linear(3, self.width) # input channel is 3: (c(x, y), x, y)
213
+ self.fc_c2 = nn.Linear(self.width, self.width)
214
+ self.fc_c3 = nn.Linear(3, self.width) # input channel is 3: (c(x, y), x, y)
215
+ self.fc_c4 = nn.Linear(self.width, self.width)
216
+ self.fc_0 = nn.Linear(dim_input, self.width) # input channel is 4: (s(x,y),c(x, y), x, y)
217
+ self.layer_num = layer_num
218
+ self.fno_step = []
219
+
220
+ for i in range(layer_num):
221
+ self.fno_step.append(FNO_step(self.width,self.modes1,self.modes2).to(self.device))
222
+ self.net =nn.Sequential(*self.fno_step)
223
+ self.F_feature = F_feature
224
+ self.add_term = add_term
225
+ self.fc1 = nn.Linear(self.width, 256)
226
+ self.fc2 = nn.Linear(256, 2)
227
+ self.val_iter = 0
228
+ self.bn = nn.BatchNorm2d(self.width, eps=0, momentum=0.5, affine=True, track_running_stats=True)
229
+ #self.field = torch.tensor(np.load('/root/Fine-tuning-NOs-master/models/field.npy'))
230
+ self.val_exp = val_exp
231
+ self.save_path = None
232
+ self.exp_name = None
233
+ self.src_path_breast = src_path_breast
234
+ self.gt_path_breast = gt_path_breast
235
+ self.src_path_arm = src_path_arm
236
+ self.src_path_limb = src_path_limb
237
+ self.gt_path_arm = gt_path_arm
238
+ self.gt_path_limb = gt_path_limb
239
+ if self.val_exp:
240
+ data = loadmat('/gpfs/share/home/2201213309/neuralFWI/breast_generator0822/exp_matcode/breast0718.mat')['image']
241
+ data = (1500/data-1)*30
242
+ sos = torch.tensor(data,dtype=torch.float).view(1,480,480,1)
243
+ sos = sos.repeat(64,1,1,1)
244
+ self.sos_exp_breast = sos
245
+ index_2 = np.arange(0,64).reshape(64,1,1,1)
246
+ src = np.load(self.src_path_breast)[:,:,:]*2e-3
247
+ src = np.concatenate((np.real(src)[:,:,:,np.newaxis],np.imag(src)[:,:,:,np.newaxis]),axis = -1)
248
+ self.src_exp_breast = torch.tensor(src,dtype=torch.float).view(64,480,480,2)
249
+ gt_np = loadmat(self.gt_path_breast)['u_all_single']
250
+ gt = torch.view_as_real(torch.tensor(gt_np))
251
+ self.gt_breast = torch.tensor(gt)
252
+
253
+ #data = loadmat('/gpfs/share/home/2201213309/neuralFWI/arm_generator1020/code1020/arm450.mat')['data']
254
+ data = loadmat('/gpfs/share/home/2201213309/neuralFWI/arm_generator1020/code1020/armcbs1022.mat')['speed']
255
+ data = (1500/data-1)*30
256
+ sos = torch.tensor(data,dtype=torch.float).view(1,480,480,1)
257
+ sos = sos.repeat(64,1,1,1)
258
+ self.sos_exp_arm = sos
259
+ index_2 = np.arange(0,64).reshape(64,1,1,1)
260
+ src = np.load(self.src_path_arm)[:,:,:]*2e-3
261
+ #theta = (index_2/64*2*np.pi)*np.ones((1,480,480,1))
262
+ src = np.concatenate((np.real(src)[:,:,:,np.newaxis],np.imag(src)[:,:,:,np.newaxis]),axis = -1)
263
+ self.src_exp_arm = torch.tensor(src,dtype=torch.float).view(64,480,480,2)
264
+ gt_np = loadmat(self.gt_path_arm)['u_all_single']
265
+ gt = torch.view_as_real(torch.tensor(gt_np))
266
+ self.gt_arm = torch.tensor(gt)
267
+
268
+ #data = loadmat('/gpfs/share/home/2201213309/neuralFWI/limb_generata0703/code0703/limb0718.mat')['image']
269
+ data = loadmat('/gpfs/share/home/2201213309/neuralFWI/limb_regenerator_1031/code1031/limb0718.mat')['image']
270
+ data = (1500/data-1)*30
271
+ sos = torch.tensor(data,dtype=torch.float).view(1,480,480,1)
272
+ sos = sos.repeat(64,1,1,1)
273
+ self.sos_exp_limb = sos
274
+ index_2 = np.arange(0,64).reshape(64,1,1,1)
275
+ src = np.load(self.src_path_limb)[:,:,:]*2e-3
276
+ #theta = (index_2/64*2*np.pi)*np.ones((1,480,480,1))
277
+ src = np.concatenate((np.real(src)[:,:,:,np.newaxis],np.imag(src)[:,:,:,np.newaxis]),axis = -1)
278
+ self.src_exp_limb = torch.tensor(src,dtype=torch.float).view(64,480,480,2)
279
+ gt_np = loadmat(self.gt_path_limb)['u_all_single']
280
+ gt = torch.view_as_real(torch.tensor(gt_np))
281
+ self.gt_limb = torch.tensor(gt)
282
+
283
+
284
+
285
+ def forward(self,sos,src):
286
+ '''
287
+ x: batch,x,y,channel=3 (c(x),s(x))
288
+ '''
289
+ if self.source_type == 'theta':
290
+ src_input = src[:,:,:,:]
291
+ elif self.source_type == 'source':
292
+ src_input = src[:,:,:,0:2]
293
+ # x = torch.cat((sos, src_input), dim=-1)
294
+ x_1 = sos
295
+ field = src[...,0:2].clone()
296
+
297
+ grid = self.get_grid(x_1.shape, x_1.device, field)
298
+
299
+ x_0 = torch.cat((x_1, grid,src_input), dim=-1)
300
+ x_c = torch.cat((x_1, grid), dim=-1)
301
+
302
+ v_0 = self.fc_0(x_0)
303
+ v_0 = v_0.permute(0, 3, 1, 2)
304
+ if self.padding >=1:
305
+ v_0 = F.pad(v_0, [0, self.padding, 0, self.padding])
306
+
307
+ v_v = self.fc_c2(F.tanh(self.fc_c1(x_c)))
308
+ v_v = v_v.permute(0, 3, 1, 2)
309
+ if self.padding >=1:
310
+ v_v = F.pad(v_v, [0, self.padding, 0, self.padding])
311
+ v_q = self.fc_c4(F.tanh(self.fc_c3(x_c)))
312
+ v_q = v_q.permute(0, 3, 1, 2)
313
+ if self.padding >=1:
314
+ v_q = F.pad(v_q, [0, self.padding, 0, self.padding])
315
+ v_mq = 1 - v_q
316
+ x_1 = v_0
317
+ x_out = x_1.clone()
318
+ #for i in range(self.layer_num):
319
+ [x_out,v_v,v_q,x_1,v_mq] = self.net([x_out,v_v,v_q,x_1, v_mq])
320
+ if self.padding >=1:
321
+ x_out = x_out[..., : -self.padding, : -self.padding]
322
+ x_out = x_out.permute(0, 2, 3, 1)
323
+ x_out = self.fc1(x_out)
324
+ x_out = F.leaky_relu(x_out)
325
+ x_out = self.fc2(x_out)#* self.field.to(x_out.device)
326
+ if self.add_term == True:
327
+ #x_out = x_out + field
328
+ x_out = torch.view_as_real(torch.view_as_complex(field.to(x_out.device))*(1+torch.view_as_complex(x_out)))
329
+ return x_out
330
+
331
+ def get_grid(self, shape, device,field):
332
+ batchsize, size_x, size_y = shape[0], shape[1], shape[2]
333
+ gridx = torch.tensor(np.linspace(0, 1, size_x), dtype=torch.float)
334
+ gridx = gridx.reshape(1, size_x, 1, 1).repeat([batchsize, 1, size_y, 1])
335
+ gridy = torch.tensor(np.linspace(0, 1, size_y), dtype=torch.float)
336
+ gridy = gridy.reshape(1, 1, size_y, 1).repeat([batchsize, size_x, 1, 1])
337
+ #feature = []
338
+ gridxy = torch.cat((gridx,gridy), dim=-1).to(device)
339
+ #feature.append(gridxy)
340
+ # if self.F_feature == True:
341
+ # for i in range(-3,4):
342
+ # feature.append(torch.sin(2**(-i)*gridxy))
343
+ # feature.append(torch.cos(2**(-i)*gridxy))
344
+ #feature.append(field)
345
+ return gridxy
346
+
347
+ def training_step(self, batch: torch.Tensor, batch_idx):
348
+ sos,src,y,index = batch
349
+ batch_size = sos.shape[0]
350
+ out = self(sos,src)
351
+ loss = self.criterion(out, y)
352
+ self.log("loss", loss, on_epoch=True, prog_bar=True, logger=True)
353
+ wandb.log({"loss": loss.item()})
354
+ return loss
355
+
356
+ def validation_step(self, val_batch: torch.Tensor, batch_idx):
357
+ sos, src, y, index = val_batch
358
+ split_index = (index[-1] + index[0])//2
359
+ batch_size = sos.shape[0]
360
+ out = self(sos, src)
361
+ val_loss = self.criterion_val(out.view(batch_size, -1), y.view(batch_size, -1))
362
+
363
+
364
+ return val_loss
365
+
366
+ # def on_validation_epoch_end(self):
367
+ # error = self.validation_exp_breast(device = self.device)
368
+ # #self.log('exp_loss_breast', error.item(), on_epoch=True, prog_bar=True, logger=True)
369
+ # error = self.validation_exp_arm(device = self.device)
370
+ # #self.log('exp_loss_arm', error.item(), on_epoch=True, prog_bar=True, logger=True)
371
+ # error = self.validation_exp_limb(device = self.device)
372
+ # #self.log('exp_loss_limb', error.item(), on_epoch=True, prog_bar=True, logger=True)
373
+
374
+ def configure_optimizers(self, optimizer=None, scheduler=None):
375
+ if optimizer is None:
376
+ optimizer = optim.AdamW(self.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay)
377
+ if scheduler is None:
378
+ #scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer,T_max = self.step_size, eta_min= self.eta_min)
379
+ scheduler = optim.lr_scheduler.StepLR(optimizer, step_size = 6, gamma = 0.1)# 6 0.5
380
+
381
+ return {
382
+ "optimizer": optimizer,
383
+ "lr_scheduler": {
384
+ "scheduler": scheduler
385
+ },
386
+ }
387
+
388
+
389
+
390
+
391
+
UNet_pretrain.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import pytorch_lightning as pl
3
+ import torch.nn as nn
4
+ from torch import optim
5
+ import numpy as np
6
+
7
+ import wandb
8
+ import matplotlib.pyplot as plt
9
+ from models.basics_model import get_grid2D,FC_nn
10
+ from scipy.io import loadmat
11
+
12
+ import os
13
+ class LpLoss(object):
14
+ def __init__(self, d=2, p=2, size_average=True, reduction=True):
15
+ super(LpLoss, self).__init__()
16
+ assert d > 0 and p > 0
17
+ self.d = d
18
+ self.p = p
19
+ self.reduction = reduction
20
+ self.size_average = size_average
21
+ def abs(self, x, y):
22
+ num_examples = x.size()[0]
23
+ h = 1.0 / (x.size()[1] - 1.0)
24
+ all_norms = (h**(self.d/self.p))*torch.norm(x.view(num_examples,-1) - y.view(num_examples,-1), self.p, 1)
25
+ if self.reduction:
26
+ if self.size_average:
27
+ return torch.mean(all_norms)
28
+ else:
29
+ return torch.sum(all_norms)
30
+ return all_norms
31
+
32
+ def rel(self, x, y):
33
+ num_examples = x.size()[0]
34
+
35
+ diff_norms = torch.norm(x.reshape(num_examples,-1) - y.reshape(num_examples,-1), self.p, 1)
36
+ y_norms = torch.norm(y.reshape(num_examples,-1), self.p, 1)
37
+
38
+ if self.reduction:
39
+ if self.size_average:
40
+ return torch.mean(diff_norms/y_norms)
41
+ else:
42
+ return torch.sum(diff_norms/y_norms)
43
+
44
+ return diff_norms/y_norms
45
+
46
+ def __call__(self, x, y):
47
+ return self.rel(x, y)
48
+
49
+
50
+ class RRMSE(object):
51
+ def __init__(self, ):
52
+ super(RRMSE, self).__init__()
53
+
54
+ def __call__(self, x, y):
55
+ num_examples = x.size()[0]
56
+ norm = torch.norm(x.view(num_examples,-1) - y.view(num_examples,-1), 2 , 1)**2
57
+ normy = torch.norm( y.view(num_examples,-1), 2 , 1)**2
58
+ mean_norm = torch.mean((norm/normy)**(1/2))
59
+ return mean_norm
60
+
61
+
62
+
63
+ def get_unet_model(in_ch=1, out_ch=1, scales=5, skip=4,
64
+ channels=(32, 32, 64, 64, 128, 128), use_sigmoid=True,
65
+ use_norm=True):
66
+ #assert (1 <= scales <= 6)
67
+ skip_channels = [skip] * (scales)
68
+ return UNet_module(in_ch=in_ch, out_ch=out_ch, channels=channels[:scales],
69
+ skip_channels=skip_channels, use_sigmoid=use_sigmoid,
70
+ use_norm=use_norm)
71
+
72
+
73
+ class DownBlock(nn.Module):
74
+ '''
75
+ Down sampling
76
+ '''
77
+ def __init__(self, in_ch, out_ch, kernel_size=3, num_groups=4, use_norm=True):
78
+ super(DownBlock, self).__init__()
79
+ to_pad = int((kernel_size - 1) / 2)
80
+ if use_norm:
81
+ self.conv = nn.Sequential(
82
+ nn.Conv2d(in_ch, out_ch, kernel_size,
83
+ stride=2, padding=to_pad),
84
+ nn.GroupNorm(num_channels=out_ch, num_groups=num_groups),
85
+ nn.LeakyReLU(0.2, inplace=True),
86
+ nn.Conv2d(out_ch, out_ch, kernel_size,
87
+ stride=1, padding=to_pad),
88
+ nn.GroupNorm(num_channels=out_ch, num_groups=num_groups),
89
+ nn.LeakyReLU(0.2, inplace=True))
90
+ else:
91
+ self.conv = nn.Sequential(
92
+ nn.Conv2d(in_ch, out_ch, kernel_size,
93
+ stride=2, padding=to_pad),
94
+ nn.LeakyReLU(0.2, inplace=True),
95
+ nn.Conv2d(out_ch, out_ch, kernel_size,
96
+ stride=1, padding=to_pad),
97
+ nn.LeakyReLU(0.2, inplace=True))
98
+
99
+ def forward(self, x):
100
+ x = self.conv(x)
101
+ return x
102
+
103
+
104
+ class InBlock(nn.Module):
105
+ def __init__(self, in_ch, out_ch, kernel_size=3, num_groups=2, use_norm=True):
106
+ super(InBlock, self).__init__()
107
+ to_pad = int((kernel_size - 1) / 2)
108
+ if use_norm:
109
+ self.conv = nn.Sequential(
110
+ nn.Conv2d(in_ch, out_ch, kernel_size,
111
+ stride=1, padding=to_pad),
112
+ nn.GroupNorm(num_channels=out_ch, num_groups=num_groups),
113
+ nn.LeakyReLU(0.2, inplace=True))
114
+ else:
115
+ self.conv = nn.Sequential(
116
+ nn.Conv2d(in_ch, out_ch, kernel_size,
117
+ stride=1, padding=to_pad),
118
+ nn.LeakyReLU(0.2, inplace=True))
119
+
120
+ def forward(self, x):
121
+ x = self.conv(x)
122
+ return x
123
+
124
+
125
+ class UpBlock(nn.Module):
126
+ def __init__(self, in_ch, out_ch, skip_ch=4, kernel_size=3, num_groups=2, use_norm=True):
127
+ super(UpBlock, self).__init__()
128
+ to_pad = int((kernel_size - 1) / 2)
129
+ self.skip = skip_ch > 0
130
+ if skip_ch == 0:
131
+ skip_ch = 1
132
+ if use_norm:
133
+ self.conv = nn.Sequential(
134
+ nn.GroupNorm(num_channels=in_ch + skip_ch, num_groups=1), #LayerNorm
135
+ nn.Conv2d(in_ch + skip_ch, out_ch, kernel_size, stride=1,
136
+ padding=to_pad),
137
+ nn.GroupNorm(num_channels=out_ch, num_groups=num_groups),
138
+ nn.LeakyReLU(0.2, inplace=True),
139
+ nn.Conv2d(out_ch, out_ch, kernel_size,
140
+ stride=1, padding=to_pad),
141
+ nn.GroupNorm(num_channels=out_ch, num_groups=num_groups),
142
+ nn.LeakyReLU(0.2, inplace=True))
143
+ else:
144
+ self.conv = nn.Sequential(
145
+ nn.Conv2d(in_ch + skip_ch, out_ch, kernel_size, stride=1,
146
+ padding=to_pad),
147
+ nn.LeakyReLU(0.2, inplace=True),
148
+ nn.Conv2d(out_ch, out_ch, kernel_size,
149
+ stride=1, padding=to_pad),
150
+ nn.LeakyReLU(0.2, inplace=True))
151
+
152
+ if use_norm:
153
+ self.skip_conv = nn.Sequential(
154
+ nn.Conv2d(out_ch, skip_ch, kernel_size=1, stride=1),
155
+ nn.GroupNorm(num_channels=skip_ch, num_groups=1), #LayerNorm
156
+ nn.LeakyReLU(0.2, inplace=True))
157
+ else:
158
+ self.skip_conv = nn.Sequential(
159
+ nn.Conv2d(out_ch, skip_ch, kernel_size=1, stride=1),
160
+ nn.LeakyReLU(0.2, inplace=True))
161
+
162
+ self.up = nn.Upsample(scale_factor=2, mode='bilinear',
163
+ align_corners=True)
164
+ self.concat = Concat()
165
+
166
+ def forward(self, x1, x2):
167
+ x1 = self.up(x1)
168
+ x2 = self.skip_conv(x2)
169
+ if not self.skip:
170
+ x2 = x2 * 0
171
+ x = self.concat(x1, x2)
172
+ x = self.conv(x)
173
+ return x
174
+
175
+
176
+ class Concat(nn.Module):
177
+ def __init__(self):
178
+ super(Concat, self).__init__()
179
+
180
+ def forward(self, *inputs):
181
+ inputs_shapes2 = [x.shape[2] for x in inputs]
182
+ inputs_shapes3 = [x.shape[3] for x in inputs]
183
+
184
+ if (np.all(np.array(inputs_shapes2) == min(inputs_shapes2)) and
185
+ np.all(np.array(inputs_shapes3) == min(inputs_shapes3))):
186
+ inputs_ = inputs
187
+ else:
188
+ target_shape2 = min(inputs_shapes2)
189
+ target_shape3 = min(inputs_shapes3)
190
+
191
+ inputs_ = []
192
+ for inp in inputs:
193
+ diff2 = (inp.size(2) - target_shape2) // 2
194
+ diff3 = (inp.size(3) - target_shape3) // 2
195
+ inputs_.append(inp[:, :, diff2: diff2 + target_shape2,
196
+ diff3:diff3 + target_shape3])
197
+ return torch.cat(inputs_, dim=1)
198
+
199
+
200
+ class OutBlock(nn.Module):
201
+ def __init__(self, in_ch, out_ch):
202
+ super(OutBlock, self).__init__()
203
+ self.conv = nn.Conv2d(in_ch, out_ch, kernel_size=1, stride=1)
204
+
205
+ def forward(self, x):
206
+ x = self.conv(x)
207
+ return x
208
+
209
+ def __len__(self):
210
+ return len(self._modules)
211
+
212
+
213
+
214
+
215
+ class UNet_module(nn.Module):
216
+ def __init__(self, in_ch, out_ch, channels, skip_channels,
217
+ use_sigmoid=True, use_norm=True):
218
+ super(UNet_module, self).__init__()
219
+
220
+ assert (len(channels) == len(skip_channels))
221
+ self.scales = len(channels)
222
+ self.use_sigmoid = use_sigmoid
223
+ self.down = nn.ModuleList()
224
+ self.up = nn.ModuleList()
225
+ self.inc = InBlock(in_ch, channels[0], use_norm=use_norm)
226
+ for i in range(1, self.scales):
227
+ self.down.append(DownBlock(in_ch=channels[i - 1],
228
+ out_ch=channels[i],
229
+ use_norm=use_norm))
230
+ for i in range(1, self.scales):
231
+ self.up.append(UpBlock(in_ch=channels[-i],
232
+ out_ch=channels[-i - 1],
233
+ skip_ch=skip_channels[-i],
234
+ use_norm=use_norm))
235
+ self.outc = OutBlock(in_ch=channels[0],
236
+ out_ch=out_ch)
237
+
238
+ def forward(self, x0):
239
+ xs = [self.inc(x0), ]
240
+ for i in range(self.scales - 1):
241
+ xs.append(self.down[i](xs[-1]))
242
+ x = xs[-1]
243
+ for i in range(self.scales - 1):
244
+ x = self.up[i](x, xs[-2 - i])
245
+
246
+ return torch.sigmoid(self.outc(x)) if self.use_sigmoid else self.outc(x)
247
+
248
+
249
+
250
+ class UNet_pretrain(pl.LightningModule):
251
+ """
252
+ """
253
+ def __init__(self,
254
+ in_ch=1,
255
+ out_ch=2,
256
+ scales=16,
257
+ skip=4,
258
+ source_type = 'theta',
259
+ channels=[60,60,60,60,120,120,120,120,240, 240, 240,240,480, 480,480, 480],
260
+ use_sigmoid=False,
261
+ use_norm=True,
262
+ learning_rate=0.001,
263
+ step_size = 5,
264
+ gamma = 0.5,
265
+ weight_decay = 0.00001,
266
+ eta_min = 5e-4,
267
+ loss = 'rel_l2',
268
+ F_feature = False,
269
+ add_term = False,
270
+ val_exp = False,
271
+ src_path_breast = '',
272
+ gt_path_breast = '',
273
+ src_path_arm = '',
274
+ gt_path_arm = '',
275
+ src_path_limb = '',
276
+ gt_path_limb = ''
277
+ ):
278
+ super().__init__()
279
+ self.in_ch = in_ch
280
+ self.with_grid = True
281
+ if self.with_grid == True:
282
+ self.in_ch +=2
283
+ self.source_type = source_type
284
+ if self.source_type == 'source':
285
+ self.in_ch +=2
286
+ elif self.source_type == 'theta':
287
+ self.in_ch +=2
288
+ self.out_ch = out_ch
289
+ self.channels = channels
290
+ self.skip = skip
291
+ self.use_sigmoid = use_sigmoid
292
+ self.use_norm = use_norm
293
+ self.scales = scales
294
+ self.unet = self.build_unet()
295
+ self.save_hyperparameters()
296
+ self.learning_rate = learning_rate
297
+ self.step_size = step_size
298
+ self.gamma = gamma
299
+ self.weight_decay = weight_decay
300
+ self.F_feature = F_feature
301
+ self.add_term = add_term
302
+ self.eta_min = eta_min
303
+ if loss == 'l1':
304
+ self.criterion = nn.L1Loss()
305
+ self.criterion_val = RRMSE()
306
+ elif loss == 'l2':
307
+ self.criterion = nn.MSELoss()
308
+ self.criterion_val = RRMSE()
309
+ # self.criterion1 = LpLoss()
310
+ elif loss == 'smooth_l1':
311
+ self.criterion = nn.SmoothL1Loss()
312
+ self.criterion_val = RRMSE()
313
+ elif loss == "rel_l2":
314
+ self.criterion =LpLoss()
315
+ self.criterion_val = RRMSE()
316
+ self.F_feature = F_feature
317
+ self.add_term = add_term
318
+ self.val_iter = 0
319
+
320
+
321
+
322
+
323
+ def forward(self, sos,src):
324
+ if self.source_type == 'theta':
325
+ src_input = src[:,:,:,:]
326
+ elif self.source_type == 'source':
327
+ src_input = src[:,:,:,0:2]
328
+ x = sos
329
+ field = src[...,:2].clone()
330
+ if self.with_grid == True:
331
+ grid = get_grid2D(x.shape, x.device)
332
+ x = torch.cat((x,grid,src_input), dim=-1) # 100,960,960,4
333
+
334
+
335
+ x = self.unet(x.permute(0,3,1,2)).contiguous()
336
+ x = x.permute(0,2,3,1).contiguous()
337
+ #print(x.shape,field.shape)
338
+ if self.add_term == True:
339
+ x = torch.view_as_real(torch.view_as_complex(field)*(1+torch.view_as_complex(x)))
340
+ return x
341
+ def get_grid(self, shape, device):
342
+ batchsize, size_x, size_y = shape[0], shape[1], shape[2]
343
+ gridx = torch.tensor(np.linspace(0, 1, size_x), dtype=torch.float)
344
+ gridx = gridx.reshape(1, size_x, 1, 1).repeat([batchsize, 1, size_y, 1])
345
+ gridy = torch.tensor(np.linspace(0, 1, size_y), dtype=torch.float)
346
+ gridy = gridy.reshape(1, 1, size_y, 1).repeat([batchsize, size_x, 1, 1])
347
+ feature = []
348
+ gridxy = torch.cat((gridx,gridy), dim=-1).to(device)
349
+ feature.append(gridxy)
350
+ if self.F_feature == True:
351
+ for i in range(1,3):
352
+ feature.append(torch.sin(10**(-i)*gridxy))
353
+ return torch.cat(feature, dim=-1).to(device)
354
+
355
+ def build_unet(self):
356
+ """
357
+ Build UNet with group normalization
358
+ Parameters
359
+ ----------
360
+ Returns
361
+ -------
362
+ torch.nn module
363
+ UNet model
364
+ """
365
+ return get_unet_model(in_ch=self.in_ch, out_ch=self.out_ch, scales=self.scales, skip=self.skip,
366
+ channels=self.channels, use_sigmoid=self.use_sigmoid,
367
+ use_norm=self.use_norm)
368
+
369
+ def training_step(self, batch: torch.Tensor, batch_idx):
370
+ # training_step defines the train loop.
371
+ # it is independent of forward
372
+ sos,src,y, index = batch
373
+ batch_size = sos.shape[0]
374
+ out = self(sos,src)
375
+ loss = self.criterion(out.view(batch_size,-1), y.view(batch_size,-1))
376
+ self.log("loss", loss, on_epoch=True, prog_bar=True, logger=True)
377
+ wandb.log({"loss": loss.item()})
378
+ return loss
379
+
380
+ def validation_step(self, val_batch: torch.Tensor, batch_idx):
381
+ sos, src, y, index = val_batch
382
+ split_index = (index[-1] + index[0])//2
383
+ batch_size = sos.shape[0]
384
+ out = self(sos, src)
385
+ val_loss = self.criterion_val(out.view(batch_size, -1), y.view(batch_size, -1))
386
+
387
+ return val_loss
388
+
389
+ # def on_validation_epoch_end(self):
390
+ # error = self.validation_exp_breast(device = self.device)
391
+ # #self.log('exp_loss_breast', error.item(), on_epoch=True, prog_bar=True, logger=True)
392
+ # error = self.validation_exp_arm(device = self.device)
393
+ # #self.log('exp_loss_arm', error.item(), on_epoch=True, prog_bar=True, logger=True)
394
+ # error = self.validation_exp_limb(device = self.device)
395
+ # #self.log('exp_loss_limb', error.item(), on_epoch=True, prog_bar=True, logger=True)
396
+
397
+
398
+ def configure_optimizers(self, optimizer=None, scheduler=None):
399
+ if optimizer is None:
400
+ optimizer = optim.AdamW(self.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay)
401
+ if scheduler is None:
402
+ #scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer,T_max = self.step_size, eta_min= self.eta_min)
403
+ scheduler = optim.lr_scheduler.StepLR(optimizer, step_size = 6, gamma = 0.1)# 6 0.5
404
+
405
+ return {
406
+ "optimizer": optimizer,
407
+ "lr_scheduler": {
408
+ "scheduler": scheduler
409
+ },
410
+ }
411
+
412
+
413
+
414
+
415
+
homo/homo_250k.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76b6e85d0c470688132d91f59f85562b7a58a3ef802b65d592698ec26602edd5
3
+ size 117964928
homo/homo_300k.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad848793b15e23d4d1bf4489c2fc6cabd20850371f983256dd34129e9623a516
3
+ size 117964928
homo/homo_350k.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2bbdfe530d63c1299cadd4e4eb054ff8899928aafca9fc0ae8db581cef972ab9
3
+ size 117964928
homo/homo_400k.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:175184f037731587ef524947edc46835b798a3a4e10a50c68cfaba689daf31f1
3
+ size 117964928
homo/homo_450k.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2eace32059c2fc1006f3795b29c2ec45af4ee71a47a77700daad3cfcc69530c
3
+ size 117964928
homo/homo_500k.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:318ce9c418eabe3cdf3d0147bffd5320b80a41db2bbe41d8dfa41cdfad71cb93
3
+ size 117964928
homo/homo_550k.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb054e3922a0f8f46c616b30fce67574c7057bc230764e33960f3bca56137550
3
+ size 117964928
homo/homo_600k.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac7513b7535530ae76237eda83df46447585f86a87898a37b443d1e765f18bc6
3
+ size 117964928
limb_wavefield.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import numpy as np
4
+ from torch.utils.data import Dataset, DataLoader
5
+ from collections import OrderedDict
6
+ import matplotlib.pyplot as plt
7
+ import torch.nn as nn
8
+ from torch import optim
9
+ import torch.nn.functional as F
10
+ # import sys
11
+ # import random
12
+ from matplotlib.patches import Rectangle
13
+ import argparse
14
+ torch.set_float32_matmul_precision("medium")
15
+ def main(model_name):
16
+
17
+ if model_name == 'S2NO_big':
18
+ from S2NO_pretrain import S2NO_pretrain
19
+ model = S2NO_pretrain().cuda()
20
+ PATH = './S2NO/big/600k.ckpt'
21
+ if model_name == 'S2NO_small':
22
+ from S2NO_pretrain import S2NO_pretrain
23
+ model = S2NO_pretrain(width = 20).cuda()
24
+ PATH = './S2NO/small/600k.ckpt'
25
+ # PATH = '/gpfs/share/home/2401112587/neuralFWI/NCBSO_ckpt/NCBSO_20width_mq_lr01_final/600k_model-epoch=007-val_loss=0.0856-val_loss_breast=0.0772-val_loss_arm=0.0773-val_loss_limb=0.1391.ckpt'
26
+ if model_name == 'FNO_big':
27
+ from FNO_pretrain import FNO_pretrain
28
+ model = FNO_pretrain(features_ = 40).cuda()
29
+ PATH = './FNO/big/600k.ckpt'
30
+ if model_name == 'FNO_small':
31
+ from FNO_pretrain import FNO_pretrain
32
+ model = FNO_pretrain(features_ = 20).cuda()
33
+ PATH = './FNO/small/600k.ckpt'
34
+ if model_name == 'UNet':
35
+ from UNet_pretrain import UNet_pretrain
36
+ model =UNet_pretrain().cuda()
37
+ PATH = './UNet/600k.ckpt'
38
+ checkpoint = torch.load(PATH, map_location=lambda storage, loc: storage)
39
+ model.load_state_dict(checkpoint['state_dict'])
40
+
41
+ homo = np.load('./homo/homo_600k.npy')[0:1,:,:]
42
+ field_real = torch.tensor(np.real(homo))
43
+ field_imag = torch.tensor(np.imag(homo))
44
+ model.eval()
45
+
46
+ def inference(data, field_real, field_imag):
47
+ data = (1500/data - 1)*30
48
+ data = torch.tensor(data, dtype=torch.float).cuda()
49
+ batchsize = field_real.shape[0]
50
+ sos = data.reshape(1,480, 480, 1).repeat(batchsize,1,1,1).cuda()
51
+ field = torch.concat([field_real.unsqueeze(-1), field_imag.unsqueeze(-1)], dim=-1).cuda() * 2e-3
52
+ src = field
53
+ pred = model(sos, src)
54
+ pred = pred * 500
55
+ pred = pred[...,0] + 1j*pred[...,1]
56
+ return pred
57
+
58
+ # 这里定义两块子图的行列范围(row_start:row_end, col_start:col_end)
59
+ sub1_row_start, sub1_row_end = 323, 343
60
+ sub1_col_start, sub1_col_end = 230, 250
61
+ sub2_row_start, sub2_row_end = 234, 254
62
+ sub2_col_start, sub2_col_end = 184, 204
63
+
64
+ index = [36]
65
+ for i in range(len(index)):
66
+ path = f'./speed/test_{index[i]}.npy'
67
+ data = np.load(path)
68
+ # 推理得到 pred
69
+ pred = inference(data, field_real, field_imag)
70
+ pred_np = pred.detach().cpu().numpy()
71
+ pred_real = np.real(pred_np)
72
+
73
+ # 分别画出两个子图并保存
74
+ # 子图1
75
+ fig, ax = plt.subplots(figsize=(5,5), dpi=300)
76
+ ax.imshow(np.squeeze(pred_real)[
77
+ sub1_row_start:sub1_row_end,
78
+ sub1_col_start:sub1_col_end],
79
+ cmap='seismic',
80
+ vmin=-2000, vmax=2000)
81
+ ax.spines['top'].set_visible(False)
82
+ ax.spines['right'].set_visible(False)
83
+ ax.spines['bottom'].set_visible(False)
84
+ ax.spines['left'].set_visible(False)
85
+ ax.get_xaxis().set_visible(False)
86
+ ax.get_yaxis().set_visible(False)
87
+ plt.savefig(f'./result/{model_name}_limb_{index[i]}_small1.pdf',
88
+ bbox_inches='tight', pad_inches=0)
89
+ plt.close()
90
+
91
+ # 子图2
92
+ fig, ax = plt.subplots(figsize=(5,5), dpi=300)
93
+ ax.imshow(np.squeeze(pred_real)[
94
+ sub2_row_start:sub2_row_end,
95
+ sub2_col_start:sub2_col_end],
96
+ cmap='seismic',
97
+ vmin=-2000, vmax=2000)
98
+ ax.spines['top'].set_visible(False)
99
+ ax.spines['right'].set_visible(False)
100
+ ax.spines['bottom'].set_visible(False)
101
+ ax.spines['left'].set_visible(False)
102
+ ax.get_xaxis().set_visible(False)
103
+ ax.get_yaxis().set_visible(False)
104
+ plt.savefig(f'./result/{model_name}_limb_{index[i]}_small2.pdf',
105
+ bbox_inches='tight', pad_inches=0)
106
+ plt.close()
107
+
108
+ # 在大图上两个子图相应位置标注出方框
109
+ # 注意:matplotlib 中默认 (x, y) 是 (列索引, 行索引),
110
+ # 因此填入 Rectangle 的时候,需要 (col_start, row_start, width, height)
111
+ # 画大图 + 标注方框
112
+ fig, ax = plt.subplots(figsize=(5,5), dpi=300)
113
+ ax.imshow(np.squeeze(pred_real),
114
+ cmap='seismic',
115
+ vmin=-2000, vmax=2000)
116
+
117
+ # 第一个方框
118
+ rect1 = Rectangle((sub1_col_start, sub1_row_start),
119
+ sub1_col_end - sub1_col_start, # width
120
+ sub1_row_end - sub1_row_start, # height
121
+ fill=False,
122
+ edgecolor='#8CA5D3',
123
+ linewidth=2)
124
+ ax.add_patch(rect1)
125
+
126
+ # 第二个方框
127
+ rect2 = Rectangle((sub2_col_start, sub2_row_start),
128
+ sub2_col_end - sub2_col_start,
129
+ sub2_row_end - sub2_row_start,
130
+ fill=False,
131
+ edgecolor='#EDAD81',
132
+ linewidth=2)
133
+ ax.add_patch(rect2)
134
+
135
+ ax.spines['top'].set_visible(False)
136
+ ax.spines['right'].set_visible(False)
137
+ ax.spines['bottom'].set_visible(False)
138
+ ax.spines['left'].set_visible(False)
139
+ ax.get_xaxis().set_visible(False)
140
+ ax.get_yaxis().set_visible(False)
141
+
142
+ # 保存带方框的大图
143
+ plt.savefig(f'./result/{model_name}_limb_{index[i]}_with_box.pdf',
144
+ bbox_inches='tight', pad_inches=0)
145
+ plt.close()
146
+ if __name__ == '__main__':
147
+ # 解析命令行参数
148
+ parser = argparse.ArgumentParser(description='Run model inference with specified model.')
149
+ parser.add_argument('--model_name', type=str, required=True,
150
+ choices=['S2NO_big', 'S2NO_small', 'FNO_big', 'FNO_small','UNet'],
151
+ help='Name of the model to use (e.g., S2NO_small)')
152
+ args = parser.parse_args()
153
+ # 调用主函数
154
+ main(args.model_name)
result/S2NO_small_limb_36_small1.pdf ADDED
Binary file (10.4 kB). View file
 
result/S2NO_small_limb_36_small2.pdf ADDED
Binary file (9.94 kB). View file
 
result/S2NO_small_limb_36_with_box.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1cfce843e4898e73f30b60a38fa2c93a66511bb8cb8d6db4252124d8dae1b72f
3
+ size 783284
speed/test_36.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c77570ff75b1d128adb1cf48d4dd4db5744529fcbfbbb79ef8cadbe2bd9da42
3
+ size 921728