This post is about training a ⚛ Physics Informed Neural 🧠 Network (PINN) to solve the Navier-Stokes equations with limited data 🖧 availability. Why is the data necessary? Because, the Navier-Stokes equations being the first principle in fluid dynamics 🌬 are extremely nonlinear and highly coupled 🪢. As of writing this post, it is not possible to find analytical solutions to these equations for any real-world 🌏 scenarios. This has resulted in attempts to solve these glorious 🐐 equations using numerical methods 🖥 by several (crazy) researchers 🧑🏫 including yours truly (read more here). Further more, PINNs are particularly advantageous in scenarios where sparse or discrete experimental data is available, such as measurements from a wind tunnel, and PINN can be used to create the complete flow field and visualize other physical quantities that are not directly measurable 📏!
Well, recently even more crazy researchers 🧑🏫; including yours truly again (read more here); have resorted to model the solutions to these wonderful equations using 🖳 machine learning i.e. neural networks. As a hobby, while experimenting with neural networks in past few years; yours truly has learned that the vanilla Data-Less PINN (free code here) approach only
works for very easy and extremely impractical and small Reynolds numbers cases. For these low Reynolds numbers, analytical solutions to the Navier-Stokes equations already exist. For complex cases of fluid flow such as turbulent flow, the loss "domain" becomes too complicated and the neural network gets stuck in local minima instead of moving towards global minima.
Therefore, in this post, PINN with limited data availability is presented. The cases considered are the cases of asymmetric lid-driven cavity, backwards-facing step, flow around square cylinder at much higher Reynolds numbers as compared to presented in the previous post, and impinging jet.
The idea is to add the training data term in the loss function to guide the PINN loss away from the local minima. Even if a model is made using the so called 💩 "dirty" data that is used in the following examples in conjunction with the Navier-Stokes 🍃 equations, the trained model will accurately depict the fluid flow properties due to the inclusion of Navier-Stokes equations in the loss function. This is why this type of machine learning 🧠 model is better than most regression 📈 and interpolation methods and models. PINNs are also robust against noise in the data. The first principles embedded in the loss function act as regularization and reduce the impact of noise in the data compared to other methods.
External Aerodynamics
In this example of flow around a square cylinder, CFD (Computational Fluid Dynamics) solution from from finite difference method code yours truly developed is used for training data. The CFD performed using the highest possible CFL number and largest possible grid size. This done to make the training data for the neural network as bad as possible. The results from CFD and PINN are compared in Fig. 1. The Reynolds number is 1000. This case is done to test the theory that this method works. The results are in good agreement with solutions at this Reynolds number available in the literature. This is how PINNs can be used to reveal important features of the partially available flow-field from experiments or from very coarse CFD simulations.
Fig. 1, Training data VS reconstructed flow-field
The second example is of flow around a backwards facing step. As is the case with square cylinder, the data is very coarse. The same code can be used for backwards facing step, just move the square's location. The Reynold's number for this case is low, i.e. at 200. The results are shown in Fig. 2.
Fig. 2, Training data VS reconstructed flow-field
Code
Here is the PINN code to reproduce Fig. 1. The data from the wind tunnel or CFD has to be in .npy files or in .csv files.
#Copyright <2024> <Fahad Butt>
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#%% import necessary libraries
import os
import numpy as np
import random as rn
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.optim as optim
# import torch_directml # enable for AMD and Intel gpu
import glob
device = torch.device("cpu") # cuda for CUDA gpu, cpu for cpu, mps for Apple GPU, torch_directml.device() for any other gpu
#%% 2D navier-stokes equations and boundary conditions
def navier_stokes_equation(ns):
ns.requires_grad_(True) # watch ns for gradient computation
out = model(ns) # output from model
u = out[:, 0] # x velocity
v = out[:, 1] # y velocity
p = out[:, 2] # pressure
du = torch.autograd.grad(u, ns, torch.ones_like(u), create_graph = True)[0] # du/dns
dv = torch.autograd.grad(v, ns, torch.ones_like(v), create_graph = True)[0] # dv/dns
num_trainable_params = count_parameters(model) # show trainable parameters
print("Number of trainable parameters:", num_trainable_params)
#%% prepare input data
X_filtered = np.load('X_filtered.npy')
Y_filtered = np.load('Y_filtered.npy')
u_cfd_n = np.load('u_cfd_n.npy')
v_cfd_n = np.load('v_cfd_n.npy')
p_cfd_n = np.load('p_cfd_n.npy')
train_CFD_points = np.vstack((X_filtered, Y_filtered)).T # stack x, y together and convert to tensor
train_CFD_values = np.vstack((u_cfd_n, v_cfd_n, p_cfd_n)).T # stack u, v and p together and convert to tensor
train_CFD_points = torch.tensor(train_CFD_points, dtype=torch.float32).to(device) # convert to tensor and move training points to GPU / CPU, use float64 if moree precision is required
train_points = np.vstack((x, y)).T # stack x, y together
train_points = torch.tensor(train_points, dtype=torch.float32).to(device) # convert to tensor and move training points to GPU / CPU, use float64 if more precision is required
#%% train using Adam
resume_training = False # True if resuming training
start_epoch = 1
optimizer = optim.Adam(model.parameters(), lr = 0.00001) # select optimizer and parameters
checkpoint_dir = './pytorch_checkpoints' # directory to save checkpoints
os.makedirs(checkpoint_dir, exist_ok = True) # create a directory to save checkpoints
test_points = np.vstack((x_te, y_te)).T # stack x, y together
test_points = torch.tensor(test_points, dtype=torch.float32).to(device) # convert to tensor and move training points to GPU / CPU, use float64 if more precision is required
predict = model(test_points).detach().cpu().numpy() # predict and move back to CPU
u = predict[:, 0] * Uinf # predict and bring back to dimensional form
sc = plt.scatter(x_te, y_te, c = u, cmap = 'jet', s = 1, edgecolor = 'none',\
alpha = 1, vmin = -1, vmax = 2.75)
# plt.colorbar(orientation='vertical')
plt.axis('equal')
plt.axis('off')
plt.show()
plt.figure(dpi = 300)
sc = plt.scatter(x_te, y_te, c = v, cmap = 'jet', s = 1, edgecolor = 'none',\
alpha = 1, vmin = -1.4, vmax = 1)
# plt.colorbar(orientation='vertical')
plt.axis('equal')
plt.axis('off')
plt.show()
plt.figure(dpi = 300)
sc = plt.scatter(x_te, y_te, c = p, cmap = 'jet', s = 1, edgecolor = 'none',\
alpha = 1, vmin = -2.5, vmax = 0.7)
# plt.colorbar(orientation='vertical')
plt.axis('equal')
plt.axis('off')
plt.show()
#%% save PINN output
np.save('X_PINN.npy', x_te)
np.save('Y_PINN.npy', y_te)
np.save('u_PINN.npy', u)
np.save('v_PINN.npy', v)
np.save('p_PINN.npy', p)
Internal Flows
The case of asymmetric lid-driven cavity at Re 1000 is considered . The case of asymmetric lid-driven cavity has two large counter rotating vortices in the center and two smaller ones in the corners i.e. a complex flow-field. Without training data, as stated above the PINN loss function gets lost in the local minima. The small amount of training data guides the PINN loss function towards global minima. The key is "small amount", to prevent the PINN to learn the training data. The PINN has to be taught solution of the Navier-Stokes equations and not to learn the data from CFD or from wind tunnel! Fig. 3 compares the results for the case of lid-driven cavity while the results from the case of flat plates are compared in Fig. 4. The code is also made available.
Fig. 3, training data from CFD VS PINN prediction
Fig. 4, Flow inside empty room
Code
Here is code to reproduce Fig. 3, provided training data which can be .csv or any format python reads.
#Copyright <2024> <FAHAD BUTT>
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#%% import necessary libraries
import os
import numpy as np
import random as rn
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.optim as optim
# import torch_directml # enable for AMD and Intel gpu
import glob
device = torch.device("cpu") # cuda for CUDA gpu, cpu for cpu, mps for Apple GPU, torch_directml.device() for any other gpu
#%% 2D navier-stokes equations and boundary conditions
def navier_stokes_equation(ns):
ns.requires_grad_(True) # watch ns for gradient computation
out = model(ns) # output from model
u = out[:, 0] # x velocity
v = out[:, 1] # y velocity
p = out[:, 2] # pressure
du = torch.autograd.grad(u, ns, torch.ones_like(u), create_graph = True)[0] # du/dns
dv = torch.autograd.grad(v, ns, torch.ones_like(v), create_graph = True)[0] # dv/dns
num_trainable_params = count_parameters(model) # show trainable parameters
print("Number of trainable parameters:", num_trainable_params)
#%% prepare input data
X_filtered = np.load('X_filtered.npy')
Y_filtered = np.load('Y_filtered.npy')
u_cfd_n = np.load('u_cfd_n.npy')
v_cfd_n = np.load('v_cfd_n.npy')
p_cfd_n = np.load('p_cfd_n.npy')
train_CFD_points = np.vstack((X_filtered, Y_filtered)).T # stack x, y together and convert to tensor
train_CFD_values = np.vstack((u_cfd_n, v_cfd_n, p_cfd_n)).T # stack u, v and p together and convert to tensor
train_CFD_points = torch.tensor(train_CFD_points, dtype=torch.float32).to(device) # convert to tensor and move training points to GPU / CPU, use float64 if moree precision is required
train_points = np.vstack((x, y)).T # stack x, y together
train_points = torch.tensor(train_points, dtype=torch.float32).to(device) # convert to tensor and move training points to GPU / CPU, use float64 if more precision is required
#%% train using Adam
resume_training = False # True if resuming training
start_epoch = 1
optimizer = optim.Adam(model.parameters(), lr = 0.00001) # select optimizer and parameters
checkpoint_dir = './pytorch_checkpoints' # directory to save checkpoints
os.makedirs(checkpoint_dir, exist_ok = True) # create a directory to save checkpoints
x_te = np.concatenate([x_l_te, x_r_te, x_b_te, x_t_te, x_m_te]) # x co-ordinates
y_te = np.concatenate([y_l_te, y_r_te, y_b_te, y_t_te, y_m_te]) # y co-ordinates
test_points = np.vstack((x_te, y_te)).T # stack x, y together
test_points = torch.tensor(test_points, dtype=torch.float32).to(device) # convert to tensor and move training points to GPU / CPU, use float64 if more precision is required
predict = model(test_points).detach().cpu().numpy() # predict and move back to CPU
u = predict[:, 0] * Uinf # predict and bring back to dimensional form
sc = plt.scatter(x_te, y_te, c = u, cmap = 'jet', s = 1, edgecolor = 'none',\
alpha = 1, vmin = -0.3, vmax = 1)
plt.gca().set_aspect('equal', adjustable = 'box')
plt.axis('off')
plt.show()
plt.figure(dpi = 300)
sc = plt.scatter(x_te, y_te, c = v, cmap = 'jet', s = 1, edgecolor = 'none',\
alpha = 1, vmin = -0.55, vmax = 0.3)
plt.gca().set_aspect('equal', adjustable = 'box')
plt.axis('off')
plt.show()
plt.figure(dpi = 300)
sc = plt.scatter(x_te, y_te, c = p, cmap = 'jet', s = 1, edgecolor = 'none',\
alpha = 1, vmin = -0.1, vmax = 0.5)
plt.gca().set_aspect('equal', adjustable = 'box')
plt.axis('off')
plt.show()
Jets
This section is about impinging jets. With very limited data availability, the PINN can also easily predict flow of impinging jets. The Reynolds number is kept at 1000. The results are shown in Fig. 5. Within Fig. 5, top left has PINN results while bottom left has training data points. As mentioned previously, the CFD is performed on highest possible CFL and largest possible mesh size to make the training data as noisy as possible, only just preventing unphysical results.
Fig. 5, Comparison of PINN with CFD, with very limited training data
The code is same as for the case of lid-driven cavity, with changes in the left side boundary conditions to simulate the jet. the modified function is presented next.
Code
#Copyright <2024> <FAHAD BUTT>
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#%% 2D navier-stokes equations and boundary conditions
def navier_stokes_equation(ns):
ns.requires_grad_(True) # watch ns for gradient computation
out = model(ns) # output from model
u = out[:, 0] # x velocity
v = out[:, 1] # y velocity
p = out[:, 2] # pressure
du = torch.autograd.grad(u, ns, torch.ones_like(u), create_graph = True)[0] # du/dns
dv = torch.autograd.grad(v, ns, torch.ones_like(v), create_graph = True)[0] # dv/dns
x_mom = (u * u_x) + (v * u_y) + p_x - ((1 / Re) * (u_xx + u_yy)) # x momentum
y_mom = (u * v_x) + (v * v_y) + p_y - ((1 / Re) * (v_xx + v_yy)) # y momentum
cont = u_x + v_y # continuity
# apply boundary conditions
u_left_bc_0 = u[(ns[:, 0] == 0) & (ns[:, 1] >= 0) & (ns[:, 1] < 0.875)] # u = 0 from y = 0 to y = 0.875
u_left_bc_1 = u[(ns[:, 0] == 0) & (ns[:, 1] >= 0.875) & (ns[:, 1] < 1.125)] - Uinf # u = Uinf from y = 0.875 to y = 1.125
u_left_bc_2 = u[(ns[:, 0] == 0) & (ns[:, 1] >= 1.125) & (ns[:, 1] <= D)] # u = 0 from y = 1.125 to y = 2
u_left_bc = torch.cat([u_left_bc_0, u_left_bc_1, u_left_bc_2]) # x = 0
u_right_bc = u[ns[:, 0] == L] # x = L
u_top_bc = u_y[ns[:, 1] == D] # y = D
u_bottom_bc = u_y[ns[:, 1] == 0] # y = 0
v_left_bc = v[ns[:, 0] == 0] # x = 0
v_right_bc = v[ns[:, 0] == L] # x = L
v_top_bc = v_y[ns[:, 1] == D] # y = D
v_bottom_bc = v_y[ns[:, 1] == 0] # y = 0
p_left_bc = p_x[ns[:, 0] == 0] # x = 0
p_right_bc = p_x[ns[:, 0] == L] # x = L
p_top_bc = p[ns[:, 1] == D] # y = D
p_bottom_bc = p[ns[:, 1] == 0] # y = 0
return x_mom, y_mom, cont, \
u_left_bc, u_right_bc, u_top_bc, u_bottom_bc, \
v_left_bc, v_right_bc, v_top_bc, v_bottom_bc, \
p_left_bc, p_right_bc, p_top_bc, p_bottom_bc
Of course, this all has been done before ⌛, but I present a simple yet effective free 🤑 code 💻 for the readers to explore and improve upon. Please cite ㉖ this blog post if you use the code in your research! Good Luck!
Here is a simple code I wrote for Data-less 📈 Physics Informed Neural 🧠 Network 🕸️ to solve the steady-state 2D incompressible Navier-Stokes equations in Python using PyTorch. Already validated results will be uploaded here in good time. The code has all the comments 👨🏫 you could possibly need. If you have questions, well... 👹
Please note that a properly cooled 🧊 GPU is recommended for running this code. If your CPU melts 🔥, don't blame me 😤. Furthermore, if you classify yourself as a poor peasant 👨🌾, use: device = torch.device("cpu") # cuda for gpu, cpu for cpu 😝.
The New Code: (Fall 2025)
After successfully 🏆 completing the validation for the SIMB, yours truly has been developing in the abundant spare time 🕒; it is now the perfect time to revisit PINNs. On a fine morning, yours truly decided to separate 𓍯𓂃𓏧♡ the tensors for boundary conditions and the equations of motion. It turns out 😱 that making separate functions for the boundary conditions and the equations of motion with separate tensors ﮩ٨ـﮩﮩ٨ـ♡ﮩ٨ـﮩﮩ٨ـ for each boundary makes the loss function converge to the global minimum 🕳️ much faster ⚡.
Copyright <2025> <Fahad Butt>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The helper function to define Navier-Stokes equations is defined first, navier_stokes_equation. This function calculates the the model output at interior points and then calculates the derivatives using autograd to assemble the equations of motion.
The boundary condition helper function is defined next, boundary_conditions. This function evaluates the model output at each boundary separately and then enforces the boundary conditions. As a result of these modifications 🛠️, the loss 📉 is also rewritten.
def navier_stokes_equation(ns):
ns.requires_grad_(True) # watch ns for gradient computation
out = model(ns) # output from model at interior
u = out[:, 0] # u interior
v = out[:, 1] # v interior
p = out[:, 2] # p interior
du = torch.autograd.grad(u, ns, torch.ones_like(u), create_graph=True)[0] # du/dns
dv = torch.autograd.grad(v, ns, torch.ones_like(v), create_graph=True)[0] # dv/dns
nn.MSELoss()(v_bottom_bc, torch.zeros_like(v_bottom_bc)) # v momentum boundary condition loss
bc_loss = u_bc_loss + v_bc_loss # total boundary condition loss
mse_loss = x_mom_loss + y_mom_loss + cont_loss # total equation loss
total_loss = mse_loss + bc_loss # total loss
return total_loss
Instead of creating a single tensor 🧊 for the entire input, five 🧮 tensors are created for this new, at least to yours truly, method. Of course, the training loop also has to be modified 🔩.
B_left = torch.tensor(cp.vstack((x_l, y_l)).T, dtype=torch.float32).to(device) # stack x, y together
optimizer.zero_grad() # clear gradients of all optimized variables
loss_value = loss_fn() # compute prediction by passing inputs to model
loss_value.backward() # compute gradient of loss with respect to model parameters
optimizer.step() # perform parameter up date
The Code:
#%% license
#Copyright <2024> <Fahad Butt>
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#%% import necessary libraries
import os
import numpy as np
import random as rn
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.optim as optim
# import torch_directml # enable for any gpu except CUDA gpu
import glob
device = torch.device("cpu") # cuda for CUDA gpu, cpu for cpu, torch_directml.device() for any other gpu
#%% 2D navier-stokes equations and boundary conditions
def navier_stokes_equation(ns):
ns.requires_grad_(True) # watch ns for gradient computation
out = model(ns) # output from model
u = out[:, 0] # x velocity
v = out[:, 1] # y velocity
p = out[:, 2] # pressure
du = torch.autograd.grad(u, ns, torch.ones_like(u), create_graph=True)[0] # du/dns
dv = torch.autograd.grad(v, ns, torch.ones_like(v), create_graph=True)[0] # dv/dns
num_trainable_params = count_parameters(model) # show trainable parameters
print("Number of trainable parameters:", num_trainable_params)
#%% prepare input data
train_points = np.vstack((x, y)).T # stack x, y together
train_points = torch.tensor(train_points, dtype=torch.float32).to(device) # convert to tensor and move training points to GPU / CPU, use float64 if mroe precision is required
#%% train using Adam
resume_training = False # True if resuming training
start_epoch = 1
optimizer = optim.Adam(model.parameters(), lr = 0.00001) # select optimizer and parameters
checkpoint_dir = './pytorch_checkpoints' # directory to save checkpoints
os.makedirs(checkpoint_dir, exist_ok=True) # create a directory to save checkpoints
x_m_te = np.random.uniform(0, L, 50000) # mid field
y_m_te = np.random.uniform(0, D, 50000)
x_te = np.concatenate([x_l_te, x_r_te, x_b_te, x_t_te, x_m_te]) # x co-ordinates
y_te = np.concatenate([y_l_te, y_r_te, y_b_te, y_t_te, y_m_te]) # y co-ordinates
test_points = np.vstack((x_te, y_te)).T # stack x, y together
test_points = torch.tensor(test_points, dtype=torch.float32).to(device) # convert to tensor and move training points to GPU / CPU, use float64 if mroe precision is required
predict = model(test_points).detach().cpu().numpy() # predict and move back to CPU
u = predict[:, 0] * Uinf # predict and bring back to dimensional form
sc = plt.scatter(x_te, y_te, c = u, cmap = 'jet', s = 1, edgecolor = 'none', alpha = 1)
plt.colorbar(orientation = 'vertical')
plt.gca().set_aspect('equal', adjustable = 'box')
plt.xticks([0, L])
plt.yticks([0, D])
plt.xlabel('x [m]')
plt.ylabel('y [m]')
plt.axis('off')
plt.show()
plt.figure(dpi = 300)
sc = plt.scatter(x_te, y_te, c = v, cmap = 'jet', s = 1, edgecolor = 'none', alpha = 1)
plt.colorbar(orientation = 'vertical')
plt.gca().set_aspect('equal', adjustable = 'box')
plt.xticks([0, L])
plt.yticks([0, D])
plt.xlabel('x [m]')
plt.ylabel('y [m]')
plt.axis('off')
plt.show()
plt.figure(dpi = 300)
sc = plt.scatter(x_te, y_te, c = p, cmap = 'jet', s = 1, edgecolor = 'none', alpha = 1)
plt.colorbar(orientation = 'vertical')
plt.gca().set_aspect('equal', adjustable = 'box')
plt.xticks([0, L])
plt.yticks([0, D])
plt.xlabel('x [m]')
plt.ylabel('y [m]')
plt.axis('off')
plt.show()
Flow between Flat - Plates
The boundary conditions are taken from [2]. The results presented in Fig. 1 are from flow between two parallel flat plates. For these boundary conditions, analytical solutions to the Navier-Stokes equations are available. As this is "just another blog" 😕; just by eye-balling 😆, the results look very promising. I mean from Fig. 1, the velocities at left side are captured well-ish!
Fig. 1, post processing
Lid-Driven Cavity
The case of flow between two flat plates shown in Fig. 1 is self-validating as area times velocity should be same for inlet and outlet, which it is. Lid-Driven Cavity however, is a benchmark problem for many numerical methods in fluid dynamics because of complex vortex dynamics. Here I present, the results of Lid-Driven Cavity problem. The results are very good 😎. The results are presented in Fig. 2. The comparison of PINN results with [1] is shown in Fig. 3. The validation of CFD is available to be read here. While the CFD code is available here.
Fig. 2, Post processing
Fig. 3, A comparison
External Fluid Dynamics
Here is a video of the PINN learning flow around obstacle i.e. a square cylinder.
Fig. 4, The animation
The PINN is now capable to predict flow around curved objects. The flow around circular cylinder is mentioned. I use polar coordinates for applying Neuman boundary conditions for pressure to satisfy the no-slip wall. The results are shown in Fig. 5. The code is also made available for fellow researchers to improve upon and use in the research, please cite properly. The results show u and v velocities at the left portion while pressure and streamlines are shown on the right side. As compared to the commercial software that shall not be named 😃, the results are very accurate. The Reynolds number is kept at 10to avoid making the loss landscape complex. Please refer to this post for more details!
Fig. 5, The post processing
Code
# Copyright <2024> <FAHAD BUTT>
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#%% import necessary libraries
import os
import numpy as np
import random as rn
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.optim as optim
# import torch_directml # enable for AMD and Intel gpu
import glob
from scipy.interpolate import griddata
device = torch.device("cpu") # cuda for CUDA gpu, cpu for cpu, mps for Apple GPU, torch_directml.device() for any other gpu
#%% 2D navier-stokes equations and boundary conditions
def navier_stokes_equation(ns):
ns.requires_grad_(True) # watch ns for gradient computation
out = model(ns) # output from model
u = out[:, 0] # x velocity
v = out[:, 1] # y velocity
p = out[:, 2] # pressure
du = torch.autograd.grad(u, ns, torch.ones_like(u), create_graph = True)[0] # du/dns
dv = torch.autograd.grad(v, ns, torch.ones_like(v), create_graph = True)[0] # dv/dns
num_trainable_params = count_parameters(model) # show trainable parameters
print("Number of trainable parameters:", num_trainable_params)
#%% prepare input data
train_points = np.vstack((x_train, y_train)).T # stack x, y together
train_points = torch.tensor(train_points, dtype=torch.float32).to(device) # convert to tensor and move training points to GPU / CPU, use float64 if more precision is required
#%% train using Adam
resume_training = False # True if resuming training
start_epoch = 1
optimizer = optim.Adam(model.parameters(), lr = 0.0001) # select optimizer and parameters
checkpoint_dir = './pytorch_checkpoints' # directory to save checkpoints
os.makedirs(checkpoint_dir, exist_ok = True) # create a directory to save checkpoints
x_te = np.concatenate([x_l_te, x_r_te, x_b_te, x_t_te, x_m_te]) # x co-ordinates
y_te = np.concatenate([y_l_te, y_r_te, y_b_te, y_t_te, y_m_te]) # y co-ordinates
distance_te = np.sqrt((x_te - center_x) ** 2 + (y_te - center_y) ** 2) # distance of each point from center
outside_circle_te = distance_te >= radius # filter out points inside circle
x_te_filtered = x_te[outside_circle_te]
y_te_filtered = y_te[outside_circle_te]
test_points = np.vstack((x_te_filtered, y_te_filtered)).T # stack x, y together
test_points = torch.tensor(test_points, dtype=torch.float32).to(device) # convert to tensor and move training points to GPU / CPU, use float64 if more precision is required
predict = model(test_points).detach().cpu().numpy() # predict and move back to CPU
u = predict[:, 0] * Uinf # predict and bring back to dimensional form
Thank you for reading! If you want to hire me as your next PostDoc researcher, reach out for collaboration in research, please do so!
References
[1] U. Ghia, K. N. Ghia, and C. T. Shin, “High-Re Solutions for Incompressible Flow Using the Navier-Stokes Equations and a Multigrid Method”, Journal of Computational Physics 48, 387-411 (1982)
[2] Cahya Amalinadhi, Pramudita S. Palar, Rafael Stevenson and Lavi Zuhal. "On Physics-Informed Deep Learning for Solving Navier-Stokes Equations," AIAA 2022-1436. AIAA SCITECH 2022 Forum. January 2022. https://doi.org/10.2514/6.2022-1436