Source code for qewton.geometries.discrete.grid_geometry

from __future__ import annotations

import itertools

import numpy as np

from qewton.config.variables import Variable
from qewton.geometries.base import Geometry, DiscreteGeometry, Structure
from qewton.backends.base import TensorType, ComputingBackend
from qewton.backends import DEFAULT_DL_BACKEND
from qewton.config.devices import Device, cpu
from qewton.config.dtypes import Bool
from qewton.geometries.discrete.product_mesh_geometry import product_of


def _grid_cells(shape: tuple[int, ...]) -> np.ndarray:
    # Cells of a grid as simplices, indexing the points in row-major order:
    # segments for one axis, two triangles per quad for two, six tetrahedra
    # per hexahedron for three (along the paths from its first to its last
    # corner, so neighbors share their faces).
    index = np.arange(int(np.prod(shape))).reshape(shape)
    if len(shape) == 1:
        return np.stack([index[:-1], index[1:]], axis=1)
    if len(shape) == 2:
        a, b = index[:-1, :-1].ravel(), index[1:, :-1].ravel()
        c, d = index[:-1, 1:].ravel(), index[1:, 1:].ravel()
        return np.concatenate([np.stack([a, b, c], 1), np.stack([b, d, c], 1)])
    if len(shape) == 3:

        def corner(offset):
            return index[
                tuple(slice(o, n - 1 + o) for o, n in zip(offset, shape))
            ].ravel()

        tetrahedra = []
        for order in itertools.permutations(range(3)):
            offset, path = [0, 0, 0], [corner((0, 0, 0))]
            for axis in order:
                offset[axis] = 1
                path.append(corner(offset))
            tetrahedra.append(np.stack(path, axis=1))
        return np.concatenate(tetrahedra)
    raise NotImplementedError("Cells of grids with more than three axes are not supported.")


[docs] class GridGeometry(DiscreteGeometry[TensorType]): """A grid of points. The underlying points are always in a mesh grid like pattern. To create a bit more complex shapes, a filter mask can be used. Args: variable (Variable): The variable connected to this geometry. point_grid (TensorType): The grid of points, should be of the shape [N_1, N_2, ..., N_d, d], where d is the dimension of the above variable. point_filter (TensorType | None, optional): A grid of boolean values with the same shape as the point_grid, except the last axis should be always 1. A value of True, means the corresponding point is inside the geometry, False, that it should not be included. Default is None. discretization_of (Geometry | None, optional): The geometry this grid is a discretization of. Defaults to None. backend (type[ComputingBackend[TensorType]], optional): Defaults to DEFAULT_DL_BACKEND. Attributes: structure (Structure): :attr:`~qewton.geometries.base.Structure.GRID` if every coordinate varies along exactly one grid axis (rectilinear), otherwise :attr:`~qewton.geometries.base.Structure.MESH`. axis_components (tuple of int): For a rectilinear grid, the coordinate component varying along each grid axis, e.g. ``(1, 0)`` for a grid built with ``meshgrid(x, y)``. factors (list of GridGeometry or None): For a rectilinear grid of two or more axes, one 1D grid per grid axis, in the order of the axes, with the leaf of its coordinate as variable (e.g. ``x_1`` of ``Variable("x", 3)``); None otherwise. The factors carry no point filter. """ def __init__( self, variable: Variable, point_grid: TensorType, point_filter: TensorType | None = None, discretization_of: Geometry | None = None, backend: type[ComputingBackend[TensorType]] = DEFAULT_DL_BACKEND, ): assert ( len(point_grid.shape) - 1 == variable.dim ), f"The point grid should have as many axis as the dimension \ of the variable. Found axis {point_grid.shape[-1]} which has \ length {len(point_grid.shape) - 1} and does not fit the \ variable dimension {variable.dim}." assert ( point_grid.shape[-1] == variable.dim ), "Dimension of the points in the grid does not fit variable." if point_filter is not None: assert ( point_grid.shape[:-1] == point_filter.shape[:-1] ), "Filter and grid do not match." super().__init__( shape=point_grid.shape[:-1], variable=variable, dim=variable.dim, discretization_points=backend.build_tensor(point_grid), backend=backend, ) self.discretization_points: TensorType = self.discretization_points self.discretization_of = discretization_of if point_filter is None: self.point_filter = self.backend.math.ones( shape=point_grid.shape[:-1] + (1,), dtype=self.backend.dtypes[Bool] ) else: self.point_filter = self.backend.build_tensor(point_filter, dtype=Bool) self.cell_volumes: TensorType | None = None self._factors: list[GridGeometry] | None = None def _move_data(self, device: Device | str) -> None: self.discretization_points = self.backend.to( self.discretization_points, device=device ) self.point_filter = self.backend.to(self.point_filter, device=device) if self.cell_volumes is not None: self.cell_volumes = self.backend.to(self.cell_volumes, device=device) self._factors = None @property def structure(self) -> Structure: # A grid aligned with the coordinate axes is rectilinear; any other # (rotated, curved, embedded in a higher dimension) is drawn as the # mesh of its cells. return Structure.GRID if self._rectilinear() is not None else Structure.MESH @property def topological_dim(self) -> int: return len(self.shape) @property def cells(self) -> np.ndarray: return _grid_cells(tuple(self.shape)) @property def axis_components(self) -> tuple[int, ...]: return self._require_rectilinear()[0]
[docs] def axis_coordinates(self) -> list[np.ndarray]: """See :meth:`~qewton.geometries.base.DiscreteGeometry.axis_coordinates`.""" return self._require_rectilinear()[1]
@property def factors(self) -> list[GridGeometry] | None: if self._factors is None: self._factors = self._build_factors() return self._factors or None def _build_factors(self) -> list[GridGeometry]: # One 1D grid per axis of a rectilinear grid, named by the leaf of # the coordinate along it; empty if the grid is no such product. rectilinear = self._rectilinear() if len(self.shape) < 2 or rectilinear is None: return [] leaves = self.variable.leaves return [ self._line(leaves[component], coordinates) for component, coordinates in zip(*rectilinear) ] def _line(self, variable: Variable, coordinates: np.ndarray) -> GridGeometry: points = self.backend.build_tensor( np.asarray(coordinates).reshape(-1, 1), device=self.device ) return GridGeometry(variable, point_grid=points, backend=self.backend)
[docs] def subproduct(self, factors: list[GridGeometry]) -> DiscreteGeometry: """See :meth:`~qewton.geometries.base.DiscreteGeometry.subproduct`; the grid over the axes of `factors`.""" return product_of(self.variable, factors, self.backend)
def _require_rectilinear(self) -> tuple[tuple[int, ...], list[np.ndarray]]: rectilinear = self._rectilinear() if rectilinear is None: raise ValueError("The grid is not aligned with the coordinate axes.") return rectilinear def _rectilinear(self) -> tuple[tuple[int, ...], list[np.ndarray]] | None: # Per grid axis the coordinate component varying along it and its # values, if every component varies along exactly one grid axis; # None otherwise. points = np.asarray(self.backend.to_numpy(self.discretization_points)) n_axes = len(self.shape) if points.shape[-1] != n_axes: return None components, coordinates = [], [] for axis in range(n_axes): index = tuple(slice(None) if i == axis else 0 for i in range(n_axes)) line = points[index] # (n_axis, n_components) varying = [k for k in range(n_axes) if np.ptp(line[:, k]) > 0] if len(varying) > 1 or (not varying and self.shape[axis] > 1): return None component = varying[0] if varying else axis shape = [-1 if i == axis else 1 for i in range(n_axes)] expanded = line[:, component].reshape(shape) if not np.allclose(points[..., component], expanded): return None components.append(component) coordinates.append(line[:, component]) if sorted(components) != list(range(n_axes)): return None return tuple(components), coordinates
[docs] @classmethod def build_unit_grid( cls, variable: Variable, resolution: int, backend: type[ComputingBackend[TensorType]] = DEFAULT_DL_BACKEND, ) -> GridGeometry: """Builds an equidistant grid in the unit cube fitting the provided variable. Args: variable (Variable): The variable connected to this geometry. resolution (int): How many points should be used in each direction. backend (type[ComputingBackend[TensorType]], optional): Defaults to DEFAULT_DL_BACKEND. Returns: GridGeometry: The grid geometry. """ axis = backend.math.linspace(0, 1, resolution) axis_list = [axis] * variable.dim grid = backend.math.stack(backend.math.meshgrid(*axis_list), axis=-1) return GridGeometry(variable=variable, point_grid=grid, backend=backend)
def _get_volume(self): if self.cell_volumes is None: self._compute_cell_volumes() return self.backend.math.sum(self.cell_volumes) def _compute_cell_volumes(self): d = self.discretization_points.shape[-1] # Compute edge vectors along each grid axis edges = [] for axis in range(d): e = self.backend.math.diff(self.discretization_points, axis=axis) # remove the last slice along all other axes so all edges # have the same cell indexing shape slices = [slice(0, n - 1) for n in self.discretization_points.shape[:-1]] slices[axis] = slice(None) e = e[tuple(slices)] edges.append(e) # (..., d, d) # Each cell gets a matrix whose columns are the edge vectors cell_matrix = self.backend.math.stack(edges, axis=-1) # remove the ones that should be filtered: slices = [slice(0, n - 1) for n in self.discretization_points.shape[:-1]] cell_matrix *= self.point_filter[slices].unsqueeze(-1) slices = [slice(1, n) for n in self.discretization_points.shape[:-1]] cell_matrix *= self.point_filter[slices].unsqueeze(-1) # determinant of every cell matrix self.cell_volumes = self.backend.math.abs(self.backend.linalg.det(cell_matrix))
[docs] def bounding_box(self): bounding_box = [] for i in range(self.variable.dim): 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)
[docs] def sample_random_uniform_from_discretization( self, n_points: int, device: Device | str = cpu ) -> TensorType: target_device, device = device, self.device points = self.discretization_points.reshape( -1, self.discretization_points.shape[-1] ) valid = self.backend.math.squeeze(self.point_filter, -1).reshape(-1) valid_points = points[valid] valid_idx = self.backend.math.arange(0, len(valid_points), device=device) idx = self.backend.random.choice(valid_idx, shape=(n_points, 1), device=device) return self._transfer(valid_points[idx], target_device)
[docs] def sample_random_uniform( self, n_points: int, device: Device | str = cpu ) -> TensorType: return self.sample_random_uniform_from_discretization(n_points, device)
[docs] def sample_grid(self, n_points: int, device: Device | str = cpu) -> TensorType: return self.sample_grid_from_discretization(n_points=n_points, device=device)
[docs] def sample_grid_from_discretization( self, n_points: int, device: Device | str = cpu ) -> TensorType: target_device, device = device, self.device # TODO: Could be done distance based points = self.discretization_points.reshape( -1, self.discretization_points.shape[-1] ) point_count = len(points) if n_points <= point_count: return self._transfer(points[:n_points], target_device) reps = n_points // point_count rem = n_points % point_count base = self.backend.math.tile(points, (reps, 1)) extra_idx = self.backend.random.permutation(point_count, device=device)[:rem] extra = points[extra_idx] return self._transfer(self.backend.math.vstack([base, extra]), target_device)
[docs] def contains(self, points): points_device = self._device_of(points) points = self._transfer(points, self.device) point_check = self.backend.math.zeros( (len(points), 1), dtype=self.backend.dtypes[Bool], device=self.device ) for i, p in enumerate(points): point_check[i] = p in self.discretization_points return self._transfer(point_check, points_device, warn=False)
[docs] def create_boundary(self): raise NotImplementedError("Boundary of a point grid currently not implemented.")