Mesh

Mesh is the object you work with once the geometry exists: it holds the blocks, the connections between them and the boundary patches. You use it to set boundary conditions, make the mesh periodic, check it, and finally create the solver Domain with Mesh.get_domain(). Every way of making a mesh (builders, BlockMesh, file readers) ends in a Mesh.

A mesh is geometry only (float64, on the CPU), so the same mesh can create domains of different precision, device or batch size.

Creating a mesh

A mesh is made from MeshBlock objects (see Blocks), by BlockMesh.build() (see Multi-block meshes with BlockMesh) or by a reader (see Reading and writing meshes). When blocks are passed to the constructor, faces that coincide are connected:

import torch
import phipict.meshing as pm
from phipict import Face

walls = pm.Patch("walls", pm.Wall())
inlet = pm.Patch("inlet", pm.Inflow((1.0, 0.0)))
outlet = pm.Patch("outlet", pm.Outflow())

left = pm.make_box((0, 0), (1, 1), cells=(8, 8), name="left",
              patches=pm.FacePatches(x_minus=inlet, y_minus=walls, y_plus=walls))
right = pm.make_box((1, 0), (3, 1), cells=(16, 8), name="right",
               patches=pm.FacePatches(x_plus=outlet, y_minus=walls, y_plus=walls))
mesh = pm.Mesh([left, right])
print(mesh)
# Mesh(2D, 2 blocks, 192 cells, 1 connections, patches=[inlet, walls, outlet])

Blocks can also be added one by one with Mesh.add() and connected later with Mesh.auto_connect(); pm.Mesh(blocks, auto_connect=False) skips the automatic connection. Blocks with the same name are renamed (block, block_1, …), and Mesh.block()/Mesh.index() find blocks by name.

Periodicity

Mesh.make_periodic() connects free faces that coincide after a shift, over the full extent of an axis or by a given translation (see Connections and periodicity):

channel = pm.Mesh([pm.make_box((0, -1), (4, 1), cells=(32, 16),
                          patches=pm.FacePatches(y_minus=walls, y_plus=walls))])
channel.make_periodic("x")

Boundary conditions

Patches are attached to faces when the blocks are made. Their conditions can be given with the patch or later by name, which is how conditions are set on meshes read from files (see Boundary patches and conditions):

mesh.set_bc("outlet", pm.Outflow())      # replaces the condition of the patch
print([p.name for p in mesh.patches])
print(mesh.faces("walls"))               # [(block, Face), ...]

Checking

Mesh.check() returns a MeshReport with quality measures and a list of errors: inverted cells, faces that are neither connected nor in a patch, and patches without a condition (see Mesh quality):

report = mesh.check()
print(report)
report.raise_if_invalid()

Creating the domain

Mesh.get_domain() creates the solver Domain: one solver block per mesh block (in the same order and with the same names), the connections and periodicity, and the boundary conditions of all patches. Outflow velocities are scaled so that the boundary fluxes balance, and PrepareSolve is called:

domain = mesh.get_domain(
    viscosity=0.01,
    dtype=torch.float64,
    device="cuda",
    passive_scalar_channels=0,
)

For outflow patches, Mesh.outflow_hook() returns the callback that advects the outflow velocity before every step, and Mesh.boundaries() gives the solver boundaries of any patch:

import phipict
from phipict import Hook, Hooks

hooks = Hooks().append(Hook.PRE, mesh.outflow_hook(domain, velocity=1.0))
sim = phipict.Simulation(domain=domain, dt=0.01, hooks=hooks)
sim.single_step()
outlet_bounds = mesh.boundaries(domain, "outlet")

Mesh.from_domain() goes the other way: it recovers the mesh of an existing domain (e.g. one loaded with load_domain()) with its connections, for plotting or export.

Changing a mesh

Mesh.extrude() turns a 2D mesh into a 3D one, keeping connections and patches; by default the result is periodic in z:

mesh3d = mesh.extrude((0.0, 0.5), cells=4)
print(mesh3d)

Mesh.transform() applies a function to every block and connects the result again, e.g. to rotate a whole mesh:

rotated = mesh.transform(lambda block: block.rotate(30.0))

Plotting

Mesh.plot() draws the grid lines of a 2D mesh (or of one z layer of a mesh extruded along z) with matplotlib, one colour per block from the phiPICT palette:

import matplotlib.pyplot as plt

ax = mesh.plot()
plt.savefig("mesh.png")

API

class phipict.meshing.Mesh(blocks: Iterable[MeshBlock] = (), *, auto_connect: bool = True, rel_tol: float = 0.0001)[source]

Structured multi-block mesh.

Parameters:
  • blocks (iterable of MeshBlock, optional) – Blocks of the mesh. Blocks with the same name are renamed.

  • auto_connect (bool, optional) – Whether to connect the coinciding free faces of the blocks. Default is True.

  • rel_tol (float, optional) – Tolerance of the face matching, relative to the smallest vertex spacing of a face. Default is 1e-4.

add(block: MeshBlock) → int[source]

Add a block (without connecting it) and return its index.

The block’s patches are unified with the mesh’s patches of the same name.

assign_patch(faces: Iterable[tuple[int, Face]], patch: Patch) → None[source]

Put block faces into a patch.

Parameters:
  • faces (iterable of tuple of int and Face) – (block, face) pairs, e.g. from free_faces().

  • patch (Patch) – The patch.

auto_connect(rel_tol: float | None = None) → list[Connection][source]

Connect the free faces whose vertices coincide.

Parameters:

rel_tol (float or None, optional) – Matching tolerance relative to the smallest vertex spacing of a face. Default is the mesh’s rel_tol.

Returns:

The new connections.

Return type:

list of Connection

Raises:

NonConformingInterfaceError – If two faces touch at their corners but their vertices differ.

block(name: str) → MeshBlock[source]

The block called name.

property blocks: tuple[MeshBlock, ...]

The blocks, in the order of the solver blocks.

boundaries(domain: phipict._C.Domain, patch: str | Patch) → list[phipict._C.Boundary][source]

The solver boundaries of a patch in a domain made by get_domain().

E.g. the outflow boundaries to update during the simulation.

bounds() → tuple[Tensor, Tensor][source]

Lower and upper corner of the axis-aligned bounding box.

check() → MeshReport[source]

Check the cells, faces and patches of the mesh.

Returns:

Quality measures; errors for inverted cells, free faces and patches without a condition.

Return type:

MeshReport

connect(block_a: int | str, face_a: Face | int, block_b: int | str, face_b: Face | int, *, orientation: Orientation | None = None, translation: Sequence[float] | None = None) → Connection[source]

Connect two faces explicitly.

The orientation is found from the geometry unless given, so this is only needed for faces that do not coincide (e.g. periodic ones with a rotation).

Parameters:
  • block_a (int or str) – Blocks, by index or name.

  • block_b (int or str) – Blocks, by index or name.

  • face_a (Face) – The faces.

  • face_b (Face) – The faces.

  • orientation (Orientation or None, optional) – Relative orientation of the faces. Default is found from the geometry.

  • translation (sequence of float or None, optional) – Shift from face A to face B for periodic faces. Default is None.

Returns:

The connection.

Return type:

Connection

property connections: tuple[Connection, ...]

The connections between block faces, periodic ones included.

extrude(z_range: tuple[float, float], cells: int, grading: Grading | float | int | None = None, *, periodic: bool = True, z_patches: tuple[Patch | None, Patch | None] = (None, None)) → Mesh[source]

A 3D mesh from this 2D mesh, extruded along z.

Parameters:
  • z_range (tuple of float) – Start and end in z.

  • cells (int) – Number of cells along z.

  • grading (Grading or float or None, optional) – Distribution along z. Default is uniform.

  • periodic (bool, optional) – Whether the mesh is periodic in z. Default is True.

  • z_patches (tuple of Patch or None, optional) – Patches of the -z/+z faces if not periodic.

Returns:

The 3D mesh, with the 2D connections and patches carried over.

Return type:

Mesh

faces(patch: str | Patch) → list[tuple[int, Face]][source]

The (block, face) pairs of a patch.

free_faces() → list[tuple[int, Face]][source]

Faces without a patch or connection, as (block, face).

classmethod from_domain(domain: phipict._C.Domain) → Mesh[source]

The mesh of a solver domain, e.g. one from load_domain().

Connections and periodicity are read from the domain. Fixed faces get a patch "fixed" without a condition.

get_domain(viscosity: float | Tensor, *, dtype: dtype = torch.float32, device: str | device = 'cuda', passive_scalar_channels: int = 1, scalar_viscosity: Tensor | None = None, name: str = 'Domain', prepare: bool = True, balance_outflow: bool = True) → phipict._C.Domain[source]

A solver domain with the blocks, connections and conditions of the mesh.

Solver block i is block i of the mesh.

Parameters:
  • viscosity (float or torch.Tensor) – Kinematic viscosity.

  • dtype (torch.dtype, optional) – Precision of the domain. Default is float32.

  • device (str or torch.device, optional) – Device of the domain. Default is "cuda".

  • passive_scalar_channels (int, optional) – Number of passive scalar channels. Default is 1.

  • scalar_viscosity (torch.Tensor or None, optional) – Diffusivity of the passive scalar. Default is None.

  • name (str, optional) – Name of the domain. Default is "Domain".

  • prepare (bool, optional) – Whether to call domain.PrepareSolve(). Default is True.

  • balance_outflow (bool, optional) – Whether to scale the Outflow velocities so that the boundary fluxes balance, as the solver requires. Default is True.

Returns:

The domain.

Return type:

phipict.Domain

Raises:

ValueError – If faces have neither patch nor connection, or patches have no condition.

index(name: str) → int[source]

Index of the block called name.

make_periodic(axis: int | str | None = None, *, translation: Sequence[float] | None = None, rel_tol: float | None = None) → list[Connection][source]

Connect free faces that coincide after a shift.

Parameters:
  • axis (int or str or None, optional) – Make the mesh periodic along this axis, over its full extent.

  • translation (sequence of float or None, optional) – Or: connect faces that coincide after this shift.

  • rel_tol (float or None, optional) – Matching tolerance, see auto_connect().

Returns:

The new periodic connections.

Return type:

list of Connection

Raises:

ValueError – If no faces match.

property n_cells: int

Total number of cells.

property ndims: int

Number of spatial dimensions.

outflow_hook(domain: phipict._C.Domain, velocity: float | Sequence[float] | Tensor, tol: float | None = None) → Any[source]

A callback that advects the Outflow faces.

Register it before each step, Hooks().append(Hook.PRE, fn). It calls update_advective_boundaries() for the outflow boundaries of a domain made by get_domain().

Parameters:
  • domain (phipict.Domain) – The domain.

  • velocity (float or sequence of float or torch.Tensor) – Velocity the outflow is advected with, e.g. the mean inflow velocity: a vector, or a number for the x component.

  • tol (float or None, optional) – Tolerance of the flux balance. Default is the solver’s.

Returns:

The callback.

Return type:

Callable

patch(name: str) → Patch[source]

The patch called name.

property patches: tuple[Patch, ...]

The patches, one per name.

plot(ax: Any = None, color: str | Sequence[str] | None = None, linewidth: float = 0.5, z_index: int = 0) → Any[source]

Plot the grid lines of the blocks with matplotlib.

Parameters:
  • ax (matplotlib.axes.Axes or None, optional) – Axes to draw into. Default is the current pyplot axes.

  • color (str or sequence of str or None, optional) – One colour for all blocks, or colours cycled over the blocks. Default is the phiPICT palette, cycled if there are more blocks than colours.

  • linewidth (float, optional) – Line width. Default is 0.5.

  • z_index (int, optional) – Vertex layer in z that is plotted for a 3D mesh, which is assumed to be extruded along z. Default is 0.

Returns:

The axes.

Return type:

matplotlib.axes.Axes

set_bc(patch: str | Patch, spec: Wall | FreeSlip | Inflow | Outflow) → None[source]

Set the condition of a patch.

Parameters:
  • patch (str or Patch) – The patch or its name.

  • spec (BoundarySpec) – The condition, e.g. pm.Inflow((1.0, 0.0)).

transform(fn: Any) → Mesh[source]

A copy with every block mapped by fn(block) -> block.

The connections are found again, so fn may also reorder the vertices of a block, e.g. lambda b: b.rotate(30).