molframe-spatial 0.2.1

Deterministic spatial indices and neighbour search for molframe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! Query-language spatial execution over a structure snapshot.

use crate::brute::finite;
use crate::{
    CellList, KdTree, NeighborPair, PeriodicBox, SpatialBackend, SpatialSearchOptions,
    pairs_within_with_options,
};
use molframe_core::ExecutionContext;
use molframe_core::contract::AnalysisPolicy;
use molframe_core::diagnostic::{Code, Diagnostic};
use molframe_core::selection::AtomSelection;
use molframe_core::structure::Structure;
use std::collections::{HashMap, hash_map::Entry};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};

#[path = "resolver_helpers.rs"]
mod helpers;
#[path = "resolver_dispatch.rs"]
mod resolver_dispatch;
#[path = "resolver_visit.rs"]
mod resolver_visit;
use helpers::{
    atom_out_of_bounds, backend_key, cacheable_backend, collect_selection_indices, collect_within,
    index_cutoff_key, mark_pair_match, periodic_box, radial_squared, select_iso_layer,
    spatial_diagnostic, update_nearest_distance, validate_shell, z_matches,
};

/// Maximum number of spatial indices retained by one resolver.
///
/// Query predicates can produce arbitrarily many distinct target selections
/// and cutoffs. Bounding retained indices prevents a long-lived resolver from
/// accumulating unbounded query-controlled cache state.
const MAX_CACHED_INDICES: usize = 64;

/// A spatial resolver bound to one immutable structure snapshot.
#[derive(Debug)]
pub struct StructureSpatial<'a> {
    structure: &'a Structure,
    context: &'a ExecutionContext,
    options: SpatialSearchOptions,
    periodic: Option<PeriodicBox>,
    cache: RwLock<HashMap<IndexKey, Arc<CachedIndex<'a>>>>,
}

/// Identifies a reusable spatial index within one immutable resolver.
///
/// Backend and cutoff precede the potentially large atom selection so equality
/// checks can reject incompatible plans before comparing selection contents.
#[derive(Debug, PartialEq, Eq, Hash)]
struct IndexKey {
    backend: u8,
    cutoff: u32,
    selection: Box<[u32]>,
}

/// A spatial index retained for reuse by compatible geometric predicates.
#[derive(Debug)]
enum CachedIndex<'a> {
    Cell(CellList<'a>),
    Kd(KdTree<'a>),
}

impl<'a> StructureSpatial<'a> {
    /// Creates a resolver under the policy's periodicity decision.
    ///
    /// # Errors
    ///
    /// Returns `E5004` when periodicity is requested without a valid unit cell.
    pub fn new(
        structure: &'a Structure,
        policy: &AnalysisPolicy,
        backend: SpatialBackend,
        context: &'a ExecutionContext,
    ) -> Result<Self, Diagnostic> {
        Self::new_with_options(
            structure,
            policy,
            SpatialSearchOptions::with_backend(backend),
            context,
        )
    }

    /// Creates a resolver under explicit spatial planning options.
    ///
    /// # Errors
    ///
    /// Returns a diagnostic for invalid options or periodic cell data.
    pub fn new_with_options(
        structure: &'a Structure,
        policy: &AnalysisPolicy,
        options: SpatialSearchOptions,
        context: &'a ExecutionContext,
    ) -> Result<Self, Diagnostic> {
        options.validate().map_err(spatial_diagnostic)?;
        let periodic = periodic_box(structure, policy)?;

        Ok(Self {
            structure,
            context,
            options,
            periodic,
            cache: RwLock::new(HashMap::new()),
        })
    }

    /// Number of structure-bound indices currently retained for reuse.
    #[must_use]
    pub fn cached_index_count(&self) -> usize {
        self.read_cache().len()
    }

    /// Returns this structure snapshot's coordinate slice.
    #[inline]
    fn positions(&self) -> &[[f32; 3]] {
        self.structure.positions()
    }

    /// Resolves one atom position or returns the query out-of-bounds diagnostic.
    #[inline]
    fn position(&self, atom: u32) -> Result<[f32; 3], Diagnostic> {
        let index = usize::try_from(atom).map_err(|_| atom_out_of_bounds(atom))?;

        self.positions()
            .get(index)
            .copied()
            .ok_or_else(|| atom_out_of_bounds(atom))
    }

    /// Selects atoms inside a radial shell around `centre`.
    ///
    /// When `z` is provided, radial distance is measured in XY and the
    /// displacement must also lie inside the requested Z interval.
    fn radial(
        &self,
        universe: &AtomSelection,
        centre: [f32; 3],
        inner: f32,
        outer: f32,
        z: Option<(f32, f32)>,
    ) -> Result<AtomSelection, Diagnostic> {
        validate_shell(inner, outer)?;

        let inner_squared = inner * inner;
        let outer_squared = outer * outer;
        let cylindrical = z.is_some();
        let mut selected = Vec::with_capacity(helpers::selection_capacity(universe));

        for atom in universe {
            let position = self.position(atom)?;

            if !finite(position) {
                continue;
            }

            let displacement = self.displacement(centre, position);

            if !z_matches(displacement[2], z) {
                continue;
            }

            let squared = radial_squared(displacement, cylindrical);

            if squared >= inner_squared && squared <= outer_squared {
                selected.push(atom);
            }
        }

        Ok(AtomSelection::from_sorted(selected))
    }

    /// Computes periodic or ordinary displacement from `left` to `right`.
    #[inline]
    fn displacement(&self, left: [f32; 3], right: [f32; 3]) -> [f32; 3] {
        match &self.periodic {
            Some(periodic) => periodic.displacement(left, right),
            None => [right[0] - left[0], right[1] - left[1], right[2] - left[2]],
        }
    }

    /// Computes the arithmetic centre of finite atoms in `target`.
    ///
    /// # Errors
    ///
    /// Returns `E5003` for an empty/no-finite target and `E6009` for invalid
    /// atom indices.
    fn centre(&self, target: &AtomSelection) -> Result<[f32; 3], Diagnostic> {
        if target.is_empty() {
            return Err(Diagnostic::new(Code::E5003));
        }

        let mut sum = [0.0f64; 3];
        let mut count = 0u32;

        for atom in target {
            let position = self.position(atom)?;

            if !finite(position) {
                continue;
            }

            sum[0] += f64::from(position[0]);
            sum[1] += f64::from(position[1]);
            sum[2] += f64::from(position[2]);

            count = count
                .checked_add(1)
                .ok_or_else(|| Diagnostic::new(Code::E3001))?;
        }

        if count == 0 {
            return Err(Diagnostic::new(Code::E5003));
        }

        let divisor = f64::from(count);

        let convert = |value: f64| {
            crate::numeric::finite_f32(value / divisor).ok_or_else(|| Diagnostic::new(Code::E5003))
        };

        Ok([convert(sum[0])?, convert(sum[1])?, convert(sum[2])?])
    }

    /// Resolves a shell around the centre of `target`.
    ///
    /// This helper centralises sphere/cylinder centre calculation.
    fn radial_from_target(
        &self,
        universe: &AtomSelection,
        target: &AtomSelection,
        inner: f32,
        outer: f32,
        z: Option<(f32, f32)>,
    ) -> Result<AtomSelection, Diagnostic> {
        let centre = self.centre(target)?;
        self.radial(universe, centre, inner, outer, z)
    }

    /// Selects atoms whose nearest target distance lies inside `[inner, outer]`.
    ///
    /// A dense nearest-distance buffer keeps pair updates contiguous and avoids
    /// map lookups for atom-indexed nearest-distance state.
    fn iso_layer(
        &self,
        universe: &AtomSelection,
        target: &AtomSelection,
        inner: f32,
        outer: f32,
    ) -> Result<AtomSelection, Diagnostic> {
        validate_shell(inner, outer)?;

        let mut nearest = vec![f32::INFINITY; self.positions().len()];
        let mut reduction_error = None;
        self.for_each_pair(universe, target, outer, |pair| {
            if reduction_error.is_none()
                && let Err(error) = update_nearest_distance(&mut nearest, universe, target, pair)
            {
                reduction_error = Some(error);
            }
        })?;
        if let Some(error) = reduction_error {
            return Err(error);
        }

        select_iso_layer(universe, target, &nearest, inner * inner, outer * outer)
    }

    /// Selects query atoms within `cutoff` of at least one target.
    ///
    /// A dense bit vector records membership directly by atom index and avoids
    /// sorting or deduplicating matched pair endpoints.
    fn within(
        &self,
        query: &AtomSelection,
        target: &AtomSelection,
        cutoff: f32,
    ) -> Result<AtomSelection, Diagnostic> {
        let mut matched = vec![false; self.positions().len()];
        let mut reduction_error = None;
        self.for_each_pair(query, target, cutoff, |pair| {
            if reduction_error.is_none()
                && let Err(error) = mark_pair_match(&mut matched, query, target, pair)
            {
                reduction_error = Some(error);
            }
        })?;
        if let Some(error) = reduction_error {
            return Err(error);
        }

        collect_within(query, target, &matched)
    }

    /// Searches one pair workload while retaining indices in this resolver.
    ///
    /// The resolver itself is configured with `Auto` in a reusable plan.  A
    /// request may still pin a concrete backend; the target index is keyed by
    /// that backend, cutoff and selection, so compatible operations share the
    /// construction without changing the requested algorithm.
    ///
    /// # Errors
    ///
    /// Returns a diagnostic when the requested backend cannot be planned or
    /// the spatial kernel rejects the workload.
    pub fn pairs_with_backend(
        &self,
        query: &AtomSelection,
        target: &AtomSelection,
        cutoff: f32,
        requested_backend: SpatialBackend,
    ) -> Result<Vec<NeighborPair>, Diagnostic> {
        let requested = SpatialSearchOptions {
            backend: requested_backend,
            ..self.options
        };
        let backend =
            cacheable_backend(requested, query.len(), target.len()).map_err(spatial_diagnostic)?;

        match backend {
            SpatialBackend::CellList | SpatialBackend::KdTree => {
                self.cached_pairs(query, target, cutoff, backend)
            }
            _ => {
                let options = SpatialSearchOptions {
                    backend,
                    ..self.options
                };

                pairs_within_with_options(
                    self.positions(),
                    query,
                    target,
                    cutoff,
                    options,
                    self.periodic.as_ref(),
                    self.context,
                )
                .map_err(spatial_diagnostic)
            }
        }
    }

    /// Executes a query using a reusable `CellList` or `KdTree`.
    ///
    /// Atom selections are materialised only where the index APIs require
    /// contiguous integer slices.
    fn cached_pairs(
        &self,
        query: &AtomSelection,
        target: &AtomSelection,
        cutoff: f32,
        backend: SpatialBackend,
    ) -> Result<Vec<NeighborPair>, Diagnostic> {
        let target_indices = collect_selection_indices(target);

        let key = IndexKey {
            backend: backend_key(backend),
            cutoff: index_cutoff_key(backend, cutoff),
            selection: target_indices.into_boxed_slice(),
        };

        let index = self.cached_index(key, backend, cutoff)?;
        let query_indices = collect_selection_indices(query);

        match index.as_ref() {
            CachedIndex::Cell(index) => index
                .pairs(&query_indices, cutoff)
                .map_err(spatial_diagnostic),
            CachedIndex::Kd(index) => index
                .pairs(&query_indices, cutoff)
                .map_err(spatial_diagnostic),
        }
    }

    /// Returns or constructs one structure-bound spatial index.
    ///
    /// Index construction occurs without holding the cache lock. A second
    /// lookup after construction resolves concurrent insertions of the same key
    /// without replacing an index already retained by another thread.
    fn cached_index(
        &self,
        key: IndexKey,
        backend: SpatialBackend,
        cutoff: f32,
    ) -> Result<Arc<CachedIndex<'a>>, Diagnostic> {
        {
            let cache = self.read_cache();

            if let Some(index) = cache.get(&key) {
                return Ok(Arc::clone(index));
            }
        }

        let built = Arc::new(self.build_cached_index(backend, key.selection.as_ref(), cutoff)?);

        let mut cache = self.write_cache();
        let can_retain = cache.len() < MAX_CACHED_INDICES;

        match cache.entry(key) {
            Entry::Occupied(entry) => Ok(Arc::clone(entry.get())),
            Entry::Vacant(entry) if can_retain => {
                entry.insert(Arc::clone(&built));
                Ok(built)
            }
            Entry::Vacant(_) => Ok(built),
        }
    }

    /// Constructs one cacheable index over `targets`.
    ///
    /// K-d trees are independent from the query cutoff, while cell lists retain
    /// the cutoff used to define their spatial grid.
    fn build_cached_index(
        &self,
        backend: SpatialBackend,
        targets: &[u32],
        cutoff: f32,
    ) -> Result<CachedIndex<'a>, Diagnostic> {
        let positions: &'a [[f32; 3]] = self.structure.positions();

        match backend {
            SpatialBackend::CellList => CellList::build_with_options(
                positions,
                targets,
                cutoff,
                self.periodic,
                self.options.cell_grid,
            )
            .map(CachedIndex::Cell)
            .map_err(spatial_diagnostic),
            SpatialBackend::KdTree => KdTree::build_with_options(
                positions,
                targets,
                self.periodic,
                self.options.kd_periodic,
            )
            .map(CachedIndex::Kd)
            .map_err(spatial_diagnostic),
            _ => Err(Diagnostic::new(Code::E9001)),
        }
    }

    /// Acquires shared access to the spatial-index cache.
    ///
    /// Poisoned locks are recovered because an interrupted cache operation
    /// cannot invalidate the immutable structure snapshot itself.
    fn read_cache(&self) -> RwLockReadGuard<'_, HashMap<IndexKey, Arc<CachedIndex<'a>>>> {
        match self.cache.read() {
            Ok(cache) => cache,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    /// Acquires exclusive access to mutate the spatial-index cache.
    ///
    /// Poisoned locks are recovered so cache availability is not coupled to a
    /// prior thread panic.
    fn write_cache(&self) -> RwLockWriteGuard<'_, HashMap<IndexKey, Arc<CachedIndex<'a>>>> {
        match self.cache.write() {
            Ok(cache) => cache,
            Err(poisoned) => poisoned.into_inner(),
        }
    }
}

#[cfg(test)]
#[path = "resolver_tests.rs"]
mod tests;