跳转至

Geometry(几何) 模块

ppsci.geometry

Geometry

Base class for geometry.

Parameters:

Name Type Description Default
ndim int

Number of geometry dimension.

required
bbox Tuple[ndarray, ndarray]

Bounding box of upper and lower.

required
diam float

Diameter of geometry.

required
Source code in ppsci/geometry/geometry.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
class Geometry:
    """Base class for geometry.

    Args:
        ndim (int): Number of geometry dimension.
        bbox (Tuple[np.ndarray, np.ndarray]): Bounding box of upper and lower.
        diam (float): Diameter of geometry.
    """

    def __init__(self, ndim: int, bbox: Tuple[np.ndarray, np.ndarray], diam: float):
        self.ndim = ndim
        self.bbox = bbox
        self.diam = min(diam, np.linalg.norm(bbox[1] - bbox[0]))

    @property
    def dim_keys(self):
        return ("x", "y", "z")[: self.ndim]

    @abc.abstractmethod
    def is_inside(self, x: np.ndarray) -> np.ndarray:
        """Returns a boolean array where x is inside the geometry.

        Args:
            x (np.ndarray): Points to check if inside the geometry. The shape is [N, D],
                where D is the number of dimension of geometry.

        Returns:
            np.ndarray: Boolean array where x is inside the geometry. The shape is [N].

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> interval = ppsci.geometry.Interval(0, 1)
            >>> x = np.array([[0], [0.5], [1.5]])
            >>> interval.is_inside(x)
            array([ True,  True, False])
            >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> x = np.array([[0.0, 0.0], [0.5, 0.5], [1.5, 1.5]])
            >>> rectangle.is_inside(x)
            array([ True,  True, False])
            >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
            >>> x = np.array([[0, 0, 0], [0.5, 0.5, 0.5], [1.5, 1.5, 1.5]])
            >>> cuboid.is_inside(x)
            array([ True,  True, False])
        """

    @abc.abstractmethod
    def on_boundary(self, x: np.ndarray) -> np.ndarray:
        """Returns a boolean array where x is on geometry boundary.

        Args:
            x (np.ndarray): Points to check if on the geometry boundary. The shape is [N, D],
                where D is the number of dimension of geometry.

        Returns:
            np.ndarray: Boolean array where x is on the geometry boundary. The shape is [N].

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> interval = ppsci.geometry.Interval(0, 1)
            >>> x = np.array([[0], [0.5], [1.5]])
            >>> interval.on_boundary(x)
            array([ True, False, False])
            >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> x = np.array([[0, 0], [0.5, 0.5], [1, 1.5]])
            >>> rectangle.on_boundary(x)
            array([ True, False, False])
            >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
            >>> x = np.array([[0, 0, 0], [0.5, 0.5, 0.5], [1, 1, 1.5]])
            >>> cuboid.on_boundary(x)
            array([ True, False, False])
        """

    def boundary_normal(self, x):
        """Compute the unit normal at x."""
        raise NotImplementedError(f"{self}.boundary_normal is not implemented")

    def uniform_points(self, n: int, boundary: bool = True) -> np.ndarray:
        """Compute the equi-spaced points in the geometry.

        Args:
            n (int): Number of points.
            boundary (bool): Include boundary points. Defaults to True.

        Returns:
            np.ndarray: Random points in the geometry. The shape is [N, D].
        """
        logger.warning(
            f"{self}.uniform_points not implemented. " f"Use random_points instead."
        )
        return self.random_points(n)

    def sample_interior(
        self,
        n: int,
        random: Literal["pseudo", "Halton", "LHS"] = "pseudo",
        criteria: Optional[Callable[..., np.ndarray]] = None,
        evenly: bool = False,
        compute_sdf_derivatives: bool = False,
    ) -> Dict[str, np.ndarray]:
        """Sample random points in the geometry and return those meet criteria.

        NOTE: sdf values returned by this function are negated because the weight in
        loss function should be positive.

        Args:
            n (int): Number of points.
            random (Literal["pseudo", "Halton", "LHS"]): Random method. Defaults to "pseudo". Options:
                - "pseudo": Pseudo random.
                - "Halton": Halton sequence.
                - "LHS": Latin Hypercube Sampling.
            criteria (Optional[Callable[..., np.ndarray]]): Criteria function. Given
                coords from different dimension and return a boolean array with shape [n,].
                Defaults to None.
            evenly (bool): Evenly sample points. Defaults to False.
            compute_sdf_derivatives (bool): Compute SDF derivatives. Defaults to False.

        Returns:
            Dict[str, np.ndarray]: Random points in the geometry. The shape is [N, D].
                                   their signed distance function. The shape is [N, 1].
                                   their derivatives of SDF(optional). The shape is [N, D].

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> np.random.seed(42)
            >>> interval = ppsci.geometry.Interval(0, 1)
            >>> interval.sample_interior(2)
            {'x': array([[0.37454012],
                   [0.9507143 ]], dtype=float32), 'sdf': array([[0.37454012],
                   [0.04928571]], dtype=float32)}
            >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> rectangle.sample_interior(2, "pseudo", None, False, True)
            {'x': array([[0.7319939 ],
                   [0.15601864]], dtype=float32), 'y': array([[0.5986585 ],
                   [0.15599452]], dtype=float32), 'sdf': array([[0.2680061 ],
                   [0.15599453]], dtype=float32), 'sdf__x': array([[-1.0001659 ],
                   [ 0.25868416]], dtype=float32), 'sdf__y': array([[-0.        ],
                   [ 0.74118376]], dtype=float32)}
            >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
            >>> cuboid.sample_interior(2, "pseudo", None, True, True)
            {'x': array([[0.],
                   [0.]], dtype=float32), 'y': array([[0.],
                   [0.]], dtype=float32), 'z': array([[0.],
                   [1.]], dtype=float32), 'sdf': array([[0.],
                   [0.]], dtype=float32), 'sdf__x': array([[0.50008297],
                   [0.50008297]], dtype=float32), 'sdf__y': array([[0.50008297],
                   [0.50008297]], dtype=float32), 'sdf__z': array([[ 0.50008297],
                   [-0.49948692]], dtype=float32)}
        """
        x = np.empty(shape=(n, self.ndim), dtype=paddle.get_default_dtype())
        _size, _ntry, _nsuc = 0, 0, 0
        while _size < n:
            if evenly:
                points = self.uniform_points(n)
            else:
                if misc.typename(self) == "TimeXGeometry":
                    points = self.random_points(n, random, criteria)
                else:
                    points = self.random_points(n, random)

            if criteria is not None:
                criteria_mask = criteria(*np.split(points, self.ndim, axis=1)).flatten()
                points = points[criteria_mask]

            if len(points) > n - _size:
                points = points[: n - _size]
            x[_size : _size + len(points)] = points

            _size += len(points)
            _ntry += 1
            if len(points) > 0:
                _nsuc += 1

            if _ntry >= 1000 and _nsuc == 0:
                raise ValueError(
                    "Sample interior points failed, "
                    "please check correctness of geometry and given criteria."
                )

        # if sdf_func added, return x_dict and sdf_dict, else, only return the x_dict
        if hasattr(self, "sdf_func"):
            # NOTE: add negative to the sdf values because weight should be positive.
            sdf = -self.sdf_func(x)
            sdf_dict = misc.convert_to_dict(sdf, ("sdf",))
            sdf_derives_dict = {}
            if compute_sdf_derivatives:
                sdf_derives = -self.sdf_derivatives(x)
                sdf_derives_dict = misc.convert_to_dict(
                    sdf_derives, tuple(f"sdf__{key}" for key in self.dim_keys)
                )
        else:
            sdf_dict = {}
            sdf_derives_dict = {}
        x_dict = misc.convert_to_dict(x, self.dim_keys)

        return {**x_dict, **sdf_dict, **sdf_derives_dict}

    def sample_boundary(
        self,
        n: int,
        random: Literal["pseudo", "Halton", "LHS"] = "pseudo",
        criteria: Optional[Callable[..., np.ndarray]] = None,
        evenly: bool = False,
    ) -> Dict[str, np.ndarray]:
        """Compute the random points in the geometry and return those meet criteria.

        Args:
            n (int): Number of points.
            random (Literal["pseudo", "Halton", "LHS"]): Random method. Defaults to "pseudo". Options:
                - "pseudo": Pseudo random.
                - "Halton": Halton sequence.
                - "LHS": Latin Hypercube Sampling.
            criteria (Optional[Callable[..., np.ndarray]]): Criteria function. Given
                coords from different dimension and return a boolean array with shape [n,].
                Defaults to None.
            evenly (bool): Evenly sample points. Defaults to False.

        Returns:
            Dict[str, np.ndarray]: Random points in the geometry. The shape is [N, D].
                                   their normal vectors. The shape is [N, D].
                                   their area. The shape is [N, 1].(only if the geometry is a mesh)

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> np.random.seed(42)
            >>> interval = ppsci.geometry.Interval(0, 1)
            >>> interval.sample_boundary(2)
            {'x': array([[0.],
                   [1.]], dtype=float32), 'normal_x': array([[-1.],
                   [ 1.]], dtype=float32)}
            >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> rectangle.sample_boundary(2)
            {'x': array([[1.],
                   [0.]], dtype=float32), 'y': array([[0.49816048],
                   [0.19714284]], dtype=float32), 'normal_x': array([[ 1.],
                   [-1.]], dtype=float32), 'normal_y': array([[0.],
                   [0.]], dtype=float32)}
            >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
            >>> cuboid.sample_boundary(2)
            {'x': array([[0.83244264],
                   [0.18182497]], dtype=float32), 'y': array([[0.21233912],
                   [0.1834045 ]], dtype=float32), 'z': array([[0.],
                   [1.]], dtype=float32), 'normal_x': array([[0.],
                   [0.]], dtype=float32), 'normal_y': array([[0.],
                   [0.]], dtype=float32), 'normal_z': array([[-1.],
                   [ 1.]], dtype=float32)}
        """
        x = np.empty(shape=(n, self.ndim), dtype=paddle.get_default_dtype())
        _size, _ntry, _nsuc = 0, 0, 0
        while _size < n:
            if evenly:
                if (
                    misc.typename(self) == "TimeXGeometry"
                    and misc.typename(self.geometry) == "Mesh"
                ):
                    points, normal, area = self.uniform_boundary_points(n)
                else:
                    points = self.uniform_boundary_points(n)
            else:
                if (
                    misc.typename(self) == "TimeXGeometry"
                    and misc.typename(self.geometry) == "Mesh"
                ):
                    points, normal, area = self.random_boundary_points(n, random)
                else:
                    if misc.typename(self) == "TimeXGeometry":
                        points = self.random_boundary_points(n, random, criteria)
                    else:
                        points = self.random_boundary_points(n, random)

            if criteria is not None:
                criteria_mask = criteria(*np.split(points, self.ndim, axis=1)).flatten()
                points = points[criteria_mask]

            if len(points) > n - _size:
                points = points[: n - _size]
            x[_size : _size + len(points)] = points

            _size += len(points)
            _ntry += 1
            if len(points) > 0:
                _nsuc += 1

            if _ntry >= 10000 and _nsuc == 0:
                raise ValueError(
                    "Sample boundary points failed, "
                    "please check correctness of geometry and given criteria."
                )

        if not (
            misc.typename(self) == "TimeXGeometry"
            and misc.typename(self.geometry) == "Mesh"
        ):
            normal = self.boundary_normal(x)

        normal_dict = misc.convert_to_dict(
            normal[:, 1:] if "t" in self.dim_keys else normal,
            [f"normal_{key}" for key in self.dim_keys if key != "t"],
        )
        x_dict = misc.convert_to_dict(x, self.dim_keys)
        if (
            misc.typename(self) == "TimeXGeometry"
            and misc.typename(self.geometry) == "Mesh"
        ):
            area_dict = misc.convert_to_dict(area[:, 1:], ["area"])
            return {**x_dict, **normal_dict, **area_dict}

        return {**x_dict, **normal_dict}

    @abc.abstractmethod
    def random_points(
        self, n: int, random: Literal["pseudo", "Halton", "LHS"] = "pseudo"
    ) -> np.ndarray:
        """Compute the random points in the geometry.

        Args:
            n (int): Number of points.
            random (Literal["pseudo", "Halton", "LHS"]): Random method. Defaults to "pseudo". Options:
                - "pseudo": Pseudo random.
                - "Halton": Halton sequence.
                - "LHS": Latin Hypercube Sampling.

        Returns:
            np.ndarray: Random points in the geometry. The shape is [N, D].

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> np.random.seed(42)
            >>> interval = ppsci.geometry.Interval(0, 1)
            >>> interval.random_points(2)
            array([[0.37454012],
                   [0.9507143 ]], dtype=float32)
            >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> rectangle.random_points(2)
            array([[0.7319939 , 0.5986585 ],
                   [0.15601864, 0.15599452]], dtype=float32)
            >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
            >>> cuboid.random_points(2)
            array([[0.05808361, 0.8661761 , 0.601115  ],
                   [0.7080726 , 0.02058449, 0.96990985]], dtype=float32)
        """

    def uniform_boundary_points(self, n: int) -> np.ndarray:
        """Compute the equi-spaced points on the boundary(not implemented).

        Args:
            n (int): Number of points.

        Returns:
            np.ndarray: Random points on the boundary. The shape is [N, D].
        """
        logger.warning(
            f"{self}.uniform_boundary_points not implemented. "
            f"Use random_boundary_points instead."
        )
        return self.random_boundary_points(n)

    @abc.abstractmethod
    def random_boundary_points(
        self, n: int, random: Literal["pseudo", "Halton", "LHS"] = "pseudo"
    ) -> np.ndarray:
        """Compute the random points on the boundary.

        Args:
            n (int): Number of points.
            random (Literal["pseudo", "Halton", "LHS"]): Random method. Defaults to "pseudo". Options:
                - "pseudo": Pseudo random.
                - "Halton": Halton sequence.
                - "LHS": Latin Hypercube Sampling.

        Returns:
            np.ndarray: Random points on the boundary. The shape is [N, D].

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> np.random.seed(42)
            >>> interval = ppsci.geometry.Interval(0, 1)
            >>> interval.random_boundary_points(2)
            array([[0.],
                   [1.]], dtype=float32)
            >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> rectangle.random_boundary_points(2)
            array([[1.        , 0.49816048],
                   [0.        , 0.19714284]], dtype=float32)
            >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
            >>> cuboid.random_boundary_points(2)
            array([[0.83244264, 0.21233912, 0.        ],
                   [0.18182497, 0.1834045 , 1.        ]], dtype=float32)
        """

    def periodic_point(self, x: np.ndarray, component: int):
        """Compute the periodic image of x(not implemented)."""
        raise NotImplementedError(f"{self}.periodic_point to be implemented")

    def sdf_derivatives(self, x: np.ndarray, epsilon: float = 1e-4) -> np.ndarray:
        """Compute derivatives of SDF function.

        Args:
            x (np.ndarray): Points for computing SDF derivatives using central
                difference. The shape is [N, D], D is the number of dimension of
                geometry.
            epsilon (float): Derivative step. Defaults to 1e-4.

        Returns:
            np.ndarray: Derivatives of corresponding SDF function.
                The shape is [N, D]. D is the number of dimension of geometry.

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> interval = ppsci.geometry.Interval(0, 1)
            >>> x = np.array([[0], [0.5], [1.5]])
            >>> interval.sdf_derivatives(x)
            array([[-1.],
                   [ 0.],
                   [ 1.]])
            >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> x = np.array([[0.0, 0.0], [0.5, 0.5], [1.5, 1.5]])
            >>> rectangle.sdf_derivatives(x)
            array([[-0.5       , -0.5       ],
                   [ 0.        ,  0.        ],
                   [ 0.70710678,  0.70710678]])
            >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
            >>> x = np.array([[0, 0, 0], [0.5, 0.5, 0.5], [1, 1, 1]])
            >>> cuboid.sdf_derivatives(x)
            array([[-0.5, -0.5, -0.5],
                   [ 0. ,  0. ,  0. ],
                   [ 0.5,  0.5,  0.5]])
        """
        if not hasattr(self, "sdf_func"):
            raise NotImplementedError(
                f"{misc.typename(self)}.sdf_func should be implemented "
                "when using 'sdf_derivatives'."
            )
        # Only compute sdf derivatives for those already implement `sdf_func` method.
        sdf_derives = np.empty_like(x)
        for i in range(self.ndim):
            h = np.zeros_like(x)
            h[:, i] += epsilon / 2
            derives_at_i = (self.sdf_func(x + h) - self.sdf_func(x - h)) / epsilon
            sdf_derives[:, i : i + 1] = derives_at_i
        return sdf_derives

    def union(self, other: "Geometry") -> "Geometry":
        """CSG Union.

        Args:
            other (Geometry): The other geometry.

        Returns:
            Geometry: The union of two geometries.

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> interval1 = ppsci.geometry.Interval(0, 1)
            >>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
            >>> union = interval1.union(interval2)
            >>> union.bbox
            (array([[0.]]), array([[1.5]]))
            >>> rectangle1 = ppsci.geometry.Rectangle((0, 0), (2, 3))
            >>> rectangle2 = ppsci.geometry.Rectangle((0, 0), (3, 2))
            >>> union = rectangle1.union(rectangle2)
            >>> union.bbox
            (array([0., 0.], dtype=float32), array([3., 3.], dtype=float32))
            >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
            >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
            >>> union = cuboid1 | cuboid2
            >>> union.bbox
            (array([0., 0., 0.], dtype=float32), array([2., 2., 2.], dtype=float32))
        """
        from ppsci.geometry import csg

        return csg.CSGUnion(self, other)

    def __or__(self, other: "Geometry") -> "Geometry":
        """CSG Union.

        Args:
            other (Geometry): The other geometry.

        Returns:
            Geometry: The union of two geometries.

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> interval1 = ppsci.geometry.Interval(0, 1)
            >>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
            >>> union = interval1.__or__(interval2)
            >>> union.bbox
            (array([[0.]]), array([[1.5]]))
            >>> rectangle1 = ppsci.geometry.Rectangle((0, 0), (2, 3))
            >>> rectangle2 = ppsci.geometry.Rectangle((0, 0), (3, 2))
            >>> union = rectangle1.__or__(rectangle2)
            >>> union.bbox
            (array([0., 0.], dtype=float32), array([3., 3.], dtype=float32))
            >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
            >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
            >>> union = cuboid1 | cuboid2
            >>> union.bbox
            (array([0., 0., 0.], dtype=float32), array([2., 2., 2.], dtype=float32))
        """
        from ppsci.geometry import csg

        return csg.CSGUnion(self, other)

    def difference(self, other: "Geometry") -> "Geometry":
        """CSG Difference.

        Args:
            other (Geometry): The other geometry.

        Returns:
            Geometry: The difference of two geometries.

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> interval1 = ppsci.geometry.Interval(0.0, 2.0)
            >>> interval2 = ppsci.geometry.Interval(1.0, 3.0)
            >>> difference = interval1.difference(interval2)
            >>> difference.bbox
            (array([[0.]]), array([[2.]]))
            >>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
            >>> rectangle2 = ppsci.geometry.Rectangle((1.0, 1.0), (2.0, 2.0))
            >>> difference = rectangle1.difference(rectangle2)
            >>> difference.bbox
            (array([0., 0.], dtype=float32), array([2., 3.], dtype=float32))
            >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
            >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
            >>> difference = cuboid1 - cuboid2
            >>> difference.bbox
            (array([0., 0., 0.], dtype=float32), array([1., 2., 2.], dtype=float32))
        """
        from ppsci.geometry import csg

        return csg.CSGDifference(self, other)

    def __sub__(self, other: "Geometry") -> "Geometry":
        """CSG Difference.

        Args:
            other (Geometry): The other geometry.

        Returns:
            Geometry: The difference of two geometries.

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> interval1 = ppsci.geometry.Interval(0.0, 2.0)
            >>> interval2 = ppsci.geometry.Interval(1.0, 3.0)
            >>> difference = interval1.__sub__(interval2)
            >>> difference.bbox
            (array([[0.]]), array([[2.]]))
            >>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
            >>> rectangle2 = ppsci.geometry.Rectangle((1.0, 1.0), (2.0, 2.0))
            >>> difference = rectangle1.__sub__(rectangle2)
            >>> difference.bbox
            (array([0., 0.], dtype=float32), array([2., 3.], dtype=float32))
            >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
            >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
            >>> difference = cuboid1 - cuboid2
            >>> difference.bbox
            (array([0., 0., 0.], dtype=float32), array([1., 2., 2.], dtype=float32))
        """
        from ppsci.geometry import csg

        return csg.CSGDifference(self, other)

    def intersection(self, other: "Geometry") -> "Geometry":
        """CSG Intersection.

        Args:
            other (Geometry): The other geometry.

        Returns:
            Geometry: The intersection of two geometries.

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> interval1 = ppsci.geometry.Interval(0.0, 1.0)
            >>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
            >>> intersection = interval1.intersection(interval2)
            >>> intersection.bbox
            (array([[0.5]]), array([[1.]]))
            >>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
            >>> rectangle2 = ppsci.geometry.Rectangle((0.0, 0.0), (3.0, 2.0))
            >>> intersection = rectangle1.intersection(rectangle2)
            >>> intersection.bbox
            (array([0., 0.], dtype=float32), array([2., 2.], dtype=float32))
            >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
            >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
            >>> intersection = cuboid1 & cuboid2
            >>> intersection.bbox
            (array([0., 0., 0.], dtype=float32), array([1., 1., 1.], dtype=float32))
        """
        from ppsci.geometry import csg

        return csg.CSGIntersection(self, other)

    def __and__(self, other: "Geometry") -> "Geometry":
        """CSG Intersection.

        Args:
            other (Geometry): The other geometry.

        Returns:
            Geometry: The intersection of two geometries.

        Examples:
            >>> import numpy as np
            >>> import ppsci
            >>> interval1 = ppsci.geometry.Interval(0.0, 1.0)
            >>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
            >>> intersection = interval1.__and__(interval2)
            >>> intersection.bbox
            (array([[0.5]]), array([[1.]]))
            >>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
            >>> rectangle2 = ppsci.geometry.Rectangle((0.0, 0.0), (3.0, 2.0))
            >>> intersection = rectangle1.__and__(rectangle2)
            >>> intersection.bbox
            (array([0., 0.], dtype=float32), array([2., 2.], dtype=float32))
            >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
            >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
            >>> intersection = cuboid1 & cuboid2
            >>> intersection.bbox
            (array([0., 0., 0.], dtype=float32), array([1., 1., 1.], dtype=float32))
        """
        from ppsci.geometry import csg

        return csg.CSGIntersection(self, other)

    def __str__(self) -> str:
        """Return the name of class.

        Returns:
            str: Meta information of geometry.

        Examples:
            >>> import ppsci
            >>> interval = ppsci.geometry.Interval(0, 1)
            >>> interval.__str__()
            "Interval, ndim = 1, bbox = (array([[0]]), array([[1]])), diam = 1, dim_keys = ('x',)"
            >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> rectangle.__str__()
            "Rectangle, ndim = 2, bbox = (array([0., 0.], dtype=float32), array([1., 1.], dtype=float32)), diam = 1.4142135381698608, dim_keys = ('x', 'y')"
            >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
            >>> cuboid.__str__()
            "Cuboid, ndim = 3, bbox = (array([0., 0., 0.], dtype=float32), array([1., 1., 1.], dtype=float32)), diam = 1.7320507764816284, dim_keys = ('x', 'y', 'z')"
        """
        return ", ".join(
            [
                self.__class__.__name__,
                f"ndim = {self.ndim}",
                f"bbox = {self.bbox}",
                f"diam = {self.diam}",
                f"dim_keys = {self.dim_keys}",
            ]
        )
__and__(other)

CSG Intersection.

Parameters:

Name Type Description Default
other Geometry

The other geometry.

required

Returns:

Name Type Description
Geometry 'Geometry'

The intersection of two geometries.

Examples:

>>> import numpy as np
>>> import ppsci
>>> interval1 = ppsci.geometry.Interval(0.0, 1.0)
>>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
>>> intersection = interval1.__and__(interval2)
>>> intersection.bbox
(array([[0.5]]), array([[1.]]))
>>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
>>> rectangle2 = ppsci.geometry.Rectangle((0.0, 0.0), (3.0, 2.0))
>>> intersection = rectangle1.__and__(rectangle2)
>>> intersection.bbox
(array([0., 0.], dtype=float32), array([2., 2.], dtype=float32))
>>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
>>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
>>> intersection = cuboid1 & cuboid2
>>> intersection.bbox
(array([0., 0., 0.], dtype=float32), array([1., 1., 1.], dtype=float32))
Source code in ppsci/geometry/geometry.py
def __and__(self, other: "Geometry") -> "Geometry":
    """CSG Intersection.

    Args:
        other (Geometry): The other geometry.

    Returns:
        Geometry: The intersection of two geometries.

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> interval1 = ppsci.geometry.Interval(0.0, 1.0)
        >>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
        >>> intersection = interval1.__and__(interval2)
        >>> intersection.bbox
        (array([[0.5]]), array([[1.]]))
        >>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
        >>> rectangle2 = ppsci.geometry.Rectangle((0.0, 0.0), (3.0, 2.0))
        >>> intersection = rectangle1.__and__(rectangle2)
        >>> intersection.bbox
        (array([0., 0.], dtype=float32), array([2., 2.], dtype=float32))
        >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
        >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
        >>> intersection = cuboid1 & cuboid2
        >>> intersection.bbox
        (array([0., 0., 0.], dtype=float32), array([1., 1., 1.], dtype=float32))
    """
    from ppsci.geometry import csg

    return csg.CSGIntersection(self, other)
__or__(other)

CSG Union.

Parameters:

Name Type Description Default
other Geometry

The other geometry.

required

Returns:

Name Type Description
Geometry 'Geometry'

The union of two geometries.

Examples:

>>> import numpy as np
>>> import ppsci
>>> interval1 = ppsci.geometry.Interval(0, 1)
>>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
>>> union = interval1.__or__(interval2)
>>> union.bbox
(array([[0.]]), array([[1.5]]))
>>> rectangle1 = ppsci.geometry.Rectangle((0, 0), (2, 3))
>>> rectangle2 = ppsci.geometry.Rectangle((0, 0), (3, 2))
>>> union = rectangle1.__or__(rectangle2)
>>> union.bbox
(array([0., 0.], dtype=float32), array([3., 3.], dtype=float32))
>>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
>>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
>>> union = cuboid1 | cuboid2
>>> union.bbox
(array([0., 0., 0.], dtype=float32), array([2., 2., 2.], dtype=float32))
Source code in ppsci/geometry/geometry.py
def __or__(self, other: "Geometry") -> "Geometry":
    """CSG Union.

    Args:
        other (Geometry): The other geometry.

    Returns:
        Geometry: The union of two geometries.

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> interval1 = ppsci.geometry.Interval(0, 1)
        >>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
        >>> union = interval1.__or__(interval2)
        >>> union.bbox
        (array([[0.]]), array([[1.5]]))
        >>> rectangle1 = ppsci.geometry.Rectangle((0, 0), (2, 3))
        >>> rectangle2 = ppsci.geometry.Rectangle((0, 0), (3, 2))
        >>> union = rectangle1.__or__(rectangle2)
        >>> union.bbox
        (array([0., 0.], dtype=float32), array([3., 3.], dtype=float32))
        >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
        >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
        >>> union = cuboid1 | cuboid2
        >>> union.bbox
        (array([0., 0., 0.], dtype=float32), array([2., 2., 2.], dtype=float32))
    """
    from ppsci.geometry import csg

    return csg.CSGUnion(self, other)
__str__()

Return the name of class.

Returns:

Name Type Description
str str

Meta information of geometry.

Examples:

>>> import ppsci
>>> interval = ppsci.geometry.Interval(0, 1)
>>> interval.__str__()
"Interval, ndim = 1, bbox = (array([[0]]), array([[1]])), diam = 1, dim_keys = ('x',)"
>>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> rectangle.__str__()
"Rectangle, ndim = 2, bbox = (array([0., 0.], dtype=float32), array([1., 1.], dtype=float32)), diam = 1.4142135381698608, dim_keys = ('x', 'y')"
>>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
>>> cuboid.__str__()
"Cuboid, ndim = 3, bbox = (array([0., 0., 0.], dtype=float32), array([1., 1., 1.], dtype=float32)), diam = 1.7320507764816284, dim_keys = ('x', 'y', 'z')"
Source code in ppsci/geometry/geometry.py
def __str__(self) -> str:
    """Return the name of class.

    Returns:
        str: Meta information of geometry.

    Examples:
        >>> import ppsci
        >>> interval = ppsci.geometry.Interval(0, 1)
        >>> interval.__str__()
        "Interval, ndim = 1, bbox = (array([[0]]), array([[1]])), diam = 1, dim_keys = ('x',)"
        >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> rectangle.__str__()
        "Rectangle, ndim = 2, bbox = (array([0., 0.], dtype=float32), array([1., 1.], dtype=float32)), diam = 1.4142135381698608, dim_keys = ('x', 'y')"
        >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
        >>> cuboid.__str__()
        "Cuboid, ndim = 3, bbox = (array([0., 0., 0.], dtype=float32), array([1., 1., 1.], dtype=float32)), diam = 1.7320507764816284, dim_keys = ('x', 'y', 'z')"
    """
    return ", ".join(
        [
            self.__class__.__name__,
            f"ndim = {self.ndim}",
            f"bbox = {self.bbox}",
            f"diam = {self.diam}",
            f"dim_keys = {self.dim_keys}",
        ]
    )
__sub__(other)

CSG Difference.

Parameters:

Name Type Description Default
other Geometry

The other geometry.

required

Returns:

Name Type Description
Geometry 'Geometry'

The difference of two geometries.

Examples:

>>> import numpy as np
>>> import ppsci
>>> interval1 = ppsci.geometry.Interval(0.0, 2.0)
>>> interval2 = ppsci.geometry.Interval(1.0, 3.0)
>>> difference = interval1.__sub__(interval2)
>>> difference.bbox
(array([[0.]]), array([[2.]]))
>>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
>>> rectangle2 = ppsci.geometry.Rectangle((1.0, 1.0), (2.0, 2.0))
>>> difference = rectangle1.__sub__(rectangle2)
>>> difference.bbox
(array([0., 0.], dtype=float32), array([2., 3.], dtype=float32))
>>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
>>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
>>> difference = cuboid1 - cuboid2
>>> difference.bbox
(array([0., 0., 0.], dtype=float32), array([1., 2., 2.], dtype=float32))
Source code in ppsci/geometry/geometry.py
def __sub__(self, other: "Geometry") -> "Geometry":
    """CSG Difference.

    Args:
        other (Geometry): The other geometry.

    Returns:
        Geometry: The difference of two geometries.

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> interval1 = ppsci.geometry.Interval(0.0, 2.0)
        >>> interval2 = ppsci.geometry.Interval(1.0, 3.0)
        >>> difference = interval1.__sub__(interval2)
        >>> difference.bbox
        (array([[0.]]), array([[2.]]))
        >>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
        >>> rectangle2 = ppsci.geometry.Rectangle((1.0, 1.0), (2.0, 2.0))
        >>> difference = rectangle1.__sub__(rectangle2)
        >>> difference.bbox
        (array([0., 0.], dtype=float32), array([2., 3.], dtype=float32))
        >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
        >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
        >>> difference = cuboid1 - cuboid2
        >>> difference.bbox
        (array([0., 0., 0.], dtype=float32), array([1., 2., 2.], dtype=float32))
    """
    from ppsci.geometry import csg

    return csg.CSGDifference(self, other)
boundary_normal(x)

Compute the unit normal at x.

Source code in ppsci/geometry/geometry.py
def boundary_normal(self, x):
    """Compute the unit normal at x."""
    raise NotImplementedError(f"{self}.boundary_normal is not implemented")
difference(other)

CSG Difference.

Parameters:

Name Type Description Default
other Geometry

The other geometry.

required

Returns:

Name Type Description
Geometry 'Geometry'

The difference of two geometries.

Examples:

>>> import numpy as np
>>> import ppsci
>>> interval1 = ppsci.geometry.Interval(0.0, 2.0)
>>> interval2 = ppsci.geometry.Interval(1.0, 3.0)
>>> difference = interval1.difference(interval2)
>>> difference.bbox
(array([[0.]]), array([[2.]]))
>>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
>>> rectangle2 = ppsci.geometry.Rectangle((1.0, 1.0), (2.0, 2.0))
>>> difference = rectangle1.difference(rectangle2)
>>> difference.bbox
(array([0., 0.], dtype=float32), array([2., 3.], dtype=float32))
>>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
>>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
>>> difference = cuboid1 - cuboid2
>>> difference.bbox
(array([0., 0., 0.], dtype=float32), array([1., 2., 2.], dtype=float32))
Source code in ppsci/geometry/geometry.py
def difference(self, other: "Geometry") -> "Geometry":
    """CSG Difference.

    Args:
        other (Geometry): The other geometry.

    Returns:
        Geometry: The difference of two geometries.

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> interval1 = ppsci.geometry.Interval(0.0, 2.0)
        >>> interval2 = ppsci.geometry.Interval(1.0, 3.0)
        >>> difference = interval1.difference(interval2)
        >>> difference.bbox
        (array([[0.]]), array([[2.]]))
        >>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
        >>> rectangle2 = ppsci.geometry.Rectangle((1.0, 1.0), (2.0, 2.0))
        >>> difference = rectangle1.difference(rectangle2)
        >>> difference.bbox
        (array([0., 0.], dtype=float32), array([2., 3.], dtype=float32))
        >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
        >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
        >>> difference = cuboid1 - cuboid2
        >>> difference.bbox
        (array([0., 0., 0.], dtype=float32), array([1., 2., 2.], dtype=float32))
    """
    from ppsci.geometry import csg

    return csg.CSGDifference(self, other)
intersection(other)

CSG Intersection.

Parameters:

Name Type Description Default
other Geometry

The other geometry.

required

Returns:

Name Type Description
Geometry 'Geometry'

The intersection of two geometries.

Examples:

>>> import numpy as np
>>> import ppsci
>>> interval1 = ppsci.geometry.Interval(0.0, 1.0)
>>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
>>> intersection = interval1.intersection(interval2)
>>> intersection.bbox
(array([[0.5]]), array([[1.]]))
>>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
>>> rectangle2 = ppsci.geometry.Rectangle((0.0, 0.0), (3.0, 2.0))
>>> intersection = rectangle1.intersection(rectangle2)
>>> intersection.bbox
(array([0., 0.], dtype=float32), array([2., 2.], dtype=float32))
>>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
>>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
>>> intersection = cuboid1 & cuboid2
>>> intersection.bbox
(array([0., 0., 0.], dtype=float32), array([1., 1., 1.], dtype=float32))
Source code in ppsci/geometry/geometry.py
def intersection(self, other: "Geometry") -> "Geometry":
    """CSG Intersection.

    Args:
        other (Geometry): The other geometry.

    Returns:
        Geometry: The intersection of two geometries.

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> interval1 = ppsci.geometry.Interval(0.0, 1.0)
        >>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
        >>> intersection = interval1.intersection(interval2)
        >>> intersection.bbox
        (array([[0.5]]), array([[1.]]))
        >>> rectangle1 = ppsci.geometry.Rectangle((0.0, 0.0), (2.0, 3.0))
        >>> rectangle2 = ppsci.geometry.Rectangle((0.0, 0.0), (3.0, 2.0))
        >>> intersection = rectangle1.intersection(rectangle2)
        >>> intersection.bbox
        (array([0., 0.], dtype=float32), array([2., 2.], dtype=float32))
        >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
        >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
        >>> intersection = cuboid1 & cuboid2
        >>> intersection.bbox
        (array([0., 0., 0.], dtype=float32), array([1., 1., 1.], dtype=float32))
    """
    from ppsci.geometry import csg

    return csg.CSGIntersection(self, other)
is_inside(x) abstractmethod

Returns a boolean array where x is inside the geometry.

Parameters:

Name Type Description Default
x ndarray

Points to check if inside the geometry. The shape is [N, D], where D is the number of dimension of geometry.

required

Returns:

Type Description
ndarray

np.ndarray: Boolean array where x is inside the geometry. The shape is [N].

Examples:

>>> import numpy as np
>>> import ppsci
>>> interval = ppsci.geometry.Interval(0, 1)
>>> x = np.array([[0], [0.5], [1.5]])
>>> interval.is_inside(x)
array([ True,  True, False])
>>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> x = np.array([[0.0, 0.0], [0.5, 0.5], [1.5, 1.5]])
>>> rectangle.is_inside(x)
array([ True,  True, False])
>>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
>>> x = np.array([[0, 0, 0], [0.5, 0.5, 0.5], [1.5, 1.5, 1.5]])
>>> cuboid.is_inside(x)
array([ True,  True, False])
Source code in ppsci/geometry/geometry.py
@abc.abstractmethod
def is_inside(self, x: np.ndarray) -> np.ndarray:
    """Returns a boolean array where x is inside the geometry.

    Args:
        x (np.ndarray): Points to check if inside the geometry. The shape is [N, D],
            where D is the number of dimension of geometry.

    Returns:
        np.ndarray: Boolean array where x is inside the geometry. The shape is [N].

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> interval = ppsci.geometry.Interval(0, 1)
        >>> x = np.array([[0], [0.5], [1.5]])
        >>> interval.is_inside(x)
        array([ True,  True, False])
        >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> x = np.array([[0.0, 0.0], [0.5, 0.5], [1.5, 1.5]])
        >>> rectangle.is_inside(x)
        array([ True,  True, False])
        >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
        >>> x = np.array([[0, 0, 0], [0.5, 0.5, 0.5], [1.5, 1.5, 1.5]])
        >>> cuboid.is_inside(x)
        array([ True,  True, False])
    """
on_boundary(x) abstractmethod

Returns a boolean array where x is on geometry boundary.

Parameters:

Name Type Description Default
x ndarray

Points to check if on the geometry boundary. The shape is [N, D], where D is the number of dimension of geometry.

required

Returns:

Type Description
ndarray

np.ndarray: Boolean array where x is on the geometry boundary. The shape is [N].

Examples:

>>> import numpy as np
>>> import ppsci
>>> interval = ppsci.geometry.Interval(0, 1)
>>> x = np.array([[0], [0.5], [1.5]])
>>> interval.on_boundary(x)
array([ True, False, False])
>>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> x = np.array([[0, 0], [0.5, 0.5], [1, 1.5]])
>>> rectangle.on_boundary(x)
array([ True, False, False])
>>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
>>> x = np.array([[0, 0, 0], [0.5, 0.5, 0.5], [1, 1, 1.5]])
>>> cuboid.on_boundary(x)
array([ True, False, False])
Source code in ppsci/geometry/geometry.py
@abc.abstractmethod
def on_boundary(self, x: np.ndarray) -> np.ndarray:
    """Returns a boolean array where x is on geometry boundary.

    Args:
        x (np.ndarray): Points to check if on the geometry boundary. The shape is [N, D],
            where D is the number of dimension of geometry.

    Returns:
        np.ndarray: Boolean array where x is on the geometry boundary. The shape is [N].

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> interval = ppsci.geometry.Interval(0, 1)
        >>> x = np.array([[0], [0.5], [1.5]])
        >>> interval.on_boundary(x)
        array([ True, False, False])
        >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> x = np.array([[0, 0], [0.5, 0.5], [1, 1.5]])
        >>> rectangle.on_boundary(x)
        array([ True, False, False])
        >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
        >>> x = np.array([[0, 0, 0], [0.5, 0.5, 0.5], [1, 1, 1.5]])
        >>> cuboid.on_boundary(x)
        array([ True, False, False])
    """
periodic_point(x, component)

Compute the periodic image of x(not implemented).

Source code in ppsci/geometry/geometry.py
def periodic_point(self, x: np.ndarray, component: int):
    """Compute the periodic image of x(not implemented)."""
    raise NotImplementedError(f"{self}.periodic_point to be implemented")
random_boundary_points(n, random='pseudo') abstractmethod

Compute the random points on the boundary.

Parameters:

Name Type Description Default
n int

Number of points.

required
random Literal['pseudo', 'Halton', 'LHS']

Random method. Defaults to "pseudo". Options: - "pseudo": Pseudo random. - "Halton": Halton sequence. - "LHS": Latin Hypercube Sampling.

'pseudo'

Returns:

Type Description
ndarray

np.ndarray: Random points on the boundary. The shape is [N, D].

Examples:

>>> import numpy as np
>>> import ppsci
>>> np.random.seed(42)
>>> interval = ppsci.geometry.Interval(0, 1)
>>> interval.random_boundary_points(2)
array([[0.],
       [1.]], dtype=float32)
>>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> rectangle.random_boundary_points(2)
array([[1.        , 0.49816048],
       [0.        , 0.19714284]], dtype=float32)
>>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
>>> cuboid.random_boundary_points(2)
array([[0.83244264, 0.21233912, 0.        ],
       [0.18182497, 0.1834045 , 1.        ]], dtype=float32)
Source code in ppsci/geometry/geometry.py
@abc.abstractmethod
def random_boundary_points(
    self, n: int, random: Literal["pseudo", "Halton", "LHS"] = "pseudo"
) -> np.ndarray:
    """Compute the random points on the boundary.

    Args:
        n (int): Number of points.
        random (Literal["pseudo", "Halton", "LHS"]): Random method. Defaults to "pseudo". Options:
            - "pseudo": Pseudo random.
            - "Halton": Halton sequence.
            - "LHS": Latin Hypercube Sampling.

    Returns:
        np.ndarray: Random points on the boundary. The shape is [N, D].

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> np.random.seed(42)
        >>> interval = ppsci.geometry.Interval(0, 1)
        >>> interval.random_boundary_points(2)
        array([[0.],
               [1.]], dtype=float32)
        >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> rectangle.random_boundary_points(2)
        array([[1.        , 0.49816048],
               [0.        , 0.19714284]], dtype=float32)
        >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
        >>> cuboid.random_boundary_points(2)
        array([[0.83244264, 0.21233912, 0.        ],
               [0.18182497, 0.1834045 , 1.        ]], dtype=float32)
    """
random_points(n, random='pseudo') abstractmethod

Compute the random points in the geometry.

Parameters:

Name Type Description Default
n int

Number of points.

required
random Literal['pseudo', 'Halton', 'LHS']

Random method. Defaults to "pseudo". Options: - "pseudo": Pseudo random. - "Halton": Halton sequence. - "LHS": Latin Hypercube Sampling.

'pseudo'

Returns:

Type Description
ndarray

np.ndarray: Random points in the geometry. The shape is [N, D].

Examples:

>>> import numpy as np
>>> import ppsci
>>> np.random.seed(42)
>>> interval = ppsci.geometry.Interval(0, 1)
>>> interval.random_points(2)
array([[0.37454012],
       [0.9507143 ]], dtype=float32)
>>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> rectangle.random_points(2)
array([[0.7319939 , 0.5986585 ],
       [0.15601864, 0.15599452]], dtype=float32)
>>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
>>> cuboid.random_points(2)
array([[0.05808361, 0.8661761 , 0.601115  ],
       [0.7080726 , 0.02058449, 0.96990985]], dtype=float32)
Source code in ppsci/geometry/geometry.py
@abc.abstractmethod
def random_points(
    self, n: int, random: Literal["pseudo", "Halton", "LHS"] = "pseudo"
) -> np.ndarray:
    """Compute the random points in the geometry.

    Args:
        n (int): Number of points.
        random (Literal["pseudo", "Halton", "LHS"]): Random method. Defaults to "pseudo". Options:
            - "pseudo": Pseudo random.
            - "Halton": Halton sequence.
            - "LHS": Latin Hypercube Sampling.

    Returns:
        np.ndarray: Random points in the geometry. The shape is [N, D].

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> np.random.seed(42)
        >>> interval = ppsci.geometry.Interval(0, 1)
        >>> interval.random_points(2)
        array([[0.37454012],
               [0.9507143 ]], dtype=float32)
        >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> rectangle.random_points(2)
        array([[0.7319939 , 0.5986585 ],
               [0.15601864, 0.15599452]], dtype=float32)
        >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
        >>> cuboid.random_points(2)
        array([[0.05808361, 0.8661761 , 0.601115  ],
               [0.7080726 , 0.02058449, 0.96990985]], dtype=float32)
    """
sample_boundary(n, random='pseudo', criteria=None, evenly=False)

Compute the random points in the geometry and return those meet criteria.

Parameters:

Name Type Description Default
n int

Number of points.

required
random Literal['pseudo', 'Halton', 'LHS']

Random method. Defaults to "pseudo". Options: - "pseudo": Pseudo random. - "Halton": Halton sequence. - "LHS": Latin Hypercube Sampling.

'pseudo'
criteria Optional[Callable[..., ndarray]]

Criteria function. Given coords from different dimension and return a boolean array with shape [n,]. Defaults to None.

None
evenly bool

Evenly sample points. Defaults to False.

False

Returns:

Type Description
Dict[str, ndarray]

Dict[str, np.ndarray]: Random points in the geometry. The shape is [N, D]. their normal vectors. The shape is [N, D]. their area. The shape is [N, 1].(only if the geometry is a mesh)

Examples:

>>> import numpy as np
>>> import ppsci
>>> np.random.seed(42)
>>> interval = ppsci.geometry.Interval(0, 1)
>>> interval.sample_boundary(2)
{'x': array([[0.],
       [1.]], dtype=float32), 'normal_x': array([[-1.],
       [ 1.]], dtype=float32)}
>>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> rectangle.sample_boundary(2)
{'x': array([[1.],
       [0.]], dtype=float32), 'y': array([[0.49816048],
       [0.19714284]], dtype=float32), 'normal_x': array([[ 1.],
       [-1.]], dtype=float32), 'normal_y': array([[0.],
       [0.]], dtype=float32)}
>>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
>>> cuboid.sample_boundary(2)
{'x': array([[0.83244264],
       [0.18182497]], dtype=float32), 'y': array([[0.21233912],
       [0.1834045 ]], dtype=float32), 'z': array([[0.],
       [1.]], dtype=float32), 'normal_x': array([[0.],
       [0.]], dtype=float32), 'normal_y': array([[0.],
       [0.]], dtype=float32), 'normal_z': array([[-1.],
       [ 1.]], dtype=float32)}
Source code in ppsci/geometry/geometry.py
def sample_boundary(
    self,
    n: int,
    random: Literal["pseudo", "Halton", "LHS"] = "pseudo",
    criteria: Optional[Callable[..., np.ndarray]] = None,
    evenly: bool = False,
) -> Dict[str, np.ndarray]:
    """Compute the random points in the geometry and return those meet criteria.

    Args:
        n (int): Number of points.
        random (Literal["pseudo", "Halton", "LHS"]): Random method. Defaults to "pseudo". Options:
            - "pseudo": Pseudo random.
            - "Halton": Halton sequence.
            - "LHS": Latin Hypercube Sampling.
        criteria (Optional[Callable[..., np.ndarray]]): Criteria function. Given
            coords from different dimension and return a boolean array with shape [n,].
            Defaults to None.
        evenly (bool): Evenly sample points. Defaults to False.

    Returns:
        Dict[str, np.ndarray]: Random points in the geometry. The shape is [N, D].
                               their normal vectors. The shape is [N, D].
                               their area. The shape is [N, 1].(only if the geometry is a mesh)

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> np.random.seed(42)
        >>> interval = ppsci.geometry.Interval(0, 1)
        >>> interval.sample_boundary(2)
        {'x': array([[0.],
               [1.]], dtype=float32), 'normal_x': array([[-1.],
               [ 1.]], dtype=float32)}
        >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> rectangle.sample_boundary(2)
        {'x': array([[1.],
               [0.]], dtype=float32), 'y': array([[0.49816048],
               [0.19714284]], dtype=float32), 'normal_x': array([[ 1.],
               [-1.]], dtype=float32), 'normal_y': array([[0.],
               [0.]], dtype=float32)}
        >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
        >>> cuboid.sample_boundary(2)
        {'x': array([[0.83244264],
               [0.18182497]], dtype=float32), 'y': array([[0.21233912],
               [0.1834045 ]], dtype=float32), 'z': array([[0.],
               [1.]], dtype=float32), 'normal_x': array([[0.],
               [0.]], dtype=float32), 'normal_y': array([[0.],
               [0.]], dtype=float32), 'normal_z': array([[-1.],
               [ 1.]], dtype=float32)}
    """
    x = np.empty(shape=(n, self.ndim), dtype=paddle.get_default_dtype())
    _size, _ntry, _nsuc = 0, 0, 0
    while _size < n:
        if evenly:
            if (
                misc.typename(self) == "TimeXGeometry"
                and misc.typename(self.geometry) == "Mesh"
            ):
                points, normal, area = self.uniform_boundary_points(n)
            else:
                points = self.uniform_boundary_points(n)
        else:
            if (
                misc.typename(self) == "TimeXGeometry"
                and misc.typename(self.geometry) == "Mesh"
            ):
                points, normal, area = self.random_boundary_points(n, random)
            else:
                if misc.typename(self) == "TimeXGeometry":
                    points = self.random_boundary_points(n, random, criteria)
                else:
                    points = self.random_boundary_points(n, random)

        if criteria is not None:
            criteria_mask = criteria(*np.split(points, self.ndim, axis=1)).flatten()
            points = points[criteria_mask]

        if len(points) > n - _size:
            points = points[: n - _size]
        x[_size : _size + len(points)] = points

        _size += len(points)
        _ntry += 1
        if len(points) > 0:
            _nsuc += 1

        if _ntry >= 10000 and _nsuc == 0:
            raise ValueError(
                "Sample boundary points failed, "
                "please check correctness of geometry and given criteria."
            )

    if not (
        misc.typename(self) == "TimeXGeometry"
        and misc.typename(self.geometry) == "Mesh"
    ):
        normal = self.boundary_normal(x)

    normal_dict = misc.convert_to_dict(
        normal[:, 1:] if "t" in self.dim_keys else normal,
        [f"normal_{key}" for key in self.dim_keys if key != "t"],
    )
    x_dict = misc.convert_to_dict(x, self.dim_keys)
    if (
        misc.typename(self) == "TimeXGeometry"
        and misc.typename(self.geometry) == "Mesh"
    ):
        area_dict = misc.convert_to_dict(area[:, 1:], ["area"])
        return {**x_dict, **normal_dict, **area_dict}

    return {**x_dict, **normal_dict}
sample_interior(n, random='pseudo', criteria=None, evenly=False, compute_sdf_derivatives=False)

Sample random points in the geometry and return those meet criteria.

NOTE: sdf values returned by this function are negated because the weight in loss function should be positive.

Parameters:

Name Type Description Default
n int

Number of points.

required
random Literal['pseudo', 'Halton', 'LHS']

Random method. Defaults to "pseudo". Options: - "pseudo": Pseudo random. - "Halton": Halton sequence. - "LHS": Latin Hypercube Sampling.

'pseudo'
criteria Optional[Callable[..., ndarray]]

Criteria function. Given coords from different dimension and return a boolean array with shape [n,]. Defaults to None.

None
evenly bool

Evenly sample points. Defaults to False.

False
compute_sdf_derivatives bool

Compute SDF derivatives. Defaults to False.

False

Returns:

Type Description
Dict[str, ndarray]

Dict[str, np.ndarray]: Random points in the geometry. The shape is [N, D]. their signed distance function. The shape is [N, 1]. their derivatives of SDF(optional). The shape is [N, D].

Examples:

>>> import numpy as np
>>> import ppsci
>>> np.random.seed(42)
>>> interval = ppsci.geometry.Interval(0, 1)
>>> interval.sample_interior(2)
{'x': array([[0.37454012],
       [0.9507143 ]], dtype=float32), 'sdf': array([[0.37454012],
       [0.04928571]], dtype=float32)}
>>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> rectangle.sample_interior(2, "pseudo", None, False, True)
{'x': array([[0.7319939 ],
       [0.15601864]], dtype=float32), 'y': array([[0.5986585 ],
       [0.15599452]], dtype=float32), 'sdf': array([[0.2680061 ],
       [0.15599453]], dtype=float32), 'sdf__x': array([[-1.0001659 ],
       [ 0.25868416]], dtype=float32), 'sdf__y': array([[-0.        ],
       [ 0.74118376]], dtype=float32)}
>>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
>>> cuboid.sample_interior(2, "pseudo", None, True, True)
{'x': array([[0.],
       [0.]], dtype=float32), 'y': array([[0.],
       [0.]], dtype=float32), 'z': array([[0.],
       [1.]], dtype=float32), 'sdf': array([[0.],
       [0.]], dtype=float32), 'sdf__x': array([[0.50008297],
       [0.50008297]], dtype=float32), 'sdf__y': array([[0.50008297],
       [0.50008297]], dtype=float32), 'sdf__z': array([[ 0.50008297],
       [-0.49948692]], dtype=float32)}
Source code in ppsci/geometry/geometry.py
def sample_interior(
    self,
    n: int,
    random: Literal["pseudo", "Halton", "LHS"] = "pseudo",
    criteria: Optional[Callable[..., np.ndarray]] = None,
    evenly: bool = False,
    compute_sdf_derivatives: bool = False,
) -> Dict[str, np.ndarray]:
    """Sample random points in the geometry and return those meet criteria.

    NOTE: sdf values returned by this function are negated because the weight in
    loss function should be positive.

    Args:
        n (int): Number of points.
        random (Literal["pseudo", "Halton", "LHS"]): Random method. Defaults to "pseudo". Options:
            - "pseudo": Pseudo random.
            - "Halton": Halton sequence.
            - "LHS": Latin Hypercube Sampling.
        criteria (Optional[Callable[..., np.ndarray]]): Criteria function. Given
            coords from different dimension and return a boolean array with shape [n,].
            Defaults to None.
        evenly (bool): Evenly sample points. Defaults to False.
        compute_sdf_derivatives (bool): Compute SDF derivatives. Defaults to False.

    Returns:
        Dict[str, np.ndarray]: Random points in the geometry. The shape is [N, D].
                               their signed distance function. The shape is [N, 1].
                               their derivatives of SDF(optional). The shape is [N, D].

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> np.random.seed(42)
        >>> interval = ppsci.geometry.Interval(0, 1)
        >>> interval.sample_interior(2)
        {'x': array([[0.37454012],
               [0.9507143 ]], dtype=float32), 'sdf': array([[0.37454012],
               [0.04928571]], dtype=float32)}
        >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> rectangle.sample_interior(2, "pseudo", None, False, True)
        {'x': array([[0.7319939 ],
               [0.15601864]], dtype=float32), 'y': array([[0.5986585 ],
               [0.15599452]], dtype=float32), 'sdf': array([[0.2680061 ],
               [0.15599453]], dtype=float32), 'sdf__x': array([[-1.0001659 ],
               [ 0.25868416]], dtype=float32), 'sdf__y': array([[-0.        ],
               [ 0.74118376]], dtype=float32)}
        >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
        >>> cuboid.sample_interior(2, "pseudo", None, True, True)
        {'x': array([[0.],
               [0.]], dtype=float32), 'y': array([[0.],
               [0.]], dtype=float32), 'z': array([[0.],
               [1.]], dtype=float32), 'sdf': array([[0.],
               [0.]], dtype=float32), 'sdf__x': array([[0.50008297],
               [0.50008297]], dtype=float32), 'sdf__y': array([[0.50008297],
               [0.50008297]], dtype=float32), 'sdf__z': array([[ 0.50008297],
               [-0.49948692]], dtype=float32)}
    """
    x = np.empty(shape=(n, self.ndim), dtype=paddle.get_default_dtype())
    _size, _ntry, _nsuc = 0, 0, 0
    while _size < n:
        if evenly:
            points = self.uniform_points(n)
        else:
            if misc.typename(self) == "TimeXGeometry":
                points = self.random_points(n, random, criteria)
            else:
                points = self.random_points(n, random)

        if criteria is not None:
            criteria_mask = criteria(*np.split(points, self.ndim, axis=1)).flatten()
            points = points[criteria_mask]

        if len(points) > n - _size:
            points = points[: n - _size]
        x[_size : _size + len(points)] = points

        _size += len(points)
        _ntry += 1
        if len(points) > 0:
            _nsuc += 1

        if _ntry >= 1000 and _nsuc == 0:
            raise ValueError(
                "Sample interior points failed, "
                "please check correctness of geometry and given criteria."
            )

    # if sdf_func added, return x_dict and sdf_dict, else, only return the x_dict
    if hasattr(self, "sdf_func"):
        # NOTE: add negative to the sdf values because weight should be positive.
        sdf = -self.sdf_func(x)
        sdf_dict = misc.convert_to_dict(sdf, ("sdf",))
        sdf_derives_dict = {}
        if compute_sdf_derivatives:
            sdf_derives = -self.sdf_derivatives(x)
            sdf_derives_dict = misc.convert_to_dict(
                sdf_derives, tuple(f"sdf__{key}" for key in self.dim_keys)
            )
    else:
        sdf_dict = {}
        sdf_derives_dict = {}
    x_dict = misc.convert_to_dict(x, self.dim_keys)

    return {**x_dict, **sdf_dict, **sdf_derives_dict}
sdf_derivatives(x, epsilon=0.0001)

Compute derivatives of SDF function.

Parameters:

Name Type Description Default
x ndarray

Points for computing SDF derivatives using central difference. The shape is [N, D], D is the number of dimension of geometry.

required
epsilon float

Derivative step. Defaults to 1e-4.

0.0001

Returns:

Type Description
ndarray

np.ndarray: Derivatives of corresponding SDF function. The shape is [N, D]. D is the number of dimension of geometry.

Examples:

>>> import numpy as np
>>> import ppsci
>>> interval = ppsci.geometry.Interval(0, 1)
>>> x = np.array([[0], [0.5], [1.5]])
>>> interval.sdf_derivatives(x)
array([[-1.],
       [ 0.],
       [ 1.]])
>>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> x = np.array([[0.0, 0.0], [0.5, 0.5], [1.5, 1.5]])
>>> rectangle.sdf_derivatives(x)
array([[-0.5       , -0.5       ],
       [ 0.        ,  0.        ],
       [ 0.70710678,  0.70710678]])
>>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
>>> x = np.array([[0, 0, 0], [0.5, 0.5, 0.5], [1, 1, 1]])
>>> cuboid.sdf_derivatives(x)
array([[-0.5, -0.5, -0.5],
       [ 0. ,  0. ,  0. ],
       [ 0.5,  0.5,  0.5]])
Source code in ppsci/geometry/geometry.py
def sdf_derivatives(self, x: np.ndarray, epsilon: float = 1e-4) -> np.ndarray:
    """Compute derivatives of SDF function.

    Args:
        x (np.ndarray): Points for computing SDF derivatives using central
            difference. The shape is [N, D], D is the number of dimension of
            geometry.
        epsilon (float): Derivative step. Defaults to 1e-4.

    Returns:
        np.ndarray: Derivatives of corresponding SDF function.
            The shape is [N, D]. D is the number of dimension of geometry.

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> interval = ppsci.geometry.Interval(0, 1)
        >>> x = np.array([[0], [0.5], [1.5]])
        >>> interval.sdf_derivatives(x)
        array([[-1.],
               [ 0.],
               [ 1.]])
        >>> rectangle = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> x = np.array([[0.0, 0.0], [0.5, 0.5], [1.5, 1.5]])
        >>> rectangle.sdf_derivatives(x)
        array([[-0.5       , -0.5       ],
               [ 0.        ,  0.        ],
               [ 0.70710678,  0.70710678]])
        >>> cuboid = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
        >>> x = np.array([[0, 0, 0], [0.5, 0.5, 0.5], [1, 1, 1]])
        >>> cuboid.sdf_derivatives(x)
        array([[-0.5, -0.5, -0.5],
               [ 0. ,  0. ,  0. ],
               [ 0.5,  0.5,  0.5]])
    """
    if not hasattr(self, "sdf_func"):
        raise NotImplementedError(
            f"{misc.typename(self)}.sdf_func should be implemented "
            "when using 'sdf_derivatives'."
        )
    # Only compute sdf derivatives for those already implement `sdf_func` method.
    sdf_derives = np.empty_like(x)
    for i in range(self.ndim):
        h = np.zeros_like(x)
        h[:, i] += epsilon / 2
        derives_at_i = (self.sdf_func(x + h) - self.sdf_func(x - h)) / epsilon
        sdf_derives[:, i : i + 1] = derives_at_i
    return sdf_derives
uniform_boundary_points(n)

Compute the equi-spaced points on the boundary(not implemented).

Parameters:

Name Type Description Default
n int

Number of points.

required

Returns:

Type Description
ndarray

np.ndarray: Random points on the boundary. The shape is [N, D].

Source code in ppsci/geometry/geometry.py
def uniform_boundary_points(self, n: int) -> np.ndarray:
    """Compute the equi-spaced points on the boundary(not implemented).

    Args:
        n (int): Number of points.

    Returns:
        np.ndarray: Random points on the boundary. The shape is [N, D].
    """
    logger.warning(
        f"{self}.uniform_boundary_points not implemented. "
        f"Use random_boundary_points instead."
    )
    return self.random_boundary_points(n)
uniform_points(n, boundary=True)

Compute the equi-spaced points in the geometry.

Parameters:

Name Type Description Default
n int

Number of points.

required
boundary bool

Include boundary points. Defaults to True.

True

Returns:

Type Description
ndarray

np.ndarray: Random points in the geometry. The shape is [N, D].

Source code in ppsci/geometry/geometry.py
def uniform_points(self, n: int, boundary: bool = True) -> np.ndarray:
    """Compute the equi-spaced points in the geometry.

    Args:
        n (int): Number of points.
        boundary (bool): Include boundary points. Defaults to True.

    Returns:
        np.ndarray: Random points in the geometry. The shape is [N, D].
    """
    logger.warning(
        f"{self}.uniform_points not implemented. " f"Use random_points instead."
    )
    return self.random_points(n)
union(other)

CSG Union.

Parameters:

Name Type Description Default
other Geometry

The other geometry.

required

Returns:

Name Type Description
Geometry 'Geometry'

The union of two geometries.

Examples:

>>> import numpy as np
>>> import ppsci
>>> interval1 = ppsci.geometry.Interval(0, 1)
>>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
>>> union = interval1.union(interval2)
>>> union.bbox
(array([[0.]]), array([[1.5]]))
>>> rectangle1 = ppsci.geometry.Rectangle((0, 0), (2, 3))
>>> rectangle2 = ppsci.geometry.Rectangle((0, 0), (3, 2))
>>> union = rectangle1.union(rectangle2)
>>> union.bbox
(array([0., 0.], dtype=float32), array([3., 3.], dtype=float32))
>>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
>>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
>>> union = cuboid1 | cuboid2
>>> union.bbox
(array([0., 0., 0.], dtype=float32), array([2., 2., 2.], dtype=float32))
Source code in ppsci/geometry/geometry.py
def union(self, other: "Geometry") -> "Geometry":
    """CSG Union.

    Args:
        other (Geometry): The other geometry.

    Returns:
        Geometry: The union of two geometries.

    Examples:
        >>> import numpy as np
        >>> import ppsci
        >>> interval1 = ppsci.geometry.Interval(0, 1)
        >>> interval2 = ppsci.geometry.Interval(0.5, 1.5)
        >>> union = interval1.union(interval2)
        >>> union.bbox
        (array([[0.]]), array([[1.5]]))
        >>> rectangle1 = ppsci.geometry.Rectangle((0, 0), (2, 3))
        >>> rectangle2 = ppsci.geometry.Rectangle((0, 0), (3, 2))
        >>> union = rectangle1.union(rectangle2)
        >>> union.bbox
        (array([0., 0.], dtype=float32), array([3., 3.], dtype=float32))
        >>> cuboid1 = ppsci.geometry.Cuboid((0, 0, 0), (1, 2, 2))
        >>> cuboid2 = ppsci.geometry.Cuboid((0, 0, 0), (2, 1, 1))
        >>> union = cuboid1 | cuboid2
        >>> union.bbox
        (array([0., 0., 0.], dtype=float32), array([2., 2., 2.], dtype=float32))
    """
    from ppsci.geometry import csg

    return csg.CSGUnion(self, other)

Cuboid

Bases: Hypercube

Class for Cuboid

Parameters:

Name Type Description Default
xmin Tuple[float, float, float]

Bottom left corner point [x0, y0, z0].

required
xmax Tuple[float, float, float]

Top right corner point [x1, y1, z1].

required

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
Source code in ppsci/geometry/geometry_3d.py
class Cuboid(geometry_nd.Hypercube):
    """Class for Cuboid

    Args:
        xmin (Tuple[float, float, float]): Bottom left corner point [x0, y0, z0].
        xmax (Tuple[float, float, float]): Top right corner point [x1, y1, z1].

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.Cuboid((0, 0, 0), (1, 1, 1))
    """

    def __init__(
        self, xmin: Tuple[float, float, float], xmax: Tuple[float, float, float]
    ):
        super().__init__(xmin, xmax)
        dx = self.xmax - self.xmin
        self.area = 2 * np.sum(dx * np.roll(dx, 2))

    def random_boundary_points(self, n, random="pseudo"):
        pts = []
        density = n / self.area
        rect = geometry_2d.Rectangle(self.xmin[:-1], self.xmax[:-1])
        for z in [self.xmin[-1], self.xmax[-1]]:
            u = rect.random_points(int(np.ceil(density * rect.area)), random=random)
            pts.append(
                np.hstack(
                    (u, np.full((len(u), 1), z, dtype=paddle.get_default_dtype()))
                )
            )
        rect = geometry_2d.Rectangle(self.xmin[::2], self.xmax[::2])
        for y in [self.xmin[1], self.xmax[1]]:
            u = rect.random_points(int(np.ceil(density * rect.area)), random=random)
            pts.append(
                np.hstack(
                    (
                        u[:, 0:1],
                        np.full((len(u), 1), y, dtype=paddle.get_default_dtype()),
                        u[:, 1:],
                    )
                )
            )
        rect = geometry_2d.Rectangle(self.xmin[1:], self.xmax[1:])
        for x in [self.xmin[0], self.xmax[0]]:
            u = rect.random_points(int(np.ceil(density * rect.area)), random=random)
            pts.append(
                np.hstack(
                    (np.full((len(u), 1), x, dtype=paddle.get_default_dtype()), u)
                )
            )
        pts = np.vstack(pts)
        if len(pts) > n:
            return pts[np.random.choice(len(pts), size=n, replace=False)]
        return pts

    def uniform_boundary_points(self, n):
        h = (self.area / n) ** 0.5
        nx, ny, nz = np.ceil((self.xmax - self.xmin) / h).astype(int) + 1
        x = np.linspace(
            self.xmin[0], self.xmax[0], num=nx, dtype=paddle.get_default_dtype()
        )
        y = np.linspace(
            self.xmin[1], self.xmax[1], num=ny, dtype=paddle.get_default_dtype()
        )
        z = np.linspace(
            self.xmin[2], self.xmax[2], num=nz, dtype=paddle.get_default_dtype()
        )

        pts = []
        for v in [self.xmin[-1], self.xmax[-1]]:
            u = list(itertools.product(x, y))
            pts.append(
                np.hstack(
                    (u, np.full((len(u), 1), v, dtype=paddle.get_default_dtype()))
                )
            )
        if nz > 2:
            for v in [self.xmin[1], self.xmax[1]]:
                u = np.array(
                    list(itertools.product(x, z[1:-1])),
                    dtype=paddle.get_default_dtype(),
                )
                pts.append(
                    np.hstack(
                        (
                            u[:, 0:1],
                            np.full((len(u), 1), v, dtype=paddle.get_default_dtype()),
                            u[:, 1:],
                        )
                    )
                )
        if ny > 2 and nz > 2:
            for v in [self.xmin[0], self.xmax[0]]:
                u = list(itertools.product(y[1:-1], z[1:-1]))
                pts.append(
                    np.hstack(
                        (np.full((len(u), 1), v, dtype=paddle.get_default_dtype()), u)
                    )
                )
        pts = np.vstack(pts)
        if len(pts) > n:
            return pts[np.random.choice(len(pts), size=n, replace=False)]
        return pts

    def sdf_func(self, points: np.ndarray) -> np.ndarray:
        """Compute signed distance field.

        Args:
            points (np.ndarray): The coordinate points used to calculate the SDF value,
                the shape is [N, 3]

        Returns:
            np.ndarray: SDF values of input points without squared, the shape is [N, 1].

        NOTE: This function usually returns ndarray with negative values, because
        according to the definition of SDF, the SDF value of the coordinate point inside
        the object(interior points) is negative, the outside is positive, and the edge
        is 0. Therefore, when used for weighting, a negative sign is often added before
        the result of this function.
        """
        if points.shape[1] != self.ndim:
            raise ValueError(
                f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
            )
        sdf = (
            ((self.xmax - self.xmin) / 2 - abs(points - (self.xmin + self.xmax) / 2))
        ).min(axis=1)
        sdf = -sdf[..., np.newaxis]
        return sdf
sdf_func(points)

Compute signed distance field.

Parameters:

Name Type Description Default
points ndarray

The coordinate points used to calculate the SDF value, the shape is [N, 3]

required

Returns:

Type Description
ndarray

np.ndarray: SDF values of input points without squared, the shape is [N, 1].

NOTE: This function usually returns ndarray with negative values, because according to the definition of SDF, the SDF value of the coordinate point inside the object(interior points) is negative, the outside is positive, and the edge is 0. Therefore, when used for weighting, a negative sign is often added before the result of this function.

Source code in ppsci/geometry/geometry_3d.py
def sdf_func(self, points: np.ndarray) -> np.ndarray:
    """Compute signed distance field.

    Args:
        points (np.ndarray): The coordinate points used to calculate the SDF value,
            the shape is [N, 3]

    Returns:
        np.ndarray: SDF values of input points without squared, the shape is [N, 1].

    NOTE: This function usually returns ndarray with negative values, because
    according to the definition of SDF, the SDF value of the coordinate point inside
    the object(interior points) is negative, the outside is positive, and the edge
    is 0. Therefore, when used for weighting, a negative sign is often added before
    the result of this function.
    """
    if points.shape[1] != self.ndim:
        raise ValueError(
            f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
        )
    sdf = (
        ((self.xmax - self.xmin) / 2 - abs(points - (self.xmin + self.xmax) / 2))
    ).min(axis=1)
    sdf = -sdf[..., np.newaxis]
    return sdf

Disk

Bases: Geometry

Class for disk geometry

Parameters:

Name Type Description Default
center Tuple[float, float]

Center point of disk [x0, y0].

required
radius float

Radius of disk.

required

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.Disk((0.0, 0.0), 1.0)
Source code in ppsci/geometry/geometry_2d.py
class Disk(geometry.Geometry):
    """Class for disk geometry

    Args:
        center (Tuple[float, float]): Center point of disk [x0, y0].
        radius (float): Radius of disk.

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.Disk((0.0, 0.0), 1.0)
    """

    def __init__(self, center: Tuple[float, float], radius: float):
        self.center = np.array(center, dtype=paddle.get_default_dtype())
        self.radius = radius
        super().__init__(2, (self.center - radius, self.center + radius), 2 * radius)

    def is_inside(self, x):
        return np.linalg.norm(x - self.center, axis=1) <= self.radius

    def on_boundary(self, x):
        return np.isclose(np.linalg.norm(x - self.center, axis=1), self.radius)

    def boundary_normal(self, x):
        ox = x - self.center
        ox_len = np.linalg.norm(ox, axis=1, keepdims=True)
        ox = (ox / ox_len) * np.isclose(ox_len, self.radius).astype(
            paddle.get_default_dtype()
        )
        return ox

    def random_points(self, n, random="pseudo"):
        # http://mathworld.wolfram.com/DiskPointPicking.html
        rng = sampler.sample(n, 2, random)
        r, theta = rng[:, 0], 2 * np.pi * rng[:, 1]
        x = np.sqrt(r) * np.cos(theta)
        y = np.sqrt(r) * np.sin(theta)
        return self.radius * np.stack((x, y), axis=1) + self.center

    def uniform_boundary_points(self, n):
        theta = np.linspace(
            0, 2 * np.pi, num=n, endpoint=False, dtype=paddle.get_default_dtype()
        )
        X = np.stack((np.cos(theta), np.sin(theta)), axis=1)
        return self.radius * X + self.center

    def random_boundary_points(self, n, random="pseudo"):
        theta = 2 * np.pi * sampler.sample(n, 1, random)
        X = np.concatenate((np.cos(theta), np.sin(theta)), axis=1)
        return self.radius * X + self.center

    def sdf_func(self, points: np.ndarray) -> np.ndarray:
        """Compute signed distance field.

        Args:
            points (np.ndarray): The coordinate points used to calculate the SDF value,
                the shape is [N, 2]

        Returns:
            np.ndarray: SDF values of input points without squared, the shape is [N, 1].

        NOTE: This function usually returns ndarray with negative values, because
        according to the definition of SDF, the SDF value of the coordinate point inside
        the object(interior points) is negative, the outside is positive, and the edge
        is 0. Therefore, when used for weighting, a negative sign is often added before
        the result of this function.
        """
        if points.shape[1] != self.ndim:
            raise ValueError(
                f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
            )
        sdf = self.radius - np.linalg.norm(points - self.center, axis=1)
        sdf = -sdf[..., np.newaxis]
        return sdf
sdf_func(points)

Compute signed distance field.

Parameters:

Name Type Description Default
points ndarray

The coordinate points used to calculate the SDF value, the shape is [N, 2]

required

Returns:

Type Description
ndarray

np.ndarray: SDF values of input points without squared, the shape is [N, 1].

NOTE: This function usually returns ndarray with negative values, because according to the definition of SDF, the SDF value of the coordinate point inside the object(interior points) is negative, the outside is positive, and the edge is 0. Therefore, when used for weighting, a negative sign is often added before the result of this function.

Source code in ppsci/geometry/geometry_2d.py
def sdf_func(self, points: np.ndarray) -> np.ndarray:
    """Compute signed distance field.

    Args:
        points (np.ndarray): The coordinate points used to calculate the SDF value,
            the shape is [N, 2]

    Returns:
        np.ndarray: SDF values of input points without squared, the shape is [N, 1].

    NOTE: This function usually returns ndarray with negative values, because
    according to the definition of SDF, the SDF value of the coordinate point inside
    the object(interior points) is negative, the outside is positive, and the edge
    is 0. Therefore, when used for weighting, a negative sign is often added before
    the result of this function.
    """
    if points.shape[1] != self.ndim:
        raise ValueError(
            f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
        )
    sdf = self.radius - np.linalg.norm(points - self.center, axis=1)
    sdf = -sdf[..., np.newaxis]
    return sdf

Hypercube

Bases: Geometry

Multi-dimensional hyper cube.

Parameters:

Name Type Description Default
xmin Tuple[float, ...]

Lower corner point.

required
xmax Tuple[float, ...]

Upper corner point.

required

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.Hypercube((0, 0, 0, 0), (1, 1, 1, 1))
Source code in ppsci/geometry/geometry_nd.py
class Hypercube(geometry.Geometry):
    """Multi-dimensional hyper cube.

    Args:
        xmin (Tuple[float, ...]): Lower corner point.
        xmax (Tuple[float, ...]): Upper corner point.

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.Hypercube((0, 0, 0, 0), (1, 1, 1, 1))
    """

    def __init__(self, xmin: Tuple[float, ...], xmax: Tuple[float, ...]):
        if len(xmin) != len(xmax):
            raise ValueError("Dimensions of xmin and xmax do not match.")

        self.xmin = np.array(xmin, dtype=paddle.get_default_dtype())
        self.xmax = np.array(xmax, dtype=paddle.get_default_dtype())
        if np.any(self.xmin >= self.xmax):
            raise ValueError("xmin >= xmax")

        self.side_length = self.xmax - self.xmin
        super().__init__(
            len(xmin), (self.xmin, self.xmax), np.linalg.norm(self.side_length)
        )
        self.volume = np.prod(self.side_length, dtype=paddle.get_default_dtype())

    def is_inside(self, x):
        return np.logical_and(
            np.all(x >= self.xmin, axis=-1), np.all(x <= self.xmax, axis=-1)
        )

    def on_boundary(self, x):
        _on_boundary = np.logical_or(
            np.any(np.isclose(x, self.xmin), axis=-1),
            np.any(np.isclose(x, self.xmax), axis=-1),
        )
        return np.logical_and(self.is_inside(x), _on_boundary)

    def boundary_normal(self, x):
        _n = -np.isclose(x, self.xmin).astype(paddle.get_default_dtype()) + np.isclose(
            x, self.xmax
        )
        # For vertices, the normal is averaged for all directions
        idx = np.count_nonzero(_n, axis=-1) > 1
        if np.any(idx):
            l = np.linalg.norm(_n[idx], axis=-1, keepdims=True)
            _n[idx] /= l
        return _n

    def uniform_points(self, n, boundary=True):
        dx = (self.volume / n) ** (1 / self.ndim)
        xi = []
        for i in range(self.ndim):
            ni = int(np.ceil(self.side_length[i] / dx))
            if boundary:
                xi.append(
                    np.linspace(
                        self.xmin[i],
                        self.xmax[i],
                        num=ni,
                        dtype=paddle.get_default_dtype(),
                    )
                )
            else:
                xi.append(
                    np.linspace(
                        self.xmin[i],
                        self.xmax[i],
                        num=ni + 1,
                        endpoint=False,
                        dtype=paddle.get_default_dtype(),
                    )[1:]
                )
        x = np.array(list(itertools.product(*xi)), dtype=paddle.get_default_dtype())
        if len(x) > n:
            x = x[0:n]
        return x

    def random_points(self, n, random="pseudo"):
        x = sampler.sample(n, self.ndim, random)
        # print(f"Hypercube's range: {self.__class__.__name__}", self.xmin, self.xmax)
        return (self.xmax - self.xmin) * x + self.xmin

    def random_boundary_points(self, n, random="pseudo"):
        x = sampler.sample(n, self.ndim, random)
        # Randomly pick a dimension
        rand_dim = np.random.randint(self.ndim, size=n)
        # Replace value of the randomly picked dimension with the nearest boundary value (0 or 1)
        x[np.arange(n), rand_dim] = np.round(x[np.arange(n), rand_dim])
        return (self.xmax - self.xmin) * x + self.xmin

    def periodic_point(self, x, component):
        y = misc.convert_to_array(x, self.dim_keys)
        _on_xmin = np.isclose(y[:, component], self.xmin[component])
        _on_xmax = np.isclose(y[:, component], self.xmax[component])
        y[:, component][_on_xmin] = self.xmax[component]
        y[:, component][_on_xmax] = self.xmin[component]
        y_normal = self.boundary_normal(y)

        y = misc.convert_to_dict(y, self.dim_keys)
        y_normal = misc.convert_to_dict(
            y_normal, [f"normal_{k}" for k in self.dim_keys]
        )
        return {**y, **y_normal}

Hypersphere

Bases: Geometry

Multi-dimensional hyper sphere.

Parameters:

Name Type Description Default
center Tuple[float, ...]

Center point coordinate.

required
radius Tuple[float, ...]

Radius along each dimension.

required

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.Hypersphere((0, 0, 0, 0), 1.0)
Source code in ppsci/geometry/geometry_nd.py
class Hypersphere(geometry.Geometry):
    """Multi-dimensional hyper sphere.

    Args:
        center (Tuple[float, ...]): Center point coordinate.
        radius (Tuple[float, ...]): Radius along each dimension.

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.Hypersphere((0, 0, 0, 0), 1.0)
    """

    def __init__(self, center, radius):
        self.center = np.array(center, dtype=paddle.get_default_dtype())
        self.radius = radius
        super().__init__(
            len(center), (self.center - radius, self.center + radius), 2 * radius
        )

        self._r2 = radius**2

    def is_inside(self, x):
        return np.linalg.norm(x - self.center, axis=-1) <= self.radius

    def on_boundary(self, x):
        return np.isclose(np.linalg.norm(x - self.center, axis=-1), self.radius)

    def boundary_normal(self, x):
        _n = x - self.center
        l = np.linalg.norm(_n, axis=-1, keepdims=True)
        _n = _n / l * np.isclose(l, self.radius)
        return _n

    def random_points(self, n, random="pseudo"):
        # https://math.stackexchange.com/questions/87230/picking-random-points-in-the-volume-of-sphere-with-uniform-probability
        if random == "pseudo":
            U = np.random.rand(n, 1).astype(paddle.get_default_dtype())
            X = np.random.normal(size=(n, self.ndim)).astype(paddle.get_default_dtype())
        else:
            rng = sampler.sample(n, self.ndim + 1, random)
            U, X = rng[:, 0:1], rng[:, 1:]  # Error if X = [0, 0, ...]
            X = stats.norm.ppf(X).astype(paddle.get_default_dtype())
        X = preprocessing.normalize(X)
        X = U ** (1 / self.ndim) * X
        return self.radius * X + self.center

    def random_boundary_points(self, n, random="pseudo"):
        # http://mathworld.wolfram.com/HyperspherePointPicking.html
        if random == "pseudo":
            X = np.random.normal(size=(n, self.ndim)).astype(paddle.get_default_dtype())
        else:
            U = sampler.sample(
                n, self.ndim, random
            )  # Error for [0, 0, ...] or [0.5, 0.5, ...]
            X = stats.norm.ppf(U).astype(paddle.get_default_dtype())
        X = preprocessing.normalize(X)
        return self.radius * X + self.center

Interval

Bases: Geometry

Class for interval.

Parameters:

Name Type Description Default
l float

Left position of interval.

required
r float

Right position of interval.

required

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.Interval(-1, 1)
Source code in ppsci/geometry/geometry_1d.py
class Interval(geometry.Geometry):
    """Class for interval.

    Args:
        l (float): Left position of interval.
        r (float): Right position of interval.

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.Interval(-1, 1)
    """

    def __init__(self, l: float, r: float):
        super().__init__(1, (np.array([[l]]), np.array([[r]])), r - l)
        self.l = l
        self.r = r

    def is_inside(self, x: np.ndarray):
        return ((self.l <= x) & (x <= self.r)).flatten()

    def on_boundary(self, x: np.ndarray):
        return (np.isclose(x, self.l) | np.isclose(x, self.r)).flatten()

    def boundary_normal(self, x: np.ndarray):
        return -np.isclose(x, self.l).astype(paddle.get_default_dtype()) + np.isclose(
            x, self.r
        ).astype(paddle.get_default_dtype())

    def uniform_points(self, n: int, boundary: bool = True):
        if boundary:
            return np.linspace(
                self.l, self.r, n, dtype=paddle.get_default_dtype()
            ).reshape([-1, 1])
        return np.linspace(
            self.l, self.r, n + 1, endpoint=False, dtype=paddle.get_default_dtype()
        )[1:].reshape([-1, 1])

    def random_points(self, n: int, random: str = "pseudo"):
        x = sample(n, 1, random)
        return (self.l + x * self.diam).astype(paddle.get_default_dtype())

    def uniform_boundary_points(self, n: int):
        if n == 1:
            return np.array([[self.l]], dtype=paddle.get_default_dtype())
        xl = np.full([n // 2, 1], self.l, dtype=paddle.get_default_dtype())
        xr = np.full([n - n // 2, 1], self.r, dtype=paddle.get_default_dtype())
        return np.concatenate((xl, xr), axis=0)

    def random_boundary_points(self, n: int, random: str = "pseudo"):
        if n == 2:
            return np.array([[self.l], [self.r]], dtype=paddle.get_default_dtype())
        return (
            np.random.choice([self.l, self.r], n)
            .reshape([-1, 1])
            .astype(paddle.get_default_dtype())
        )

    def periodic_point(self, x: np.ndarray, component: int = 0):
        x_array = misc.convert_to_array(x, self.dim_keys)
        periodic_x = x_array
        periodic_x[np.isclose(x_array, self.l)] = self.r
        periodic_x[np.isclose(x_array, self.r)] = self.l
        periodic_x_normal = self.boundary_normal(periodic_x)

        periodic_x = misc.convert_to_dict(periodic_x, self.dim_keys)
        periodic_x_normal = misc.convert_to_dict(
            periodic_x_normal, [f"normal_{k}" for k in self.dim_keys]
        )
        return {**periodic_x, **periodic_x_normal}

    def sdf_func(self, points: np.ndarray) -> np.ndarray:
        """Compute signed distance field

        Args:
            points (np.ndarray): The coordinate points used to calculate the SDF value,
                the shape is [N, 1]

        Returns:
            np.ndarray: SDF values of input points without squared, the shape is [N, 1].

        NOTE: This function usually returns ndarray with negative values, because
        according to the definition of SDF, the SDF value of the coordinate point inside
        the object(interior points) is negative, the outside is positive, and the edge
        is 0. Therefore, when used for weighting, a negative sign is often added before
        the result of this function.
        """
        if points.shape[1] != self.ndim:
            raise ValueError(
                f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
            )
        return -((self.r - self.l) / 2 - np.abs(points - (self.l + self.r) / 2))
sdf_func(points)

Compute signed distance field

Parameters:

Name Type Description Default
points ndarray

The coordinate points used to calculate the SDF value, the shape is [N, 1]

required

Returns:

Type Description
ndarray

np.ndarray: SDF values of input points without squared, the shape is [N, 1].

NOTE: This function usually returns ndarray with negative values, because according to the definition of SDF, the SDF value of the coordinate point inside the object(interior points) is negative, the outside is positive, and the edge is 0. Therefore, when used for weighting, a negative sign is often added before the result of this function.

Source code in ppsci/geometry/geometry_1d.py
def sdf_func(self, points: np.ndarray) -> np.ndarray:
    """Compute signed distance field

    Args:
        points (np.ndarray): The coordinate points used to calculate the SDF value,
            the shape is [N, 1]

    Returns:
        np.ndarray: SDF values of input points without squared, the shape is [N, 1].

    NOTE: This function usually returns ndarray with negative values, because
    according to the definition of SDF, the SDF value of the coordinate point inside
    the object(interior points) is negative, the outside is positive, and the edge
    is 0. Therefore, when used for weighting, a negative sign is often added before
    the result of this function.
    """
    if points.shape[1] != self.ndim:
        raise ValueError(
            f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
        )
    return -((self.r - self.l) / 2 - np.abs(points - (self.l + self.r) / 2))

Mesh

Bases: Geometry

Class for mesh geometry.

Parameters:

Name Type Description Default
mesh Union[str, Mesh]

Mesh file path or mesh object, such as "/path/to/mesh.stl".

required

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.Mesh("/path/to/mesh.stl")
Source code in ppsci/geometry/mesh.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
class Mesh(geometry.Geometry):
    """Class for mesh geometry.

    Args:
        mesh (Union[str, Mesh]): Mesh file path or mesh object, such as "/path/to/mesh.stl".

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.Mesh("/path/to/mesh.stl")  # doctest: +SKIP
    """

    def __init__(self, mesh: Union["pymesh.Mesh", str]):
        # check if pymesh is installed when using Mesh Class
        if not checker.dynamic_import_to_globals(["pymesh"]):
            raise ImportError(
                "Could not import pymesh python package."
                "Please install it as https://pymesh.readthedocs.io/en/latest/installation.html."
            )
        import pymesh

        if isinstance(mesh, str):
            self.py_mesh = pymesh.meshio.load_mesh(mesh)
        elif isinstance(mesh, pymesh.Mesh):
            self.py_mesh = mesh
        else:
            raise ValueError("arg `mesh` should be path string or `pymesh.Mesh`")

        self.init_mesh()

    @classmethod
    def from_pymesh(cls, mesh: "pymesh.Mesh") -> "Mesh":
        """Instantiate Mesh object with given PyMesh object.

        Args:
            mesh (pymesh.Mesh): PyMesh object.

        Returns:
            Mesh: Instantiated ppsci.geometry.Mesh object.

        Examples:
            >>> import ppsci
            >>> import pymesh  # doctest: +SKIP
            >>> import numpy as np  # doctest: +SKIP
            >>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))  # doctest: +SKIP
            >>> mesh = ppsci.geometry.Mesh.from_pymesh(box)  # doctest: +SKIP
            >>> print(mesh.vertices)  # doctest: +SKIP
            [[0. 0. 0.]
             [1. 0. 0.]
             [1. 1. 0.]
             [0. 1. 0.]
             [0. 0. 1.]
             [1. 0. 1.]
             [1. 1. 1.]
             [0. 1. 1.]]
        """
        # check if pymesh is installed when using Mesh Class
        if not checker.dynamic_import_to_globals(["pymesh"]):
            raise ImportError(
                "Could not import pymesh python package."
                "Please install it as https://pymesh.readthedocs.io/en/latest/installation.html."
            )
        import pymesh

        if isinstance(mesh, pymesh.Mesh):
            return cls(mesh)
        else:
            raise ValueError(
                f"arg `mesh` should be type of `pymesh.Mesh`, but got {type(mesh)}"
            )

    def init_mesh(self):
        """Initialize necessary variables for mesh"""
        if "face_normal" not in self.py_mesh.get_attribute_names():
            self.py_mesh.add_attribute("face_normal")
        self.face_normal = self.py_mesh.get_attribute("face_normal").reshape([-1, 3])

        if not checker.dynamic_import_to_globals(["open3d"]):
            raise ImportError(
                "Could not import open3d python package. "
                "Please install it with `pip install open3d`."
            )
        import open3d

        self.open3d_mesh = open3d.geometry.TriangleMesh(
            open3d.utility.Vector3dVector(np.array(self.py_mesh.vertices)),
            open3d.utility.Vector3iVector(np.array(self.py_mesh.faces)),
        )
        self.open3d_mesh.compute_vertex_normals()

        self.vertices = self.py_mesh.vertices
        self.faces = self.py_mesh.faces
        self.vectors = self.vertices[self.faces]
        super().__init__(
            self.vertices.shape[-1],
            (np.amin(self.vertices, axis=0), np.amax(self.vertices, axis=0)),
            np.inf,
        )
        self.v0 = self.vectors[:, 0]
        self.v1 = self.vectors[:, 1]
        self.v2 = self.vectors[:, 2]
        self.num_vertices = self.py_mesh.num_vertices
        self.num_faces = self.py_mesh.num_faces

        if not checker.dynamic_import_to_globals(["pysdf"]):
            raise ImportError(
                "Could not import pysdf python package. "
                "Please install open3d with `pip install pysdf`."
            )
        import pysdf

        self.pysdf = pysdf.SDF(self.vertices, self.faces)
        self.bounds = (
            ((np.min(self.vectors[:, :, 0])), np.max(self.vectors[:, :, 0])),
            ((np.min(self.vectors[:, :, 1])), np.max(self.vectors[:, :, 1])),
            ((np.min(self.vectors[:, :, 2])), np.max(self.vectors[:, :, 2])),
        )

    def sdf_func(self, points: np.ndarray) -> np.ndarray:
        """Compute signed distance field.

        Args:
            points (np.ndarray): The coordinate points used to calculate the SDF value,
                the shape is [N, 3]

        Returns:
            np.ndarray: SDF values of input points without squared, the shape is [N, 1].

        NOTE: This function usually returns ndarray with negative values, because
        according to the definition of SDF, the SDF value of the coordinate point inside
        the object(interior points) is negative, the outside is positive, and the edge
        is 0. Therefore, when used for weighting, a negative sign is often added before
        the result of this function.
        """
        if not checker.dynamic_import_to_globals(["pymesh"]):
            raise ImportError(
                "Could not import pymesh python package."
                "Please install it as https://pymesh.readthedocs.io/en/latest/installation.html."
            )
        import pymesh

        sdf, _, _, _ = pymesh.signed_distance_to_mesh(self.py_mesh, points)
        sdf = sdf[..., np.newaxis].astype(paddle.get_default_dtype())
        return sdf

    def is_inside(self, x):
        # NOTE: point on boundary is included
        return self.pysdf.contains(x)

    def on_boundary(self, x):
        return np.isclose(self.sdf_func(x), 0.0).ravel()

    def translate(self, translation: np.ndarray, relative: bool = True) -> "Mesh":
        """Translate by given offsets.

        NOTE: This API generate a completely new Mesh object with translated geometry,
        without modifying original Mesh object inplace.

        Args:
            translation (np.ndarray): Translation offsets, numpy array of shape (3,):
                [offset_x, offset_y, offset_z].
            relative (bool, optional): Whether translate relatively. Defaults to True.

        Returns:
            Mesh: Translated Mesh object.

        Examples:
            >>> import ppsci
            >>> import pymesh  # doctest: +SKIP
            >>> import numpy as np
            >>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))  # doctest: +SKIP
            >>> mesh = ppsci.geometry.Mesh(box)  # doctest: +SKIP
            >>> print(mesh.vertices)  # doctest: +SKIP
            [[0. 0. 0.]
             [1. 0. 0.]
             [1. 1. 0.]
             [0. 1. 0.]
             [0. 0. 1.]
             [1. 0. 1.]
             [1. 1. 1.]
             [0. 1. 1.]]
            >>> print(mesh.translate((-0.5, 0, 0.5), False).vertices) # the center is moved to the translation vector.  # doctest: +SKIP
            [[-1.  -0.5  0. ]
             [ 0.  -0.5  0. ]
             [ 0.   0.5  0. ]
             [-1.   0.5  0. ]
             [-1.  -0.5  1. ]
             [ 0.  -0.5  1. ]
             [ 0.   0.5  1. ]
             [-1.   0.5  1. ]]
            >>> print(mesh.translate((-0.5, 0, 0.5), True).vertices) # the translation vector is directly added to the geometry coordinates  # doctest: +SKIP
            [[-0.5  0.   0.5]
             [ 0.5  0.   0.5]
             [ 0.5  1.   0.5]
             [-0.5  1.   0.5]
             [-0.5  0.   1.5]
             [ 0.5  0.   1.5]
             [ 0.5  1.   1.5]
             [-0.5  1.   1.5]]
        """
        vertices = np.array(self.vertices, dtype=paddle.get_default_dtype())
        faces = np.array(self.faces)

        if not checker.dynamic_import_to_globals(("open3d", "pymesh")):
            raise ImportError(
                "Could not import open3d and pymesh python package. "
                "Please install open3d with `pip install open3d` and "
                "pymesh as https://paddlescience-docs.readthedocs.io/zh/latest/zh/install_setup/#__tabbed_4_1"
            )
        import open3d  # isort:skip
        import pymesh  # isort:skip

        open3d_mesh = open3d.geometry.TriangleMesh(
            open3d.utility.Vector3dVector(vertices),
            open3d.utility.Vector3iVector(faces),
        )
        open3d_mesh = open3d_mesh.translate(translation, relative)
        translated_mesh = pymesh.form_mesh(
            np.asarray(open3d_mesh.vertices, dtype=paddle.get_default_dtype()), faces
        )
        # Generate a new Mesh object using class method
        return Mesh.from_pymesh(translated_mesh)

    def scale(
        self, scale: float, center: Tuple[float, float, float] = (0, 0, 0)
    ) -> "Mesh":
        """Scale by given scale coefficient and center coordinate.

        NOTE: This API generate a completely new Mesh object with scaled geometry,
        without modifying original Mesh object inplace.

        Args:
            scale (float): Scale coefficient.
            center (Tuple[float,float,float], optional): Center coordinate, [x, y, z].
                Defaults to (0, 0, 0).

        Returns:
            Mesh: Scaled Mesh object.

        Examples:
            >>> import ppsci
            >>> import pymesh  # doctest: +SKIP
            >>> import numpy as np
            >>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))  # doctest: +SKIP
            >>> mesh = ppsci.geometry.Mesh(box)  # doctest: +SKIP
            >>> print(mesh.vertices)  # doctest: +SKIP
            [[0. 0. 0.]
             [1. 0. 0.]
             [1. 1. 0.]
             [0. 1. 0.]
             [0. 0. 1.]
             [1. 0. 1.]
             [1. 1. 1.]
             [0. 1. 1.]]
            >>> mesh = mesh.scale(2, (0.25, 0.5, 0.75))  # doctest: +SKIP
            >>> print(mesh.vertices)  # doctest: +SKIP
            [[-0.25 -0.5  -0.75]
             [ 1.75 -0.5  -0.75]
             [ 1.75  1.5  -0.75]
             [-0.25  1.5  -0.75]
             [-0.25 -0.5   1.25]
             [ 1.75 -0.5   1.25]
             [ 1.75  1.5   1.25]
             [-0.25  1.5   1.25]]
        """
        vertices = np.array(self.vertices, dtype=paddle.get_default_dtype())
        faces = np.array(self.faces, dtype=paddle.get_default_dtype())

        if not checker.dynamic_import_to_globals(("open3d", "pymesh")):
            raise ImportError(
                "Could not import open3d and pymesh python package. "
                "Please install open3d with `pip install open3d` and "
                "pymesh as https://pymesh.readthedocs.io/en/latest/installation.html."
            )
        import open3d  # isort:skip
        import pymesh  # isort:skip

        open3d_mesh = open3d.geometry.TriangleMesh(
            open3d.utility.Vector3dVector(vertices),
            open3d.utility.Vector3iVector(faces),
        )
        open3d_mesh = open3d_mesh.scale(scale, center)
        scaled_pymesh = pymesh.form_mesh(
            np.asarray(open3d_mesh.vertices, dtype=paddle.get_default_dtype()), faces
        )
        # Generate a new Mesh object using class method
        return Mesh.from_pymesh(scaled_pymesh)

    def uniform_boundary_points(self, n: int):
        """Compute the equi-spaced points on the boundary."""
        return self.pysdf.sample_surface(n)

    def inflated_random_points(self, n, distance, random="pseudo", criteria=None):
        if not isinstance(n, (tuple, list)):
            n = [n]
        if not isinstance(distance, (tuple, list)):
            distance = [distance]
        if len(n) != len(distance):
            raise ValueError(
                f"len(n)({len(n)}) should be equal to len(distance)({len(distance)})"
            )

        from ppsci.geometry import inflation

        all_points = []
        all_areas = []
        for _n, _dist in zip(n, distance):
            inflated_mesh = Mesh(inflation.pymesh_inflation(self.py_mesh, _dist))
            points, areas = inflated_mesh.random_points(_n, random, criteria)
            all_points.append(points)
            all_areas.append(areas)

        all_points = np.concatenate(all_points, axis=0)
        all_areas = np.concatenate(all_areas, axis=0)
        return all_points, all_areas

    def _approximate_area(
        self,
        random: Literal["pseudo"] = "pseudo",
        criteria: Optional[Callable] = None,
        n_appr: int = 10000,
    ) -> float:
        """Approximate area with given `criteria` and `n_appr` points by Monte Carlo
        algorithm.

        Args:
            random (str, optional): Random method. Defaults to "pseudo".
            criteria (Optional[Callable]): Criteria function. Defaults to None.
            n_appr (int): Number of points for approximating area. Defaults to 10000.

        Returns:
            float: Approximation area with given criteria.
        """
        triangle_areas = area_of_triangles(self.v0, self.v1, self.v2)
        triangle_probabilities = triangle_areas / np.linalg.norm(triangle_areas, ord=1)
        triangle_index = np.arange(triangle_probabilities.shape[0])
        npoint_per_triangle = np.random.choice(
            triangle_index, n_appr, p=triangle_probabilities
        )
        npoint_per_triangle, _ = np.histogram(
            npoint_per_triangle,
            np.arange(triangle_probabilities.shape[0] + 1) - 0.5,
        )

        appr_areas = []
        if criteria is not None:
            aux_points = []

        for i, npoint in enumerate(npoint_per_triangle):
            if npoint == 0:
                continue
            # sample points for computing criteria mask if criteria is given
            if criteria is not None:
                points_at_triangle_i = sample_in_triangle(
                    self.v0[i], self.v1[i], self.v2[i], npoint, random
                )
                aux_points.append(points_at_triangle_i)

            appr_areas.append(
                np.full(
                    (npoint, 1), triangle_areas[i] / npoint, paddle.get_default_dtype()
                )
            )
        appr_areas = np.concatenate(appr_areas, axis=0)  # [n_appr, 1]

        # set invalid area to 0 by computing criteria mask with auxiliary points
        if criteria is not None:
            aux_points = np.concatenate(aux_points, axis=0)  # [n_appr, 3]
            criteria_mask = criteria(*np.split(aux_points, self.ndim, 1))
            appr_areas *= criteria_mask
        return appr_areas.sum()

    def random_boundary_points(self, n, random="pseudo"):
        triangle_area = area_of_triangles(self.v0, self.v1, self.v2)
        triangle_prob = triangle_area / np.linalg.norm(triangle_area, ord=1)
        npoint_per_triangle = np.random.choice(
            np.arange(len(triangle_prob)), n, p=triangle_prob
        )
        npoint_per_triangle, _ = np.histogram(
            npoint_per_triangle, np.arange(len(triangle_prob) + 1) - 0.5
        )

        points = []
        normal = []
        areas = []
        for i, npoint in enumerate(npoint_per_triangle):
            if npoint == 0:
                continue
            points_at_triangle_i = sample_in_triangle(
                self.v0[i], self.v1[i], self.v2[i], npoint, random
            )
            normal_at_triangle_i = np.tile(self.face_normal[i], (npoint, 1)).astype(
                paddle.get_default_dtype()
            )
            areas_at_triangle_i = np.full(
                (npoint, 1),
                triangle_area[i] / npoint,
                dtype=paddle.get_default_dtype(),
            )

            points.append(points_at_triangle_i)
            normal.append(normal_at_triangle_i)
            areas.append(areas_at_triangle_i)

        points = np.concatenate(points, axis=0)
        normal = np.concatenate(normal, axis=0)
        areas = np.concatenate(areas, axis=0)

        return points, normal, areas

    def sample_boundary(
        self,
        n: int,
        random: Literal["pseudo"] = "pseudo",
        criteria: Optional[Callable[..., np.ndarray]] = None,
        evenly: bool = False,
        inflation_dist: Union[float, Tuple[float, ...]] = None,
    ) -> Dict[str, np.ndarray]:
        # TODO(sensen): Support for time-dependent points(repeat data in time)
        if inflation_dist is not None:
            if not isinstance(n, (tuple, list)):
                n = [n]
            if not isinstance(inflation_dist, (tuple, list)):
                inflation_dist = [inflation_dist]
            if len(n) != len(inflation_dist):
                raise ValueError(
                    f"len(n)({len(n)}) should be equal to len(inflation_dist)({len(inflation_dist)})"
                )

            from ppsci.geometry import inflation

            inflated_data_dict = {}
            for _n, _dist in zip(n, inflation_dist):
                # 1. manually inflate mesh at first
                inflated_mesh = Mesh(inflation.pymesh_inflation(self.py_mesh, _dist))
                # 2. compute all data by sample_boundary with `inflation_dist=None`
                data_dict = inflated_mesh.sample_boundary(
                    _n,
                    random,
                    criteria,
                    evenly,
                    inflation_dist=None,
                )
                for key, value in data_dict.items():
                    if key not in inflated_data_dict:
                        inflated_data_dict[key] = value
                    else:
                        inflated_data_dict[key] = np.concatenate(
                            (inflated_data_dict[key], value), axis=0
                        )
            return inflated_data_dict
        else:
            if evenly:
                raise ValueError(
                    "Can't sample evenly on mesh now, please set evenly=False."
                )
            _size, _ntry, _nsuc = 0, 0, 0
            all_points = []
            all_normal = []
            while _size < n:
                points, normal, _ = self.random_boundary_points(n, random)
                if criteria is not None:
                    criteria_mask = criteria(
                        *np.split(points, self.ndim, axis=1)
                    ).ravel()
                    points = points[criteria_mask]
                    normal = normal[criteria_mask]

                if len(points) > n - _size:
                    points = points[: n - _size]
                    normal = normal[: n - _size]

                all_points.append(points)
                all_normal.append(normal)

                _size += len(points)
                _ntry += 1
                if len(points) > 0:
                    _nsuc += 1

                if _ntry >= 1000 and _nsuc == 0:
                    raise ValueError(
                        "Sample boundary points failed, "
                        "please check correctness of geometry and given criteria."
                    )

            all_points = np.concatenate(all_points, axis=0)
            all_normal = np.concatenate(all_normal, axis=0)
            appr_area = self._approximate_area(random, criteria)
            all_areas = np.full((n, 1), appr_area / n, paddle.get_default_dtype())

        x_dict = misc.convert_to_dict(all_points, self.dim_keys)
        normal_dict = misc.convert_to_dict(
            all_normal, [f"normal_{key}" for key in self.dim_keys if key != "t"]
        )
        area_dict = misc.convert_to_dict(all_areas, ["area"])
        return {**x_dict, **normal_dict, **area_dict}

    def random_points(self, n, random="pseudo", criteria=None):
        _size = 0
        all_points = []
        cuboid = geometry_3d.Cuboid(
            [bound[0] for bound in self.bounds],
            [bound[1] for bound in self.bounds],
        )
        _nsample, _nvalid = 0, 0
        while _size < n:
            random_points = cuboid.random_points(n, random)
            valid_mask = self.is_inside(random_points)

            if criteria:
                valid_mask &= criteria(
                    *np.split(random_points, self.ndim, axis=1)
                ).ravel()
            valid_points = random_points[valid_mask]
            _nvalid += len(valid_points)

            if len(valid_points) > n - _size:
                valid_points = valid_points[: n - _size]

            all_points.append(valid_points)
            _size += len(valid_points)
            _nsample += n

        all_points = np.concatenate(all_points, axis=0)
        cuboid_volume = np.prod([b[1] - b[0] for b in self.bounds])
        all_areas = np.full(
            (n, 1), cuboid_volume * (_nvalid / _nsample) / n, paddle.get_default_dtype()
        )
        return all_points, all_areas

    def sample_interior(
        self,
        n: int,
        random: Literal["pseudo"] = "pseudo",
        criteria: Optional[Callable[..., np.ndarray]] = None,
        evenly: bool = False,
        compute_sdf_derivatives: bool = False,
    ):
        """
        Sample random points in the geometry and return those meet criteria.

        NOTE: sdf values returned by this function are negated because the weight in
        loss function should be positive.
        """
        if evenly:
            # TODO(sensen): Implement uniform sample for mesh interior.
            raise NotImplementedError(
                "uniformly sample for interior in mesh is not support yet, "
                "you may need to set evenly=False in config dict of constraint"
            )
        points, areas = self.random_points(n, random, criteria)

        x_dict = misc.convert_to_dict(points, self.dim_keys)
        area_dict = misc.convert_to_dict(areas, ("area",))

        # NOTE: add negative to the sdf values because weight should be positive.
        sdf = -self.sdf_func(points)
        sdf_dict = misc.convert_to_dict(sdf, ("sdf",))

        sdf_derives_dict = {}
        if compute_sdf_derivatives:
            sdf_derives = -self.sdf_derivatives(points)
            sdf_derives_dict = misc.convert_to_dict(
                sdf_derives, tuple(f"sdf__{key}" for key in self.dim_keys)
            )

        return {**x_dict, **area_dict, **sdf_dict, **sdf_derives_dict}

    def union(self, other: "Mesh"):
        if not checker.dynamic_import_to_globals(["pymesh"]):
            raise ImportError(
                "Could not import pymesh python package. "
                "Please install it as https://pymesh.readthedocs.io/en/latest/installation.html."
            )
        import pymesh

        csg = pymesh.CSGTree(
            {"union": [{"mesh": self.py_mesh}, {"mesh": other.py_mesh}]}
        )
        return Mesh(csg.mesh)

    def __or__(self, other: "Mesh"):
        return self.union(other)

    def __add__(self, other: "Mesh"):
        return self.union(other)

    def difference(self, other: "Mesh"):
        if not checker.dynamic_import_to_globals(["pymesh"]):
            raise ImportError(
                "Could not import pymesh python package. "
                "Please install it as https://pymesh.readthedocs.io/en/latest/installation.html."
            )
        import pymesh

        csg = pymesh.CSGTree(
            {"difference": [{"mesh": self.py_mesh}, {"mesh": other.py_mesh}]}
        )
        return Mesh(csg.mesh)

    def __sub__(self, other: "Mesh"):
        return self.difference(other)

    def intersection(self, other: "Mesh"):
        if not checker.dynamic_import_to_globals(["pymesh"]):
            raise ImportError(
                "Could not import pymesh python package. "
                "Please install it as https://pymesh.readthedocs.io/en/latest/installation.html."
            )
        import pymesh

        csg = pymesh.CSGTree(
            {"intersection": [{"mesh": self.py_mesh}, {"mesh": other.py_mesh}]}
        )
        return Mesh(csg.mesh)

    def __and__(self, other: "Mesh"):
        return self.intersection(other)

    def __str__(self) -> str:
        """Return the name of class"""
        return ", ".join(
            [
                self.__class__.__name__,
                f"num_vertices = {self.num_vertices}",
                f"num_faces = {self.num_faces}",
                f"bounds = {self.bounds}",
                f"dim_keys = {self.dim_keys}",
            ]
        )
__str__()

Return the name of class

Source code in ppsci/geometry/mesh.py
def __str__(self) -> str:
    """Return the name of class"""
    return ", ".join(
        [
            self.__class__.__name__,
            f"num_vertices = {self.num_vertices}",
            f"num_faces = {self.num_faces}",
            f"bounds = {self.bounds}",
            f"dim_keys = {self.dim_keys}",
        ]
    )
from_pymesh(mesh) classmethod

Instantiate Mesh object with given PyMesh object.

Parameters:

Name Type Description Default
mesh Mesh

PyMesh object.

required

Returns:

Name Type Description
Mesh 'Mesh'

Instantiated ppsci.geometry.Mesh object.

Examples:

>>> import ppsci
>>> import pymesh
>>> import numpy as np
>>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))
>>> mesh = ppsci.geometry.Mesh.from_pymesh(box)
>>> print(mesh.vertices)
[[0. 0. 0.]
 [1. 0. 0.]
 [1. 1. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [1. 0. 1.]
 [1. 1. 1.]
 [0. 1. 1.]]
Source code in ppsci/geometry/mesh.py
@classmethod
def from_pymesh(cls, mesh: "pymesh.Mesh") -> "Mesh":
    """Instantiate Mesh object with given PyMesh object.

    Args:
        mesh (pymesh.Mesh): PyMesh object.

    Returns:
        Mesh: Instantiated ppsci.geometry.Mesh object.

    Examples:
        >>> import ppsci
        >>> import pymesh  # doctest: +SKIP
        >>> import numpy as np  # doctest: +SKIP
        >>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))  # doctest: +SKIP
        >>> mesh = ppsci.geometry.Mesh.from_pymesh(box)  # doctest: +SKIP
        >>> print(mesh.vertices)  # doctest: +SKIP
        [[0. 0. 0.]
         [1. 0. 0.]
         [1. 1. 0.]
         [0. 1. 0.]
         [0. 0. 1.]
         [1. 0. 1.]
         [1. 1. 1.]
         [0. 1. 1.]]
    """
    # check if pymesh is installed when using Mesh Class
    if not checker.dynamic_import_to_globals(["pymesh"]):
        raise ImportError(
            "Could not import pymesh python package."
            "Please install it as https://pymesh.readthedocs.io/en/latest/installation.html."
        )
    import pymesh

    if isinstance(mesh, pymesh.Mesh):
        return cls(mesh)
    else:
        raise ValueError(
            f"arg `mesh` should be type of `pymesh.Mesh`, but got {type(mesh)}"
        )
init_mesh()

Initialize necessary variables for mesh

Source code in ppsci/geometry/mesh.py
def init_mesh(self):
    """Initialize necessary variables for mesh"""
    if "face_normal" not in self.py_mesh.get_attribute_names():
        self.py_mesh.add_attribute("face_normal")
    self.face_normal = self.py_mesh.get_attribute("face_normal").reshape([-1, 3])

    if not checker.dynamic_import_to_globals(["open3d"]):
        raise ImportError(
            "Could not import open3d python package. "
            "Please install it with `pip install open3d`."
        )
    import open3d

    self.open3d_mesh = open3d.geometry.TriangleMesh(
        open3d.utility.Vector3dVector(np.array(self.py_mesh.vertices)),
        open3d.utility.Vector3iVector(np.array(self.py_mesh.faces)),
    )
    self.open3d_mesh.compute_vertex_normals()

    self.vertices = self.py_mesh.vertices
    self.faces = self.py_mesh.faces
    self.vectors = self.vertices[self.faces]
    super().__init__(
        self.vertices.shape[-1],
        (np.amin(self.vertices, axis=0), np.amax(self.vertices, axis=0)),
        np.inf,
    )
    self.v0 = self.vectors[:, 0]
    self.v1 = self.vectors[:, 1]
    self.v2 = self.vectors[:, 2]
    self.num_vertices = self.py_mesh.num_vertices
    self.num_faces = self.py_mesh.num_faces

    if not checker.dynamic_import_to_globals(["pysdf"]):
        raise ImportError(
            "Could not import pysdf python package. "
            "Please install open3d with `pip install pysdf`."
        )
    import pysdf

    self.pysdf = pysdf.SDF(self.vertices, self.faces)
    self.bounds = (
        ((np.min(self.vectors[:, :, 0])), np.max(self.vectors[:, :, 0])),
        ((np.min(self.vectors[:, :, 1])), np.max(self.vectors[:, :, 1])),
        ((np.min(self.vectors[:, :, 2])), np.max(self.vectors[:, :, 2])),
    )
sample_interior(n, random='pseudo', criteria=None, evenly=False, compute_sdf_derivatives=False)

Sample random points in the geometry and return those meet criteria.

NOTE: sdf values returned by this function are negated because the weight in loss function should be positive.

Source code in ppsci/geometry/mesh.py
def sample_interior(
    self,
    n: int,
    random: Literal["pseudo"] = "pseudo",
    criteria: Optional[Callable[..., np.ndarray]] = None,
    evenly: bool = False,
    compute_sdf_derivatives: bool = False,
):
    """
    Sample random points in the geometry and return those meet criteria.

    NOTE: sdf values returned by this function are negated because the weight in
    loss function should be positive.
    """
    if evenly:
        # TODO(sensen): Implement uniform sample for mesh interior.
        raise NotImplementedError(
            "uniformly sample for interior in mesh is not support yet, "
            "you may need to set evenly=False in config dict of constraint"
        )
    points, areas = self.random_points(n, random, criteria)

    x_dict = misc.convert_to_dict(points, self.dim_keys)
    area_dict = misc.convert_to_dict(areas, ("area",))

    # NOTE: add negative to the sdf values because weight should be positive.
    sdf = -self.sdf_func(points)
    sdf_dict = misc.convert_to_dict(sdf, ("sdf",))

    sdf_derives_dict = {}
    if compute_sdf_derivatives:
        sdf_derives = -self.sdf_derivatives(points)
        sdf_derives_dict = misc.convert_to_dict(
            sdf_derives, tuple(f"sdf__{key}" for key in self.dim_keys)
        )

    return {**x_dict, **area_dict, **sdf_dict, **sdf_derives_dict}
scale(scale, center=(0, 0, 0))

Scale by given scale coefficient and center coordinate.

NOTE: This API generate a completely new Mesh object with scaled geometry, without modifying original Mesh object inplace.

Parameters:

Name Type Description Default
scale float

Scale coefficient.

required
center Tuple[float, float, float]

Center coordinate, [x, y, z]. Defaults to (0, 0, 0).

(0, 0, 0)

Returns:

Name Type Description
Mesh 'Mesh'

Scaled Mesh object.

Examples:

>>> import ppsci
>>> import pymesh
>>> import numpy as np
>>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))
>>> mesh = ppsci.geometry.Mesh(box)
>>> print(mesh.vertices)
[[0. 0. 0.]
 [1. 0. 0.]
 [1. 1. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [1. 0. 1.]
 [1. 1. 1.]
 [0. 1. 1.]]
>>> mesh = mesh.scale(2, (0.25, 0.5, 0.75))
>>> print(mesh.vertices)
[[-0.25 -0.5  -0.75]
 [ 1.75 -0.5  -0.75]
 [ 1.75  1.5  -0.75]
 [-0.25  1.5  -0.75]
 [-0.25 -0.5   1.25]
 [ 1.75 -0.5   1.25]
 [ 1.75  1.5   1.25]
 [-0.25  1.5   1.25]]
Source code in ppsci/geometry/mesh.py
def scale(
    self, scale: float, center: Tuple[float, float, float] = (0, 0, 0)
) -> "Mesh":
    """Scale by given scale coefficient and center coordinate.

    NOTE: This API generate a completely new Mesh object with scaled geometry,
    without modifying original Mesh object inplace.

    Args:
        scale (float): Scale coefficient.
        center (Tuple[float,float,float], optional): Center coordinate, [x, y, z].
            Defaults to (0, 0, 0).

    Returns:
        Mesh: Scaled Mesh object.

    Examples:
        >>> import ppsci
        >>> import pymesh  # doctest: +SKIP
        >>> import numpy as np
        >>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))  # doctest: +SKIP
        >>> mesh = ppsci.geometry.Mesh(box)  # doctest: +SKIP
        >>> print(mesh.vertices)  # doctest: +SKIP
        [[0. 0. 0.]
         [1. 0. 0.]
         [1. 1. 0.]
         [0. 1. 0.]
         [0. 0. 1.]
         [1. 0. 1.]
         [1. 1. 1.]
         [0. 1. 1.]]
        >>> mesh = mesh.scale(2, (0.25, 0.5, 0.75))  # doctest: +SKIP
        >>> print(mesh.vertices)  # doctest: +SKIP
        [[-0.25 -0.5  -0.75]
         [ 1.75 -0.5  -0.75]
         [ 1.75  1.5  -0.75]
         [-0.25  1.5  -0.75]
         [-0.25 -0.5   1.25]
         [ 1.75 -0.5   1.25]
         [ 1.75  1.5   1.25]
         [-0.25  1.5   1.25]]
    """
    vertices = np.array(self.vertices, dtype=paddle.get_default_dtype())
    faces = np.array(self.faces, dtype=paddle.get_default_dtype())

    if not checker.dynamic_import_to_globals(("open3d", "pymesh")):
        raise ImportError(
            "Could not import open3d and pymesh python package. "
            "Please install open3d with `pip install open3d` and "
            "pymesh as https://pymesh.readthedocs.io/en/latest/installation.html."
        )
    import open3d  # isort:skip
    import pymesh  # isort:skip

    open3d_mesh = open3d.geometry.TriangleMesh(
        open3d.utility.Vector3dVector(vertices),
        open3d.utility.Vector3iVector(faces),
    )
    open3d_mesh = open3d_mesh.scale(scale, center)
    scaled_pymesh = pymesh.form_mesh(
        np.asarray(open3d_mesh.vertices, dtype=paddle.get_default_dtype()), faces
    )
    # Generate a new Mesh object using class method
    return Mesh.from_pymesh(scaled_pymesh)
sdf_func(points)

Compute signed distance field.

Parameters:

Name Type Description Default
points ndarray

The coordinate points used to calculate the SDF value, the shape is [N, 3]

required

Returns:

Type Description
ndarray

np.ndarray: SDF values of input points without squared, the shape is [N, 1].

NOTE: This function usually returns ndarray with negative values, because according to the definition of SDF, the SDF value of the coordinate point inside the object(interior points) is negative, the outside is positive, and the edge is 0. Therefore, when used for weighting, a negative sign is often added before the result of this function.

Source code in ppsci/geometry/mesh.py
def sdf_func(self, points: np.ndarray) -> np.ndarray:
    """Compute signed distance field.

    Args:
        points (np.ndarray): The coordinate points used to calculate the SDF value,
            the shape is [N, 3]

    Returns:
        np.ndarray: SDF values of input points without squared, the shape is [N, 1].

    NOTE: This function usually returns ndarray with negative values, because
    according to the definition of SDF, the SDF value of the coordinate point inside
    the object(interior points) is negative, the outside is positive, and the edge
    is 0. Therefore, when used for weighting, a negative sign is often added before
    the result of this function.
    """
    if not checker.dynamic_import_to_globals(["pymesh"]):
        raise ImportError(
            "Could not import pymesh python package."
            "Please install it as https://pymesh.readthedocs.io/en/latest/installation.html."
        )
    import pymesh

    sdf, _, _, _ = pymesh.signed_distance_to_mesh(self.py_mesh, points)
    sdf = sdf[..., np.newaxis].astype(paddle.get_default_dtype())
    return sdf
translate(translation, relative=True)

Translate by given offsets.

NOTE: This API generate a completely new Mesh object with translated geometry, without modifying original Mesh object inplace.

Parameters:

Name Type Description Default
translation ndarray

Translation offsets, numpy array of shape (3,): [offset_x, offset_y, offset_z].

required
relative bool

Whether translate relatively. Defaults to True.

True

Returns:

Name Type Description
Mesh 'Mesh'

Translated Mesh object.

Examples:

>>> import ppsci
>>> import pymesh
>>> import numpy as np
>>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))
>>> mesh = ppsci.geometry.Mesh(box)
>>> print(mesh.vertices)
[[0. 0. 0.]
 [1. 0. 0.]
 [1. 1. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [1. 0. 1.]
 [1. 1. 1.]
 [0. 1. 1.]]
>>> print(mesh.translate((-0.5, 0, 0.5), False).vertices) # the center is moved to the translation vector.
[[-1.  -0.5  0. ]
 [ 0.  -0.5  0. ]
 [ 0.   0.5  0. ]
 [-1.   0.5  0. ]
 [-1.  -0.5  1. ]
 [ 0.  -0.5  1. ]
 [ 0.   0.5  1. ]
 [-1.   0.5  1. ]]
>>> print(mesh.translate((-0.5, 0, 0.5), True).vertices) # the translation vector is directly added to the geometry coordinates
[[-0.5  0.   0.5]
 [ 0.5  0.   0.5]
 [ 0.5  1.   0.5]
 [-0.5  1.   0.5]
 [-0.5  0.   1.5]
 [ 0.5  0.   1.5]
 [ 0.5  1.   1.5]
 [-0.5  1.   1.5]]
Source code in ppsci/geometry/mesh.py
def translate(self, translation: np.ndarray, relative: bool = True) -> "Mesh":
    """Translate by given offsets.

    NOTE: This API generate a completely new Mesh object with translated geometry,
    without modifying original Mesh object inplace.

    Args:
        translation (np.ndarray): Translation offsets, numpy array of shape (3,):
            [offset_x, offset_y, offset_z].
        relative (bool, optional): Whether translate relatively. Defaults to True.

    Returns:
        Mesh: Translated Mesh object.

    Examples:
        >>> import ppsci
        >>> import pymesh  # doctest: +SKIP
        >>> import numpy as np
        >>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))  # doctest: +SKIP
        >>> mesh = ppsci.geometry.Mesh(box)  # doctest: +SKIP
        >>> print(mesh.vertices)  # doctest: +SKIP
        [[0. 0. 0.]
         [1. 0. 0.]
         [1. 1. 0.]
         [0. 1. 0.]
         [0. 0. 1.]
         [1. 0. 1.]
         [1. 1. 1.]
         [0. 1. 1.]]
        >>> print(mesh.translate((-0.5, 0, 0.5), False).vertices) # the center is moved to the translation vector.  # doctest: +SKIP
        [[-1.  -0.5  0. ]
         [ 0.  -0.5  0. ]
         [ 0.   0.5  0. ]
         [-1.   0.5  0. ]
         [-1.  -0.5  1. ]
         [ 0.  -0.5  1. ]
         [ 0.   0.5  1. ]
         [-1.   0.5  1. ]]
        >>> print(mesh.translate((-0.5, 0, 0.5), True).vertices) # the translation vector is directly added to the geometry coordinates  # doctest: +SKIP
        [[-0.5  0.   0.5]
         [ 0.5  0.   0.5]
         [ 0.5  1.   0.5]
         [-0.5  1.   0.5]
         [-0.5  0.   1.5]
         [ 0.5  0.   1.5]
         [ 0.5  1.   1.5]
         [-0.5  1.   1.5]]
    """
    vertices = np.array(self.vertices, dtype=paddle.get_default_dtype())
    faces = np.array(self.faces)

    if not checker.dynamic_import_to_globals(("open3d", "pymesh")):
        raise ImportError(
            "Could not import open3d and pymesh python package. "
            "Please install open3d with `pip install open3d` and "
            "pymesh as https://paddlescience-docs.readthedocs.io/zh/latest/zh/install_setup/#__tabbed_4_1"
        )
    import open3d  # isort:skip
    import pymesh  # isort:skip

    open3d_mesh = open3d.geometry.TriangleMesh(
        open3d.utility.Vector3dVector(vertices),
        open3d.utility.Vector3iVector(faces),
    )
    open3d_mesh = open3d_mesh.translate(translation, relative)
    translated_mesh = pymesh.form_mesh(
        np.asarray(open3d_mesh.vertices, dtype=paddle.get_default_dtype()), faces
    )
    # Generate a new Mesh object using class method
    return Mesh.from_pymesh(translated_mesh)
uniform_boundary_points(n)

Compute the equi-spaced points on the boundary.

Source code in ppsci/geometry/mesh.py
def uniform_boundary_points(self, n: int):
    """Compute the equi-spaced points on the boundary."""
    return self.pysdf.sample_surface(n)

PointCloud

Bases: Geometry

Class for point cloud geometry, i.e. a set of points from given file or array.

Parameters:

Name Type Description Default
interior Dict[str, ndarray]

Filepath or dict data, which store interior points of a point cloud, such as {"x": np.ndarray, "y": np.ndarray}.

required
coord_keys Tuple[str, ...]

Tuple of coordinate keys, such as ("x", "y").

required
boundary Dict[str, ndarray]

Boundary points of a point cloud. Defaults to None.

None
boundary_normal Dict[str, ndarray]

Boundary normal points of a point cloud. Defaults to None.

None

Examples:

>>> import ppsci
>>> import numpy as np
>>> interior_points = {"x": np.linspace(-1, 1, dtype="float32").reshape((-1, 1))}
>>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
Source code in ppsci/geometry/pointcloud.py
class PointCloud(geometry.Geometry):
    """Class for point cloud geometry, i.e. a set of points from given file or array.

    Args:
        interior (Dict[str, np.ndarray]): Filepath or dict data, which store interior points of a point cloud, such as {"x": np.ndarray, "y": np.ndarray}.
        coord_keys (Tuple[str, ...]): Tuple of coordinate keys, such as ("x", "y").
        boundary (Dict[str, np.ndarray]): Boundary points of a point cloud. Defaults to None.
        boundary_normal (Dict[str, np.ndarray]): Boundary normal points of a point cloud. Defaults to None.

    Examples:
        >>> import ppsci
        >>> import numpy as np
        >>> interior_points = {"x": np.linspace(-1, 1, dtype="float32").reshape((-1, 1))}
        >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
    """

    def __init__(
        self,
        interior: Dict[str, np.ndarray],
        coord_keys: Tuple[str, ...],
        boundary: Optional[Dict[str, np.ndarray]] = None,
        boundary_normal: Optional[Dict[str, np.ndarray]] = None,
    ):
        # Interior points
        self.interior = misc.convert_to_array(interior, coord_keys)
        self.len = self.interior.shape[0]

        # Boundary points
        self.boundary = boundary
        if self.boundary is not None:
            self.boundary = misc.convert_to_array(self.boundary, coord_keys)

        # Boundary normal points
        self.normal = boundary_normal
        if self.normal is not None:
            self.normal = misc.convert_to_array(
                self.normal, tuple(f"{key}_normal" for key in coord_keys)
            )
            if list(self.normal.shape) != list(self.boundary.shape):
                raise ValueError(
                    f"boundary's shape({self.boundary.shape}) must equal "
                    f"to normal's shape({self.normal.shape})"
                )

        self.input_keys = coord_keys
        super().__init__(
            len(coord_keys),
            (np.amin(self.interior, axis=0), np.amax(self.interior, axis=0)),
            np.inf,
        )

    @property
    def dim_keys(self):
        return self.input_keys

    def is_inside(self, x):
        # NOTE: point on boundary is included
        return (
            np.isclose((x[:, None, :] - self.interior[None, :, :]), 0, atol=1e-6)
            .all(axis=2)
            .any(axis=1)
        )

    def on_boundary(self, x):
        if not self.boundary:
            raise ValueError(
                "self.boundary must be initialized" " when call 'on_boundary' function"
            )
        return (
            np.isclose(
                (x[:, None, :] - self.boundary[None, :, :]),
                0,
                atol=1e-6,
            )
            .all(axis=2)
            .any(axis=1)
        )

    def translate(self, translation: np.ndarray) -> "PointCloud":
        """
        Translate the geometry by the given offset.

        Args:
            translation (np.ndarray): Translation offset.The shape of translation must be the same as the shape of the interior points.

        Returns:
            PointCloud: Translated point cloud.

        Examples:
            >>> import ppsci
            >>> import numpy as np
            >>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
            >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
            >>> translation = np.array([1.0])
            >>> print(geom.translate(translation).interior)
            [[1. ]
             [1.5]
             [2. ]
             [2.5]
             [3. ]]
            >>> interior_points_2d = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1)),
            ...                       "y": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
            >>> geom_2d = ppsci.geometry.PointCloud(interior_points_2d, ("x", "y"))
            >>> translation_2d = np.array([1.0, 3.0])
            >>> print(geom_2d.translate(translation_2d).interior)
            [[1.  3. ]
             [1.5 3.5]
             [2.  4. ]
             [2.5 4.5]
             [3.  5. ]]
        """
        for i, offset in enumerate(translation):
            self.interior[:, i] += offset
            if self.boundary:
                self.boundary += offset
        return self

    def scale(self, scale: np.ndarray) -> "PointCloud":
        """
        Scale the geometry by the given factor.

        Args:
            scale (np.ndarray): Scale factor.The shape of scale must be the same as the shape of the interior points.

        Returns:
            PointCloud: Scaled point cloud.

        Examples:
            >>> import ppsci
            >>> import numpy as np
            >>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
            >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
            >>> scale = np.array([2.0])
            >>> print(geom.scale(scale).interior)
            [[0.]
             [1.]
             [2.]
             [3.]
             [4.]]
            >>> interior_points_2d = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1)),
            ...                       "y": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
            >>> geom_2d = ppsci.geometry.PointCloud(interior_points_2d, ("x", "y"))
            >>> scale_2d = np.array([2.0, 0.5])
            >>> print(geom_2d.scale(scale_2d).interior)
            [[0.   0.  ]
             [1.   0.25]
             [2.   0.5 ]
             [3.   0.75]
             [4.   1.  ]]
        """
        for i, _scale in enumerate(scale):
            self.interior[:, i] *= _scale
            if self.boundary:
                self.boundary[:, i] *= _scale
            if self.normal:
                self.normal[:, i] *= _scale
        return self

    def uniform_boundary_points(self, n: int):
        """Compute the equi-spaced points on the boundary."""
        raise NotImplementedError(
            "PointCloud do not have 'uniform_boundary_points' method"
        )

    def random_boundary_points(self, n: int, random: str = "pseudo") -> np.ndarray:
        """Randomly sample points on the boundary.

        Args:
            n (int): Number of sample points.
            random (str): Random method. Defaults to "pseudo".

        Returns:
            np.ndarray: Randomly sampled points on the boundary.The shape of the returned array is (n, ndim).

        Examples:
            >>> import ppsci
            >>> import numpy as np
            >>> np.random.seed(0)
            >>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
            >>> boundary_points = {"x": np.array([0.0, 2.0], dtype="float32").reshape((-1, 1))}
            >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",), boundary_points)
            >>> print(geom.random_boundary_points(1))
            [[2.]]
        """
        assert self.boundary is not None, (
            "boundary points can't be empty when call "
            "'random_boundary_points' method"
        )
        assert n <= len(self.boundary), (
            f"number of sample points({n}) "
            f"can't be more than that in boundary({len(self.boundary)})"
        )
        return self.boundary[
            np.random.choice(len(self.boundary), size=n, replace=False)
        ]

    def random_points(self, n: int, random: str = "pseudo") -> np.ndarray:
        """Randomly sample points in the geometry.

        Args:
            n (int): Number of sample points.
            random (str): Random method. Defaults to "pseudo".

        Returns:
            np.ndarray: Randomly sampled points in the geometry.The shape of the returned array is (n, ndim).

        Examples:
            >>> import ppsci
            >>> import numpy as np
            >>> np.random.seed(0)
            >>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
            >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
            >>> print(geom.random_points(2))
            [[1.]
             [0.]]
        """
        assert n <= len(self.interior), (
            f"number of sample points({n}) "
            f"can't be more than that in points({len(self.interior)})"
        )
        return self.interior[
            np.random.choice(len(self.interior), size=n, replace=False)
        ]

    def uniform_points(self, n: int, boundary: bool = True) -> np.ndarray:
        """Compute the equi-spaced points in the geometry.

        Args:
            n (int): Number of sample points.
            boundary (bool): Whether to include boundary points. Defaults to True.

        Returns:
            np.ndarray: Equi-spaced points in the geometry.The shape of the returned array is (n, ndim).

        Examples:
            >>> import ppsci
            >>> import numpy as np
            >>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
            >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
            >>> print(geom.uniform_points(2))
            [[0. ]
             [0.5]]
        """
        return self.interior[:n]

    def union(self, other):
        raise NotImplementedError(
            "Union operation for PointCloud is not supported yet."
        )

    def __or__(self, other):
        raise NotImplementedError(
            "Union operation for PointCloud is not supported yet."
        )

    def difference(self, other):
        raise NotImplementedError(
            "Subtraction operation for PointCloud is not supported yet."
        )

    def __sub__(self, other):
        raise NotImplementedError(
            "Subtraction operation for PointCloud is not supported yet."
        )

    def intersection(self, other):
        raise NotImplementedError(
            "Intersection operation for PointCloud is not supported yet."
        )

    def __and__(self, other):
        raise NotImplementedError(
            "Intersection operation for PointCloud is not supported yet."
        )

    def __str__(self) -> str:
        """Return the name of class."""
        return ", ".join(
            [
                self.__class__.__name__,
                f"num_points = {len(self.interior)}",
                f"ndim = {self.ndim}",
                f"bbox = {self.bbox}",
                f"dim_keys = {self.dim_keys}",
            ]
        )
__str__()

Return the name of class.

Source code in ppsci/geometry/pointcloud.py
def __str__(self) -> str:
    """Return the name of class."""
    return ", ".join(
        [
            self.__class__.__name__,
            f"num_points = {len(self.interior)}",
            f"ndim = {self.ndim}",
            f"bbox = {self.bbox}",
            f"dim_keys = {self.dim_keys}",
        ]
    )
random_boundary_points(n, random='pseudo')

Randomly sample points on the boundary.

Parameters:

Name Type Description Default
n int

Number of sample points.

required
random str

Random method. Defaults to "pseudo".

'pseudo'

Returns:

Type Description
ndarray

np.ndarray: Randomly sampled points on the boundary.The shape of the returned array is (n, ndim).

Examples:

>>> import ppsci
>>> import numpy as np
>>> np.random.seed(0)
>>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
>>> boundary_points = {"x": np.array([0.0, 2.0], dtype="float32").reshape((-1, 1))}
>>> geom = ppsci.geometry.PointCloud(interior_points, ("x",), boundary_points)
>>> print(geom.random_boundary_points(1))
[[2.]]
Source code in ppsci/geometry/pointcloud.py
def random_boundary_points(self, n: int, random: str = "pseudo") -> np.ndarray:
    """Randomly sample points on the boundary.

    Args:
        n (int): Number of sample points.
        random (str): Random method. Defaults to "pseudo".

    Returns:
        np.ndarray: Randomly sampled points on the boundary.The shape of the returned array is (n, ndim).

    Examples:
        >>> import ppsci
        >>> import numpy as np
        >>> np.random.seed(0)
        >>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
        >>> boundary_points = {"x": np.array([0.0, 2.0], dtype="float32").reshape((-1, 1))}
        >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",), boundary_points)
        >>> print(geom.random_boundary_points(1))
        [[2.]]
    """
    assert self.boundary is not None, (
        "boundary points can't be empty when call "
        "'random_boundary_points' method"
    )
    assert n <= len(self.boundary), (
        f"number of sample points({n}) "
        f"can't be more than that in boundary({len(self.boundary)})"
    )
    return self.boundary[
        np.random.choice(len(self.boundary), size=n, replace=False)
    ]
random_points(n, random='pseudo')

Randomly sample points in the geometry.

Parameters:

Name Type Description Default
n int

Number of sample points.

required
random str

Random method. Defaults to "pseudo".

'pseudo'

Returns:

Type Description
ndarray

np.ndarray: Randomly sampled points in the geometry.The shape of the returned array is (n, ndim).

Examples:

>>> import ppsci
>>> import numpy as np
>>> np.random.seed(0)
>>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
>>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
>>> print(geom.random_points(2))
[[1.]
 [0.]]
Source code in ppsci/geometry/pointcloud.py
def random_points(self, n: int, random: str = "pseudo") -> np.ndarray:
    """Randomly sample points in the geometry.

    Args:
        n (int): Number of sample points.
        random (str): Random method. Defaults to "pseudo".

    Returns:
        np.ndarray: Randomly sampled points in the geometry.The shape of the returned array is (n, ndim).

    Examples:
        >>> import ppsci
        >>> import numpy as np
        >>> np.random.seed(0)
        >>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
        >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
        >>> print(geom.random_points(2))
        [[1.]
         [0.]]
    """
    assert n <= len(self.interior), (
        f"number of sample points({n}) "
        f"can't be more than that in points({len(self.interior)})"
    )
    return self.interior[
        np.random.choice(len(self.interior), size=n, replace=False)
    ]
scale(scale)

Scale the geometry by the given factor.

Parameters:

Name Type Description Default
scale ndarray

Scale factor.The shape of scale must be the same as the shape of the interior points.

required

Returns:

Name Type Description
PointCloud 'PointCloud'

Scaled point cloud.

Examples:

>>> import ppsci
>>> import numpy as np
>>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
>>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
>>> scale = np.array([2.0])
>>> print(geom.scale(scale).interior)
[[0.]
 [1.]
 [2.]
 [3.]
 [4.]]
>>> interior_points_2d = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1)),
...                       "y": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
>>> geom_2d = ppsci.geometry.PointCloud(interior_points_2d, ("x", "y"))
>>> scale_2d = np.array([2.0, 0.5])
>>> print(geom_2d.scale(scale_2d).interior)
[[0.   0.  ]
 [1.   0.25]
 [2.   0.5 ]
 [3.   0.75]
 [4.   1.  ]]
Source code in ppsci/geometry/pointcloud.py
def scale(self, scale: np.ndarray) -> "PointCloud":
    """
    Scale the geometry by the given factor.

    Args:
        scale (np.ndarray): Scale factor.The shape of scale must be the same as the shape of the interior points.

    Returns:
        PointCloud: Scaled point cloud.

    Examples:
        >>> import ppsci
        >>> import numpy as np
        >>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
        >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
        >>> scale = np.array([2.0])
        >>> print(geom.scale(scale).interior)
        [[0.]
         [1.]
         [2.]
         [3.]
         [4.]]
        >>> interior_points_2d = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1)),
        ...                       "y": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
        >>> geom_2d = ppsci.geometry.PointCloud(interior_points_2d, ("x", "y"))
        >>> scale_2d = np.array([2.0, 0.5])
        >>> print(geom_2d.scale(scale_2d).interior)
        [[0.   0.  ]
         [1.   0.25]
         [2.   0.5 ]
         [3.   0.75]
         [4.   1.  ]]
    """
    for i, _scale in enumerate(scale):
        self.interior[:, i] *= _scale
        if self.boundary:
            self.boundary[:, i] *= _scale
        if self.normal:
            self.normal[:, i] *= _scale
    return self
translate(translation)

Translate the geometry by the given offset.

Parameters:

Name Type Description Default
translation ndarray

Translation offset.The shape of translation must be the same as the shape of the interior points.

required

Returns:

Name Type Description
PointCloud 'PointCloud'

Translated point cloud.

Examples:

>>> import ppsci
>>> import numpy as np
>>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
>>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
>>> translation = np.array([1.0])
>>> print(geom.translate(translation).interior)
[[1. ]
 [1.5]
 [2. ]
 [2.5]
 [3. ]]
>>> interior_points_2d = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1)),
...                       "y": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
>>> geom_2d = ppsci.geometry.PointCloud(interior_points_2d, ("x", "y"))
>>> translation_2d = np.array([1.0, 3.0])
>>> print(geom_2d.translate(translation_2d).interior)
[[1.  3. ]
 [1.5 3.5]
 [2.  4. ]
 [2.5 4.5]
 [3.  5. ]]
Source code in ppsci/geometry/pointcloud.py
def translate(self, translation: np.ndarray) -> "PointCloud":
    """
    Translate the geometry by the given offset.

    Args:
        translation (np.ndarray): Translation offset.The shape of translation must be the same as the shape of the interior points.

    Returns:
        PointCloud: Translated point cloud.

    Examples:
        >>> import ppsci
        >>> import numpy as np
        >>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
        >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
        >>> translation = np.array([1.0])
        >>> print(geom.translate(translation).interior)
        [[1. ]
         [1.5]
         [2. ]
         [2.5]
         [3. ]]
        >>> interior_points_2d = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1)),
        ...                       "y": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
        >>> geom_2d = ppsci.geometry.PointCloud(interior_points_2d, ("x", "y"))
        >>> translation_2d = np.array([1.0, 3.0])
        >>> print(geom_2d.translate(translation_2d).interior)
        [[1.  3. ]
         [1.5 3.5]
         [2.  4. ]
         [2.5 4.5]
         [3.  5. ]]
    """
    for i, offset in enumerate(translation):
        self.interior[:, i] += offset
        if self.boundary:
            self.boundary += offset
    return self
uniform_boundary_points(n)

Compute the equi-spaced points on the boundary.

Source code in ppsci/geometry/pointcloud.py
def uniform_boundary_points(self, n: int):
    """Compute the equi-spaced points on the boundary."""
    raise NotImplementedError(
        "PointCloud do not have 'uniform_boundary_points' method"
    )
uniform_points(n, boundary=True)

Compute the equi-spaced points in the geometry.

Parameters:

Name Type Description Default
n int

Number of sample points.

required
boundary bool

Whether to include boundary points. Defaults to True.

True

Returns:

Type Description
ndarray

np.ndarray: Equi-spaced points in the geometry.The shape of the returned array is (n, ndim).

Examples:

>>> import ppsci
>>> import numpy as np
>>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
>>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
>>> print(geom.uniform_points(2))
[[0. ]
 [0.5]]
Source code in ppsci/geometry/pointcloud.py
def uniform_points(self, n: int, boundary: bool = True) -> np.ndarray:
    """Compute the equi-spaced points in the geometry.

    Args:
        n (int): Number of sample points.
        boundary (bool): Whether to include boundary points. Defaults to True.

    Returns:
        np.ndarray: Equi-spaced points in the geometry.The shape of the returned array is (n, ndim).

    Examples:
        >>> import ppsci
        >>> import numpy as np
        >>> interior_points = {"x": np.linspace(0, 2, 5, dtype="float32").reshape((-1, 1))}
        >>> geom = ppsci.geometry.PointCloud(interior_points, ("x",))
        >>> print(geom.uniform_points(2))
        [[0. ]
         [0.5]]
    """
    return self.interior[:n]

Polygon

Bases: Geometry

Class for simple polygon.

Parameters:

Name Type Description Default
vertices Tuple[Tuple[float, float], ...]

The order of vertices can be in a clockwise or counter-clockwise direction. The vertices will be re-ordered in counterclockwise (right hand rule).

required

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.Polygon(((0, 0), (1, 0), (2, 1), (2, 2), (0, 2)))
Source code in ppsci/geometry/geometry_2d.py
class Polygon(geometry.Geometry):
    """Class for simple polygon.

    Args:
        vertices (Tuple[Tuple[float, float], ...]): The order of vertices can be in a
            clockwise or counter-clockwise direction. The vertices will be re-ordered in
            counterclockwise (right hand rule).

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.Polygon(((0, 0), (1, 0), (2, 1), (2, 2), (0, 2)))
    """

    def __init__(self, vertices):
        self.vertices = np.array(vertices, dtype=paddle.get_default_dtype())
        if len(vertices) == 3:
            raise ValueError("The polygon is a triangle. Use Triangle instead.")
        if Rectangle.is_valid(self.vertices):
            raise ValueError("The polygon is a rectangle. Use Rectangle instead.")

        self.area = polygon_signed_area(self.vertices)
        # Clockwise
        if self.area < 0:
            self.area = -self.area
            self.vertices = np.flipud(self.vertices)

        self.diagonals = spatial.distance.squareform(
            spatial.distance.pdist(self.vertices)
        )
        super().__init__(
            2,
            (np.amin(self.vertices, axis=0), np.amax(self.vertices, axis=0)),
            np.max(self.diagonals),
        )
        self.nvertices = len(self.vertices)
        self.perimeter = np.sum(
            [self.diagonals[i, i + 1] for i in range(-1, self.nvertices - 1)]
        )
        self.bbox = np.array(
            [np.min(self.vertices, axis=0), np.max(self.vertices, axis=0)],
            dtype=paddle.get_default_dtype(),
        )

        self.segments = self.vertices[1:] - self.vertices[:-1]
        self.segments = np.vstack((self.vertices[0] - self.vertices[-1], self.segments))
        self.normal = clockwise_rotation_90(self.segments.T).T
        self.normal = self.normal / np.linalg.norm(self.normal, axis=1).reshape(-1, 1)

    def is_inside(self, x):
        def wn_PnPoly(P, V):
            """Winding number algorithm.

            https://en.wikipedia.org/wiki/Point_in_polygon
            http://geomalgorithms.com/a03-_inclusion.html

            Args:
                P: A point.
                V: Vertex points of a polygon.

            Returns:
                wn: Winding number (=0 only if P is outside polygon).
            """
            wn = np.zeros(len(P))  # Winding number counter

            # Repeat the first vertex at end
            # Loop through all edges of the polygon
            for i in range(-1, self.nvertices - 1):  # Edge from V[i] to V[i+1]
                tmp = np.all(
                    np.hstack(
                        [
                            V[i, 1] <= P[:, 1:2],  # Start y <= P[1]
                            V[i + 1, 1] > P[:, 1:2],  # An upward crossing
                            is_left(V[i], V[i + 1], P) > 0,  # P left of edge
                        ]
                    ),
                    axis=-1,
                )
                wn[tmp] += 1  # Have a valid up intersect
                tmp = np.all(
                    np.hstack(
                        [
                            V[i, 1] > P[:, 1:2],  # Start y > P[1]
                            V[i + 1, 1] <= P[:, 1:2],  # A downward crossing
                            is_left(V[i], V[i + 1], P) < 0,  # P right of edge
                        ]
                    ),
                    axis=-1,
                )
                wn[tmp] -= 1  # Have a valid down intersect
            return wn

        return wn_PnPoly(x, self.vertices) != 0

    def on_boundary(self, x):
        _on = np.zeros(shape=len(x), dtype=np.int)
        for i in range(-1, self.nvertices - 1):
            l1 = np.linalg.norm(self.vertices[i] - x, axis=-1)
            l2 = np.linalg.norm(self.vertices[i + 1] - x, axis=-1)
            _on[np.isclose(l1 + l2, self.diagonals[i, i + 1])] += 1
        return _on > 0

    def random_points(self, n, random="pseudo"):
        x = np.empty((0, 2), dtype=paddle.get_default_dtype())
        vbbox = self.bbox[1] - self.bbox[0]
        while len(x) < n:
            x_new = sampler.sample(n, 2, "pseudo") * vbbox + self.bbox[0]
            x = np.vstack((x, x_new[self.is_inside(x_new)]))
        return x[:n]

    def uniform_boundary_points(self, n):
        density = n / self.perimeter
        x = []
        for i in range(-1, self.nvertices - 1):
            x.append(
                np.linspace(
                    0,
                    1,
                    num=int(np.ceil(density * self.diagonals[i, i + 1])),
                    endpoint=False,
                    dtype=paddle.get_default_dtype(),
                )[:, None]
                * (self.vertices[i + 1] - self.vertices[i])
                + self.vertices[i]
            )
        x = np.vstack(x)
        if len(x) > n:
            x = x[0:n]
        return x

    def random_boundary_points(self, n, random="pseudo"):
        u = np.ravel(sampler.sample(n + self.nvertices, 1, random))
        # Remove the possible points very close to the corners
        l = 0
        for i in range(0, self.nvertices - 1):
            l += self.diagonals[i, i + 1]
            u = u[np.logical_not(np.isclose(u, l / self.perimeter))]
        u = u[:n]
        u *= self.perimeter
        u.sort()

        x = []
        i = -1
        l0 = 0
        l1 = l0 + self.diagonals[i, i + 1]
        v = (self.vertices[i + 1] - self.vertices[i]) / self.diagonals[i, i + 1]
        for l in u:
            if l > l1:
                i += 1
                l0, l1 = l1, l1 + self.diagonals[i, i + 1]
                v = (self.vertices[i + 1] - self.vertices[i]) / self.diagonals[i, i + 1]
            x.append((l - l0) * v + self.vertices[i])
        return np.vstack(x)

    def sdf_func(self, points: np.ndarray) -> np.ndarray:
        """Compute signed distance field.

        Args:
            points (np.ndarray): The coordinate points used to calculate the SDF value,
                the shape is [N, 2]
        Returns:
            np.ndarray: SDF values of input points without squared, the shape is [N, 1].

        NOTE: This function usually returns ndarray with negative values, because
        according to the definition of SDF, the SDF value of the coordinate point inside
        the object(interior points) is negative, the outside is positive, and the edge
        is 0. Therefore, when used for weighting, a negative sign is often added before
        the result of this function.
        """
        if points.shape[1] != self.ndim:
            raise ValueError(
                f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
            )
        sdf_value = np.empty((points.shape[0], 1), dtype=paddle.get_default_dtype())
        for n in range(points.shape[0]):
            distance = np.dot(
                points[n] - self.vertices[0], points[n] - self.vertices[0]
            )
            inside_tag = 1.0
            for i in range(self.vertices.shape[0]):
                j = (self.vertices.shape[0] - 1) if i == 0 else (i - 1)
                # Calculate the shortest distance from point P to each edge.
                vector_ij = self.vertices[j] - self.vertices[i]
                vector_in = points[n] - self.vertices[i]
                distance_vector = vector_in - vector_ij * np.clip(
                    np.dot(vector_in, vector_ij) / np.dot(vector_ij, vector_ij),
                    0.0,
                    1.0,
                )
                distance = np.minimum(
                    distance, np.dot(distance_vector, distance_vector)
                )
                # Calculate the inside and outside using the Odd-even rule
                odd_even_rule_number = np.array(
                    [
                        points[n][1] >= self.vertices[i][1],
                        points[n][1] < self.vertices[j][1],
                        vector_ij[0] * vector_in[1] > vector_ij[1] * vector_in[0],
                    ]
                )
                if odd_even_rule_number.all() or np.all(~odd_even_rule_number):
                    inside_tag *= -1.0
            sdf_value[n] = inside_tag * np.sqrt(distance)
        return -sdf_value
sdf_func(points)

Compute signed distance field.

Parameters:

Name Type Description Default
points ndarray

The coordinate points used to calculate the SDF value, the shape is [N, 2]

required

Returns: np.ndarray: SDF values of input points without squared, the shape is [N, 1].

NOTE: This function usually returns ndarray with negative values, because according to the definition of SDF, the SDF value of the coordinate point inside the object(interior points) is negative, the outside is positive, and the edge is 0. Therefore, when used for weighting, a negative sign is often added before the result of this function.

Source code in ppsci/geometry/geometry_2d.py
def sdf_func(self, points: np.ndarray) -> np.ndarray:
    """Compute signed distance field.

    Args:
        points (np.ndarray): The coordinate points used to calculate the SDF value,
            the shape is [N, 2]
    Returns:
        np.ndarray: SDF values of input points without squared, the shape is [N, 1].

    NOTE: This function usually returns ndarray with negative values, because
    according to the definition of SDF, the SDF value of the coordinate point inside
    the object(interior points) is negative, the outside is positive, and the edge
    is 0. Therefore, when used for weighting, a negative sign is often added before
    the result of this function.
    """
    if points.shape[1] != self.ndim:
        raise ValueError(
            f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
        )
    sdf_value = np.empty((points.shape[0], 1), dtype=paddle.get_default_dtype())
    for n in range(points.shape[0]):
        distance = np.dot(
            points[n] - self.vertices[0], points[n] - self.vertices[0]
        )
        inside_tag = 1.0
        for i in range(self.vertices.shape[0]):
            j = (self.vertices.shape[0] - 1) if i == 0 else (i - 1)
            # Calculate the shortest distance from point P to each edge.
            vector_ij = self.vertices[j] - self.vertices[i]
            vector_in = points[n] - self.vertices[i]
            distance_vector = vector_in - vector_ij * np.clip(
                np.dot(vector_in, vector_ij) / np.dot(vector_ij, vector_ij),
                0.0,
                1.0,
            )
            distance = np.minimum(
                distance, np.dot(distance_vector, distance_vector)
            )
            # Calculate the inside and outside using the Odd-even rule
            odd_even_rule_number = np.array(
                [
                    points[n][1] >= self.vertices[i][1],
                    points[n][1] < self.vertices[j][1],
                    vector_ij[0] * vector_in[1] > vector_ij[1] * vector_in[0],
                ]
            )
            if odd_even_rule_number.all() or np.all(~odd_even_rule_number):
                inside_tag *= -1.0
        sdf_value[n] = inside_tag * np.sqrt(distance)
    return -sdf_value

Rectangle

Bases: Hypercube

Class for rectangle geometry

Parameters:

Name Type Description Default
xmin Tuple[float, float]

Bottom left corner point, [x0, y0].

required
xmax Tuple[float, float]

Top right corner point, [x1, y1].

required

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.Rectangle((0.0, 0.0), (1.0, 1.0))
Source code in ppsci/geometry/geometry_2d.py
class Rectangle(geometry_nd.Hypercube):
    """Class for rectangle geometry

    Args:
        xmin (Tuple[float, float]): Bottom left corner point, [x0, y0].
        xmax (Tuple[float, float]): Top right corner point, [x1, y1].

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.Rectangle((0.0, 0.0), (1.0, 1.0))
    """

    def __init__(self, xmin, xmax):
        super().__init__(xmin, xmax)
        self.perimeter = 2 * np.sum(self.xmax - self.xmin)
        self.area = np.prod(self.xmax - self.xmin)

    def uniform_boundary_points(self, n):
        nx, ny = np.ceil(n / self.perimeter * (self.xmax - self.xmin)).astype(int)
        bottom = np.hstack(
            (
                np.linspace(
                    self.xmin[0],
                    self.xmax[0],
                    nx,
                    endpoint=False,
                    dtype=paddle.get_default_dtype(),
                ).reshape([nx, 1]),
                np.full([nx, 1], self.xmin[1], dtype=paddle.get_default_dtype()),
            )
        )
        right = np.hstack(
            (
                np.full([ny, 1], self.xmax[0], dtype=paddle.get_default_dtype()),
                np.linspace(
                    self.xmin[1],
                    self.xmax[1],
                    ny,
                    endpoint=False,
                    dtype=paddle.get_default_dtype(),
                ).reshape([ny, 1]),
            )
        )
        top = np.hstack(
            (
                np.linspace(
                    self.xmin[0], self.xmax[0], nx + 1, dtype=paddle.get_default_dtype()
                )[1:].reshape([nx, 1]),
                np.full([nx, 1], self.xmax[1], dtype=paddle.get_default_dtype()),
            )
        )
        left = np.hstack(
            (
                np.full([ny, 1], self.xmin[0], dtype=paddle.get_default_dtype()),
                np.linspace(
                    self.xmin[1], self.xmax[1], ny + 1, dtype=paddle.get_default_dtype()
                )[1:].reshape([ny, 1]),
            )
        )
        x = np.vstack((bottom, right, top, left))
        if len(x) > n:
            x = x[0:n]
        return x

    def random_boundary_points(self, n, random="pseudo"):
        l1 = self.xmax[0] - self.xmin[0]
        l2 = l1 + self.xmax[1] - self.xmin[1]
        l3 = l2 + l1
        u = np.ravel(sampler.sample(n + 10, 1, random))
        # Remove the possible points very close to the corners
        u = u[~np.isclose(u, l1 / self.perimeter)]
        u = u[~np.isclose(u, l3 / self.perimeter)]
        u = u[0:n]

        u *= self.perimeter
        x = []
        for l in u:
            if l < l1:
                x.append([self.xmin[0] + l, self.xmin[1]])
            elif l < l2:
                x.append([self.xmax[0], self.xmin[1] + (l - l1)])
            elif l < l3:
                x.append([self.xmax[0] - (l - l2), self.xmax[1]])
            else:
                x.append([self.xmin[0], self.xmax[1] - (l - l3)])
        return np.vstack(x)

    @staticmethod
    def is_valid(vertices):
        """Check if the geometry is a Rectangle."""
        return (
            len(vertices) == 4
            and np.isclose(np.prod(vertices[1] - vertices[0]), 0)
            and np.isclose(np.prod(vertices[2] - vertices[1]), 0)
            and np.isclose(np.prod(vertices[3] - vertices[2]), 0)
            and np.isclose(np.prod(vertices[0] - vertices[3]), 0)
        )

    def sdf_func(self, points: np.ndarray) -> np.ndarray:
        """Compute signed distance field.

        Args:
            points (np.ndarray): The coordinate points used to calculate the SDF value,
                the shape of the array is [N, 2].

        Returns:
            np.ndarray: SDF values of input points without squared, the shape is [N, 1].

        NOTE: This function usually returns ndarray with negative values, because
        according to the definition of SDF, the SDF value of the coordinate point inside
        the object(interior points) is negative, the outside is positive, and the edge
        is 0. Therefore, when used for weighting, a negative sign is often added before
        the result of this function.
        """
        if points.shape[1] != self.ndim:
            raise ValueError(
                f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
            )
        center = (self.xmin + self.xmax) / 2
        dist_to_boundary = (
            np.abs(points - center) - np.array([self.xmax - self.xmin]) / 2
        )
        return (
            np.linalg.norm(np.maximum(dist_to_boundary, 0), axis=1)
            + np.minimum(np.max(dist_to_boundary, axis=1), 0)
        ).reshape(-1, 1)
is_valid(vertices) staticmethod

Check if the geometry is a Rectangle.

Source code in ppsci/geometry/geometry_2d.py
@staticmethod
def is_valid(vertices):
    """Check if the geometry is a Rectangle."""
    return (
        len(vertices) == 4
        and np.isclose(np.prod(vertices[1] - vertices[0]), 0)
        and np.isclose(np.prod(vertices[2] - vertices[1]), 0)
        and np.isclose(np.prod(vertices[3] - vertices[2]), 0)
        and np.isclose(np.prod(vertices[0] - vertices[3]), 0)
    )
sdf_func(points)

Compute signed distance field.

Parameters:

Name Type Description Default
points ndarray

The coordinate points used to calculate the SDF value, the shape of the array is [N, 2].

required

Returns:

Type Description
ndarray

np.ndarray: SDF values of input points without squared, the shape is [N, 1].

NOTE: This function usually returns ndarray with negative values, because according to the definition of SDF, the SDF value of the coordinate point inside the object(interior points) is negative, the outside is positive, and the edge is 0. Therefore, when used for weighting, a negative sign is often added before the result of this function.

Source code in ppsci/geometry/geometry_2d.py
def sdf_func(self, points: np.ndarray) -> np.ndarray:
    """Compute signed distance field.

    Args:
        points (np.ndarray): The coordinate points used to calculate the SDF value,
            the shape of the array is [N, 2].

    Returns:
        np.ndarray: SDF values of input points without squared, the shape is [N, 1].

    NOTE: This function usually returns ndarray with negative values, because
    according to the definition of SDF, the SDF value of the coordinate point inside
    the object(interior points) is negative, the outside is positive, and the edge
    is 0. Therefore, when used for weighting, a negative sign is often added before
    the result of this function.
    """
    if points.shape[1] != self.ndim:
        raise ValueError(
            f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
        )
    center = (self.xmin + self.xmax) / 2
    dist_to_boundary = (
        np.abs(points - center) - np.array([self.xmax - self.xmin]) / 2
    )
    return (
        np.linalg.norm(np.maximum(dist_to_boundary, 0), axis=1)
        + np.minimum(np.max(dist_to_boundary, axis=1), 0)
    ).reshape(-1, 1)

SDFMesh

Bases: Geometry

Class for SDF geometry, a kind of implicit surface mesh.

Parameters:

Name Type Description Default
vectors ndarray

Vectors of triangles of mesh with shape [M, 3, 3].

required
normals ndarray

Unit normals of each triangle face with shape [M, 3].

required
sdf_func Callable[[ndarray, bool], ndarray]

Signed distance function of the triangle mesh.

required

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.SDFMesh.from_stl("/path/to/mesh.stl")
Source code in ppsci/geometry/mesh.py
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
class SDFMesh(geometry.Geometry):
    """Class for SDF geometry, a kind of implicit surface mesh.

    Args:
        vectors (np.ndarray): Vectors of triangles of mesh with shape [M, 3, 3].
        normals (np.ndarray): Unit normals of each triangle face with shape [M, 3].
        sdf_func (Callable[[np.ndarray, bool], np.ndarray]): Signed distance function
            of the triangle mesh.

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.SDFMesh.from_stl("/path/to/mesh.stl")  # doctest: +SKIP
    """

    eps = 1e-6

    def __init__(
        self,
        vectors: np.ndarray,
        normals: np.ndarray,
        sdf_func: Callable[[np.ndarray, bool], np.ndarray],
    ):
        if vectors.shape[1:] != (3, 3):
            raise ValueError(
                f"The shape of `vectors` must be [M, 3, 3], but got {vectors.shape}"
            )
        if normals.shape[1] != 3:
            raise ValueError(
                f"The shape of `normals` must be [M, 3], but got {normals.shape}"
            )
        self.vectors = vectors
        self.face_normal = normals
        self.sdf_func = sdf_func  # overwrite sdf_func
        self.bounds = (
            ((np.min(self.vectors[:, :, 0])), np.max(self.vectors[:, :, 0])),
            ((np.min(self.vectors[:, :, 1])), np.max(self.vectors[:, :, 1])),
            ((np.min(self.vectors[:, :, 2])), np.max(self.vectors[:, :, 2])),
        )
        self.ndim = 3
        super().__init__(
            self.vectors.shape[-1],
            (np.amin(self.vectors, axis=(0, 1)), np.amax(self.vectors, axis=(0, 1))),
            np.inf,
        )

    @property
    def v0(self) -> np.ndarray:
        return self.vectors[:, 0]

    @property
    def v1(self) -> np.ndarray:
        return self.vectors[:, 1]

    @property
    def v2(self) -> np.ndarray:
        return self.vectors[:, 2]

    @classmethod
    def from_stl(cls, mesh_file: str) -> "SDFMesh":
        """Instantiate SDFMesh from given mesh file.

        Args:
            mesh_file (str): Path to triangle mesh file.

        Returns:
            SDFMesh: Instantiated ppsci.geometry.SDFMesh object.

        Examples:
            >>> import ppsci
            >>> import pymesh  # doctest: +SKIP
            >>> import numpy as np  # doctest: +SKIP
            >>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))  # doctest: +SKIP
            >>> pymesh.save_mesh("box.stl", box)  # doctest: +SKIP
            >>> mesh = ppsci.geometry.SDFMesh.from_stl("box.stl")  # doctest: +SKIP
            >>> print(sdfmesh.vectors.shape)  # doctest: +SKIP
            (12, 3, 3)
        """
        # check if pymesh is installed when using Mesh Class
        if not checker.dynamic_import_to_globals(["stl"]):
            raise ImportError(
                "Could not import stl python package. "
                "Please install numpy-stl with: pip install 'numpy-stl>=2.16,<2.17'"
            )

        np_mesh_obj = np_mesh_module.Mesh.from_file(mesh_file)
        return cls(
            np_mesh_obj.vectors,
            np_mesh_obj.get_unit_normals(),
            make_sdf(np_mesh_obj.vectors),
        )

    def sdf_func(
        self, points: np.ndarray, compute_sdf_derivatives: bool = False
    ) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
        """Compute signed distance field.

        Args:
            points (np.ndarray): The coordinate points used to calculate the SDF value,
                the shape is [N, 3]
            compute_sdf_derivatives (bool): Whether to compute SDF derivatives.
                Defaults to False.

        Returns:
            Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
            If compute_sdf_derivatives is True, then return both SDF values([N, 1])
                and their derivatives([N, 3]); otherwise only return SDF values([N, 1]).

        NOTE: This function usually returns ndarray with negative values, because
        according to the definition of SDF, the SDF value of the coordinate point inside
        the object(interior points) is negative, the outside is positive, and the edge
        is 0. Therefore, when used for weighting, a negative sign is often added before
        the result of this function.
        """
        # normalize triangles
        x_min, y_min, z_min = np.min(points, axis=0)
        x_max, y_max, z_max = np.max(points, axis=0)
        max_dis = max(max((x_max - x_min), (y_max - y_min)), (z_max - z_min))
        store_triangles = np.array(self.vectors, dtype=np.float64)
        store_triangles[:, :, 0] -= x_min
        store_triangles[:, :, 1] -= y_min
        store_triangles[:, :, 2] -= z_min
        store_triangles *= 1 / max_dis
        store_triangles = store_triangles.reshape([-1, 3])

        # normalize query points
        points = points.copy()
        points[:, 0] -= x_min
        points[:, 1] -= y_min
        points[:, 2] -= z_min
        points *= 1 / max_dis
        points = points.astype(np.float64).ravel()

        # compute sdf values for query points
        sdf = sdf_module.signed_distance_field(
            store_triangles,
            np.arange((store_triangles.shape[0])),
            points,
            include_hit_points=compute_sdf_derivatives,
        )
        if compute_sdf_derivatives:
            sdf, hit_points = sdf

        sdf = sdf.numpy()  # [N]
        sdf = np.expand_dims(max_dis * sdf, axis=1)  # [N, 1]

        if compute_sdf_derivatives:
            hit_points = hit_points.numpy()  # [N, 3]
            # Gradient of SDF is the unit vector from the query point to the hit point.
            sdf_derives = hit_points - points
            sdf_derives /= np.linalg.norm(sdf_derives, axis=1, keepdims=True)
            return sdf, sdf_derives

        return sdf

    def is_inside(self, x):
        # NOTE: point on boundary is included
        return np.less(self.sdf_func(x), 0.0).ravel()

    def on_boundary(self, x: np.ndarray, normal: np.ndarray) -> np.ndarray:
        x_plus = x + self.eps * normal
        x_minus = x - self.eps * normal

        sdf_x_plus = self.sdf_func(x_plus)
        sdf_x_minus = self.sdf_func(x_minus)
        mask_on_boundary = np.less_equal(sdf_x_plus * sdf_x_minus, 0)
        return mask_on_boundary.ravel()

    def translate(self, translation: np.ndarray) -> "SDFMesh":
        """Translate by given offsets.

        NOTE: This API generate a completely new Mesh object with translated geometry,
        without modifying original Mesh object inplace.

        Args:
            translation (np.ndarray): Translation offsets, numpy array of shape (3,):
                [offset_x, offset_y, offset_z].

        Returns:
            Mesh: Translated Mesh object.

        Examples:
            >>> import ppsci
            >>> import pymesh  # doctest: +SKIP
            >>> mesh = ppsci.geometry.SDFMesh.from_stl('/path/to/mesh.stl')  # doctest: +SKIP
            >>> mesh = mesh.translate(np.array([1, -1, 2]))  # doctest: +SKIP
        """
        new_vectors = self.vectors + translation.reshape([1, 1, 3])

        return SDFMesh(
            new_vectors,
            self.face_normal,
            make_sdf(new_vectors),
        )

    def scale(self, scale: float) -> "SDFMesh":
        """Scale by given scale coefficient and center coordinate.

        NOTE: This API generate a completely new Mesh object with scaled geometry,
        without modifying original Mesh object inplace.

        Args:
            scale (float): Scale coefficient.

        Returns:
            Mesh: Scaled Mesh object.

        Examples:
            >>> import ppsci
            >>> import pymesh  # doctest: +SKIP
            >>> mesh = ppsci.geometry.SDFMesh.from_stl('/path/to/mesh.stl')  # doctest: +SKIP
            >>> mesh = mesh.scale(np.array([1.3, 1.5, 2.0]))  # doctest: +SKIP
        """
        new_vectors = self.vectors * scale
        return SDFMesh(
            new_vectors,
            self.face_normal,
            make_sdf(new_vectors),
        )

    def uniform_boundary_points(self, n: int):
        """Compute the equi-spaced points on the boundary."""
        raise NotImplementedError(
            "'uniform_boundary_points' is not available in SDFMesh."
        )

    def inflated_random_points(self, n, distance, random="pseudo", criteria=None):
        raise NotImplementedError(
            "'inflated_random_points' is not available in SDFMesh."
        )

    def _approximate_area(
        self,
        random: Literal["pseudo"] = "pseudo",
        criteria: Optional[Callable] = None,
        n_appr: int = 10000,
    ) -> float:
        """Approximate area with given `criteria` and `n_appr` points by Monte Carlo
        algorithm.

        Args:
            random (str, optional): Random method. Defaults to "pseudo".
            criteria (Optional[Callable]): Criteria function. Defaults to None.
            n_appr (int): Number of points for approximating area. Defaults to 10000.

        Returns:
            float: Approximation area with given criteria.
        """
        triangle_areas = area_of_triangles(self.v0, self.v1, self.v2)
        triangle_probabilities = triangle_areas / np.linalg.norm(triangle_areas, ord=1)
        triangle_index = np.arange(triangle_probabilities.shape[0])
        npoint_per_triangle = np.random.choice(
            triangle_index, n_appr, p=triangle_probabilities
        )
        npoint_per_triangle, _ = np.histogram(
            npoint_per_triangle,
            np.arange(triangle_probabilities.shape[0] + 1) - 0.5,
        )

        aux_points = []
        aux_normals = []
        appr_areas = []

        for i, npoint in enumerate(npoint_per_triangle):
            if npoint == 0:
                continue
            # sample points for computing criteria mask if criteria is given
            points_at_triangle_i = sample_in_triangle(
                self.v0[i], self.v1[i], self.v2[i], npoint, random
            )
            normal_at_triangle_i = np.tile(
                self.face_normal[i].reshape(1, 3), (npoint, 1)
            )
            aux_points.append(points_at_triangle_i)
            aux_normals.append(normal_at_triangle_i)
            appr_areas.append(
                np.full(
                    (npoint, 1), triangle_areas[i] / npoint, paddle.get_default_dtype()
                )
            )

        aux_points = np.concatenate(aux_points, axis=0)  # [n_appr, 3]
        aux_normals = np.concatenate(aux_normals, axis=0)  # [n_appr, 3]
        appr_areas = np.concatenate(appr_areas, axis=0)  # [n_appr, 1]
        valid_mask = self.on_boundary(aux_points, aux_normals)[:, None]
        # set invalid area to 0 by computing criteria mask with auxiliary points
        if criteria is not None:
            criteria_mask = criteria(*np.split(aux_points, self.ndim, 1))
            assert valid_mask.shape == criteria_mask.shape
            valid_mask = np.logical_and(valid_mask, criteria_mask)

        appr_areas *= valid_mask

        return appr_areas.sum()

    def random_boundary_points(
        self, n, random="pseudo"
    ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
        triangle_area = area_of_triangles(self.v0, self.v1, self.v2)
        triangle_prob = triangle_area / np.linalg.norm(triangle_area, ord=1)
        npoint_per_triangle = np.random.choice(
            np.arange(len(triangle_prob)), n, p=triangle_prob
        )
        npoint_per_triangle, _ = np.histogram(
            npoint_per_triangle, np.arange(len(triangle_prob) + 1) - 0.5
        )

        points = []
        normal = []
        areas = []
        for i, npoint in enumerate(npoint_per_triangle):
            if npoint == 0:
                continue
            points_at_triangle_i = sample_in_triangle(
                self.v0[i], self.v1[i], self.v2[i], npoint, random
            )
            normal_at_triangle_i = np.tile(self.face_normal[i], (npoint, 1)).astype(
                paddle.get_default_dtype()
            )
            areas_at_triangle_i = np.full(
                (npoint, 1),
                triangle_area[i] / npoint,
                dtype=paddle.get_default_dtype(),
            )

            points.append(points_at_triangle_i)
            normal.append(normal_at_triangle_i)
            areas.append(areas_at_triangle_i)

        points = np.concatenate(points, axis=0)
        normal = np.concatenate(normal, axis=0)
        areas = np.concatenate(areas, axis=0)

        return points, normal, areas

    def sample_boundary(
        self,
        n: int,
        random: Literal["pseudo"] = "pseudo",
        criteria: Optional[Callable[..., np.ndarray]] = None,
        evenly: bool = False,
        inflation_dist: Union[float, Tuple[float, ...]] = None,
    ) -> Dict[str, np.ndarray]:
        # TODO(sensen): Support for time-dependent points(repeat data in time)
        if inflation_dist is not None:
            raise NotImplementedError("Not implemented yet")
        else:
            if evenly:
                raise ValueError(
                    "Can't sample evenly on mesh now, please set evenly=False."
                )
            _size, _ntry, _nsuc = 0, 0, 0
            all_points = []
            all_normal = []
            while _size < n:
                points, normal, _ = self.random_boundary_points(n, random)
                valid_mask = self.on_boundary(points, normal)

                if criteria is not None:
                    criteria_mask = criteria(
                        *np.split(points, self.ndim, axis=1)
                    ).ravel()
                    assert valid_mask.shape == criteria_mask.shape
                    valid_mask = np.logical_and(valid_mask, criteria_mask)

                points = points[valid_mask]
                normal = normal[valid_mask]

                if len(points) > n - _size:
                    points = points[: n - _size]
                    normal = normal[: n - _size]

                all_points.append(points)
                all_normal.append(normal)

                _size += len(points)
                _ntry += 1
                if len(points) > 0:
                    _nsuc += 1

                if _ntry >= 1000 and _nsuc == 0:
                    raise ValueError(
                        "Sample boundary points failed, "
                        "please check correctness of geometry and given criteria."
                    )

            all_points = np.concatenate(all_points, axis=0)
            all_normal = np.concatenate(all_normal, axis=0)
            _appr_area = self._approximate_area(random, criteria)
            all_areas = np.full((n, 1), _appr_area / n, paddle.get_default_dtype())

        x_dict = misc.convert_to_dict(all_points, self.dim_keys)
        normal_dict = misc.convert_to_dict(
            all_normal, [f"normal_{key}" for key in self.dim_keys if key != "t"]
        )
        area_dict = misc.convert_to_dict(all_areas, ["area"])
        return {**x_dict, **normal_dict, **area_dict}

    def random_points(self, n, random="pseudo", criteria=None):
        _size = 0
        all_points = []
        cuboid = geometry_3d.Cuboid(
            [bound[0] for bound in self.bounds],
            [bound[1] for bound in self.bounds],
        )
        _nsample, _nvalid = 0, 0
        while _size < n:
            random_points = cuboid.random_points(n, random)
            valid_mask = self.is_inside(random_points)

            if criteria:
                criteria_mask = criteria(
                    *np.split(random_points, self.ndim, axis=1)
                ).ravel()
                assert valid_mask.shape == criteria_mask.shape
                valid_mask = np.logical_and(valid_mask, criteria_mask)

            valid_points = random_points[valid_mask]
            _nvalid += len(valid_points)

            if len(valid_points) > n - _size:
                valid_points = valid_points[: n - _size]

            all_points.append(valid_points)
            _size += len(valid_points)
            _nsample += n

        all_points = np.concatenate(all_points, axis=0)
        cuboid_volume = np.prod([b[1] - b[0] for b in self.bounds])
        all_areas = np.full(
            (n, 1), cuboid_volume * (_nvalid / _nsample) / n, paddle.get_default_dtype()
        )
        return all_points, all_areas

    def sample_interior(
        self,
        n: int,
        random: Literal["pseudo"] = "pseudo",
        criteria: Optional[Callable[..., np.ndarray]] = None,
        evenly: bool = False,
        compute_sdf_derivatives: bool = False,
    ):
        """
        Sample random points in the geometry and return those meet criteria.

        NOTE: sdf values returned by this function are negated because the weight in
        loss function should be positive.
        """
        if evenly:
            # TODO(sensen): Implement uniform sample for mesh interior.
            raise NotImplementedError(
                "uniformly sample for interior in mesh is not support yet, "
                "you may need to set evenly=False in config dict of constraint"
            )
        points, areas = self.random_points(n, random, criteria)

        x_dict = misc.convert_to_dict(points, self.dim_keys)
        area_dict = misc.convert_to_dict(areas, ("area",))

        sdf = self.sdf_func(points, compute_sdf_derivatives)
        if compute_sdf_derivatives:
            sdf, sdf_derives = sdf

        # NOTE: add negative to the sdf values because weight should be positive.
        sdf_dict = misc.convert_to_dict(-sdf, ("sdf",))

        sdf_derives_dict = {}
        if compute_sdf_derivatives:
            # NOTE: Negate sdf derivatives
            sdf_derives_dict = misc.convert_to_dict(
                -sdf_derives, tuple(f"sdf__{key}" for key in self.dim_keys)
            )

        return {**x_dict, **area_dict, **sdf_dict, **sdf_derives_dict}

    def union(self, other: "SDFMesh"):
        new_vectors = np.concatenate([self.vectors, other.vectors], axis=0)
        new_normals = np.concatenate([self.face_normal, other.face_normal], axis=0)

        def make_union_new_sdf(sdf_func1, sdf_func2):
            def new_sdf_func(points: np.ndarray, compute_sdf_derivatives: bool = False):
                # Invert definition of sdf to make boolean operation accurate
                # see: https://iquilezles.org/articles/interiordistance/
                sdf_self = sdf_func1(points, compute_sdf_derivatives)
                sdf_other = sdf_func2(points, compute_sdf_derivatives)
                if compute_sdf_derivatives:
                    sdf_self, sdf_derives_self = sdf_self
                    sdf_other, sdf_derives_other = sdf_other

                computed_sdf = -np.maximum(-sdf_self, -sdf_other)

                if compute_sdf_derivatives:
                    computed_sdf_derives = -np.where(
                        sdf_self < sdf_other,
                        sdf_derives_self,
                        sdf_derives_other,
                    )
                    return computed_sdf, computed_sdf_derives

                return computed_sdf

            return new_sdf_func

        return SDFMesh(
            new_vectors,
            new_normals,
            make_union_new_sdf(self.sdf_func, other.sdf_func),
        )

    def __or__(self, other: "SDFMesh"):
        return self.union(other)

    def __add__(self, other: "SDFMesh"):
        return self.union(other)

    def difference(self, other: "SDFMesh"):
        new_vectors = np.concatenate([self.vectors, other.vectors], axis=0)
        new_normals = np.concatenate([self.face_normal, -other.face_normal], axis=0)

        def make_difference_new_sdf(sdf_func1, sdf_func2):
            def new_sdf_func(points: np.ndarray, compute_sdf_derivatives: bool = False):
                # Invert definition of sdf to make boolean operation accurate
                # see: https://iquilezles.org/articles/interiordistance/
                sdf_self = sdf_func1(points, compute_sdf_derivatives)
                sdf_other = sdf_func2(points, compute_sdf_derivatives)
                if compute_sdf_derivatives:
                    sdf_self, sdf_derives_self = sdf_self
                    sdf_other, sdf_derives_other = sdf_other

                computed_sdf = -np.minimum(-sdf_self, sdf_other)

                if compute_sdf_derivatives:
                    computed_sdf_derives = np.where(
                        -sdf_self < sdf_other,
                        -sdf_derives_self,
                        sdf_derives_other,
                    )
                    return computed_sdf, computed_sdf_derives

                return computed_sdf

            return new_sdf_func

        return SDFMesh(
            new_vectors,
            new_normals,
            make_difference_new_sdf(self.sdf_func, other.sdf_func),
        )

    def __sub__(self, other: "SDFMesh"):
        return self.difference(other)

    def intersection(self, other: "SDFMesh"):
        new_vectors = np.concatenate([self.vectors, other.vectors], axis=0)
        new_normals = np.concatenate([self.face_normal, other.face_normal], axis=0)

        def make_intersection_new_sdf(sdf_func1, sdf_func2):
            def new_sdf_func(points: np.ndarray, compute_sdf_derivatives: bool = False):
                # Invert definition of sdf to make boolean operation accurate
                # see: https://iquilezles.org/articles/interiordistance/
                sdf_self = sdf_func1(points, compute_sdf_derivatives)
                sdf_other = sdf_func2(points, compute_sdf_derivatives)
                if compute_sdf_derivatives:
                    sdf_self, sdf_derives_self = sdf_self
                    sdf_other, sdf_derives_other = sdf_other

                computed_sdf = -np.minimum(-sdf_self, -sdf_other)

                if compute_sdf_derivatives:
                    computed_sdf_derives = np.where(
                        sdf_self > sdf_other,
                        -sdf_derives_self,
                        -sdf_derives_other,
                    )
                    return computed_sdf, computed_sdf_derives

                return computed_sdf

            return new_sdf_func

        return SDFMesh(
            new_vectors,
            new_normals,
            make_intersection_new_sdf(self.sdf_func, other.sdf_func),
        )

    def __and__(self, other: "SDFMesh"):
        return self.intersection(other)

    def __str__(self) -> str:
        """Return the name of class"""
        return ", ".join(
            [
                self.__class__.__name__,
                f"num_faces = {self.vectors.shape[0]}",
                f"bounds = {self.bounds}",
                f"dim_keys = {self.dim_keys}",
            ]
        )
__str__()

Return the name of class

Source code in ppsci/geometry/mesh.py
def __str__(self) -> str:
    """Return the name of class"""
    return ", ".join(
        [
            self.__class__.__name__,
            f"num_faces = {self.vectors.shape[0]}",
            f"bounds = {self.bounds}",
            f"dim_keys = {self.dim_keys}",
        ]
    )
from_stl(mesh_file) classmethod

Instantiate SDFMesh from given mesh file.

Parameters:

Name Type Description Default
mesh_file str

Path to triangle mesh file.

required

Returns:

Name Type Description
SDFMesh 'SDFMesh'

Instantiated ppsci.geometry.SDFMesh object.

Examples:

>>> import ppsci
>>> import pymesh
>>> import numpy as np
>>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))
>>> pymesh.save_mesh("box.stl", box)
>>> mesh = ppsci.geometry.SDFMesh.from_stl("box.stl")
>>> print(sdfmesh.vectors.shape)
(12, 3, 3)
Source code in ppsci/geometry/mesh.py
@classmethod
def from_stl(cls, mesh_file: str) -> "SDFMesh":
    """Instantiate SDFMesh from given mesh file.

    Args:
        mesh_file (str): Path to triangle mesh file.

    Returns:
        SDFMesh: Instantiated ppsci.geometry.SDFMesh object.

    Examples:
        >>> import ppsci
        >>> import pymesh  # doctest: +SKIP
        >>> import numpy as np  # doctest: +SKIP
        >>> box = pymesh.generate_box_mesh(np.array([0, 0, 0]), np.array([1, 1, 1]))  # doctest: +SKIP
        >>> pymesh.save_mesh("box.stl", box)  # doctest: +SKIP
        >>> mesh = ppsci.geometry.SDFMesh.from_stl("box.stl")  # doctest: +SKIP
        >>> print(sdfmesh.vectors.shape)  # doctest: +SKIP
        (12, 3, 3)
    """
    # check if pymesh is installed when using Mesh Class
    if not checker.dynamic_import_to_globals(["stl"]):
        raise ImportError(
            "Could not import stl python package. "
            "Please install numpy-stl with: pip install 'numpy-stl>=2.16,<2.17'"
        )

    np_mesh_obj = np_mesh_module.Mesh.from_file(mesh_file)
    return cls(
        np_mesh_obj.vectors,
        np_mesh_obj.get_unit_normals(),
        make_sdf(np_mesh_obj.vectors),
    )
sample_interior(n, random='pseudo', criteria=None, evenly=False, compute_sdf_derivatives=False)

Sample random points in the geometry and return those meet criteria.

NOTE: sdf values returned by this function are negated because the weight in loss function should be positive.

Source code in ppsci/geometry/mesh.py
def sample_interior(
    self,
    n: int,
    random: Literal["pseudo"] = "pseudo",
    criteria: Optional[Callable[..., np.ndarray]] = None,
    evenly: bool = False,
    compute_sdf_derivatives: bool = False,
):
    """
    Sample random points in the geometry and return those meet criteria.

    NOTE: sdf values returned by this function are negated because the weight in
    loss function should be positive.
    """
    if evenly:
        # TODO(sensen): Implement uniform sample for mesh interior.
        raise NotImplementedError(
            "uniformly sample for interior in mesh is not support yet, "
            "you may need to set evenly=False in config dict of constraint"
        )
    points, areas = self.random_points(n, random, criteria)

    x_dict = misc.convert_to_dict(points, self.dim_keys)
    area_dict = misc.convert_to_dict(areas, ("area",))

    sdf = self.sdf_func(points, compute_sdf_derivatives)
    if compute_sdf_derivatives:
        sdf, sdf_derives = sdf

    # NOTE: add negative to the sdf values because weight should be positive.
    sdf_dict = misc.convert_to_dict(-sdf, ("sdf",))

    sdf_derives_dict = {}
    if compute_sdf_derivatives:
        # NOTE: Negate sdf derivatives
        sdf_derives_dict = misc.convert_to_dict(
            -sdf_derives, tuple(f"sdf__{key}" for key in self.dim_keys)
        )

    return {**x_dict, **area_dict, **sdf_dict, **sdf_derives_dict}
scale(scale)

Scale by given scale coefficient and center coordinate.

NOTE: This API generate a completely new Mesh object with scaled geometry, without modifying original Mesh object inplace.

Parameters:

Name Type Description Default
scale float

Scale coefficient.

required

Returns:

Name Type Description
Mesh 'SDFMesh'

Scaled Mesh object.

Examples:

>>> import ppsci
>>> import pymesh
>>> mesh = ppsci.geometry.SDFMesh.from_stl('/path/to/mesh.stl')
>>> mesh = mesh.scale(np.array([1.3, 1.5, 2.0]))
Source code in ppsci/geometry/mesh.py
def scale(self, scale: float) -> "SDFMesh":
    """Scale by given scale coefficient and center coordinate.

    NOTE: This API generate a completely new Mesh object with scaled geometry,
    without modifying original Mesh object inplace.

    Args:
        scale (float): Scale coefficient.

    Returns:
        Mesh: Scaled Mesh object.

    Examples:
        >>> import ppsci
        >>> import pymesh  # doctest: +SKIP
        >>> mesh = ppsci.geometry.SDFMesh.from_stl('/path/to/mesh.stl')  # doctest: +SKIP
        >>> mesh = mesh.scale(np.array([1.3, 1.5, 2.0]))  # doctest: +SKIP
    """
    new_vectors = self.vectors * scale
    return SDFMesh(
        new_vectors,
        self.face_normal,
        make_sdf(new_vectors),
    )
sdf_func(points, compute_sdf_derivatives=False)

Compute signed distance field.

Parameters:

Name Type Description Default
points ndarray

The coordinate points used to calculate the SDF value, the shape is [N, 3]

required
compute_sdf_derivatives bool

Whether to compute SDF derivatives. Defaults to False.

False

Returns:

Type Description
Union[ndarray, Tuple[ndarray, ndarray]]

Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:

Union[ndarray, Tuple[ndarray, ndarray]]

If compute_sdf_derivatives is True, then return both SDF values([N, 1]) and their derivatives([N, 3]); otherwise only return SDF values([N, 1]).

NOTE: This function usually returns ndarray with negative values, because according to the definition of SDF, the SDF value of the coordinate point inside the object(interior points) is negative, the outside is positive, and the edge is 0. Therefore, when used for weighting, a negative sign is often added before the result of this function.

Source code in ppsci/geometry/mesh.py
def sdf_func(
    self, points: np.ndarray, compute_sdf_derivatives: bool = False
) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
    """Compute signed distance field.

    Args:
        points (np.ndarray): The coordinate points used to calculate the SDF value,
            the shape is [N, 3]
        compute_sdf_derivatives (bool): Whether to compute SDF derivatives.
            Defaults to False.

    Returns:
        Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
        If compute_sdf_derivatives is True, then return both SDF values([N, 1])
            and their derivatives([N, 3]); otherwise only return SDF values([N, 1]).

    NOTE: This function usually returns ndarray with negative values, because
    according to the definition of SDF, the SDF value of the coordinate point inside
    the object(interior points) is negative, the outside is positive, and the edge
    is 0. Therefore, when used for weighting, a negative sign is often added before
    the result of this function.
    """
    # normalize triangles
    x_min, y_min, z_min = np.min(points, axis=0)
    x_max, y_max, z_max = np.max(points, axis=0)
    max_dis = max(max((x_max - x_min), (y_max - y_min)), (z_max - z_min))
    store_triangles = np.array(self.vectors, dtype=np.float64)
    store_triangles[:, :, 0] -= x_min
    store_triangles[:, :, 1] -= y_min
    store_triangles[:, :, 2] -= z_min
    store_triangles *= 1 / max_dis
    store_triangles = store_triangles.reshape([-1, 3])

    # normalize query points
    points = points.copy()
    points[:, 0] -= x_min
    points[:, 1] -= y_min
    points[:, 2] -= z_min
    points *= 1 / max_dis
    points = points.astype(np.float64).ravel()

    # compute sdf values for query points
    sdf = sdf_module.signed_distance_field(
        store_triangles,
        np.arange((store_triangles.shape[0])),
        points,
        include_hit_points=compute_sdf_derivatives,
    )
    if compute_sdf_derivatives:
        sdf, hit_points = sdf

    sdf = sdf.numpy()  # [N]
    sdf = np.expand_dims(max_dis * sdf, axis=1)  # [N, 1]

    if compute_sdf_derivatives:
        hit_points = hit_points.numpy()  # [N, 3]
        # Gradient of SDF is the unit vector from the query point to the hit point.
        sdf_derives = hit_points - points
        sdf_derives /= np.linalg.norm(sdf_derives, axis=1, keepdims=True)
        return sdf, sdf_derives

    return sdf
translate(translation)

Translate by given offsets.

NOTE: This API generate a completely new Mesh object with translated geometry, without modifying original Mesh object inplace.

Parameters:

Name Type Description Default
translation ndarray

Translation offsets, numpy array of shape (3,): [offset_x, offset_y, offset_z].

required

Returns:

Name Type Description
Mesh 'SDFMesh'

Translated Mesh object.

Examples:

>>> import ppsci
>>> import pymesh
>>> mesh = ppsci.geometry.SDFMesh.from_stl('/path/to/mesh.stl')
>>> mesh = mesh.translate(np.array([1, -1, 2]))
Source code in ppsci/geometry/mesh.py
def translate(self, translation: np.ndarray) -> "SDFMesh":
    """Translate by given offsets.

    NOTE: This API generate a completely new Mesh object with translated geometry,
    without modifying original Mesh object inplace.

    Args:
        translation (np.ndarray): Translation offsets, numpy array of shape (3,):
            [offset_x, offset_y, offset_z].

    Returns:
        Mesh: Translated Mesh object.

    Examples:
        >>> import ppsci
        >>> import pymesh  # doctest: +SKIP
        >>> mesh = ppsci.geometry.SDFMesh.from_stl('/path/to/mesh.stl')  # doctest: +SKIP
        >>> mesh = mesh.translate(np.array([1, -1, 2]))  # doctest: +SKIP
    """
    new_vectors = self.vectors + translation.reshape([1, 1, 3])

    return SDFMesh(
        new_vectors,
        self.face_normal,
        make_sdf(new_vectors),
    )
uniform_boundary_points(n)

Compute the equi-spaced points on the boundary.

Source code in ppsci/geometry/mesh.py
def uniform_boundary_points(self, n: int):
    """Compute the equi-spaced points on the boundary."""
    raise NotImplementedError(
        "'uniform_boundary_points' is not available in SDFMesh."
    )

Sphere

Bases: Hypersphere

Class for Sphere

Parameters:

Name Type Description Default
center Tuple[float, float, float]

Center of the sphere [x0, y0, z0].

required
radius float

Radius of the sphere.

required
Source code in ppsci/geometry/geometry_3d.py
class Sphere(geometry_nd.Hypersphere):
    """Class for Sphere

    Args:
        center (Tuple[float, float, float]): Center of the sphere [x0, y0, z0].
        radius (float): Radius of the sphere.
    """

    def __init__(self, center, radius):
        super().__init__(center, radius)

    def uniform_boundary_points(self, n: int):
        nl = np.arange(1, n + 1).astype(paddle.get_default_dtype())
        g = (np.sqrt(5) - 1) / 2
        z = (2 * nl - 1) / n - 1
        x = np.sqrt(1 - z**2) * np.cos(2 * np.pi * nl * g)
        y = np.sqrt(1 - z**2) * np.sin(2 * np.pi * nl * g)
        return np.stack((x, y, z), axis=-1)

    def sdf_func(self, points: np.ndarray) -> np.ndarray:
        """Compute signed distance field.

        Args:
            points (np.ndarray): The coordinate points used to calculate the SDF value,
                the shape is [N, 3]

        Returns:
            np.ndarray: SDF values of input points without squared, the shape is [N, 1].

        NOTE: This function usually returns ndarray with negative values, because
        according to the definition of SDF, the SDF value of the coordinate point inside
        the object(interior points) is negative, the outside is positive, and the edge
        is 0. Therefore, when used for weighting, a negative sign is often added before
        the result of this function.
        """
        if points.shape[1] != self.ndim:
            raise ValueError(
                f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
            )
        sdf = self.radius - (((points - self.center) ** 2).sum(axis=1)) ** 0.5
        sdf = -sdf[..., np.newaxis]
        return sdf
sdf_func(points)

Compute signed distance field.

Parameters:

Name Type Description Default
points ndarray

The coordinate points used to calculate the SDF value, the shape is [N, 3]

required

Returns:

Type Description
ndarray

np.ndarray: SDF values of input points without squared, the shape is [N, 1].

NOTE: This function usually returns ndarray with negative values, because according to the definition of SDF, the SDF value of the coordinate point inside the object(interior points) is negative, the outside is positive, and the edge is 0. Therefore, when used for weighting, a negative sign is often added before the result of this function.

Source code in ppsci/geometry/geometry_3d.py
def sdf_func(self, points: np.ndarray) -> np.ndarray:
    """Compute signed distance field.

    Args:
        points (np.ndarray): The coordinate points used to calculate the SDF value,
            the shape is [N, 3]

    Returns:
        np.ndarray: SDF values of input points without squared, the shape is [N, 1].

    NOTE: This function usually returns ndarray with negative values, because
    according to the definition of SDF, the SDF value of the coordinate point inside
    the object(interior points) is negative, the outside is positive, and the edge
    is 0. Therefore, when used for weighting, a negative sign is often added before
    the result of this function.
    """
    if points.shape[1] != self.ndim:
        raise ValueError(
            f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
        )
    sdf = self.radius - (((points - self.center) ** 2).sum(axis=1)) ** 0.5
    sdf = -sdf[..., np.newaxis]
    return sdf

TimeDomain

Bases: Interval

Class for timedomain, an special interval geometry.

Parameters:

Name Type Description Default
t0 float

Start of time.

required
t1 float

End of time.

required
time_step Optional[float]

Step interval of time. Defaults to None.

None
timestamps Optional[Tuple[float, ...]]

List of timestamps. Defaults to None.

None

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.TimeDomain(0, 1)
Source code in ppsci/geometry/timedomain.py
class TimeDomain(geometry_1d.Interval):
    """Class for timedomain, an special interval geometry.

    Args:
        t0 (float): Start of time.
        t1 (float): End of time.
        time_step (Optional[float]): Step interval of time. Defaults to None.
        timestamps (Optional[Tuple[float, ...]]): List of timestamps.
            Defaults to None.

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.TimeDomain(0, 1)
    """

    def __init__(
        self,
        t0: float,
        t1: float,
        time_step: Optional[float] = None,
        timestamps: Optional[Tuple[float, ...]] = None,
    ):
        super().__init__(t0, t1)
        self.t0 = t0
        self.t1 = t1
        assert (
            time_step is None or timestamps is None
        ), "time_step and timestamps cannot be both set."
        self.time_step = time_step
        if timestamps is not None:
            self.timestamps = np.array(
                timestamps, dtype=paddle.get_default_dtype()
            ).reshape([-1])
            self.num_timestamps = len(self.timestamps)
        elif time_step is not None:
            # set timestamps manually with given time_step
            self.timestamps = np.arange(
                t0, t1, time_step, dtype=paddle.get_default_dtype()
            )
            self.num_timestamps = len(self.timestamps)
        else:
            self.timestamps = None

    def on_initial(self, t: np.ndarray) -> np.ndarray:
        """Check if a specific time is on the initial time point.

        Args:
            t (np.ndarray): The time to be checked.

        Returns:
            np.ndarray: Bool numpy array of whether the specific time is on the initial time point.

        Examples:
            >>> import paddle
            >>> import ppsci
            >>> geom = ppsci.geometry.TimeDomain(0, 1)
            >>> 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()
on_initial(t)

Check if a specific time is on the initial time point.

Parameters:

Name Type Description Default
t ndarray

The time to be checked.

required

Returns:

Type Description
ndarray

np.ndarray: Bool numpy array of whether the specific time is on the initial time point.

Examples:

>>> import paddle
>>> import ppsci
>>> geom = ppsci.geometry.TimeDomain(0, 1)
>>> T = [0, 0.01, 0.126, 0.2, 0.3]
>>> check = geom.on_initial(T)
>>> print(check)
[ True False False False False]
Source code in ppsci/geometry/timedomain.py
def on_initial(self, t: np.ndarray) -> np.ndarray:
    """Check if a specific time is on the initial time point.

    Args:
        t (np.ndarray): The time to be checked.

    Returns:
        np.ndarray: Bool numpy array of whether the specific time is on the initial time point.

    Examples:
        >>> import paddle
        >>> import ppsci
        >>> geom = ppsci.geometry.TimeDomain(0, 1)
        >>> 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()

TimeXGeometry

Bases: Geometry

Class for combination of time and geometry.

Parameters:

Name Type Description Default
timedomain TimeDomain

TimeDomain object.

required
geometry Geometry

Geometry object.

required

Examples:

>>> import ppsci
>>> timedomain = ppsci.geometry.TimeDomain(0, 1)
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
Source code in ppsci/geometry/timedomain.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
class TimeXGeometry(geometry.Geometry):
    """Class for combination of time and geometry.

    Args:
        timedomain (TimeDomain): TimeDomain object.
        geometry (geometry.Geometry): Geometry object.

    Examples:
        >>> import ppsci
        >>> timedomain = ppsci.geometry.TimeDomain(0, 1)
        >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
    """

    def __init__(self, timedomain: TimeDomain, geometry: geometry.Geometry):
        self.timedomain = timedomain
        self.geometry = geometry
        self.ndim = geometry.ndim + timedomain.ndim

        if hasattr(self.geometry, "sdf_func"):

            def sdf_func(self, points: np.ndarray) -> np.ndarray:
                """Compute signed distance field.

                Args:
                    points (np.ndarray): The temporal-spatial coordinate points used to calculate
                        the SDF value, the shape is [N, 1+D], where 1 represents the temporal
                        dimension and D represents the spatial dimensions.

                Returns:
                    np.ndarray: SDF values of input points without squared, the shape is [N, 1].

                NOTE: This function usually returns ndarray with negative values, because
                according to the definition of SDF, the SDF value of the coordinate point inside
                the object(interior points) is negative, the outside is positive, and the edge
                is 0. Therefore, when used for weighting, a negative sign is often added before
                the result of this function.
                """
                if points.shape[1] != self.ndim:
                    raise ValueError(
                        f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
                    )
                spatial_points = points[:, 1:]
                sdf = self.geometry.sdf_func(spatial_points)
                return sdf

            self.sdf_func = types.MethodType(sdf_func, self)

    @property
    def dim_keys(self):
        return ("t",) + self.geometry.dim_keys

    def on_boundary(self, x):
        # [N, ndim(txyz)]
        return self.geometry.on_boundary(x[:, 1:])

    def on_initial(self, x):
        # [N, 1(t)]
        return self.timedomain.on_initial(x[:, :1])

    def boundary_normal(self, x):
        # x: [N, ndim(txyz)]
        normal = self.geometry.boundary_normal(x[:, 1:])
        return np.hstack((x[:, :1], normal))

    def uniform_points(self, n: int, boundary: bool = True) -> np.ndarray:
        """Uniform points on the spatial-temporal domain.
        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:
            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, 0.001)
            >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
            >>> ts = time_geom.uniform_points(1000)
            >>> print(ts.shape)
            (1000, 3)
        """
        if (
            self.timedomain.time_step is not None
            or self.timedomain.timestamps is not None
        ):
            # exclude start time t0
            nt = self.timedomain.num_timestamps - 1
            nx = int(np.ceil(n / nt))
        else:
            nx = int(
                np.ceil(
                    (
                        n
                        * np.prod(self.geometry.bbox[1] - self.geometry.bbox[0])
                        / self.timedomain.diam
                    )
                    ** 0.5
                )
            )
            nt = int(np.ceil(n / nx))
        x = self.geometry.uniform_points(nx, boundary=boundary)
        nx = len(x)
        if boundary and (
            self.timedomain.time_step is None and self.timedomain.timestamps is None
        ):
            t = self.timedomain.uniform_points(nt, boundary=True)
        else:
            if self.timedomain.time_step is not None:
                t = np.linspace(
                    self.timedomain.t1,
                    self.timedomain.t0,
                    num=nt,
                    endpoint=boundary,
                    dtype=paddle.get_default_dtype(),
                )[:, None][::-1]
            else:
                t = self.timedomain.timestamps[1:]
        tx = []
        for ti in t:
            tx.append(
                np.hstack((np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), x))
            )
        tx = np.vstack(tx)
        if len(tx) > n:
            tx = tx[:n]
        return tx

    def random_points(
        self, n: int, random: str = "pseudo", criteria: Optional[Callable] = None
    ) -> np.ndarray:
        """Generate random points on the spatial-temporal domain.

        Args:
            n (int): The total number of random points to generate.
            random (str): Specifies the way to generate random points, default is "pseudo" , which means that a pseudo-random number generator is used.
            criteria (Optional[Callable]): A method that filters on the generated random points. Defaults to None.

        Returns:
            np.ndarray: A array of random spatial-temporal points with shape [N, 1+D], where 1 represents the
            temporal dimension and D represents the spatial dimensions.

        Examples:
            >>> import ppsci
            >>> timedomain = ppsci.geometry.TimeDomain(0, 1, 0.001)
            >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
            >>> 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
            or self.timedomain.timestamps is not None
        ):
            # 1. sample nx points in static geometry with criteria
            t = self.timedomain.timestamps[1:]
            nt = self.timedomain.num_timestamps - 1
            nx = int(np.ceil(n / nt))
            _size, _ntry, _nsuc = 0, 0, 0
            x = np.empty(
                shape=(nx, self.geometry.ndim), dtype=paddle.get_default_dtype()
            )
            while _size < nx:
                _x = self.geometry.random_points(nx, random)
                if criteria is not None:
                    # fix arg 't' to None in criteria there
                    criteria_mask = criteria(
                        None, *np.split(_x, self.geometry.ndim, axis=1)
                    ).flatten()
                    _x = _x[criteria_mask]
                if len(_x) > nx - _size:
                    _x = _x[: nx - _size]
                x[_size : _size + len(_x)] = _x

                _size += len(_x)
                _ntry += 1
                if len(_x) > 0:
                    _nsuc += 1

                if _ntry >= 1000 and _nsuc == 0:
                    raise ValueError(
                        "Sample interior points failed, "
                        "please check correctness of geometry and given criteria."
                    )

            # 2. repeat spatial points along time
            tx = []
            for ti in t:
                tx.append(
                    np.hstack(
                        (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), x)
                    )
                )
            tx = np.vstack(tx)
            if len(tx) > n:
                tx = tx[:n]
            return tx

        if isinstance(self.geometry, geometry_1d.Interval):
            geom = geometry_2d.Rectangle(
                [self.timedomain.t0, self.geometry.l],
                [self.timedomain.t1, self.geometry.r],
            )
            return geom.random_points(n, random=random)

        if isinstance(self.geometry, geometry_2d.Rectangle):
            geom = geometry_3d.Cuboid(
                [self.timedomain.t0, self.geometry.xmin[0], self.geometry.xmin[1]],
                [self.timedomain.t1, self.geometry.xmax[0], self.geometry.xmax[1]],
            )
            return geom.random_points(n, random=random)

        if isinstance(self.geometry, (geometry_3d.Cuboid, geometry_nd.Hypercube)):
            geom = geometry_nd.Hypercube(
                np.append(self.timedomain.t0, self.geometry.xmin),
                np.append(self.timedomain.t1, self.geometry.xmax),
            )
            return geom.random_points(n, random=random)

        x = self.geometry.random_points(n, random=random)
        t = self.timedomain.random_points(n, random=random)
        t = np.random.permutation(t)
        return np.hstack((t, x))

    def uniform_boundary_points(
        self, n: int, criteria: Optional[Callable] = None
    ) -> np.ndarray:
        """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 (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.

        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)
            >>> print(ts.shape)
            (1000, 3)
        """
        if self.geometry.ndim == 1:
            nx = 2
        else:
            s = 2 * sum(
                map(
                    lambda l: l[0] * l[1],
                    itertools.combinations(
                        self.geometry.bbox[1] - self.geometry.bbox[0], 2
                    ),
                )
            )
            nx = int((n * s / self.timedomain.diam) ** 0.5)
        nt = int(np.ceil(n / nx))

        _size, _ntry, _nsuc = 0, 0, 0
        x = np.empty(shape=(nx, self.geometry.ndim), dtype=paddle.get_default_dtype())
        while _size < nx:
            _x = self.geometry.uniform_boundary_points(nx)
            if criteria is not None:
                # fix arg 't' to None in criteria there
                criteria_mask = criteria(
                    None, *np.split(_x, self.geometry.ndim, axis=1)
                ).flatten()
                _x = _x[criteria_mask]
            if len(_x) > nx - _size:
                _x = _x[: nx - _size]
            x[_size : _size + len(_x)] = _x

            _size += len(_x)
            _ntry += 1
            if len(_x) > 0:
                _nsuc += 1

            if _ntry >= 1000 and _nsuc == 0:
                raise ValueError(
                    "Sample boundary points failed, "
                    "please check correctness of geometry and given criteria."
                )

        nx = len(x)
        t = np.linspace(
            self.timedomain.t1,
            self.timedomain.t0,
            num=nt,
            endpoint=False,
            dtype=paddle.get_default_dtype(),
        )[:, None][::-1]
        tx = []
        for ti in t:
            tx.append(
                np.hstack((np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), x))
            )
        tx = np.vstack(tx)
        if len(tx) > n:
            tx = tx[:n]
        return tx

    def random_boundary_points(
        self, n: int, random: str = "pseudo", criteria: Optional[Callable] = None
    ) -> np.ndarray:
        """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 (str): Controls the way to generate random points. Default is "pseudo".
            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.

        Examples:
            >>> import ppsci
            >>> timedomain = ppsci.geometry.TimeDomain(0, 1, 0.001)
            >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
            >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
            >>> 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))
            t = np.linspace(
                self.timedomain.t1,
                self.timedomain.t0,
                num=nt,
                endpoint=False,
                dtype=paddle.get_default_dtype(),
            )[:, None][::-1]
            nx = int(np.ceil(n / nt))

            if isinstance(self.geometry, mesh.Mesh):
                x, _n, a = self.geometry.random_boundary_points(nx, random=random)
            else:
                _size, _ntry, _nsuc = 0, 0, 0
                x = np.empty(
                    shape=(nx, self.geometry.ndim), dtype=paddle.get_default_dtype()
                )
                while _size < nx:
                    _x = self.geometry.random_boundary_points(nx, random)
                    if criteria is not None:
                        # fix arg 't' to None in criteria there
                        criteria_mask = criteria(
                            None, *np.split(_x, self.geometry.ndim, axis=1)
                        ).flatten()
                        _x = _x[criteria_mask]
                    if len(_x) > nx - _size:
                        _x = _x[: nx - _size]
                    x[_size : _size + len(_x)] = _x

                    _size += len(_x)
                    _ntry += 1
                    if len(_x) > 0:
                        _nsuc += 1

                    if _ntry >= 1000 and _nsuc == 0:
                        raise ValueError(
                            "Sample boundary points failed, "
                            "please check correctness of geometry and given criteria."
                        )

            t_x = []
            if isinstance(self.geometry, mesh.Mesh):
                t_normal = []
                t_area = []

            for ti in t:
                t_x.append(
                    np.hstack(
                        (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), x)
                    )
                )
                if isinstance(self.geometry, mesh.Mesh):
                    t_normal.append(
                        np.hstack(
                            (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), _n)
                        )
                    )
                    t_area.append(
                        np.hstack(
                            (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), a)
                        )
                    )

            t_x = np.vstack(t_x)
            if isinstance(self.geometry, mesh.Mesh):
                t_normal = np.vstack(t_normal)
                t_area = np.vstack(t_area)

            if len(t_x) > n:
                t_x = t_x[:n]
                if isinstance(self.geometry, mesh.Mesh):
                    t_normal = t_normal[:n]
                    t_area = t_area[:n]

            if isinstance(self.geometry, mesh.Mesh):
                return t_x, t_normal, t_area
            else:
                return t_x
        elif self.timedomain.timestamps is not None:
            # exclude start time t0
            nt = self.timedomain.num_timestamps - 1
            t = self.timedomain.timestamps[1:]
            nx = int(np.ceil(n / nt))

            if isinstance(self.geometry, mesh.Mesh):
                x, _n, a = self.geometry.random_boundary_points(nx, random=random)
            else:
                _size, _ntry, _nsuc = 0, 0, 0
                x = np.empty(
                    shape=(nx, self.geometry.ndim), dtype=paddle.get_default_dtype()
                )
                while _size < nx:
                    _x = self.geometry.random_boundary_points(nx, random)
                    if criteria is not None:
                        # fix arg 't' to None in criteria there
                        criteria_mask = criteria(
                            None, *np.split(_x, self.geometry.ndim, axis=1)
                        ).flatten()
                        _x = _x[criteria_mask]
                    if len(_x) > nx - _size:
                        _x = _x[: nx - _size]
                    x[_size : _size + len(_x)] = _x

                    _size += len(_x)
                    _ntry += 1
                    if len(_x) > 0:
                        _nsuc += 1

                    if _ntry >= 1000 and _nsuc == 0:
                        raise ValueError(
                            "Sample boundary points failed, "
                            "please check correctness of geometry and given criteria."
                        )

            t_x = []
            if isinstance(self.geometry, mesh.Mesh):
                t_normal = []
                t_area = []

            for ti in t:
                t_x.append(
                    np.hstack(
                        (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), x)
                    )
                )
                if isinstance(self.geometry, mesh.Mesh):
                    t_normal.append(
                        np.hstack(
                            (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), _n)
                        )
                    )
                    t_area.append(
                        np.hstack(
                            (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), a)
                        )
                    )

            t_x = np.vstack(t_x)
            if isinstance(self.geometry, mesh.Mesh):
                t_normal = np.vstack(t_normal)
                t_area = np.vstack(t_area)

            if len(t_x) > n:
                t_x = t_x[:n]
                if isinstance(self.geometry, mesh.Mesh):
                    t_normal = t_normal[:n]
                    t_area = t_area[:n]

            if isinstance(self.geometry, mesh.Mesh):
                return t_x, t_normal, t_area
            else:
                return t_x
        else:
            if isinstance(self.geometry, mesh.Mesh):
                x, _n, a = self.geometry.random_boundary_points(n, random=random)
            else:
                x = self.geometry.random_boundary_points(n, random=random)

            t = self.timedomain.random_points(n, random=random)
            t = np.random.permutation(t)

            t_x = np.hstack((t, x))

            if isinstance(self.geometry, mesh.Mesh):
                t_normal = np.hstack((_n, t))
                t_area = np.hstack((_n, t))
                return t_x, t_normal, t_area
            else:
                return t_x

    def uniform_initial_points(self, n: int) -> np.ndarray:
        """Generate evenly distributed point coordinates on the spatial-temporal domain at the initial moment.

        Args:
            n (int): The total number of generated points.

        Returns:
           np.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)
            >>> print(ts.shape)
            (1000, 3)
        """
        x = self.geometry.uniform_points(n, True)
        t = self.timedomain.t0
        if len(x) > n:
            x = x[:n]
        return np.hstack((np.full([n, 1], t, dtype=paddle.get_default_dtype()), x))

    def random_initial_points(self, n: int, random: str = "pseudo") -> np.ndarray:
        """Generate randomly distributed point coordinates on the spatial-temporal domain at the initial moment.

        Args:
            n (int): The total number of generated points.
            random (str): Controls the way to generate random points. Default is "pseudo".

        Returns:
            np.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)
            >>> 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: Dict[str, np.ndarray], component: int
    ) -> Dict[str, np.ndarray]:
        """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.
            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.

        Examples:
        >>> 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)
        txp = {"t": x["t"], **xp}
        return txp

    def sample_initial_interior(
        self,
        n: int,
        random: str = "pseudo",
        criteria: Optional[Callable] = None,
        evenly: bool = False,
        compute_sdf_derivatives: bool = False,
    ) -> Dict[str, np.ndarray]:
        """Sample random points in the time-geometry and return those meet criteria.

        Args:
            n (int): The total number of interior points generated.
            random (str): The method used to specify the initial point of generation. Default is "pseudo".
            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.

        Returns:
            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
            >>> 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)
            >>> 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())
        _size, _ntry, _nsuc = 0, 0, 0
        while _size < n:
            if evenly:
                points = self.uniform_initial_points(n)
            else:
                points = self.random_initial_points(n, random)

            if criteria is not None:
                criteria_mask = criteria(*np.split(points, self.ndim, axis=1)).flatten()
                points = points[criteria_mask]

            if len(points) > n - _size:
                points = points[: n - _size]
            x[_size : _size + len(points)] = points

            _size += len(points)
            _ntry += 1
            if len(points) > 0:
                _nsuc += 1

            if _ntry >= 1000 and _nsuc == 0:
                raise ValueError(
                    "Sample initial interior points failed, "
                    "please check correctness of geometry and given criteria."
                )

        # if sdf_func added, return x_dict and sdf_dict, else, only return the x_dict
        if hasattr(self.geometry, "sdf_func"):
            # compute sdf excluding time t
            sdf = -self.geometry.sdf_func(x[..., 1:])
            sdf_dict = misc.convert_to_dict(sdf, ("sdf",))
            sdf_derives_dict = {}
            if compute_sdf_derivatives:
                # compute sdf derivatives excluding time t
                sdf_derives = -self.geometry.sdf_derivatives(x[..., 1:])
                sdf_derives_dict = misc.convert_to_dict(
                    sdf_derives, tuple(f"sdf__{key}" for key in self.geometry.dim_keys)
                )
        else:
            sdf_dict = {}
            sdf_derives_dict = {}
        x_dict = misc.convert_to_dict(x, self.dim_keys)

        return {**x_dict, **sdf_dict, **sdf_derives_dict}

    def __str__(self) -> str:
        """Return the name of class"""
        return ", ".join(
            [
                self.__class__.__name__,
                f"ndim = {self.ndim}",
                f"bbox = (time){self.timedomain.bbox} x (space){self.geometry.bbox}",
                f"diam = (time){self.timedomain.diam} x (space){self.geometry.diam}",
                f"dim_keys = {self.dim_keys}",
            ]
        )
__init__(timedomain, geometry)
Source code in ppsci/geometry/timedomain.py
def __init__(self, timedomain: TimeDomain, geometry: geometry.Geometry):
    self.timedomain = timedomain
    self.geometry = geometry
    self.ndim = geometry.ndim + timedomain.ndim

    if hasattr(self.geometry, "sdf_func"):

        def sdf_func(self, points: np.ndarray) -> np.ndarray:
            """Compute signed distance field.

            Args:
                points (np.ndarray): The temporal-spatial coordinate points used to calculate
                    the SDF value, the shape is [N, 1+D], where 1 represents the temporal
                    dimension and D represents the spatial dimensions.

            Returns:
                np.ndarray: SDF values of input points without squared, the shape is [N, 1].

            NOTE: This function usually returns ndarray with negative values, because
            according to the definition of SDF, the SDF value of the coordinate point inside
            the object(interior points) is negative, the outside is positive, and the edge
            is 0. Therefore, when used for weighting, a negative sign is often added before
            the result of this function.
            """
            if points.shape[1] != self.ndim:
                raise ValueError(
                    f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
                )
            spatial_points = points[:, 1:]
            sdf = self.geometry.sdf_func(spatial_points)
            return sdf

        self.sdf_func = types.MethodType(sdf_func, self)
__str__()

Return the name of class

Source code in ppsci/geometry/timedomain.py
def __str__(self) -> str:
    """Return the name of class"""
    return ", ".join(
        [
            self.__class__.__name__,
            f"ndim = {self.ndim}",
            f"bbox = (time){self.timedomain.bbox} x (space){self.geometry.bbox}",
            f"diam = (time){self.timedomain.diam} x (space){self.geometry.diam}",
            f"dim_keys = {self.dim_keys}",
        ]
    )
periodic_point(x, component)

Process given point coordinates to satisfy the periodic boundary conditions of the geometry.

Parameters:

Name Type Description Default
x Dict[str, ndarray]

Contains the coordinates and timestamps of the points. It represents the coordinates of the point to be processed.

required
component int

Specifies the components or dimensions of specific spatial coordinates that are periodically processed.

required

Returns:

Type Description
Dict[str, ndarray]

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, 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)

Source code in ppsci/geometry/timedomain.py
def periodic_point(
    self, x: Dict[str, np.ndarray], component: int
) -> Dict[str, np.ndarray]:
    """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.
        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.

    Examples:
    >>> 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)
    txp = {"t": x["t"], **xp}
    return txp
random_boundary_points(n, random='pseudo', criteria=None)

Random boundary points on the spatial-temporal domain.

Parameters:

Name Type Description Default
n int

The total number of spatial-temporal points generated on a given geometry boundary.

required
random str

Controls the way to generate random points. Default is "pseudo".

'pseudo'
criteria Optional[Callable]

Used to filter the generated boundary points, only points that meet certain conditions are retained. Default is None.

None

Returns:

Type Description
ndarray

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, 0.001)
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
>>> ts = time_geom.random_boundary_points(1000)
>>> print(ts.shape)
(1000, 3)
Source code in ppsci/geometry/timedomain.py
def random_boundary_points(
    self, n: int, random: str = "pseudo", criteria: Optional[Callable] = None
) -> np.ndarray:
    """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 (str): Controls the way to generate random points. Default is "pseudo".
        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.

    Examples:
        >>> import ppsci
        >>> timedomain = ppsci.geometry.TimeDomain(0, 1, 0.001)
        >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
        >>> 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))
        t = np.linspace(
            self.timedomain.t1,
            self.timedomain.t0,
            num=nt,
            endpoint=False,
            dtype=paddle.get_default_dtype(),
        )[:, None][::-1]
        nx = int(np.ceil(n / nt))

        if isinstance(self.geometry, mesh.Mesh):
            x, _n, a = self.geometry.random_boundary_points(nx, random=random)
        else:
            _size, _ntry, _nsuc = 0, 0, 0
            x = np.empty(
                shape=(nx, self.geometry.ndim), dtype=paddle.get_default_dtype()
            )
            while _size < nx:
                _x = self.geometry.random_boundary_points(nx, random)
                if criteria is not None:
                    # fix arg 't' to None in criteria there
                    criteria_mask = criteria(
                        None, *np.split(_x, self.geometry.ndim, axis=1)
                    ).flatten()
                    _x = _x[criteria_mask]
                if len(_x) > nx - _size:
                    _x = _x[: nx - _size]
                x[_size : _size + len(_x)] = _x

                _size += len(_x)
                _ntry += 1
                if len(_x) > 0:
                    _nsuc += 1

                if _ntry >= 1000 and _nsuc == 0:
                    raise ValueError(
                        "Sample boundary points failed, "
                        "please check correctness of geometry and given criteria."
                    )

        t_x = []
        if isinstance(self.geometry, mesh.Mesh):
            t_normal = []
            t_area = []

        for ti in t:
            t_x.append(
                np.hstack(
                    (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), x)
                )
            )
            if isinstance(self.geometry, mesh.Mesh):
                t_normal.append(
                    np.hstack(
                        (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), _n)
                    )
                )
                t_area.append(
                    np.hstack(
                        (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), a)
                    )
                )

        t_x = np.vstack(t_x)
        if isinstance(self.geometry, mesh.Mesh):
            t_normal = np.vstack(t_normal)
            t_area = np.vstack(t_area)

        if len(t_x) > n:
            t_x = t_x[:n]
            if isinstance(self.geometry, mesh.Mesh):
                t_normal = t_normal[:n]
                t_area = t_area[:n]

        if isinstance(self.geometry, mesh.Mesh):
            return t_x, t_normal, t_area
        else:
            return t_x
    elif self.timedomain.timestamps is not None:
        # exclude start time t0
        nt = self.timedomain.num_timestamps - 1
        t = self.timedomain.timestamps[1:]
        nx = int(np.ceil(n / nt))

        if isinstance(self.geometry, mesh.Mesh):
            x, _n, a = self.geometry.random_boundary_points(nx, random=random)
        else:
            _size, _ntry, _nsuc = 0, 0, 0
            x = np.empty(
                shape=(nx, self.geometry.ndim), dtype=paddle.get_default_dtype()
            )
            while _size < nx:
                _x = self.geometry.random_boundary_points(nx, random)
                if criteria is not None:
                    # fix arg 't' to None in criteria there
                    criteria_mask = criteria(
                        None, *np.split(_x, self.geometry.ndim, axis=1)
                    ).flatten()
                    _x = _x[criteria_mask]
                if len(_x) > nx - _size:
                    _x = _x[: nx - _size]
                x[_size : _size + len(_x)] = _x

                _size += len(_x)
                _ntry += 1
                if len(_x) > 0:
                    _nsuc += 1

                if _ntry >= 1000 and _nsuc == 0:
                    raise ValueError(
                        "Sample boundary points failed, "
                        "please check correctness of geometry and given criteria."
                    )

        t_x = []
        if isinstance(self.geometry, mesh.Mesh):
            t_normal = []
            t_area = []

        for ti in t:
            t_x.append(
                np.hstack(
                    (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), x)
                )
            )
            if isinstance(self.geometry, mesh.Mesh):
                t_normal.append(
                    np.hstack(
                        (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), _n)
                    )
                )
                t_area.append(
                    np.hstack(
                        (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), a)
                    )
                )

        t_x = np.vstack(t_x)
        if isinstance(self.geometry, mesh.Mesh):
            t_normal = np.vstack(t_normal)
            t_area = np.vstack(t_area)

        if len(t_x) > n:
            t_x = t_x[:n]
            if isinstance(self.geometry, mesh.Mesh):
                t_normal = t_normal[:n]
                t_area = t_area[:n]

        if isinstance(self.geometry, mesh.Mesh):
            return t_x, t_normal, t_area
        else:
            return t_x
    else:
        if isinstance(self.geometry, mesh.Mesh):
            x, _n, a = self.geometry.random_boundary_points(n, random=random)
        else:
            x = self.geometry.random_boundary_points(n, random=random)

        t = self.timedomain.random_points(n, random=random)
        t = np.random.permutation(t)

        t_x = np.hstack((t, x))

        if isinstance(self.geometry, mesh.Mesh):
            t_normal = np.hstack((_n, t))
            t_area = np.hstack((_n, t))
            return t_x, t_normal, t_area
        else:
            return t_x
random_initial_points(n, random='pseudo')

Generate randomly distributed point coordinates on the spatial-temporal domain at the initial moment.

Parameters:

Name Type Description Default
n int

The total number of generated points.

required
random str

Controls the way to generate random points. Default is "pseudo".

'pseudo'

Returns:

Type Description
ndarray

np.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)
>>> print(ts.shape)
(1000, 3)
Source code in ppsci/geometry/timedomain.py
def random_initial_points(self, n: int, random: str = "pseudo") -> np.ndarray:
    """Generate randomly distributed point coordinates on the spatial-temporal domain at the initial moment.

    Args:
        n (int): The total number of generated points.
        random (str): Controls the way to generate random points. Default is "pseudo".

    Returns:
        np.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)
        >>> 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))
random_points(n, random='pseudo', criteria=None)

Generate random points on the spatial-temporal domain.

Parameters:

Name Type Description Default
n int

The total number of random points to generate.

required
random str

Specifies the way to generate random points, default is "pseudo" , which means that a pseudo-random number generator is used.

'pseudo'
criteria Optional[Callable]

A method that filters on the generated random points. Defaults to None.

None

Returns:

Type Description
ndarray

np.ndarray: A array of random spatial-temporal points with shape [N, 1+D], where 1 represents the

ndarray

temporal dimension and D represents the spatial dimensions.

Examples:

>>> import ppsci
>>> timedomain = ppsci.geometry.TimeDomain(0, 1, 0.001)
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
>>> ts = time_geom.random_points(1000)
>>> print(ts.shape)
(1000, 3)
Source code in ppsci/geometry/timedomain.py
def random_points(
    self, n: int, random: str = "pseudo", criteria: Optional[Callable] = None
) -> np.ndarray:
    """Generate random points on the spatial-temporal domain.

    Args:
        n (int): The total number of random points to generate.
        random (str): Specifies the way to generate random points, default is "pseudo" , which means that a pseudo-random number generator is used.
        criteria (Optional[Callable]): A method that filters on the generated random points. Defaults to None.

    Returns:
        np.ndarray: A array of random spatial-temporal points with shape [N, 1+D], where 1 represents the
        temporal dimension and D represents the spatial dimensions.

    Examples:
        >>> import ppsci
        >>> timedomain = ppsci.geometry.TimeDomain(0, 1, 0.001)
        >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
        >>> 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
        or self.timedomain.timestamps is not None
    ):
        # 1. sample nx points in static geometry with criteria
        t = self.timedomain.timestamps[1:]
        nt = self.timedomain.num_timestamps - 1
        nx = int(np.ceil(n / nt))
        _size, _ntry, _nsuc = 0, 0, 0
        x = np.empty(
            shape=(nx, self.geometry.ndim), dtype=paddle.get_default_dtype()
        )
        while _size < nx:
            _x = self.geometry.random_points(nx, random)
            if criteria is not None:
                # fix arg 't' to None in criteria there
                criteria_mask = criteria(
                    None, *np.split(_x, self.geometry.ndim, axis=1)
                ).flatten()
                _x = _x[criteria_mask]
            if len(_x) > nx - _size:
                _x = _x[: nx - _size]
            x[_size : _size + len(_x)] = _x

            _size += len(_x)
            _ntry += 1
            if len(_x) > 0:
                _nsuc += 1

            if _ntry >= 1000 and _nsuc == 0:
                raise ValueError(
                    "Sample interior points failed, "
                    "please check correctness of geometry and given criteria."
                )

        # 2. repeat spatial points along time
        tx = []
        for ti in t:
            tx.append(
                np.hstack(
                    (np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), x)
                )
            )
        tx = np.vstack(tx)
        if len(tx) > n:
            tx = tx[:n]
        return tx

    if isinstance(self.geometry, geometry_1d.Interval):
        geom = geometry_2d.Rectangle(
            [self.timedomain.t0, self.geometry.l],
            [self.timedomain.t1, self.geometry.r],
        )
        return geom.random_points(n, random=random)

    if isinstance(self.geometry, geometry_2d.Rectangle):
        geom = geometry_3d.Cuboid(
            [self.timedomain.t0, self.geometry.xmin[0], self.geometry.xmin[1]],
            [self.timedomain.t1, self.geometry.xmax[0], self.geometry.xmax[1]],
        )
        return geom.random_points(n, random=random)

    if isinstance(self.geometry, (geometry_3d.Cuboid, geometry_nd.Hypercube)):
        geom = geometry_nd.Hypercube(
            np.append(self.timedomain.t0, self.geometry.xmin),
            np.append(self.timedomain.t1, self.geometry.xmax),
        )
        return geom.random_points(n, random=random)

    x = self.geometry.random_points(n, random=random)
    t = self.timedomain.random_points(n, random=random)
    t = np.random.permutation(t)
    return np.hstack((t, x))
sample_initial_interior(n, random='pseudo', criteria=None, evenly=False, compute_sdf_derivatives=False)

Sample random points in the time-geometry and return those meet criteria.

Parameters:

Name Type Description Default
n int

The total number of interior points generated.

required
random str

The method used to specify the initial point of generation. Default is "pseudo".

'pseudo'
criteria Optional[Callable]

Used to filter the generated interior points, only points that meet certain conditions are retained. Default is None.

None
evenly bool

Indicates whether the initial points are generated evenly. Default is False.

False
compute_sdf_derivatives bool

Indicates whether to calculate the derivative of signed distance function or not. Default is False.

False

Returns:

Type Description
Dict[str, ndarray]

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
>>> 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)
>>> for k,v in ts.items():
...     print(k, v.shape)
t (1000, 1)
x (1000, 1)
y (1000, 1)
sdf (1000, 1)
Source code in ppsci/geometry/timedomain.py
def sample_initial_interior(
    self,
    n: int,
    random: str = "pseudo",
    criteria: Optional[Callable] = None,
    evenly: bool = False,
    compute_sdf_derivatives: bool = False,
) -> Dict[str, np.ndarray]:
    """Sample random points in the time-geometry and return those meet criteria.

    Args:
        n (int): The total number of interior points generated.
        random (str): The method used to specify the initial point of generation. Default is "pseudo".
        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.

    Returns:
        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
        >>> 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)
        >>> 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())
    _size, _ntry, _nsuc = 0, 0, 0
    while _size < n:
        if evenly:
            points = self.uniform_initial_points(n)
        else:
            points = self.random_initial_points(n, random)

        if criteria is not None:
            criteria_mask = criteria(*np.split(points, self.ndim, axis=1)).flatten()
            points = points[criteria_mask]

        if len(points) > n - _size:
            points = points[: n - _size]
        x[_size : _size + len(points)] = points

        _size += len(points)
        _ntry += 1
        if len(points) > 0:
            _nsuc += 1

        if _ntry >= 1000 and _nsuc == 0:
            raise ValueError(
                "Sample initial interior points failed, "
                "please check correctness of geometry and given criteria."
            )

    # if sdf_func added, return x_dict and sdf_dict, else, only return the x_dict
    if hasattr(self.geometry, "sdf_func"):
        # compute sdf excluding time t
        sdf = -self.geometry.sdf_func(x[..., 1:])
        sdf_dict = misc.convert_to_dict(sdf, ("sdf",))
        sdf_derives_dict = {}
        if compute_sdf_derivatives:
            # compute sdf derivatives excluding time t
            sdf_derives = -self.geometry.sdf_derivatives(x[..., 1:])
            sdf_derives_dict = misc.convert_to_dict(
                sdf_derives, tuple(f"sdf__{key}" for key in self.geometry.dim_keys)
            )
    else:
        sdf_dict = {}
        sdf_derives_dict = {}
    x_dict = misc.convert_to_dict(x, self.dim_keys)

    return {**x_dict, **sdf_dict, **sdf_derives_dict}
uniform_boundary_points(n, criteria=None)

Uniform boundary points on the spatial-temporal domain. Geometry surface area ~ bbox. Time surface area ~ diam.

Parameters:

Name Type Description Default
n int

The total number of boundary points on the spatial-temporal domain to be generated that are evenly distributed across geometry boundaries.

required
criteria Optional[Callable]

Used to filter the generated boundary points, only points that meet certain conditions are retained. Default is None.

None

Returns:

Type Description
ndarray

np.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)
>>> print(ts.shape)
(1000, 3)
Source code in ppsci/geometry/timedomain.py
def uniform_boundary_points(
    self, n: int, criteria: Optional[Callable] = None
) -> np.ndarray:
    """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 (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.

    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)
        >>> print(ts.shape)
        (1000, 3)
    """
    if self.geometry.ndim == 1:
        nx = 2
    else:
        s = 2 * sum(
            map(
                lambda l: l[0] * l[1],
                itertools.combinations(
                    self.geometry.bbox[1] - self.geometry.bbox[0], 2
                ),
            )
        )
        nx = int((n * s / self.timedomain.diam) ** 0.5)
    nt = int(np.ceil(n / nx))

    _size, _ntry, _nsuc = 0, 0, 0
    x = np.empty(shape=(nx, self.geometry.ndim), dtype=paddle.get_default_dtype())
    while _size < nx:
        _x = self.geometry.uniform_boundary_points(nx)
        if criteria is not None:
            # fix arg 't' to None in criteria there
            criteria_mask = criteria(
                None, *np.split(_x, self.geometry.ndim, axis=1)
            ).flatten()
            _x = _x[criteria_mask]
        if len(_x) > nx - _size:
            _x = _x[: nx - _size]
        x[_size : _size + len(_x)] = _x

        _size += len(_x)
        _ntry += 1
        if len(_x) > 0:
            _nsuc += 1

        if _ntry >= 1000 and _nsuc == 0:
            raise ValueError(
                "Sample boundary points failed, "
                "please check correctness of geometry and given criteria."
            )

    nx = len(x)
    t = np.linspace(
        self.timedomain.t1,
        self.timedomain.t0,
        num=nt,
        endpoint=False,
        dtype=paddle.get_default_dtype(),
    )[:, None][::-1]
    tx = []
    for ti in t:
        tx.append(
            np.hstack((np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), x))
        )
    tx = np.vstack(tx)
    if len(tx) > n:
        tx = tx[:n]
    return tx
uniform_initial_points(n)

Generate evenly distributed point coordinates on the spatial-temporal domain at the initial moment.

Parameters:

Name Type Description Default
n int

The total number of generated points.

required

Returns:

Type Description
ndarray

np.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)
>>> print(ts.shape)
(1000, 3)
Source code in ppsci/geometry/timedomain.py
def uniform_initial_points(self, n: int) -> np.ndarray:
    """Generate evenly distributed point coordinates on the spatial-temporal domain at the initial moment.

    Args:
        n (int): The total number of generated points.

    Returns:
       np.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)
        >>> print(ts.shape)
        (1000, 3)
    """
    x = self.geometry.uniform_points(n, True)
    t = self.timedomain.t0
    if len(x) > n:
        x = x[:n]
    return np.hstack((np.full([n, 1], t, dtype=paddle.get_default_dtype()), x))
uniform_points(n, boundary=True)

Uniform points on the spatial-temporal domain. Geometry volume ~ bbox. Time volume ~ diam.

Parameters:

Name Type Description Default
n int

The total number of sample points to be generated.

required
boundary bool

Indicates whether boundary points are included, default is True.

True

Returns:

Type Description
ndarray

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, 0.001)
>>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
>>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
>>> ts = time_geom.uniform_points(1000)
>>> print(ts.shape)
(1000, 3)
Source code in ppsci/geometry/timedomain.py
def uniform_points(self, n: int, boundary: bool = True) -> np.ndarray:
    """Uniform points on the spatial-temporal domain.
    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:
        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, 0.001)
        >>> geom = ppsci.geometry.Rectangle((0, 0), (1, 1))
        >>> time_geom = ppsci.geometry.TimeXGeometry(timedomain, geom)
        >>> ts = time_geom.uniform_points(1000)
        >>> print(ts.shape)
        (1000, 3)
    """
    if (
        self.timedomain.time_step is not None
        or self.timedomain.timestamps is not None
    ):
        # exclude start time t0
        nt = self.timedomain.num_timestamps - 1
        nx = int(np.ceil(n / nt))
    else:
        nx = int(
            np.ceil(
                (
                    n
                    * np.prod(self.geometry.bbox[1] - self.geometry.bbox[0])
                    / self.timedomain.diam
                )
                ** 0.5
            )
        )
        nt = int(np.ceil(n / nx))
    x = self.geometry.uniform_points(nx, boundary=boundary)
    nx = len(x)
    if boundary and (
        self.timedomain.time_step is None and self.timedomain.timestamps is None
    ):
        t = self.timedomain.uniform_points(nt, boundary=True)
    else:
        if self.timedomain.time_step is not None:
            t = np.linspace(
                self.timedomain.t1,
                self.timedomain.t0,
                num=nt,
                endpoint=boundary,
                dtype=paddle.get_default_dtype(),
            )[:, None][::-1]
        else:
            t = self.timedomain.timestamps[1:]
    tx = []
    for ti in t:
        tx.append(
            np.hstack((np.full([nx, 1], ti, dtype=paddle.get_default_dtype()), x))
        )
    tx = np.vstack(tx)
    if len(tx) > n:
        tx = tx[:n]
    return tx

Triangle

Bases: Geometry

Class for Triangle

The order of vertices can be in a clockwise or counterclockwise direction. The vertices will be re-ordered in counterclockwise (right hand rule).

Parameters:

Name Type Description Default
x1 Tuple[float, float]

First point of Triangle [x0, y0].

required
x2 Tuple[float, float]

Second point of Triangle [x1, y1].

required
x3 Tuple[float, float]

Third point of Triangle [x2, y2].

required

Examples:

>>> import ppsci
>>> geom = ppsci.geometry.Triangle((0, 0), (1, 0), (0, 1))
Source code in ppsci/geometry/geometry_2d.py
class Triangle(geometry.Geometry):
    """Class for Triangle

    The order of vertices can be in a clockwise or counterclockwise direction. The
    vertices will be re-ordered in counterclockwise (right hand rule).

    Args:
        x1 (Tuple[float, float]): First point of Triangle [x0, y0].
        x2 (Tuple[float, float]): Second point of Triangle [x1, y1].
        x3 (Tuple[float, float]): Third point of Triangle [x2, y2].

    Examples:
        >>> import ppsci
        >>> geom = ppsci.geometry.Triangle((0, 0), (1, 0), (0, 1))
    """

    def __init__(self, x1, x2, x3):
        self.area = polygon_signed_area([x1, x2, x3])
        # Clockwise
        if self.area < 0:
            self.area = -self.area
            x2, x3 = x3, x2

        self.x1 = np.array(x1, dtype=paddle.get_default_dtype())
        self.x2 = np.array(x2, dtype=paddle.get_default_dtype())
        self.x3 = np.array(x3, dtype=paddle.get_default_dtype())

        self.v12 = self.x2 - self.x1
        self.v23 = self.x3 - self.x2
        self.v31 = self.x1 - self.x3
        self.l12 = np.linalg.norm(self.v12)
        self.l23 = np.linalg.norm(self.v23)
        self.l31 = np.linalg.norm(self.v31)
        self.n12 = self.v12 / self.l12
        self.n23 = self.v23 / self.l23
        self.n31 = self.v31 / self.l31
        self.n12_normal = clockwise_rotation_90(self.n12)
        self.n23_normal = clockwise_rotation_90(self.n23)
        self.n31_normal = clockwise_rotation_90(self.n31)
        self.perimeter = self.l12 + self.l23 + self.l31

        super().__init__(
            2,
            (np.minimum(x1, np.minimum(x2, x3)), np.maximum(x1, np.maximum(x2, x3))),
            self.l12
            * self.l23
            * self.l31
            / (
                self.perimeter
                * (self.l12 + self.l23 - self.l31)
                * (self.l23 + self.l31 - self.l12)
                * (self.l31 + self.l12 - self.l23)
            )
            ** 0.5,
        )

    def is_inside(self, x):
        # https://stackoverflow.com/a/2049593/12679294
        _sign = np.stack(
            [
                np.cross(self.v12, x - self.x1),
                np.cross(self.v23, x - self.x2),
                np.cross(self.v31, x - self.x3),
            ],
            axis=1,
        )
        return ~(np.any(_sign > 0, axis=-1) & np.any(_sign < 0, axis=-1))

    def on_boundary(self, x):
        l1 = np.linalg.norm(x - self.x1, axis=-1)
        l2 = np.linalg.norm(x - self.x2, axis=-1)
        l3 = np.linalg.norm(x - self.x3, axis=-1)
        return np.any(
            np.isclose(
                [l1 + l2 - self.l12, l2 + l3 - self.l23, l3 + l1 - self.l31],
                0,
                atol=1e-6,
            ),
            axis=0,
        )

    def boundary_normal(self, x):
        l1 = np.linalg.norm(x - self.x1, axis=-1, keepdims=True)
        l2 = np.linalg.norm(x - self.x2, axis=-1, keepdims=True)
        l3 = np.linalg.norm(x - self.x3, axis=-1, keepdims=True)
        on12 = np.isclose(l1 + l2, self.l12)
        on23 = np.isclose(l2 + l3, self.l23)
        on31 = np.isclose(l3 + l1, self.l31)
        # Check points on the vertexes
        if np.any(np.count_nonzero(np.hstack([on12, on23, on31]), axis=-1) > 1):
            raise ValueError(
                "{}.boundary_normal do not accept points on the vertexes.".format(
                    self.__class__.__name__
                )
            )
        return self.n12_normal * on12 + self.n23_normal * on23 + self.n31_normal * on31

    def random_points(self, n, random="pseudo"):
        # There are two methods for triangle point picking.
        # Method 1 (used here):
        # - https://math.stackexchange.com/questions/18686/uniform-random-point-in-triangle
        # Method 2:
        # - http://mathworld.wolfram.com/TrianglePointPicking.html
        # - https://hbfs.wordpress.com/2010/10/05/random-points-in-a-triangle-generating-random-sequences-ii/
        # - https://stackoverflow.com/questions/19654251/random-point-inside-triangle-inside-java
        sqrt_r1 = np.sqrt(np.random.rand(n, 1))
        r2 = np.random.rand(n, 1)
        return (
            (1 - sqrt_r1) * self.x1
            + sqrt_r1 * (1 - r2) * self.x2
            + r2 * sqrt_r1 * self.x3
        )

    def uniform_boundary_points(self, n):
        density = n / self.perimeter
        x12 = (
            np.linspace(
                0,
                1,
                num=int(np.ceil(density * self.l12)),
                endpoint=False,
                dtype=paddle.get_default_dtype(),
            )[:, None]
            * self.v12
            + self.x1
        )
        x23 = (
            np.linspace(
                0,
                1,
                num=int(np.ceil(density * self.l23)),
                endpoint=False,
                dtype=paddle.get_default_dtype(),
            )[:, None]
            * self.v23
            + self.x2
        )
        x31 = (
            np.linspace(
                0,
                1,
                num=int(np.ceil(density * self.l31)),
                endpoint=False,
                dtype=paddle.get_default_dtype(),
            )[:, None]
            * self.v31
            + self.x3
        )
        x = np.vstack((x12, x23, x31))
        if len(x) > n:
            x = x[0:n]
        return x

    def random_boundary_points(self, n, random="pseudo"):
        u = np.ravel(sampler.sample(n + 2, 1, random))
        # Remove the possible points very close to the corners
        u = u[np.logical_not(np.isclose(u, self.l12 / self.perimeter))]
        u = u[np.logical_not(np.isclose(u, (self.l12 + self.l23) / self.perimeter))]
        u = u[:n]

        u *= self.perimeter
        x = []
        for l in u:
            if l < self.l12:
                x.append(l * self.n12 + self.x1)
            elif l < self.l12 + self.l23:
                x.append((l - self.l12) * self.n23 + self.x2)
            else:
                x.append((l - self.l12 - self.l23) * self.n31 + self.x3)
        return np.vstack(x)

    def sdf_func(self, points: np.ndarray) -> np.ndarray:
        """Compute signed distance field.

        Args:
            points (np.ndarray): The coordinate points used to calculate the SDF value,
                the shape of the array is [N, 2].

        Returns:
            np.ndarray: SDF values of input points without squared, the shape is [N, 1].

        NOTE: This function usually returns ndarray with negative values, because
        according to the definition of SDF, the SDF value of the coordinate point inside
        the object(interior points) is negative, the outside is positive, and the edge
        is 0. Therefore, when used for weighting, a negative sign is often added before
        the result of this function.
        """
        if points.shape[1] != self.ndim:
            raise ValueError(
                f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
            )
        v1p = points - self.x1  # v1p: vector from x1 to points
        v2p = points - self.x2
        v3p = points - self.x3
        # vv12_p: vertical vector of points to v12(If the vertical point is in the extension of v12,
        # the vector will be the vector from x1 to points)
        vv12_p = (
            self.v12
            * np.clip(np.dot(v1p, self.v12.reshape(2, -1)) / self.l12**2, 0, 1)
            - v1p
        )
        vv23_p = (
            self.v23
            * np.clip(np.dot(v2p, self.v23.reshape(2, -1)) / self.l23**2, 0, 1)
            - v2p
        )
        vv31_p = (
            self.v31
            * np.clip(np.dot(v3p, self.v31.reshape(2, -1)) / self.l31**2, 0, 1)
            - v3p
        )
        is_inside = self.is_inside(points).reshape(-1, 1) * 2 - 1
        len_vv12_p = np.linalg.norm(vv12_p, axis=1, keepdims=True)
        len_vv23_p = np.linalg.norm(vv23_p, axis=1, keepdims=True)
        len_vv31_p = np.linalg.norm(vv31_p, axis=1, keepdims=True)
        mini_dist = np.minimum(np.minimum(len_vv12_p, len_vv23_p), len_vv31_p)
        return is_inside * mini_dist
sdf_func(points)

Compute signed distance field.

Parameters:

Name Type Description Default
points ndarray

The coordinate points used to calculate the SDF value, the shape of the array is [N, 2].

required

Returns:

Type Description
ndarray

np.ndarray: SDF values of input points without squared, the shape is [N, 1].

NOTE: This function usually returns ndarray with negative values, because according to the definition of SDF, the SDF value of the coordinate point inside the object(interior points) is negative, the outside is positive, and the edge is 0. Therefore, when used for weighting, a negative sign is often added before the result of this function.

Source code in ppsci/geometry/geometry_2d.py
def sdf_func(self, points: np.ndarray) -> np.ndarray:
    """Compute signed distance field.

    Args:
        points (np.ndarray): The coordinate points used to calculate the SDF value,
            the shape of the array is [N, 2].

    Returns:
        np.ndarray: SDF values of input points without squared, the shape is [N, 1].

    NOTE: This function usually returns ndarray with negative values, because
    according to the definition of SDF, the SDF value of the coordinate point inside
    the object(interior points) is negative, the outside is positive, and the edge
    is 0. Therefore, when used for weighting, a negative sign is often added before
    the result of this function.
    """
    if points.shape[1] != self.ndim:
        raise ValueError(
            f"Shape of given points should be [*, {self.ndim}], but got {points.shape}"
        )
    v1p = points - self.x1  # v1p: vector from x1 to points
    v2p = points - self.x2
    v3p = points - self.x3
    # vv12_p: vertical vector of points to v12(If the vertical point is in the extension of v12,
    # the vector will be the vector from x1 to points)
    vv12_p = (
        self.v12
        * np.clip(np.dot(v1p, self.v12.reshape(2, -1)) / self.l12**2, 0, 1)
        - v1p
    )
    vv23_p = (
        self.v23
        * np.clip(np.dot(v2p, self.v23.reshape(2, -1)) / self.l23**2, 0, 1)
        - v2p
    )
    vv31_p = (
        self.v31
        * np.clip(np.dot(v3p, self.v31.reshape(2, -1)) / self.l31**2, 0, 1)
        - v3p
    )
    is_inside = self.is_inside(points).reshape(-1, 1) * 2 - 1
    len_vv12_p = np.linalg.norm(vv12_p, axis=1, keepdims=True)
    len_vv23_p = np.linalg.norm(vv23_p, axis=1, keepdims=True)
    len_vv31_p = np.linalg.norm(vv31_p, axis=1, keepdims=True)
    mini_dist = np.minimum(np.minimum(len_vv12_p, len_vv23_p), len_vv31_p)
    return is_inside * mini_dist