From aad358eca893ca9d11614685dd5ebf5fcf101ab7 Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Thu, 28 Mar 2024 22:53:46 +0800
Subject: [PATCH 01/15] ppsci.equation.PDE.parameters/state_dict/set_state_dict
api fix
---
ppsci/equation/pde/base.py | 65 +++++++++++++++++++++++++++++++++++---
1 file changed, 60 insertions(+), 5 deletions(-)
diff --git a/ppsci/equation/pde/base.py b/ppsci/equation/pde/base.py
index 41a0089de..3fe24469f 100644
--- a/ppsci/equation/pde/base.py
+++ b/ppsci/equation/pde/base.py
@@ -83,19 +83,74 @@ def add_equation(self, name: str, equation: Callable):
self.equations.update({name: equation})
def parameters(self) -> List[paddle.Tensor]:
- """Return parameters contained in PDE.
+ """Return learnable parameters contained in PDE.
+
+ Args:
+ None
Returns:
- List[Tensor]: A list of parameters.
+ List[Tensor]: A list of learnable parameters.
+
+ Examples:
+ >>> import ppsci
+ >>> pde = ppsci.equation.Vibration(2, -4, 0)
+ >>> print(pde.parameters())
+ [Parameter containing:
+ Tensor(shape=[], dtype=float32, place=Place(gpu:0), stop_gradient=False,
+ -4.), Parameter containing:
+ Tensor(shape=[], dtype=float32, place=Place(gpu:0), stop_gradient=False,
+ 0.)]
+
"""
return self.learnable_parameters.parameters()
def state_dict(self) -> Dict[str, paddle.Tensor]:
- """Return named parameters in dict."""
+ """Return named learnable parameters in dict.
+
+ Args:
+ None
+
+ Returns:
+ Dict[str, Tensor]: A dict of states(str) and learnable parameters(Tensor).
+
+ Examples:
+ >>> import ppsci
+ >>> pde = ppsci.equation.Vibration(2, -4, 0)
+ >>> print(pde.state_dict())
+ OrderedDict([('0', Parameter containing:
+ Tensor(shape=[], dtype=float64, place=Place(gpu:0), stop_gradient=False,
+ -4.)), ('1', Parameter containing:
+ Tensor(shape=[], dtype=float64, place=Place(gpu:0), stop_gradient=False,
+ 0.))])
+
+ """
+
return self.learnable_parameters.state_dict()
- def set_state_dict(self, state_dict):
- """Set state dict from dict."""
+ def set_state_dict(self, state_dict:Dict[str, paddle.Tensor]):
+ """Set state dict from dict.
+
+ Args:
+ state_dict (Dict[str, paddle.Tensor]): The state dict to be set.
+
+ Returns:
+ None
+
+ Examples:
+ >>> import paddle
+ >>> import ppsci
+ >>> paddle.set_default_dtype("float64")
+ >>> pde = ppsci.equation.Vibration(2, -4, 0)
+ >>> state = pde.state_dict()
+ >>> state['0'] = paddle.to_tensor(-3.1)
+ >>> pde.set_state_dict(state)
+ >>> print(state)
+ OrderedDict([('0', Tensor(shape=[], dtype=float64, place=Place(gpu:0), stop_gradient=True,
+ -3.10000000)), ('1', Parameter containing:
+ Tensor(shape=[], dtype=float64, place=Place(gpu:0), stop_gradient=False,
+ 0.))])
+
+ """
self.learnable_parameters.set_state_dict(state_dict)
def __str__(self):
From dbddb1b8f067a5b9018278f4661984fa850eb4c4 Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Thu, 28 Mar 2024 23:08:54 +0800
Subject: [PATCH 02/15] ppsci.equation.PDE.parameters/state_dict/set_state_dict
api fix
---
ppsci/equation/pde/base.py | 11 ++++-------
1 file changed, 4 insertions(+), 7 deletions(-)
diff --git a/ppsci/equation/pde/base.py b/ppsci/equation/pde/base.py
index 3fe24469f..9a0c0c53e 100644
--- a/ppsci/equation/pde/base.py
+++ b/ppsci/equation/pde/base.py
@@ -100,13 +100,12 @@ def parameters(self) -> List[paddle.Tensor]:
-4.), Parameter containing:
Tensor(shape=[], dtype=float32, place=Place(gpu:0), stop_gradient=False,
0.)]
-
"""
return self.learnable_parameters.parameters()
def state_dict(self) -> Dict[str, paddle.Tensor]:
"""Return named learnable parameters in dict.
-
+
Args:
None
@@ -122,21 +121,20 @@ def state_dict(self) -> Dict[str, paddle.Tensor]:
-4.)), ('1', Parameter containing:
Tensor(shape=[], dtype=float64, place=Place(gpu:0), stop_gradient=False,
0.))])
-
"""
return self.learnable_parameters.state_dict()
- def set_state_dict(self, state_dict:Dict[str, paddle.Tensor]):
+ def set_state_dict(self, state_dict: Dict[str, paddle.Tensor]):
"""Set state dict from dict.
-
+
Args:
state_dict (Dict[str, paddle.Tensor]): The state dict to be set.
Returns:
None
- Examples:
+ Examples:
>>> import paddle
>>> import ppsci
>>> paddle.set_default_dtype("float64")
@@ -149,7 +147,6 @@ def set_state_dict(self, state_dict:Dict[str, paddle.Tensor]):
-3.10000000)), ('1', Parameter containing:
Tensor(shape=[], dtype=float64, place=Place(gpu:0), stop_gradient=False,
0.))])
-
"""
self.learnable_parameters.set_state_dict(state_dict)
From 4c4f63173157ef0a318a5851b2462f099ca15821 Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Mon, 1 Apr 2024 22:00:35 +0800
Subject: [PATCH 03/15] fix api docs in the timedomain
---
ppsci/geometry/timedomain.py | 164 ++++++++++++++++++++++++++++++++++-
1 file changed, 161 insertions(+), 3 deletions(-)
diff --git a/ppsci/geometry/timedomain.py b/ppsci/geometry/timedomain.py
index 740a1a71b..7d8dd4eab 100644
--- a/ppsci/geometry/timedomain.py
+++ b/ppsci/geometry/timedomain.py
@@ -71,6 +71,24 @@ def __init__(
self.num_timestamps = len(timestamps)
def on_initial(self, t):
+ """Check if a specific time is on the initial time point
+
+ Args:
+ t (float): The time to be checked.
+
+ Returns:
+ bool: True or False for whether the specific time is on the initial time point.
+
+ Examples:
+ >>> import paddle
+ >>> import ppsci
+ >>> paddle.set_default_dtype("float64")
+ >>> geom = ppsci.geometry.TimeDomain(0, 1)
+ >>> check1 = geom.on_initial(0.00000001)
+ >>> check2 = geom.on_initial(0.6)
+ >>> print(check1, check2)
+ [ True] [False]
+ """
return np.isclose(t, self.t0).flatten()
@@ -112,9 +130,25 @@ def boundary_normal(self, x):
def uniform_points(self, n, boundary=True):
"""Uniform points on the spatial-temporal domain.
-
+ Note: Before using this method, you need to specify time_step or timestamps.(See Examples)
Geometry volume ~ bbox.
Time volume ~ diam.
+
+ Args:
+ n (int): The total number of sample points to be generated.
+ boundary (bool): Indicates whether boundary points are included, default is True.
+
+ Returns:
+ Ndarray: a set of spatial-temporal coordinate points 'tx' that represent sample points evenly distributed within the spatial-temporal domain.
+
+ Examples:
+ >>> import ppsci
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
+ >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
+ >>> time_geom.timedomain.time_step = 0.001
+ >>> ts = time_geom.uniform_points(1000)
+
"""
if self.timedomain.time_step is not None:
# exclude start time t0
@@ -164,6 +198,26 @@ def uniform_points(self, n, boundary=True):
return tx
def random_points(self, n, random="pseudo", criteria=None):
+ """ "Generate random points on the spatial-temporal domain.
+ Note: Before using this method, you need to specify time_step or timestamps.(See Examples)
+
+ Args:
+ n (int): The total number of random points to generate.
+ random (string): Specifies the way to generate random points, default is "pseudo" , which means that a pseudo-random number generator is used.
+ criteria (method): A method that filters on the generated random points, defualt is None.
+
+ Returns:
+ Ndarray: A set of random spatial-temporal points.
+
+ Examples:
+ >>> import ppsci
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
+ >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
+ >>> time_geom.timedomain.time_step = 0.001
+ >>> ts = time_geom.random_points(1000)
+
+ """
# time evenly and geometry random, if time_step if specified
if self.timedomain.time_step is not None:
nt = int(np.ceil(self.timedomain.diam / self.timedomain.time_step))
@@ -289,9 +343,23 @@ def random_points(self, n, random="pseudo", criteria=None):
def uniform_boundary_points(self, n, criteria=None):
"""Uniform boundary points on the spatial-temporal domain.
-
Geometry surface area ~ bbox.
Time surface area ~ diam.
+
+ Args:
+ n (int): The total number of boundary points on the spatial-temporal domain to be generated that are evenly distributed across geometry boundaries.
+ criteria (method): Used to filter the generated boundary points, only points that meet certain conditions are retained. Default is None.
+
+ Returns:
+ Ndarray: A set of point coordinates evenly distributed across geometry boundaries on the spatial-temporal domain.
+
+ Examples:
+ >>> import ppsci
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
+ >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
+ >>> ts = time_geom.uniform_boundary_points(1000)
+
"""
if self.geometry.ndim == 1:
nx = 2
@@ -351,6 +419,25 @@ def uniform_boundary_points(self, n, criteria=None):
return tx
def random_boundary_points(self, n, random="pseudo", criteria=None):
+ """Random boundary points on the spatial-temporal domain.
+ Note: Before using this method, you need to specify time_step or timestamps.(See Examples)
+
+ Args:
+ n (int): The total number of spatial-temporal points generated on a given geometry boundary.
+ random (string): Controls the way to generate random points. Default is "pseudo".
+ criteria (method): Used to filter the generated boundary points, only points that meet certain conditions are retained. Default is None.
+
+ Returns:
+ Ndarray: A set of point coordinates randomly distributed across geometry boundaries on the spatial-temporal domain.
+ Examples:
+ >>> import ppsci
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
+ >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
+ >>> time_geom.timedomain.time_step = 0.001
+ >>> ts = time_geom.random_boundary_points(1000)
+
+ """
if self.timedomain.time_step is not None:
# exclude start time t0
nt = int(np.ceil(self.timedomain.diam / self.timedomain.time_step))
@@ -524,6 +611,22 @@ def random_boundary_points(self, n, random="pseudo", criteria=None):
return t_x
def uniform_initial_points(self, n):
+ """Generate evenly distributed point coordinates on the spatial-temporal domain at the initial moment.
+
+ Args:
+ n (int): The total number of generated points.
+
+ Returns:
+ Ndarray: A set of point coordinates evenly distributed on the spatial-temporal domain at the initial moment.
+
+ Examples:
+ >>> import ppsci
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
+ >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
+ >>> ts = time_geom.uniform_initial_points(1000)
+
+ """
x = self.geometry.uniform_points(n, True)
t = self.timedomain.t0
if len(x) > n:
@@ -531,11 +634,47 @@ def uniform_initial_points(self, n):
return np.hstack((np.full([n, 1], t, dtype=paddle.get_default_dtype()), x))
def random_initial_points(self, n, random="pseudo"):
+ """Generate randomly distributed point coordinates on the spatial-temporal domain at the initial moment.
+
+ Args:
+ n (int): The total number of generated points.
+ random (string): Controls the way to generate random points. Default is "pseudo".
+
+ Returns:
+ Ndarray: A set of point coordinates randomly distributed on the spatial-temporal domain at the initial moment.
+
+ Examples:
+ >>> import ppsci
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
+ >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
+ >>> ts = time_geom.random_initial_points(1000)
+
+ """
x = self.geometry.random_points(n, random=random)
t = self.timedomain.t0
return np.hstack((np.full([n, 1], t, dtype=paddle.get_default_dtype()), x))
def periodic_point(self, x, component):
+ """process given point coordinates to satisfy the periodic boundary conditions of the geometry
+
+ Args:
+ x (Dict[str, ndarray]): Contains the coordinates and timestamps of the points. It represents the coordinates of the point to be processed.
+ component (int): Specifies the components or dimensions of specific spatial coordinates that are periodically processed
+
+ Returns:
+ Dict[str, ndarray] : contains the original timestamps and the coordinates of the spatial point after periodic processing.
+
+ Examples:
+ >>> import ppsci
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
+ >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
+ >>> time_geom.timedomain.time_step = 0.1
+ >>> ts = time_geom.sample_boundary(100)
+ >>> result = time_geom.periodic_point(ts, 0)
+
+ """
xp = self.geometry.periodic_point(x, component)
txp = {"t": x["t"], **xp}
return txp
@@ -548,7 +687,26 @@ def sample_initial_interior(
evenly=False,
compute_sdf_derivatives: bool = False,
):
- """Sample random points in the time-geometry and return those meet criteria."""
+ """Sample random points in the time-geometry and return those meet criteria.
+
+ Args:
+ n (int): The total number of interior points generated.
+ random (string): The method used to specify the initial point of generation. Default is "pseudo".
+ criteria (method): Used to filter the generated interior points, only points that meet certain conditions are retained. Default is None.
+ evenly (bool): Indicates whether the initial points are generated evenly. Default is False.
+ compute_sdf_derivatives (bool): Indicates whether to calculate the derivative of signed distance function or not. Default is False.
+
+ Returns:
+ Ndarray: Contains the coordinates of the initial internal point generated, as well as the potentially computed signed distance function and its derivative.
+
+ Examples:
+ >>> import ppsci
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
+ >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
+ >>> ts = time_geom.sample_initial_interior(1000)
+
+ """
x = np.empty(shape=(n, self.ndim), dtype=paddle.get_default_dtype())
_size, _ntry, _nsuc = 0, 0, 0
while _size < n:
From c54753357f6cdb183d9136910acc1bc1bfc5bdf8 Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Tue, 2 Apr 2024 19:08:23 +0800
Subject: [PATCH 04/15] fix api docs of timedomain
---
ppsci/geometry/timedomain.py | 130 +++++++++++++++++++++--------------
1 file changed, 77 insertions(+), 53 deletions(-)
diff --git a/ppsci/geometry/timedomain.py b/ppsci/geometry/timedomain.py
index 7d8dd4eab..eda752e1b 100644
--- a/ppsci/geometry/timedomain.py
+++ b/ppsci/geometry/timedomain.py
@@ -60,9 +60,12 @@ def __init__(
self.t0 = t0
self.t1 = t1
self.time_step = time_step
- self.timestamps = np.array(
- timestamps, dtype=paddle.get_default_dtype()
- ).reshape([-1])
+ if timestamps is None:
+ self.timestamps = None
+ else:
+ self.timestamps = np.array(
+ timestamps, dtype=paddle.get_default_dtype()
+ ).reshape([-1])
if time_step is not None:
if time_step <= 0:
raise ValueError(f"time_step({time_step}) must be larger than 0.")
@@ -70,11 +73,11 @@ def __init__(
elif timestamps is not None:
self.num_timestamps = len(timestamps)
- def on_initial(self, t):
- """Check if a specific time is on the initial time point
+ def on_initial(self, t: np.ndarray):
+ """Check if a specific time is on the initial time point.
Args:
- t (float): The time to be checked.
+ t (np.ndarray): The time to be checked.
Returns:
bool: True or False for whether the specific time is on the initial time point.
@@ -82,12 +85,11 @@ def on_initial(self, t):
Examples:
>>> import paddle
>>> import ppsci
- >>> paddle.set_default_dtype("float64")
>>> geom = ppsci.geometry.TimeDomain(0, 1)
- >>> check1 = geom.on_initial(0.00000001)
- >>> check2 = geom.on_initial(0.6)
- >>> print(check1, check2)
- [ True] [False]
+ >>> T = [0, 0.01, 0.126, 0.2, 0.3]
+ >>> check = geom.on_initial(T)
+ >>> print(check)
+ [ True False False False False]
"""
return np.isclose(t, self.t0).flatten()
@@ -128,9 +130,8 @@ def boundary_normal(self, x):
normal = self.geometry.boundary_normal(x[:, 1:])
return np.hstack((x[:, :1], normal))
- def uniform_points(self, n, boundary=True):
+ def uniform_points(self, n: int, boundary: bool = True):
"""Uniform points on the spatial-temporal domain.
- Note: Before using this method, you need to specify time_step or timestamps.(See Examples)
Geometry volume ~ bbox.
Time volume ~ diam.
@@ -139,17 +140,19 @@ def uniform_points(self, n, boundary=True):
boundary (bool): Indicates whether boundary points are included, default is True.
Returns:
- Ndarray: a set of spatial-temporal coordinate points 'tx' that represent sample points evenly distributed within the spatial-temporal domain.
+ np.ndarray: a set of spatial-temporal coordinate points 'tx' that represent sample points evenly distributed within the spatial-temporal domain.
Examples:
>>> import ppsci
- >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1, 0.001)
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
- >>> time_geom.timedomain.time_step = 0.001
>>> ts = time_geom.uniform_points(1000)
-
+ >>> print(ts.shape)
+ (1000, 3)
"""
+ if self.timedomain.time_step is None and self.timedomain.timestamps is None:
+ raise ValueError("Either time_step or timestamps must be provided.")
if self.timedomain.time_step is not None:
# exclude start time t0
nt = int(np.ceil(self.timedomain.diam / self.timedomain.time_step))
@@ -197,9 +200,8 @@ def uniform_points(self, n, boundary=True):
tx = tx[:n]
return tx
- def random_points(self, n, random="pseudo", criteria=None):
- """ "Generate random points on the spatial-temporal domain.
- Note: Before using this method, you need to specify time_step or timestamps.(See Examples)
+ def random_points(self, n: int, random: str = "pseudo", criteria: callable = None):
+ """Generate random points on the spatial-temporal domain.
Args:
n (int): The total number of random points to generate.
@@ -207,17 +209,19 @@ def random_points(self, n, random="pseudo", criteria=None):
criteria (method): A method that filters on the generated random points, defualt is None.
Returns:
- Ndarray: A set of random spatial-temporal points.
+ np.ndarray: A set of random spatial-temporal points.
Examples:
>>> import ppsci
- >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1, 0.001)
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
- >>> time_geom.timedomain.time_step = 0.001
>>> ts = time_geom.random_points(1000)
-
+ >>> print(ts.shape)
+ (1000, 3)
"""
+ if self.timedomain.time_step is None and self.timedomain.timestamps is None:
+ raise ValueError("Either time_step or timestamps must be provided.")
# time evenly and geometry random, if time_step if specified
if self.timedomain.time_step is not None:
nt = int(np.ceil(self.timedomain.diam / self.timedomain.time_step))
@@ -341,7 +345,7 @@ def random_points(self, n, random="pseudo", criteria=None):
t = np.random.permutation(t)
return np.hstack((t, x))
- def uniform_boundary_points(self, n, criteria=None):
+ def uniform_boundary_points(self, n: int, criteria: callable = None):
"""Uniform boundary points on the spatial-temporal domain.
Geometry surface area ~ bbox.
Time surface area ~ diam.
@@ -351,7 +355,7 @@ def uniform_boundary_points(self, n, criteria=None):
criteria (method): Used to filter the generated boundary points, only points that meet certain conditions are retained. Default is None.
Returns:
- Ndarray: A set of point coordinates evenly distributed across geometry boundaries on the spatial-temporal domain.
+ np.ndarray: A set of point coordinates evenly distributed across geometry boundaries on the spatial-temporal domain.
Examples:
>>> import ppsci
@@ -359,7 +363,8 @@ def uniform_boundary_points(self, n, criteria=None):
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
>>> ts = time_geom.uniform_boundary_points(1000)
-
+ >>> print(ts.shape)
+ (1000, 3)
"""
if self.geometry.ndim == 1:
nx = 2
@@ -418,9 +423,10 @@ def uniform_boundary_points(self, n, criteria=None):
tx = tx[:n]
return tx
- def random_boundary_points(self, n, random="pseudo", criteria=None):
+ def random_boundary_points(
+ self, n: int, random: str = "pseudo", criteria: callable = None
+ ):
"""Random boundary points on the spatial-temporal domain.
- Note: Before using this method, you need to specify time_step or timestamps.(See Examples)
Args:
n (int): The total number of spatial-temporal points generated on a given geometry boundary.
@@ -428,16 +434,20 @@ def random_boundary_points(self, n, random="pseudo", criteria=None):
criteria (method): Used to filter the generated boundary points, only points that meet certain conditions are retained. Default is None.
Returns:
- Ndarray: A set of point coordinates randomly distributed across geometry boundaries on the spatial-temporal domain.
+ np.ndarray: A set of point coordinates randomly distributed across geometry boundaries on the spatial-temporal domain.
+
Examples:
>>> import ppsci
- >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1, 0.001)
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
- >>> time_geom.timedomain.time_step = 0.001
>>> ts = time_geom.random_boundary_points(1000)
+ >>> print(ts.shape)
+ (1000, 3)
"""
+ if self.timedomain.time_step is None and self.timedomain.timestamps is None:
+ raise ValueError("Either time_step or timestamps must be provided.")
if self.timedomain.time_step is not None:
# exclude start time t0
nt = int(np.ceil(self.timedomain.diam / self.timedomain.time_step))
@@ -610,14 +620,14 @@ def random_boundary_points(self, n, random="pseudo", criteria=None):
else:
return t_x
- def uniform_initial_points(self, n):
+ def uniform_initial_points(self, n: int):
"""Generate evenly distributed point coordinates on the spatial-temporal domain at the initial moment.
Args:
n (int): The total number of generated points.
Returns:
- Ndarray: A set of point coordinates evenly distributed on the spatial-temporal domain at the initial moment.
+ np.ndarray: A set of point coordinates evenly distributed on the spatial-temporal domain at the initial moment.
Examples:
>>> import ppsci
@@ -625,7 +635,8 @@ def uniform_initial_points(self, n):
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
>>> ts = time_geom.uniform_initial_points(1000)
-
+ >>> print(ts.shape)
+ (1000, 3)
"""
x = self.geometry.uniform_points(n, True)
t = self.timedomain.t0
@@ -633,7 +644,7 @@ def uniform_initial_points(self, n):
x = x[:n]
return np.hstack((np.full([n, 1], t, dtype=paddle.get_default_dtype()), x))
- def random_initial_points(self, n, random="pseudo"):
+ def random_initial_points(self, n: int, random: str = "pseudo"):
"""Generate randomly distributed point coordinates on the spatial-temporal domain at the initial moment.
Args:
@@ -641,7 +652,7 @@ def random_initial_points(self, n, random="pseudo"):
random (string): Controls the way to generate random points. Default is "pseudo".
Returns:
- Ndarray: A set of point coordinates randomly distributed on the spatial-temporal domain at the initial moment.
+ np.ndarray: A set of point coordinates randomly distributed on the spatial-temporal domain at the initial moment.
Examples:
>>> import ppsci
@@ -649,30 +660,37 @@ def random_initial_points(self, n, random="pseudo"):
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
>>> ts = time_geom.random_initial_points(1000)
-
+ >>> print(ts.shape)
+ (1000, 3)
"""
x = self.geometry.random_points(n, random=random)
t = self.timedomain.t0
return np.hstack((np.full([n, 1], t, dtype=paddle.get_default_dtype()), x))
- def periodic_point(self, x, component):
- """process given point coordinates to satisfy the periodic boundary conditions of the geometry
+ def periodic_point(self, x: dict[str, np.ndarray], component: int):
+ """process given point coordinates to satisfy the periodic boundary conditions of the geometry.
Args:
- x (Dict[str, ndarray]): Contains the coordinates and timestamps of the points. It represents the coordinates of the point to be processed.
- component (int): Specifies the components or dimensions of specific spatial coordinates that are periodically processed
+ x (dict[str, np.ndarray]): Contains the coordinates and timestamps of the points. It represents the coordinates of the point to be processed.
+ component (int): Specifies the components or dimensions of specific spatial coordinates that are periodically processed.
Returns:
- Dict[str, ndarray] : contains the original timestamps and the coordinates of the spatial point after periodic processing.
+ dict[str, np.ndarray] : contains the original timestamps and the coordinates of the spatial point after periodic processing.
Examples:
- >>> import ppsci
- >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
- >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
- >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
- >>> time_geom.timedomain.time_step = 0.1
- >>> ts = time_geom.sample_boundary(100)
- >>> result = time_geom.periodic_point(ts, 0)
+ >>> import ppsci
+ >>> timedomain = ppsci.geometry.TimeDomain(0, 1, 0.1)
+ >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
+ >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
+ >>> ts = time_geom.sample_boundary(1000)
+ >>> result = time_geom.periodic_point(ts, 0)
+ >>> for k,v in result.items():
+ ... print(k, v.shape)
+ t (1000, 1)
+ x (1000, 1)
+ y (1000, 1)
+ normal_x (1000, 1)
+ normal_y (1000, 1)
"""
xp = self.geometry.periodic_point(x, component)
@@ -683,8 +701,8 @@ def sample_initial_interior(
self,
n: int,
random: str = "pseudo",
- criteria=None,
- evenly=False,
+ criteria: callable = None,
+ evenly: bool = False,
compute_sdf_derivatives: bool = False,
):
"""Sample random points in the time-geometry and return those meet criteria.
@@ -697,7 +715,7 @@ def sample_initial_interior(
compute_sdf_derivatives (bool): Indicates whether to calculate the derivative of signed distance function or not. Default is False.
Returns:
- Ndarray: Contains the coordinates of the initial internal point generated, as well as the potentially computed signed distance function and its derivative.
+ np.ndarray: Contains the coordinates of the initial internal point generated, as well as the potentially computed signed distance function and its derivative.
Examples:
>>> import ppsci
@@ -705,6 +723,12 @@ def sample_initial_interior(
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
>>> ts = time_geom.sample_initial_interior(1000)
+ >>> for k,v in ts.items():
+ ... print(k, v.shape)
+ t (1000, 1)
+ x (1000, 1)
+ y (1000, 1)
+ sdf (1000, 1)
"""
x = np.empty(shape=(n, self.ndim), dtype=paddle.get_default_dtype())
From 4cf16b45b9437a6ff2fe4333812e8c1a8f3aaf7f Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Wed, 3 Apr 2024 23:38:31 +0800
Subject: [PATCH 05/15] fix api docs of timedomain
---
ppsci/geometry/timedomain.py | 31 +++++++++++++++----------------
1 file changed, 15 insertions(+), 16 deletions(-)
diff --git a/ppsci/geometry/timedomain.py b/ppsci/geometry/timedomain.py
index eda752e1b..da32539b0 100644
--- a/ppsci/geometry/timedomain.py
+++ b/ppsci/geometry/timedomain.py
@@ -19,6 +19,8 @@
from __future__ import annotations
import itertools
+from typing import Callable
+from typing import Dict
from typing import Optional
from typing import Tuple
@@ -151,8 +153,6 @@ def uniform_points(self, n: int, boundary: bool = True):
>>> print(ts.shape)
(1000, 3)
"""
- if self.timedomain.time_step is None and self.timedomain.timestamps is None:
- raise ValueError("Either time_step or timestamps must be provided.")
if self.timedomain.time_step is not None:
# exclude start time t0
nt = int(np.ceil(self.timedomain.diam / self.timedomain.time_step))
@@ -200,13 +200,15 @@ def uniform_points(self, n: int, boundary: bool = True):
tx = tx[:n]
return tx
- def random_points(self, n: int, random: str = "pseudo", criteria: callable = None):
+ def random_points(
+ self, n: int, random: str = "pseudo", criteria: Optional[Callable] = None
+ ):
"""Generate random points on the spatial-temporal domain.
Args:
n (int): The total number of random points to generate.
random (string): Specifies the way to generate random points, default is "pseudo" , which means that a pseudo-random number generator is used.
- criteria (method): A method that filters on the generated random points, defualt is None.
+ criteria (Optional[Callable]): A method that filters on the generated random points, defualt is None.
Returns:
np.ndarray: A set of random spatial-temporal points.
@@ -345,14 +347,14 @@ def random_points(self, n: int, random: str = "pseudo", criteria: callable = Non
t = np.random.permutation(t)
return np.hstack((t, x))
- def uniform_boundary_points(self, n: int, criteria: callable = None):
+ def uniform_boundary_points(self, n: int, criteria: Optional[Callable] = None):
"""Uniform boundary points on the spatial-temporal domain.
Geometry surface area ~ bbox.
Time surface area ~ diam.
Args:
n (int): The total number of boundary points on the spatial-temporal domain to be generated that are evenly distributed across geometry boundaries.
- criteria (method): Used to filter the generated boundary points, only points that meet certain conditions are retained. Default is None.
+ criteria (Optional[Callable]): Used to filter the generated boundary points, only points that meet certain conditions are retained. Default is None.
Returns:
np.ndarray: A set of point coordinates evenly distributed across geometry boundaries on the spatial-temporal domain.
@@ -424,14 +426,14 @@ def uniform_boundary_points(self, n: int, criteria: callable = None):
return tx
def random_boundary_points(
- self, n: int, random: str = "pseudo", criteria: callable = None
+ self, n: int, random: str = "pseudo", criteria: Optional[Callable] = None
):
"""Random boundary points on the spatial-temporal domain.
Args:
n (int): The total number of spatial-temporal points generated on a given geometry boundary.
random (string): Controls the way to generate random points. Default is "pseudo".
- criteria (method): Used to filter the generated boundary points, only points that meet certain conditions are retained. Default is None.
+ criteria (Optional[Callable]): Used to filter the generated boundary points, only points that meet certain conditions are retained. Default is None.
Returns:
np.ndarray: A set of point coordinates randomly distributed across geometry boundaries on the spatial-temporal domain.
@@ -444,7 +446,6 @@ def random_boundary_points(
>>> ts = time_geom.random_boundary_points(1000)
>>> print(ts.shape)
(1000, 3)
-
"""
if self.timedomain.time_step is None and self.timedomain.timestamps is None:
raise ValueError("Either time_step or timestamps must be provided.")
@@ -667,15 +668,15 @@ def random_initial_points(self, n: int, random: str = "pseudo"):
t = self.timedomain.t0
return np.hstack((np.full([n, 1], t, dtype=paddle.get_default_dtype()), x))
- def periodic_point(self, x: dict[str, np.ndarray], component: int):
+ def periodic_point(self, x: Dict[str, np.ndarray], component: int):
"""process given point coordinates to satisfy the periodic boundary conditions of the geometry.
Args:
- x (dict[str, np.ndarray]): Contains the coordinates and timestamps of the points. It represents the coordinates of the point to be processed.
+ x (Dict[str, np.ndarray]): Contains the coordinates and timestamps of the points. It represents the coordinates of the point to be processed.
component (int): Specifies the components or dimensions of specific spatial coordinates that are periodically processed.
Returns:
- dict[str, np.ndarray] : contains the original timestamps and the coordinates of the spatial point after periodic processing.
+ Dict[str, np.ndarray] : contains the original timestamps and the coordinates of the spatial point after periodic processing.
Examples:
>>> import ppsci
@@ -691,7 +692,6 @@ def periodic_point(self, x: dict[str, np.ndarray], component: int):
y (1000, 1)
normal_x (1000, 1)
normal_y (1000, 1)
-
"""
xp = self.geometry.periodic_point(x, component)
txp = {"t": x["t"], **xp}
@@ -701,7 +701,7 @@ def sample_initial_interior(
self,
n: int,
random: str = "pseudo",
- criteria: callable = None,
+ criteria: Optional[Callable] = None,
evenly: bool = False,
compute_sdf_derivatives: bool = False,
):
@@ -710,7 +710,7 @@ def sample_initial_interior(
Args:
n (int): The total number of interior points generated.
random (string): The method used to specify the initial point of generation. Default is "pseudo".
- criteria (method): Used to filter the generated interior points, only points that meet certain conditions are retained. Default is None.
+ criteria (Optional[Callable]): Used to filter the generated interior points, only points that meet certain conditions are retained. Default is None.
evenly (bool): Indicates whether the initial points are generated evenly. Default is False.
compute_sdf_derivatives (bool): Indicates whether to calculate the derivative of signed distance function or not. Default is False.
@@ -729,7 +729,6 @@ def sample_initial_interior(
x (1000, 1)
y (1000, 1)
sdf (1000, 1)
-
"""
x = np.empty(shape=(n, self.ndim), dtype=paddle.get_default_dtype())
_size, _ntry, _nsuc = 0, 0, 0
From 01f54d5aa467a6d00d8bd2ab9d29c916b5f1f44a Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Wed, 10 Apr 2024 01:07:09 +0800
Subject: [PATCH 06/15] ppsci api docs fixed
---
ppsci/arch/physx_transformer.py | 16 ++++++++--------
ppsci/autodiff/ad.py | 18 +++++++++---------
2 files changed, 17 insertions(+), 17 deletions(-)
diff --git a/ppsci/arch/physx_transformer.py b/ppsci/arch/physx_transformer.py
index f004a63a3..e3fc5e510 100644
--- a/ppsci/arch/physx_transformer.py
+++ b/ppsci/arch/physx_transformer.py
@@ -256,14 +256,14 @@ class PhysformerGPT2(base.Arch):
output data to the physical space. Defaults to None.
Examples:
- >>> import paddle
- >>> import ppsci
- >>> model = ppsci.arch.PhysformerGPT2(("embeds", ), ("pred_embeds", ), 6, 16, 128, 4)
- >>> data = paddle.to_tensor(paddle.randn([10, 16, 128]))
- >>> inputs = {"embeds": data}
- >>> outputs = model(inputs)
- >>> print(outputs["pred_embeds"].shape)
- [10, 16, 128]
+ >>> import paddle
+ >>> import ppsci
+ >>> model = ppsci.arch.PhysformerGPT2(("embeds", ), ("pred_embeds", ), 6, 16, 128, 4)
+ >>> data = paddle.to_tensor(paddle.randn([10, 16, 128]))
+ >>> inputs = {"embeds": data}
+ >>> outputs = model(inputs)
+ >>> print(outputs["pred_embeds"].shape)
+ [10, 16, 128]
"""
def __init__(
diff --git a/ppsci/autodiff/ad.py b/ppsci/autodiff/ad.py
index 3be90dbea..55453aa07 100644
--- a/ppsci/autodiff/ad.py
+++ b/ppsci/autodiff/ad.py
@@ -310,15 +310,15 @@ def clear():
None.
Examples:
- >>> import paddle
- >>> import ppsci
- >>> x = paddle.randn([4, 3])
- >>> x.stop_gradient = False
- >>> y = (x * x).sin()
- >>> dy_dxx = ppsci.autodiff.hessian(y, x, component=0)
- >>> ppsci.autodiff.clear()
- >>> print(ppsci.autodiff.hessian.Hs)
- {}
+ >>> import paddle
+ >>> import ppsci
+ >>> x = paddle.randn([4, 3])
+ >>> x.stop_gradient = False
+ >>> y = (x * x).sin()
+ >>> dy_dxx = ppsci.autodiff.hessian(y, x, component=0)
+ >>> ppsci.autodiff.clear()
+ >>> print(ppsci.autodiff.hessian.Hs)
+ {}
"""
jacobian._clear()
hessian._clear()
From ca34443aca8a02232937a0a4c3bd77c5851fa835 Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Wed, 10 Apr 2024 14:10:24 +0800
Subject: [PATCH 07/15] ppsci api docs fixed
---
ppsci/utils/misc.py | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/ppsci/utils/misc.py b/ppsci/utils/misc.py
index b4ae27a87..390ccee33 100644
--- a/ppsci/utils/misc.py
+++ b/ppsci/utils/misc.py
@@ -303,6 +303,22 @@ def all_gather(
Returns:
Union[paddle.Tensor, List[paddle.Tensor]]: Gathered Tensors.
+
+ Examples:
+ >>> import paddle
+ >>> import ppsci
+ >>> import paddle.distributed as dist
+ >>> dist.init_parallel_env()
+ >>> if dist.get_rank() == 0:
+ ... data = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])
+ ... else:
+ ... data = paddle.to_tensor([[7, 8, 9], [10, 11, 12]])
+ >>> result = ppsci.utils.misc.all_gather(data)
+ >>> print(result.numpy())
+ [[ 1 2 3]
+ [ 4 5 6]
+ [ 7 8 9]
+ [10 11 12]]
"""
result: List[paddle.Tensor] = []
From bd621abe8b012748912c25d2c12e45bf37243910 Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Fri, 12 Apr 2024 10:43:19 +0800
Subject: [PATCH 08/15] ppsci api docs fixed
---
ppsci/arch/afno.py | 6 +++---
ppsci/utils/misc.py | 8 ++++----
2 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/ppsci/arch/afno.py b/ppsci/arch/afno.py
index dd8fe44f9..f30cd6ede 100644
--- a/ppsci/arch/afno.py
+++ b/ppsci/arch/afno.py
@@ -413,12 +413,12 @@ class AFNONet(base.Arch):
Examples:
>>> import ppsci
- >>> model = ppsci.arch.AFNONet(("input", ), ("output", ), img_size=(180, 360))
- >>> input_data = {"input": paddle.randn([4, 20, 180, 360])}
+ >>> model = ppsci.arch.AFNONet(("input", ), ("output", ))
+ >>> input_data = {"input": paddle.randn([1, 20, 720, 1440])}
>>> output_data = model(input_data)
>>> for k, v in output_data.items():
... print(k, v.shape)
- output [4, 20, 176, 360]
+ output [1, 20, 720, 1440]
"""
def __init__(
diff --git a/ppsci/utils/misc.py b/ppsci/utils/misc.py
index 390ccee33..df29db303 100644
--- a/ppsci/utils/misc.py
+++ b/ppsci/utils/misc.py
@@ -308,13 +308,13 @@ def all_gather(
>>> import paddle
>>> import ppsci
>>> import paddle.distributed as dist
- >>> dist.init_parallel_env()
- >>> if dist.get_rank() == 0:
+ >>> dist.init_parallel_env() # doctest: +SKIP
+ >>> if dist.get_rank() == 0: # doctest: +SKIP
... data = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])
... else:
... data = paddle.to_tensor([[7, 8, 9], [10, 11, 12]])
- >>> result = ppsci.utils.misc.all_gather(data)
- >>> print(result.numpy())
+ >>> result = ppsci.utils.misc.all_gather(data) # doctest: +SKIP
+ >>> print(result.numpy()) # doctest: +SKIP
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
From 559a4a496ece9c8e4cd515a95afdf033691ba302 Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Mon, 6 May 2024 15:39:54 +0800
Subject: [PATCH 09/15] add export and infer for bracket
---
examples/bracket/bracket.py | 63 ++++++++++++++++++++++++++++++
examples/bracket/conf/bracket.yaml | 18 +++++++++
2 files changed, 81 insertions(+)
diff --git a/examples/bracket/bracket.py b/examples/bracket/bracket.py
index 381e63ce8..5213a6875 100644
--- a/examples/bracket/bracket.py
+++ b/examples/bracket/bracket.py
@@ -11,6 +11,65 @@
import ppsci
+def export(cfg: DictConfig):
+ # set model
+ disp_net = ppsci.arch.MLP(**cfg.MODEL.disp_net)
+ stress_net = ppsci.arch.MLP(**cfg.MODEL.stress_net)
+ # wrap to a model_list
+ model = ppsci.arch.ModelList((disp_net, stress_net))
+
+ # initialize solver
+ solver = ppsci.solver.Solver(
+ model,
+ pretrained_model_path=cfg.INFER.pretrained_model_path,
+ )
+
+ # export model
+ from paddle.static import InputSpec
+
+ input_spec = [
+ {key: InputSpec([None, 1], "float32", name=key) for key in model.input_keys},
+ ]
+ solver.export(input_spec, cfg.INFER.export_path)
+
+
+def inference(cfg: DictConfig):
+ from deploy.python_infer import pinn_predictor
+
+ predictor = pinn_predictor.PINNPredictor(cfg)
+ ref_xyzu = ppsci.utils.reader.load_csv_file(
+ cfg.DEFORMATION_X_PATH,
+ ("x", "y", "z", "u"),
+ {
+ "x": "X Location (m)",
+ "y": "Y Location (m)",
+ "z": "Z Location (m)",
+ "u": "Directional Deformation (m)",
+ },
+ "\t",
+ )
+ input_dict = {
+ "x": ref_xyzu["x"],
+ "y": ref_xyzu["y"],
+ "z": ref_xyzu["z"],
+ }
+ output_dict = predictor.predict(input_dict, cfg.INFER.batch_size)
+
+ # mapping data to cfg.INFER.output_keys
+ output_keys = cfg.MODEL.disp_net.output_keys + cfg.MODEL.stress_net.output_keys
+ output_dict = {
+ store_key: output_dict[infer_key]
+ for store_key, infer_key in zip(output_keys, output_dict.keys())
+ }
+
+ ppsci.visualize.save_vtu_from_dict(
+ "./bracket_pred",
+ {**input_dict, **output_dict},
+ input_dict.keys(),
+ output_keys,
+ )
+
+
def train(cfg: DictConfig):
# set model
disp_net = ppsci.arch.MLP(**cfg.MODEL.disp_net)
@@ -520,6 +579,10 @@ def main(cfg: DictConfig):
train(cfg)
elif cfg.mode == "eval":
evaluate(cfg)
+ elif cfg.mode == "export":
+ export(cfg)
+ elif cfg.mode == "infer":
+ inference(cfg)
else:
raise ValueError(f"cfg.mode should in ['train', 'eval'], but got '{cfg.mode}'")
diff --git a/examples/bracket/conf/bracket.yaml b/examples/bracket/conf/bracket.yaml
index fd6cef0fa..67c253ef4 100644
--- a/examples/bracket/conf/bracket.yaml
+++ b/examples/bracket/conf/bracket.yaml
@@ -102,3 +102,21 @@ EVAL:
eval_with_no_grad: true
batch_size:
sup_validator: 128
+
+# inference settings
+INFER:
+ pretrained_model_path: "https://paddle-org.bj.bcebos.com/paddlescience/models/bracket/bracket_pretrained.pdparams"
+ export_path: ./inference/bracket
+ pdmodel_path: ${INFER.export_path}.pdmodel
+ pdpiparams_path: ${INFER.export_path}.pdiparams
+ device: gpu
+ engine: native
+ precision: fp32
+ onnx_path: ${INFER.export_path}.onnx
+ ir_optim: true
+ min_subgraph_size: 10
+ gpu_mem: 4000
+ gpu_id: 0
+ max_batch_size: 64
+ num_cpu_threads: 4
+ batch_size: 16
From 18d247f6de9f500d2f217c9e42abd9b4a74bb77a Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Mon, 6 May 2024 16:23:59 +0800
Subject: [PATCH 10/15] updata bracket doc
---
docs/zh/examples/bracket.md | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/docs/zh/examples/bracket.md b/docs/zh/examples/bracket.md
index 14c6bba14..4db059f73 100644
--- a/docs/zh/examples/bracket.md
+++ b/docs/zh/examples/bracket.md
@@ -26,6 +26,24 @@
python bracket.py mode=eval EVAL.pretrained_model_path=https://paddle-org.bj.bcebos.com/paddlescience/models/bracket/bracket_pretrained.pdparams
```
+=== "模型导出命令"
+
+ ``` sh
+ python bracket.py mode=export
+ ```
+
+=== "模型推理命令"
+
+ ``` sh
+ # linux
+ wget -nc https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar
+ # windows
+ # curl https://paddle-org.bj.bcebos.com/paddlescience/datasets/bracket/bracket_dataset.tar --output bracket_dataset.tar
+ # unzip it
+ tar -xvf bracket_dataset.tar
+ python bracket.py mode=infer
+ ```
+
| 预训练模型 | 指标 |
|:--| :--|
| [bracket_pretrained.pdparams](https://paddle-org.bj.bcebos.com/paddlescience/models/bracket/bracket_pretrained.pdparams) | loss(commercial_ref_u_v_w_sigmas): 32.28704
MSE.u(commercial_ref_u_v_w_sigmas): 0.00005
MSE.v(commercial_ref_u_v_w_sigmas): 0.00000
MSE.w(commercial_ref_u_v_w_sigmas): 0.00734
MSE.sigma_xx(commercial_ref_u_v_w_sigmas): 27.64751
MSE.sigma_yy(commercial_ref_u_v_w_sigmas): 1.23101
MSE.sigma_zz(commercial_ref_u_v_w_sigmas): 0.89106
MSE.sigma_xy(commercial_ref_u_v_w_sigmas): 0.84370
MSE.sigma_xz(commercial_ref_u_v_w_sigmas): 1.42126
MSE.sigma_yz(commercial_ref_u_v_w_sigmas): 0.24510 |
From c85c063775f816c5899489b9059eae37d33da32e Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Tue, 7 May 2024 20:27:29 +0800
Subject: [PATCH 11/15] solve conflict according to the branch named develop
---
ppsci/autodiff/ad.py | 29 ++++++++++-------------------
1 file changed, 10 insertions(+), 19 deletions(-)
diff --git a/ppsci/autodiff/ad.py b/ppsci/autodiff/ad.py
index e7ba3bc38..1214e8331 100644
--- a/ppsci/autodiff/ad.py
+++ b/ppsci/autodiff/ad.py
@@ -303,25 +303,16 @@ def _clear(self):
def clear():
"""Clear cached Jacobians and Hessians.
- <<<<<<< HEAD
- Args:
- None.
-
- Returns:
- None.
-
- =======
- >>>>>>> e87bf34a931911d9d1c799308a1c8c5f7d53fe17
- Examples:
- >>> import paddle
- >>> import ppsci
- >>> x = paddle.randn([4, 3])
- >>> x.stop_gradient = False
- >>> y = (x * x).sin()
- >>> dy_dxx = ppsci.autodiff.hessian(y, x, component=0)
- >>> ppsci.autodiff.clear()
- >>> print(ppsci.autodiff.hessian.Hs)
- {}
+ Examples:
+ >>> import paddle
+ >>> import ppsci
+ >>> x = paddle.randn([4, 3])
+ >>> x.stop_gradient = False
+ >>> y = (x * x).sin()
+ >>> dy_dxx = ppsci.autodiff.hessian(y, x, component=0)
+ >>> ppsci.autodiff.clear()
+ >>> print(ppsci.autodiff.hessian.Hs)
+ {}
"""
jacobian._clear()
hessian._clear()
From a6d6fcfbbcb297b2d3825302247878d2452fe191 Mon Sep 17 00:00:00 2001
From: HydrogenSulfate <490868991@qq.com>
Date: Tue, 7 May 2024 21:18:41 +0800
Subject: [PATCH 12/15] Update examples/bracket/conf/bracket.yaml
---
examples/bracket/conf/bracket.yaml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/examples/bracket/conf/bracket.yaml b/examples/bracket/conf/bracket.yaml
index 42bac6ea1..6103dbdbd 100644
--- a/examples/bracket/conf/bracket.yaml
+++ b/examples/bracket/conf/bracket.yaml
@@ -108,7 +108,7 @@ INFER:
pretrained_model_path: "https://paddle-org.bj.bcebos.com/paddlescience/models/bracket/bracket_pretrained.pdparams"
export_path: ./inference/bracket
pdmodel_path: ${INFER.export_path}.pdmodel
- pdpiparams_path: ${INFER.export_path}.pdiparams
+ pdiparams_path: ${INFER.export_path}.pdiparams
device: gpu
engine: native
precision: fp32
From ebf95fc94b61b5f24afa92bffcd8a3bfb3b89d2a Mon Sep 17 00:00:00 2001
From: HydrogenSulfate <490868991@qq.com>
Date: Tue, 7 May 2024 21:18:58 +0800
Subject: [PATCH 13/15] Update examples/bracket/conf/bracket.yaml
---
examples/bracket/conf/bracket.yaml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/examples/bracket/conf/bracket.yaml b/examples/bracket/conf/bracket.yaml
index 6103dbdbd..fbe918d1e 100644
--- a/examples/bracket/conf/bracket.yaml
+++ b/examples/bracket/conf/bracket.yaml
@@ -117,6 +117,6 @@ INFER:
min_subgraph_size: 10
gpu_mem: 4000
gpu_id: 0
- max_batch_size: 64
+ max_batch_size: 128
num_cpu_threads: 4
batch_size: 16
From 0840aa3467555b4bef482bb105dab2d19b42eefd Mon Sep 17 00:00:00 2001
From: HydrogenSulfate <490868991@qq.com>
Date: Tue, 7 May 2024 21:19:18 +0800
Subject: [PATCH 14/15] Update examples/bracket/conf/bracket.yaml
---
examples/bracket/conf/bracket.yaml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/examples/bracket/conf/bracket.yaml b/examples/bracket/conf/bracket.yaml
index fbe918d1e..5e4682b4f 100644
--- a/examples/bracket/conf/bracket.yaml
+++ b/examples/bracket/conf/bracket.yaml
@@ -119,4 +119,4 @@ INFER:
gpu_id: 0
max_batch_size: 128
num_cpu_threads: 4
- batch_size: 16
+ batch_size: 128
From e91fdd9fc0793e27398879d32d2dfd1e526ba95a Mon Sep 17 00:00:00 2001
From: krp <2934631798@qq.com>
Date: Tue, 7 May 2024 22:51:35 +0800
Subject: [PATCH 15/15] add export&inference for bracket
---
examples/bracket/bracket.py | 118 ++++++++++++++++++------------------
1 file changed, 59 insertions(+), 59 deletions(-)
diff --git a/examples/bracket/bracket.py b/examples/bracket/bracket.py
index 5213a6875..5d85b535a 100644
--- a/examples/bracket/bracket.py
+++ b/examples/bracket/bracket.py
@@ -11,65 +11,6 @@
import ppsci
-def export(cfg: DictConfig):
- # set model
- disp_net = ppsci.arch.MLP(**cfg.MODEL.disp_net)
- stress_net = ppsci.arch.MLP(**cfg.MODEL.stress_net)
- # wrap to a model_list
- model = ppsci.arch.ModelList((disp_net, stress_net))
-
- # initialize solver
- solver = ppsci.solver.Solver(
- model,
- pretrained_model_path=cfg.INFER.pretrained_model_path,
- )
-
- # export model
- from paddle.static import InputSpec
-
- input_spec = [
- {key: InputSpec([None, 1], "float32", name=key) for key in model.input_keys},
- ]
- solver.export(input_spec, cfg.INFER.export_path)
-
-
-def inference(cfg: DictConfig):
- from deploy.python_infer import pinn_predictor
-
- predictor = pinn_predictor.PINNPredictor(cfg)
- ref_xyzu = ppsci.utils.reader.load_csv_file(
- cfg.DEFORMATION_X_PATH,
- ("x", "y", "z", "u"),
- {
- "x": "X Location (m)",
- "y": "Y Location (m)",
- "z": "Z Location (m)",
- "u": "Directional Deformation (m)",
- },
- "\t",
- )
- input_dict = {
- "x": ref_xyzu["x"],
- "y": ref_xyzu["y"],
- "z": ref_xyzu["z"],
- }
- output_dict = predictor.predict(input_dict, cfg.INFER.batch_size)
-
- # mapping data to cfg.INFER.output_keys
- output_keys = cfg.MODEL.disp_net.output_keys + cfg.MODEL.stress_net.output_keys
- output_dict = {
- store_key: output_dict[infer_key]
- for store_key, infer_key in zip(output_keys, output_dict.keys())
- }
-
- ppsci.visualize.save_vtu_from_dict(
- "./bracket_pred",
- {**input_dict, **output_dict},
- input_dict.keys(),
- output_keys,
- )
-
-
def train(cfg: DictConfig):
# set model
disp_net = ppsci.arch.MLP(**cfg.MODEL.disp_net)
@@ -573,6 +514,65 @@ def evaluate(cfg: DictConfig):
solver.visualize()
+def export(cfg: DictConfig):
+ # set model
+ disp_net = ppsci.arch.MLP(**cfg.MODEL.disp_net)
+ stress_net = ppsci.arch.MLP(**cfg.MODEL.stress_net)
+ # wrap to a model_list
+ model = ppsci.arch.ModelList((disp_net, stress_net))
+
+ # initialize solver
+ solver = ppsci.solver.Solver(
+ model,
+ pretrained_model_path=cfg.INFER.pretrained_model_path,
+ )
+
+ # export model
+ from paddle.static import InputSpec
+
+ input_spec = [
+ {key: InputSpec([None, 1], "float32", name=key) for key in model.input_keys},
+ ]
+ solver.export(input_spec, cfg.INFER.export_path)
+
+
+def inference(cfg: DictConfig):
+ from deploy.python_infer import pinn_predictor
+
+ predictor = pinn_predictor.PINNPredictor(cfg)
+ ref_xyzu = ppsci.utils.reader.load_csv_file(
+ cfg.DEFORMATION_X_PATH,
+ ("x", "y", "z", "u"),
+ {
+ "x": "X Location (m)",
+ "y": "Y Location (m)",
+ "z": "Z Location (m)",
+ "u": "Directional Deformation (m)",
+ },
+ "\t",
+ )
+ input_dict = {
+ "x": ref_xyzu["x"],
+ "y": ref_xyzu["y"],
+ "z": ref_xyzu["z"],
+ }
+ output_dict = predictor.predict(input_dict, cfg.INFER.batch_size)
+
+ # mapping data to cfg.INFER.output_keys
+ output_keys = cfg.MODEL.disp_net.output_keys + cfg.MODEL.stress_net.output_keys
+ output_dict = {
+ store_key: output_dict[infer_key]
+ for store_key, infer_key in zip(output_keys, output_dict.keys())
+ }
+
+ ppsci.visualize.save_vtu_from_dict(
+ "./bracket_pred",
+ {**input_dict, **output_dict},
+ input_dict.keys(),
+ output_keys,
+ )
+
+
@hydra.main(version_base=None, config_path="./conf", config_name="bracket.yaml")
def main(cfg: DictConfig):
if cfg.mode == "train":