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//! The matrix is inverted here; lengths and angles are not rebuilt.
11
12use crate::storage_dtype::{FloatArray1, FloatArray2};
13use crate::types::{Bond, ConFrame, ConFrameBuilder};
14use rustc_hash::FxHashMap;
15
16/// How strictly two atoms that share an `atom_id` must agree.
17///
18/// Symbol mismatches, duplicate ids, and missing or extra ids fail in both
19/// modes. [`IdentityCheck::Strict`] also requires the mass and the fixed
20/// mask to agree. Masses within [`ConFrameBuilder::TYPE_MASS_ABS_TOL`] agree.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22pub enum IdentityCheck {
23    /// Symbol, mass, and fixed mask agree.
24    #[default]
25    Strict,
26    /// Symbol agrees. Mass and fixed mask may differ.
27    Lenient,
28}
29
30/// Why two frames (or a later frame in a sequence) do not correspond.
31#[derive(Debug, Clone, PartialEq)]
32pub enum CorrespondenceError {
33    /// `check_atom_id_consistency` was given no frames.
34    EmptySequence,
35    /// The same id occurs twice in one frame.
36    Duplicate {
37        frame_index: usize,
38        atom_id: u64,
39        /// Index of the second occurrence.
40        atom_index: usize,
41        first_index: usize,
42    },
43    /// `atom_id` is in the reference frame and absent from this frame.
44    Missing {
45        frame_index: usize,
46        atom_id: u64,
47        /// Index of the atom in the reference frame.
48        reference_index: usize,
49    },
50    /// `atom_id` is in this frame and absent from the reference frame.
51    Extra {
52        frame_index: usize,
53        atom_id: u64,
54        atom_index: usize,
55    },
56    Symbol {
57        frame_index: usize,
58        atom_id: u64,
59        atom_index: usize,
60        reference_symbol: String,
61        found_symbol: String,
62    },
63    Mass {
64        frame_index: usize,
65        atom_id: u64,
66        atom_index: usize,
67        reference_mass: f64,
68        found_mass: f64,
69    },
70    Fixed {
71        frame_index: usize,
72        atom_id: u64,
73        atom_index: usize,
74        reference_fixed: [bool; 3],
75        found_fixed: [bool; 3],
76    },
77    /// Reference cell matrix cannot be inverted.
78    SingularCell {
79        determinant: f64,
80    },
81    NonFiniteDelta,
82    NonFiniteCoordinate {
83        frame_index: usize,
84        atom_id: u64,
85        atom_index: usize,
86    },
87    SectionLength {
88        section: &'static str,
89        rows: usize,
90        atoms: usize,
91    },
92    BondEndpoint {
93        index: u32,
94        atoms: usize,
95    },
96}
97
98impl CorrespondenceError {
99    /// Frame that failed. `None` when the failure is not a frame.
100    pub fn frame_index(&self) -> Option<usize> {
101        match self {
102            Self::EmptySequence | Self::SingularCell { .. } | Self::NonFiniteDelta => None,
103            Self::Duplicate { frame_index, .. }
104            | Self::Missing { frame_index, .. }
105            | Self::Extra { frame_index, .. }
106            | Self::Symbol { frame_index, .. }
107            | Self::Mass { frame_index, .. }
108            | Self::Fixed { frame_index, .. }
109            | Self::NonFiniteCoordinate { frame_index, .. } => Some(*frame_index),
110            Self::SectionLength { .. } | Self::BondEndpoint { .. } => None,
111        }
112    }
113
114    /// Atom id involved, when the failure names one atom.
115    pub fn atom_id(&self) -> Option<u64> {
116        match self {
117            Self::Duplicate { atom_id, .. }
118            | Self::Missing { atom_id, .. }
119            | Self::Extra { atom_id, .. }
120            | Self::Symbol { atom_id, .. }
121            | Self::Mass { atom_id, .. }
122            | Self::Fixed { atom_id, .. }
123            | Self::NonFiniteCoordinate { atom_id, .. } => Some(*atom_id),
124            _ => None,
125        }
126    }
127
128    /// Storage index of that atom.
129    ///
130    /// For [`CorrespondenceError::Missing`] this is the index in the
131    /// reference frame. Otherwise it is the index in [`Self::frame_index`].
132    pub fn atom_index(&self) -> Option<usize> {
133        match self {
134            Self::Duplicate { atom_index, .. }
135            | Self::Extra { atom_index, .. }
136            | Self::Symbol { atom_index, .. }
137            | Self::Mass { atom_index, .. }
138            | Self::Fixed { atom_index, .. }
139            | Self::NonFiniteCoordinate { atom_index, .. } => Some(*atom_index),
140            Self::Missing {
141                reference_index, ..
142            } => Some(*reference_index),
143            _ => None,
144        }
145    }
146}
147
148impl std::fmt::Display for CorrespondenceError {
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        match self {
151            Self::EmptySequence => {
152                write!(f, "atom-id consistency check needs at least one frame")
153            }
154            Self::Duplicate {
155                frame_index,
156                atom_id,
157                atom_index,
158                first_index,
159            } => write!(
160                f,
161                "duplicate atom_id {atom_id} in frame {frame_index} at index {atom_index} (first index {first_index})"
162            ),
163            Self::Missing {
164                frame_index,
165                atom_id,
166                reference_index,
167            } => write!(
168                f,
169                "frame {frame_index} is missing atom_id {atom_id} (reference index {reference_index})"
170            ),
171            Self::Extra {
172                frame_index,
173                atom_id,
174                atom_index,
175            } => write!(
176                f,
177                "frame {frame_index} atom_id {atom_id} at index {atom_index} is not in the reference frame"
178            ),
179            Self::Symbol {
180                frame_index,
181                atom_id,
182                atom_index,
183                reference_symbol,
184                found_symbol,
185            } => write!(
186                f,
187                "frame {frame_index} atom_id {atom_id} at index {atom_index} has symbol {found_symbol}; reference symbol is {reference_symbol}"
188            ),
189            Self::Mass {
190                frame_index,
191                atom_id,
192                atom_index,
193                reference_mass,
194                found_mass,
195            } => write!(
196                f,
197                "frame {frame_index} atom_id {atom_id} at index {atom_index} has mass {found_mass}; reference mass is {reference_mass} (tolerance {})",
198                ConFrameBuilder::TYPE_MASS_ABS_TOL
199            ),
200            Self::Fixed {
201                frame_index,
202                atom_id,
203                atom_index,
204                reference_fixed,
205                found_fixed,
206            } => write!(
207                f,
208                "frame {frame_index} atom_id {atom_id} at index {atom_index} has fixed mask {found_fixed:?}; reference fixed mask is {reference_fixed:?}"
209            ),
210            Self::SingularCell { determinant } => write!(
211                f,
212                "minimum-image displacement: reference cell matrix is singular (determinant {determinant})"
213            ),
214            Self::NonFiniteDelta => {
215                write!(
216                    f,
217                    "minimum-image displacement: cartesian delta is non-finite"
218                )
219            }
220            Self::NonFiniteCoordinate {
221                frame_index,
222                atom_id,
223                atom_index,
224            } => write!(
225                f,
226                "frame {frame_index} atom_id {atom_id} at index {atom_index} has a non-finite coordinate"
227            ),
228            Self::SectionLength {
229                section,
230                rows,
231                atoms,
232            } => write!(f, "{section} has {rows} rows for {atoms} atoms"),
233            Self::BondEndpoint { index, atoms } => {
234                write!(
235                    f,
236                    "bond endpoint {index} is outside the atom list ({atoms} atoms)"
237                )
238            }
239        }
240    }
241}
242
243impl std::error::Error for CorrespondenceError {}
244
245/// `perm[i]` is the index in `other` of the atom whose `atom_id` equals
246/// `reference.atom_data[i].atom_id`.
247///
248/// Frame index 0 in an error is `reference`. Frame index 1 is `other`.
249pub fn atom_id_permutation(
250    reference: &ConFrame,
251    other: &ConFrame,
252    check: IdentityCheck,
253) -> Result<Vec<usize>, CorrespondenceError> {
254    atom_id_permutation_at(reference, other, 1, check)
255}
256
257fn atom_id_permutation_at(
258    reference: &ConFrame,
259    other: &ConFrame,
260    other_index: usize,
261    check: IdentityCheck,
262) -> Result<Vec<usize>, CorrespondenceError> {
263    index_ids(&reference.atom_data, 0)?;
264    let other_index_map = index_ids(&other.atom_data, other_index)?;
265    let ref_mass = masses_of(reference)?;
266    let other_mass = masses_of(other)?;
267    let mut perm = Vec::with_capacity(reference.atom_data.len());
268    for (ri, atom) in reference.atom_data.iter().enumerate() {
269        let Some(&bi) = other_index_map.get(&atom.atom_id) else {
270            return Err(CorrespondenceError::Missing {
271                frame_index: other_index,
272                atom_id: atom.atom_id,
273                reference_index: ri,
274            });
275        };
276        let found = &other.atom_data[bi];
277        if found.symbol != atom.symbol {
278            return Err(CorrespondenceError::Symbol {
279                frame_index: other_index,
280                atom_id: atom.atom_id,
281                atom_index: bi,
282                reference_symbol: atom.symbol.to_string(),
283                found_symbol: found.symbol.to_string(),
284            });
285        }
286        if check == IdentityCheck::Strict {
287            let reference_mass = ref_mass[ri];
288            let found_mass = other_mass[bi];
289            if !reference_mass.is_finite()
290                || !found_mass.is_finite()
291                || (reference_mass - found_mass).abs() > ConFrameBuilder::TYPE_MASS_ABS_TOL
292            {
293                return Err(CorrespondenceError::Mass {
294                    frame_index: other_index,
295                    atom_id: atom.atom_id,
296                    atom_index: bi,
297                    reference_mass,
298                    found_mass,
299                });
300            }
301            if found.fixed != atom.fixed {
302                return Err(CorrespondenceError::Fixed {
303                    frame_index: other_index,
304                    atom_id: atom.atom_id,
305                    atom_index: bi,
306                    reference_fixed: atom.fixed,
307                    found_fixed: found.fixed,
308                });
309            }
310        }
311        perm.push(bi);
312    }
313    if other.atom_data.len() != reference.atom_data.len() {
314        let mut seen = vec![false; other.atom_data.len()];
315        for &bi in &perm {
316            seen[bi] = true;
317        }
318        for (i, atom) in other.atom_data.iter().enumerate() {
319            if !seen[i] {
320                return Err(CorrespondenceError::Extra {
321                    frame_index: other_index,
322                    atom_id: atom.atom_id,
323                    atom_index: i,
324                });
325            }
326        }
327    }
328    Ok(perm)
329}
330
331fn index_ids(
332    atoms: &[crate::types::AtomDatum],
333    frame_index: usize,
334) -> Result<FxHashMap<u64, usize>, CorrespondenceError> {
335    let mut map = FxHashMap::with_capacity_and_hasher(atoms.len(), Default::default());
336    for (i, atom) in atoms.iter().enumerate() {
337        if let Some(first) = map.insert(atom.atom_id, i) {
338            return Err(CorrespondenceError::Duplicate {
339                frame_index,
340                atom_id: atom.atom_id,
341                atom_index: i,
342                first_index: first,
343            });
344        }
345    }
346    Ok(map)
347}
348
349fn masses_of(frame: &ConFrame) -> Result<Vec<f64>, CorrespondenceError> {
350    let n = frame.atom_data.len();
351    if frame.masses.len() != n {
352        return Err(CorrespondenceError::SectionLength {
353            section: "masses",
354            rows: frame.masses.len(),
355            atoms: n,
356        });
357    }
358    Ok((0..n).map(|i| frame.masses.get_f64(i)).collect())
359}
360
361/// `other` with atoms stored in `reference` order.
362///
363/// Positions, velocities, forces, and the other per-atom sections move
364/// with the atom. Bond endpoints, which are `atom_data` indices, are
365/// remapped. The cell, the metadata, and the per-frame scalars stay
366/// those of `other`. Type counts are rebuilt from the new order so the
367/// frame still writes as CON when that order is type-grouped.
368pub fn reorder_like(
369    reference: &ConFrame,
370    other: &ConFrame,
371    check: IdentityCheck,
372) -> Result<ConFrame, CorrespondenceError> {
373    let perm = atom_id_permutation(reference, other, check)?;
374    apply_permutation(other, &perm)
375}
376
377fn apply_permutation(frame: &ConFrame, perm: &[usize]) -> Result<ConFrame, CorrespondenceError> {
378    let n = perm.len();
379    let mut out = frame.clone();
380    let mut atoms = Vec::with_capacity(n);
381    for &j in perm {
382        let mut atom = frame.atom_data[j].clone();
383        let p = position_of(frame, j)?;
384        atom.x = p[0];
385        atom.y = p[1];
386        atom.z = p[2];
387        overlay_sections(&mut atom, frame, j)?;
388        atoms.push(atom);
389    }
390    out.atom_data = atoms;
391    out.positions = permute_rows(&frame.positions, perm, "positions")?;
392    out.velocities = permute_rows(&frame.velocities, perm, "velocities")?;
393    out.forces = permute_rows(&frame.forces, perm, "forces")?;
394    out.magmoms = permute_rows(&frame.magmoms, perm, "magmoms")?;
395    out.displacements = permute_rows(&frame.displacements, perm, "displacements")?;
396    out.spreads = permute_rows(&frame.spreads, perm, "spreads")?;
397    out.atom_energies = permute_col(&frame.atom_energies, perm, "energies")?;
398    out.charges = permute_col(&frame.charges, perm, "charges")?;
399    out.spins = permute_col(&frame.spins, perm, "spins")?;
400    out.masses = permute_col(&frame.masses, perm, "masses")?;
401    let ids: Vec<u64> = perm.iter().map(|&j| frame.atom_data[j].atom_id).collect();
402    out.atom_ids = ndarray::Array1::from_vec(ids).into_shared();
403    // Positions were copied above. When the source stored coordinates only
404    // on the atoms, the permuted array is empty and the atoms carry xyz.
405    if frame.positions.nrows() == n {
406        for (i, atom) in out.atom_data.iter().enumerate() {
407            out.positions.set_f64_row(i, [atom.x, atom.y, atom.z]);
408        }
409    }
410    refresh_type_runs(&mut out);
411    remap_bonds(&mut out, perm)?;
412    Ok(out)
413}
414
415fn position_of(frame: &ConFrame, i: usize) -> Result<[f64; 3], CorrespondenceError> {
416    let n = frame.atom_data.len();
417    if frame.positions.nrows() == n {
418        return Ok(frame.positions.as_f64_row(i));
419    }
420    if frame.positions.nrows() == 0 {
421        let atom = &frame.atom_data[i];
422        return Ok([atom.x, atom.y, atom.z]);
423    }
424    Err(CorrespondenceError::SectionLength {
425        section: "positions",
426        rows: frame.positions.nrows(),
427        atoms: n,
428    })
429}
430
431fn overlay_sections(
432    atom: &mut crate::types::AtomDatum,
433    frame: &ConFrame,
434    j: usize,
435) -> Result<(), CorrespondenceError> {
436    let n = frame.atom_data.len();
437    if frame.velocities.nrows() == n {
438        atom.set_velocity(Some(frame.velocities.as_f64_row(j)));
439    } else if frame.velocities.nrows() != 0 {
440        return Err(CorrespondenceError::SectionLength {
441            section: "velocities",
442            rows: frame.velocities.nrows(),
443            atoms: n,
444        });
445    }
446    if frame.forces.nrows() == n {
447        atom.set_force(Some(frame.forces.as_f64_row(j)));
448    } else if frame.forces.nrows() != 0 {
449        return Err(CorrespondenceError::SectionLength {
450            section: "forces",
451            rows: frame.forces.nrows(),
452            atoms: n,
453        });
454    }
455    if frame.atom_energies.len() == n {
456        atom.set_energy(Some(frame.atom_energies.get_f64(j)));
457    } else if !frame.atom_energies.is_empty() {
458        return Err(CorrespondenceError::SectionLength {
459            section: "energies",
460            rows: frame.atom_energies.len(),
461            atoms: n,
462        });
463    }
464    if frame.charges.len() == n {
465        atom.set_charge(Some(frame.charges.get_f64(j)));
466    } else if !frame.charges.is_empty() {
467        return Err(CorrespondenceError::SectionLength {
468            section: "charges",
469            rows: frame.charges.len(),
470            atoms: n,
471        });
472    }
473    if frame.spins.len() == n {
474        atom.set_spin(Some(frame.spins.get_f64(j)));
475    } else if !frame.spins.is_empty() {
476        return Err(CorrespondenceError::SectionLength {
477            section: "spins",
478            rows: frame.spins.len(),
479            atoms: n,
480        });
481    }
482    if frame.magmoms.nrows() == n {
483        atom.set_magmom(Some(frame.magmoms.as_f64_row(j)));
484    } else if frame.magmoms.nrows() != 0 {
485        return Err(CorrespondenceError::SectionLength {
486            section: "magmoms",
487            rows: frame.magmoms.nrows(),
488            atoms: n,
489        });
490    }
491    if frame.displacements.nrows() == n {
492        atom.set_displacement(Some(frame.displacements.as_f64_row(j)));
493    } else if frame.displacements.nrows() != 0 {
494        return Err(CorrespondenceError::SectionLength {
495            section: "displacements",
496            rows: frame.displacements.nrows(),
497            atoms: n,
498        });
499    }
500    if frame.spreads.nrows() == n {
501        atom.set_spread(Some(frame.spreads.as_f64_row(j)));
502    } else if frame.spreads.nrows() != 0 {
503        return Err(CorrespondenceError::SectionLength {
504            section: "spreads",
505            rows: frame.spreads.nrows(),
506            atoms: n,
507        });
508    }
509    Ok(())
510}
511
512fn permute_rows(
513    src: &FloatArray2,
514    perm: &[usize],
515    section: &'static str,
516) -> Result<FloatArray2, CorrespondenceError> {
517    let n = perm.len();
518    if src.nrows() == 0 {
519        return Ok(FloatArray2::zeros(src.kind(), 0, 3));
520    }
521    if src.nrows() != n {
522        return Err(CorrespondenceError::SectionLength {
523            section,
524            rows: src.nrows(),
525            atoms: n,
526        });
527    }
528    let mut out = FloatArray2::zeros(src.kind(), n, src.ncols().max(3));
529    for (i, &j) in perm.iter().enumerate() {
530        out.set_f64_row(i, src.as_f64_row(j));
531    }
532    Ok(out)
533}
534
535fn permute_col(
536    src: &FloatArray1,
537    perm: &[usize],
538    section: &'static str,
539) -> Result<FloatArray1, CorrespondenceError> {
540    let n = perm.len();
541    if src.is_empty() {
542        return Ok(FloatArray1::zeros(src.kind(), 0));
543    }
544    if src.len() != n {
545        return Err(CorrespondenceError::SectionLength {
546            section,
547            rows: src.len(),
548            atoms: n,
549        });
550    }
551    let mut out = FloatArray1::zeros(src.kind(), n);
552    for (i, &j) in perm.iter().enumerate() {
553        out.set_f64(i, src.get_f64(j));
554    }
555    Ok(out)
556}
557
558fn refresh_type_runs(frame: &mut ConFrame) {
559    let n = frame.atom_data.len();
560    if n == 0 {
561        frame.header.natm_types = 0;
562        frame.header.natms_per_type.clear();
563        frame.header.masses_per_type.clear();
564        return;
565    }
566    let mut counts = Vec::new();
567    let mut masses = Vec::new();
568    let mut run_symbol = frame.atom_data[0].symbol.clone();
569    let mut run_count = 0usize;
570    let mut run_mass = frame.masses.get_f64(0);
571    for i in 0..n {
572        if frame.atom_data[i].symbol != run_symbol {
573            counts.push(run_count);
574            masses.push(run_mass);
575            run_symbol = frame.atom_data[i].symbol.clone();
576            run_count = 0;
577            run_mass = frame.masses.get_f64(i);
578        }
579        run_count += 1;
580    }
581    counts.push(run_count);
582    masses.push(run_mass);
583    frame.header.natm_types = counts.len();
584    frame.header.natms_per_type = counts;
585    frame.header.masses_per_type = masses;
586}
587
588fn remap_bonds(frame: &mut ConFrame, perm: &[usize]) -> Result<(), CorrespondenceError> {
589    let bonds = frame.bonds();
590    if bonds.is_empty() {
591        return Ok(());
592    }
593    let n = perm.len();
594    let mut inverse = vec![0usize; n];
595    for (i, &j) in perm.iter().enumerate() {
596        inverse[j] = i;
597    }
598    let mut mapped = Vec::with_capacity(bonds.len());
599    for bond in bonds {
600        if bond.i as usize >= n {
601            return Err(CorrespondenceError::BondEndpoint {
602                index: bond.i,
603                atoms: n,
604            });
605        }
606        if bond.j as usize >= n {
607            return Err(CorrespondenceError::BondEndpoint {
608                index: bond.j,
609                atoms: n,
610            });
611        }
612        mapped.push(Bond {
613            i: inverse[bond.i as usize] as u32,
614            j: inverse[bond.j as usize] as u32,
615            order: bond.order,
616        });
617    }
618    frame.header.set_bonds(&mapped);
619    Ok(())
620}
621
622/// Walk `frames` in order. Frame 0 is the reference.
623///
624/// The error is the first frame that disagrees with frame 0, and the
625/// atom involved. A one-frame sequence checks that its ids are unique.
626pub fn check_atom_id_consistency(
627    frames: &[ConFrame],
628    check: IdentityCheck,
629) -> Result<(), CorrespondenceError> {
630    let refs: Vec<&ConFrame> = frames.iter().collect();
631    check_atom_id_consistency_refs(&refs, check)
632}
633
634pub(crate) fn check_atom_id_consistency_refs(
635    frames: &[&ConFrame],
636    check: IdentityCheck,
637) -> Result<(), CorrespondenceError> {
638    let Some(reference) = frames.first() else {
639        return Err(CorrespondenceError::EmptySequence);
640    };
641    if frames.len() == 1 {
642        index_ids(&reference.atom_data, 0)?;
643        return Ok(());
644    }
645    for (i, frame) in frames.iter().enumerate().skip(1) {
646        atom_id_permutation_at(reference, frame, i, check)?;
647    }
648    Ok(())
649}
650
651/// Minimum-image displacement of each reference atom toward the atom in
652/// `other` with the same `atom_id`.
653///
654/// Row `i` is the wrapped `r_other - r_reference` for reference atom `i`.
655/// The cell and the periodic flags are the reference frame's
656/// [`FrameHeader::cell_matrix`] and [`FrameHeader::pbc_effective`].
657pub fn minimum_image_displacements(
658    reference: &ConFrame,
659    other: &ConFrame,
660    check: IdentityCheck,
661) -> Result<Vec<[f64; 3]>, CorrespondenceError> {
662    let perm = atom_id_permutation(reference, other, check)?;
663    let cell = reference.header.cell_matrix();
664    let pbc = reference.header.pbc_effective();
665    let mut out = Vec::with_capacity(perm.len());
666    for (i, &j) in perm.iter().enumerate() {
667        let ra = position_of(reference, i)?;
668        let rb = position_of(other, j)?;
669        if !finite3(ra) {
670            return Err(CorrespondenceError::NonFiniteCoordinate {
671                frame_index: 0,
672                atom_id: reference.atom_data[i].atom_id,
673                atom_index: i,
674            });
675        }
676        if !finite3(rb) {
677            return Err(CorrespondenceError::NonFiniteCoordinate {
678                frame_index: 1,
679                atom_id: other.atom_data[j].atom_id,
680                atom_index: j,
681            });
682        }
683        let delta = [rb[0] - ra[0], rb[1] - ra[1], rb[2] - ra[2]];
684        out.push(minimum_image_delta(cell, pbc, delta)?);
685    }
686    Ok(out)
687}
688
689fn finite3(v: [f64; 3]) -> bool {
690    v.iter().all(|x| x.is_finite())
691}
692
693/// Wrap one cartesian delta into the reference cell.
694///
695/// `cell` is a [`FrameHeader::cell_matrix`]: each row is a lattice vector.
696/// Fractional coordinates are `delta * cell^{-1}` (row vector on the left).
697/// A periodic axis subtracts the nearest integer. `f64::round` breaks a
698/// half-integer toward ±infinity, away from zero.
699pub fn minimum_image_delta(
700    cell: [[f64; 3]; 3],
701    pbc: [bool; 3],
702    delta: [f64; 3],
703) -> Result<[f64; 3], CorrespondenceError> {
704    if !finite3(delta) {
705        return Err(CorrespondenceError::NonFiniteDelta);
706    }
707    let (inv, _) = invert_cell(cell).ok_or(CorrespondenceError::SingularCell {
708        determinant: det3(cell),
709    })?;
710    let mut frac = mul_row(delta, inv);
711    for axis in 0..3 {
712        if pbc[axis] {
713            frac[axis] -= frac[axis].round();
714        }
715    }
716    Ok(mul_row(frac, cell))
717}
718
719fn det3(m: [[f64; 3]; 3]) -> f64 {
720    m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
721        - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
722        + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
723}
724
725fn invert_cell(m: [[f64; 3]; 3]) -> Option<([[f64; 3]; 3], f64)> {
726    let det = det3(m);
727    if !det.is_finite() || det.abs() < 1e-18 {
728        return None;
729    }
730    let inv_det = 1.0 / det;
731    let c00 = m[1][1] * m[2][2] - m[1][2] * m[2][1];
732    let c01 = -(m[1][0] * m[2][2] - m[1][2] * m[2][0]);
733    let c02 = m[1][0] * m[2][1] - m[1][1] * m[2][0];
734    let c10 = -(m[0][1] * m[2][2] - m[0][2] * m[2][1]);
735    let c11 = m[0][0] * m[2][2] - m[0][2] * m[2][0];
736    let c12 = -(m[0][0] * m[2][1] - m[0][1] * m[2][0]);
737    let c20 = m[0][1] * m[1][2] - m[0][2] * m[1][1];
738    let c21 = -(m[0][0] * m[1][2] - m[0][2] * m[1][0]);
739    let c22 = m[0][0] * m[1][1] - m[0][1] * m[1][0];
740    let inv = [
741        [c00 * inv_det, c10 * inv_det, c20 * inv_det],
742        [c01 * inv_det, c11 * inv_det, c21 * inv_det],
743        [c02 * inv_det, c12 * inv_det, c22 * inv_det],
744    ];
745    Some((inv, det))
746}
747
748/// Row vector times a row-major matrix.
749fn mul_row(v: [f64; 3], m: [[f64; 3]; 3]) -> [f64; 3] {
750    [
751        v[0] * m[0][0] + v[1] * m[1][0] + v[2] * m[2][0],
752        v[0] * m[0][1] + v[1] * m[1][1] + v[2] * m[2][1],
753        v[0] * m[0][2] + v[1] * m[1][2] + v[2] * m[2][2],
754    ]
755}
756
757#[cfg(test)]
758mod tests {
759    use super::*;
760    use crate::types::cell_vectors;
761
762    fn close(a: [f64; 3], b: [f64; 3]) {
763        for k in 0..3 {
764            assert!(
765                (a[k] - b[k]).abs() < 1e-9,
766                "component {k}: {} vs {}",
767                a[k],
768                b[k]
769            );
770        }
771    }
772
773    #[test]
774    fn orthogonal_wrap_uses_the_cell_matrix() {
775        let cell = cell_vectors([10.0, 12.0, 14.0], [90.0, 90.0, 90.0]);
776        let wrapped = minimum_image_delta(cell, [true, true, true], [9.0, 0.0, 0.0]).unwrap();
777        close(wrapped, [-1.0, 0.0, 0.0]);
778        let open = minimum_image_delta(cell, [false, true, true], [9.0, 9.0, 0.0]).unwrap();
779        close(open, [9.0, -3.0, 0.0]);
780    }
781
782    #[test]
783    fn a_lattice_vector_wraps_to_zero() {
784        let cell = cell_vectors([10.0, 12.0, 14.0], [80.0, 90.0, 70.0]);
785        let along_a = minimum_image_delta(cell, [true, true, true], cell[0]).unwrap();
786        close(along_a, [0.0, 0.0, 0.0]);
787        let along_b = minimum_image_delta(cell, [true, true, true], cell[1]).unwrap();
788        close(along_b, [0.0, 0.0, 0.0]);
789    }
790
791    #[test]
792    fn a_flat_cell_is_rejected() {
793        let err = minimum_image_delta([[0.0; 3]; 3], [true; 3], [1.0, 0.0, 0.0]).unwrap_err();
794        assert!(matches!(err, CorrespondenceError::SingularCell { .. }));
795        assert!(err.to_string().contains("singular"));
796    }
797}