Write me a sum over a neighborhood in pytorch
- User
Write me a sum over a neighborhood in pytorch
- Assistant
To write a sum over a neighborhood in PyTorch, we can leverage PyTorch's tensor indexing and scatter operations. The goal is to sum properties (e.g., features) of neighboring atoms for each atom in a system. Below is an example implementation that sums features over neighborhoods using a neighborhood index list (
idx_iandidx_j) similar to the one used inSchNetLayerin the provided codebase.Example: Sum Over Neighborhood in PyTorch
pythonimport torch import torch_scatter def sum_over_neighborhood(features, idx_i, idx_j, pair_mask=None): """ Perform a sum over the neighborhood for each atom. Args: features (torch.Tensor): Atomic features, shape: (n_atoms, F). idx_i (torch.Tensor): Indices of center atoms, shape: (n_pairs,). idx_j (torch.Tensor): Indices of neighbor atoms, shape: (n_pairs,). pair_mask (torch.Tensor, optional): Index-based mask to exclude invalid pairs, shape: (n_pairs,). If None, all pairs are considered valid. Returns: torch.Tensor: Result of summing neighbor features for each atom, shape: (n_atoms, F). """ # Gather features of neighbors using idx_j neighbor_features = features[idx_j] # shape: (n_pairs, F) # Apply mask if provided if pair_mask is not None: neighbor_features = neighbor_features * pair_mask.unsqueeze(-1) # shape: (n_pairs, F) # Sum the neighbor features for each atom using scatter_add n_atoms = features.size(0) summed_features = torch_scatter.scatter_add(neighbor_features, idx_i, dim=0, dim_size=n_atoms) return summed_features # Example Usage if __name__ == "__main__": # Number of atoms and feature dimensions n_atoms, F = 5, 3 # Example atomic features features = torch.rand(n_atoms, F) # Shape: (n_atoms, F) # Example indices for pairs (idx_i: central atoms, idx_j: neighbors) idx_i = torch.tensor([0, 0, 1, 1, 2, 3, 4]) # Shape: (n_pairs,) idx_j = torch.tensor([1, 2, 0, 2, 3, 4, 3]) # Shape: (n_pairs,) # Optional pair mask pair_mask = torch.tensor([1, 1, 1, 1, 1, 0, 1], dtype=torch.float32) # Shape: (n_pairs,) # Compute sum over neighborhood result = sum_over_neighborhood(features, idx_i, idx_j, pair_mask=pair_mask) print("Features:") print(features) print("\nSummed Features:") print(result)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.