# SPDX-FileCopyrightText: Copyright (c) 2023 - 2026 NVIDIA CORPORATION & AFFILIATES.
# SPDX-FileCopyrightText: All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Loop subdivision for simplicial meshes.
Loop subdivision is an approximating scheme where both old and new vertices
are repositioned. It produces smooth limit surfaces for triangular meshes.
Original vertices are moved using valence-based weights, and new edge midpoints
use weighted averages. This provides C² continuity for regular vertices.
Reference: Charles Loop, "Smooth Subdivision Surfaces Based on Triangles" (1987)
"""
from typing import TYPE_CHECKING
import torch
from jaxtyping import Float, Int
from physicsnemo.mesh.neighbors._adjacency import build_adjacency_from_pairs
from physicsnemo.mesh.subdivision._data import propagate_cell_data_to_children
from physicsnemo.mesh.subdivision._topology import (
generate_child_cells,
get_subdivision_pattern,
)
from physicsnemo.mesh.utilities._topology import extract_unique_edges
from physicsnemo.utils._index_tuple_ops import unique_index_tuples
if TYPE_CHECKING:
from physicsnemo.mesh.mesh import Mesh
def reposition_original_vertices_2d(
mesh: "Mesh",
unique_edges: Int[torch.Tensor, "n_edges 2"] | None = None,
) -> Float[torch.Tensor, "n_points n_spatial_dims"]:
"""Reposition original vertices using Loop's valence-based formula.
For each vertex, compute new position as:
new_pos = (1 - n*beta) * old_pos + beta * sum(neighbor_positions)
where n is the vertex valence and beta depends on n.
This implementation is fully vectorized using the Adjacency structure directly,
avoiding any Python loops over mesh elements.
Parameters
----------
mesh : Mesh
Input 2D manifold mesh
unique_edges : torch.Tensor | None, optional
Pre-computed unique edges (optional). If provided, uses these
instead of recomputing them, which saves significant time.
Returns
-------
torch.Tensor
Repositioned vertex positions, shape (n_points, n_spatial_dims)
"""
device = mesh.points.device
n_points = mesh.n_points
### Get point-to-point adjacency (vertex neighbors)
if unique_edges is not None:
# Build adjacency directly from pre-computed edges (avoids re-extracting
# edges from cells, which is the expensive part of get_point_to_points_adjacency)
sources = torch.cat([unique_edges[:, 0], unique_edges[:, 1]])
targets = torch.cat([unique_edges[:, 1], unique_edges[:, 0]])
adjacency = build_adjacency_from_pairs(
sources,
targets,
n_sources=n_points,
n_targets=n_points,
)
else:
adjacency = mesh.get_point_to_points_adjacency()
### Compute valences for all points at once
# valences[i] = offsets[i+1] - offsets[i]
# Shape: (n_points,)
valences = adjacency.counts
### Compute beta weights for all valences at once
# Vectorize the beta formula
# If valence == 3: beta = 3/16
# Else: beta = (1/n) * (5/8 - (3/8 + 1/4 * cos(2π/n))²)
# Shape: (n_points,)
# Weights and positions are computed in the points' dtype, but at least
# float32, since neighbor sums can overflow float16; the new positions are
# cast back to the points' dtype
weight_dtype = torch.promote_types(mesh.points.dtype, torch.float32)
points = mesh.points.to(weight_dtype)
valences_float = valences.to(weight_dtype)
cos_term = 3.0 / 8.0 + 0.25 * torch.cos(2.0 * torch.pi / valences_float)
beta_else = (1.0 / valences_float) * (5.0 / 8.0 - cos_term * cos_term)
beta = torch.where(valences == 3, 3.0 / 16.0, beta_else)
# Handle isolated vertices (valence=0) - beta should be 0 to keep original position
beta = torch.where(valences > 0, beta, 0.0)
### Compute neighbor position sums for all points using scatter_add
# For each neighbor relationship, add neighbor's position to source point's sum
# Shape: (n_points, n_spatial_dims)
neighbor_sums = torch.zeros_like(points)
# Get source point indices by expanding offsets
# For adjacency.indices[i], the source point is the one whose offset range contains i
# We can use searchsorted or create source indices directly
# (output_size is known, which spares a device synchronization)
source_point_indices = torch.repeat_interleave(
torch.arange(n_points, dtype=torch.int64, device=device),
valences,
output_size=adjacency.n_total_neighbors,
)
# Get neighbor positions and scatter-add to source points
# adjacency.indices contains the neighbor point indices
neighbor_positions = points[adjacency.indices] # (total_neighbors, n_spatial_dims)
# Expand source_point_indices for scatter_add
source_point_indices_expanded = source_point_indices.unsqueeze(-1).expand(
-1, mesh.n_spatial_dims
)
neighbor_sums.scatter_add_(
dim=0,
index=source_point_indices_expanded,
src=neighbor_positions,
)
### Apply the interior Loop formula for all points at once
# new_pos = (1 - n*beta) * old_pos + beta * sum(neighbors)
# Shape: (n_points, n_spatial_dims)
valences_expanded = valences_float.unsqueeze(-1) # (n_points, 1)
beta_expanded = beta.unsqueeze(-1) # (n_points, 1)
interior_new_positions = (
1 - valences_expanded * beta_expanded
) * points + beta_expanded * neighbor_sums
### Boundary vertices need the Loop boundary/crease mask, not the interior rule.
# Applying the interior one-ring rule to boundary vertices pulls the open
# boundary inward (shrinkage). A manifold boundary vertex instead uses
# new_pos = 3/4 * old + 1/8 * (the two neighbours reached along boundary edges),
# which keeps straight boundaries straight. Boundary vertices with a non-standard
# number of boundary neighbours (corners with !=2, or non-manifold junctions) are
# held fixed to avoid distortion. (compute_loop_edge_positions_2d already
# special-cases boundary *edges*; this makes the *vertex* rule consistent.)
from physicsnemo.mesh.boundaries import get_boundary_edges
boundary_edges = get_boundary_edges(mesh).long() # (n_boundary_edges, 2)
if len(boundary_edges) == 0:
return interior_new_positions.to(mesh.points.dtype)
be0, be1 = boundary_edges[:, 0], boundary_edges[:, 1]
# index_fill_ passes the value as a kernel argument; ``mask[index] = True``
# would copy it from the host and synchronize.
boundary_vertex_mask = torch.zeros(n_points, dtype=torch.bool, device=device)
boundary_vertex_mask.index_fill_(0, be0, True)
boundary_vertex_mask.index_fill_(0, be1, True)
boundary_neighbor_sums = torch.zeros_like(points)
idx0 = be0.unsqueeze(-1).expand(-1, mesh.n_spatial_dims)
idx1 = be1.unsqueeze(-1).expand(-1, mesh.n_spatial_dims)
boundary_neighbor_sums.scatter_add_(0, idx0, points[be1])
boundary_neighbor_sums.scatter_add_(0, idx1, points[be0])
boundary_neighbor_counts = torch.zeros(n_points, dtype=torch.long, device=device)
ones = torch.ones_like(be0)
boundary_neighbor_counts.scatter_add_(0, be0, ones)
boundary_neighbor_counts.scatter_add_(0, be1, ones)
boundary_new_positions = 0.75 * points + 0.125 * boundary_neighbor_sums
# Regular boundary vertex (exactly two boundary neighbours) -> boundary mask;
# other boundary vertices are held fixed (new_pos = old_pos).
is_regular_boundary = boundary_vertex_mask & (boundary_neighbor_counts == 2)
new_positions = torch.where(
is_regular_boundary.unsqueeze(-1),
boundary_new_positions,
torch.where(
boundary_vertex_mask.unsqueeze(-1),
points,
interior_new_positions,
),
)
return new_positions.to(mesh.points.dtype)
def compute_loop_edge_positions_2d(
mesh: "Mesh",
unique_edges: Int[torch.Tensor, "n_edges 2"],
) -> Float[torch.Tensor, "n_edges n_spatial_dims"]:
"""Compute new edge vertex positions using Loop's edge rule.
For an interior edge with endpoints v0, v1 and opposite vertices opp0, opp1:
new_pos = 3/8 * (v0 + v1) + 1/8 * (opp0 + opp1)
For boundary edges, use simple average: (v0 + v1) / 2
Parameters
----------
mesh : Mesh
Input 2D manifold mesh
unique_edges : torch.Tensor
Edge connectivity, shape (n_edges, 2)
Returns
-------
torch.Tensor
Edge vertex positions, shape (n_edges, n_spatial_dims)
"""
from physicsnemo.mesh.boundaries import extract_candidate_facets
### Build edge-to-cells mapping
candidate_edges, parent_cell_indices = extract_candidate_facets(
mesh.cells,
manifold_codimension=mesh.n_manifold_dims - 1,
)
### Map candidates to unique edges and count adjacent cells for each edge
# adjacent_counts shape: (n_edges,)
_, inverse_indices, adjacent_counts = unique_index_tuples(
candidate_edges,
index_bound=mesh.n_points,
return_inverse=True,
return_counts=True,
)
### Identify boundary vs interior edges
is_interior = adjacent_counts == 2
### Boundary rule (simple average), computed for every edge
# In the points' dtype, but at least float32, since sums of positions can
# overflow float16; the positions are cast back to the points' dtype
points = mesh.points.to(torch.promote_types(mesh.points.dtype, torch.float32))
v0_pos = points[unique_edges[:, 0]] # (n_edges, n_spatial_dims)
v1_pos = points[unique_edges[:, 1]] # (n_edges, n_spatial_dims)
boundary_positions = (v0_pos + v1_pos) / 2
### Interior rule (Loop's formula), also computed for every edge
# torch.where then keeps it for the interior edges; selecting them by boolean
# masks instead would synchronize the device for each selection.
# Sorted by edge, the candidates of each edge form one contiguous run, so the
# two cells adjacent to an interior edge are the first two of its run. (For
# any other edge the second entry is unused, and may belong to the next edge.)
sorted_parents = parent_cell_indices[torch.argsort(inverse_indices)]
run_starts = torch.cumsum(adjacent_counts, dim=0) - adjacent_counts
second = (run_starts + 1).clamp(max=len(sorted_parents) - 1)
# Shape: (n_edges, 2)
adjacent_cells = torch.stack(
[sorted_parents[run_starts], sorted_parents[second]], dim=1
)
### Get the triangles
# Shape: (n_edges, 2, 3)
triangles = mesh.cells[adjacent_cells]
### Find opposite vertices for each triangle
# For each triangle, find the vertex that's not in the edge
# Shape: (n_edges, 2, 3) - broadcast comparison
edge_v0 = unique_edges[:, 0].unsqueeze(1).unsqueeze(2) # (n_edges, 1, 1)
edge_v1 = unique_edges[:, 1].unsqueeze(1).unsqueeze(2) # (n_edges, 1, 1)
is_edge_vertex = (triangles == edge_v0) | (triangles == edge_v1)
# The opposite vertex is where is_edge_vertex is False; argmax finds it
# Shape: (n_edges, 2)
opposite_vertex_indices = torch.argmax((~is_edge_vertex).int(), dim=2)
opposite_vertices = torch.gather(
triangles, # (n_edges, 2, 3)
dim=2,
index=opposite_vertex_indices.unsqueeze(2), # (n_edges, 2, 1)
).squeeze(2) # (n_edges, 2)
### Compute Loop edge rule: 3/8 * (v0 + v1) + 1/8 * (opp0 + opp1)
opp0_pos = points[opposite_vertices[:, 0]] # (n_edges, n_spatial_dims)
opp1_pos = points[opposite_vertices[:, 1]] # (n_edges, n_spatial_dims)
interior_positions = (3.0 / 8.0) * (v0_pos + v1_pos) + (1.0 / 8.0) * (
opp0_pos + opp1_pos
)
return torch.where(
is_interior.unsqueeze(-1), interior_positions, boundary_positions
).to(mesh.points.dtype)
[docs]
def subdivide_loop(mesh: "Mesh") -> "Mesh":
"""Perform one level of Loop subdivision on the mesh.
Loop subdivision is an approximating scheme that:
1. Repositions original vertices using valence-weighted averaging
2. Creates new edge vertices using weighted stencils
3. Connects vertices to form 4 triangles per original triangle
Properties:
- Approximating: original vertices move to new positions
- Produces C² smooth limit surfaces for regular meshes
- Designed for 2D manifolds (triangular meshes)
- For non-2D manifolds: raises NotImplementedError
The result is a smoother mesh that approximates (rather than interpolates)
the original surface.
Parameters
----------
mesh : Mesh
Input mesh to subdivide (must be 2D manifold)
Returns
-------
Mesh
Subdivided mesh with Loop-repositioned vertices
Raises
------
NotImplementedError
If n_manifold_dims is not 2
Examples
--------
>>> from physicsnemo.mesh.primitives.surfaces import sphere_icosahedral
>>> # Smooth a rough triangulated surface
>>> mesh = sphere_icosahedral.load(subdivisions=2)
>>> smooth = subdivide_loop(mesh)
>>> # Original vertices have moved; result is smoother
"""
from physicsnemo.mesh.mesh import Mesh
### Check manifold dimension
if mesh.n_manifold_dims != 2:
raise NotImplementedError(
f"Loop subdivision currently only supports 2D manifolds (triangular meshes). "
f"Got {mesh.n_manifold_dims=}. "
f"For other dimensions, use linear subdivision instead."
)
### Handle empty mesh
if mesh.n_cells == 0:
return mesh
### Extract unique edges
unique_edges, edge_inverse = extract_unique_edges(mesh)
n_original_points = mesh.n_points
### Reposition original vertices (pass unique_edges to avoid recomputation)
repositioned_vertices = reposition_original_vertices_2d(
mesh, unique_edges=unique_edges
)
### Compute new edge vertex positions
edge_vertices = compute_loop_edge_positions_2d(mesh, unique_edges)
### Combine repositioned original vertices and new edge vertices
new_points = torch.cat([repositioned_vertices, edge_vertices], dim=0)
### Interpolate point_data
# For Loop subdivision, data should ideally be repositioned like geometry,
# but for simplicity, use linear interpolation for edge data
from physicsnemo.mesh.subdivision._data import interpolate_point_data_to_edges
new_point_data = interpolate_point_data_to_edges(
point_data=mesh.point_data,
edges=unique_edges,
n_original_points=n_original_points,
)
### Get subdivision pattern
subdivision_pattern = get_subdivision_pattern(mesh.n_manifold_dims)
# non_blocking: a small pageable host table, staged by CUDA before returning
subdivision_pattern = subdivision_pattern.to(mesh.cells.device, non_blocking=True)
### Generate child cells
child_cells = generate_child_cells(
parent_cells=mesh.cells,
edge_inverse=edge_inverse,
n_original_points=n_original_points,
subdivision_pattern=subdivision_pattern,
)
### Propagate cell_data
new_cell_data = propagate_cell_data_to_children(
cell_data=mesh.cell_data,
n_children_per_parent=subdivision_pattern.shape[0],
device=mesh.cells.device,
)
### Create and return subdivided mesh
result = Mesh(
points=new_points,
cells=child_cells,
point_data=new_point_data,
cell_data=new_cell_data,
global_data=mesh.global_data.copy(), # Shared tensors, own container
)
from physicsnemo.mesh.calculus.measure import (
EFFECTIVE_MEASURE_KEY,
_transfer_cell_measures,
)
if EFFECTIVE_MEASURE_KEY in mesh.cell_data:
# Only explicit measures need each child's parent index
parent_indices = torch.arange(
mesh.n_cells, device=mesh.cells.device
).repeat_interleave(subdivision_pattern.shape[0])
_transfer_cell_measures(mesh, result, parent_indices)
return result