forked from neuraloperator/neuraloperator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fourier_1d.py
232 lines (181 loc) · 6.91 KB
/
fourier_1d.py
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
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
import matplotlib.pyplot as plt
import operator
from functools import reduce
from functools import partial
from timeit import default_timer
from utilities3 import *
torch.manual_seed(0)
np.random.seed(0)
#Complex multiplication
def compl_mul1d(a, b):
# (batch, in_channel, x ), (in_channel, out_channel, x) -> (batch, out_channel, x)
op = partial(torch.einsum, "bix,iox->box")
return torch.stack([
op(a[..., 0], b[..., 0]) - op(a[..., 1], b[..., 1]),
op(a[..., 1], b[..., 0]) + op(a[..., 0], b[..., 1])
], dim=-1)
################################################################
# 1d fourier layer
################################################################
class SpectralConv1d(nn.Module):
def __init__(self, in_channels, out_channels, modes1):
super(SpectralConv1d, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.modes1 = modes1 #Number of Fourier modes to multiply, at most floor(N/2) + 1
self.scale = (1 / (in_channels*out_channels))
self.weights1 = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, self.modes1, 2))
def forward(self, x):
batchsize = x.shape[0]
#Compute Fourier coeffcients up to factor of e^(- something constant)
x_ft = torch.rfft(x, 1, normalized=True, onesided=True)
# Multiply relevant Fourier modes
out_ft = torch.zeros(batchsize, self.in_channels, x.size(-1)//2 + 1, 2, device=x.device)
out_ft[:, :, :self.modes1] = compl_mul1d(x_ft[:, :, :self.modes1], self.weights1)
#Return to physical space
x = torch.irfft(out_ft, 1, normalized=True, onesided=True, signal_sizes=(x.size(-1), ))
return x
class SimpleBlock1d(nn.Module):
def __init__(self, modes, width):
super(SimpleBlock1d, self).__init__()
self.modes1 = modes
self.width = width
self.fc0 = nn.Linear(2, self.width)
self.conv0 = SpectralConv1d(self.width, self.width, self.modes1)
self.conv1 = SpectralConv1d(self.width, self.width, self.modes1)
self.conv2 = SpectralConv1d(self.width, self.width, self.modes1)
self.conv3 = SpectralConv1d(self.width, self.width, self.modes1)
self.w0 = nn.Conv1d(self.width, self.width, 1)
self.w1 = nn.Conv1d(self.width, self.width, 1)
self.w2 = nn.Conv1d(self.width, self.width, 1)
self.w3 = nn.Conv1d(self.width, self.width, 1)
self.bn0 = torch.nn.BatchNorm1d(self.width)
self.bn1 = torch.nn.BatchNorm1d(self.width)
self.bn2 = torch.nn.BatchNorm1d(self.width)
self.bn3 = torch.nn.BatchNorm1d(self.width)
self.fc1 = nn.Linear(self.width, 128)
self.fc2 = nn.Linear(128, 1)
def forward(self, x):
x = self.fc0(x)
x = x.permute(0, 2, 1)
x1 = self.conv0(x)
x2 = self.w0(x)
x = self.bn0(x1 + x2)
x = F.relu(x)
x1 = self.conv1(x)
x2 = self.w1(x)
x = self.bn1(x1 + x2)
x = F.relu(x)
x1 = self.conv2(x)
x2 = self.w2(x)
x = self.bn2(x1 + x2)
x = F.relu(x)
x1 = self.conv3(x)
x2 = self.w3(x)
x = self.bn3(x1 + x2)
x = x.permute(0, 2, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
return x
class Net1d(nn.Module):
def __init__(self, modes, width):
super(Net1d, self).__init__()
self.conv1 = SimpleBlock1d(modes, width)
def forward(self, x):
x = self.conv1(x)
return x.squeeze()
def count_params(self):
c = 0
for p in self.parameters():
c += reduce(operator.mul, list(p.size()))
return c
################################################################
# configurations
################################################################
ntrain = 1000
ntest = 100
sub = 1 #subsampling rate
h = 2**10 // sub
s = h
batch_size = 20
learning_rate = 0.001
epochs = 500
step_size = 100
gamma = 0.5
modes = 16
width = 64
################################################################
# read data
################################################################
dataloader = MatReader('data/burgers_data_R10.mat')
x_data = dataloader.read_field('a')[:,::sub]
y_data = dataloader.read_field('u')[:,::sub]
x_train = x_data[:ntrain,:]
y_train = y_data[:ntrain,:]
x_test = x_data[-ntest:,:]
y_test = y_data[-ntest:,:]
# cat the locations information
grid = np.linspace(0, 2*np.pi, s).reshape(1, s, 1)
grid = torch.tensor(grid, dtype=torch.float)
x_train = torch.cat([x_train.reshape(ntrain,s,1), grid.repeat(ntrain,1,1)], dim=2)
x_test = torch.cat([x_test.reshape(ntest,s,1), grid.repeat(ntest,1,1)], dim=2)
train_loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(x_train, y_train), batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(x_test, y_test), batch_size=batch_size, shuffle=False)
# model
model = Net1d(modes, width).cuda()
print(model.count_params())
################################################################
# training and evaluation
################################################################
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=gamma)
myloss = LpLoss(size_average=False)
for ep in range(epochs):
model.train()
t1 = default_timer()
train_mse = 0
train_l2 = 0
for x, y in train_loader:
x, y = x.cuda(), y.cuda()
optimizer.zero_grad()
out = model(x)
mse = F.mse_loss(out, y, reduction='mean')
# mse.backward()
l2 = myloss(out.view(batch_size, -1), y.view(batch_size, -1))
l2.backward()
optimizer.step()
train_mse += mse.item()
train_l2 += l2.item()
scheduler.step()
model.eval()
test_l2 = 0.0
with torch.no_grad():
for x, y in test_loader:
x, y = x.cuda(), y.cuda()
out = model(x)
test_l2 += myloss(out.view(batch_size, -1), y.view(batch_size, -1)).item()
train_mse /= len(train_loader)
train_l2 /= ntrain
test_l2 /= ntest
t2 = default_timer()
print(ep, t2-t1, train_mse, train_l2, test_l2)
# torch.save(model, 'model/ns_fourier_burgers_8192')
pred = torch.zeros(y_test.shape)
index = 0
test_loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(x_test, y_test), batch_size=1, shuffle=False)
with torch.no_grad():
for x, y in test_loader:
test_l2 = 0
x, y = x.cuda(), y.cuda()
out = model(x)
pred[index] = out
test_l2 += myloss(out.view(1, -1), y.view(1, -1)).item()
print(index, test_l2)
index = index + 1
# scipy.io.savemat('pred/burger_test.mat', mdict={'pred': pred.cpu().numpy()})