cgkitten 0.2.0

Convert mmCIF/PDB protein structures to coarse-grained representation with Monte Carlo titration
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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
//! Convert mmCIF protein structures to coarse-grained xyzq representation.
//!
//! Each amino acid residue is represented as a single bead at its center of mass.
//! Titratable side-chains (ASP, GLU, HIS, CYS, TYR, LYS, ARG) generate an
//! additional bead at the charge center. Charges are computed via
//! [`ChargeCalc`], which supports Henderson-Hasselbalch and Monte Carlo titration.
//!
//! ```no_run
//! let cif_data = std::fs::read("structure.cif").unwrap();
//! let beads = cgkitten::coarse_grain(cif_data.as_slice());
//! let result = cgkitten::ChargeCalc::new()
//!     .ph(7.0)
//!     .mc(10000)
//!     .run(&beads);
//! let charged = result.apply(&beads);
//! ```

#![warn(missing_docs)]

pub(crate) mod charge;
/// Force field model definitions.
pub mod forcefield;
pub(crate) mod mc;
pub(crate) mod mmcif;
pub(crate) mod pdb;
/// Amino acid residue definitions and constants.
pub mod residue;
/// Topology type assignment for coarse-grained beads.
pub mod topology;

use std::collections::{HashMap, HashSet};
use std::fmt::Write as FmtWrite;
use std::io::BufRead;
use std::path::Path;

use log::{debug, info};

use charge::{ChargeCalculator, Conditions, HendersonHasselbalch};
use mmcif::{AtomRecord, DisulfideBond, ParseOptions};
use residue::{CTERM_GROUP, NTERM_GROUP, TitratableGroup};

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// A coarse-grained bead with position and charge.
#[derive(Clone, Debug)]
pub struct Bead {
    /// X coordinate in Ångströms.
    pub x: f64,
    /// Y coordinate in Ångströms.
    pub y: f64,
    /// Z coordinate in Ångströms.
    pub z: f64,
    /// Partial charge in elementary charge units.
    pub charge: f64,
    /// Mass in Da (sum of constituent atom masses).
    pub mass: f64,
    /// Source residue name (e.g., "ALA", "ZN").
    pub res_name: String,
    /// Chain identifier.
    pub chain_id: String,
    /// Residue sequence number.
    pub res_seq: i32,
    /// Bead classification.
    pub bead_type: BeadType,
}

/// Classification of a coarse-grained bead.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BeadType {
    /// Center-of-mass bead carrying the full residue mass (backbone + sidechain atoms).
    Residue,
    /// Massless virtual bead placed at the titratable charge centre (e.g. Glu OE1/OE2).
    Virtual,
    /// N-terminal group.
    Ntr,
    /// C-terminal group.
    Ctr,
    /// Metal ion.
    Ion,
    /// Single-bead residue that is also titratable (used by SingleBead policy).
    Titratable,
}

impl BeadType {
    /// True for bead types that carry a titratable charge (virtual, N-/C-terminal, titratable).
    pub fn is_titratable(self) -> bool {
        matches!(
            self,
            Self::Virtual | Self::Ntr | Self::Ctr | Self::Titratable
        )
    }
}

impl std::fmt::Display for BeadType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Residue => write!(f, "residue"),
            Self::Virtual => write!(f, "virtual"),
            Self::Ntr => write!(f, "NTR"),
            Self::Ctr => write!(f, "CTR"),
            Self::Ion => write!(f, "ion"),
            Self::Titratable => write!(f, "titratable"),
        }
    }
}

/// Charge calculation builder.
///
/// Configures pH, temperature, ionic strength, and charge method (Henderson-Hasselbalch
/// or Monte Carlo). Use [`run`](ChargeCalc::run) to compute per-bead charges and multipole moments.
///
/// ```ignore
/// // Builder pattern
/// let result = ChargeCalc::new().ph(7.4).mc(10000).run(&beads);
///
/// // Direct construction
/// let result = ChargeCalc { ph: 7.4, mc: 10000, ..Default::default() }.run(&beads);
///
/// // Serde (with "serde" feature)
/// let calc: ChargeCalc = serde_json::from_str(r#"{"ph": 7.4, "mc": 10000}"#)?;
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct ChargeCalc {
    /// pH for charge calculation (default 7.0).
    pub ph: f64,
    /// Temperature in Kelvin (default 298.15).
    pub temperature: f64,
    /// Ionic strength in mol/L (default 0.1).
    pub ionic_strength: f64,
    /// Monte Carlo sweeps per titratable site (0 = Henderson-Hasselbalch only).
    pub mc: usize,
}

impl Default for ChargeCalc {
    fn default() -> Self {
        Self {
            ph: 7.0,
            temperature: 298.15,
            ionic_strength: 0.1,
            mc: 0,
        }
    }
}

impl ChargeCalc {
    /// Create a new charge calculator with default settings (pH 7.0, HH).
    pub fn new() -> Self {
        Self::default()
    }

    /// Set pH.
    pub fn ph(mut self, ph: f64) -> Self {
        self.ph = ph;
        self
    }

    /// Set temperature in Kelvin.
    pub fn temperature(mut self, t: f64) -> Self {
        self.temperature = t;
        self
    }

    /// Set ionic strength in mol/L.
    pub fn ionic_strength(mut self, i: f64) -> Self {
        self.ionic_strength = i;
        self
    }

    /// Set Monte Carlo sweeps (0 = Henderson-Hasselbalch only).
    pub fn mc(mut self, sweeps: usize) -> Self {
        self.mc = sweeps;
        self
    }

    /// Log physical conditions (pH, T, I, Bjerrum/Debye lengths).
    pub fn log_conditions(&self) {
        let lb = mc::bjerrum_length(self.temperature);
        let ld = mc::debye_length(self.temperature, self.ionic_strength);
        info!(
            "pH={:.2} T={:.1} K I={:.3} M λ_B={:.2} Å λ_D={:.2} Å",
            self.ph, self.temperature, self.ionic_strength, lb, ld,
        );
    }

    /// Compute per-bead charges and multipole moments.
    pub fn run(&self, beads: &[Bead]) -> ChargeResult {
        let conditions = Conditions::from(self);

        if self.mc > 0 {
            let mut engine = mc::TitrationMC::new(beads, &conditions);
            let n_sites = engine.num_sites();
            debug!(
                "MC titration: {} sweeps × {} sites = {} trial moves",
                self.mc,
                n_sites,
                self.mc * n_sites,
            );
            let mut rng = rand::thread_rng();
            let mc_result = engine.run(self.mc, &mut rng);
            ChargeResult {
                multipole: Multipole {
                    charge: mc_result.mean_charge,
                    charge_sq: mc_result.mean_charge_sq,
                    dipole: mc_result.mean_dipole,
                    dipole_sq: mc_result.mean_dipole_sq,
                },
                charges: mc_result.charges,
            }
        } else {
            let hh = HendersonHasselbalch;
            let rn = res_name_map(beads);
            // Start from existing charges so non-titratable beads (e.g. metal ions) keep theirs
            let mut charges: Vec<f64> = beads.iter().map(|b| b.charge).collect();
            for (i, b) in beads.iter().enumerate() {
                if let Some(group) = titratable_group_for_bead(b, &rn) {
                    charges[i] = hh.charge(group, &conditions);
                }
            }
            let multipole = compute_multipole(beads, &charges);
            ChargeResult { multipole, charges }
        }
    }
}

/// Multipole moments: net charge and dipole with their squares.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Multipole {
    /// Net charge ⟨Z⟩.
    pub charge: f64,
    /// ⟨Z²⟩ (equals Z² for HH; ensemble average for MC).
    pub charge_sq: f64,
    /// Dipole moment magnitude ⟨μ⟩ in e·Å.
    pub dipole: f64,
    /// ⟨μ²⟩ in (e·Å)².
    pub dipole_sq: f64,
}

/// Result of a charge calculation.
#[derive(Clone, Debug)]
pub struct ChargeResult {
    /// Multipole moments.
    pub multipole: Multipole,
    /// Per-bead charges (same indexing as input beads).
    pub charges: Vec<f64>,
}

impl ChargeResult {
    /// Apply computed charges to beads, returning new beads.
    pub fn apply(&self, beads: &[Bead]) -> Vec<Bead> {
        beads
            .iter()
            .enumerate()
            .map(|(i, b)| Bead {
                charge: self.charges[i],
                ..b.clone()
            })
            .collect()
    }
}

// ---------------------------------------------------------------------------
// Coarse-graining trait and implementations
// ---------------------------------------------------------------------------

/// Convert one amino acid residue into beads (backbone/sidechain only, not terminals).
pub trait CoarseGrain {
    /// Convert one amino acid residue into beads.
    fn residue_to_beads(
        &self,
        key: &ResidueKey,
        atoms: &[&AtomRecord],
        is_ss_bonded: bool,
    ) -> Vec<Bead>;
}

/// Look up the titratable group for a residue, returning `None` for SS-bonded CYS.
fn titratable_group_unless_ss(
    key: &ResidueKey,
    res_name: &str,
    is_ss_bonded: bool,
) -> Option<&'static residue::TitratableGroup> {
    if res_name == "CYS" && is_ss_bonded {
        debug!(
            "Skipping titration for SS-bonded CYS {}:{}",
            key.chain_id, key.res_seq
        );
        return None;
    }
    residue::find_titratable_group(res_name)
}

/// Create a residue bead at the geometric center of the given atoms.
fn make_residue_bead(key: &ResidueKey, atoms: &[&AtomRecord], bead_type: BeadType) -> Bead {
    let ((cx, cy, cz), mass) = center_and_mass(atoms).unwrap();
    Bead {
        x: cx,
        y: cy,
        z: cz,
        charge: 0.0,
        mass,
        res_name: atoms[0].res_name.clone(),
        chain_id: key.chain_id.clone(),
        res_seq: key.res_seq,
        bead_type,
    }
}

/// Multi-bead coarse-graining: one backbone bead + optional sidechain bead per titratable residue.
pub struct MultiBead;

impl CoarseGrain for MultiBead {
    fn residue_to_beads(
        &self,
        key: &ResidueKey,
        atoms: &[&AtomRecord],
        is_ss_bonded: bool,
    ) -> Vec<Bead> {
        let mut beads = vec![make_residue_bead(key, atoms, BeadType::Residue)];

        if let Some(group) = titratable_group_unless_ss(key, &atoms[0].res_name, is_ss_bonded)
            && let Some(bead) = make_titratable_bead(key, atoms, group, BeadType::Virtual)
        {
            beads.push(bead);
        }

        beads
    }
}

/// Single-bead coarse-graining: one bead per residue. Titratable residues get `BeadType::Titratable`.
pub struct SingleBead;

impl CoarseGrain for SingleBead {
    fn residue_to_beads(
        &self,
        key: &ResidueKey,
        atoms: &[&AtomRecord],
        is_ss_bonded: bool,
    ) -> Vec<Bead> {
        let bead_type =
            if titratable_group_unless_ss(key, &atoms[0].res_name, is_ss_bonded).is_some() {
                BeadType::Titratable
            } else {
                BeadType::Residue
            };

        vec![make_residue_bead(key, atoms, bead_type)]
    }
}

// ---------------------------------------------------------------------------
// Public functions
// ---------------------------------------------------------------------------

/// Filter beads to keep only the requested chains.
///
/// If `chains` is empty, all beads are returned unchanged.
pub fn filter_chains(beads: Vec<Bead>, chains: &[impl AsRef<str>]) -> Vec<Bead> {
    if chains.is_empty() {
        return beads;
    }
    let kept: Vec<_> = beads
        .into_iter()
        .filter(|b| chains.iter().any(|c| c.as_ref() == b.chain_id))
        .collect();
    info!("Chain filter: {} beads retained", kept.len());
    kept
}

/// Convert mmCIF data to coarse-grained beads using the default multi-bead policy.
///
/// Reads atom records, groups by residue, and creates backbone and titratable
/// side-chain beads. Charges are set to 0.0 for titratable sites; use
/// [`ChargeCalc::run`] to compute charges.
///
/// Metal ions retain their formal charges.
pub fn coarse_grain<R: BufRead>(reader: R) -> Vec<Bead> {
    coarse_grain_with(reader, &MultiBead)
}

/// Convert mmCIF data to coarse-grained beads using the given policy.
pub fn coarse_grain_with<R: BufRead>(reader: R, policy: &dyn CoarseGrain) -> Vec<Bead> {
    let parsed = mmcif::parse_mmcif(reader, &ParseOptions::default());
    debug!(
        "Parsed {} atom records, {} disulfide bonds from _struct_conn",
        parsed.atoms.len(),
        parsed.disulfide_bonds.len(),
    );
    beads_from_parsed(&parsed, policy)
}

/// Convert PDB data to coarse-grained beads using the given policy.
pub fn coarse_grain_pdb_with<R: BufRead>(reader: R, policy: &dyn CoarseGrain) -> Vec<Bead> {
    let parsed = pdb::parse_pdb(reader, &ParseOptions::default());
    debug!(
        "Parsed {} atom records, {} SSBOND disulfide bonds from PDB",
        parsed.atoms.len(),
        parsed.disulfide_bonds.len(),
    );
    beads_from_parsed(&parsed, policy)
}

// Both coarse_grain_with and coarse_grain_pdb_with produce a ParsedMmcif, so the
// downstream bead-building logic is shared here rather than duplicated per format.
fn beads_from_parsed(parsed: &mmcif::ParsedMmcif, policy: &dyn CoarseGrain) -> Vec<Bead> {
    records_to_beads(&parsed.atoms, &parsed.disulfide_bonds, policy)
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Unique residue key for grouping atoms, used in the [`CoarseGrain`] trait.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ResidueKey {
    /// Chain identifier.
    pub chain_id: String,
    /// Residue sequence number.
    pub res_seq: i32,
    /// Insertion code.
    pub i_code: String,
}

/// Convert atom records to coarse-grained beads (geometry only).
fn records_to_beads(
    records: &[AtomRecord],
    disulfide_bonds: &[DisulfideBond],
    policy: &dyn CoarseGrain,
) -> Vec<Bead> {
    // Group atoms by residue
    let mut residue_groups: Vec<(ResidueKey, Vec<&AtomRecord>)> = Vec::new();
    let mut key_to_index: HashMap<ResidueKey, usize> = HashMap::new();

    // Separate metal ions
    let mut metal_beads = Vec::new();

    for record in records {
        if residue::is_metal_ion(record) {
            metal_beads.push(Bead {
                x: record.x,
                y: record.y,
                z: record.z,
                charge: metal_charge(&record.res_name),
                mass: residue::atomic_mass(&record.element),
                res_name: record.res_name.clone(),
                chain_id: record.chain_id.clone(),
                res_seq: record.res_seq,
                bead_type: BeadType::Ion,
            });
            continue;
        }

        if !residue::is_amino_acid(&record.res_name) {
            continue;
        }

        let key = ResidueKey {
            chain_id: record.chain_id.clone(),
            res_seq: record.res_seq,
            i_code: record.i_code.clone(),
        };

        if let Some(&idx) = key_to_index.get(&key) {
            residue_groups[idx].1.push(record);
        } else {
            let idx = residue_groups.len();
            key_to_index.insert(key.clone(), idx);
            residue_groups.push((key, vec![record]));
        }
    }

    debug!(
        "{} residues, {} metal ions",
        residue_groups.len(),
        metal_beads.len()
    );

    let ss_bonded = if disulfide_bonds.is_empty() {
        debug!("No _struct_conn disulfides, using geometric detection");
        find_disulfide_bonds_geometric(&residue_groups)
    } else {
        disulfide_bonds_to_keys(disulfide_bonds)
    };
    if ss_bonded.is_empty() {
        info!("No disulfide bonds detected");
    } else {
        info!("{} disulfide-bonded CYS residues detected", ss_bonded.len());
    }

    let chain_first_last = find_chain_terminals(&residue_groups);

    let mut beads = Vec::new();

    for (key, atoms) in &residue_groups {
        let is_ss_bonded = atoms[0].res_name == "CYS" && ss_bonded.contains(key);

        // Delegate per-residue bead creation to the policy
        beads.extend(policy.residue_to_beads(key, atoms, is_ss_bonded));

        // Terminal beads (shared across all policies)
        if let Some(&(first_idx, last_idx)) = chain_first_last.get(&key.chain_id) {
            let idx = key_to_index[key];
            if idx == first_idx
                && let Some(bead) = make_titratable_bead(key, atoms, &NTERM_GROUP, BeadType::Ntr)
            {
                beads.push(bead);
            }
            if idx == last_idx
                && let Some(bead) = make_titratable_bead(key, atoms, &CTERM_GROUP, BeadType::Ctr)
            {
                beads.push(bead);
            }
        }
    }

    beads.extend(metal_beads);

    let n_titratable = beads.iter().filter(|b| b.bead_type.is_titratable()).count();

    info!(
        "{} residues, {} titratable sites",
        residue_groups.len(),
        n_titratable,
    );

    beads
}

/// Compute multipole moments from beads and external charges.
fn compute_multipole(beads: &[Bead], charges: &[f64]) -> Multipole {
    let charge: f64 = charges.iter().sum();
    let (mut mx, mut my, mut mz) = (0.0, 0.0, 0.0);
    for (b, &q) in beads.iter().zip(charges) {
        mx += q * b.x;
        my += q * b.y;
        mz += q * b.z;
    }
    let dipole = mz.mul_add(mz, mx.mul_add(mx, my * my)).sqrt();
    Multipole {
        charge,
        charge_sq: charge * charge,
        dipole,
        dipole_sq: dipole * dipole,
    }
}

/// Map (chain_id, res_seq) → residue name from backbone/titratable beads.
pub(crate) fn res_name_map(beads: &[Bead]) -> HashMap<(String, i32), String> {
    beads
        .iter()
        .filter(|b| matches!(b.bead_type, BeadType::Residue | BeadType::Titratable))
        .map(|b| ((b.chain_id.clone(), b.res_seq), b.res_name.clone()))
        .collect()
}

/// Look up the titratable group for a bead, if any.
pub(crate) fn titratable_group_for_bead(
    bead: &Bead,
    res_names: &HashMap<(String, i32), String>,
) -> Option<&'static TitratableGroup> {
    match bead.bead_type {
        BeadType::Virtual => res_names
            .get(&(bead.chain_id.clone(), bead.res_seq))
            .and_then(|name| residue::find_titratable_group(name)),
        BeadType::Titratable => residue::find_titratable_group(&bead.res_name),
        BeadType::Ntr => Some(&NTERM_GROUP),
        BeadType::Ctr => Some(&CTERM_GROUP),
        _ => None,
    }
}

/// Compute geometric center (unweighted) and total mass of atoms in a single pass.
/// Uses geometric center rather than mass-weighted center; conventional for CG bead placement.
fn center_and_mass(atoms: &[&AtomRecord]) -> Option<((f64, f64, f64), f64)> {
    if atoms.is_empty() {
        return None;
    }
    let (weighted, mass) = atoms
        .iter()
        .fold(((0.0, 0.0, 0.0), 0.0), |((sx, sy, sz), m), a| {
            let am = residue::atomic_mass(&a.element);
            ((sx + a.x * am, sy + a.y * am, sz + a.z * am), m + am)
        });
    Some((
        (weighted.0 / mass, weighted.1 / mass, weighted.2 / mass),
        mass,
    ))
}

/// Create a titratable bead at the group's charge center (charge = 0.0).
fn make_titratable_bead(
    key: &ResidueKey,
    atoms: &[&AtomRecord],
    group: &TitratableGroup,
    bead_type: BeadType,
) -> Option<Bead> {
    let center_atoms: Vec<&AtomRecord> = atoms
        .iter()
        .filter(|a| group.center_atoms.contains(&a.name.as_str()))
        .copied()
        .collect();
    let ((x, y, z), _mass) = center_and_mass(&center_atoms)?;
    Some(Bead {
        x,
        y,
        z,
        charge: 0.0,
        mass: 0.0, // mass already accounted for in the main residue bead at COM
        // Named by element (O, N, S) to distinguish from backbone beads (which use residue name)
        res_name: group.element.to_string(),
        chain_id: key.chain_id.clone(),
        res_seq: key.res_seq,
        bead_type,
    })
}

/// Convert parsed `_struct_conn` disulfide bonds to a set of residue keys.
fn disulfide_bonds_to_keys(bonds: &[DisulfideBond]) -> HashSet<ResidueKey> {
    bonds
        .iter()
        .flat_map(|bond| {
            [
                ResidueKey {
                    chain_id: bond.chain_id_1.clone(),
                    res_seq: bond.res_seq_1,
                    i_code: String::new(),
                },
                ResidueKey {
                    chain_id: bond.chain_id_2.clone(),
                    res_seq: bond.res_seq_2,
                    i_code: String::new(),
                },
            ]
        })
        .collect()
}

/// Maximum SG-SG distance (Å) to consider a disulfide bond.
/// Typical S-S bond is ~2.05 Å; 2.5 Å allows for crystallographic uncertainty.
const DISULFIDE_CUTOFF: f64 = 2.5;

/// Find CYS residues involved in disulfide bonds by SG-SG proximity.
/// Used as fallback when _struct_conn records are absent from the mmCIF file.
fn find_disulfide_bonds_geometric(
    residue_groups: &[(ResidueKey, Vec<&AtomRecord>)],
) -> HashSet<ResidueKey> {
    let cys_sg: Vec<(&ResidueKey, f64, f64, f64)> = residue_groups
        .iter()
        .filter(|(_, atoms)| atoms[0].res_name == "CYS")
        .filter_map(|(key, atoms)| {
            atoms
                .iter()
                .find(|a| a.name == "SG")
                .map(|sg| (key, sg.x, sg.y, sg.z))
        })
        .collect();

    let mut ss_bonded = HashSet::new();
    for i in 0..cys_sg.len() {
        for j in (i + 1)..cys_sg.len() {
            let dx = cys_sg[i].1 - cys_sg[j].1;
            let dy = cys_sg[i].2 - cys_sg[j].2;
            let dz = cys_sg[i].3 - cys_sg[j].3;
            let dist = dz.mul_add(dz, dx.mul_add(dx, dy * dy)).sqrt();
            if dist < DISULFIDE_CUTOFF {
                ss_bonded.insert(cys_sg[i].0.clone());
                ss_bonded.insert(cys_sg[j].0.clone());
            }
        }
    }
    ss_bonded
}

/// Find first and last residue index for each chain.
fn find_chain_terminals(
    residue_groups: &[(ResidueKey, Vec<&AtomRecord>)],
) -> HashMap<String, (usize, usize)> {
    let mut terminals: HashMap<String, (usize, usize)> = HashMap::new();
    for (idx, (key, _)) in residue_groups.iter().enumerate() {
        terminals
            .entry(key.chain_id.clone())
            .and_modify(|(_, last)| *last = idx)
            .or_insert((idx, idx));
    }
    terminals
}

/// Common formal charges for metal ions.
fn metal_charge(res_name: &str) -> f64 {
    match res_name {
        "ZN" | "MG" | "CA" | "MN" | "CU" | "CO" | "NI" | "CD" => 2.0,
        "FE" => 3.0, // Fe3+ more common in proteins
        "NA" | "K" => 1.0,
        _ => 0.0,
    }
}

// ---------------------------------------------------------------------------
// Public formatters
// ---------------------------------------------------------------------------

/// Format beads as plain XYZ string (name x y z).
pub fn format_xyz(beads: &[Bead], names: &[String], comment: &str) -> String {
    debug_assert_eq!(beads.len(), names.len(), "beads and names must be 1:1");
    let mut out = String::new();
    writeln!(out, "{}", beads.len()).expect("writing to String is infallible");
    writeln!(out, "{comment}").expect("writing to String is infallible");
    for (i, b) in beads.iter().enumerate() {
        writeln!(
            out,
            "{:<5} {:>10.4} {:>10.4} {:>10.4}",
            &names[i], b.x, b.y, b.z
        )
        .expect("writing to String is infallible");
    }
    out
}

/// Format topology as YAML with unique atom types and optional force field parameters.
pub fn format_topology(
    topo: &topology::Topology,
    ff: Option<&dyn forcefield::ForceField>,
    multi_bead: bool,
) -> String {
    let label = if multi_bead { "multi" } else { "single" };
    let mut out = format!("# model: {label}\natoms:\n");
    let mut ff_types: Vec<(&str, f64, forcefield::BeadParams)> = Vec::new();
    for t in topo.types() {
        let sc_comment = if multi_bead && t.bead_type == BeadType::Virtual {
            " # virtual titratable site"
        } else {
            ""
        };
        let ff_params = ff.and_then(|f| f.params(t.res_name, t.bead_type));
        let mass = ff_params
            .and_then(|p| (p.mass > 0.0).then_some(p.mass))
            .unwrap_or(t.mass);
        let ff_fields = if let Some(p) = ff_params {
            ff_types.push((t.name, t.charge, p));
            format!(", {}", ff.unwrap().format_atom_fields(&p))
        } else {
            String::new()
        };
        writeln!(
            out,
            "  - {{charge: {:.4}, mass: {:.2}, name: {}{}}}{}",
            t.charge, mass, t.name, ff_fields, sc_comment,
        )
        .expect("writing to String is infallible");
    }

    if let Some(f) = ff {
        out.push_str(&f.nonbonded_yaml(&ff_types));
    }

    out
}

/// Run the full coarse-graining pipeline and write XYZ and topology YAML files.
///
/// Detects PDB vs mmCIF from `is_pdb`, coarse-grains with the given policy,
/// computes charges via MC titration, and writes the results to disk.
#[allow(clippy::too_many_arguments)]
pub fn coarse_grain_to_files(
    reader: impl BufRead,
    is_pdb: bool,
    charge_calc: &ChargeCalc,
    model: &str,
    policy: &dyn CoarseGrain,
    merge_tolerance: f64,
    scaling: forcefield::HydrophobicScaling,
    chains: &[impl AsRef<str>],
    xyz_path: impl AsRef<Path>,
    topology_path: impl AsRef<Path>,
) -> Result<(), String> {
    let xyz_path = xyz_path.as_ref();
    let topology_path = topology_path.as_ref();

    // 1. Coarse-grain and optionally filter by chain
    let beads = if is_pdb {
        coarse_grain_pdb_with(reader, policy)
    } else {
        coarse_grain_with(reader, policy)
    };
    let beads = filter_chains(beads, chains);

    // 2. Compute charges
    charge_calc.log_conditions();
    let result = charge_calc.run(&beads);
    let charged = result.apply(&beads);

    // 3. Build topology
    let topo = topology::Topology::new(&charged, merge_tolerance);
    let names = topo.bead_names();

    // 4. Load force field
    let multi_bead = charged.iter().any(|b| b.bead_type == BeadType::Virtual);
    let ff = forcefield::from_name(model, scaling)?;

    // 5. Write XYZ
    let xyz_content = format_xyz(&charged, names, "generated by cgkitten");
    std::fs::write(xyz_path, &xyz_content)
        .map_err(|e| format!("Failed to write {}: {e}", xyz_path.display()))?;
    info!("Wrote {}", xyz_path.display());

    // 6. Write topology YAML
    let yaml_content = format_topology(&topo, ff.as_deref(), multi_bead);
    std::fs::write(topology_path, &yaml_content)
        .map_err(|e| format!("Failed to write {}: {e}", topology_path.display()))?;
    info!("Wrote {}", topology_path.display());

    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    const TEST_CIF: &str = r#"
data_test
loop_
_atom_site.group_PDB
_atom_site.id
_atom_site.auth_atom_id
_atom_site.auth_comp_id
_atom_site.auth_asym_id
_atom_site.auth_seq_id
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.type_symbol
_atom_site.label_alt_id
_atom_site.pdbx_PDB_model_num
ATOM 1 N ALA A 1 0.000 0.000 0.000 N . 1
ATOM 2 CA ALA A 1 1.458 0.000 0.000 C . 1
ATOM 3 C ALA A 1 2.400 -1.100 0.000 C . 1
ATOM 4 O ALA A 1 2.200 -2.300 0.000 O . 1
ATOM 5 CB ALA A 1 2.000 1.000 0.000 C . 1
ATOM 6 N GLU A 2 3.600 -0.500 0.000 N . 1
ATOM 7 CA GLU A 2 4.900 -1.100 0.000 C . 1
ATOM 8 C GLU A 2 5.800 -2.200 0.000 C . 1
ATOM 9 O GLU A 2 5.600 -3.400 0.000 O . 1
ATOM 10 OXT GLU A 2 6.800 -1.800 0.500 O . 1
ATOM 11 CB GLU A 2 5.500 -0.500 1.200 C . 1
ATOM 12 CG GLU A 2 6.800 -1.000 1.800 C . 1
ATOM 13 CD GLU A 2 7.200 -0.200 3.000 C . 1
ATOM 14 OE1 GLU A 2 6.500 0.700 3.400 O . 1
ATOM 15 OE2 GLU A 2 8.200 -0.500 3.700 O . 1
HETATM 99 ZN ZN A 100 5.000 5.000 5.000 ZN . 1
"#;

    #[test]
    fn coarse_grain_basic() {
        let beads = coarse_grain(TEST_CIF.as_bytes());

        // ALA backbone + NTR + GLU backbone + CTR + GLU sidechain + ZN ion = 6 beads
        assert_eq!(beads.len(), 6, "beads: {beads:#?}");

        // ALA backbone has zero charge
        let ala = &beads[0];
        assert_eq!(ala.res_name, "ALA");
        assert_eq!(ala.bead_type, BeadType::Residue);
        assert!(ala.charge.abs() < 1e-10);

        // GLU sidechain bead exists, named by element
        let glu_sc = beads
            .iter()
            .find(|b| b.bead_type == BeadType::Virtual && b.res_seq == 2)
            .unwrap();
        assert_eq!(glu_sc.res_name, "O");

        // ZN ion has formal charge
        let zn = beads.iter().find(|b| b.res_name == "ZN").unwrap();
        assert_eq!(zn.bead_type, BeadType::Ion);
        assert!((zn.charge - 2.0).abs() < 1e-10);
    }

    #[test]
    fn charge_calc_hh() {
        let beads = coarse_grain(TEST_CIF.as_bytes());
        let result = ChargeCalc::new().run(&beads);
        let charged = result.apply(&beads);

        // GLU sidechain should have negative charge at pH 7
        let glu_sc = charged
            .iter()
            .find(|b| b.bead_type == BeadType::Virtual && b.res_seq == 2)
            .unwrap();
        assert!(
            glu_sc.charge < -0.9,
            "GLU sidechain charge at pH 7: {}",
            glu_sc.charge
        );

        // NTR bead positive at pH 7
        let ntr = charged
            .iter()
            .find(|b| b.bead_type == BeadType::Ntr)
            .unwrap();
        assert!(ntr.charge > 0.9, "NTR charge at pH 7: {}", ntr.charge);

        // CTR bead negative at pH 7
        let ctr = charged
            .iter()
            .find(|b| b.bead_type == BeadType::Ctr)
            .unwrap();
        assert!(ctr.charge < -0.9, "CTR charge at pH 7: {}", ctr.charge);

        // Backbone beads should have zero charge
        assert!(
            charged
                .iter()
                .filter(|b| b.bead_type == BeadType::Residue)
                .all(|b| b.charge.abs() < 1e-10),
            "backbone beads should have zero charge"
        );
    }

    #[test]
    fn terminal_beads_created() {
        let beads = coarse_grain(TEST_CIF.as_bytes());

        let ntr = beads.iter().find(|b| b.bead_type == BeadType::Ntr).unwrap();
        assert_eq!(ntr.res_seq, 1);

        let ctr = beads.iter().find(|b| b.bead_type == BeadType::Ctr).unwrap();
        assert_eq!(ctr.res_seq, 2);
    }

    #[test]
    fn sidechain_bead_has_zero_mass() {
        // The charged sidechain bead must have mass 0.0 — its atoms are already
        // counted in the main residue bead placed at the COM.
        let beads = coarse_grain(TEST_CIF.as_bytes());
        let sc_beads: Vec<_> = beads
            .iter()
            .filter(|b| b.bead_type == BeadType::Virtual)
            .collect();
        assert!(!sc_beads.is_empty(), "expected at least one sidechain bead");
        for b in &sc_beads {
            assert_eq!(
                b.mass, 0.0,
                "sidechain bead {}:{} has non-zero mass {}",
                b.chain_id, b.res_seq, b.mass
            );
        }
    }

    #[test]
    fn backbone_bead_at_com() {
        // ALA has atoms of different elements (N, C, O) so geometric center != COM.
        // This test would fail if center_and_mass used unweighted averaging.
        // Expected COM computed from TEST_CIF atom coordinates and IUPAC masses.
        let beads = coarse_grain(TEST_CIF.as_bytes());
        let ala = beads
            .iter()
            .find(|b| b.bead_type == BeadType::Residue && b.res_seq == 1)
            .unwrap();
        assert!((ala.x - 1.598423).abs() < 1e-4, "ALA COM x: {}", ala.x);
        assert!((ala.y - (-0.575399)).abs() < 1e-4, "ALA COM y: {}", ala.y);
        assert!(ala.z.abs() < 1e-10, "ALA COM z: {}", ala.z);
    }

    #[test]
    fn sidechain_bead_position() {
        // GLU sidechain center atoms (OE1, OE2) are both oxygen — same mass —
        // so geometric center and COM coincide. This test checks the position
        // but does NOT verify mass-weighting; see backbone_bead_at_com for that.
        let beads = coarse_grain(TEST_CIF.as_bytes());

        let glu_sc = beads
            .iter()
            .find(|b| b.bead_type == BeadType::Virtual && b.res_seq == 2)
            .unwrap();
        assert!((glu_sc.x - 7.35).abs() < 0.01, "GLU SC x: {}", glu_sc.x);
        assert!((glu_sc.y - 0.1).abs() < 0.01, "GLU SC y: {}", glu_sc.y);
        assert!((glu_sc.z - 3.55).abs() < 0.01, "GLU SC z: {}", glu_sc.z);
    }

    #[test]
    fn water_and_nonprotein_removed() {
        let cif = r#"
data_test
loop_
_atom_site.group_PDB
_atom_site.id
_atom_site.auth_atom_id
_atom_site.auth_comp_id
_atom_site.auth_asym_id
_atom_site.auth_seq_id
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.type_symbol
_atom_site.label_alt_id
_atom_site.pdbx_PDB_model_num
ATOM 1 CA ALA A 1 1.0 2.0 3.0 C . 1
HETATM 2 O HOH B 1 4.0 5.0 6.0 O . 1
HETATM 3 C1 LIG C 1 7.0 8.0 9.0 C . 1
"#;
        let beads = coarse_grain(cif.as_bytes());
        assert_eq!(beads.len(), 1);
        assert_eq!(beads[0].res_name, "ALA");
    }

    #[test]
    fn struct_conn_disulfide_suppresses_titration() {
        let cif = r#"
data_test
loop_
_struct_conn.id
_struct_conn.conn_type_id
_struct_conn.ptnr1_auth_asym_id
_struct_conn.ptnr1_auth_seq_id
_struct_conn.ptnr2_auth_asym_id
_struct_conn.ptnr2_auth_seq_id
disulf1 disulf A 5 A 20
loop_
_atom_site.group_PDB
_atom_site.id
_atom_site.auth_atom_id
_atom_site.auth_comp_id
_atom_site.auth_asym_id
_atom_site.auth_seq_id
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.type_symbol
_atom_site.label_alt_id
_atom_site.pdbx_PDB_model_num
ATOM 1 N CYS A 5 0.000 0.000 0.000 N . 1
ATOM 2 CA CYS A 5 1.458 0.000 0.000 C . 1
ATOM 3 SG CYS A 5 3.500 1.500 0.000 S . 1
ATOM 4 N CYS A 20 50.000 50.000 50.000 N . 1
ATOM 5 CA CYS A 20 51.458 50.000 50.000 C . 1
ATOM 6 SG CYS A 20 53.500 51.500 50.000 S . 1
"#;
        let beads = coarse_grain(cif.as_bytes());
        assert_eq!(beads.len(), 3, "beads: {beads:#?}");
        assert!(!beads.iter().any(|b| b.bead_type == BeadType::Virtual));
    }

    #[test]
    fn disulfide_bonded_cys_not_titrated() {
        let cif = r#"
data_test
loop_
_atom_site.group_PDB
_atom_site.id
_atom_site.auth_atom_id
_atom_site.auth_comp_id
_atom_site.auth_asym_id
_atom_site.auth_seq_id
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.type_symbol
_atom_site.label_alt_id
_atom_site.pdbx_PDB_model_num
ATOM 1 N CYS A 5 0.000 0.000 0.000 N . 1
ATOM 2 CA CYS A 5 1.458 0.000 0.000 C . 1
ATOM 3 CB CYS A 5 2.000 1.200 0.000 C . 1
ATOM 4 SG CYS A 5 3.500 1.500 0.000 S . 1
ATOM 5 N CYS A 20 5.000 0.000 0.000 N . 1
ATOM 6 CA CYS A 20 6.458 0.000 0.000 C . 1
ATOM 7 CB CYS A 20 7.000 1.200 0.000 C . 1
ATOM 8 SG CYS A 20 5.500 1.500 0.000 S . 1
"#;
        let beads = coarse_grain(cif.as_bytes());
        assert_eq!(beads.len(), 3, "beads: {beads:#?}");
        assert!(!beads.iter().any(|b| b.bead_type == BeadType::Virtual));
    }

    #[test]
    fn free_cys_titrates() {
        let cif = r#"
data_test
loop_
_atom_site.group_PDB
_atom_site.id
_atom_site.auth_atom_id
_atom_site.auth_comp_id
_atom_site.auth_asym_id
_atom_site.auth_seq_id
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.type_symbol
_atom_site.label_alt_id
_atom_site.pdbx_PDB_model_num
ATOM 1 N CYS A 5 0.000 0.000 0.000 N . 1
ATOM 2 CA CYS A 5 1.458 0.000 0.000 C . 1
ATOM 3 CB CYS A 5 2.000 1.200 0.000 C . 1
ATOM 4 SG CYS A 5 3.500 1.500 0.000 S . 1
"#;
        let beads = coarse_grain(cif.as_bytes());
        assert_eq!(beads.len(), 3, "beads: {beads:#?}");
        assert!(beads.iter().any(|b| b.bead_type == BeadType::Virtual));
    }

    #[test]
    fn terminal_with_titratable_sidechain() {
        let cif = r#"
data_test
loop_
_atom_site.group_PDB
_atom_site.id
_atom_site.auth_atom_id
_atom_site.auth_comp_id
_atom_site.auth_asym_id
_atom_site.auth_seq_id
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.type_symbol
_atom_site.label_alt_id
_atom_site.pdbx_PDB_model_num
ATOM 1 N LYS A 1 0.000 0.000 0.000 N . 1
ATOM 2 CA LYS A 1 1.458 0.000 0.000 C . 1
ATOM 3 C LYS A 1 2.400 -1.100 0.000 C . 1
ATOM 4 O LYS A 1 2.200 -2.300 0.000 O . 1
ATOM 5 CB LYS A 1 2.000 1.200 0.000 C . 1
ATOM 6 CG LYS A 1 3.500 1.500 0.000 C . 1
ATOM 7 CD LYS A 1 5.000 1.200 0.000 C . 1
ATOM 8 CE LYS A 1 6.500 1.500 0.000 C . 1
ATOM 9 NZ LYS A 1 8.000 1.200 0.000 N . 1
ATOM 10 N ALA A 2 3.600 -0.500 0.000 N . 1
ATOM 11 CA ALA A 2 4.900 -1.100 0.000 C . 1
ATOM 12 C ALA A 2 5.800 -2.200 0.000 C . 1
ATOM 13 O ALA A 2 5.600 -3.400 0.000 O . 1
ATOM 14 OXT ALA A 2 6.800 -1.800 0.500 O . 1
"#;
        let beads = coarse_grain(cif.as_bytes());

        // LYS backbone + NTR(N) + sidechain(N at NZ) + ALA backbone + CTR(O) = 5
        assert_eq!(beads.len(), 5, "beads: {beads:#?}");

        let lys_beads: Vec<_> = beads.iter().filter(|b| b.res_seq == 1).collect();
        assert_eq!(
            lys_beads.len(),
            3,
            "LYS should have 3 beads: {lys_beads:#?}"
        );
        assert!(lys_beads.iter().any(|b| b.bead_type == BeadType::Residue));
        assert!(lys_beads.iter().any(|b| b.bead_type == BeadType::Ntr));
        assert!(lys_beads.iter().any(|b| b.bead_type == BeadType::Virtual));

        // NTR bead at N atom position
        let ntr = lys_beads
            .iter()
            .find(|b| b.bead_type == BeadType::Ntr)
            .unwrap();
        assert_eq!(ntr.res_name, "N");
        assert!((ntr.x - 0.0).abs() < 0.01);

        // Sidechain bead at NZ position
        let sc = lys_beads
            .iter()
            .find(|b| b.bead_type == BeadType::Virtual)
            .unwrap();
        assert_eq!(sc.res_name, "N");
        assert!((sc.x - 8.0).abs() < 0.01);
    }

    #[test]
    fn multipole_moments() {
        let beads = coarse_grain(TEST_CIF.as_bytes());
        let result = ChargeCalc::new().run(&beads);

        // HH is deterministic: charge_sq == charge²
        let m = &result.multipole;
        assert!(
            (m.charge_sq - m.charge * m.charge).abs() < 1e-10,
            "HH: ⟨Z²⟩ should equal ⟨Z⟩²"
        );
        assert!(
            (m.dipole_sq - m.dipole * m.dipole).abs() < 1e-10,
            "HH: ⟨μ²⟩ should equal ⟨μ⟩²"
        );
    }
}