qewton.geometries package

Module contents

Geometries Submodule

The geometries module defines the domains of physical space used in the algorithms. They live inside spaces which are defined via Variable objects. For example, a 2D image domain could be defined by a Geometry with variables ‘x’ and ‘y’, while a time series would have a variable ‘t’, with an interval as the domain.

We integrate some simple own domains, and refer to CAD and meshing libraries for more complex stuff. Here we also enable marking specific regions of the domain or its boundary, which is useful for applying boundary conditions in physics-informed models. The geometries are also used to generate collocation points for training PINNs, and to provide spatial context (e.g., normal vectors) to nodes during the forward pass.

Key Components

  • Geometry: The base class for defining a domain (e.g., a Hypercube, Circle, or complex Mesh). Its device tells where its data lives; only to(device) changes it.

  • DiscreteGeometry: A geometry defined by a fixed set of points, useful for graph-based models or when working with pre-sampled data, or everything lying on a grid. A MeshGeometry is a specific type of DiscreteGeometry can also be generated by meshing other Geometry objects.

  • BoundaryGeometry: A Geometry that represents the boundary of another geometry. It can provide additional information such as normal vectors or boundary masks.

  • ProductGeometry: The Cartesian product of two geometries, created with geometry_a * geometry_b (e.g. space x time). Meshing it meshes every factor and returns a ProductMeshGeometry, whose vertices are all combinations of the factor vertices (first factor varying slowest) and whose simplex mesh is built on demand. ProductDiscreteGeometry is the product of discrete geometries that keeps each factor’s own shape, e.g. for reference data on a grid; its structure (grid, mesh or points) follows from the factors. A rectilinear GridGeometry is the product of its axes: its factors are one 1D grid per axis. A discrete geometry’s point_filter marks which of its points belong to it, e.g. a rectilinear grid in a domain that is no box.

  • SampledGeometry: Created by every PointSampler; holds the points (and cells) of the sampler’s current forward pass and a reference to the source geometry, so data configurations and plots can refer to the sampled points.

Goals

  1. Abstraction: Decouple the physical definition of a problem (boundaries, dimensions) from the tensor operations.

  2. Sampling: Provide standardized methods to sample points for training, such as collocation points for Physics-Informed Neural Networks (PINNs).

See DECISIONS.md for design decisions.

qewton.geometries.create_mesh_geometry(*args, **kwargs)[source]

Placeholder, since Gmsh could not be imported.

Subpackages

Submodules

qewton.geometries.base module

Base classes for geometries: Geometry, DiscreteGeometry and BoundaryGeometry.

qewton.geometries.base.vertex_distance_for(max_vertex_distance: float | dict[Variable, float] | None, variable: Variable) → float | None[source]

Return the maximum vertex distance that applies to variable.

Parameters:
  • max_vertex_distance – One value for every geometry, or one value per geometry variable.

  • variable – The variable of the geometry being meshed.

Returns:

The value for variable; None if a dict has no

entry for it.

Return type:

float or None

exception qewton.geometries.base.DeviceTransferWarning[source]

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

class qewton.geometries.base.Geometry(variable: Variable | None = None, dim: int | None = None, shape: tuple[int | None, ...] | ~types.EllipsisType=Ellipsis, backend: type[ComputingBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Serializable, Generic[TensorType]

Geometric domain used for sampling points, meshing and plotting.

Parameters:
  • variable – The variable that belongs to this geometry. If None, an empty placeholder 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.

variable

The variable that belongs to this geometry.

Type:

Variable

dim

The dimension, taken from variable if it is not empty, otherwise the dim passed at construction or set by unification.

Type:

int or None

shape

The discrete shape of the geometry.

Type:

tuple of (int or None) or EllipsisType

backend

The backend used for computations.

Type:

type[ComputingBackend]

markers

Named subdomains of this geometry.

Type:

dict

boundary

The boundary of this geometry. Created by create_boundary() on first access and cached in boundary_object.

Type:

BoundaryGeometry

factors

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.

Type:

list of Geometry or None

Notes

Subclasses should implement create_boundary(), sample_random_uniform(), sample_grid(), contains(), bounding_box() and _get_volume where these operations make sense; the base implementations raise NotImplementedError. They may override create_mesh(), is_discretization_of() and apply_unified().

property device: Device | str

The device holding this geometry’s data. Only to() changes it; methods called with points or a device on another device compute there without moving the geometry.

to(device: Device | str) → Geometry[source]

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.

Parameters:

device (Device | str) – The target device.

Returns:

This geometry.

Return type:

Geometry

property boundary: BoundaryGeometry
create_boundary() → BoundaryGeometry[source]

Create the boundary of this geometry.

Returns:

A new boundary geometry.

Return type:

BoundaryGeometry

Raises:

NotImplementedError – If the geometry has no boundary implementation.

property dim: int | None
apply_unified(unified_variable: Variable, unified_dim: int | None, unified_shape: tuple[int | None, ...] | EllipsisType) → None[source]

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.

Parameters:
  • unified_variable – The unified variable.

  • unified_dim – The unified dimension.

  • unified_shape – The unified shape.

discretize(discretization_points: Any | None = None, discretization_shape: tuple[int, ...] | None = None) → DiscreteGeometry[source]

Discretize this geometry into a DiscreteGeometry.

The discretization is defined by the discretization points, the discretization shape, or both (then they must be consistent).

Parameters:
  • 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:

The discretized geometry. Its

discretization_of is set to this geometry.

Return type:

DiscreteGeometry

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.

is_discrete = False

Whether this geometry consists of given points (and cells), so that nothing discretizes it further.

is_discretization_of(other_geometry: Geometry) → bool[source]

Check whether this geometry is a discretization of another one.

Parameters:

other_geometry – The geometry to compare to.

Returns:

Whether this geometry discretizes other_geometry. Always

False for a continuous geometry.

Return type:

bool

create_mesh(max_vertex_distance: float | None = None, device: Device = CPU())[source]

Mesh this geometry into a mesh geometry.

Parameters:
  • 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:

The meshed geometry.

Return type:

DiscreteGeometry

Raises:

NotImplementedError – If the geometry does not support meshing.

set_marker(marker, marker_description)[source]

Mark a subdomain of this geometry.

Parameters:
  • 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.

get_marker(marker)[source]

Return the subdomain stored under marker.

Parameters:

marker (hashable) – The name of the marker.

Returns:

The stored marker entry.

Return type:

Any

Raises:

KeyError – If no marker with this name exists.

sample_random_uniform(n_points: int, device: Device | str = CPU()) → TensorType[source]

Sample uniformly distributed random points inside the geometry.

Parameters:
  • n_points – The number of points to sample.

  • device – The device to sample on.

Returns:

The sampled points, shape (n_points, dim).

Return type:

TensorType

sample_grid(n_points: int, device: Device | str = CPU()) → TensorType[source]

Sample grid points inside the geometry.

Parameters:
  • n_points – The number of points to sample.

  • device – The device to sample on.

Returns:

The sampled points, shape (n_points, dim).

Return type:

TensorType

contains(points)[source]

Check for every point whether it lies inside the geometry.

Parameters:

points (TensorType) – The points to check, shape (n_points, dim).

Returns:

Boolean tensor of shape (n_points, 1), True

where the point lies inside.

Return type:

TensorType

bounding_box()[source]

Compute the axis-aligned bounds of the geometry.

Returns:

Tensor of length 2 * dim of the form

[axis_1_min, axis_1_max, axis_2_min, axis_2_max, ...].

Return type:

TensorType

set_volume(volume: float)[source]

Set the volume of the geometry by hand.

Parameters:

volume – The volume of the geometry. 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.

property factors: list[Geometry] | None
subproduct(factors: list[Geometry]) → Geometry[source]

The product of some of this product’s factors, of the same kind.

Parameters:

factors – At least two of factors, in their order.

Returns:

The product of factors.

Return type:

Geometry

Raises:

ValueError – If this geometry is no product, or cannot build one of some of its factors.

volume()[source]

Return the volume of the geometry.

Returns:

The volume set by set_volume(), if any, otherwise the

computed volume.

Return type:

float

class qewton.geometries.base.Structure(*values)[source]

Bases: Enum

How the points of a discrete geometry are connected.

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 = 1
MESH = 2
GRID = 3
qewton.geometries.base.boundary_facets(cells: ndarray) → ndarray[source]

The facets of simplex cells that belong to one cell only.

Parameters:

cells – Point indices per cell, shape (n_cells, k).

Returns:

Point indices per facet, shape (n_facets, k - 1).

Return type:

numpy.ndarray

class qewton.geometries.base.DiscreteGeometry(shape: tuple[int, ...], variable: ~qewton.config.variables.Variable | None = None, dim: int | None = None, discretization_points: ~qewton.backends.base.TensorType | None = None, backend: type[~qewton.backends.base.ComputingBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Geometry[TensorType]

Geometry with a concrete discretization shape and optional points.

Parameters:
  • 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.

discretization_of

The geometry this one discretizes, if known.

Type:

Geometry or None

discretization_points

The discrete points of this geometry.

Type:

TensorType or None

point_filter

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.

Type:

TensorType or None

structure

How its points are connected.

Type:

Structure

topological_dim

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.

Type:

int

cells

Point indices per cell, shape (n_cells, n_vertices); None for Structure.POINTS.

Type:

numpy.ndarray or None

boundary_cells

The facets of cells that belong to one cell only, e.g. the triangles bounding a volume of tetrahedra.

Type:

numpy.ndarray

Notes

Subclasses may implement sample_random_uniform_from_discretization() and sample_grid_from_discretization(). A discrete geometry is a point set (Structure.POINTS) unless a subclass with cells overrides structure, topological_dim and cells, and axis_coordinates() for Structure.GRID.

is_discrete = True

Whether this geometry consists of given points (and cells), so that nothing discretizes it further.

discretization_of: Geometry | None
point_filter: TensorType | None
property structure: Structure
property topological_dim: int
property cells: ndarray | None
property boundary_cells: ndarray
coordinates() → ndarray[source]

Return the points as a numpy array on the CPU.

Returns:

Shape (n_points, dim), in the order of the

geometry’s axes in a DataConfiguration (row-major over shape).

Return type:

numpy.ndarray

property axis_components: 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 Structure.GRID.

axis_coordinates() → list[ndarray][source]

Return the coordinates along each axis of a rectilinear grid.

Returns:

One 1D array per axis of shape.

Return type:

list of numpy.ndarray

Raises:

ValueError – If structure is not Structure.GRID.

bounding_box()[source]

Compute the axis-aligned bounds of the geometry.

Uses the discretization points if present, otherwise the bounding box of discretization_of.

Returns:

Tensor of the form [axis_1_min, axis_1_max, ...].

Return type:

TensorType

Raises:

NotImplementedError – If neither points nor a source geometry are available.

is_discretization_of(other_geometry: Geometry) → bool[source]

Check whether this geometry is a discretization of another one.

Parameters:

other_geometry – The geometry to compare to.

Returns:

True if other_geometry equals discretization_of or

is this geometry itself.

Return type:

bool

sample_random_uniform_from_discretization(n_points: int, device: Device | str = CPU()) → TensorType[source]

Sample random points from the discretization points.

Parameters:
  • 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:

The sampled points, shape (n_points, dim).

Return type:

TensorType

sample_grid_from_discretization(n_points: int, device: Device | str = CPU()) → TensorType[source]

Sample points evenly from the discretization points.

Every discretization point is returned equally often.

Parameters:
  • 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:

The sampled points, shape (n_points, dim).

Return type:

TensorType

class qewton.geometries.base.BoundaryGeometry(geometry)[source]

Bases: Geometry[TensorType]

Base class for the boundary of a geometry.

Can be used like any other Geometry.

Parameters:

geometry (Geometry) – The geometry whose boundary this is. Its variable, dimension and backend are taken over.

geometry

The geometry whose boundary this is.

Type:

Geometry

Notes

Subclasses should implement normal(), sample_grid() and sample_random_uniform(), including the include_normals option.

bounding_box()[source]

Return the bounding box of the underlying geometry.

Returns:

Tensor of the form [axis_1_min, axis_1_max, ...].

Return type:

TensorType

create_boundary() → BoundaryGeometry[source]

Raise, since a boundary has no boundary.

Raises:

NotImplementedError – Always.

normal(points, device: Device | str = CPU()) → TensorType[source]

Compute the outward normal vector at each point.

Parameters:
  • points (TensorType) – The boundary points, shape (n_points, dim).

  • device – The device to compute on.

Returns:

The normal vectors, shape (n_points, dim).

Return type:

TensorType

sample_grid(n_points: int, device: Device | str = CPU(), include_normals: bool = False) → TensorType | tuple[TensorType, TensorType][source]

Sample grid points on the boundary.

Parameters:
  • 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:

The points, or

(points, normals) if include_normals is True.

Return type:

TensorType or tuple of TensorType

sample_random_uniform(n_points: int, device: Device | str = CPU(), include_normals: bool = False) → TensorType | tuple[TensorType, TensorType][source]

Sample uniformly distributed random points on the boundary.

Parameters:
  • 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:

The points, or

(points, normals) if include_normals is True.

Return type:

TensorType or tuple of TensorType

qewton.geometries.product module

Cartesian product of two geometries.

class qewton.geometries.product.ProductGeometry(geometry_a: Geometry, geometry_b: Geometry)[source]

Bases: Geometry[TensorType]

Cartesian product of two geometries.

Usually created with geometry_a * geometry_b. Points of the product are the concatenation of a point of geometry_a and a point of geometry_b.

Parameters:
  • geometry_a – The first factor.

  • geometry_b – The second factor. Must use the same backend as geometry_a and a different variable.

geometry_a

The first factor.

Type:

Geometry

geometry_b

The second factor.

Type:

Geometry

factors

The non-product geometries this product is built from, in order. Nested products are flattened.

Type:

list of Geometry

property factors: list[Geometry]
create_mesh(max_vertex_distance: float | dict[Variable, float] | None = None, device: Device = CPU())[source]

Mesh every factor and combine the meshes into a product mesh.

Parameters:
  • max_vertex_distance – How fine each factor mesh is. A dict sets the value per factor variable; factors missing from it get None.

  • device – The device the mesh is created on.

Returns:

The product of the factor meshes, see

ProductMeshGeometry.

Return type:

ProductMeshGeometry

create_boundary() → BoundaryGeometry[source]

Raise, since the boundary of a product is not built directly.

Raises:

NotImplementedError – Always. Build a product of the factor boundaries instead.

sample_grid(n_points: int, device: Device | str = CPU()) → TensorType[source]

Raise, since grids on products are built from product samplers.

Raises:

NotImplementedError – Always. Use a product of samplers instead.

contains(points)[source]

Check for every point whether it lies inside both factors.

Parameters:

points (TensorType) – The points to check; the first geometry_a.dim coordinates belong to geometry_a, the rest to geometry_b.

Returns:

Boolean tensor, True where the point lies inside.

Return type:

TensorType

bounding_box()[source]

Return the concatenated bounding boxes of both factors.

Returns:

Tensor of the form [axis_1_min, axis_1_max, ...].

Return type:

TensorType

sample_random_uniform(n_points: int, device: Device | str = CPU()) → TensorType[source]

Sample random points in both factors and concatenate them.

Parameters:
  • n_points – The number of points to sample.

  • device – The device to sample on.

Returns:

The sampled points, shape (n_points, dim).

Return type:

TensorType