-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPINN_circular_loops_asymmetric.py
275 lines (212 loc) · 11.8 KB
/
PINN_circular_loops_asymmetric.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
import os
os.add_dll_directory("C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.6/bin") # might create a problem for you
#from numpy.core.fromnumeric import shape
import numpy as np
from tensorflow.python.ops.init_ops_v2 import Initializer
from tensorflow.python.keras.backend import dtype
from tensorflow.python.keras.utils.tf_utils import dataset_is_infinite
from tensorflow.python.ops.variables import trainable_variables
import tensorflow as tf
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy.special as sc
import matplotlib.pyplot as plt
from scipy.io import savemat
#from scipy.integrate import quad
#import plotly.graph_objects as go
#from IPython.display import HTML
#import sympy as smp
#from sympy.vector import cross
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1';
# First define the magnetic field generated by a circle (counter clock wise current)
def circB(x,y,z):
#Defining some parameters to be used in the formulas
r_sq = x**2 + y**2 + z**2
rho_sq = x**2 + y**2
alpha_sq = 1. + r_sq - 2. * np.sqrt(rho_sq)
beta_sq = 1. + r_sq + 2. * np.sqrt(rho_sq)
k_sq = 1. - alpha_sq/beta_sq
#Evaluate elliptic integrals
e_k_sq = sc.ellipe(k_sq)
k_k_sq = sc.ellipk(k_sq)
#Magnetic field components in Cartesian coordinates
Bx = 2. * x * z / (alpha_sq * rho_sq * np.sqrt(beta_sq)) * ((1. + r_sq) * e_k_sq - alpha_sq * k_k_sq)
By = y * Bx / x
Bz = 2. / (alpha_sq * np.sqrt(beta_sq)) * ((1. - r_sq) * e_k_sq + alpha_sq * k_k_sq)
return np.array([Bx,By,Bz]) * 50
# Now calculate the mag field of collection of circles
def B(x,y,z):
return 0.6*circB(x + 1.01,y + 1.0,z - 4.0) + 0.2*circB(x - 1.01,y - 1.0, z - 4.0) - 0.8*circB(x + 1.01,y - 1.0,z - 4.0) - 0.5*circB(x - 1.01,y + 1.0,z - 4.0) - 0.98*circB(x + 1.01,y + 1.0,z + 4.0) - 0.46*circB(x - 1.01,y - 1.0,z + 4.0) + 0.35*circB(x + 1.01,y - 1.0,z + 4.0) + 0.87*circB(x - 1.01,y + 1.0,z + 4.0)
# Construct neural network
class PINN(tf.keras.Model):
def __init__(self, x_u, y_u, z_u, validation_data, validation_labels, u_labels, L, layers, input_dim=2, output_dim=1):
super(PINN, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.x_u = tf.cast(x_u, dtype = "float32")
self.y_u = tf.cast(y_u, dtype = "float32")
self.z_u = tf.cast(z_u, dtype = "float32")
#self.x_f = tf.cast(x_f, dtype = "float32")
#self.y_f = tf.cast(y_f, dtype = "float32")
#self.z_f = tf.cast(z_f, dtype = "float32")
self.u_labels = tf.cast(u_labels, dtype = "float32")
self.validation_data = validation_data
self.validation_labels = validation_labels
#print(self.u_labels)
self.L = L
self.PINN_layers = []
for i in range(1, len(layers)-1):
self.PINN_layers.append(tf.keras.layers.Dense(layers[i], activation = tf.keras.activations.tanh, kernel_regularizer = tf.keras.regularizers.L1(0.01), trainable = True))
self.PINN_layers.append(tf.keras.layers.Dense(layers[-1], activation = None, trainable = True))
self(tf.concat([self.x_u, self.y_u, self.z_u], axis = 1))
def compile(self, optimizer, loss):
super(PINN, self).compile()
self.optimizer = optimizer
self.loss_fn = loss
@tf.function
def call(self, inputs):
y = inputs
for i in range(len(self.PINN_layers)):
y = self.PINN_layers[i](y)
return y
@tf.function
def train_step(self, o1):
# Number of physics training points
N_f = 2048*8
# Side length of the cube
L = self.L
# Generate random physics training points for each epoch
x_f = np.random.default_rng().uniform(low = -L, high = L, size = ((N_f, 1)))
y_f = np.random.default_rng().uniform(low = -L, high = L, size = ((N_f, 1)))
z_f = np.random.default_rng().uniform(low = -L, high = L, size = ((N_f, 1)))
self.x_f = tf.cast(x_f, dtype = "float32")
self.y_f = tf.cast(y_f, dtype = "float32")
self.z_f = tf.cast(z_f, dtype = "float32")
# Calculate derivateves and set PDE
with tf.GradientTape(persistent = True) as g:
g.watch([self.x_f, self.y_f, self.z_f, self.x_u, self.y_u, self.z_u])
inputs2 = tf.concat([self.x_u, self.y_u, self.z_u], axis = 1)
u_pred = self(inputs2)
inputs = tf.concat([self.x_f, self.y_f, self.z_f], axis = 1)
u = self(inputs)
temp_ux = u[:,0]
temp_uy = u[:,1]
temp_uz = u[:,2]
u_x = g.gradient(temp_ux, self.x_f)
u_y = g.gradient(temp_uy, self.y_f)
u_z = g.gradient(temp_uz, self.z_f)
u_zy = g.gradient(temp_uz, self.y_f)
u_yz = g.gradient(temp_uy, self.z_f)
u_xz = g.gradient(temp_ux, self.z_f)
u_zx = g.gradient(temp_uz, self.x_f)
u_yx = g.gradient(temp_uy, self.x_f)
u_xy = g.gradient(temp_ux, self.y_f)
f = u_x + u_y + u_z
loss_cross = tf.reduce_mean(tf.square(u_zy-u_yz) + tf.square(u_xz-u_zx) + tf.square(u_yx-u_xy))
loss_u = tf.reduce_mean(tf.square(u_pred - self.u_labels))
loss_f = tf.reduce_mean(tf.square(f)
loss = loss_f + 2*loss_u + loss_cross
gradients_1 = g.gradient(loss, self.trainable_variables)
self.optimizer.apply_gradients(zip(gradients_1, self.trainable_variables))
loss_val = tf.reduce_mean(tf.sqrt(tf.reduce_sum(tf.square(self(self.validation_data) - self.validation_labels), 1)))
return {"Loss": loss, "Loss_cross": loss_cross, "Loss_f": loss_f, "Loss_u": loss_u, "Loss_val": loss_val}
class LearningRateReducerCb(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if epoch % 10 == 0:
old_lr = self.model.optimizer.lr.read_value()
new_lr = 0.0
with open("learning_rate.txt", 'r') as file1:
for line in file1.readlines():
new_lr = float(line)
print("\nEpoch: {}. Reducing Learning Rate from {} to {}".format(epoch, old_lr, new_lr))
self.model.optimizer.lr.assign(new_lr)
if __name__ == "__main__":
# There are 6 faces
# x = \pm 1/2
# y = \pm 1/2
# z = \pm 1/2
N_u = 15 # x 6(6 faces in a Cube) = 60 boundary conditions
L = 1 # x 2 lenght of the cubes edges
x_u = np.concatenate((-L*np.ones([N_u, 1]), L*np.ones([N_u, 1]),
np.random.default_rng().uniform(low = -L, high = L, size = (4*N_u, 1))),
axis = 0)
y_u = np.concatenate((np.random.default_rng().uniform(low = -L, high = L, size = (2*N_u, 1)),
-L*np.ones([N_u, 1]), L*np.ones([N_u, 1]),
np.random.default_rng().uniform(low = -L, high = L, size = (2*N_u, 1))),
axis = 0)
z_u = np.concatenate((np.random.default_rng().uniform(low = -L, high = L, size = (4*N_u, 1)),
-L*np.ones([N_u, 1]), L*np.ones([N_u, 1])),
axis = 0)
u_labels = np.array([B(x_u[i], y_u[i], z_u[i]) for i in range(len(x_u))]) + np.random.default_rng().normal(0, 0.01, size = (N_u*6, 3, 1))
u_labels = u_labels.reshape((N_u*6, 3))
# Points on the cube
N_val = 1000
x_validation = np.random.default_rng().uniform(low = -L, high = L, size = ((N_val, 1)))
y_validation = np.random.default_rng().uniform(low = -L, high = L, size = ((N_val, 1)))
z_validation = np.random.default_rng().uniform(low = -L, high = L, size = ((N_val, 1)))
validation_labels = np.array([B(x_validation[i], y_validation[i], z_validation[i]) for i in range(N_val)])
validation_labels = tf.cast(validation_labels.reshape((N_val, 3)), dtype=tf.float32)
validation_data = tf.concat([tf.cast(x_validation, dtype=tf.float32), tf.cast(y_validation, dtype=tf.float32), tf.cast(z_validation, dtype=tf.float32)], axis = 1)
print(np.mean(validation_labels, axis=0))
print(np.std(validation_labels, axis=0))
# Define layer sizes
layers = [3, 64, 64, 64, 64, 3]
output_file_name = "saved_models/Circular_loops_" + str(len(layers)-2)+ "x" + str(layers[1]) + "_N_u_" + str(N_u*6)
model = PINN(x_u, y_u, z_u, validation_data, validation_labels, u_labels, L, layers)
trainingStopCallback = tf.keras.callbacks.EarlyStopping(monitor='Loss', patience=1000, min_delta=0.0000000001)
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.01), loss=tf.keras.losses.MeanSquaredError())
model.summary()
history_callback = model.fit((x_u, y_u), epochs = 1000000, batch_size = len(u_labels), callbacks = [LearningRateReducerCb(), trainingStopCallback])
model.save(output_file_name, save_format='tf')
## Recording Losses
loss_history = np.array(history_callback.history['Loss'])
np.savetxt(output_file_name + '/Loss.txt', loss_history, delimiter = ",")
loss_cross_history = np.array(history_callback.history['Loss_cross'])
np.savetxt(output_file_name + '/Loss_cross.txt', loss_cross_history, delimiter = ",")
loss_f_history = np.array(history_callback.history['Loss_f'])
np.savetxt(output_file_name + '/Loss_f.txt', loss_f_history, delimiter = ",")
loss_u_history = np.array(history_callback.history['Loss_u'])
np.savetxt(output_file_name + '/Loss_u.txt', loss_u_history, delimiter = ",")
loss_val_history = np.array(history_callback.history['Loss_val'])
np.savetxt(output_file_name + '/Loss_val.txt', loss_val_history, delimiter = ",")
#############
model = tf.keras.models.load_model(output_file_name)
model.summary()
#model.fit((x_u, y_u), epochs = 75, batch_size = len(u_labels), callbacks = [LearningRateReducerCb(), trainingStopCallback])
#############
N_val = 100
#x_test_np = np.random.default_rng().uniform(low = -L, high = L, size = (N_val, 1))
#y_test_np = np.random.default_rng().uniform(low = -L, high = L, size = (N_val, 1))
#z_test_np = np.ones((N_val, 1))*0.3
x_test_np_grid = np.linspace(-L, L, N_val)
y_test_np_grid = np.linspace(-L, L, N_val)
z_test_np_grid = np.linspace(-L, L, N_val)
xx, yy, zz = np.meshgrid(x_test_np_grid, x_test_np_grid, z_test_np_grid, sparse=False)
x_test_np = xx.reshape((N_val**3, 1))
y_test_np = yy.reshape((N_val**3, 1))
z_test_np = zz.reshape((N_val**3, 1))
x_test = tf.cast(x_test_np, dtype=tf.float32)
y_test = tf.cast(y_test_np, dtype=tf.float32)
z_test = tf.cast(z_test_np, dtype=tf.float32)
print(x_test.shape)
inputs = tf.concat([x_test, y_test, z_test], axis = 1)
temp_final = np.array([B(x_test_np[i], y_test_np[i], z_test_np[i]) for i in range(N_val**3)])
temp_final = temp_final.reshape((N_val, N_val, N_val, 3))
model_output = tf.reshape(model.call(inputs), [N_val, N_val, N_val, 3])
np.save("mesh_x.npy", xx);
np.save("mesh_y.npy", yy);
np.save("mesh_z.npy", zz);
np.save("B_real.npy", temp_final);
np.save("B_pred.npy", model_output);
model_output = tf.sqrt(tf.reduce_sum(tf.square(model_output-temp_final), axis = 1))
model_output = model_output.numpy().reshape((N_val, N_val))
plt.pcolor(xx, yy, model_output)
plt.show()
print(temp_final.shape)
print(model_output.shape)
final_plot = tf.sqrt(tf.reduce_sum(tf.square(temp_final - model_output), axis=1))
final_plot = tf.reshape(final_plot, [N_val, 1])
print(final_plot.shape)
ax.plot3D(x_test, y_test, final_plot)
plt.show()