| import numpy as np |
| import torch |
| import pytorch_lightning as pl |
| from torch import optim, nn |
| import torch.nn.functional as F |
|
|
| import wandb |
| import matplotlib.pyplot as plt |
| import math |
| import os |
| from scipy.io import loadmat |
|
|
| class LpLoss(object): |
| def __init__(self, d=2, p=2, size_average=True, reduction=True): |
| super(LpLoss, self).__init__() |
| assert d > 0 and p > 0 |
| self.d = d |
| self.p = p |
| self.reduction = reduction |
| self.size_average = size_average |
| def abs(self, x, y): |
| num_examples = x.size()[0] |
| h = 1.0 / (x.size()[1] - 1.0) |
| all_norms = (h**(self.d/self.p))*torch.norm(x.view(num_examples,-1) - y.view(num_examples,-1), self.p, 1) |
| if self.reduction: |
| if self.size_average: |
| return torch.mean(all_norms) |
| else: |
| return torch.sum(all_norms) |
| return all_norms |
|
|
| def rel(self, x, y): |
| num_examples = x.size()[0] |
| |
| diff_norms = torch.norm(x.reshape(num_examples,-1) - y.reshape(num_examples,-1), self.p, 1) |
| y_norms = torch.norm(y.reshape(num_examples,-1), self.p, 1) |
| |
| if self.reduction: |
| if self.size_average: |
| return torch.mean(diff_norms/y_norms) |
| else: |
| return torch.sum(diff_norms/y_norms) |
|
|
| return diff_norms/y_norms |
|
|
| def __call__(self, x, y): |
| return self.rel(x, y) |
| |
|
|
| class RRMSE(object): |
| def __init__(self, ): |
| super(RRMSE, self).__init__() |
| |
| def __call__(self, x, y): |
| num_examples = x.size()[0] |
| norm = torch.norm(x.view(num_examples,-1) - y.view(num_examples,-1), 2 , 1)**2 |
| normy = torch.norm( y.view(num_examples,-1), 2 , 1)**2 |
| mean_norm = torch.mean((norm/normy)**(1/2)) |
| return mean_norm |
| |
|
|
| class SpectralConv2d_born(nn.Module): |
| ''' |
| Input: |
| x: batch,in, x,y |
| x_eps: batch,in,x,y |
| Output: batch,out,x,y |
| ''' |
| def __init__(self, in_channels, out_channels, modes1, modes2): |
| super(SpectralConv2d_born, self).__init__() |
|
|
| """ |
| 2D Fourier layer. It does FFT, linear transform, and Inverse FFT. |
| """ |
|
|
| self.in_channels = in_channels |
| self.out_channels = out_channels |
| self.modes1 = modes1 |
| self.modes2 = modes2 |
| self.scale = 1 / (in_channels * out_channels) |
| self.weights1 = nn.Parameter( |
| self.scale * torch.rand(in_channels, out_channels, self.modes1, self.modes2,2, dtype=torch.float32) |
| ) |
| self.weights2 = nn.Parameter( |
| self.scale * torch.rand(in_channels, out_channels, self.modes1, self.modes2,2, dtype=torch.float32) |
| ) |
| def compl_mul2d(self,input, weights): |
| |
| real = torch.einsum('bixy,ioxy->boxy',input[...,0],weights[...,0])-torch.einsum('bixy,ioxy->boxy',input[...,1],weights[...,1]) |
| comp = torch.einsum('bixy,ioxy->boxy',input[...,0],weights[...,1])+torch.einsum('bixy,ioxy->boxy',input[...,1],weights[...,0]) |
| output = torch.cat((real.unsqueeze(-1),comp.unsqueeze(-1)),dim = -1) |
| |
| return output |
| |
| |
| |
| |
|
|
| def forward(self, x, x_eps): |
| batchsize = x.shape[0] |
| |
| x_ft = torch.view_as_real(torch.fft.rfft2(x * x_eps)) |
| |
| out_ft = torch.zeros( |
| batchsize, self.out_channels, x.size(-2), x.size(-1) // 2 + 1,2, dtype=torch.float32, device=x.device |
| ) |
| |
| out_ft[:, :, : self.modes1, : self.modes2] = self.compl_mul2d( |
| x_ft[:, :, : self.modes1, : self.modes2,:], self.weights1 |
| ) |
| out_ft[:, :, -self.modes1 :, : self.modes2] = self.compl_mul2d( |
| x_ft[:, :, -self.modes1 :, : self.modes2,:], self.weights2 |
| ) |
| |
| x = torch.fft.irfft2(torch.view_as_complex(out_ft), s=(x.size(-2), x.size(-1))) |
| return x |
|
|
|
|
| class FNO_step(nn.Module): |
| def __init__(self, width, modes1, modes2 ): |
| super(FNO_step, self).__init__() |
| self.modes1 = modes1 |
| self.modes2 = modes2 |
| self.width = width |
| self.conv0 = SpectralConv2d_born(self.width, self.width, self.modes1, self.modes2) |
| self.w0 = nn.Conv2d(self.width, self.width, 1) |
| self.w1 = nn.Conv2d(self.width, self.width, 1) |
| self.bn = nn.BatchNorm2d(self.width, eps=0, momentum=0.5, affine=True) |
| |
| def forward(self,input): |
| |
| x,v_v,v_q,x_0, v_mq= input |
| x_n = x.clone() |
| x = self.conv0(x, v_v) |
| x = x * v_mq+ v_q * x_n |
| x = self.w1(F.leaky_relu(self.w0(x))) |
| x = F.leaky_relu(x) |
| x = x + x_0 |
| x = self.bn(x) |
| return [x,v_v,v_q,x_0,v_mq] |
|
|
| class S2NO_step_wrap(nn.Module): |
| def __init__(self, model,width): |
| super(S2NO_step_wrap, self).__init__() |
| self.model = model |
| |
| self.bn = nn.BatchNorm2d(width, eps=0, momentum=0.5, affine=True) |
| |
| |
| def forward(self,input): |
| |
| |
| [x,v_v,v_q,x_0] = self.model(input) |
| x = self.bn(x) |
| return [x,v_v,v_q,x_0] |
|
|
|
|
| class S2NO_pretrain(pl.LightningModule): |
| def __init__(self,width=40, |
| modes1=128, |
| modes2=128, |
| layer_num=7, |
| padding = 6, |
| dim_input = 1, |
| source_type = 'theta', |
| loss = "rel_l2", |
| learning_rate = 1e-2, |
| step_size= 100, |
| gamma= 0.5, |
| weight_decay= 1e-5, |
| F_feature = False, |
| add_term = False, |
| eta_min = 2e-4, |
| val_exp = False, |
| src_path_breast = '', |
| gt_path_breast = '', |
| src_path_arm = '', |
| gt_path_arm = '', |
| src_path_limb = '', |
| gt_path_limb = '' |
| ): |
| super().__init__() |
| self.with_grid = True |
| if self.with_grid == True: |
| dim_input +=2 |
| self.source_type = source_type |
| if self.source_type == 'source': |
| dim_input +=2 |
| elif self.source_type == 'theta': |
| dim_input +=2 |
| self.padding = padding |
| self.learning_rate = learning_rate |
| self.step_size = step_size |
| self.gamma = gamma |
| self.weight_decay = weight_decay |
| self.eta_min = eta_min |
| if loss == 'l1': |
| self.criterion = nn.L1Loss() |
| elif loss == 'l2': |
| self.criterion = nn.MSELoss() |
| self.criterion_val = LpLoss() |
| elif loss == "rel_l2": |
| self.criterion =LpLoss() |
| self.criterion_val = RRMSE() |
|
|
|
|
| |
| self.modes1 = modes1 |
| self.modes2 = modes2 |
| self.width = width |
| self.padding = padding |
| self.fc_c1 = nn.Linear(3, self.width) |
| self.fc_c2 = nn.Linear(self.width, self.width) |
| self.fc_c3 = nn.Linear(3, self.width) |
| self.fc_c4 = nn.Linear(self.width, self.width) |
| self.fc_0 = nn.Linear(dim_input, self.width) |
| self.layer_num = layer_num |
| self.fno_step = [] |
|
|
| for i in range(layer_num): |
| self.fno_step.append(FNO_step(self.width,self.modes1,self.modes2).to(self.device)) |
| self.net =nn.Sequential(*self.fno_step) |
| self.F_feature = F_feature |
| self.add_term = add_term |
| self.fc1 = nn.Linear(self.width, 256) |
| self.fc2 = nn.Linear(256, 2) |
| self.val_iter = 0 |
| self.bn = nn.BatchNorm2d(self.width, eps=0, momentum=0.5, affine=True, track_running_stats=True) |
| |
| self.val_exp = val_exp |
| self.save_path = None |
| self.exp_name = None |
| self.src_path_breast = src_path_breast |
| self.gt_path_breast = gt_path_breast |
| self.src_path_arm = src_path_arm |
| self.src_path_limb = src_path_limb |
| self.gt_path_arm = gt_path_arm |
| self.gt_path_limb = gt_path_limb |
| if self.val_exp: |
| data = loadmat('/gpfs/share/home/2201213309/neuralFWI/breast_generator0822/exp_matcode/breast0718.mat')['image'] |
| data = (1500/data-1)*30 |
| sos = torch.tensor(data,dtype=torch.float).view(1,480,480,1) |
| sos = sos.repeat(64,1,1,1) |
| self.sos_exp_breast = sos |
| index_2 = np.arange(0,64).reshape(64,1,1,1) |
| src = np.load(self.src_path_breast)[:,:,:]*2e-3 |
| src = np.concatenate((np.real(src)[:,:,:,np.newaxis],np.imag(src)[:,:,:,np.newaxis]),axis = -1) |
| self.src_exp_breast = torch.tensor(src,dtype=torch.float).view(64,480,480,2) |
| gt_np = loadmat(self.gt_path_breast)['u_all_single'] |
| gt = torch.view_as_real(torch.tensor(gt_np)) |
| self.gt_breast = torch.tensor(gt) |
|
|
| |
| data = loadmat('/gpfs/share/home/2201213309/neuralFWI/arm_generator1020/code1020/armcbs1022.mat')['speed'] |
| data = (1500/data-1)*30 |
| sos = torch.tensor(data,dtype=torch.float).view(1,480,480,1) |
| sos = sos.repeat(64,1,1,1) |
| self.sos_exp_arm = sos |
| index_2 = np.arange(0,64).reshape(64,1,1,1) |
| src = np.load(self.src_path_arm)[:,:,:]*2e-3 |
| |
| src = np.concatenate((np.real(src)[:,:,:,np.newaxis],np.imag(src)[:,:,:,np.newaxis]),axis = -1) |
| self.src_exp_arm = torch.tensor(src,dtype=torch.float).view(64,480,480,2) |
| gt_np = loadmat(self.gt_path_arm)['u_all_single'] |
| gt = torch.view_as_real(torch.tensor(gt_np)) |
| self.gt_arm = torch.tensor(gt) |
|
|
| |
| data = loadmat('/gpfs/share/home/2201213309/neuralFWI/limb_regenerator_1031/code1031/limb0718.mat')['image'] |
| data = (1500/data-1)*30 |
| sos = torch.tensor(data,dtype=torch.float).view(1,480,480,1) |
| sos = sos.repeat(64,1,1,1) |
| self.sos_exp_limb = sos |
| index_2 = np.arange(0,64).reshape(64,1,1,1) |
| src = np.load(self.src_path_limb)[:,:,:]*2e-3 |
| |
| src = np.concatenate((np.real(src)[:,:,:,np.newaxis],np.imag(src)[:,:,:,np.newaxis]),axis = -1) |
| self.src_exp_limb = torch.tensor(src,dtype=torch.float).view(64,480,480,2) |
| gt_np = loadmat(self.gt_path_limb)['u_all_single'] |
| gt = torch.view_as_real(torch.tensor(gt_np)) |
| self.gt_limb = torch.tensor(gt) |
| |
|
|
| |
| def forward(self,sos,src): |
| ''' |
| x: batch,x,y,channel=3 (c(x),s(x)) |
| ''' |
| if self.source_type == 'theta': |
| src_input = src[:,:,:,:] |
| elif self.source_type == 'source': |
| src_input = src[:,:,:,0:2] |
| |
| x_1 = sos |
| field = src[...,0:2].clone() |
| |
| grid = self.get_grid(x_1.shape, x_1.device, field) |
|
|
| x_0 = torch.cat((x_1, grid,src_input), dim=-1) |
| x_c = torch.cat((x_1, grid), dim=-1) |
| |
| v_0 = self.fc_0(x_0) |
| v_0 = v_0.permute(0, 3, 1, 2) |
| if self.padding >=1: |
| v_0 = F.pad(v_0, [0, self.padding, 0, self.padding]) |
|
|
| v_v = self.fc_c2(F.tanh(self.fc_c1(x_c))) |
| v_v = v_v.permute(0, 3, 1, 2) |
| if self.padding >=1: |
| v_v = F.pad(v_v, [0, self.padding, 0, self.padding]) |
| v_q = self.fc_c4(F.tanh(self.fc_c3(x_c))) |
| v_q = v_q.permute(0, 3, 1, 2) |
| if self.padding >=1: |
| v_q = F.pad(v_q, [0, self.padding, 0, self.padding]) |
| v_mq = 1 - v_q |
| x_1 = v_0 |
| x_out = x_1.clone() |
| |
| [x_out,v_v,v_q,x_1,v_mq] = self.net([x_out,v_v,v_q,x_1, v_mq]) |
| if self.padding >=1: |
| x_out = x_out[..., : -self.padding, : -self.padding] |
| x_out = x_out.permute(0, 2, 3, 1) |
| x_out = self.fc1(x_out) |
| x_out = F.leaky_relu(x_out) |
| x_out = self.fc2(x_out) |
| if self.add_term == True: |
| |
| x_out = torch.view_as_real(torch.view_as_complex(field.to(x_out.device))*(1+torch.view_as_complex(x_out))) |
| return x_out |
|
|
| def get_grid(self, shape, device,field): |
| batchsize, size_x, size_y = shape[0], shape[1], shape[2] |
| gridx = torch.tensor(np.linspace(0, 1, size_x), dtype=torch.float) |
| gridx = gridx.reshape(1, size_x, 1, 1).repeat([batchsize, 1, size_y, 1]) |
| gridy = torch.tensor(np.linspace(0, 1, size_y), dtype=torch.float) |
| gridy = gridy.reshape(1, 1, size_y, 1).repeat([batchsize, size_x, 1, 1]) |
| |
| gridxy = torch.cat((gridx,gridy), dim=-1).to(device) |
| |
| |
| |
| |
| |
| |
| return gridxy |
| |
| def training_step(self, batch: torch.Tensor, batch_idx): |
| sos,src,y,index = batch |
| batch_size = sos.shape[0] |
| out = self(sos,src) |
| loss = self.criterion(out, y) |
| self.log("loss", loss, on_epoch=True, prog_bar=True, logger=True) |
| wandb.log({"loss": loss.item()}) |
| return loss |
|
|
| def validation_step(self, val_batch: torch.Tensor, batch_idx): |
| sos, src, y, index = val_batch |
| split_index = (index[-1] + index[0])//2 |
| batch_size = sos.shape[0] |
| out = self(sos, src) |
| val_loss = self.criterion_val(out.view(batch_size, -1), y.view(batch_size, -1)) |
|
|
| |
| return val_loss |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| def configure_optimizers(self, optimizer=None, scheduler=None): |
| if optimizer is None: |
| optimizer = optim.AdamW(self.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay) |
| if scheduler is None: |
| |
| scheduler = optim.lr_scheduler.StepLR(optimizer, step_size = 6, gamma = 0.1) |
|
|
| return { |
| "optimizer": optimizer, |
| "lr_scheduler": { |
| "scheduler": scheduler |
| }, |
| } |
|
|
|
|
|
|
|
|
|
|
|
|