version 0.0.1
This commit is contained in:
@@ -1,35 +1,26 @@
|
||||
import numpy as np
|
||||
import scipy.io
|
||||
import torch
|
||||
|
||||
from pina.segment import Segment
|
||||
from pina.cube import Cube
|
||||
from pina.problem import TimeDependentProblem, Problem1D
|
||||
from pina.problem import TimeDependentProblem, SpatialProblem
|
||||
from pina.operators import grad
|
||||
from pina import Condition
|
||||
from pina.span import Span
|
||||
|
||||
def tmp_grad(output_, input_):
|
||||
return torch.autograd.grad(
|
||||
output_,
|
||||
input_.tensor,
|
||||
grad_outputs=torch.ones(output_.size()).to(
|
||||
dtype=input_.tensor.dtype,
|
||||
device=input_.tensor.device),
|
||||
create_graph=True, retain_graph=True, allow_unused=True)[0]
|
||||
|
||||
class Burgers1D(TimeDependentProblem, Problem1D):
|
||||
class Burgers1D(TimeDependentProblem, SpatialProblem):
|
||||
|
||||
input_variables = ['x', 't']
|
||||
spatial_variables = ['x']
|
||||
temporal_variable = ['t']
|
||||
output_variables = ['u']
|
||||
spatial_domain = Cube([[-1, 1]])
|
||||
temporal_domain = Cube([[0, 1]])
|
||||
domain = Span({'x': [-1, 1], 't': [0, 1]})
|
||||
|
||||
def burger_equation(input_, output_):
|
||||
grad_u = grad(output_['u'], input_)
|
||||
grad_x, grad_t = tmp_grad(output_['u'], input_).T
|
||||
grad_x, grad_t = grad(output_['u'], input_).T
|
||||
gradgrad_u_x = grad(grad_u['x'], input_)
|
||||
grad_xx = tmp_grad(grad_x, input_)[:, 0]
|
||||
return grad_u['t'] + output_['u']*grad_u['x'] - (0.01/torch.pi)*gradgrad_u_x['x']
|
||||
|
||||
return (
|
||||
grad_u['t'] + output_['u']*grad_u['x'] -
|
||||
(0.01/torch.pi)*gradgrad_u_x['x']
|
||||
)
|
||||
|
||||
def nil_dirichlet(input_, output_):
|
||||
u_expected = 0.0
|
||||
@@ -39,11 +30,9 @@ class Burgers1D(TimeDependentProblem, Problem1D):
|
||||
u_expected = -torch.sin(torch.pi*input_['x'])
|
||||
return output_['u'] - u_expected
|
||||
|
||||
|
||||
|
||||
conditions = {
|
||||
'gamma1': {'location': Segment((-1, 0), (-1, 1)), 'func': nil_dirichlet},
|
||||
'gamma2': {'location': Segment(( 1, 0), ( 1, 1)), 'func': nil_dirichlet},
|
||||
'initia': {'location': Segment((-1, 0), ( 1, 0)), 'func': initial_condition},
|
||||
'D': {'location': Cube([[-1, 1],[0,1]]), 'func': burger_equation}
|
||||
'gamma1': Condition(Span({'x': -1, 't': [0, 1]}), nil_dirichlet),
|
||||
'gamma2': Condition(Span({'x': 1, 't': [0, 1]}), nil_dirichlet),
|
||||
't0': Condition(Span({'x': [-1, 1], 't': 0}), initial_condition),
|
||||
'D': Condition(Span({'x': [-1, 1], 't': [0, 1]}), burger_equation),
|
||||
}
|
||||
|
||||
@@ -1,43 +1,41 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
from pina.segment import Segment
|
||||
from pina.cube import Cube
|
||||
from pina.problem2d import Problem2D
|
||||
from pina.problem import Problem
|
||||
|
||||
from pina.problem import SpatialProblem, ParametricProblem
|
||||
from pina.operators import nabla
|
||||
from pina import Span, Condition
|
||||
|
||||
|
||||
class ParametricPoisson2DProblem(Problem2D):
|
||||
class ParametricPoisson(SpatialProblem, ParametricProblem):
|
||||
|
||||
def __init__(self):
|
||||
spatial_variables = ['x', 'y']
|
||||
parameters = ['mu1', 'mu2']
|
||||
output_variables = ['u']
|
||||
domain = Span({'x': [-1, 1], 'y': [-1, 1]})
|
||||
|
||||
def laplace_equation(input_, param_, output_):
|
||||
grad_u = self.grad(output_['u'], input_)
|
||||
gradgrad_u_x = self.grad(grad_u['x'], input_)
|
||||
gradgrad_u_y = self.grad(grad_u['y'], input_)
|
||||
force_term = torch.exp(
|
||||
- 2*(input_['x'] - input_['mu1'])**2 -
|
||||
2*(input_['y'] - input_['mu2'])**2
|
||||
)
|
||||
return gradgrad_u_x['x'] + gradgrad_u_y['y'] - force_term
|
||||
def laplace_equation(input_, output_):
|
||||
force_term = torch.exp(
|
||||
- 2*(input_['x'] - input_['mu1'])**2 - 2*(input_['y'] -
|
||||
input_['mu2'])**2)
|
||||
return nabla(output_['u'], input_) - force_term
|
||||
|
||||
def nil_dirichlet(input_, param_, output_):
|
||||
value = 0.0
|
||||
return output_['u'] - value
|
||||
def nil_dirichlet(input_, output_):
|
||||
value = 0.0
|
||||
return output_['u'] - value
|
||||
|
||||
self.conditions = {
|
||||
'gamma1': {'location': Segment((-1, -1), ( 1, -1)),'func': nil_dirichlet},
|
||||
'gamma2': {'location': Segment(( 1, -1), ( 1, 1)),'func': nil_dirichlet},
|
||||
'gamma3': {'location': Segment(( 1, 1), (-1, 1)),'func': nil_dirichlet},
|
||||
'gamma4': {'location': Segment((-1, 1), (-1, -1)),'func': nil_dirichlet},
|
||||
'D': {'location': Cube([[-1, 1], [-1, 1]]), 'func': laplace_equation}
|
||||
}
|
||||
|
||||
self.input_variables = ['x', 'y']
|
||||
self.output_variables = ['u']
|
||||
self.parameters = ['mu1', 'mu2']
|
||||
#self.truth_solution = poisson_sol
|
||||
self.spatial_domain = Cube([[0, 1], [0, 1]])
|
||||
self.parameter_domain = np.array([[-1, 1], [-1, 1]])
|
||||
|
||||
|
||||
#self.check() # Check the problem is correctly set
|
||||
conditions = {
|
||||
'gamma1': Condition(
|
||||
Span({'x': [-1, 1], 'y': 1, 'mu1': [-1, 1], 'mu2': [-1, 1]}),
|
||||
nil_dirichlet),
|
||||
'gamma2': Condition(
|
||||
Span({'x': [-1, 1], 'y': -1, 'mu1': [-1, 1], 'mu2': [-1, 1]}),
|
||||
nil_dirichlet),
|
||||
'gamma3': Condition(
|
||||
Span({'x': 1, 'y': [-1, 1], 'mu1': [-1, 1], 'mu2': [-1, 1]}),
|
||||
nil_dirichlet),
|
||||
'gamma4': Condition(
|
||||
Span({'x': -1, 'y': [-1, 1], 'mu1': [-1, 1], 'mu2': [-1, 1]}),
|
||||
nil_dirichlet),
|
||||
'D': Condition(
|
||||
Span({'x': [-1, 1], 'y': [-1, 1], 'mu1': [-1, 1], 'mu2': [-1, 1]}),
|
||||
laplace_equation),
|
||||
}
|
||||
|
||||
35
examples/problems/poisson.py
Normal file
35
examples/problems/poisson.py
Normal file
@@ -0,0 +1,35 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from pina.problem import SpatialProblem
|
||||
from pina.operators import nabla
|
||||
from pina import Condition, Span
|
||||
|
||||
|
||||
class Poisson(SpatialProblem):
|
||||
|
||||
spatial_variables = ['x', 'y']
|
||||
output_variables = ['u']
|
||||
domain = Span({'x': [0, 1], 'y': [0, 1]})
|
||||
|
||||
def laplace_equation(input_, output_):
|
||||
force_term = (torch.sin(input_['x']*torch.pi) *
|
||||
torch.sin(input_['y']*torch.pi))
|
||||
return nabla(output_['u'], input_).flatten() - force_term
|
||||
|
||||
def nil_dirichlet(input_, output_):
|
||||
value = 0.0
|
||||
return output_['u'] - value
|
||||
|
||||
conditions = {
|
||||
'gamma1': Condition(Span({'x': [-1, 1], 'y': 1}), nil_dirichlet),
|
||||
'gamma2': Condition(Span({'x': [-1, 1], 'y': -1}), nil_dirichlet),
|
||||
'gamma3': Condition(Span({'x': 1, 'y': [-1, 1]}), nil_dirichlet),
|
||||
'gamma4': Condition(Span({'x': -1, 'y': [-1, 1]}), nil_dirichlet),
|
||||
'D': Condition(Span({'x': [-1, 1], 'y': [-1, 1]}), laplace_equation),
|
||||
}
|
||||
|
||||
def poisson_sol(self, x, y):
|
||||
return -(np.sin(x*np.pi)*np.sin(y*np.pi))/(2*np.pi**2)
|
||||
|
||||
truth_solution = poisson_sol
|
||||
@@ -1,35 +0,0 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
from pina.segment import Segment
|
||||
from pina.cube import Cube
|
||||
from pina.problem import Problem2D
|
||||
from pina.operators import grad, div, nabla
|
||||
|
||||
|
||||
class Poisson2D(Problem2D):
|
||||
|
||||
input_variables = ['x', 'y']
|
||||
output_variables = ['u']
|
||||
spatial_domain = Cube([[0, 1], [0, 1]])
|
||||
|
||||
def laplace_equation(input_, output_):
|
||||
force_term = (torch.sin(input_['x']*torch.pi)
|
||||
* torch.sin(input_['y']*torch.pi))
|
||||
return nabla(output_['u'], input_).flatten() - force_term
|
||||
|
||||
def nil_dirichlet(input_, output_):
|
||||
value = 0.0
|
||||
return output_['u'] - value
|
||||
|
||||
conditions = {
|
||||
'gamma1': {'location': Segment((0, 0), (1, 0)), 'func': nil_dirichlet},
|
||||
'gamma2': {'location': Segment((1, 0), (1, 1)), 'func': nil_dirichlet},
|
||||
'gamma3': {'location': Segment((1, 1), (0, 1)), 'func': nil_dirichlet},
|
||||
'gamma4': {'location': Segment((0, 1), (0, 0)), 'func': nil_dirichlet},
|
||||
'D': {'location': Cube([[0, 1], [0, 1]]), 'func': laplace_equation}
|
||||
}
|
||||
|
||||
def poisson_sol(self, x, y):
|
||||
return -(np.sin(x*np.pi)*np.sin(y*np.pi))/(2*np.pi**2)
|
||||
|
||||
truth_solution = poisson_sol
|
||||
@@ -1,15 +1,10 @@
|
||||
import sys
|
||||
import numpy as np
|
||||
import torch
|
||||
import argparse
|
||||
from pina.pinn import PINN
|
||||
from pina.ppinn import ParametricPINN as pPINN
|
||||
from pina.label_tensor import LabelTensor
|
||||
from torch.nn import ReLU, Tanh, Softplus
|
||||
from problems.burgers import Burgers1D
|
||||
from pina.deep_feed_forward import DeepFeedForward
|
||||
import torch
|
||||
from torch.nn import Softplus
|
||||
|
||||
from pina import Plotter
|
||||
from pina import PINN, Plotter
|
||||
from pina.model import FeedForward
|
||||
from problems.burgers import Burgers1D
|
||||
|
||||
|
||||
class myFeature(torch.nn.Module):
|
||||
@@ -23,6 +18,7 @@ class myFeature(torch.nn.Module):
|
||||
def forward(self, x):
|
||||
return torch.sin(torch.pi * x[:, self.idx])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
parser = argparse.ArgumentParser(description="Run PINA")
|
||||
@@ -36,11 +32,8 @@ if __name__ == "__main__":
|
||||
feat = [myFeature(0)] if args.features else []
|
||||
|
||||
burgers_problem = Burgers1D()
|
||||
model = DeepFeedForward(
|
||||
model = FeedForward(
|
||||
layers=[30, 20, 10, 5],
|
||||
#layers=[8, 8, 8],
|
||||
#layers=[16, 8, 4, 4],
|
||||
#layers=[20, 4, 4, 4],
|
||||
output_variables=burgers_problem.output_variables,
|
||||
input_variables=burgers_problem.input_variables,
|
||||
func=Softplus,
|
||||
@@ -57,7 +50,7 @@ if __name__ == "__main__":
|
||||
|
||||
if args.s:
|
||||
pinn.span_pts(2000, 'latin', ['D'])
|
||||
pinn.span_pts(150, 'random', ['gamma1', 'gamma2', 'initia'])
|
||||
pinn.span_pts(150, 'random', ['gamma1', 'gamma2', 't0'])
|
||||
pinn.train(5000, 100)
|
||||
pinn.save_state('pina.burger.{}.{}'.format(args.id_run, args.features))
|
||||
else:
|
||||
|
||||
@@ -1,27 +1,21 @@
|
||||
import sys
|
||||
import numpy as np
|
||||
import torch
|
||||
import argparse
|
||||
from pina.pinn import PINN
|
||||
from pina.ppinn import ParametricPINN as pPINN
|
||||
from pina.label_tensor import LabelTensor
|
||||
from torch.nn import ReLU, Tanh, Softplus
|
||||
from problems.parametric_poisson import ParametricPoisson2DProblem as Poisson2D
|
||||
from pina.deep_feed_forward import DeepFeedForward
|
||||
import torch
|
||||
from torch.nn import Softplus
|
||||
|
||||
from pina.adaptive_functions import AdaptiveSin, AdaptiveCos, AdaptiveTanh
|
||||
from pina import PINN as pPINN
|
||||
from problems.parametric_poisson import ParametricPoisson
|
||||
from pina.model import FeedForward
|
||||
|
||||
|
||||
class myFeature(torch.nn.Module):
|
||||
"""
|
||||
Feature: sin(x)
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super(myFeature, self).__init__()
|
||||
|
||||
def forward(self, x):
|
||||
return torch.exp(- 2*(x[:, 0] - x[:, 2])**2 - 2*(x[:, 1] - x[:, 3])**2)
|
||||
return torch.exp(- 2*(x['x'] - x['mu1'])**2 - 2*(x['y'] - x['mu2'])**2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -35,11 +29,11 @@ if __name__ == "__main__":
|
||||
|
||||
feat = [myFeature()] if args.features else []
|
||||
|
||||
poisson_problem = Poisson2D()
|
||||
model = DeepFeedForward(
|
||||
poisson_problem = ParametricPoisson()
|
||||
model = FeedForward(
|
||||
layers=[200, 40, 10],
|
||||
output_variables=poisson_problem.output_variables,
|
||||
input_variables=poisson_problem.input_variables+['mu1', 'mu2'],
|
||||
input_variables=poisson_problem.input_variables,
|
||||
func=Softplus,
|
||||
extra_features=feat
|
||||
)
|
||||
@@ -53,105 +47,10 @@ if __name__ == "__main__":
|
||||
|
||||
if args.s:
|
||||
|
||||
pinn.span_pts(30, 'chebyshev', ['D'])
|
||||
pinn.span_pts(50, 'grid', ['gamma1', 'gamma2', 'gamma3', 'gamma4'])
|
||||
#pinn.plot_pts()
|
||||
pinn.span_pts(2000, 'random', ['D'])
|
||||
pinn.span_pts(200, 'random', ['gamma1', 'gamma2', 'gamma3', 'gamma4'])
|
||||
pinn.train(10000, 10)
|
||||
pinn.save_state('pina.poisson_param')
|
||||
|
||||
else:
|
||||
pinn.load_state('pina.poisson_param')
|
||||
#pinn.plot(40, torch.tensor([-0.8, -0.8]))
|
||||
#pinn.plot(40, torch.tensor([ 0.8, 0.8]))
|
||||
|
||||
from smithers.io import VTUHandler
|
||||
from scipy.interpolate import griddata
|
||||
import matplotlib
|
||||
matplotlib.use('GTK3Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
res = 64
|
||||
fname_minus = 'Poisson_param_08minus000000.vtu'
|
||||
param = torch.tensor([-0.8, -0.8])
|
||||
pts_container = []
|
||||
for mn, mx in [[-1, 1], [-1, 1]]:
|
||||
pts_container.append(np.linspace(mn, mx, res))
|
||||
grids_container = np.meshgrid(*pts_container)
|
||||
unrolled_pts = torch.tensor([t.flatten() for t in grids_container]).T
|
||||
unrolled_pts = torch.cat([unrolled_pts, param.double().repeat(unrolled_pts.shape[0]).reshape(-1, 2)], axis=1)
|
||||
|
||||
#unrolled_pts.to(dtype=self.dtype)
|
||||
unrolled_pts = LabelTensor(unrolled_pts, ['x1', 'x2', 'mu1', 'mu2'])
|
||||
|
||||
Z_pred = pinn.model(unrolled_pts.tensor)
|
||||
data = VTUHandler.read(fname_minus)
|
||||
|
||||
|
||||
print(data['points'][:, :2].shape)
|
||||
print(data['point_data']['f_16'].shape)
|
||||
print(grids_container[0].shape)
|
||||
print(grids_container[1].shape)
|
||||
Z_truth = griddata(data['points'][:, :2], data['point_data']['f_16'], (grids_container[0], grids_container[1]))
|
||||
|
||||
|
||||
err = np.abs(Z_truth + Z_pred.tensor.reshape(res, res).detach().numpy())
|
||||
|
||||
plt.subplot(1, 3, 1)
|
||||
plt.pcolor(-Z_pred.tensor.reshape(res, res).detach())
|
||||
plt.colorbar()
|
||||
plt.subplot(1, 3, 2)
|
||||
plt.pcolor(Z_truth)
|
||||
plt.colorbar()
|
||||
plt.subplot(1, 3, 3)
|
||||
plt.pcolor(err, vmin=0, vmax=0.009)
|
||||
plt.colorbar()
|
||||
plt.show()
|
||||
|
||||
print(unrolled_pts.tensor.shape)
|
||||
with open('parpoisson_minus_plot.txt', 'w') as f_:
|
||||
f_.write('x y truth pred e\n')
|
||||
for (x, y), tru, pre, e in zip(unrolled_pts[:, :2], Z_truth.reshape(-1, 1), -Z_pred.tensor.reshape(-1, 1), err.reshape(-1, 1)):
|
||||
f_.write('{} {} {} {} {}\n'.format(x.item(), y.item(), tru.item(), pre.item(), e.item()))
|
||||
|
||||
fname_plus = 'Poisson_param_08plus000000.vtu'
|
||||
param = torch.tensor([0.8, 0.8])
|
||||
pts_container = []
|
||||
for mn, mx in [[-1, 1], [-1, 1]]:
|
||||
pts_container.append(np.linspace(mn, mx, res))
|
||||
grids_container = np.meshgrid(*pts_container)
|
||||
unrolled_pts = torch.tensor([t.flatten() for t in grids_container]).T
|
||||
unrolled_pts = torch.cat([unrolled_pts, param.double().repeat(unrolled_pts.shape[0]).reshape(-1, 2)], axis=1)
|
||||
|
||||
#unrolled_pts.to(dtype=self.dtype)
|
||||
unrolled_pts = LabelTensor(unrolled_pts, ['x1', 'x2', 'mu1', 'mu2'])
|
||||
|
||||
Z_pred = pinn.model(unrolled_pts.tensor)
|
||||
data = VTUHandler.read(fname_plus)
|
||||
|
||||
|
||||
print(data['points'][:, :2].shape)
|
||||
print(data['point_data']['f_16'].shape)
|
||||
print(grids_container[0].shape)
|
||||
print(grids_container[1].shape)
|
||||
Z_truth = griddata(data['points'][:, :2], data['point_data']['f_16'], (grids_container[0], grids_container[1]))
|
||||
|
||||
|
||||
err = np.abs(Z_truth + Z_pred.tensor.reshape(res, res).detach().numpy())
|
||||
|
||||
plt.subplot(1, 3, 1)
|
||||
plt.pcolor(-Z_pred.tensor.reshape(res, res).detach())
|
||||
plt.colorbar()
|
||||
plt.subplot(1, 3, 2)
|
||||
plt.pcolor(Z_truth)
|
||||
plt.colorbar()
|
||||
plt.subplot(1, 3, 3)
|
||||
print('gggggg')
|
||||
plt.pcolor(err, vmin=0, vmax=0.001)
|
||||
plt.colorbar()
|
||||
plt.show()
|
||||
with open('parpoisson_plus_plot.txt', 'w') as f_:
|
||||
f_.write('x y truth pred e\n')
|
||||
for (x, y), tru, pre, e in zip(unrolled_pts[:, :2], Z_truth.reshape(-1, 1), -Z_pred.tensor.reshape(-1, 1), err.reshape(-1, 1)):
|
||||
f_.write('{} {} {} {} {}\n'.format(x.item(), y.item(), tru.item(), pre.item(), e.item()))
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user