readcon-core 0.25.0

An oxidized single and multiple CON file reader and writer with FFI bindings for ergonomic C/C++ usage. Implements CON spec v4.
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
//! Pair atoms across frames by column-5 `atom_id`.
//!
//! CON stores atoms in type-grouped order. The id is the index from before
//! that grouping, so a reactant and a product that a writer grouped
//! differently still name the same atom. These helpers are the map, the
//! reorder, the band check, and the minimum-image displacement of the
//! matched pairs.
//!
//! The cell is [`FrameHeader::cell_matrix`] and [`FrameHeader::pbc_effective`].
//! Lengths and angles are not rebuilt. Every periodic axis is wrapped in
//! the span of those lattice vectors. An open axis is left out of that
//! span, so a flat slab is not inverted through its short `c` vector.
//!
//! ```
//! use readcon_core::types::ConFrameBuilder;
//! use readcon_core::{
//!     IdentityCheck, atom_id_permutation, check_atom_id_consistency,
//!     minimum_image_displacements, reorder_like,
//! };
//!
//! fn frame(rows: &[(u64, &str, f64)]) -> readcon_core::types::ConFrame {
//!     let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
//!     for (id, symbol, x) in rows {
//!         builder.add_atom(symbol, *x, 0.0, 0.0, [false; 3], *id, 12.0);
//!     }
//!     builder.build().unwrap()
//! }
//!
//! let reactant = frame(&[(1, "C", 0.0), (2, "O", 1.0)]);
//! let product = frame(&[(2, "O", 1.2), (1, "C", 0.1)]);
//! let perm = atom_id_permutation(&reactant, &product, IdentityCheck::Strict).unwrap();
//! assert_eq!(perm, vec![1, 0]);
//! let ordered = reorder_like(&reactant, &product, IdentityCheck::Strict).unwrap();
//! assert_eq!(ordered.atom_data[0].atom_id, 1);
//! assert_eq!(ordered.atom_data[1].atom_id, 2);
//! check_atom_id_consistency(&[reactant.clone(), product.clone()], IdentityCheck::Strict)
//!     .unwrap();
//! let disp = minimum_image_displacements(&reactant, &product, IdentityCheck::Strict).unwrap();
//! assert_eq!(disp.len(), 2);
//! assert!((disp[0][0] - 0.1).abs() < 1e-12);
//! ```

use crate::storage_dtype::{FloatArray1, FloatArray2};
use crate::types::{Bond, ConFrame, ConFrameBuilder};
use rustc_hash::FxHashMap;

/// How strictly two atoms that share an `atom_id` must agree.
///
/// Symbol mismatches, duplicate ids, and missing or extra ids fail in both
/// modes. [`IdentityCheck::Strict`] also requires the mass and the fixed
/// mask to agree. Masses within [`ConFrameBuilder::TYPE_MASS_ABS_TOL`] agree.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IdentityCheck {
    /// Symbol, mass, and fixed mask agree.
    #[default]
    Strict,
    /// Symbol agrees. Mass and fixed mask may differ.
    Lenient,
}

/// Why two frames (or a later frame in a sequence) do not correspond.
#[derive(Debug, Clone, PartialEq)]
pub enum CorrespondenceError {
    /// `check_atom_id_consistency` was given no frames.
    EmptySequence,
    /// The same id occurs twice in one frame.
    Duplicate {
        frame_index: usize,
        atom_id: u64,
        /// Index of the second occurrence.
        atom_index: usize,
        first_index: usize,
    },
    /// `atom_id` is in the reference frame and absent from this frame.
    Missing {
        frame_index: usize,
        atom_id: u64,
        /// Index of the atom in the reference frame.
        reference_index: usize,
    },
    /// `atom_id` is in this frame and absent from the reference frame.
    Extra {
        frame_index: usize,
        atom_id: u64,
        atom_index: usize,
    },
    Symbol {
        frame_index: usize,
        atom_id: u64,
        atom_index: usize,
        reference_symbol: String,
        found_symbol: String,
    },
    Mass {
        frame_index: usize,
        atom_id: u64,
        atom_index: usize,
        reference_mass: f64,
        found_mass: f64,
    },
    Fixed {
        frame_index: usize,
        atom_id: u64,
        atom_index: usize,
        reference_fixed: [bool; 3],
        found_fixed: [bool; 3],
    },
    /// Reference cell matrix cannot be inverted.
    SingularCell {
        determinant: f64,
    },
    NonFiniteDelta,
    NonFiniteCoordinate {
        frame_index: usize,
        atom_id: u64,
        atom_index: usize,
    },
    SectionLength {
        section: &'static str,
        rows: usize,
        atoms: usize,
    },
    BondEndpoint {
        index: u32,
        atoms: usize,
    },
    /// A selected atom index is outside the frame.
    AtomIndex {
        index: usize,
        atoms: usize,
    },
    /// The same atom index was selected twice.
    RepeatedIndex {
        index: usize,
        /// Position in the selection of the first occurrence.
        first_position: usize,
        /// Position in the selection of the second occurrence.
        position: usize,
    },
}

impl CorrespondenceError {
    /// Frame that failed. `None` when the failure is not a frame.
    pub fn frame_index(&self) -> Option<usize> {
        match self {
            Self::EmptySequence | Self::SingularCell { .. } | Self::NonFiniteDelta => None,
            Self::Duplicate { frame_index, .. }
            | Self::Missing { frame_index, .. }
            | Self::Extra { frame_index, .. }
            | Self::Symbol { frame_index, .. }
            | Self::Mass { frame_index, .. }
            | Self::Fixed { frame_index, .. }
            | Self::NonFiniteCoordinate { frame_index, .. } => Some(*frame_index),
            Self::SectionLength { .. }
            | Self::BondEndpoint { .. }
            | Self::AtomIndex { .. }
            | Self::RepeatedIndex { .. } => None,
        }
    }

    /// Atom id involved, when the failure names one atom.
    pub fn atom_id(&self) -> Option<u64> {
        match self {
            Self::Duplicate { atom_id, .. }
            | Self::Missing { atom_id, .. }
            | Self::Extra { atom_id, .. }
            | Self::Symbol { atom_id, .. }
            | Self::Mass { atom_id, .. }
            | Self::Fixed { atom_id, .. }
            | Self::NonFiniteCoordinate { atom_id, .. } => Some(*atom_id),
            _ => None,
        }
    }

    /// Storage index of that atom.
    ///
    /// For [`CorrespondenceError::Missing`] this is the index in the
    /// reference frame. Otherwise it is the index in [`Self::frame_index`].
    pub fn atom_index(&self) -> Option<usize> {
        match self {
            Self::Duplicate { atom_index, .. }
            | Self::Extra { atom_index, .. }
            | Self::Symbol { atom_index, .. }
            | Self::Mass { atom_index, .. }
            | Self::Fixed { atom_index, .. }
            | Self::NonFiniteCoordinate { atom_index, .. } => Some(*atom_index),
            Self::Missing {
                reference_index, ..
            } => Some(*reference_index),
            _ => None,
        }
    }
}

impl std::fmt::Display for CorrespondenceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EmptySequence => {
                write!(f, "atom-id consistency check needs at least one frame")
            }
            Self::Duplicate {
                frame_index,
                atom_id,
                atom_index,
                first_index,
            } => write!(
                f,
                "duplicate atom_id {atom_id} in frame {frame_index} at index {atom_index} (first index {first_index})"
            ),
            Self::Missing {
                frame_index,
                atom_id,
                reference_index,
            } => write!(
                f,
                "frame {frame_index} is missing atom_id {atom_id} (reference index {reference_index})"
            ),
            Self::Extra {
                frame_index,
                atom_id,
                atom_index,
            } => write!(
                f,
                "frame {frame_index} atom_id {atom_id} at index {atom_index} is not in the reference frame"
            ),
            Self::Symbol {
                frame_index,
                atom_id,
                atom_index,
                reference_symbol,
                found_symbol,
            } => write!(
                f,
                "frame {frame_index} atom_id {atom_id} at index {atom_index} has symbol {found_symbol}; reference symbol is {reference_symbol}"
            ),
            Self::Mass {
                frame_index,
                atom_id,
                atom_index,
                reference_mass,
                found_mass,
            } => write!(
                f,
                "frame {frame_index} atom_id {atom_id} at index {atom_index} has mass {found_mass}; reference mass is {reference_mass} (tolerance {})",
                ConFrameBuilder::TYPE_MASS_ABS_TOL
            ),
            Self::Fixed {
                frame_index,
                atom_id,
                atom_index,
                reference_fixed,
                found_fixed,
            } => write!(
                f,
                "frame {frame_index} atom_id {atom_id} at index {atom_index} has fixed mask {found_fixed:?}; reference fixed mask is {reference_fixed:?}"
            ),
            Self::SingularCell { determinant } => write!(
                f,
                "minimum-image displacement: the periodic cell is singular (cell-matrix or Gram determinant {determinant})"
            ),
            Self::NonFiniteDelta => {
                write!(
                    f,
                    "minimum-image displacement: cartesian delta is non-finite"
                )
            }
            Self::NonFiniteCoordinate {
                frame_index,
                atom_id,
                atom_index,
            } => write!(
                f,
                "frame {frame_index} atom_id {atom_id} at index {atom_index} has a non-finite coordinate"
            ),
            Self::SectionLength {
                section,
                rows,
                atoms,
            } => write!(f, "{section} has {rows} rows for {atoms} atoms"),
            Self::BondEndpoint { index, atoms } => {
                write!(
                    f,
                    "bond endpoint {index} is outside the atom list ({atoms} atoms)"
                )
            }
            Self::AtomIndex { index, atoms } => {
                write!(f, "atom index {index} is outside the frame ({atoms} atoms)")
            }
            Self::RepeatedIndex {
                index,
                first_position,
                position,
            } => write!(
                f,
                "atom index {index} is selected twice (positions {first_position} and {position})"
            ),
        }
    }
}

impl std::error::Error for CorrespondenceError {}

/// `perm[i]` is the index in `other` of the atom whose `atom_id` equals
/// `reference.atom_data[i].atom_id`.
///
/// Frame index 0 in an error is `reference`. Frame index 1 is `other`.
pub fn atom_id_permutation(
    reference: &ConFrame,
    other: &ConFrame,
    check: IdentityCheck,
) -> Result<Vec<usize>, CorrespondenceError> {
    atom_id_permutation_at(reference, other, 1, check)
}

fn atom_id_permutation_at(
    reference: &ConFrame,
    other: &ConFrame,
    other_index: usize,
    check: IdentityCheck,
) -> Result<Vec<usize>, CorrespondenceError> {
    index_ids(&reference.atom_data, 0)?;
    let other_index_map = index_ids(&other.atom_data, other_index)?;
    let ref_mass = masses_of(reference)?;
    let other_mass = masses_of(other)?;
    let mut perm = Vec::with_capacity(reference.atom_data.len());
    for (ri, atom) in reference.atom_data.iter().enumerate() {
        let Some(&bi) = other_index_map.get(&atom.atom_id) else {
            return Err(CorrespondenceError::Missing {
                frame_index: other_index,
                atom_id: atom.atom_id,
                reference_index: ri,
            });
        };
        let found = &other.atom_data[bi];
        if found.symbol != atom.symbol {
            return Err(CorrespondenceError::Symbol {
                frame_index: other_index,
                atom_id: atom.atom_id,
                atom_index: bi,
                reference_symbol: atom.symbol.to_string(),
                found_symbol: found.symbol.to_string(),
            });
        }
        if check == IdentityCheck::Strict {
            let reference_mass = ref_mass[ri];
            let found_mass = other_mass[bi];
            if !reference_mass.is_finite()
                || !found_mass.is_finite()
                || (reference_mass - found_mass).abs() > ConFrameBuilder::TYPE_MASS_ABS_TOL
            {
                return Err(CorrespondenceError::Mass {
                    frame_index: other_index,
                    atom_id: atom.atom_id,
                    atom_index: bi,
                    reference_mass,
                    found_mass,
                });
            }
            if found.fixed() != atom.fixed() {
                return Err(CorrespondenceError::Fixed {
                    frame_index: other_index,
                    atom_id: atom.atom_id,
                    atom_index: bi,
                    reference_fixed: atom.fixed(),
                    found_fixed: found.fixed(),
                });
            }
        }
        perm.push(bi);
    }
    if other.atom_data.len() != reference.atom_data.len() {
        let mut seen = vec![false; other.atom_data.len()];
        for &bi in &perm {
            seen[bi] = true;
        }
        for (i, atom) in other.atom_data.iter().enumerate() {
            if !seen[i] {
                return Err(CorrespondenceError::Extra {
                    frame_index: other_index,
                    atom_id: atom.atom_id,
                    atom_index: i,
                });
            }
        }
    }
    Ok(perm)
}

fn index_ids(
    atoms: &[crate::types::AtomDatum],
    frame_index: usize,
) -> Result<FxHashMap<u64, usize>, CorrespondenceError> {
    let mut map = FxHashMap::with_capacity_and_hasher(atoms.len(), Default::default());
    for (i, atom) in atoms.iter().enumerate() {
        if let Some(first) = map.insert(atom.atom_id, i) {
            return Err(CorrespondenceError::Duplicate {
                frame_index,
                atom_id: atom.atom_id,
                atom_index: i,
                first_index: first,
            });
        }
    }
    Ok(map)
}

fn masses_of(frame: &ConFrame) -> Result<Vec<f64>, CorrespondenceError> {
    let n = frame.atom_data.len();
    if frame.masses.len() != n {
        return Err(CorrespondenceError::SectionLength {
            section: "masses",
            rows: frame.masses.len(),
            atoms: n,
        });
    }
    Ok((0..n).map(|i| frame.masses.get_f64(i)).collect())
}

/// `other` with atoms stored in `reference` order.
///
/// Positions, velocities, forces, and the other per-atom sections move
/// with the atom. Bond endpoints, which are `atom_data` indices, are
/// remapped. The cell, the metadata, and the per-frame scalars stay
/// those of `other`. Type counts are rebuilt from the new order so the
/// frame still writes as CON when that order is type-grouped.
pub fn reorder_like(
    reference: &ConFrame,
    other: &ConFrame,
    check: IdentityCheck,
) -> Result<ConFrame, CorrespondenceError> {
    let perm = atom_id_permutation(reference, other, check)?;
    apply_permutation(other, &perm)
}

fn apply_permutation(frame: &ConFrame, perm: &[usize]) -> Result<ConFrame, CorrespondenceError> {
    let n = perm.len();
    let mut atoms = Vec::with_capacity(n);
    for &j in perm {
        let mut atom = frame.atom_data[j].clone();
        overlay_sections(&mut atom, frame, j)?;
        atoms.push(atom);
    }
    let velocities = permute_rows(&frame.velocities, perm, "velocities")?;
    let forces = permute_rows(&frame.forces, perm, "forces")?;
    let mut out = frame.clone();
    // The clone's atoms address its velocity and force columns. Both are
    // replaced here, and the atoms in `perm` order then address the rows
    // of the permuted columns.
    let bound = out.materialise_section_slots();
    out.atom_data = atoms;
    out.positions = permute_rows(&frame.positions, perm, "positions")?;
    out.velocities = velocities.into();
    out.forces = forces.into();
    out.magmoms = permute_rows(&frame.magmoms, perm, "magmoms")?.into();
    out.displacements = permute_rows(&frame.displacements, perm, "displacements")?.into();
    out.spreads = permute_rows(&frame.spreads, perm, "spreads")?.into();
    out.atom_energies = permute_col(&frame.atom_energies, perm, "energies")?.into();
    out.charges = permute_col(&frame.charges, perm, "charges")?.into();
    out.spins = permute_col(&frame.spins, perm, "spins")?.into();
    out.masses = permute_col(&frame.masses, perm, "masses")?;
    let ids: Vec<u64> = perm.iter().map(|&j| frame.atom_data[j].atom_id).collect();
    out.atom_ids = ndarray::Array1::from_vec(ids).into_shared();
    refresh_type_runs(&mut out);
    remap_bonds(&mut out, perm)?;
    if !bound.is_empty() {
        let bound: Vec<bool> = perm.iter().map(|&j| bound[j]).collect();
        out.bind_section_slots(&bound);
    }
    Ok(out)
}

fn position_of(frame: &ConFrame, i: usize) -> Result<[f64; 3], CorrespondenceError> {
    let n = frame.atom_data.len();
    if frame.positions.nrows() == n {
        return Ok(frame.positions.as_f64_row(i));
    }
    Err(CorrespondenceError::SectionLength {
        section: "positions",
        rows: frame.positions.nrows(),
        atoms: n,
    })
}

fn overlay_sections(
    atom: &mut crate::types::AtomDatum,
    frame: &ConFrame,
    j: usize,
) -> Result<(), CorrespondenceError> {
    let n = frame.atom_data.len();
    if frame.velocities.nrows() == n {
        atom.set_velocity(Some(frame.velocities.as_f64_row(j)));
    } else if frame.velocities.nrows() != 0 {
        return Err(CorrespondenceError::SectionLength {
            section: "velocities",
            rows: frame.velocities.nrows(),
            atoms: n,
        });
    }
    if frame.forces.nrows() == n {
        atom.set_force(Some(frame.forces.as_f64_row(j)));
    } else if frame.forces.nrows() != 0 {
        return Err(CorrespondenceError::SectionLength {
            section: "forces",
            rows: frame.forces.nrows(),
            atoms: n,
        });
    }
    if frame.atom_energies.len() == n {
        atom.set_energy(Some(frame.atom_energies.get_f64(j)));
    } else if !frame.atom_energies.is_empty() {
        return Err(CorrespondenceError::SectionLength {
            section: "energies",
            rows: frame.atom_energies.len(),
            atoms: n,
        });
    }
    if frame.charges.len() == n {
        atom.set_charge(Some(frame.charges.get_f64(j)));
    } else if !frame.charges.is_empty() {
        return Err(CorrespondenceError::SectionLength {
            section: "charges",
            rows: frame.charges.len(),
            atoms: n,
        });
    }
    if frame.spins.len() == n {
        atom.set_spin(Some(frame.spins.get_f64(j)));
    } else if !frame.spins.is_empty() {
        return Err(CorrespondenceError::SectionLength {
            section: "spins",
            rows: frame.spins.len(),
            atoms: n,
        });
    }
    if frame.magmoms.nrows() == n {
        atom.set_magmom(Some(frame.magmoms.as_f64_row(j)));
    } else if frame.magmoms.nrows() != 0 {
        return Err(CorrespondenceError::SectionLength {
            section: "magmoms",
            rows: frame.magmoms.nrows(),
            atoms: n,
        });
    }
    if frame.displacements.nrows() == n {
        atom.set_displacement(Some(frame.displacements.as_f64_row(j)));
    } else if frame.displacements.nrows() != 0 {
        return Err(CorrespondenceError::SectionLength {
            section: "displacements",
            rows: frame.displacements.nrows(),
            atoms: n,
        });
    }
    if frame.spreads.nrows() == n {
        atom.set_spread(Some(frame.spreads.as_f64_row(j)));
    } else if frame.spreads.nrows() != 0 {
        return Err(CorrespondenceError::SectionLength {
            section: "spreads",
            rows: frame.spreads.nrows(),
            atoms: n,
        });
    }
    Ok(())
}

fn permute_rows(
    src: &FloatArray2,
    perm: &[usize],
    section: &'static str,
) -> Result<FloatArray2, CorrespondenceError> {
    let n = perm.len();
    if src.nrows() == 0 {
        return Ok(FloatArray2::zeros(src.kind(), 0, 3));
    }
    if src.nrows() != n {
        return Err(CorrespondenceError::SectionLength {
            section,
            rows: src.nrows(),
            atoms: n,
        });
    }
    let mut out = FloatArray2::zeros(src.kind(), n, src.ncols().max(3));
    for (i, &j) in perm.iter().enumerate() {
        out.set_f64_row(i, src.as_f64_row(j));
    }
    Ok(out)
}

fn permute_col(
    src: &FloatArray1,
    perm: &[usize],
    section: &'static str,
) -> Result<FloatArray1, CorrespondenceError> {
    let n = perm.len();
    if src.is_empty() {
        return Ok(FloatArray1::zeros(src.kind(), 0));
    }
    if src.len() != n {
        return Err(CorrespondenceError::SectionLength {
            section,
            rows: src.len(),
            atoms: n,
        });
    }
    let mut out = FloatArray1::zeros(src.kind(), n);
    for (i, &j) in perm.iter().enumerate() {
        out.set_f64(i, src.get_f64(j));
    }
    Ok(out)
}

fn refresh_type_runs(frame: &mut ConFrame) {
    let n = frame.atom_data.len();
    if n == 0 {
        frame.header.natm_types = 0;
        frame.header.natms_per_type.clear();
        frame.header.masses_per_type.clear();
        return;
    }
    let mut counts = Vec::new();
    let mut masses = Vec::new();
    let mut run_symbol = frame.atom_data[0].symbol.clone();
    let mut run_count = 0usize;
    let mut run_mass = frame.masses.get_f64(0);
    for i in 0..n {
        if frame.atom_data[i].symbol != run_symbol {
            counts.push(run_count);
            masses.push(run_mass);
            run_symbol = frame.atom_data[i].symbol.clone();
            run_count = 0;
            run_mass = frame.masses.get_f64(i);
        }
        run_count += 1;
    }
    counts.push(run_count);
    masses.push(run_mass);
    frame.header.natm_types = counts.len();
    frame.header.natms_per_type = counts;
    frame.header.masses_per_type = masses;
}

fn remap_bonds(frame: &mut ConFrame, perm: &[usize]) -> Result<(), CorrespondenceError> {
    let bonds = frame.bonds();
    if bonds.is_empty() {
        return Ok(());
    }
    let n = perm.len();
    let mut inverse = vec![0usize; n];
    for (i, &j) in perm.iter().enumerate() {
        inverse[j] = i;
    }
    let mut mapped = Vec::with_capacity(bonds.len());
    for bond in bonds {
        if bond.i as usize >= n {
            return Err(CorrespondenceError::BondEndpoint {
                index: bond.i,
                atoms: n,
            });
        }
        if bond.j as usize >= n {
            return Err(CorrespondenceError::BondEndpoint {
                index: bond.j,
                atoms: n,
            });
        }
        mapped.push(Bond {
            i: inverse[bond.i as usize] as u32,
            j: inverse[bond.j as usize] as u32,
            order: bond.order,
        });
    }
    frame.header.set_bonds(&mapped);
    Ok(())
}

/// The atoms of `frame` at `indices`, in that order, as a frame of their own.
///
/// `indices` are `atom_data` indices. Each selected atom keeps its
/// position, symbol, mass, fixed flags and `atom_id`, and its row of every
/// per-atom section the frame carries: velocities, forces, energies,
/// charges, spins, magnetic moments, displacements and spreads. The cell,
/// the header lines, the metadata and the per-frame scalars are those of
/// `frame`. A bond is kept, with its endpoints renumbered, when both of
/// its atoms are selected, and dropped otherwise. Type counts are rebuilt
/// from the new order, so the result writes as CON when that order is
/// type-grouped.
///
/// The ids are what ties the sub-frame back to its source: an atom of the
/// result is the atom of `frame` with the same `atom_id`.
///
/// # Errors
///
/// [`CorrespondenceError::AtomIndex`] for an index outside the frame,
/// [`CorrespondenceError::RepeatedIndex`] for an index given twice, and
/// [`CorrespondenceError::SectionLength`] for a per-atom section whose
/// length is neither zero nor the atom count.
pub fn subframe(frame: &ConFrame, indices: &[usize]) -> Result<ConFrame, CorrespondenceError> {
    let n = frame.atom_data.len();
    let mut position_of_index: std::collections::HashMap<usize, usize> =
        std::collections::HashMap::with_capacity(indices.len());
    for (position, &index) in indices.iter().enumerate() {
        if index >= n {
            return Err(CorrespondenceError::AtomIndex { index, atoms: n });
        }
        if let Some(&first_position) = position_of_index.get(&index) {
            return Err(CorrespondenceError::RepeatedIndex {
                index,
                first_position,
                position,
            });
        }
        position_of_index.insert(index, position);
    }
    let mut out = frame.clone();
    let mut atoms = Vec::with_capacity(indices.len());
    for &j in indices {
        let mut atom = frame.atom_data[j].clone();
        overlay_sections(&mut atom, frame, j)?;
        atoms.push(atom);
    }
    out.atom_data = atoms;
    out.positions = select_rows(&frame.positions, indices, n, "positions")?;
    out.velocities = select_rows(&frame.velocities, indices, n, "velocities")?.into();
    out.forces = select_rows(&frame.forces, indices, n, "forces")?.into();
    out.magmoms = select_rows(&frame.magmoms, indices, n, "magmoms")?.into();
    out.displacements = select_rows(&frame.displacements, indices, n, "displacements")?.into();
    out.spreads = select_rows(&frame.spreads, indices, n, "spreads")?.into();
    out.atom_energies = select_col(&frame.atom_energies, indices, n, "energies")?.into();
    out.charges = select_col(&frame.charges, indices, n, "charges")?.into();
    out.spins = select_col(&frame.spins, indices, n, "spins")?.into();
    out.masses = select_col(&frame.masses, indices, n, "masses")?;
    let ids: Vec<u64> = indices
        .iter()
        .map(|&j| frame.atom_data[j].atom_id)
        .collect();
    out.atom_ids = ndarray::Array1::from_vec(ids).into_shared();
    refresh_type_runs(&mut out);
    let kept: Vec<Bond> = frame
        .bonds()
        .into_iter()
        .filter_map(|bond| {
            let i = position_of_index.get(&(bond.i as usize))?;
            let j = position_of_index.get(&(bond.j as usize))?;
            Some(Bond {
                i: *i as u32,
                j: *j as u32,
                order: bond.order,
            })
        })
        .collect();
    if !frame.bonds().is_empty() {
        out.header.set_bonds(&kept);
    }
    Ok(out)
}

fn select_rows(
    src: &FloatArray2,
    indices: &[usize],
    atoms: usize,
    section: &'static str,
) -> Result<FloatArray2, CorrespondenceError> {
    if src.nrows() == 0 {
        return Ok(FloatArray2::zeros(src.kind(), 0, 3));
    }
    if src.nrows() != atoms {
        return Err(CorrespondenceError::SectionLength {
            section,
            rows: src.nrows(),
            atoms,
        });
    }
    let mut out = FloatArray2::zeros(src.kind(), indices.len(), src.ncols().max(3));
    for (i, &j) in indices.iter().enumerate() {
        out.set_f64_row(i, src.as_f64_row(j));
    }
    Ok(out)
}

fn select_col(
    src: &FloatArray1,
    indices: &[usize],
    atoms: usize,
    section: &'static str,
) -> Result<FloatArray1, CorrespondenceError> {
    if src.is_empty() {
        return Ok(FloatArray1::zeros(src.kind(), 0));
    }
    if src.len() != atoms {
        return Err(CorrespondenceError::SectionLength {
            section,
            rows: src.len(),
            atoms,
        });
    }
    let mut out = FloatArray1::zeros(src.kind(), indices.len());
    for (i, &j) in indices.iter().enumerate() {
        out.set_f64(i, src.get_f64(j));
    }
    Ok(out)
}

/// Walk `frames` in order. Frame 0 is the reference.
///
/// The error is the first frame that disagrees with frame 0, and the
/// atom involved. A one-frame sequence checks that its ids are unique.
pub fn check_atom_id_consistency(
    frames: &[ConFrame],
    check: IdentityCheck,
) -> Result<(), CorrespondenceError> {
    let refs: Vec<&ConFrame> = frames.iter().collect();
    check_atom_id_consistency_refs(&refs, check)
}

pub(crate) fn check_atom_id_consistency_refs(
    frames: &[&ConFrame],
    check: IdentityCheck,
) -> Result<(), CorrespondenceError> {
    let Some(reference) = frames.first() else {
        return Err(CorrespondenceError::EmptySequence);
    };
    if frames.len() == 1 {
        index_ids(&reference.atom_data, 0)?;
        return Ok(());
    }
    for (i, frame) in frames.iter().enumerate().skip(1) {
        atom_id_permutation_at(reference, frame, i, check)?;
    }
    Ok(())
}

/// Minimum-image displacement of each reference atom toward the atom in
/// `other` with the same `atom_id`.
///
/// Row `i` is the wrapped `r_other - r_reference` for reference atom `i`.
/// The cell and the periodic flags are the reference frame's
/// [`FrameHeader::cell_matrix`] and [`FrameHeader::pbc_effective`].
pub fn minimum_image_displacements(
    reference: &ConFrame,
    other: &ConFrame,
    check: IdentityCheck,
) -> Result<Vec<[f64; 3]>, CorrespondenceError> {
    let perm = atom_id_permutation(reference, other, check)?;
    let cell = reference.header.cell_matrix();
    let pbc = reference.header.pbc_effective();
    let mut out = Vec::with_capacity(perm.len());
    for (i, &j) in perm.iter().enumerate() {
        let ra = position_of(reference, i)?;
        let rb = position_of(other, j)?;
        if !finite3(ra) {
            return Err(CorrespondenceError::NonFiniteCoordinate {
                frame_index: 0,
                atom_id: reference.atom_data[i].atom_id,
                atom_index: i,
            });
        }
        if !finite3(rb) {
            return Err(CorrespondenceError::NonFiniteCoordinate {
                frame_index: 1,
                atom_id: other.atom_data[j].atom_id,
                atom_index: j,
            });
        }
        let delta = [rb[0] - ra[0], rb[1] - ra[1], rb[2] - ra[2]];
        out.push(minimum_image_delta(cell, pbc, delta)?);
    }
    Ok(out)
}

fn finite3(v: [f64; 3]) -> bool {
    v.iter().all(|x| x.is_finite())
}

/// Wrap one cartesian delta into the reference cell.
///
/// `cell` is a [`FrameHeader::cell_matrix`]: each row is a lattice vector.
/// With every axis periodic, fractional coordinates are `delta * cell^{-1}`
/// (row vector on the left) and each axis subtracts the nearest integer.
/// `f64::round` breaks a half-integer toward ±infinity, away from zero.
///
/// An open axis is not wrapped through that full inverse. One periodic
/// vector is a rounding along it. Two periodic vectors are Gauss-reduced
/// and the nine neighbours of the rounded image are searched. That result
/// can differ from the per-axis fractional wrap three periodic axes still
/// use, and it can be shorter. The component normal to the periodic
/// vectors is left as it is.
pub fn minimum_image_delta(
    cell: [[f64; 3]; 3],
    pbc: [bool; 3],
    delta: [f64; 3],
) -> Result<[f64; 3], CorrespondenceError> {
    if !finite3(delta) {
        return Err(CorrespondenceError::NonFiniteDelta);
    }
    let mut rows = [[0.0; 3]; 2];
    let mut n = 0usize;
    for axis in 0..3 {
        if pbc[axis] {
            if n < 2 {
                rows[n] = cell[axis];
            }
            n += 1;
        }
    }
    match n {
        0 => Ok(delta),
        1 => wrap_wire(delta, rows[0]),
        2 => wrap_slab(delta, rows[0], rows[1]),
        _ => wrap_full(cell, delta),
    }
}

fn wrap_full(cell: [[f64; 3]; 3], delta: [f64; 3]) -> Result<[f64; 3], CorrespondenceError> {
    let (inv, _) = invert_cell(cell).ok_or(CorrespondenceError::SingularCell {
        determinant: det3(cell),
    })?;
    let mut frac = mul_row(delta, inv);
    for component in &mut frac {
        *component -= component.round();
    }
    Ok(mul_row(frac, cell))
}

fn wrap_wire(delta: [f64; 3], axis: [f64; 3]) -> Result<[f64; 3], CorrespondenceError> {
    let length2 = dot(axis, axis);
    if !length2.is_finite() || length2 <= 0.0 {
        return Err(CorrespondenceError::SingularCell {
            determinant: length2,
        });
    }
    let steps = (dot(delta, axis) / length2).round();
    Ok(axpy(delta, -steps, axis))
}

fn wrap_slab(delta: [f64; 3], u: [f64; 3], v: [f64; 3]) -> Result<[f64; 3], CorrespondenceError> {
    if plane_duals(u, v).is_none() {
        return Err(CorrespondenceError::SingularCell {
            determinant: gram_det(u, v),
        });
    }
    let reduced = lagrange_reduce(u, v);
    let Some((dual, _)) = plane_duals(reduced[0], reduced[1]) else {
        return Err(CorrespondenceError::SingularCell {
            determinant: gram_det(reduced[0], reduced[1]),
        });
    };
    let along_u = dot(delta, dual[0]).round();
    let along_v = dot(delta, dual[1]).round();
    let mut best = axpy(axpy(delta, -along_u, reduced[0]), -along_v, reduced[1]);
    let mut best_n2 = dot(best, best);
    for i in -1i32..=1 {
        for j in -1i32..=1 {
            let cand = axpy(
                axpy(delta, -(along_u + f64::from(i)), reduced[0]),
                -(along_v + f64::from(j)),
                reduced[1],
            );
            let cand_n2 = dot(cand, cand);
            // A tie, or a difference below this floor, keeps the rounded
            // image. A shorter neighbour replaces it.
            if cand_n2 + 1e-12 * (1.0 + best_n2) < best_n2 {
                best = cand;
                best_n2 = cand_n2;
            }
        }
    }
    Ok(best)
}

fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}

fn axpy(y: [f64; 3], alpha: f64, x: [f64; 3]) -> [f64; 3] {
    [
        y[0] + alpha * x[0],
        y[1] + alpha * x[1],
        y[2] + alpha * x[2],
    ]
}

fn gram_det(u: [f64; 3], v: [f64; 3]) -> f64 {
    let uu = dot(u, u);
    let vv = dot(v, v);
    let uv = dot(u, v);
    uu * vv - uv * uv
}

/// In-plane duals. `dual[i] · basis[j]` is the Kronecker delta, and each
/// dual lies in the plane of the basis. `None` when the pair is
/// collinear or non-finite.
fn plane_duals(u: [f64; 3], v: [f64; 3]) -> Option<([[f64; 3]; 2], f64)> {
    let uu = dot(u, u);
    let vv = dot(v, v);
    let uv = dot(u, v);
    let det = gram_det(u, v);
    let bound = 1e-24 * uu * vv;
    if !det.is_finite() || !bound.is_finite() || det <= bound {
        return None;
    }
    let inv = 1.0 / det;
    let dual_u = axpy(
        [vv * inv * u[0], vv * inv * u[1], vv * inv * u[2]],
        -uv * inv,
        v,
    );
    let dual_v = axpy(
        [uu * inv * v[0], uu * inv * v[1], uu * inv * v[2]],
        -uv * inv,
        u,
    );
    Some(([dual_u, dual_v], det))
}

/// Gauss reduction of a two-dimensional lattice basis.
fn lagrange_reduce(mut u: [f64; 3], mut v: [f64; 3]) -> [[f64; 3]; 2] {
    if dot(u, u) > dot(v, v) {
        std::mem::swap(&mut u, &mut v);
    }
    for _ in 0..128 {
        let mu = (dot(u, v) / dot(u, u)).round();
        if mu != 0.0 {
            v = axpy(v, -mu, u);
        }
        if dot(v, v) >= dot(u, u) {
            break;
        }
        std::mem::swap(&mut u, &mut v);
    }
    [u, v]
}

fn det3(m: [[f64; 3]; 3]) -> f64 {
    m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
        - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
        + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
}

fn invert_cell(m: [[f64; 3]; 3]) -> Option<([[f64; 3]; 3], f64)> {
    let det = det3(m);
    if !det.is_finite() || det.abs() < 1e-18 {
        return None;
    }
    let inv_det = 1.0 / det;
    let c00 = m[1][1] * m[2][2] - m[1][2] * m[2][1];
    let c01 = -(m[1][0] * m[2][2] - m[1][2] * m[2][0]);
    let c02 = m[1][0] * m[2][1] - m[1][1] * m[2][0];
    let c10 = -(m[0][1] * m[2][2] - m[0][2] * m[2][1]);
    let c11 = m[0][0] * m[2][2] - m[0][2] * m[2][0];
    let c12 = -(m[0][0] * m[2][1] - m[0][1] * m[2][0]);
    let c20 = m[0][1] * m[1][2] - m[0][2] * m[1][1];
    let c21 = -(m[0][0] * m[1][2] - m[0][2] * m[1][0]);
    let c22 = m[0][0] * m[1][1] - m[0][1] * m[1][0];
    let inv = [
        [c00 * inv_det, c10 * inv_det, c20 * inv_det],
        [c01 * inv_det, c11 * inv_det, c21 * inv_det],
        [c02 * inv_det, c12 * inv_det, c22 * inv_det],
    ];
    Some((inv, det))
}

/// Row vector times a row-major matrix.
fn mul_row(v: [f64; 3], m: [[f64; 3]; 3]) -> [f64; 3] {
    [
        v[0] * m[0][0] + v[1] * m[1][0] + v[2] * m[2][0],
        v[0] * m[0][1] + v[1] * m[1][1] + v[2] * m[2][1],
        v[0] * m[0][2] + v[1] * m[1][2] + v[2] * m[2][2],
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::cell_vectors;

    fn close(a: [f64; 3], b: [f64; 3]) {
        for k in 0..3 {
            assert!(
                (a[k] - b[k]).abs() < 1e-9,
                "component {k}: {} vs {}",
                a[k],
                b[k]
            );
        }
    }

    #[test]
    fn orthogonal_wrap_uses_the_cell_matrix() {
        let cell = cell_vectors([10.0, 12.0, 14.0], [90.0, 90.0, 90.0]);
        let wrapped = minimum_image_delta(cell, [true, true, true], [9.0, 0.0, 0.0]).unwrap();
        close(wrapped, [-1.0, 0.0, 0.0]);
        let open = minimum_image_delta(cell, [false, true, true], [9.0, 9.0, 0.0]).unwrap();
        close(open, [9.0, -3.0, 0.0]);
    }

    #[test]
    fn a_lattice_vector_wraps_to_zero() {
        let cell = cell_vectors([10.0, 12.0, 14.0], [80.0, 90.0, 70.0]);
        let along_a = minimum_image_delta(cell, [true, true, true], cell[0]).unwrap();
        close(along_a, [0.0, 0.0, 0.0]);
        let along_b = minimum_image_delta(cell, [true, true, true], cell[1]).unwrap();
        close(along_b, [0.0, 0.0, 0.0]);
    }

    #[test]
    fn a_flat_cell_is_rejected() {
        let err = minimum_image_delta([[0.0; 3]; 3], [true; 3], [1.0, 0.0, 0.0]).unwrap_err();
        assert!(matches!(err, CorrespondenceError::SingularCell { .. }));
        assert!(err.to_string().contains("singular"));
    }

    #[test]
    fn a_collapsed_slab_is_rejected() {
        let cell = [[1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 0.0, 1.0]];
        let err = minimum_image_delta(cell, [true, true, false], [0.1, 0.2, 0.3]).unwrap_err();
        assert!(matches!(err, CorrespondenceError::SingularCell { .. }));
        assert!(err.to_string().contains("singular"));
    }

    #[test]
    fn an_open_cell_keeps_the_cartesian_delta() {
        let delta = [1.5, -2.0, 0.25];
        let kept = minimum_image_delta([[0.0; 3]; 3], [false; 3], delta).unwrap();
        close(kept, delta);
    }

    #[test]
    fn a_wire_wraps_only_along_its_axis() {
        let cell = cell_vectors([10.0, 12.0, 14.0], [90.0, 90.0, 90.0]);
        let wrapped = minimum_image_delta(cell, [false, false, true], [1.0, 2.0, 9.0]).unwrap();
        close(wrapped, [1.0, 2.0, -5.0]);
    }

    #[test]
    fn a_near_flat_slab_keeps_a_small_out_of_plane_step() {
        let cell = cell_vectors([5.0, 5.0, 3.0], [86.892, 16.892, 70.0]);
        assert!(
            cell[2][2].abs() < 1e-6,
            "c_z {} should be near 1e-8",
            cell[2][2]
        );
        let delta = [0.02, -0.01, 0.275];
        let wrapped = minimum_image_delta(cell, [true, true, false], delta).unwrap();
        close(wrapped, delta);
        assert!(
            wrapped.iter().all(|component| component.abs() < 1.0),
            "{wrapped:?}"
        );
    }
}