"""Base classes for geometries: :class:`Geometry`, :class:`DiscreteGeometry`
and :class:`BoundaryGeometry`."""
from __future__ import annotations
from enum import Enum, auto
from types import EllipsisType
import warnings
from typing import Any, Generic
import numpy as np
from qewton.config.variables import Variable
from qewton.config.devices import Device, cpu
from qewton.config.saving.saving import Serializable
from qewton.backends.base import ComputingBackend, TensorType
from qewton.backends import DEFAULT_DL_BACKEND
[docs]
def vertex_distance_for(
max_vertex_distance: float | dict[Variable, float] | None, variable: Variable
) -> float | None:
"""Return the maximum vertex distance that applies to `variable`.
Args:
max_vertex_distance: One value for every geometry, or one value per
geometry variable.
variable: The variable of the geometry being meshed.
Returns:
float or None: The value for `variable`; ``None`` if a dict has no
entry for it.
"""
if isinstance(max_vertex_distance, dict):
return max_vertex_distance.get(variable)
return max_vertex_distance
[docs]
class DeviceTransferWarning(UserWarning):
"""A discrete geometry (e.g. a mesh) transferred points or results between
its own device and another one for a single call, e.g. `contains` on a
mesh on the CPU with points on a GPU. Moving the geometry with
``to(device)`` avoids the transfer."""
[docs]
class Geometry(Serializable, Generic[TensorType]):
"""Geometric domain used for sampling points, meshing and plotting.
Args:
variable: The variable that belongs to this geometry. If ``None``, an
empty placeholder :class:`~qewton.config.variables.Variable` is
used.
dim: The dimension of the geometry. Must match ``variable.dim`` if both
are given.
shape: The discrete shape of the geometry. Entries may be ``None`` and
``...`` means the shape is unknown.
backend: The backend used for computations.
Attributes:
variable (Variable): The variable that belongs to this geometry.
dim (int or None): The dimension, taken from `variable` if it is not
empty, otherwise the `dim` passed at construction or set by
unification.
shape (tuple of (int or None) or EllipsisType): The discrete shape of
the geometry.
backend (type[ComputingBackend]): The backend used for computations.
markers (dict): Named subdomains of this geometry.
boundary (BoundaryGeometry): The boundary of this geometry. Created by
:meth:`create_boundary` on first access and cached in
``boundary_object``.
factors (list of Geometry or None): The factor geometries of a
Cartesian product, in the order of its tensor axes (for a
discrete product, the first factor varies slowest); None for a
geometry that is no product.
Notes:
Subclasses should implement :meth:`create_boundary`,
:meth:`sample_random_uniform`, :meth:`sample_grid`, :meth:`contains`,
:meth:`bounding_box` and ``_get_volume`` where these operations make
sense; the base implementations raise :class:`NotImplementedError`.
They may override :meth:`create_mesh`, :meth:`is_discretization_of` and
:meth:`apply_unified`.
"""
def __init__(
self,
variable: Variable | None = None,
dim: int | None = None,
shape: tuple[int | None, ...] | EllipsisType = ...,
backend: type[ComputingBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
self.variable = variable if variable is not None else Variable()
self._dim = dim
self.shape: tuple[int | None, ...] | EllipsisType = shape
if variable is not None and dim is not None:
assert variable.dim == dim
self.markers = {}
self._user_volume = None
self.boundary_object: BoundaryGeometry | None = None
self.backend = backend
self._device: Device | str = cpu
def _collect_serializable_attributes(self) -> tuple[list, list]:
# The device is stored as text ("cpu", "cuda:0"), which tensors and
# `to()` accept as well.
keys, values = super()._collect_serializable_attributes()
return keys, [
str(self.backend.get_device(value)) if key == "_device" else value
for key, value in zip(keys, values)
]
@property
def device(self) -> Device | str:
"""The device holding this geometry's data. Only :meth:`to` changes it;
methods called with points or a `device` on another device compute
there without moving the geometry."""
return getattr(self, "_device", cpu)
[docs]
def to(self, device: Device | str) -> Geometry:
"""Move this geometry's data to `device`.
Related geometries (its boundary, the domain of a boundary, the
factors of a product, the parts of a union, ...) are moved as well,
since they share data or are used together.
Args:
device (Device | str): The target device.
Returns:
Geometry: This geometry.
"""
self._to(device, set())
return self
def _to(self, device: Device | str, moved: set[int]) -> None:
if id(self) in moved:
return
moved.add(id(self))
self._move_data(device)
self._device = device
for geometry in self._related_geometries():
geometry._to(device, moved)
def _related_geometries(self) -> list[Geometry]:
"""Geometries moved together with this one by :meth:`to`."""
return [self.boundary_object] if self.boundary_object is not None else []
def _move_data(self, device: Device | str) -> None:
"""Move the tensors this geometry stores itself to `device`."""
def _on(self, data, device: Device | str):
"""`data` of this geometry on `device`, as a local copy if needed.
Used by continuous geometries for their few constants (corners,
centers, ...); the geometry itself is not changed.
"""
return self.backend.to(data, device)
def _transfer(self, data, device: Device | str, warn: bool = True):
"""`data` (e.g. points or a result) moved to `device`.
Used by discrete geometries, which compute on their own device: points
from another device are brought there and the result is moved back.
With `warn`, a transfer issues a :class:`DeviceTransferWarning`.
"""
moved = self.backend.to(data, device)
if warn and moved is not data:
warnings.warn(
f"{type(self).__name__} on {self.device} transfers data from or "
f"to {device} for this call. Move it with .to(...) to the device "
"of the points to avoid the transfer.",
DeviceTransferWarning,
stacklevel=3,
)
return moved
def _bounds(self, bounds) -> TensorType:
"""A bounding box ``[axis_1_min, axis_1_max, ...]`` built from numbers
or scalar tensors, on this geometry's device."""
return self.backend.build_tensor([float(b) for b in bounds], device=self.device)
@staticmethod
def _device_of(points) -> Device | str:
"""The device of `points`, the CPU for data without one."""
return getattr(points, "device", cpu)
@property
def boundary(self) -> BoundaryGeometry:
if self.boundary_object is None:
self.boundary_object = self.create_boundary()
return self.boundary_object
[docs]
def create_boundary(self) -> BoundaryGeometry:
"""Create the boundary of this geometry.
Returns:
BoundaryGeometry: A new boundary geometry.
Raises:
NotImplementedError: If the geometry has no boundary
implementation.
"""
raise NotImplementedError()
@property
def dim(self) -> int | None:
return self.variable.dim if not self.variable.is_empty else self._dim
def _shape_is_placeholder(self, shape: tuple[int | None, ...] | EllipsisType) -> bool:
if shape is ...:
return True
return any(dim is None for dim in shape)
def _shape_needs_update(
self,
current_shape: tuple[int | None, ...] | EllipsisType,
unified_shape: tuple[int | None, ...] | EllipsisType,
) -> bool:
if current_shape is ...:
return unified_shape is not ...
if isinstance(current_shape, tuple) and isinstance(unified_shape, tuple):
return current_shape != unified_shape
return False
[docs]
def apply_unified(
self,
unified_variable: Variable,
unified_dim: int | None,
unified_shape: tuple[int | None, ...] | EllipsisType,
) -> None:
"""Fill this geometry's placeholders with unified values in place.
The variable and dimension are only set if they are still empty; the
shape is replaced if it differs from `unified_shape`.
Args:
unified_variable: The unified variable.
unified_dim: The unified dimension.
unified_shape: The unified shape.
"""
if not unified_variable.is_empty and self.variable.is_empty:
self.variable = unified_variable
if unified_dim is not None and self._dim is None:
self._dim = unified_dim
if self._shape_needs_update(self.shape, unified_shape):
self.shape = unified_shape
def _preferred_refinement_target(self, other: Geometry) -> Geometry:
assert Geometry in [self.__class__, other.__class__]
if type(self) is not type(other):
if isinstance(self, type(other)):
return self
if isinstance(other, type(self)):
return other
return self
[docs]
def discretize(
self,
discretization_points: Any | None = None,
discretization_shape: tuple[int, ...] | None = None,
) -> DiscreteGeometry:
"""Discretize this geometry into a :class:`DiscreteGeometry`.
The discretization is defined by the discretization points, the
discretization shape, or both (then they must be consistent).
Args:
discretization_points: The points of the discrete geometry, with
the dimension in the last axis.
discretization_shape: The shape of the discretization, without the
dimension axis.
Returns:
DiscreteGeometry: The discretized geometry. Its
``discretization_of`` is set to this geometry.
Raises:
ValueError: If neither `discretization_points` nor
`discretization_shape` is given.
AssertionError: If the given points, shape, dimension or this
geometry's shape are inconsistent.
"""
if discretization_points is not None:
shape = discretization_points.shape[:-1]
if discretization_shape is not None:
assert shape == discretization_shape
if self.dim is not None:
assert (
discretization_points.shape[-1] == self.dim
), "Points shape does not match dimension"
elif discretization_shape is not None:
shape = discretization_shape
else:
raise ValueError(
"Either discretization_points or discretization_shape must be provided."
)
if self.shape is not ...:
for p_s, s in zip(shape, self.shape):
assert (
p_s == s or s is None
), f"Default shape {self.shape} does not match provided points"
dis_geo = DiscreteGeometry(
variable=self.variable,
dim=self.dim,
shape=shape,
discretization_points=discretization_points,
)
dis_geo.discretization_of = self
return dis_geo
#: Whether this geometry consists of given points (and cells), so that
#: nothing discretizes it further.
is_discrete = False
[docs]
def is_discretization_of(
self, other_geometry: Geometry # pylint: disable=unused-argument
) -> bool:
"""Check whether this geometry is a discretization of another one.
Args:
other_geometry: The geometry to compare to.
Returns:
bool: Whether this geometry discretizes `other_geometry`. Always
``False`` for a continuous geometry.
"""
return False
[docs]
def create_mesh(self, max_vertex_distance: float | None = None, device: Device = cpu):
"""Mesh this geometry into a mesh geometry.
Args:
max_vertex_distance: The maximum distance between mesh vertices,
which controls how fine the mesh is.
device: The device the mesh is created on.
Returns:
DiscreteGeometry: The meshed geometry.
Raises:
NotImplementedError: If the geometry does not support meshing.
"""
raise NotImplementedError()
[docs]
def set_marker(self, marker, marker_description):
"""Mark a subdomain of this geometry.
Args:
marker (hashable): The name of the marker.
marker_description (Any): The description of the marked subdomain.
Raises:
NotImplementedError: Always, since general geometries can not be
marked.
"""
# TODO!!!
raise NotImplementedError(
"General geometries can not be marked, use "
"the filter functions in the sampler object instead."
)
[docs]
def get_marker(self, marker):
"""Return the subdomain stored under `marker`.
Args:
marker (hashable): The name of the marker.
Returns:
Any: The stored marker entry.
Raises:
KeyError: If no marker with this name exists.
"""
# TODO!!!
if marker in self.markers:
return self.markers[marker]
raise KeyError(f"{marker} marker not found.")
[docs]
def sample_grid(self, n_points: int, device: Device | str = cpu) -> TensorType:
"""Sample grid points inside the geometry.
Args:
n_points: The number of points to sample.
device: The device to sample on.
Returns:
TensorType: The sampled points, shape ``(n_points, dim)``.
"""
raise NotImplementedError()
def __and__(self, other):
"""Return the intersection of two geometries."""
raise NotImplementedError()
def __add__(self, other):
"""Return the union of two geometries."""
return NotImplementedError()
def __or__(self, other):
"""Return the union of two geometries."""
raise self + other
def __sub__(self, other):
"""Return the difference of two geometries."""
raise NotImplementedError()
def __mul__(self, other):
"""Return the Cartesian product of two geometries.
Returns:
ProductGeometry: The product of this geometry and `other`, see
:class:`~qewton.geometries.product.ProductGeometry`.
"""
from .product import ProductGeometry
return ProductGeometry(self, other)
[docs]
def contains(self, points):
"""Check for every point whether it lies inside the geometry.
Args:
points (TensorType): The points to check, shape
``(n_points, dim)``.
Returns:
TensorType: Boolean tensor of shape ``(n_points, 1)``, ``True``
where the point lies inside.
"""
raise NotImplementedError()
[docs]
def bounding_box(self):
"""Compute the axis-aligned bounds of the geometry.
Returns:
TensorType: Tensor of length ``2 * dim`` of the form
``[axis_1_min, axis_1_max, axis_2_min, axis_2_max, ...]``.
"""
raise NotImplementedError()
[docs]
def set_volume(self, volume: float):
"""Set the volume of the geometry by hand.
Args:
volume: The volume of the geometry. :meth:`volume` returns this
value instead of computing one.
Notes:
Use this for geometries whose volume can otherwise only be
approximated, if the exact value is known.
"""
self._user_volume = volume
@property
def factors(self) -> list[Geometry] | None:
return None
[docs]
def subproduct(self, factors: list[Geometry]) -> Geometry:
"""The product of some of this product's factors, of the same kind.
Args:
factors: At least two of `factors`, in their order.
Returns:
Geometry: The product of `factors`.
Raises:
ValueError: If this geometry is no product, or cannot build one
of some of its factors.
"""
raise ValueError(
f"{type(self).__name__} cannot build a product of some of its factors."
)
def _get_volume(self):
raise NotImplementedError()
[docs]
def volume(self):
"""Return the volume of the geometry.
Returns:
float: The volume set by :meth:`set_volume`, if any, otherwise the
computed volume.
"""
if self._user_volume is None:
return self._get_volume()
return self._user_volume
[docs]
class Structure(Enum):
"""How the points of a discrete geometry are connected.
Attributes:
POINTS: No connectivity, e.g. a point cloud.
MESH: Cells with explicit connectivity, e.g. a simplex mesh.
GRID: A rectilinear grid: one coordinate array per axis, aligned
with the coordinate axes.
"""
POINTS = auto()
MESH = auto()
GRID = auto()
[docs]
def boundary_facets(cells: np.ndarray) -> np.ndarray:
"""The facets of simplex cells that belong to one cell only.
Args:
cells: Point indices per cell, shape ``(n_cells, k)``.
Returns:
numpy.ndarray: Point indices per facet, shape ``(n_facets, k - 1)``.
"""
k = cells.shape[1]
facets = np.concatenate([np.delete(cells, i, axis=1) for i in range(k)])
_, first, counts = np.unique(
np.sort(facets, axis=1), axis=0, return_index=True, return_counts=True
)
return facets[np.sort(first[counts == 1])]
[docs]
class DiscreteGeometry(Geometry[TensorType]):
"""Geometry with a concrete discretization shape and optional points.
Args:
shape: The shape of the discretization, e.g. the number of points per
axis.
variable: The variable connected to this geometry.
dim: The dimension of this geometry.
discretization_points: The discrete points that make up this geometry,
with the dimension in the last axis.
backend: The backend used for computations.
Attributes:
discretization_of (Geometry or None): The geometry this one
discretizes, if known.
discretization_points (TensorType or None): The discrete points of this
geometry.
point_filter (TensorType or None): Whether each point belongs to the
geometry, shape ``(*shape, 1)``, e.g. the points of a
rectilinear grid inside a non-box domain; None if all do.
structure (Structure): How its points are connected.
topological_dim (int): Dimension of its cells: 0 for points, 1 for
curves, 2 for surfaces, 3 for volumes. `dim` is the number of
coordinates of a point, so a curve in the plane has
``topological_dim`` 1 and ``dim`` 2.
cells (numpy.ndarray or None): Point indices per cell, shape
``(n_cells, n_vertices)``; None for :attr:`Structure.POINTS`.
boundary_cells (numpy.ndarray): The facets of `cells` that belong
to one cell only, e.g. the triangles bounding a volume of
tetrahedra.
Notes:
Subclasses may implement
:meth:`sample_random_uniform_from_discretization` and
:meth:`sample_grid_from_discretization`. A discrete geometry is a
point set (:attr:`Structure.POINTS`) unless a subclass with cells
overrides `structure`, `topological_dim` and `cells`, and
:meth:`axis_coordinates` for :attr:`Structure.GRID`.
"""
is_discrete = True
def __init__(
self,
shape: tuple[int, ...],
variable: Variable | None = None,
dim: int | None = None,
discretization_points: TensorType | None = None,
backend: type[ComputingBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
super().__init__(variable=variable, dim=dim, shape=shape, backend=backend)
self.discretization_of: Geometry | None = None
self.discretization_points = discretization_points
self.point_filter: TensorType | None = None
@property
def structure(self) -> Structure:
return Structure.POINTS
@property
def topological_dim(self) -> int:
return 0
@property
def cells(self) -> np.ndarray | None:
return None
@property
def boundary_cells(self) -> np.ndarray:
cells = self.cells
if cells is None:
raise ValueError(f"{type(self).__name__} has no cells and so no boundary.")
return boundary_facets(cells)
[docs]
def coordinates(self) -> np.ndarray:
"""Return the points as a numpy array on the CPU.
Returns:
numpy.ndarray: Shape ``(n_points, dim)``, in the order of the
geometry's axes in a DataConfiguration (row-major over
`shape`).
"""
points = self.discretization_points
if not isinstance(points, np.ndarray):
points = self.backend.to_numpy(points)
return np.asarray(points).reshape(-1, points.shape[-1])
@property
def axis_components(self) -> tuple[int, ...]:
"""The coordinate component varying along each axis of a rectilinear
grid, e.g. ``(1, 0)`` for a grid built with ``meshgrid(x, y)``.
Raises:
ValueError: If `structure` is not :attr:`Structure.GRID`.
"""
raise ValueError(f"{type(self).__name__} is not a rectilinear grid.")
[docs]
def axis_coordinates(self) -> list[np.ndarray]:
"""Return the coordinates along each axis of a rectilinear grid.
Returns:
list of numpy.ndarray: One 1D array per axis of `shape`.
Raises:
ValueError: If `structure` is not :attr:`Structure.GRID`.
"""
raise ValueError(f"{type(self).__name__} is not a rectilinear grid.")
[docs]
def bounding_box(self):
"""Compute the axis-aligned bounds of the geometry.
Uses the discretization points if present, otherwise the bounding
box of ``discretization_of``.
Returns:
TensorType: Tensor of the form ``[axis_1_min, axis_1_max, ...]``.
Raises:
NotImplementedError: If neither points nor a source geometry are
available.
"""
if self.discretization_points is not None:
self.discretization_points = self.backend.build_tensor(
self.discretization_points
)
bounding_box = []
for i in range(self.discretization_points.shape[-1]):
min_val = self.backend.math.min(self.discretization_points[..., i])
max_val = self.backend.math.max(self.discretization_points[..., i])
bounding_box.append(min_val)
bounding_box.append(max_val)
return self._bounds(bounding_box)
if self.discretization_of is not None:
return self.discretization_of.bounding_box()
raise NotImplementedError(
"Bounding box is not implemented for this discrete geometry."
)
[docs]
def is_discretization_of(self, other_geometry: Geometry) -> bool:
"""Check whether this geometry is a discretization of another one.
Args:
other_geometry: The geometry to compare to.
Returns:
bool: ``True`` if `other_geometry` equals ``discretization_of`` or
is this geometry itself.
"""
if self.discretization_of == other_geometry:
return True
if self is other_geometry:
return True
return False
[docs]
def sample_grid_from_discretization(
self, n_points: int, device: Device | str = cpu
) -> TensorType:
"""Sample points evenly from the discretization points.
Every discretization point is returned equally often.
Args:
n_points: The number of points to sample. If larger than the number
of discretization points, duplicates are returned.
device: The device to sample on.
Returns:
TensorType: The sampled points, shape ``(n_points, dim)``.
"""
raise NotImplementedError()
[docs]
class BoundaryGeometry(Geometry[TensorType]):
"""Base class for the boundary of a geometry.
Can be used like any other :class:`Geometry`.
Args:
geometry (Geometry): The geometry whose boundary this is. Its variable,
dimension and backend are taken over.
Attributes:
geometry (Geometry): The geometry whose boundary this is.
Notes:
Subclasses should implement :meth:`normal`, :meth:`sample_grid` and
:meth:`sample_random_uniform`, including the `include_normals` option.
"""
def __init__(self, geometry):
assert isinstance(geometry, Geometry)
if geometry.dim is not None:
dim = geometry.dim
else:
dim = None
super().__init__(variable=geometry.variable, dim=dim, backend=geometry.backend)
self.geometry = geometry
self._device = geometry.device
def _related_geometries(self) -> list[Geometry]:
return [self.geometry, *super()._related_geometries()]
[docs]
def bounding_box(self):
"""Return the bounding box of the underlying geometry.
Returns:
TensorType: Tensor of the form ``[axis_1_min, axis_1_max, ...]``.
"""
return self.geometry.bounding_box()
[docs]
def create_boundary(self) -> BoundaryGeometry:
"""Raise, since a boundary has no boundary.
Raises:
NotImplementedError: Always.
"""
raise NotImplementedError("Boundary of a boundary geometry is not defined.")
[docs]
def normal(self, points, device: Device | str = cpu) -> TensorType:
"""Compute the outward normal vector at each point.
Args:
points (TensorType): The boundary points, shape
``(n_points, dim)``.
device: The device to compute on.
Returns:
TensorType: The normal vectors, shape ``(n_points, dim)``.
"""
raise NotImplementedError()
[docs]
def sample_grid(
self,
n_points: int,
device: Device | str = cpu,
include_normals: bool = False, # pylint: disable=unused-argument
) -> TensorType | tuple[TensorType, TensorType]:
"""Sample grid points on the boundary.
Args:
n_points: The number of points to sample.
device: The device to sample on.
include_normals: Whether to also return the normal vectors at the
points.
Returns:
TensorType or tuple of TensorType: The points, or
``(points, normals)`` if `include_normals` is ``True``.
"""
return super().sample_grid(n_points)
####################################
### Plan:
# - We can mark CAD-geometries via lambda functions, the functions will
# be saved internally, and we return the corresponding subdomains for further usage.
# The saved markers can be used when creating a mesh.
# - Put CAD into qewton.geometry.cad
### Samplers:
# - One can still filter points via rejection sampling