Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Replace python funcion with sympy expression #507

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
2d95737
add sympy2func
AndPuQing Aug 9, 2023
f8bb795
fix node
AndPuQing Aug 10, 2023
b31a785
fix var name
AndPuQing Aug 10, 2023
d9d30d1
fix implementation
AndPuQing Aug 13, 2023
6877901
Merge branch 'develop' into feature-sympy
HydrogenSulfate Aug 23, 2023
2ccc9f5
add sympy to func module
HydrogenSulfate Aug 24, 2023
bb9d71c
add type hint and clean code
HydrogenSulfate Aug 24, 2023
8783ec9
update unitest for N-S equation with sympy-base 'nu'
HydrogenSulfate Aug 25, 2023
6f376b6
delete redundant sympy2func.py
HydrogenSulfate Aug 25, 2023
cfa853f
remove sympy to function code from expression.py to sym_to_func.py
HydrogenSulfate Aug 25, 2023
62e9855
update type hint in expression
HydrogenSulfate Aug 26, 2023
fee4553
update code
HydrogenSulfate Aug 26, 2023
1b7642e
update code
HydrogenSulfate Aug 26, 2023
1538f0d
update code
HydrogenSulfate Aug 26, 2023
36e48e5
refine sym_to_func.py
HydrogenSulfate Aug 26, 2023
d32fd84
replace sympy PDE for biharmonic and laplace
HydrogenSulfate Aug 26, 2023
4e61fa5
refine sym_to_func.py
HydrogenSulfate Aug 27, 2023
4baf466
fix bug in _cvt_to_key
HydrogenSulfate Aug 27, 2023
ba2a5c2
refine sym_to_func and expression code
HydrogenSulfate Aug 27, 2023
f057eec
add euler_beam static code(WIP, can not running, to be debug)
HydrogenSulfate Aug 27, 2023
ffd6b27
wip code
HydrogenSulfate Aug 28, 2023
0809194
Merge branch 'develop' into cvt_pyfunc_to_sym
HydrogenSulfate Aug 28, 2023
b0d1df1
temporary code(need to be refined)
HydrogenSulfate Aug 28, 2023
2fa8a8b
Merge branch 'develop' into cvt_pyfunc_to_sym
HydrogenSulfate Sep 6, 2023
b2a4509
update solver code
HydrogenSulfate Sep 6, 2023
13d6ff6
replace more pdes with sympy
HydrogenSulfate Sep 6, 2023
ffd3a93
simplify code in solver
HydrogenSulfate Sep 6, 2023
256f31a
update code
HydrogenSulfate Sep 7, 2023
3a870d9
rename 'normal_dot_vel' to 'normal_dot_vec'
HydrogenSulfate Sep 7, 2023
08e92d3
fix bug
HydrogenSulfate Sep 7, 2023
c2373ca
update unitest
HydrogenSulfate Sep 7, 2023
051dcd6
remove redundant unitest
HydrogenSulfate Sep 7, 2023
2eacfea
Merge branch 'develop' into cvt_pyfunc_to_sym
HydrogenSulfate Sep 7, 2023
c7eea1b
remove unnecessary code
HydrogenSulfate Sep 7, 2023
615fefb
remove unnecessary more code
HydrogenSulfate Sep 7, 2023
e096ea2
use DETACH_FUNC_NAME instead of 'detach'
HydrogenSulfate Sep 7, 2023
cb16107
add derivatives for sdf function
HydrogenSulfate Sep 7, 2023
899a2d2
replace .diff.diff with .diff(, 2)
HydrogenSulfate Sep 10, 2023
640c080
support exporting expression to .dot and .png file for visualizing an…
HydrogenSulfate Sep 10, 2023
16aae52
remove compute_sdf_derivatives for next PR
HydrogenSulfate Sep 10, 2023
9b46410
refine docstring of ppsci/data/dataset/array_dataset.py
HydrogenSulfate Sep 10, 2023
f179ec1
remove sdf_derivatives code in geometry for next PR
HydrogenSulfate Sep 10, 2023
2e37bca
remove print code in solver
HydrogenSulfate Sep 10, 2023
6ecb31b
rename sympy_to_function to lambdify and add it in ppsci.*
HydrogenSulfate Sep 10, 2023
0a88a08
rename for test files
HydrogenSulfate Sep 11, 2023
18a1638
rename sym_to_func.py to symbolic.py
HydrogenSulfate Sep 12, 2023
8ccf858
update linear_init_ and conv_init_ to kaiming style
HydrogenSulfate Sep 12, 2023
978cdfc
Merge branch 'develop' into cvt_pyfunc_to_sym
HydrogenSulfate Sep 12, 2023
a319e99
refine probability document
HydrogenSulfate Sep 12, 2023
be67fb4
change list to tuple
HydrogenSulfate Sep 12, 2023
eecc5e9
update docstrings of equations
HydrogenSulfate Sep 13, 2023
cb7f777
Merge branch 'develop' into cvt_pyfunc_to_sym
HydrogenSulfate Sep 13, 2023
59bc990
Merge branch 'develop' into cvt_pyfunc_to_sym
HydrogenSulfate Sep 13, 2023
c0228f0
larger atol to 1e-7 for test_linear_elasticity
HydrogenSulfate Sep 13, 2023
408e378
fix seed to 42 for test_linear_elasticity
HydrogenSulfate Sep 13, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
update code
  • Loading branch information
HydrogenSulfate committed Sep 7, 2023
commit 256f31a677eb2a54ac483ab06a8500ab163cff15
24 changes: 12 additions & 12 deletions examples/bracket/bracket.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,15 +127,15 @@
support_interior_constraint = ppsci.constraint.InteriorConstraint(
equation["LinearElasticity"].equations,
{
"equilibrium_x": 0,
"equilibrium_y": 0,
"equilibrium_z": 0,
"stress_disp_xx": 0,
"stress_disp_yy": 0,
"stress_disp_zz": 0,
"stress_disp_xy": 0,
"stress_disp_xz": 0,
"stress_disp_yz": 0,
"equilibrium_x": 0,
"equilibrium_y": 0,
"equilibrium_z": 0,
},
geom["geo"],
{**train_dataloader_cfg, "batch_size": 2048},
Expand All @@ -149,30 +149,30 @@
& (z < BOUNDS_SUPPORT_Z[1])
),
weight_dict={
"equilibrium_x": "sdf",
"equilibrium_y": "sdf",
"equilibrium_z": "sdf",
"stress_disp_xx": "sdf",
"stress_disp_yy": "sdf",
"stress_disp_zz": "sdf",
"stress_disp_xy": "sdf",
"stress_disp_xz": "sdf",
"stress_disp_yz": "sdf",
"equilibrium_x": "sdf",
"equilibrium_y": "sdf",
"equilibrium_z": "sdf",
},
name="support_interior",
)
bracket_interior_constraint = ppsci.constraint.InteriorConstraint(
equation["LinearElasticity"].equations,
{
"equilibrium_x": 0,
"equilibrium_y": 0,
"equilibrium_z": 0,
"stress_disp_xx": 0,
"stress_disp_yy": 0,
"stress_disp_zz": 0,
"stress_disp_xy": 0,
"stress_disp_xz": 0,
"stress_disp_yz": 0,
"equilibrium_x": 0,
"equilibrium_y": 0,
"equilibrium_z": 0,
},
geom["geo"],
{**train_dataloader_cfg, "batch_size": 1024},
Expand All @@ -186,15 +186,15 @@
& (z < BOUNDS_BRACKET_Z[1])
),
weight_dict={
"equilibrium_x": "sdf",
"equilibrium_y": "sdf",
"equilibrium_z": "sdf",
"stress_disp_xx": "sdf",
"stress_disp_yy": "sdf",
"stress_disp_zz": "sdf",
"stress_disp_xy": "sdf",
"stress_disp_xz": "sdf",
"stress_disp_yz": "sdf",
"equilibrium_x": "sdf",
"equilibrium_y": "sdf",
"equilibrium_z": "sdf",
},
name="bracket_interior",
)
Expand Down
4 changes: 1 addition & 3 deletions examples/pipe/poiseuille_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,7 @@ def output_trans_p(input, out):

# set euqation
equation = {
"NavierStokes": ppsci.equation.NavierStokes(
nu=lambda out: out["nu"], rho=RHO, dim=2, time=False
)
"NavierStokes": ppsci.equation.NavierStokes(nu="nu", rho=RHO, dim=2, time=False)
}

# set constraint
Expand Down
7 changes: 5 additions & 2 deletions ppsci/constraint/boundary_constraint.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,16 @@ def __init__(
name: str = "BC",
):
self.output_expr = output_expr
for label_name, expr in self.output_expr.items():
for output_name, expr in self.output_expr.items():
if isinstance(expr, str):
self.output_expr[label_name] = sp_parser.parse_expr(expr)
self.output_expr[output_name] = sp_parser.parse_expr(expr)

self.label_dict = label_dict
self.input_keys = geom.dim_keys
self.output_keys = list(label_dict.keys())
self.output_expr = {
k: v for k, v in output_expr.items() if k in self.output_keys
}
# "area" will be kept in "output_dict" for computation.
if isinstance(geom, geometry.Mesh):
self.output_keys += ["area"]
Expand Down
7 changes: 5 additions & 2 deletions ppsci/constraint/initial_constraint.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,16 @@ def __init__(
name: str = "IC",
):
self.output_expr = output_expr
for label_name, expr in self.output_expr.items():
for output_name, expr in self.output_expr.items():
if isinstance(expr, str):
self.output_expr[label_name] = sp_parser.parse_expr(expr)
self.output_expr[output_name] = sp_parser.parse_expr(expr)

self.label_dict = label_dict
self.input_keys = geom.dim_keys
self.output_keys = list(label_dict.keys())
self.output_expr = {
k: v for k, v in output_expr.items() if k in self.output_keys
}
# "area" will be kept in "output_dict" for computation.
if isinstance(geom.geometry, geometry.Mesh):
self.output_keys += ["area"]
Expand Down
7 changes: 5 additions & 2 deletions ppsci/constraint/integral_constraint.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,16 @@ def __init__(
name: str = "IgC",
):
self.output_expr = output_expr
for label_name, expr in self.output_expr.items():
for output_name, expr in self.output_expr.items():
if isinstance(expr, str):
self.output_expr[label_name] = sp_parser.parse_expr(expr)
self.output_expr[output_name] = sp_parser.parse_expr(expr)

self.label_dict = label_dict
self.input_keys = geom.dim_keys
self.output_keys = list(label_dict.keys())
self.output_expr = {
k: v for k, v in output_expr.items() if k in self.output_keys
}
# "area" will be kept in "output_dict" for computation.
if isinstance(geom, geometry.Mesh):
self.output_keys += ["area"]
Expand Down
9 changes: 6 additions & 3 deletions ppsci/constraint/interior_constraint.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,16 @@ def __init__(
name: str = "EQ",
):
self.output_expr = output_expr
for label_name, expr in self.output_expr.items():
if isinstance(expr, str):
self.output_expr[label_name] = sp_parser.parse_expr(expr)
for output_name, expr in self.output_expr.items():
if isinstance(expr, str) and output_name in label_dict:
self.output_expr[output_name] = sp_parser.parse_expr(expr)

self.label_dict = label_dict
self.input_keys = geom.dim_keys
self.output_keys = list(label_dict.keys())
self.output_expr = {
k: v for k, v in output_expr.items() if k in self.output_keys
}
# "area" will be kept in "output_dict" for computation.
if isinstance(geom, geometry.Mesh):
self.output_keys += ["area"]
Expand Down
7 changes: 5 additions & 2 deletions ppsci/constraint/periodic_constraint.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,15 @@ def __init__(
name: str = "PeriodicBC",
):
self.output_expr = output_expr
for label_name, expr in self.output_expr.items():
for output_name, expr in self.output_expr.items():
if isinstance(expr, str):
self.output_expr[label_name] = sp_parser.parse_expr(expr)
self.output_expr[output_name] = sp_parser.parse_expr(expr)

self.input_keys = geom.dim_keys
self.output_keys = list(output_expr.keys())
self.output_expr = {
k: v for k, v in output_expr.items() if k in self.output_keys
}
# "area" will be kept in "output_dict" for computation.
if isinstance(geom, geometry.Mesh):
self.output_keys += ["area"]
Expand Down
25 changes: 21 additions & 4 deletions ppsci/equation/pde/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple

import paddle
Expand All @@ -30,12 +31,11 @@ class PDE:
def __init__(self):
super().__init__()
self.equations = {}
# self.equations_func = {}
# self.detach_keys = []

# for PDE which has learnable parameter(s)
self.learnable_parameters = nn.ParameterList()

self.detach_keys: Optional[Tuple[str, ...]] = None

def create_symbols(self, symbol_str: str) -> Tuple[sympy.Symbol, ...]:
"""Create symbols

Expand All @@ -59,7 +59,24 @@ def create_function(
Returns:
sympy.Function: Named sympy function.
"""
return sympy.Function(name)(*invars)
expr = sympy.Function(name)(*invars)
if self.detach_keys and name in self.detach_keys:
expr = sympy.Function("detach")(expr)
return expr

def create_detach(
self,
expr: sympy.Basic,
) -> sympy.Function:
"""Create detach function for given expression.

Args:
expr (sympy.Basic): Given expression to be detached.

Returns:
sympy.Function: Detached expression.
"""
return sympy.Function("detach")(expr)

def add_equation(self, name: str, equation: Callable):
"""Add an equation.
Expand Down
23 changes: 20 additions & 3 deletions ppsci/equation/pde/biharmonic.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@

from __future__ import annotations

from typing import Optional
from typing import Tuple

from ppsci.equation.pde import base


Expand All @@ -34,14 +37,28 @@ class Biharmonic(base.PDE):
>>> pde = ppsci.equation.Biharmonic(2, -1.0, 1.0)
"""

def __init__(self, dim: int, q: float, D: float):
def __init__(
self,
dim: int,
q: float,
D: float,
detach_keys: Optional[Tuple[str, ...]] = None,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

更新docstring, 检查类型提示

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修改

):
super().__init__()
self.detach_keys = detach_keys

invars = self.create_symbols("x y z")[:dim]
u = self.create_function("u", invars)

if isinstance(q, str):
q = self.create_function("q", invars)
if isinstance(D, str):
D = self.create_function("D", invars)

self.dim = dim
self.q = q
self.D = D

invars = self.create_symbols("x y z")[: self.dim]
u = self.create_function("u", invars)
biharmonic = -self.q / self.D
for invar_i in invars:
for invar_j in invars:
Expand Down
12 changes: 9 additions & 3 deletions ppsci/equation/pde/laplace.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@

from __future__ import annotations

from typing import Optional
from typing import Tuple

from ppsci.equation.pde import base


Expand All @@ -32,12 +35,15 @@ class Laplace(base.PDE):
>>> pde = ppsci.equation.Laplace(2)
"""

def __init__(self, dim: int):
def __init__(self, dim: int, detach_keys: Optional[Tuple[str, ...]] = None):
super().__init__()
self.dim = dim
invars = self.create_symbols("x y z")[: self.dim]
self.detach_keys = detach_keys

invars = self.create_symbols("x y z")[:dim]
u = self.create_function("u", invars)

self.dim = dim

laplace = 0
for invar in invars:
laplace += u.diff(invar).diff(invar)
Expand Down
3 changes: 3 additions & 0 deletions ppsci/equation/pde/linear_elasticity.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from __future__ import annotations

from typing import Optional
from typing import Tuple

import sympy as sp

Expand Down Expand Up @@ -61,8 +62,10 @@ def __init__(
rho: float = 1,
dim: int = 3,
time: bool = False,
detach_keys: Optional[Tuple[str, ...]] = None,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

更新docstring

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修改

):
super().__init__()
self.detach_keys = detach_keys
self.dim = dim
self.time = time

Expand Down
39 changes: 29 additions & 10 deletions ppsci/equation/pde/navier_stokes.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
from __future__ import annotations

from typing import Callable
from typing import Optional
from typing import Tuple
from typing import Union

import sympy as sp

from ppsci.equation.pde import base


Expand Down Expand Up @@ -63,19 +63,37 @@ class NavierStokes(base.PDE):
>>> pde = ppsci.equation.NavierStokes(0.1, 1.0, 3, False)
"""

def __init__(self, nu: Union[float, Callable], rho: float, dim: int, time: bool):
def __init__(
self,
nu: Union[float, Callable],
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

后面代码中 nu 允许类型为 str, 类型提示需要修改下。其他变量也检查下有没有类似情况

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修改

rho: float,
dim: int,
time: bool,
detach_keys: Optional[Tuple[str, ...]] = None,
):
super().__init__()
self.detach_keys = detach_keys
t, x, y, z = self.create_symbols("t x y z")
invars = (x, y)
if time:
invars = (t,) + invars
if dim == 3:
invars += (z,)

self.nu = nu
self.rho = rho
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这两行代码中用的的 nu, rho 在后续代码中有修改,看是否需要把这两行放到修改后面

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修改

self.dim = dim
self.time = time

t, x, y, z = self.create_symbols("t x y z")
u, v, w, p = self.create_symbols("u v w p")
if self.dim == 2:
w = sp.Number(0)
if not time:
t = sp.Number(0)
if isinstance(nu, str):
nu = self.create_function(nu, invars)
if isinstance(rho, str):
rho = self.create_function(rho, invars)

u = self.create_function("u", invars)
v = self.create_function("v", invars)
w = self.create_function("w", invars)
p = self.create_function("p", invars)

continuity = u.diff(x) + v.diff(y) + w.diff(z)
momentum_x = (
Expand Down Expand Up @@ -105,4 +123,5 @@ def __init__(self, nu: Union[float, Callable], rho: float, dim: int, time: bool)
self.add_equation("continuity", continuity)
self.add_equation("momentum_x", momentum_x)
self.add_equation("momentum_y", momentum_y)
self.add_equation("momentum_z", momentum_z)
if self.dim == 3:
self.add_equation("momentum_z", momentum_z)
Loading