跳转至

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
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):
        """Returns a boolean array where x is inside the geometry."""

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

    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=True):
        """Compute the equi-spaced points in the geometry."""
        logger.warning(
            f"{self}.uniform_points not implemented. " f"Use random_points instead."
        )
        return self.random_points(n)

    def sample_interior(
        self,
        n,
        random="pseudo",
        criteria=None,
        evenly=False,
        compute_sdf_derivatives: bool = False,
    ):
        """Sample random points in the geometry and return those meet criteria."""
        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"):
            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, random="pseudo", criteria=None, evenly=False):
        """Compute the random points in the geometry and return those meet criteria."""
        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 >= 1000 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: str = "pseudo"):
        """Compute the random points in the geometry."""

    def uniform_boundary_points(self, n: int):
        """Compute the equi-spaced points on the boundary."""
        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, random="pseudo"):
        """Compute the random points on the boundary."""

    def periodic_point(self, x: np.ndarray, component: int):
        """Compute the periodic image of x."""
        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.
        """
        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):
        """CSG Union."""
        from ppsci.geometry import csg

        return csg.CSGUnion(self, other)

    def __or__(self, other):
        """CSG Union."""
        from ppsci.geometry import csg

        return csg.CSGUnion(self, other)

    def difference(self, other):
        """CSG Difference."""
        from ppsci.geometry import csg

        return csg.CSGDifference(self, other)

    def __sub__(self, other):
        """CSG Difference."""
        from ppsci.geometry import csg

        return csg.CSGDifference(self, other)

    def intersection(self, other):
        """CSG Intersection."""
        from ppsci.geometry import csg

        return csg.CSGIntersection(self, other)

    def __and__(self, other):
        """CSG Intersection."""
        from ppsci.geometry import csg

        return csg.CSGIntersection(self, other)

    def __str__(self) -> str:
        """Return the name of class"""
        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.

Source code in ppsci/geometry/geometry.py
def __and__(self, other):
    """CSG Intersection."""
    from ppsci.geometry import csg

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

CSG Union.

Source code in ppsci/geometry/geometry.py
def __or__(self, other):
    """CSG Union."""
    from ppsci.geometry import csg

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

Return the name of class

Source code in ppsci/geometry/geometry.py
def __str__(self) -> str:
    """Return the name of class"""
    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.

Source code in ppsci/geometry/geometry.py
def __sub__(self, other):
    """CSG Difference."""
    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.

Source code in ppsci/geometry/geometry.py
def difference(self, other):
    """CSG Difference."""
    from ppsci.geometry import csg

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

CSG Intersection.

Source code in ppsci/geometry/geometry.py
def intersection(self, other):
    """CSG Intersection."""
    from ppsci.geometry import csg

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

Returns a boolean array where x is inside the geometry.

Source code in ppsci/geometry/geometry.py
@abc.abstractmethod
def is_inside(self, x):
    """Returns a boolean array where x is inside the geometry."""
on_boundary(x) abstractmethod

Returns a boolean array where x is on geometry boundary.

Source code in ppsci/geometry/geometry.py
@abc.abstractmethod
def on_boundary(self, x):
    """Returns a boolean array where x is on geometry boundary."""
periodic_point(x, component)

Compute the periodic image of x.

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

Compute the random points on the boundary.

Source code in ppsci/geometry/geometry.py
@abc.abstractmethod
def random_boundary_points(self, n, random="pseudo"):
    """Compute the random points on the boundary."""
random_points(n, random='pseudo') abstractmethod

Compute the random points in the geometry.

Source code in ppsci/geometry/geometry.py
@abc.abstractmethod
def random_points(self, n: int, random: str = "pseudo"):
    """Compute the random points in the geometry."""
sample_boundary(n, random='pseudo', criteria=None, evenly=False)

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

Source code in ppsci/geometry/geometry.py
def sample_boundary(self, n, random="pseudo", criteria=None, evenly=False):
    """Compute the random points in the geometry and return those meet criteria."""
    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 >= 1000 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.

Source code in ppsci/geometry/geometry.py
def sample_interior(
    self,
    n,
    random="pseudo",
    criteria=None,
    evenly=False,
    compute_sdf_derivatives: bool = False,
):
    """Sample random points in the geometry and return those meet criteria."""
    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"):
        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.

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.
    """
    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.

Source code in ppsci/geometry/geometry.py
def uniform_boundary_points(self, n: int):
    """Compute the equi-spaced points on the boundary."""
    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.

Source code in ppsci/geometry/geometry.py
def uniform_points(self, n: int, boundary=True):
    """Compute the equi-spaced points in the geometry."""
    logger.warning(
        f"{self}.uniform_points not implemented. " f"Use random_points instead."
    )
    return self.random_points(n)
union(other)

CSG Union.

Source code in ppsci/geometry/geometry.py
def union(self, other):
    """CSG Union."""
    from ppsci.geometry import csg

    return csg.CSGUnion(self, other)

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

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

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. 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.

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)

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

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

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

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

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
 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
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.
        """
        # 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]
        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).flatten()

    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.
        """
        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://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.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.
        """
        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: str = "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:
            np.ndarray: Approximated areas with shape of [n_faces, ].
        """
        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, random="pseudo", criteria=None, evenly=False, inflation_dist=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)
                    ).flatten()
                    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)
                ).flatten()
            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)
        return all_points, all_areas

    def sample_interior(
        self,
        n,
        random="pseudo",
        criteria=None,
        evenly=False,
        compute_sdf_derivatives: bool = False,
    ):
        """Sample random points in the geometry and return those meet criteria."""
        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.

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.
    """
    # 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.

Source code in ppsci/geometry/mesh.py
def sample_interior(
    self,
    n,
    random="pseudo",
    criteria=None,
    evenly=False,
    compute_sdf_derivatives: bool = False,
):
    """Sample random points in the geometry and return those meet criteria."""
    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.

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.
    """
    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]
    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.

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.
    """
    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://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.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):
        for i, offset in enumerate(translation):
            self.interior[:, i] += offset
            if self.boundary:
                self.boundary += offset
        return self

    def scale(self, scale):
        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, random="pseudo"):
        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, random="pseudo"):
        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=True):
        """Compute the equi-spaced points in the geometry."""
        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}",
        ]
    )
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.

Source code in ppsci/geometry/pointcloud.py
def uniform_points(self, n: int, boundary=True):
    """Compute the equi-spaced points in the geometry."""
    return self.interior[:n]

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
        self.time_step = time_step
        self.timestamps = np.array(
            timestamps, dtype=paddle.get_default_dtype()
        ).reshape([-1])
        if time_step is not None:
            if time_step <= 0:
                raise ValueError(f"time_step({time_step}) must be larger than 0.")
            self.num_timestamps = int(np.ceil((t1 - t0) / time_step)) + 1
        elif timestamps is not None:
            self.num_timestamps = len(timestamps)

    def on_initial(self, t):
        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
 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
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

    @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, boundary=True):
        """Uniform points on the spatial-temporal domain.

        Geometry volume ~ bbox.
        Time volume ~ diam.
        """
        if self.timedomain.time_step is not None:
            # exclude start time t0
            nt = int(np.ceil(self.timedomain.diam / self.timedomain.time_step))
            nx = int(np.ceil(n / nt))
        elif 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, random="pseudo", criteria=None):
        # time evenly and geometry random, if time_step if specified
        if self.timedomain.time_step is not None:
            nt = int(np.ceil(self.timedomain.diam / self.timedomain.time_step))
            t = np.linspace(
                self.timedomain.t1,
                self.timedomain.t0,
                num=nt,
                endpoint=False,
                dtype=paddle.get_default_dtype(),
            )[:, None][
                ::-1
            ]  # [nt, 1]
            # 1. sample nx points in static geometry with criteria
            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 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
        elif self.timedomain.timestamps is not None:
            nt = self.timedomain.num_timestamps - 1
            t = self.timedomain.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."
                    )

            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, criteria=None):
        """Uniform boundary points on the spatial-temporal domain.

        Geometry surface area ~ bbox.
        Time surface area ~ diam.
        """
        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, random="pseudo", criteria=None):
        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):
        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, random="pseudo"):
        x = self.geometry.random_points(n, random=random)
        t = self.timedomain.t0
        return np.hstack((np.full([n, 1], t, dtype=paddle.get_default_dtype()), x))

    def periodic_point(self, x, component):
        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=None,
        evenly=False,
        compute_sdf_derivatives: bool = False,
    ):
        """Sample random points in the time-geometry and return those meet criteria."""
        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}",
            ]
        )
__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}",
        ]
    )
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.

Source code in ppsci/geometry/timedomain.py
def sample_initial_interior(
    self,
    n: int,
    random: str = "pseudo",
    criteria=None,
    evenly=False,
    compute_sdf_derivatives: bool = False,
):
    """Sample random points in the time-geometry and return those meet criteria."""
    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.

Source code in ppsci/geometry/timedomain.py
def uniform_boundary_points(self, n, criteria=None):
    """Uniform boundary points on the spatial-temporal domain.

    Geometry surface area ~ bbox.
    Time surface area ~ diam.
    """
    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_points(n, boundary=True)

Uniform points on the spatial-temporal domain.

Geometry volume ~ bbox. Time volume ~ diam.

Source code in ppsci/geometry/timedomain.py
def uniform_points(self, n, boundary=True):
    """Uniform points on the spatial-temporal domain.

    Geometry volume ~ bbox.
    Time volume ~ diam.
    """
    if self.timedomain.time_step is not None:
        # exclude start time t0
        nt = int(np.ceil(self.timedomain.diam / self.timedomain.time_step))
        nx = int(np.ceil(n / nt))
    elif 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

最后更新: November 17, 2023
创建日期: November 6, 2023