Skip to content

Commit 10518a3

Browse files
Refine formula, docstring and code. (#353)
* refine losses formula and doc of loss * refine docstring according to pydocstyle
1 parent ca39b4b commit 10518a3

33 files changed

+237
-159
lines changed

docs/zh/api/autodiff.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,6 @@
88
- Jacobians
99
- hessian
1010
- Hessians
11+
- clear
1112
show_root_heading: false
1213
heading_level: 3

docs/zh/api/visualize.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
handler: python
55
options:
66
members:
7+
- Visualizer
78
- VisualizerScatter1D
89
- VisualizerScatter3D
910
- VisualizerVtu
@@ -12,6 +13,7 @@
1213
- Visualizer3D
1314
- VisualizerWeather
1415
- save_vtu_from_dict
16+
- save_vtu_to_mesh
1517
- save_plot_from_1d_dict
1618
- save_plot_from_3d_dict
1719
show_root_heading: false

ppsci/arch/afno.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222

2323
import paddle
2424
import paddle.fft
25-
import paddle.nn as nn
2625
import paddle.nn.functional as F
26+
from paddle import nn
2727

2828
from ppsci.arch import activation as act_mod
2929
from ppsci.arch import base
@@ -381,7 +381,7 @@ def __init__(
381381
)
382382

383383
def forward(self, x):
384-
B, C, H, W = x.shape
384+
_, _, H, W = x.shape
385385
if not (H == self.img_size[0] and W == self.img_size[1]):
386386
raise ValueError(
387387
f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
@@ -541,7 +541,7 @@ def forward(self, x):
541541

542542
y = []
543543
input = x
544-
for i in range(self.num_timestamps):
544+
for _ in range(self.num_timestamps):
545545
out = self.forward_tensor(input)
546546
y.append(out)
547547
input = out
@@ -665,7 +665,7 @@ def forward(self, x):
665665

666666
input_wind = x
667667
y = []
668-
for i in range(self.num_timestamps):
668+
for _ in range(self.num_timestamps):
669669
with paddle.no_grad():
670670
out_wind = self.wind_model.forward_tensor(input_wind)
671671
out = self.forward_tensor(out_wind)

ppsci/arch/physx_transformer.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,7 @@ def split_heads(self, x, k=False):
114114
x = x.reshape(new_x_shape)
115115
if k:
116116
return x.transpose([0, 2, 3, 1])
117-
else:
118-
return x.transpose([0, 2, 1, 3])
117+
return x.transpose([0, 2, 1, 3])
119118

120119
def forward(
121120
self,

ppsci/autodiff/ad.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def __call__(
166166
j: int = 0,
167167
grad_y: Optional[paddle.Tensor] = None,
168168
) -> paddle.Tensor:
169-
"""compute hessian matrix for given ys and xs.
169+
"""Compute hessian matrix for given ys and xs.
170170
171171
Args:
172172
ys (paddle.Tensor): Output tensor.

ppsci/constraint/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from typing import Any
1616
from typing import Dict
1717

18-
import paddle.io as io
18+
from paddle import io
1919

2020
from ppsci import data
2121
from ppsci import loss

ppsci/data/dataset/array_dataset.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ def __init__(
9595
weight: Dict[str, np.ndarray],
9696
transforms: Optional[vision.Compose] = None,
9797
):
98+
super().__init__()
9899
self.input = {key: paddle.to_tensor(value) for key, value in input.items()}
99100
self.label = {key: paddle.to_tensor(value) for key, value in label.items()}
100101
self.weight = {key: paddle.to_tensor(value) for key, value in weight.items()}

ppsci/data/dataset/era5_dataset.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,8 @@ def read_data(self, path: str, var="fields"):
9090
paths = [path] if path.endswith(".h5") else glob.glob(path + "/*.h5")
9191
paths.sort()
9292
files = []
93-
for path in paths:
94-
_file = h5py.File(path, "r")
93+
for path_ in paths:
94+
_file = h5py.File(path_, "r")
9595
files.append(_file[var])
9696
return files
9797

ppsci/geometry/geometry.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,8 +157,8 @@ def sample_boundary(self, n, random="pseudo", criteria=None, evenly=False):
157157
):
158158
area_dict = misc.convert_to_dict(area[:, 1:], ["area"])
159159
return {**x_dict, **normal_dict, **area_dict}
160-
else:
161-
return {**x_dict, **normal_dict}
160+
161+
return {**x_dict, **normal_dict}
162162

163163
@abc.abstractmethod
164164
def random_points(self, n: int, random: str = "pseudo"):

ppsci/geometry/geometry_2d.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -455,7 +455,7 @@ def random_points(self, n, random="pseudo"):
455455
x = np.empty((0, 2), dtype=paddle.get_default_dtype())
456456
vbbox = self.bbox[1] - self.bbox[0]
457457
while len(x) < n:
458-
x_new = sampler.sample(n, 2, sampler="pseudo") * vbbox + self.bbox[0]
458+
x_new = sampler.sample(n, 2, "pseudo") * vbbox + self.bbox[0]
459459
x = np.vstack((x, x_new[self.is_inside(x_new)]))
460460
return x[:n]
461461

ppsci/geometry/mesh.py

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ def inflated_random_boundary_points(
222222
all_points.append(normal)
223223
all_points.append(area)
224224

225-
all_point = np.concatenate(all_point, axis=0)
225+
all_points = np.concatenate(all_points, axis=0)
226226
all_normal = np.concatenate(all_normal, axis=0)
227227
all_area = np.concatenate(all_area, axis=0)
228228
return all_points, all_normal, all_area
@@ -270,7 +270,7 @@ def random_boundary_points(self, n, random="pseudo", criteria=None):
270270
npoint_per_triangle, np.arange(len(triangle_prob) + 1) - 0.5
271271
)
272272

273-
all_point = []
273+
all_points = []
274274
all_normal = []
275275
all_area = []
276276
for i, npoint in enumerate(npoint_per_triangle):
@@ -286,17 +286,17 @@ def random_boundary_points(self, n, random="pseudo", criteria=None):
286286
dtype=paddle.get_default_dtype(),
287287
)
288288

289-
all_point.append(face_points)
289+
all_points.append(face_points)
290290
all_normal.append(face_normal)
291291
all_area.append(valid_area)
292292

293-
all_point = np.concatenate(all_point, axis=0)
293+
all_points = np.concatenate(all_points, axis=0)
294294
all_normal = np.concatenate(all_normal, axis=0)
295295
all_area = np.concatenate(all_area, axis=0)
296296

297297
# NOTE: use global mean area instead of local mean area
298298
all_area = np.full_like(all_area, all_area.mean())
299-
return all_point, all_normal, all_area
299+
return all_points, all_normal, all_area
300300

301301
def sample_boundary(
302302
self, n, random="pseudo", criteria=None, evenly=False, inflation_dist=None
@@ -311,11 +311,8 @@ def sample_boundary(
311311
raise ValueError(
312312
"Can't sample evenly on mesh now, please set evenly=False."
313313
)
314-
# points, normal, area = self.uniform_boundary_points(n, False)
315-
else:
316-
points, normals, areas = self.random_boundary_points(
317-
n, random, criteria
318-
)
314+
# points, normal, area = self.uniform_boundary_points(n, False)
315+
points, normals, areas = self.random_boundary_points(n, random, criteria)
319316

320317
x_dict = misc.convert_to_dict(points, self.dim_keys)
321318
normal_dict = misc.convert_to_dict(
@@ -362,9 +359,7 @@ def sample_interior(self, n, random="pseudo", criteria=None, evenly=False):
362359
raise NotImplementedError(
363360
"uniformly sample for interior in mesh is not support yet"
364361
)
365-
# points, area = self.uniform_points(n)
366-
else:
367-
points, areas = self.random_points(n, random, criteria)
362+
points, areas = self.random_points(n, random, criteria)
368363

369364
x_dict = misc.convert_to_dict(points, self.dim_keys)
370365
area_dict = misc.convert_to_dict(areas, ["area"])
@@ -375,45 +370,47 @@ def sample_interior(self, n, random="pseudo", criteria=None, evenly=False):
375370

376371
return {**x_dict, **area_dict, **sdf_dict}
377372

378-
def union(self, rhs: "Mesh"):
373+
def union(self, other: "Mesh"):
379374
if not checker.dynamic_import_to_globals(["pymesh"]):
380375
raise ModuleNotFoundError
381376
import pymesh
382377

383-
csg = pymesh.CSGTree({"union": [{"mesh": self.py_mesh}, {"mesh": rhs.py_mesh}]})
378+
csg = pymesh.CSGTree(
379+
{"union": [{"mesh": self.py_mesh}, {"mesh": other.py_mesh}]}
380+
)
384381
return Mesh(csg.mesh)
385382

386-
def __or__(self, rhs: "Mesh"):
387-
return self.union(rhs)
383+
def __or__(self, other: "Mesh"):
384+
return self.union(other)
388385

389-
def __add__(self, rhs: "Mesh"):
390-
return self.union(rhs)
386+
def __add__(self, other: "Mesh"):
387+
return self.union(other)
391388

392-
def difference(self, rhs: "Mesh"):
389+
def difference(self, other: "Mesh"):
393390
if not checker.dynamic_import_to_globals(["pymesh"]):
394391
raise ModuleNotFoundError
395392
import pymesh
396393

397394
csg = pymesh.CSGTree(
398-
{"difference": [{"mesh": self.py_mesh}, {"mesh": rhs.py_mesh}]}
395+
{"difference": [{"mesh": self.py_mesh}, {"mesh": other.py_mesh}]}
399396
)
400397
return Mesh(csg.mesh)
401398

402-
def __sub__(self, rhs: "Mesh"):
403-
return self.difference(rhs)
399+
def __sub__(self, other: "Mesh"):
400+
return self.difference(other)
404401

405-
def intersection(self, rhs: "Mesh"):
402+
def intersection(self, other: "Mesh"):
406403
if not checker.dynamic_import_to_globals(["pymesh"]):
407404
raise ModuleNotFoundError
408405
import pymesh
409406

410407
csg = pymesh.CSGTree(
411-
{"intersection": [{"mesh": self.py_mesh}, {"mesh": rhs.py_mesh}]}
408+
{"intersection": [{"mesh": self.py_mesh}, {"mesh": other.py_mesh}]}
412409
)
413410
return Mesh(csg.mesh)
414411

415-
def __and__(self, rhs: "Mesh"):
416-
return self.intersection(rhs)
412+
def __and__(self, other: "Mesh"):
413+
return self.intersection(other)
417414

418415
def __str__(self) -> str:
419416
"""Return the name of class"""
@@ -429,7 +426,7 @@ def __str__(self) -> str:
429426

430427

431428
def area_of_triangles(v0, v1, v2):
432-
"""ref https://math.stackexchange.com/questions/128991/how-to-calculate-the-area-of-a-3d-triangle
429+
"""Ref https://math.stackexchange.com/questions/128991/how-to-calculate-the-area-of-a-3d-triangle
433430
434431
Args:
435432
v0 (np.ndarray): Coordinates of the first vertex of the triangle surface with shape of [N, 3].

ppsci/geometry/pointcloud.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818

1919
import numpy as np
2020

21-
import ppsci.utils.misc as misc
2221
from ppsci.geometry import geometry
22+
from ppsci.utils import misc
2323

2424

2525
class PointCloud(geometry.Geometry):
@@ -148,32 +148,32 @@ def uniform_points(self, n: int, boundary=True):
148148
"""Compute the equispaced points in the geometry."""
149149
return self.interior[:n]
150150

151-
def union(self, rhs):
151+
def union(self, other):
152152
raise NotImplementedError(
153153
"Union operation for PointCloud is not supported yet."
154154
)
155155

156-
def __or__(self, rhs):
156+
def __or__(self, other):
157157
raise NotImplementedError(
158158
"Union operation for PointCloud is not supported yet."
159159
)
160160

161-
def difference(self, rhs):
161+
def difference(self, other):
162162
raise NotImplementedError(
163163
"Subtraction operation for PointCloud is not supported yet."
164164
)
165165

166-
def __sub__(self, rhs):
166+
def __sub__(self, other):
167167
raise NotImplementedError(
168168
"Subtraction operation for PointCloud is not supported yet."
169169
)
170170

171-
def intersection(self, rhs):
171+
def intersection(self, other):
172172
raise NotImplementedError(
173173
"Intersection operation for PointCloud is not supported yet."
174174
)
175175

176-
def __and__(self, rhs):
176+
def __and__(self, other):
177177
raise NotImplementedError(
178178
"Intersection operation for PointCloud is not supported yet."
179179
)

ppsci/loss/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from typing import Optional
1717
from typing import Union
1818

19-
import paddle.nn as nn
19+
from paddle import nn
2020
from typing_extensions import Literal
2121

2222

ppsci/loss/integral.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,14 @@ class IntegralLoss(base.Loss):
2828
$$
2929
L =
3030
\begin{cases}
31-
\dfrac{1}{N}\sum\limits_{i=1}^{N}{(\sum\limits_{j=1}^{M}{(x_i^j s_{j})}-y_i)^2}, & \text{if reduction='mean'} \\
32-
\sum\limits_{i=1}^{N}{(\sum\limits_{j=1}^{M}{(x_i^j s_{j})}-y_i)^2}, & \text{if reduction='sum'}
31+
\dfrac{1}{N} \Vert \mathbf{s} \circ \mathbf{x} - \mathbf{y} \Vert_2^2, & \text{if reduction='mean'} \\
32+
\Vert \mathbf{s} \circ \mathbf{x} - \mathbf{y} \Vert_2^2, & \text{if reduction='sum'}
3333
\end{cases}
3434
$$
3535
36-
$M$ is the number of samples in Monte-Carlo integration.
36+
$$
37+
\mathbf{x}, \mathbf{y}, \mathbf{s} \in \mathcal{R}^{N}
38+
$$
3739
3840
Args:
3941
reduction (Literal["mean", "sum"], optional): Reduction method. Defaults to "mean".

0 commit comments

Comments
 (0)