Grids, meshes and point clouds

The same shape as a grid, a graph or a point cloud: how geometry and fields become tensors.

Outcome: Describe the same geometry as a grid, a graph and a point cloud; build each with NumPy, SciPy and PyTorch, and name its tensor: (C, H, W), edge_index (2, E), (N, 3).

Builds on A first field surrogate

The project’s neural field (a first surrogate, end to end) receives the aircraft’s geometry only as each point’s position and normal and the two design numbers, sees each point alone and covers one family of shapes. A network that reads the geometry itself needs it as arrays, and the structure of those arrays decides which networks can use them. There are three common choices.

Figure 5-1. Flow speed around the wing section at α 4°: the same slice, drawn as the representation chosen below.

Voxel grid. The geometry is rasterised onto a regular 3D grid, and each cell stores a value of the field there, an average or an interpolated sample. Grids are simple, GPU-friendly and what convolutional networks expect. But memory grows with the cube of the resolution, anything thinner than a cell, such as a trailing edge, can disappear, and cells cut by the wall mix fluid and solid, which smears the thin, high-gradient region at the surface. U-Nets and Fourier neural operators work on grids.

Graph. Nodes sit on mesh points and edges connect neighbours, taken from the simulation mesh or built by k-nearest neighbours. An unstructured CFD mesh fits as it is: nodes crowd the wall and the leading edge and thin out in the far field, so the graph follows the geometry closely. Each node carries the field at that point; edges say which nodes exchange information. The price: information moves one hop per layer, so long-range effects need many layers or multiscale graphs. Graph networks such as MeshGraphNets work on graphs.

Point cloud. Only points with coordinates, and often normals, with no connectivity. It is the lightest form and can come from CAD tessellations or scans. Point-cloud models take the points in any order and can accept different point counts, though accuracy depends on how densely the surface is sampled. The geometry is only implicit: the points sample the surface, and nothing says what lies between them. The network has to learn spatial relations itself, with attention, a learned latent grid or by conditioning on coordinates. The neural field works on points, and so do the attention models from tokens onwards.

Geometry on a grid: signed distance

On a grid, the simplest geometry channel is a mask: 1 inside the body, 0 in the fluid. A richer one is the signed distance field (SDF).

DefinitionSigned distance field

Every cell stores its distance to the nearest wall, negative inside the body, zero on the wall, positive in the fluid.

It gives the network both where the body is and the distance to the nearest wall at every cell, a quantity that turbulence models such as Spalart–Allmaras also take as an input.

The tensors each structure becomes

  • Grid. (C, H, W) in 2D or (C, D, H, W) in 3D, with C channels (SDF, inflow velocity, later pressure) and one value per cell. A batch adds a leading dimension B.
  • Graph. Node features xx of shape (N, F), and the connectivity as edge_index, a (2, E) tensor of integers: column k holds the sender and the receiver of edge k. Edge features, if any, are (E, F_e).
  • Point cloud. Coordinates (N, 3), plus per-point features (N, F). Order carries no meaning.

Example 5-1 builds the three structures. The grid holds a circle, since the aircraft’s surface is not a grid; the point cloud and the graph are the 2,000 surface points of the download’s first run.

Example 5-1. One grid, then the aircraft as a point cloud and a graph, with NumPy, SciPy and PyTorch
import numpy as np
import torch
from scipy.spatial import KDTree
from aircraft import load_runs

# Grid: C channels on an H x W image. One channel here:
# the signed distance to a circle (< 0 inside the body,
# 0 on the wall, > 0 in the fluid).
H, W = 64, 128
y, x = np.meshgrid(np.linspace(-1, 1, H),
                   np.linspace(-2, 2, W), indexing="ij")
sdf = np.sqrt(x**2 + y**2) - 0.51
# (C, H, W) = (1, 64, 128)
grid = torch.tensor(sdf, dtype=torch.float32)[None]2

# Point cloud: run 0 of the aircraft, N = 2,000 surface
# points with 3 coordinates, (N, 3), and Cp there, (N, 1).
d = load_runs()
points = d["xyz"][0]
cp = d["cp"][0][:, None]

# Graph: connect each point to its 8 nearest neighbours.
# The first neighbour returned is the point itself.
_, nbr = KDTree(points).query(points, k=9)3
src = np.repeat(np.arange(len(points)), 8)
dst = nbr[:, 1:].reshape(-1)
# (2, E) with E = 8 N. Senders first: each point receives
# from its 8 neighbours.
edge_index = torch.tensor(np.stack([dst, src]))4

print(grid.shape, points.shape, cp.shape, edge_index.shape)
  1. The signed distance to a circle of radius 0.5: the distance to the centre minus the radius.
  2. [None] adds the channel axis, so the single SDF grid becomes (C, H, W) = (1, 64, 128).
  3. k=9, not 8, because each point is its own nearest neighbour; nbr[:, 1:] drops it.
  4. Despite their names, dst holds the neighbours and goes in row 0, the senders; src, each point repeated 8 times, goes in row 1, the receivers. That is PyTorch Geometric’s default direction, source to target.

Example 5-1 prints torch.Size([1, 64, 128]) (2000, 3) (2000, 1) torch.Size([2, 16000]): 8 one-way edges into each of the 2,000 points.

When the simulation mesh exists, the graph takes its edges; the k-nearest-neighbour graph of Example 5-1 is for point clouds without one, such as the download, which stores no mesh. Public datasets differ in the same way: AirfRANS gives 2D airfoil runs with their volume and surface fields, and DrivAerML gives car runs on meshes of about 160 million cells, too many to pass through a network at once, so models train on samples of them (training on industrial meshes).

Moving between structures is interpolation: a mesh field is resampled onto a grid (for example with scipy.interpolate.griddata) and grid predictions are interpolated back to the surface points. Each such step can lose detail near walls, which is one reason mesh-native and point-based models exist.

A network for unordered points

A point cloud has no grid, no edges and no order. PointNet (Qi et al. 2017) handles this with two ideas: apply the same small MLP to every point, then combine all points with an operation that ignores order, such as a maximum. The result is one vector describing the whole shape; copying it back to every point lets each point's prediction depend on the global shape. The attention models of the next unit replace the single maximum with a learned way of mixing points.

Example 5-2. The PointNet idea in PyTorch: a shared MLP, then a max over points
import numpy as np
import torch
from torch import nn
from aircraft import load_runs

class PointNetSeg(nn.Module):
    def __init__(self, f_in=6, d=64):
        super().__init__()
        # The same small MLP for every point
        self.local = nn.Sequential(
            nn.Linear(f_in, d), nn.SiLU(), nn.Linear(d, d))
        self.head = nn.Sequential(
            nn.Linear(2 * d, d), nn.SiLU(), nn.Linear(d, 1))

    def forward(self, pts):             # pts: (B, N, f_in)
        h = self.local(pts)             # (B, N, d)1
        # Max over points: one vector for the whole shape,
        # whatever the order or number of points.
        g = h.max(dim=1, keepdim=True).values2
        g = g.expand_as(h)              # copy it to each point
        return self.head(torch.cat([h, g], dim=-1))3

# Two runs of the aircraft, 2,000 points each: xyz and normal
d = load_runs()
pts = np.concatenate([d["xyz"][:2], d["normal"][:2]], axis=-1)
pts = torch.tensor(pts)
torch.manual_seed(0)
print(PointNetSeg()(pts).shape)         # (2, 2000, 1)
  1. nn.Linear acts on the last axis, so the same weights are applied to each of the N points independently.
  2. The maximum runs over axis 1, the points, separately for each of the dd features. keepdim=True leaves a shape of (B, 1, d), ready to be copied.
  3. Each point now carries its own dd features and the shape’s dd: the 2d2d inputs of self.head.

Example 5-2 prints torch.Size([2, 2000, 1]): one value per point of each of the two runs, from their positions and normals alone. Those inputs carry the sweep, which moves the points, but not the angle of attack, which leaves them where they are; to predict cp, each point’s features would also take α\alpha and Λ\Lambda (f_in=8).

Up to the rollout lesson’s Burgers model, the listings of this unit run untrained models, on the aircraft or on random tensors, to show shapes and mechanics. Trained on the aircraft, a model of the unit is compared on the rows of the project’s results table; an exercise of the graph-network lesson does this for MeshGNN.

Check yourself

  1. 1A trailing edge is 2 mm thick and the grid cells are 5 mm. In which representation does it disappear?
  2. 2A car’s surface points come out in a different order every time it is exported. What must a PointNet-style network do?
  3. 3A mesh graph has 10,000 nodes with 5 features each and 60,000 edges. What is the shape of edge_index?
What does a signed distance of −0.02 at a grid cell mean?

The cell centre is inside the body, 0.02 length units from the nearest wall. Zero is on the wall, positive values are in the fluid.

Exercises

  1. Exercise 5-1. Store each edge of the aircraft’s nearest-neighbour graph (k = 8, run 0) in both directions, without duplicates. Are there 32,000 edges?

    Answer

    No: 19,014. Many neighbour pairs are mutual, each point among the other’s eight nearest, so the reversed edges add only 3,014 new ones. np.unique(..., axis=1) on the stacked pairs removes the duplicates, as in the listing of the graph-network lesson.

  2. Exercise 5-2. Shuffle the order of the 2,000 points of one run before PointNet, and compare its output with the unshuffled one, each value matched to its point.

    Answer

    They match exactly: the largest difference is 0.0. The shared MLP acts on each point alone, and the maximum over points ignores their order.

Go further