Distance Grid Methods — Choosing the Right Backend
Compare all four distance grid backends (rust_exact, rust_aabb, rust_aabb_interp, cpu/dask), pick the right one for your system size, and learn which two methods to never use.
Overview
The distance grid is the foundation of every mofography pore analysis — segmentation, RAG, PSD, PLD, and surface area all consume the same dgrid array. Which function you call to build that array matters because each backend trades off accuracy, memory, and runtime differently, and two of the legacy backends are unsafe on non-orthogonal cells.
This tutorial covers:
The four active distance grid backends and their exact signatures
A decision tree mapping system size to the right method
The auto-AABB policy the interactive app uses
⚠️ The two broken methods to never use and why
If you have not done so, please complete the Distance Grid tutorial first — the rest of this page assumes you understand what a dgrid is and what spacing controls.
The four distance grid backends
#
Function
Strategy
Best for
Status
1
dgrid_from_atoms_rust
Brute-force Rust, exact MIC, thread-parallel
All systems — default
✅ Active
2
dgrid_from_atoms_aabb_rust
R-tree (AABB) neighbor search in Rust
Large systems, memory-constrained
✅ Active
3
dgrid_from_atoms_aabb_interp_rust
Coarse AABB + trilinear interpolation
Very large systems, mild smoothing OK
✅ Active
4
dgrid_from_atoms_cpu
freud AABBQuery + Dask, Python
Legacy compatibility
⚠️ Legacy
Warning⚠️ Do NOT use these two methods
dgrid_from_atoms_gpu and dgrid_from_atoms_cpu_no_aabb are BROKEN on non-orthogonal (skewed) cells. They compute the minimum-image convention with per-axis NINT, which is only correct for orthogonal cells. Most MOFs (and all triclinic/monoclinic cells) violate this assumption, so these functions produce systematically wrong distance grids on real materials. They are kept in the codebase for legacy code paths but must not be used in new work. The Rust backend uses the same correct MIC path for every cell type. See the Broken methods section for details.
Per-atom VDW radii (Å). None → Bondi (1964) with Mendeleev fill
Returns:np.ndarray of shape (nx, ny, nz), signed distance to the nearest atom surface.
Strategy: Thread-parallel (Rayon) brute-force — every grid point is checked against every atom using an exact minimum-image convention. Orthogonal cells use a SIMD-optimized SoA path; skewed cells fall back to a 7-image Wassenaar construction. O(N_atoms × N_grid) work, O(N_grid) memory.
Use when: you want the most accurate distance grid and you have enough RAM for one float32 per voxel.
Strategy: Builds a Rust AABB (axis-aligned bounding box) tree on the atoms, then queries n_neighbors nearest atoms for every grid point under PBC. The minimum of dist - radii[nbr] becomes the surface distance. Memory is dominated by the R-tree, not by the grid → much smaller RAM footprint than brute force on large cells.
Use when: cells > 50 Å or atoms > 1000 and the brute-force Rust path runs out of memory. Accuracy depends on n_neighbors: 10 is safe for typical MOFs; reduce to 4–6 if the structure has very large open channels where the nearest atoms may be far apart, and consider whether you need 20+ for tiny-pore systems.
Coarsening factor for the AABB sampling grid (must be > 1)
radii
np.ndarray or None
None
Per-atom VDW radii (Å)
n_neighbors
int
10
AABB neighbor count
Returns:np.ndarray (float32) of shape (nx, ny, nz) matching the finespacing.
Strategy: Computes the AABB distance grid on a coarse grid (spacing × coarse_factor), then trilinearly interpolates back to the fine grid. Reduces compute by coarse_factor³ (default 8×) and also acts as a mild low-pass filter. The grid shape is identical to the brute-force result, so downstream code is unchanged.
Use when: systems so large that even the AABB Rust path is too slow, and you can tolerate a slightly smoother distance field (mild trilinear averaging of nearby values). Good for HT screens where you want a ballpark PSD, less ideal for resolving sub-Å features like pore-limiting windows. Increase coarse_factor to 3 or 4 for very large cells; decrease toward 1 (in practice, use the plain AABB method) when you need sharper windows.
If True, call .compute() and return a NumPy array; if False, return a lazy Dask array
Strategy: Builds a freud AABBQuery on the framework, lays out the grid as a Dask array of block_size chunks, and maps gpd_aabb (a NumPy reduction over the freud neighbor list) over every block. Uses complete_cell().T for the box, so the MIC is correct on skewed cells — this is not one of the broken methods.
Use when: you need Python-level introspection of intermediate values, are running on a machine without the Rust extension, or want lazy Dask composition with other grid ops. Performance is generally 5–20× slower than the Rust path on the same machine.
Decision tree
flowchart TD
A[System: ASE Atoms + spacing] --> B{Atoms × grid voxels<br/>fits in RAM<br/>and runtime OK?}
B -- Yes --> C[rust_exact<br/>dgrid_from_atoms_rust]
B -- No, OOM or too slow --> D{Is mild smoothing<br/>of the dgrid OK?}
D -- Yes --> E[rust_aabb_interp<br/>dgrid_from_atoms_aabb_interp_rust]
D -- No, need exact --> F[rust_aabb<br/>dgrid_from_atoms_aabb_rust]
A --> G[Need Python-level<br/>introspection?]
G -- Yes --> H[cpu / Dask<br/>dgrid_from_atoms_cpu]
G -- No --> C
A -.->|NEVER| X[gpu or cpu_no_aabb<br/>broken on skewed cells]
X -.->|redirect| C
Rule of thumb
System size (atoms × grid voxels)
Recommended method
Why
< 5 × 10⁷ (small-to-medium)
dgrid_from_atoms_rust
Brute-force is fast enough and the most accurate
5 × 10⁷ to 5 × 10⁸ (large)
dgrid_from_atoms_aabb_rust
AABB tree cuts memory; same accuracy as brute force
> 5 × 10⁸ (very large, HT screens)
dgrid_from_atoms_aabb_interp_rust with coarse_factor=2 or 3
8–27× compute savings; smooths fine features
Need Python / Dask composition
dgrid_from_atoms_cpu
Slowest but flexible; uses correct freud MIC
These are rough numbers — the actual crossover depends on cell shape, number of periodic images the AABB has to handle, and how much RAM you have. The auto-AABB policy in the interactive app uses a similar memory budget to switch.
Auto-AABB policy (interactive app)
The Streamlit app (mofography_dash / hosted demo) does not expose the distance-grid method as a user knob by default. Instead it runs a two-step policy:
Estimate the float32 memory cost of the brute-force grid: 4 × nx × ny × nz bytes.
If that estimate exceeds the configured RAM budget (default: ~512 MB), it auto-switches to dgrid_from_atoms_aabb_rust with n_neighbors=10 (or to dgrid_from_atoms_aabb_interp_rust with coarse_factor=2 for very large systems). A short status line in the UI tells you which backend was used.
This means the app “just works” for both IRMOF-1 and a 100-atom × 200-Å supercell, but it also means you should check the UI output before running a 1000-frame batch — silently hitting the AABB path on a system that needs brute-force precision can change window diameters by a few percent. The notebook and CLI surfaces do not auto-switch; you choose the backend explicitly.
Setup
Show code
import mofography as mgrfrom ase.io import readimport numpy as npimport time# Load a MOF structureatoms = read("IRMOF-1.cif") # 424 atoms, ~26 Å cubic cellprint(f"Loaded {len(atoms)} atoms, cell: {atoms.cell.cellpar()[:3].round(2)}")
rust_aabb: shape=(52, 52, 52), min=-1.70, max=7.54, time=36 ms
max |dgrid_exact - dgrid_aabb| = 0.000e+00
Uses a Rust AABB tree to find nearby atoms for each grid point. n_neighbors controls the search radius — higher = more accurate but slower. For typical MOFs, n_neighbors=10 agrees with the exact method to ~1e-3 Å. If you see a few-voxel disagreement near a wall, raise n_neighbors to 16 or 20.
Method 3: dgrid_from_atoms_aabb_interp_rust (very large systems)
rust_aabb+int: shape=(52, 52, 52), min=-1.26, max=7.54, time=8 ms
max |dgrid_exact - dgrid_interp| = 8.061e-01
The coarse grid is at 1.0 Å spacing (spacing × coarse_factor), and the result is trilinearly interpolated back to 0.5 Å. The interpolation step is what introduces the mild smoothing — you can see it as a slight rounding of the surface near tight windows. Do not crank coarse_factor above ~3 if you care about sub-Å window diameters; beyond that the interpolation swamps the true signal.
cpu/dask: shape=(52, 52, 52), min=-1.98, max=7.54, time=1033 ms
max |dgrid_exact - dgrid_cpu| = 2.800e-01
5–20× slower than the Rust path on a single thread, but the Dask graph is composable: pass precompute=False to get a lazy array and chain downstream reductions. This is the right entry point if you need to plug dgrid into an existing Dask pipeline.
Side-by-side timing
Show code
methods = {"rust_exact": mgr.dgrid_from_atoms_rust(atoms, spacing=0.5),"rust_aabb": mgr.dgrid_from_atoms_aabb_rust(atoms, spacing=0.5, n_neighbors=10),"rust_aabb+int": mgr.dgrid_from_atoms_aabb_interp_rust(atoms, spacing=0.5, coarse_factor=2),"cpu/dask": mgr.dgrid_from_atoms_cpu(atoms, spacing=0.5, block_size=50000),}ref = methods["rust_exact"]print(f"{'method':<18}{'shape':<14}{'min':>7}{'max':>7} max|diff|")for name, g in methods.items(): diff =float(np.abs(g - ref).max()) if name !="rust_exact"else0.0print(f"{name:<18}{str(g.shape):<14}{g.min():>7.2f}{g.max():>7.2f}{diff:.3e}")
This is only correct for orthogonal cells (cubic, tetragonal, orthorhombic). On a monoclinic or triclinic cell — which includes most real MOFs — the per-axis NINT picks the wrong image for some atom–grid pairs, and the distance grid develops systematic stripes near the cell walls. The bug is silent: the function returns without warning and the dgrid looks plausible until you compare it to the exact result.
Use the Rust backend (dgrid_from_atoms_rust) instead. Its MIC path uses a 7-image Wassenaar construction on skewed cells, which is correct for all cell types. The CPU/Dask method (dgrid_from_atoms_cpu, without the _no_aabb suffix) is also correct because it routes through freud’s AABB query, which uses the proper box geometry.
If you see dgrid_from_atoms_gpu or dgrid_from_atoms_cpu_no_aabb in legacy code, replace the call with: