|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023 - 2026 NVIDIA CORPORATION & AFFILIATES. |
| 2 | +# SPDX-FileCopyrightText: All rights reserved. |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +"""Cell area (n-simplex volume) computation for simplicial meshes. |
| 18 | +
|
| 19 | +Computes the volume of each n-simplex from its edge vectors using |
| 20 | +dimension-specific closed-form expressions where possible: |
| 21 | +
|
| 22 | +- **Edges** (n=1): vector norm. |
| 23 | +- **Triangles** (n=2): Lagrange identity (works in any spatial dimension). |
| 24 | +- **Tetrahedra** (n=3): scalar triple product in 3-space, or Sarrus' rule |
| 25 | + on the 3x3 Gram matrix for higher spatial dimensions. |
| 26 | +- **General** (n>=4): Gram determinant via ``torch.det``. |
| 27 | +
|
| 28 | +The closed-form branches use only multiply-add-sqrt operations, so they |
| 29 | +support reduced-precision dtypes (bfloat16, float16) natively. The general |
| 30 | +fallback disables ``torch.autocast`` to keep ``torch.matmul`` in the |
| 31 | +native dtype, since ``torch.det`` dispatches to cuBLAS LU factorization |
| 32 | +which does not support reduced-precision dtypes. |
| 33 | +""" |
| 34 | + |
| 35 | +import math |
| 36 | + |
| 37 | +import torch |
| 38 | +from jaxtyping import Float |
| 39 | + |
| 40 | + |
| 41 | +def compute_cell_areas( |
| 42 | + relative_vectors: Float[torch.Tensor, "n_cells n_manifold_dims n_spatial_dims"], |
| 43 | +) -> Float[torch.Tensor, " n_cells"]: |
| 44 | + """Compute volumes (areas) of n-simplices from edge vectors. |
| 45 | +
|
| 46 | + Given the edge vectors ``e_i = v_{i+1} - v_0`` for each simplex, computes |
| 47 | + the n-dimensional volume: |
| 48 | +
|
| 49 | + .. math:: |
| 50 | + \\text{vol} = \\frac{1}{n!} \\sqrt{\\lvert \\det(E E^T) \\rvert} |
| 51 | +
|
| 52 | + where *E* is the matrix whose rows are the edge vectors. Specialized |
| 53 | + closed-form expressions are used for n <= 3 (see module docstring). |
| 54 | +
|
| 55 | + Args: |
| 56 | + relative_vectors: Edge vectors of shape |
| 57 | + ``(n_cells, n_manifold_dims, n_spatial_dims)``. |
| 58 | + Row *i* is the vector from vertex 0 to vertex *i+1* of each |
| 59 | + simplex. |
| 60 | +
|
| 61 | + Returns: |
| 62 | + Tensor of shape ``(n_cells,)`` with the volume of each simplex. |
| 63 | + For 1-simplices this is edge length, for 2-simplices triangle area, |
| 64 | + for 3-simplices tetrahedral volume, etc. |
| 65 | +
|
| 66 | + Examples: |
| 67 | + >>> # Unit right triangle in 2D |
| 68 | + >>> vecs = torch.tensor([[[1.0, 0.0], [0.0, 1.0]]]) |
| 69 | + >>> compute_cell_areas(vecs) |
| 70 | + tensor([0.5000]) |
| 71 | +
|
| 72 | + >>> # Unit edge in 3D |
| 73 | + >>> vecs = torch.tensor([[[1.0, 0.0, 0.0]]]) |
| 74 | + >>> compute_cell_areas(vecs) |
| 75 | + tensor([1.]) |
| 76 | +
|
| 77 | + >>> # Regular tetrahedron |
| 78 | + >>> vecs = torch.tensor([[[1.0, 0.0, 0.0], |
| 79 | + ... [0.5, 0.866025, 0.0], |
| 80 | + ... [0.5, 0.288675, 0.816497]]]) |
| 81 | + >>> compute_cell_areas(vecs).item() # doctest: +SKIP |
| 82 | + 0.1178... |
| 83 | + """ |
| 84 | + n_manifold_dims = relative_vectors.shape[-2] |
| 85 | + |
| 86 | + match n_manifold_dims: |
| 87 | + case 1: |
| 88 | + return _edge_lengths(relative_vectors) |
| 89 | + case 2: |
| 90 | + return _triangle_areas(relative_vectors) |
| 91 | + case 3: |
| 92 | + return _tetrahedron_volumes(relative_vectors) |
| 93 | + case _: |
| 94 | + return _gram_det_volumes(relative_vectors) |
| 95 | + |
| 96 | + |
| 97 | +# --------------------------------------------------------------------------- |
| 98 | +# Specialized branches |
| 99 | +# --------------------------------------------------------------------------- |
| 100 | + |
| 101 | + |
| 102 | +def _edge_lengths( |
| 103 | + relative_vectors: Float[torch.Tensor, "n_cells 1 n_spatial_dims"], |
| 104 | +) -> Float[torch.Tensor, " n_cells"]: |
| 105 | + """Edge length = ||e1||.""" |
| 106 | + return relative_vectors[:, 0].norm(dim=-1) |
| 107 | + |
| 108 | + |
| 109 | +def _triangle_areas( |
| 110 | + relative_vectors: Float[torch.Tensor, "n_cells 2 n_spatial_dims"], |
| 111 | +) -> Float[torch.Tensor, " n_cells"]: |
| 112 | + r"""Triangle area via Lagrange's identity (any spatial dimension). |
| 113 | +
|
| 114 | + .. math:: |
| 115 | + A = \tfrac{1}{2}\sqrt{\|e_1\|^2 \|e_2\|^2 - (e_1 \cdot e_2)^2} |
| 116 | +
|
| 117 | + This is equivalent to ``||e1 x e2|| / 2`` but generalises beyond 3-space. |
| 118 | + """ |
| 119 | + e1, e2 = relative_vectors[:, 0], relative_vectors[:, 1] |
| 120 | + d11 = (e1 * e1).sum(-1) |
| 121 | + d22 = (e2 * e2).sum(-1) |
| 122 | + d12 = (e1 * e2).sum(-1) |
| 123 | + # clamp guards against tiny negative values from floating-point roundoff |
| 124 | + return (d11 * d22 - d12 * d12).clamp(min=0).sqrt() / 2 |
| 125 | + |
| 126 | + |
| 127 | +def _tetrahedron_volumes( |
| 128 | + relative_vectors: Float[torch.Tensor, "n_cells 3 n_spatial_dims"], |
| 129 | +) -> Float[torch.Tensor, " n_cells"]: |
| 130 | + """Tetrahedral volume, dispatching on spatial dimension.""" |
| 131 | + n_spatial_dims = relative_vectors.shape[-1] |
| 132 | + if n_spatial_dims == 3: |
| 133 | + return _tetrahedron_volumes_3d(relative_vectors) |
| 134 | + return _tetrahedron_volumes_general(relative_vectors) |
| 135 | + |
| 136 | + |
| 137 | +def _tetrahedron_volumes_3d( |
| 138 | + relative_vectors: Float[torch.Tensor, "n_cells 3 3"], |
| 139 | +) -> Float[torch.Tensor, " n_cells"]: |
| 140 | + r"""Tetrahedral volume via scalar triple product (3D only). |
| 141 | +
|
| 142 | + .. math:: |
| 143 | + V = \frac{1}{6} \lvert e_1 \cdot (e_2 \times e_3) \rvert |
| 144 | + """ |
| 145 | + e1, e2, e3 = relative_vectors[:, 0], relative_vectors[:, 1], relative_vectors[:, 2] |
| 146 | + return (e1 * torch.linalg.cross(e2, e3)).sum(-1).abs() / 6 |
| 147 | + |
| 148 | + |
| 149 | +def _tetrahedron_volumes_general( |
| 150 | + relative_vectors: Float[torch.Tensor, "n_cells 3 n_spatial_dims"], |
| 151 | +) -> Float[torch.Tensor, " n_cells"]: |
| 152 | + r"""Tetrahedral volume via Sarrus' rule on the 3x3 Gram matrix. |
| 153 | +
|
| 154 | + Computes the 6 unique entries of the symmetric Gram matrix |
| 155 | + :math:`G_{ij} = e_i \cdot e_j` and evaluates its determinant with the |
| 156 | + closed-form 3x3 expansion. Works for any spatial dimension >= 3. |
| 157 | + """ |
| 158 | + e1, e2, e3 = relative_vectors[:, 0], relative_vectors[:, 1], relative_vectors[:, 2] |
| 159 | + ### 6 unique dot products (G is symmetric) |
| 160 | + g11 = (e1 * e1).sum(-1) |
| 161 | + g22 = (e2 * e2).sum(-1) |
| 162 | + g33 = (e3 * e3).sum(-1) |
| 163 | + g12 = (e1 * e2).sum(-1) |
| 164 | + g13 = (e1 * e3).sum(-1) |
| 165 | + g23 = (e2 * e3).sum(-1) |
| 166 | + ### Sarrus' rule: det(G) expanded along first row |
| 167 | + det_G = ( |
| 168 | + g11 * (g22 * g33 - g23 * g23) |
| 169 | + - g12 * (g12 * g33 - g23 * g13) |
| 170 | + + g13 * (g12 * g23 - g22 * g13) |
| 171 | + ) |
| 172 | + return det_G.clamp(min=0).sqrt() / 6 |
| 173 | + |
| 174 | + |
| 175 | +def _gram_det_volumes( |
| 176 | + relative_vectors: Float[torch.Tensor, "n_cells n_manifold_dims n_spatial_dims"], |
| 177 | +) -> Float[torch.Tensor, " n_cells"]: |
| 178 | + r"""General n-simplex volume via Gram determinant (n >= 4). |
| 179 | +
|
| 180 | + Falls back to ``torch.matmul`` + ``torch.det`` for manifold dimensions |
| 181 | + that lack a closed-form specialization. Disables ``torch.autocast`` so |
| 182 | + that ``matmul`` operates in the native dtype of the input, because |
| 183 | + ``torch.det`` dispatches to cuBLAS LU factorization which does not |
| 184 | + support reduced-precision dtypes (bfloat16, float16). |
| 185 | + """ |
| 186 | + with torch.autocast(device_type=relative_vectors.device.type, enabled=False): |
| 187 | + gram_matrix = torch.matmul( |
| 188 | + relative_vectors, |
| 189 | + relative_vectors.transpose(-2, -1), |
| 190 | + ) |
| 191 | + n_manifold_dims = relative_vectors.shape[-2] |
| 192 | + factorial = math.factorial(n_manifold_dims) |
| 193 | + return gram_matrix.det().abs().sqrt() / factorial |
0 commit comments