-
Notifications
You must be signed in to change notification settings - Fork 2
/
Helm_pinn_sine_adaptive.py
286 lines (204 loc) · 8.66 KB
/
Helm_pinn_sine_adaptive.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
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
"""
@author: Chao Song
"""
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
from scipy.interpolate import griddata
import time
import cmath
np.random.seed(1234)
tf.set_random_seed(1234)
#fre = 4.0 #for homogeneous model
fre = 3.0 #for Marmousi model
PI = 3.1415926
omega = 2.0*PI*fre
#niter = 50000 #for homogeneous model
niter = 100000 #for Marmousi model
w0_n = []
misfit = []
misfit1 = []
def fwd_gradients(Y, x):
dummy = tf.ones_like(Y)
G = tf.gradients(Y, x, grad_ys=dummy, colocate_gradients_with_ops=True)[0]
Y_x = tf.gradients(G, dummy, colocate_gradients_with_ops=True)[0]
return Y_x
class PhysicsInformedNN:
# Initialize the class
def __init__(self, x, z, A, B, C, ps, m, layers, omega):
X = np.concatenate([x, z], 1)
self.iter=0
self.start_time=0
self.lb = X.min(0)
self.ub = X.max(0)
self.X = X
self.x = X[:,0:1]
self.z = X[:,1:2]
self.ps = ps
self.m = m
self.A = A
self.B = B
self.C = C
self.layers = layers
self.omega = omega
# Initialize NN
self.weights, self.biases, self.w0 = self.initialize_NN(layers)
# tf placeholders
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
log_device_placement=True))
self.x_tf = tf.placeholder(tf.float32, shape=[None, self.x.shape[1]])
self.z_tf = tf.placeholder(tf.float32, shape=[None, self.z.shape[1]])
self.u_real_pred, self.u_imag_pred, self.f_loss = self.net_NS(self.x_tf, self.z_tf)
# loss function we define
self.loss = tf.reduce_sum(tf.square(tf.abs(self.f_loss)))
# optimizer used by default (in original paper)
self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss,
method = 'L-BFGS-B',
options = {'maxiter': 50000,
'maxfun': 50000,
'maxcor': 50,
'maxls': 50,
'ftol' : 1.0 * np.finfo(float).eps})
self.global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.001
self.learning_rate = tf.train.exponential_decay(starter_learning_rate, self.global_step,
10000, 0.9, staircase=False)
self.optimizer_Adam = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
self.train_op_Adam = self.optimizer_Adam.minimize(self.loss)
init = tf.global_variables_initializer()
self.sess.run(init)
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
w0 = tf.Variable(tf.zeros([1,1], dtype=tf.float32)+3.0, dtype=tf.float32)
for l in range(0,num_layers-1):
if (l == 0):
W = self.xavier_init_first(size=[layers[l], layers[l+1]])
else:
W = self.xavier_init(w0,size=[layers[l], layers[l+1]])
b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32)+0.0, dtype=tf.float32)
weights.append(W)
biases.append(b)
return weights, biases, w0
def xavier_init(self, w0, size):
in_dim = size[0]
out_dim = size[1]
w_std = np.sqrt(3.0/in_dim)/w0
return tf.Variable(tf.random_uniform([in_dim, out_dim], -w_std, w_std), dtype=tf.float32)
def xavier_init_first(self, size):
in_dim = size[0]
out_dim = size[1]
w_std = np.sqrt(3.0/in_dim)
return tf.Variable(tf.random_uniform([in_dim, out_dim], -w_std, w_std), dtype=tf.float32)
def neural_net(self, X, weights, biases, w0):
num_layers = len(weights) + 1
H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0
H = w0*H
for l in range(0,num_layers-2):
W = weights[l]
b = biases[l]
H = tf.sin(tf.add(tf.matmul(H, W), b))
W = weights[-1]
b = biases[-1]
Y = tf.add(tf.matmul(H, W), b)
return Y
def net_NS(self, x, z):
omega = self.omega
m = self.m
ps = self.ps
A = self.A
B = self.B
C = self.C
ureal_and_uimag = self.neural_net(tf.concat([x,z], 1), self.weights, self.biases, self.w0)
u_real = ureal_and_uimag[:,0:1]
u_imag = ureal_and_uimag[:,1:2]
u = tf.complex(u_real, u_imag)
dudx = fwd_gradients(u, x)
dudz = fwd_gradients(u, z)
dudxx = fwd_gradients((A*dudx), x)
dudzz = fwd_gradients((B*dudz), z)
f_loss = C*omega*omega*m*u + dudxx + dudzz - ps # L u - f
return u_real, u_imag, f_loss
def callback(self, loss):
#print('Loss: %.3e' % (loss))
misfit1.append(loss)
self.iter=self.iter+1
if self.iter % 10 == 0:
elapsed = time.time() - self.start_time
print('It: %d, LBFGS Loss: %.3e,Time: %.2f' %
(self.iter, loss, elapsed))
self.start_time = time.time()
def train(self, nIter):
tf_dict = {self.x_tf: self.x, self.z_tf: self.z}
start_time = time.time()
init_start_time = time.time()
for it in range(nIter):
self.sess.run(self.train_op_Adam, tf_dict)
loss_value = self.sess.run(self.loss, tf_dict)
misfit.append(loss_value)
# Print
if it % 10 == 0:
elapsed = time.time() - start_time
[loss_value, w0_value] = self.sess.run([self.loss, self.w0], tf_dict)
w0_n.append(w0_value)
print('It: %d, Loss: %.3e,Time: %.2f,w0:%.2f' %
(it, loss_value, elapsed,w0_value))
start_time = time.time()
self.optimizer.minimize(self.sess,
feed_dict = tf_dict,
fetches = [self.loss],
loss_callback = self.callback)
total_time = time.time() - init_start_time
print('total time:', total_time)
def predict(self, x_star, z_star):
tf_dict = {self.x_tf: x_star, self.z_tf: z_star}
u_real_star = self.sess.run(self.u_real_pred, tf_dict)
u_imag_star = self.sess.run(self.u_imag_pred, tf_dict)
return u_real_star, u_imag_star
if __name__ == "__main__":
layers = [2, 40, 40, 40, 40, 40, 40,40, 40, 2]
#layers = [2, 80, 80, 80, 80, 80, 80,80, 80, 2]
# Load Data for Homogeneous model
# data = scipy.io.loadmat('Homo_4Hz_singlesource_ps.mat')
# Load Data for Marmousi model
data = scipy.io.loadmat('Marmousi_3Hz_singlesource_ps.mat')
u_real = data['U_real']
u_imag = data['U_imag']
ps = data['Ps']
x = data['x_star']
z = data['z_star']
m = data['m']
A = data['A']
B = data['B']
C = data['C']
N = x.shape[0]
N_train = round(N/4*4)
idx = np.random.choice(N, N_train, replace=False)
x_train = x[idx,:]
z_train = z[idx,:]
ps_train = ps[idx,:]
A_train = A[idx,:]
B_train = B[idx,:]
C_train = C[idx,:]
m_train = m[idx,:]
# Training
model = PhysicsInformedNN(x_train, z_train, A_train, B_train, C_train, ps_train, m_train, layers, omega)
model.train(niter)
scipy.io.savemat('w0.mat',{'w0':w0_n})
scipy.io.savemat('loss_adam_sine_adpative_mar.mat',{'misfit':misfit})
scipy.io.savemat('loss_lbfgs_sine_adaptive_mar.mat',{'misfit1':misfit1})
# Test Data
x_star = x
z_star = z
u_real_star = u_real
u_imag_star = u_imag
# Prediction
u_real_pred, u_imag_pred = model.predict(x_star, z_star)
# Error
error_u_real = np.linalg.norm(u_real_star-u_real_pred,2)/np.linalg.norm(u_real_star,2)
error_u_imag = np.linalg.norm(u_imag_star-u_imag_pred,2)/np.linalg.norm(u_imag_star,2)
print('Error u_real: %e, Error u_imag: %e' % (error_u_real,error_u_imag))
scipy.io.savemat('u_real_pred_sine_adaptive_mar.mat',{'u_real_pred':u_real_pred})
scipy.io.savemat('u_imag_pred_sine_adaptive_mar.mat',{'u_imag_pred':u_imag_pred})