# 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.
"""Core data structure for storing ragged adjacency relationships in meshes.
This module provides the Adjacency tensorclass for representing ragged arrays
using offset-indices encoding, commonly used in graph and mesh processing.
"""
import torch
from jaxtyping import Int
from tensordict import TensorClass
from physicsnemo.utils._tracing import is_tracing
# Packed (source, target) keys ``source * n_targets + target`` are used while
# ``n_sources * n_targets`` stays below this bound, safely inside int64.
_PACKED_PAIR_KEY_LIMIT = 1 << 62
[docs]
class Adjacency(TensorClass, skip_post_init_on_rebuild=True):
"""Ragged adjacency list stored with offset-indices encoding.
This structure efficiently represents variable-length neighbor lists using two
arrays: offsets and indices. This is a standard format for sparse graph data
structures and enables GPU-compatible operations on ragged data.
Attributes
----------
offsets : torch.Tensor
Indices into the indices array marking the start of each neighbor list.
Shape ``(n_sources + 1,)``, dtype int64. The i-th source's neighbors are
``indices[offsets[i]:offsets[i+1]]``.
indices : torch.Tensor
Flattened array of all neighbor indices.
Shape ``(total_neighbors,)``, integer dtype. The adjacencies that
``Mesh`` builds store cell indices as int64 and point indices in the
dtype of ``mesh.cells``, so the point-to-points and cell-to-points
adjacencies of an int32 mesh have int32 indices. A mesh without
cells gives int64 indices.
Examples
--------
>>> # Represent [[0,1,2], [3,4], [5], [6,7,8]]
>>> adj = Adjacency(
... offsets=torch.tensor([0, 3, 5, 6, 9]),
... indices=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7, 8]),
... )
>>> adj.to_list()
[[0, 1, 2], [3, 4], [5], [6, 7, 8]]
>>> # Empty neighbor list for source 2
>>> adj = Adjacency(
... offsets=torch.tensor([0, 2, 2, 4]),
... indices=torch.tensor([10, 11, 12, 13]),
... )
>>> adj.to_list()
[[10, 11], [], [12, 13]]
"""
# n_sources_plus_one == n_sources + 1; the trailing offset is len(indices).
offsets: Int[torch.Tensor, " n_sources_plus_one"]
indices: Int[torch.Tensor, " n_total_neighbors"]
def __post_init__(self) -> None:
# Runs on construction and load, but not when tensordict rebuilds an
# existing adjacency (clone, to, indexing): the offsets read below
# synchronize a CUDA device.
if not is_tracing():
### Validate offsets is non-empty
# Offsets must have length (n_sources + 1), so minimum length is 1 (for n_sources=0)
if len(self.offsets) < 1:
raise ValueError(
f"Offsets array must have length >= 1 (n_sources + 1), but got {len(self.offsets)=}. "
f"Even for 0 sources, offsets should be [0]."
)
### Read the first and last offsets in one device-to-host transfer
# (each transfer of a CUDA tensor synchronizes the device).
first_offset, last_offset = torch.stack(
(self.offsets[0], self.offsets[-1])
).tolist()
### Validate offsets starts at 0
if first_offset != 0:
raise ValueError(
f"First offset must be 0, but got {first_offset=}. "
f"The offset-indices encoding requires offsets[0] == 0."
)
### Validate last offset equals length of indices
indices_length = len(self.indices)
if last_offset != indices_length:
raise ValueError(
f"Last offset must equal length of indices, but got "
f"{last_offset=} != {indices_length=}. "
f"The offset-indices encoding requires offsets[-1] == len(indices)."
)
[docs]
def to_list(self) -> list[list[int]]:
"""Convert adjacency to a ragged list-of-lists representation.
This method is primarily for testing and comparison with other libraries.
The order of neighbors within each sublist is preserved (not sorted).
This is, in general, much less efficient than directly using the sparse encoding
itself -- all internal library operations use Adjacency objects directly.
Returns
-------
list[list[int]]
Ragged list where result[i] contains all neighbors of source i.
Empty sublists represent sources with no neighbors.
Examples
--------
>>> adj = Adjacency(
... offsets=torch.tensor([0, 3, 3, 5]),
... indices=torch.tensor([1, 2, 0, 4, 3]),
... )
>>> adj.to_list()
[[1, 2, 0], [], [4, 3]]
"""
### Convert to CPU numpy for Python list operations
offsets_np = self.offsets.cpu().numpy()
indices_np = self.indices.cpu().numpy()
### Build ragged list structure
n_sources = len(offsets_np) - 1
result = []
for i in range(n_sources):
start = offsets_np[i]
end = offsets_np[i + 1]
neighbors = indices_np[start:end].tolist()
result.append(neighbors)
return result
@property
def n_sources(self) -> int:
"""Number of source elements (points or cells) in the adjacency."""
return len(self.offsets) - 1
@property
def n_total_neighbors(self) -> int:
"""Total number of neighbor relationships across all sources."""
return len(self.indices)
@property
def counts(self) -> Int[torch.Tensor, " n_sources"]:
"""Number of neighbors for each source element.
Returns
-------
torch.Tensor
Shape (n_sources,), dtype int64. counts[i] is the number of
neighbors for source i.
Example
-------
>>> adj = Adjacency(
... offsets=torch.tensor([0, 3, 3, 5]),
... indices=torch.tensor([1, 2, 0, 4, 3]),
... )
>>> adj.counts.tolist()
[3, 0, 2]
"""
return self.offsets[1:] - self.offsets[:-1]
[docs]
def expand_to_pairs(
self,
) -> tuple[Int[torch.Tensor, " n_pairs"], Int[torch.Tensor, " n_pairs"]]:
"""Expand offset-indices encoding to (source_idx, target_idx) pairs.
This is the inverse of build_adjacency_from_pairs. It produces a pair
of tensors where (source_indices[i], target_indices[i]) represents the
i-th edge in the adjacency.
Returns
-------
tuple[torch.Tensor, torch.Tensor]
Tuple of (source_indices, target_indices), both shape (n_total_neighbors,).
source_indices[i] is the source entity for the i-th pair.
target_indices[i] is the target entity for the i-th pair.
Examples
--------
>>> adj = Adjacency(
... offsets=torch.tensor([0, 2, 4, 5]),
... indices=torch.tensor([10, 11, 20, 21, 30]),
... )
>>> sources, targets = adj.expand_to_pairs()
>>> sources.tolist()
[0, 0, 1, 1, 2]
>>> targets.tolist()
[10, 11, 20, 21, 30]
"""
device = self.offsets.device
### Handle empty adjacency
if self.n_total_neighbors == 0:
return (
torch.tensor([], dtype=torch.int64, device=device),
self.indices,
)
### For each position in indices, find which source it belongs to
# offsets[i] <= position < offsets[i+1] means position belongs to source i
# searchsorted(offsets, position, right=True) - 1 gives source index
positions = torch.arange(
self.n_total_neighbors, dtype=torch.int64, device=device
)
source_indices = torch.searchsorted(self.offsets, positions, right=True) - 1
return source_indices, self.indices
[docs]
def truncate_per_source(self, max_count: int | None = None) -> "Adjacency":
"""Limit each source to at most max_count neighbors.
This is useful for capping the number of candidates in spatial queries
(e.g., BVH candidate cells) to prevent memory explosion.
Parameters
----------
max_count : int | None, optional
Maximum neighbors per source. If None (default),
returns self unchanged (no limit applied).
Returns
-------
Adjacency
New Adjacency with at most max_count neighbors per source.
If max_count is None, returns self.
Examples
--------
>>> adj = Adjacency(
... offsets=torch.tensor([0, 5, 8, 10]),
... indices=torch.tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
... )
>>> adj.to_list()
[[0, 1, 2, 3, 4], [5, 6, 7], [8, 9]]
>>> adj.truncate_per_source(2).to_list()
[[0, 1], [5, 6], [8, 9]]
"""
if max_count is None:
return self
device = self.offsets.device
### Compute counts per source
counts = self.offsets[1:] - self.offsets[:-1]
### Clamp counts to max_count
clamped_counts = torch.clamp(counts, max=max_count)
### Build new offsets from clamped counts
new_offsets = torch.zeros_like(self.offsets)
new_offsets[1:] = torch.cumsum(clamped_counts, dim=0)
### Build mask for which indices to keep
if self.n_total_neighbors == 0:
return Adjacency(offsets=new_offsets, indices=self.indices)
### Use expand_to_pairs to get source ID for each position
source_ids, _ = self.expand_to_pairs()
# Compute position within source: position - offsets[source_id]
positions = torch.arange(self.n_total_neighbors, device=device)
within_source_pos = positions - self.offsets[source_ids]
# Keep only positions where within_source_pos < max_count
keep_mask = within_source_pos < max_count
return Adjacency(
offsets=new_offsets,
indices=self.indices[keep_mask],
)
[docs]
def build_adjacency_from_pairs(
source_indices: Int[torch.Tensor, " n_pairs"],
target_indices: Int[torch.Tensor, " n_pairs"],
n_sources: int,
n_targets: int | None = None,
) -> Adjacency:
"""Build offset-index adjacency from (source, target) pairs.
This utility consolidates the common pattern of constructing an Adjacency object
from a list of directed edges (source → target pairs).
Algorithm:
1. Sort pairs by source index (then by target for consistency)
2. Binary-search the sorted sources for each source's first pair,
which gives the offsets without a device synchronization
3. Return Adjacency with sorted neighbor lists
Parameters
----------
source_indices : torch.Tensor
Source entity indices, shape (n_pairs,)
target_indices : torch.Tensor
Target entity (neighbor) indices, shape (n_pairs,)
n_sources : int
Total number of source entities (may exceed max(source_indices))
n_targets : int, optional
Strict upper bound for target indices. Passing this avoids a GPU
synchronization and enables a faster composite-key sort.
Returns
-------
Adjacency
Adjacency object where ``adjacency.to_list()[i]`` contains all targets
connected from source ``i``. Sources with no outgoing edges have empty lists.
Examples
--------
>>> # Create adjacency: 0→[1,2], 1→[3], 2→[], 3→[0]
>>> sources = torch.tensor([0, 0, 1, 3])
>>> targets = torch.tensor([1, 2, 3, 0])
>>> adj = build_adjacency_from_pairs(sources, targets, n_sources=4)
>>> adj.to_list()
[[1, 2], [3], [], [0]]
"""
device = source_indices.device
### Handle empty pairs
# Each Adjacency here and below is built with its device, so storing it in a
# Mesh cache on that device keeps the object instead of re-creating it (and
# re-running the validating __post_init__) through ``.to(device)``.
if len(source_indices) == 0:
return Adjacency(
offsets=torch.zeros(n_sources + 1, dtype=torch.int64, device=device),
indices=torch.zeros(0, dtype=torch.int64, device=device),
device=device,
)
if n_targets is None:
n_targets = int(target_indices.max().item()) + 1
### Lexicographic sort by (source, target). The common mesh case has small
# bounded indices, so a single composite-key sort avoids two stable sorts.
if n_sources * n_targets < _PACKED_PAIR_KEY_LIMIT:
composite_keys = source_indices.long() * n_targets + target_indices.long()
sorted_keys = torch.sort(composite_keys).values
del composite_keys
return adjacency_from_sorted_keys(
sorted_keys, n_sources, n_targets, dtype=target_indices.dtype
)
# Fall back to two stable argsorts when the composite key could overflow.
sort_by_target = torch.argsort(target_indices, stable=True)
sort_indices = sort_by_target[
torch.argsort(source_indices[sort_by_target], stable=True)
]
sorted_sources = source_indices[sort_indices]
sorted_targets = target_indices[sort_indices]
### Compute offsets for each source
# offsets[i] marks the start of source i's neighbor list: the number of pairs
# whose source is below i. (CUDA bincount would synchronize twice to bound
# its input.)
offsets = torch.searchsorted(
sorted_sources,
torch.arange(n_sources + 1, dtype=sorted_sources.dtype, device=device),
)
return Adjacency(
offsets=offsets,
indices=sorted_targets,
device=device,
)
def adjacency_from_sorted_keys(
sorted_keys: Int[torch.Tensor, " n_pairs"],
n_sources: int,
n_targets: int,
dtype: torch.dtype = torch.int64,
) -> Adjacency:
"""Build offset-index adjacency from ascending packed (source, target) keys.
Parameters
----------
sorted_keys : torch.Tensor
Ascending int64 keys ``source * n_targets + target``, shape (n_pairs,).
The caller must ensure ``n_sources * n_targets < 2**62``.
n_sources : int
Total number of source entities.
n_targets : int
Strict upper bound for target indices; the radix of the keys.
dtype : torch.dtype, optional
Integer dtype of the returned ``indices``.
Returns
-------
Adjacency
Adjacency whose neighbor lists hold the targets of each source in
ascending order.
"""
device = sorted_keys.device
### offsets[i] is the number of keys below i * n_targets, i.e. the number of
# pairs whose source is below i. (CUDA bincount would synchronize twice to
# bound its input.)
source_starts = (
torch.arange(n_sources + 1, dtype=torch.int64, device=device) * n_targets
)
offsets = torch.searchsorted(sorted_keys, source_starts)
del source_starts
indices = (sorted_keys % n_targets).to(dtype)
return Adjacency(offsets=offsets, indices=indices, device=device)