Molecular graphs, equivariance and docking · INTEGRATION
Typed radius, bond-prefix and sequence-neighbor graph assembly
Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.
Your task
Build a directed graph while retaining a slot for every candidate edge. An accepted slot stores its receiver and sender, displacement, and the sender’s feature; rejected slots are zeroed and marked by edge_valid. Radius mode tests supplied periodic sender images against a strict distance cutoff. RFdiffusion modes use sequence/KNN rules and the separately specified displacement sign.
Function signature
radius_neighbor_graph(
activations: dict,
masks: dict,
structure: dict,
neighborhood: str = 'radius',
bond_prefix: bool = False,
kmin: int = 32,
) -> dict[str, torch.Tensor]Worked example
One periodic candidate
In radius mode, let receiver 0 be at [0,0,0], sender 1 at [1,0,0], and sender feature be [7,2]. They are valid and in the same batch. With cell rows [[3,0,0],[0,3,0],[0,0,3]], supplied image shift [-1,0,0], and directed cutoff 2.5, the sender image is [-2,0,0]. This candidate has displacement [-2,0,0], squared distance 4 < 6.25, endpoints [0,1], and neighbor feature [7,2]. It contributes one incoming neighbor to receiver 0; it stays in its original candidate slot.
Parameters
| Parameter | Shape and meaning |
|---|---|
activationsdict | Supplied intermediate tensors. |
masksdict | Supplied masks. Each field below defines what True includes or permits. |
structuredict | Fields supplied together in this dictionary. |
neighborhoodstrDefault 'radius' | Select periodic radius candidates, RF refinement kNN/sequence union, or RF full nonzero-sequence-separation pairs. |
bond_prefixboolDefault False | Prepend supplied bond candidates when True. |
kminintDefault 32 | Minimum sequence-neighborhood width in the RF neighborhood rule. |
Return
dict[str, torch.Tensor]
Return exactly the named fields applicable to this operation.
Required behavior
- Config
neighborhood='radius'(default): enumerateE=N\cdot N\cdot Scandidates in lexicographic order(\mathrm{receiver} i, \mathrm{sender} j, \mathrm{image} s), last index fastest. - For receiver
batchb, shiftu=\mathrm{image\_shifts}[b,s]and row-vector latticecell[b], computer=\mathrm{xyz}[j]+u\mathbin{@}\mathrm{cell}[b]-\mathrm{xyz}[i]. - Keep exactly observed
iandjin the samebatch, an observed image, not (i=jandu=0), and\|r\|^2<\texttt{cutoffs}[b,\texttt{types}[i],\texttt{types}[j]]^2. Nonzero self images are allowed. A duplicate supplied image remains a duplicate edge. Directed typecutoffsneed not be symmetric. - Nonnegative
cutoffsare allowed: cutoff zero disables that directed radius relation. Return fixed-width masked edge arrays, not a data-dependent compact list: every rejected candidate has indices/image_index0and zero geometry/features.neighbor_countcounts accepted candidates per receiver. Configbond_prefix=Falseby default. - If
True, prependLsupplied directedbond_edge_indexcolumns to radius candidates, in their supplied order. Accept a bond independently of radius only ifbond_edge_valid, both nodes are valid in the samebatchand endpoints differ. - Its displacement is
\mathrm{xyz}[\mathrm{sender}]-\mathrm{xyz}[\mathrm{receiver}]without an image shift, and accepted\mathrm{image\_index}=-1.Falsebonds have all-zero outputs.E=L+N\cdot N\cdot Sin this mode. - Do not deduplicate: duplicate supplied bonds and separate bond/radius copies remain separate messages, as in DiffDock's concatenation.
L=0is required ifN=0. Invalid nodes may carry nonfinitexyz/featuresand sentinelbatch/type indices; invalid images may carry arbitrary shifts, all ignored before arithmetic/gather. - Cell/
cutoffsare finite globally.N=0orS=0givesE=0. Selection is exact on the supplied finite list; no nearest-image approximation, automatic image generation, completeness claim or sorting is implied. - Config
neighborhood='rfd_refinement'selects a different nonperiodic graph: each source rowisuppliesknn_index[i,:]withknn_valid. Form a Boolean adjacency from those choices, then OR it withi\ne jand\left|\mathrm{sequence\_index}[j]-\mathrm{sequence\_index}[i]\right|<\mathrm{kmin}. - Config
\mathrm{kmin}=32by default,0\le \mathrm{kmin}<999.9. The inequality is STRICT, matching the released code rather than\mathrm{its} \le \mathrm{comment}. Both nodes must be valid and sharebatch. Duplicate kNN entries and overlaps with sequence neighbors produce ONE pair. - An explicitly supplied self kNN choice is retained (the upstream
\mathrm{top\_k}\ge Lbranch can include self); the sequence term alone never introduces self.Falseknn_validentries and all choices from invalid source rows may have sentinel indices and are ignored before scatter. - Config
neighborhood='rfd_full'ignores kNN and selects same-batchvalid pairs with nonzero sequence-index difference, matchingmake_full_graph. - RF modes enumerate
N\cdot N (\mathrm{source} i,\mathrm{target} j)candidates and return\mathrm{edge\_index}=[j,i]in the common\mathrm{RECEIVER},\mathrm{SENDER}order,\mathrm{image\_index}=0, senderfeaturesfeatures[i], and incoming receiver counts. - Their displacement is
\mathrm{xyz}[j]-\mathrm{xyz}[i], RECEIVER minus SENDER, matching RFdiffusion DGLrel_pos; this sign differs from the radius mode. Pair attributes from upstreampair[i,j]therefore gather aspair[\mathrm{sender},\mathrm{receiver}]. - RF modes ignore
cell/types/radius/image tensors and rejectbond_prefix=True. kNN selection is supplied, not recomputed here: the existingbatched_neighbor_graphcovers unperturbed distance kNN. - Upstream's diagonal
999.9penalty and\mathrm{distance}+\varepsilon\cdot \mathrm{sequence\_separation}ranking must be reflected in supplied choices for exact upstream selection; that\epsilonranking is not silently attributed to the old distance-only exercise. - No coordinate detach is allowed here, unlike upstream's detached basis geometry.
Why this matters
A graph specifies which atoms or residues can exchange messages. The radius mode tests supplied periodic images; RF modes use supplied sequence and neighbor relationships. Their displacement conventions differ, so select the mode before assembling edge geometry.
Starter code
You write the body of this function in the BioTorch workspace. Your code runs in an isolated PyTorch sandbox; Run checks the public examples and Submit grades the full test suite, including gradients.
import torch
def radius_neighbor_graph(
activations: dict,
masks: dict,
structure: dict,
neighborhood: str = 'radius',
bond_prefix: bool = False,
kmin: int = 32,
) -> dict[str, torch.Tensor]:
"""Return dict[str, torch.Tensor]:
edge_index: (2, E).
image_index: (E,).
edge_valid: (E,).
displacements: (E, 3).
squared_distances: (E,).
neighbor_features: (E, F).
neighbor_count: (N,)."""
# Implement the operation. Inputs and test setup are supplied by BioTorch.
raise NotImplementedError("Implement radius_neighbor_graph")
Ready to implement it?
3 progressive hints, a solution walkthrough, and grading that checks values, shapes and gradients are waiting in the workspace.
Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.
Related exercises
Sources and further reading
A primitive exercise, not an end-to-end reproduction of the named models. No affiliation or endorsement is implied.