Skip to main content

readcon_core/
correspondence.rs

1//! Pair atoms across frames by column-5 `atom_id`.
2//!
3//! CON stores atoms in type-grouped order. The id is the index from before
4//! that grouping, so a reactant and a product that a writer grouped
5//! differently still name the same atom. These helpers are the map, the
6//! reorder, the band check, and the minimum-image displacement of the
7//! matched pairs.
8//!
9//! The cell is [`FrameHeader::cell_matrix`] and [`FrameHeader::pbc_effective`].
10//! Lengths and angles are not rebuilt. Every periodic axis is wrapped in
11//! the span of those lattice vectors. An open axis is left out of that
12//! span, so a flat slab is not inverted through its short `c` vector.
13//!
14//! ```
15//! use readcon_core::types::ConFrameBuilder;
16//! use readcon_core::{
17//!     IdentityCheck, atom_id_permutation, check_atom_id_consistency,
18//!     minimum_image_displacements, reorder_like,
19//! };
20//!
21//! fn frame(rows: &[(u64, &str, f64)]) -> readcon_core::types::ConFrame {
22//!     let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
23//!     for (id, symbol, x) in rows {
24//!         builder.add_atom(symbol, *x, 0.0, 0.0, [false; 3], *id, 12.0);
25//!     }
26//!     builder.build().unwrap()
27//! }
28//!
29//! let reactant = frame(&[(1, "C", 0.0), (2, "O", 1.0)]);
30//! let product = frame(&[(2, "O", 1.2), (1, "C", 0.1)]);
31//! let perm = atom_id_permutation(&reactant, &product, IdentityCheck::Strict).unwrap();
32//! assert_eq!(perm, vec![1, 0]);
33//! let ordered = reorder_like(&reactant, &product, IdentityCheck::Strict).unwrap();
34//! assert_eq!(ordered.atom_data[0].atom_id, 1);
35//! assert_eq!(ordered.atom_data[1].atom_id, 2);
36//! check_atom_id_consistency(&[reactant.clone(), product.clone()], IdentityCheck::Strict)
37//!     .unwrap();
38//! let disp = minimum_image_displacements(&reactant, &product, IdentityCheck::Strict).unwrap();
39//! assert_eq!(disp.len(), 2);
40//! assert!((disp[0][0] - 0.1).abs() < 1e-12);
41//! ```
42
43use crate::storage_dtype::{FloatArray1, FloatArray2};
44use crate::types::{Bond, ConFrame, ConFrameBuilder};
45use rustc_hash::FxHashMap;
46
47/// How strictly two atoms that share an `atom_id` must agree.
48///
49/// Symbol mismatches, duplicate ids, and missing or extra ids fail in both
50/// modes. [`IdentityCheck::Strict`] also requires the mass and the fixed
51/// mask to agree. Masses within [`ConFrameBuilder::TYPE_MASS_ABS_TOL`] agree.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
53pub enum IdentityCheck {
54    /// Symbol, mass, and fixed mask agree.
55    #[default]
56    Strict,
57    /// Symbol agrees. Mass and fixed mask may differ.
58    Lenient,
59}
60
61/// Why two frames (or a later frame in a sequence) do not correspond.
62#[derive(Debug, Clone, PartialEq)]
63pub enum CorrespondenceError {
64    /// `check_atom_id_consistency` was given no frames.
65    EmptySequence,
66    /// The same id occurs twice in one frame.
67    Duplicate {
68        frame_index: usize,
69        atom_id: u64,
70        /// Index of the second occurrence.
71        atom_index: usize,
72        first_index: usize,
73    },
74    /// `atom_id` is in the reference frame and absent from this frame.
75    Missing {
76        frame_index: usize,
77        atom_id: u64,
78        /// Index of the atom in the reference frame.
79        reference_index: usize,
80    },
81    /// `atom_id` is in this frame and absent from the reference frame.
82    Extra {
83        frame_index: usize,
84        atom_id: u64,
85        atom_index: usize,
86    },
87    Symbol {
88        frame_index: usize,
89        atom_id: u64,
90        atom_index: usize,
91        reference_symbol: String,
92        found_symbol: String,
93    },
94    Mass {
95        frame_index: usize,
96        atom_id: u64,
97        atom_index: usize,
98        reference_mass: f64,
99        found_mass: f64,
100    },
101    Fixed {
102        frame_index: usize,
103        atom_id: u64,
104        atom_index: usize,
105        reference_fixed: [bool; 3],
106        found_fixed: [bool; 3],
107    },
108    /// Reference cell matrix cannot be inverted.
109    SingularCell {
110        determinant: f64,
111    },
112    NonFiniteDelta,
113    NonFiniteCoordinate {
114        frame_index: usize,
115        atom_id: u64,
116        atom_index: usize,
117    },
118    SectionLength {
119        section: &'static str,
120        rows: usize,
121        atoms: usize,
122    },
123    BondEndpoint {
124        index: u32,
125        atoms: usize,
126    },
127    /// A selected atom index is outside the frame.
128    AtomIndex {
129        index: usize,
130        atoms: usize,
131    },
132    /// The same atom index was selected twice.
133    RepeatedIndex {
134        index: usize,
135        /// Position in the selection of the first occurrence.
136        first_position: usize,
137        /// Position in the selection of the second occurrence.
138        position: usize,
139    },
140}
141
142impl CorrespondenceError {
143    /// Frame that failed. `None` when the failure is not a frame.
144    pub fn frame_index(&self) -> Option<usize> {
145        match self {
146            Self::EmptySequence | Self::SingularCell { .. } | Self::NonFiniteDelta => None,
147            Self::Duplicate { frame_index, .. }
148            | Self::Missing { frame_index, .. }
149            | Self::Extra { frame_index, .. }
150            | Self::Symbol { frame_index, .. }
151            | Self::Mass { frame_index, .. }
152            | Self::Fixed { frame_index, .. }
153            | Self::NonFiniteCoordinate { frame_index, .. } => Some(*frame_index),
154            Self::SectionLength { .. }
155            | Self::BondEndpoint { .. }
156            | Self::AtomIndex { .. }
157            | Self::RepeatedIndex { .. } => None,
158        }
159    }
160
161    /// Atom id involved, when the failure names one atom.
162    pub fn atom_id(&self) -> Option<u64> {
163        match self {
164            Self::Duplicate { atom_id, .. }
165            | Self::Missing { atom_id, .. }
166            | Self::Extra { atom_id, .. }
167            | Self::Symbol { atom_id, .. }
168            | Self::Mass { atom_id, .. }
169            | Self::Fixed { atom_id, .. }
170            | Self::NonFiniteCoordinate { atom_id, .. } => Some(*atom_id),
171            _ => None,
172        }
173    }
174
175    /// Storage index of that atom.
176    ///
177    /// For [`CorrespondenceError::Missing`] this is the index in the
178    /// reference frame. Otherwise it is the index in [`Self::frame_index`].
179    pub fn atom_index(&self) -> Option<usize> {
180        match self {
181            Self::Duplicate { atom_index, .. }
182            | Self::Extra { atom_index, .. }
183            | Self::Symbol { atom_index, .. }
184            | Self::Mass { atom_index, .. }
185            | Self::Fixed { atom_index, .. }
186            | Self::NonFiniteCoordinate { atom_index, .. } => Some(*atom_index),
187            Self::Missing {
188                reference_index, ..
189            } => Some(*reference_index),
190            _ => None,
191        }
192    }
193}
194
195impl std::fmt::Display for CorrespondenceError {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        match self {
198            Self::EmptySequence => {
199                write!(f, "atom-id consistency check needs at least one frame")
200            }
201            Self::Duplicate {
202                frame_index,
203                atom_id,
204                atom_index,
205                first_index,
206            } => write!(
207                f,
208                "duplicate atom_id {atom_id} in frame {frame_index} at index {atom_index} (first index {first_index})"
209            ),
210            Self::Missing {
211                frame_index,
212                atom_id,
213                reference_index,
214            } => write!(
215                f,
216                "frame {frame_index} is missing atom_id {atom_id} (reference index {reference_index})"
217            ),
218            Self::Extra {
219                frame_index,
220                atom_id,
221                atom_index,
222            } => write!(
223                f,
224                "frame {frame_index} atom_id {atom_id} at index {atom_index} is not in the reference frame"
225            ),
226            Self::Symbol {
227                frame_index,
228                atom_id,
229                atom_index,
230                reference_symbol,
231                found_symbol,
232            } => write!(
233                f,
234                "frame {frame_index} atom_id {atom_id} at index {atom_index} has symbol {found_symbol}; reference symbol is {reference_symbol}"
235            ),
236            Self::Mass {
237                frame_index,
238                atom_id,
239                atom_index,
240                reference_mass,
241                found_mass,
242            } => write!(
243                f,
244                "frame {frame_index} atom_id {atom_id} at index {atom_index} has mass {found_mass}; reference mass is {reference_mass} (tolerance {})",
245                ConFrameBuilder::TYPE_MASS_ABS_TOL
246            ),
247            Self::Fixed {
248                frame_index,
249                atom_id,
250                atom_index,
251                reference_fixed,
252                found_fixed,
253            } => write!(
254                f,
255                "frame {frame_index} atom_id {atom_id} at index {atom_index} has fixed mask {found_fixed:?}; reference fixed mask is {reference_fixed:?}"
256            ),
257            Self::SingularCell { determinant } => write!(
258                f,
259                "minimum-image displacement: the periodic cell is singular (cell-matrix or Gram determinant {determinant})"
260            ),
261            Self::NonFiniteDelta => {
262                write!(
263                    f,
264                    "minimum-image displacement: cartesian delta is non-finite"
265                )
266            }
267            Self::NonFiniteCoordinate {
268                frame_index,
269                atom_id,
270                atom_index,
271            } => write!(
272                f,
273                "frame {frame_index} atom_id {atom_id} at index {atom_index} has a non-finite coordinate"
274            ),
275            Self::SectionLength {
276                section,
277                rows,
278                atoms,
279            } => write!(f, "{section} has {rows} rows for {atoms} atoms"),
280            Self::BondEndpoint { index, atoms } => {
281                write!(
282                    f,
283                    "bond endpoint {index} is outside the atom list ({atoms} atoms)"
284                )
285            }
286            Self::AtomIndex { index, atoms } => {
287                write!(f, "atom index {index} is outside the frame ({atoms} atoms)")
288            }
289            Self::RepeatedIndex {
290                index,
291                first_position,
292                position,
293            } => write!(
294                f,
295                "atom index {index} is selected twice (positions {first_position} and {position})"
296            ),
297        }
298    }
299}
300
301impl std::error::Error for CorrespondenceError {}
302
303/// `perm[i]` is the index in `other` of the atom whose `atom_id` equals
304/// `reference.atom_data[i].atom_id`.
305///
306/// Frame index 0 in an error is `reference`. Frame index 1 is `other`.
307pub fn atom_id_permutation(
308    reference: &ConFrame,
309    other: &ConFrame,
310    check: IdentityCheck,
311) -> Result<Vec<usize>, CorrespondenceError> {
312    atom_id_permutation_at(reference, other, 1, check)
313}
314
315fn atom_id_permutation_at(
316    reference: &ConFrame,
317    other: &ConFrame,
318    other_index: usize,
319    check: IdentityCheck,
320) -> Result<Vec<usize>, CorrespondenceError> {
321    index_ids(&reference.atom_data, 0)?;
322    let other_index_map = index_ids(&other.atom_data, other_index)?;
323    let ref_mass = masses_of(reference)?;
324    let other_mass = masses_of(other)?;
325    let mut perm = Vec::with_capacity(reference.atom_data.len());
326    for (ri, atom) in reference.atom_data.iter().enumerate() {
327        let Some(&bi) = other_index_map.get(&atom.atom_id) else {
328            return Err(CorrespondenceError::Missing {
329                frame_index: other_index,
330                atom_id: atom.atom_id,
331                reference_index: ri,
332            });
333        };
334        let found = &other.atom_data[bi];
335        if found.symbol != atom.symbol {
336            return Err(CorrespondenceError::Symbol {
337                frame_index: other_index,
338                atom_id: atom.atom_id,
339                atom_index: bi,
340                reference_symbol: atom.symbol.to_string(),
341                found_symbol: found.symbol.to_string(),
342            });
343        }
344        if check == IdentityCheck::Strict {
345            let reference_mass = ref_mass[ri];
346            let found_mass = other_mass[bi];
347            if !reference_mass.is_finite()
348                || !found_mass.is_finite()
349                || (reference_mass - found_mass).abs() > ConFrameBuilder::TYPE_MASS_ABS_TOL
350            {
351                return Err(CorrespondenceError::Mass {
352                    frame_index: other_index,
353                    atom_id: atom.atom_id,
354                    atom_index: bi,
355                    reference_mass,
356                    found_mass,
357                });
358            }
359            if found.fixed() != atom.fixed() {
360                return Err(CorrespondenceError::Fixed {
361                    frame_index: other_index,
362                    atom_id: atom.atom_id,
363                    atom_index: bi,
364                    reference_fixed: atom.fixed(),
365                    found_fixed: found.fixed(),
366                });
367            }
368        }
369        perm.push(bi);
370    }
371    if other.atom_data.len() != reference.atom_data.len() {
372        let mut seen = vec![false; other.atom_data.len()];
373        for &bi in &perm {
374            seen[bi] = true;
375        }
376        for (i, atom) in other.atom_data.iter().enumerate() {
377            if !seen[i] {
378                return Err(CorrespondenceError::Extra {
379                    frame_index: other_index,
380                    atom_id: atom.atom_id,
381                    atom_index: i,
382                });
383            }
384        }
385    }
386    Ok(perm)
387}
388
389fn index_ids(
390    atoms: &[crate::types::AtomDatum],
391    frame_index: usize,
392) -> Result<FxHashMap<u64, usize>, CorrespondenceError> {
393    let mut map = FxHashMap::with_capacity_and_hasher(atoms.len(), Default::default());
394    for (i, atom) in atoms.iter().enumerate() {
395        if let Some(first) = map.insert(atom.atom_id, i) {
396            return Err(CorrespondenceError::Duplicate {
397                frame_index,
398                atom_id: atom.atom_id,
399                atom_index: i,
400                first_index: first,
401            });
402        }
403    }
404    Ok(map)
405}
406
407fn masses_of(frame: &ConFrame) -> Result<Vec<f64>, CorrespondenceError> {
408    let n = frame.atom_data.len();
409    if frame.masses.len() != n {
410        return Err(CorrespondenceError::SectionLength {
411            section: "masses",
412            rows: frame.masses.len(),
413            atoms: n,
414        });
415    }
416    Ok((0..n).map(|i| frame.masses.get_f64(i)).collect())
417}
418
419/// `other` with atoms stored in `reference` order.
420///
421/// Positions, velocities, forces, and the other per-atom sections move
422/// with the atom. Bond endpoints, which are `atom_data` indices, are
423/// remapped. The cell, the metadata, and the per-frame scalars stay
424/// those of `other`. Type counts are rebuilt from the new order so the
425/// frame still writes as CON when that order is type-grouped.
426pub fn reorder_like(
427    reference: &ConFrame,
428    other: &ConFrame,
429    check: IdentityCheck,
430) -> Result<ConFrame, CorrespondenceError> {
431    let perm = atom_id_permutation(reference, other, check)?;
432    apply_permutation(other, &perm)
433}
434
435fn apply_permutation(frame: &ConFrame, perm: &[usize]) -> Result<ConFrame, CorrespondenceError> {
436    let n = perm.len();
437    let mut atoms = Vec::with_capacity(n);
438    for &j in perm {
439        let mut atom = frame.atom_data[j].clone();
440        overlay_sections(&mut atom, frame, j)?;
441        atoms.push(atom);
442    }
443    let velocities = permute_rows(&frame.velocities, perm, "velocities")?;
444    let forces = permute_rows(&frame.forces, perm, "forces")?;
445    let mut out = frame.clone();
446    // The clone's atoms address its velocity and force columns. Both are
447    // replaced here, and the atoms in `perm` order then address the rows
448    // of the permuted columns.
449    let bound = out.materialise_section_slots();
450    out.atom_data = atoms;
451    out.positions = permute_rows(&frame.positions, perm, "positions")?;
452    out.velocities = velocities.into();
453    out.forces = forces.into();
454    out.magmoms = permute_rows(&frame.magmoms, perm, "magmoms")?.into();
455    out.displacements = permute_rows(&frame.displacements, perm, "displacements")?.into();
456    out.spreads = permute_rows(&frame.spreads, perm, "spreads")?.into();
457    out.atom_energies = permute_col(&frame.atom_energies, perm, "energies")?.into();
458    out.charges = permute_col(&frame.charges, perm, "charges")?.into();
459    out.spins = permute_col(&frame.spins, perm, "spins")?.into();
460    out.masses = permute_col(&frame.masses, perm, "masses")?;
461    let ids: Vec<u64> = perm.iter().map(|&j| frame.atom_data[j].atom_id).collect();
462    out.atom_ids = ndarray::Array1::from_vec(ids).into_shared();
463    refresh_type_runs(&mut out);
464    remap_bonds(&mut out, perm)?;
465    if !bound.is_empty() {
466        let bound: Vec<bool> = perm.iter().map(|&j| bound[j]).collect();
467        out.bind_section_slots(&bound);
468    }
469    Ok(out)
470}
471
472fn position_of(frame: &ConFrame, i: usize) -> Result<[f64; 3], CorrespondenceError> {
473    let n = frame.atom_data.len();
474    if frame.positions.nrows() == n {
475        return Ok(frame.positions.as_f64_row(i));
476    }
477    Err(CorrespondenceError::SectionLength {
478        section: "positions",
479        rows: frame.positions.nrows(),
480        atoms: n,
481    })
482}
483
484fn overlay_sections(
485    atom: &mut crate::types::AtomDatum,
486    frame: &ConFrame,
487    j: usize,
488) -> Result<(), CorrespondenceError> {
489    let n = frame.atom_data.len();
490    if frame.velocities.nrows() == n {
491        atom.set_velocity(Some(frame.velocities.as_f64_row(j)));
492    } else if frame.velocities.nrows() != 0 {
493        return Err(CorrespondenceError::SectionLength {
494            section: "velocities",
495            rows: frame.velocities.nrows(),
496            atoms: n,
497        });
498    }
499    if frame.forces.nrows() == n {
500        atom.set_force(Some(frame.forces.as_f64_row(j)));
501    } else if frame.forces.nrows() != 0 {
502        return Err(CorrespondenceError::SectionLength {
503            section: "forces",
504            rows: frame.forces.nrows(),
505            atoms: n,
506        });
507    }
508    if frame.atom_energies.len() == n {
509        atom.set_energy(Some(frame.atom_energies.get_f64(j)));
510    } else if !frame.atom_energies.is_empty() {
511        return Err(CorrespondenceError::SectionLength {
512            section: "energies",
513            rows: frame.atom_energies.len(),
514            atoms: n,
515        });
516    }
517    if frame.charges.len() == n {
518        atom.set_charge(Some(frame.charges.get_f64(j)));
519    } else if !frame.charges.is_empty() {
520        return Err(CorrespondenceError::SectionLength {
521            section: "charges",
522            rows: frame.charges.len(),
523            atoms: n,
524        });
525    }
526    if frame.spins.len() == n {
527        atom.set_spin(Some(frame.spins.get_f64(j)));
528    } else if !frame.spins.is_empty() {
529        return Err(CorrespondenceError::SectionLength {
530            section: "spins",
531            rows: frame.spins.len(),
532            atoms: n,
533        });
534    }
535    if frame.magmoms.nrows() == n {
536        atom.set_magmom(Some(frame.magmoms.as_f64_row(j)));
537    } else if frame.magmoms.nrows() != 0 {
538        return Err(CorrespondenceError::SectionLength {
539            section: "magmoms",
540            rows: frame.magmoms.nrows(),
541            atoms: n,
542        });
543    }
544    if frame.displacements.nrows() == n {
545        atom.set_displacement(Some(frame.displacements.as_f64_row(j)));
546    } else if frame.displacements.nrows() != 0 {
547        return Err(CorrespondenceError::SectionLength {
548            section: "displacements",
549            rows: frame.displacements.nrows(),
550            atoms: n,
551        });
552    }
553    if frame.spreads.nrows() == n {
554        atom.set_spread(Some(frame.spreads.as_f64_row(j)));
555    } else if frame.spreads.nrows() != 0 {
556        return Err(CorrespondenceError::SectionLength {
557            section: "spreads",
558            rows: frame.spreads.nrows(),
559            atoms: n,
560        });
561    }
562    Ok(())
563}
564
565fn permute_rows(
566    src: &FloatArray2,
567    perm: &[usize],
568    section: &'static str,
569) -> Result<FloatArray2, CorrespondenceError> {
570    let n = perm.len();
571    if src.nrows() == 0 {
572        return Ok(FloatArray2::zeros(src.kind(), 0, 3));
573    }
574    if src.nrows() != n {
575        return Err(CorrespondenceError::SectionLength {
576            section,
577            rows: src.nrows(),
578            atoms: n,
579        });
580    }
581    let mut out = FloatArray2::zeros(src.kind(), n, src.ncols().max(3));
582    for (i, &j) in perm.iter().enumerate() {
583        out.set_f64_row(i, src.as_f64_row(j));
584    }
585    Ok(out)
586}
587
588fn permute_col(
589    src: &FloatArray1,
590    perm: &[usize],
591    section: &'static str,
592) -> Result<FloatArray1, CorrespondenceError> {
593    let n = perm.len();
594    if src.is_empty() {
595        return Ok(FloatArray1::zeros(src.kind(), 0));
596    }
597    if src.len() != n {
598        return Err(CorrespondenceError::SectionLength {
599            section,
600            rows: src.len(),
601            atoms: n,
602        });
603    }
604    let mut out = FloatArray1::zeros(src.kind(), n);
605    for (i, &j) in perm.iter().enumerate() {
606        out.set_f64(i, src.get_f64(j));
607    }
608    Ok(out)
609}
610
611fn refresh_type_runs(frame: &mut ConFrame) {
612    let n = frame.atom_data.len();
613    if n == 0 {
614        frame.header.natm_types = 0;
615        frame.header.natms_per_type.clear();
616        frame.header.masses_per_type.clear();
617        return;
618    }
619    let mut counts = Vec::new();
620    let mut masses = Vec::new();
621    let mut run_symbol = frame.atom_data[0].symbol.clone();
622    let mut run_count = 0usize;
623    let mut run_mass = frame.masses.get_f64(0);
624    for i in 0..n {
625        if frame.atom_data[i].symbol != run_symbol {
626            counts.push(run_count);
627            masses.push(run_mass);
628            run_symbol = frame.atom_data[i].symbol.clone();
629            run_count = 0;
630            run_mass = frame.masses.get_f64(i);
631        }
632        run_count += 1;
633    }
634    counts.push(run_count);
635    masses.push(run_mass);
636    frame.header.natm_types = counts.len();
637    frame.header.natms_per_type = counts;
638    frame.header.masses_per_type = masses;
639}
640
641fn remap_bonds(frame: &mut ConFrame, perm: &[usize]) -> Result<(), CorrespondenceError> {
642    let bonds = frame.bonds();
643    if bonds.is_empty() {
644        return Ok(());
645    }
646    let n = perm.len();
647    let mut inverse = vec![0usize; n];
648    for (i, &j) in perm.iter().enumerate() {
649        inverse[j] = i;
650    }
651    let mut mapped = Vec::with_capacity(bonds.len());
652    for bond in bonds {
653        if bond.i as usize >= n {
654            return Err(CorrespondenceError::BondEndpoint {
655                index: bond.i,
656                atoms: n,
657            });
658        }
659        if bond.j as usize >= n {
660            return Err(CorrespondenceError::BondEndpoint {
661                index: bond.j,
662                atoms: n,
663            });
664        }
665        mapped.push(Bond {
666            i: inverse[bond.i as usize] as u32,
667            j: inverse[bond.j as usize] as u32,
668            order: bond.order,
669        });
670    }
671    frame.header.set_bonds(&mapped);
672    Ok(())
673}
674
675/// The atoms of `frame` at `indices`, in that order, as a frame of their own.
676///
677/// `indices` are `atom_data` indices. Each selected atom keeps its
678/// position, symbol, mass, fixed flags and `atom_id`, and its row of every
679/// per-atom section the frame carries: velocities, forces, energies,
680/// charges, spins, magnetic moments, displacements and spreads. The cell,
681/// the header lines, the metadata and the per-frame scalars are those of
682/// `frame`. A bond is kept, with its endpoints renumbered, when both of
683/// its atoms are selected, and dropped otherwise. Type counts are rebuilt
684/// from the new order, so the result writes as CON when that order is
685/// type-grouped.
686///
687/// The ids are what ties the sub-frame back to its source: an atom of the
688/// result is the atom of `frame` with the same `atom_id`.
689///
690/// # Errors
691///
692/// [`CorrespondenceError::AtomIndex`] for an index outside the frame,
693/// [`CorrespondenceError::RepeatedIndex`] for an index given twice, and
694/// [`CorrespondenceError::SectionLength`] for a per-atom section whose
695/// length is neither zero nor the atom count.
696pub fn subframe(frame: &ConFrame, indices: &[usize]) -> Result<ConFrame, CorrespondenceError> {
697    let n = frame.atom_data.len();
698    let mut position_of_index: std::collections::HashMap<usize, usize> =
699        std::collections::HashMap::with_capacity(indices.len());
700    for (position, &index) in indices.iter().enumerate() {
701        if index >= n {
702            return Err(CorrespondenceError::AtomIndex { index, atoms: n });
703        }
704        if let Some(&first_position) = position_of_index.get(&index) {
705            return Err(CorrespondenceError::RepeatedIndex {
706                index,
707                first_position,
708                position,
709            });
710        }
711        position_of_index.insert(index, position);
712    }
713    let mut out = frame.clone();
714    let mut atoms = Vec::with_capacity(indices.len());
715    for &j in indices {
716        let mut atom = frame.atom_data[j].clone();
717        overlay_sections(&mut atom, frame, j)?;
718        atoms.push(atom);
719    }
720    out.atom_data = atoms;
721    out.positions = select_rows(&frame.positions, indices, n, "positions")?;
722    out.velocities = select_rows(&frame.velocities, indices, n, "velocities")?.into();
723    out.forces = select_rows(&frame.forces, indices, n, "forces")?.into();
724    out.magmoms = select_rows(&frame.magmoms, indices, n, "magmoms")?.into();
725    out.displacements = select_rows(&frame.displacements, indices, n, "displacements")?.into();
726    out.spreads = select_rows(&frame.spreads, indices, n, "spreads")?.into();
727    out.atom_energies = select_col(&frame.atom_energies, indices, n, "energies")?.into();
728    out.charges = select_col(&frame.charges, indices, n, "charges")?.into();
729    out.spins = select_col(&frame.spins, indices, n, "spins")?.into();
730    out.masses = select_col(&frame.masses, indices, n, "masses")?;
731    let ids: Vec<u64> = indices
732        .iter()
733        .map(|&j| frame.atom_data[j].atom_id)
734        .collect();
735    out.atom_ids = ndarray::Array1::from_vec(ids).into_shared();
736    refresh_type_runs(&mut out);
737    let kept: Vec<Bond> = frame
738        .bonds()
739        .into_iter()
740        .filter_map(|bond| {
741            let i = position_of_index.get(&(bond.i as usize))?;
742            let j = position_of_index.get(&(bond.j as usize))?;
743            Some(Bond {
744                i: *i as u32,
745                j: *j as u32,
746                order: bond.order,
747            })
748        })
749        .collect();
750    if !frame.bonds().is_empty() {
751        out.header.set_bonds(&kept);
752    }
753    Ok(out)
754}
755
756fn select_rows(
757    src: &FloatArray2,
758    indices: &[usize],
759    atoms: usize,
760    section: &'static str,
761) -> Result<FloatArray2, CorrespondenceError> {
762    if src.nrows() == 0 {
763        return Ok(FloatArray2::zeros(src.kind(), 0, 3));
764    }
765    if src.nrows() != atoms {
766        return Err(CorrespondenceError::SectionLength {
767            section,
768            rows: src.nrows(),
769            atoms,
770        });
771    }
772    let mut out = FloatArray2::zeros(src.kind(), indices.len(), src.ncols().max(3));
773    for (i, &j) in indices.iter().enumerate() {
774        out.set_f64_row(i, src.as_f64_row(j));
775    }
776    Ok(out)
777}
778
779fn select_col(
780    src: &FloatArray1,
781    indices: &[usize],
782    atoms: usize,
783    section: &'static str,
784) -> Result<FloatArray1, CorrespondenceError> {
785    if src.is_empty() {
786        return Ok(FloatArray1::zeros(src.kind(), 0));
787    }
788    if src.len() != atoms {
789        return Err(CorrespondenceError::SectionLength {
790            section,
791            rows: src.len(),
792            atoms,
793        });
794    }
795    let mut out = FloatArray1::zeros(src.kind(), indices.len());
796    for (i, &j) in indices.iter().enumerate() {
797        out.set_f64(i, src.get_f64(j));
798    }
799    Ok(out)
800}
801
802/// Walk `frames` in order. Frame 0 is the reference.
803///
804/// The error is the first frame that disagrees with frame 0, and the
805/// atom involved. A one-frame sequence checks that its ids are unique.
806pub fn check_atom_id_consistency(
807    frames: &[ConFrame],
808    check: IdentityCheck,
809) -> Result<(), CorrespondenceError> {
810    let refs: Vec<&ConFrame> = frames.iter().collect();
811    check_atom_id_consistency_refs(&refs, check)
812}
813
814pub(crate) fn check_atom_id_consistency_refs(
815    frames: &[&ConFrame],
816    check: IdentityCheck,
817) -> Result<(), CorrespondenceError> {
818    let Some(reference) = frames.first() else {
819        return Err(CorrespondenceError::EmptySequence);
820    };
821    if frames.len() == 1 {
822        index_ids(&reference.atom_data, 0)?;
823        return Ok(());
824    }
825    for (i, frame) in frames.iter().enumerate().skip(1) {
826        atom_id_permutation_at(reference, frame, i, check)?;
827    }
828    Ok(())
829}
830
831/// Minimum-image displacement of each reference atom toward the atom in
832/// `other` with the same `atom_id`.
833///
834/// Row `i` is the wrapped `r_other - r_reference` for reference atom `i`.
835/// The cell and the periodic flags are the reference frame's
836/// [`FrameHeader::cell_matrix`] and [`FrameHeader::pbc_effective`].
837pub fn minimum_image_displacements(
838    reference: &ConFrame,
839    other: &ConFrame,
840    check: IdentityCheck,
841) -> Result<Vec<[f64; 3]>, CorrespondenceError> {
842    let perm = atom_id_permutation(reference, other, check)?;
843    let cell = reference.header.cell_matrix();
844    let pbc = reference.header.pbc_effective();
845    let mut out = Vec::with_capacity(perm.len());
846    for (i, &j) in perm.iter().enumerate() {
847        let ra = position_of(reference, i)?;
848        let rb = position_of(other, j)?;
849        if !finite3(ra) {
850            return Err(CorrespondenceError::NonFiniteCoordinate {
851                frame_index: 0,
852                atom_id: reference.atom_data[i].atom_id,
853                atom_index: i,
854            });
855        }
856        if !finite3(rb) {
857            return Err(CorrespondenceError::NonFiniteCoordinate {
858                frame_index: 1,
859                atom_id: other.atom_data[j].atom_id,
860                atom_index: j,
861            });
862        }
863        let delta = [rb[0] - ra[0], rb[1] - ra[1], rb[2] - ra[2]];
864        out.push(minimum_image_delta(cell, pbc, delta)?);
865    }
866    Ok(out)
867}
868
869fn finite3(v: [f64; 3]) -> bool {
870    v.iter().all(|x| x.is_finite())
871}
872
873/// Wrap one cartesian delta into the reference cell.
874///
875/// `cell` is a [`FrameHeader::cell_matrix`]: each row is a lattice vector.
876/// With every axis periodic, fractional coordinates are `delta * cell^{-1}`
877/// (row vector on the left) and each axis subtracts the nearest integer.
878/// `f64::round` breaks a half-integer toward ±infinity, away from zero.
879///
880/// An open axis is not wrapped through that full inverse. One periodic
881/// vector is a rounding along it. Two periodic vectors are Gauss-reduced
882/// and the nine neighbours of the rounded image are searched. That result
883/// can differ from the per-axis fractional wrap three periodic axes still
884/// use, and it can be shorter. The component normal to the periodic
885/// vectors is left as it is.
886pub fn minimum_image_delta(
887    cell: [[f64; 3]; 3],
888    pbc: [bool; 3],
889    delta: [f64; 3],
890) -> Result<[f64; 3], CorrespondenceError> {
891    if !finite3(delta) {
892        return Err(CorrespondenceError::NonFiniteDelta);
893    }
894    let mut rows = [[0.0; 3]; 2];
895    let mut n = 0usize;
896    for axis in 0..3 {
897        if pbc[axis] {
898            if n < 2 {
899                rows[n] = cell[axis];
900            }
901            n += 1;
902        }
903    }
904    match n {
905        0 => Ok(delta),
906        1 => wrap_wire(delta, rows[0]),
907        2 => wrap_slab(delta, rows[0], rows[1]),
908        _ => wrap_full(cell, delta),
909    }
910}
911
912fn wrap_full(cell: [[f64; 3]; 3], delta: [f64; 3]) -> Result<[f64; 3], CorrespondenceError> {
913    let (inv, _) = invert_cell(cell).ok_or(CorrespondenceError::SingularCell {
914        determinant: det3(cell),
915    })?;
916    let mut frac = mul_row(delta, inv);
917    for component in &mut frac {
918        *component -= component.round();
919    }
920    Ok(mul_row(frac, cell))
921}
922
923fn wrap_wire(delta: [f64; 3], axis: [f64; 3]) -> Result<[f64; 3], CorrespondenceError> {
924    let length2 = dot(axis, axis);
925    if !length2.is_finite() || length2 <= 0.0 {
926        return Err(CorrespondenceError::SingularCell {
927            determinant: length2,
928        });
929    }
930    let steps = (dot(delta, axis) / length2).round();
931    Ok(axpy(delta, -steps, axis))
932}
933
934fn wrap_slab(delta: [f64; 3], u: [f64; 3], v: [f64; 3]) -> Result<[f64; 3], CorrespondenceError> {
935    if plane_duals(u, v).is_none() {
936        return Err(CorrespondenceError::SingularCell {
937            determinant: gram_det(u, v),
938        });
939    }
940    let reduced = lagrange_reduce(u, v);
941    let Some((dual, _)) = plane_duals(reduced[0], reduced[1]) else {
942        return Err(CorrespondenceError::SingularCell {
943            determinant: gram_det(reduced[0], reduced[1]),
944        });
945    };
946    let along_u = dot(delta, dual[0]).round();
947    let along_v = dot(delta, dual[1]).round();
948    let mut best = axpy(axpy(delta, -along_u, reduced[0]), -along_v, reduced[1]);
949    let mut best_n2 = dot(best, best);
950    for i in -1i32..=1 {
951        for j in -1i32..=1 {
952            let cand = axpy(
953                axpy(delta, -(along_u + f64::from(i)), reduced[0]),
954                -(along_v + f64::from(j)),
955                reduced[1],
956            );
957            let cand_n2 = dot(cand, cand);
958            // A tie, or a difference below this floor, keeps the rounded
959            // image. A shorter neighbour replaces it.
960            if cand_n2 + 1e-12 * (1.0 + best_n2) < best_n2 {
961                best = cand;
962                best_n2 = cand_n2;
963            }
964        }
965    }
966    Ok(best)
967}
968
969fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
970    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
971}
972
973fn axpy(y: [f64; 3], alpha: f64, x: [f64; 3]) -> [f64; 3] {
974    [
975        y[0] + alpha * x[0],
976        y[1] + alpha * x[1],
977        y[2] + alpha * x[2],
978    ]
979}
980
981fn gram_det(u: [f64; 3], v: [f64; 3]) -> f64 {
982    let uu = dot(u, u);
983    let vv = dot(v, v);
984    let uv = dot(u, v);
985    uu * vv - uv * uv
986}
987
988/// In-plane duals. `dual[i] · basis[j]` is the Kronecker delta, and each
989/// dual lies in the plane of the basis. `None` when the pair is
990/// collinear or non-finite.
991fn plane_duals(u: [f64; 3], v: [f64; 3]) -> Option<([[f64; 3]; 2], f64)> {
992    let uu = dot(u, u);
993    let vv = dot(v, v);
994    let uv = dot(u, v);
995    let det = gram_det(u, v);
996    let bound = 1e-24 * uu * vv;
997    if !det.is_finite() || !bound.is_finite() || det <= bound {
998        return None;
999    }
1000    let inv = 1.0 / det;
1001    let dual_u = axpy(
1002        [vv * inv * u[0], vv * inv * u[1], vv * inv * u[2]],
1003        -uv * inv,
1004        v,
1005    );
1006    let dual_v = axpy(
1007        [uu * inv * v[0], uu * inv * v[1], uu * inv * v[2]],
1008        -uv * inv,
1009        u,
1010    );
1011    Some(([dual_u, dual_v], det))
1012}
1013
1014/// Gauss reduction of a two-dimensional lattice basis.
1015fn lagrange_reduce(mut u: [f64; 3], mut v: [f64; 3]) -> [[f64; 3]; 2] {
1016    if dot(u, u) > dot(v, v) {
1017        std::mem::swap(&mut u, &mut v);
1018    }
1019    for _ in 0..128 {
1020        let mu = (dot(u, v) / dot(u, u)).round();
1021        if mu != 0.0 {
1022            v = axpy(v, -mu, u);
1023        }
1024        if dot(v, v) >= dot(u, u) {
1025            break;
1026        }
1027        std::mem::swap(&mut u, &mut v);
1028    }
1029    [u, v]
1030}
1031
1032fn det3(m: [[f64; 3]; 3]) -> f64 {
1033    m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
1034        - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
1035        + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
1036}
1037
1038fn invert_cell(m: [[f64; 3]; 3]) -> Option<([[f64; 3]; 3], f64)> {
1039    let det = det3(m);
1040    if !det.is_finite() || det.abs() < 1e-18 {
1041        return None;
1042    }
1043    let inv_det = 1.0 / det;
1044    let c00 = m[1][1] * m[2][2] - m[1][2] * m[2][1];
1045    let c01 = -(m[1][0] * m[2][2] - m[1][2] * m[2][0]);
1046    let c02 = m[1][0] * m[2][1] - m[1][1] * m[2][0];
1047    let c10 = -(m[0][1] * m[2][2] - m[0][2] * m[2][1]);
1048    let c11 = m[0][0] * m[2][2] - m[0][2] * m[2][0];
1049    let c12 = -(m[0][0] * m[2][1] - m[0][1] * m[2][0]);
1050    let c20 = m[0][1] * m[1][2] - m[0][2] * m[1][1];
1051    let c21 = -(m[0][0] * m[1][2] - m[0][2] * m[1][0]);
1052    let c22 = m[0][0] * m[1][1] - m[0][1] * m[1][0];
1053    let inv = [
1054        [c00 * inv_det, c10 * inv_det, c20 * inv_det],
1055        [c01 * inv_det, c11 * inv_det, c21 * inv_det],
1056        [c02 * inv_det, c12 * inv_det, c22 * inv_det],
1057    ];
1058    Some((inv, det))
1059}
1060
1061/// Row vector times a row-major matrix.
1062fn mul_row(v: [f64; 3], m: [[f64; 3]; 3]) -> [f64; 3] {
1063    [
1064        v[0] * m[0][0] + v[1] * m[1][0] + v[2] * m[2][0],
1065        v[0] * m[0][1] + v[1] * m[1][1] + v[2] * m[2][1],
1066        v[0] * m[0][2] + v[1] * m[1][2] + v[2] * m[2][2],
1067    ]
1068}
1069
1070#[cfg(test)]
1071mod tests {
1072    use super::*;
1073    use crate::types::cell_vectors;
1074
1075    fn close(a: [f64; 3], b: [f64; 3]) {
1076        for k in 0..3 {
1077            assert!(
1078                (a[k] - b[k]).abs() < 1e-9,
1079                "component {k}: {} vs {}",
1080                a[k],
1081                b[k]
1082            );
1083        }
1084    }
1085
1086    #[test]
1087    fn orthogonal_wrap_uses_the_cell_matrix() {
1088        let cell = cell_vectors([10.0, 12.0, 14.0], [90.0, 90.0, 90.0]);
1089        let wrapped = minimum_image_delta(cell, [true, true, true], [9.0, 0.0, 0.0]).unwrap();
1090        close(wrapped, [-1.0, 0.0, 0.0]);
1091        let open = minimum_image_delta(cell, [false, true, true], [9.0, 9.0, 0.0]).unwrap();
1092        close(open, [9.0, -3.0, 0.0]);
1093    }
1094
1095    #[test]
1096    fn a_lattice_vector_wraps_to_zero() {
1097        let cell = cell_vectors([10.0, 12.0, 14.0], [80.0, 90.0, 70.0]);
1098        let along_a = minimum_image_delta(cell, [true, true, true], cell[0]).unwrap();
1099        close(along_a, [0.0, 0.0, 0.0]);
1100        let along_b = minimum_image_delta(cell, [true, true, true], cell[1]).unwrap();
1101        close(along_b, [0.0, 0.0, 0.0]);
1102    }
1103
1104    #[test]
1105    fn a_flat_cell_is_rejected() {
1106        let err = minimum_image_delta([[0.0; 3]; 3], [true; 3], [1.0, 0.0, 0.0]).unwrap_err();
1107        assert!(matches!(err, CorrespondenceError::SingularCell { .. }));
1108        assert!(err.to_string().contains("singular"));
1109    }
1110
1111    #[test]
1112    fn a_collapsed_slab_is_rejected() {
1113        let cell = [[1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 0.0, 1.0]];
1114        let err = minimum_image_delta(cell, [true, true, false], [0.1, 0.2, 0.3]).unwrap_err();
1115        assert!(matches!(err, CorrespondenceError::SingularCell { .. }));
1116        assert!(err.to_string().contains("singular"));
1117    }
1118
1119    #[test]
1120    fn an_open_cell_keeps_the_cartesian_delta() {
1121        let delta = [1.5, -2.0, 0.25];
1122        let kept = minimum_image_delta([[0.0; 3]; 3], [false; 3], delta).unwrap();
1123        close(kept, delta);
1124    }
1125
1126    #[test]
1127    fn a_wire_wraps_only_along_its_axis() {
1128        let cell = cell_vectors([10.0, 12.0, 14.0], [90.0, 90.0, 90.0]);
1129        let wrapped = minimum_image_delta(cell, [false, false, true], [1.0, 2.0, 9.0]).unwrap();
1130        close(wrapped, [1.0, 2.0, -5.0]);
1131    }
1132
1133    #[test]
1134    fn a_near_flat_slab_keeps_a_small_out_of_plane_step() {
1135        let cell = cell_vectors([5.0, 5.0, 3.0], [86.892, 16.892, 70.0]);
1136        assert!(
1137            cell[2][2].abs() < 1e-6,
1138            "c_z {} should be near 1e-8",
1139            cell[2][2]
1140        );
1141        let delta = [0.02, -0.01, 0.275];
1142        let wrapped = minimum_image_delta(cell, [true, true, false], delta).unwrap();
1143        close(wrapped, delta);
1144        assert!(
1145            wrapped.iter().all(|component| component.abs() < 1.0),
1146            "{wrapped:?}"
1147        );
1148    }
1149}