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

add unit test for biharmonic #394

Merged
merged 1 commit into from
Jun 23, 2023
Merged
Changes from all commits
Commits
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
74 changes: 74 additions & 0 deletions test/equation/test_biharmonic.py
Copy link
Collaborator

Choose a reason for hiding this comment

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

单测应该写的不正确,biharmonic是四阶微分,但是单测的参考值构造只用了一次hessian,相当于只有二阶微分image

Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import paddle
import pytest
from paddle import nn

from ppsci import equation

__all__ = []


@pytest.mark.parametrize("dim", (2, 3))
def test_biharmonic(dim):
"""Test for biharmonic equation."""
batch_size = 13
input_dims = ("x", "y", "z")[:dim]
output_dims = ("u",)

q = -1.0
D = 1.0

# generate input data
x = paddle.randn([batch_size, 1])
y = paddle.randn([batch_size, 1])
x.stop_gradient = False
y.stop_gradient = False
input_data = paddle.concat([x, y], axis=1)
if dim == 3:
z = paddle.randn([batch_size, 1])
z.stop_gradient = False
input_data = paddle.concat([x, y, z], axis=1)

# build NN model
model = nn.Sequential(
nn.Linear(len(input_dims), len(output_dims)),
nn.Tanh(),
)

# manually generate output
u = model(input_data)

# use self-defined jacobian and hessian
def jacobian(y: "paddle.Tensor", x: "paddle.Tensor") -> "paddle.Tensor":
return paddle.grad(y, x, create_graph=True)[0]

def hessian(y: "paddle.Tensor", x: "paddle.Tensor") -> "paddle.Tensor":
return jacobian(jacobian(y, x), x)

# compute expected result
expected_result = -q / D

# compute fourth order derivative
vars = (x, y)
if dim == 3:
vars += (z,)
for var_i in vars:
for var_j in vars:
expected_result += hessian(hessian(u, var_i), var_j)

# compute result using built-in Biharmonic module
biharmonic_equation = equation.Biharmonic(dim=dim, q=q, D=D)
data_dict = {
"x": x,
"y": y,
"u": u,
}
if dim == 3:
data_dict["z"] = z
test_result = biharmonic_equation.equations["biharmonic"](data_dict)

# check result whether is equal
assert paddle.allclose(expected_result, test_result)


if __name__ == "__main__":
pytest.main()