pdbrust 0.7.0

A comprehensive Rust library for parsing and analyzing Protein Data Bank (PDB) files
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
//! Structure quality assessment functions.
//!
//! This module provides fast, non-destructive quality checks for PDB structures.
//! These functions are useful for filtering datasets and characterizing structures.
//!
//! # Quality Checks
//!
//! - **Atom content**: Detect CA-only (coarse-grained) structures
//! - **Model content**: Detect multi-model structures (NMR ensembles)
//! - **Alternate locations**: Detect conformational heterogeneity
//! - **Chain count**: Count distinct protein chains
//! - **Completeness**: Check for missing atoms or residues
//!
//! # Examples
//!
//! ```ignore
//! use pdbrust::PdbStructure;
//!
//! let structure = PdbStructure::from_file("protein.pdb")?;
//!
//! // Quick quality checks
//! if structure.has_multiple_models() {
//!     println!("NMR ensemble detected");
//! }
//!
//! if structure.has_altlocs() {
//!     println!("Structure has alternate conformations");
//! }
//!
//! // Get comprehensive quality report
//! let report = structure.quality_report();
//! println!("Chains: {}, Models: {}", report.num_chains, report.num_models);
//! ```
//!
//! # Feature Flag
//!
//! This module requires the `quality` feature:
//!
//! ```toml
//! [dependencies]
//! pdbrust = { version = "0.7", features = ["quality"] }
//! ```

use crate::core::PdbStructure;

/// Comprehensive quality assessment report for a PDB structure.
///
/// This struct contains all quality metrics for a structure,
/// suitable for filtering datasets or generating quality summaries.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct QualityReport {
    /// True if the structure contains only Cα atoms (coarse-grained)
    pub has_ca_only: bool,
    /// True if the structure has multiple models (e.g., NMR ensemble)
    pub has_multiple_models: bool,
    /// True if any atoms have alternate location indicators
    pub has_altlocs: bool,
    /// Number of distinct chains in the structure
    pub num_chains: usize,
    /// Number of models in the structure
    pub num_models: usize,
    /// Number of atoms in the structure
    pub num_atoms: usize,
    /// Number of residues (based on unique chain+resnum+icode)
    pub num_residues: usize,
    /// True if the structure contains HETATM records (ligands, waters)
    pub has_hetatm: bool,
    /// True if the structure contains hydrogen atoms
    pub has_hydrogens: bool,
    /// True if the structure has disulfide bonds defined
    pub has_ssbonds: bool,
    /// True if the structure has connectivity records
    pub has_conect: bool,
}

impl QualityReport {
    /// Check if the structure passes basic quality criteria.
    ///
    /// Returns true if the structure:
    /// - Has at least one atom
    /// - Is not CA-only (unless that's expected)
    /// - Has no alternate locations (clean structure)
    pub fn is_clean(&self) -> bool {
        self.num_atoms > 0 && !self.has_ca_only && !self.has_altlocs
    }

    /// Check if the structure is suitable for typical analysis.
    ///
    /// Returns true if the structure:
    /// - Has atoms
    /// - Is a single model (not NMR ensemble)
    /// - Has no alternate locations
    pub fn is_analysis_ready(&self) -> bool {
        self.num_atoms > 0 && !self.has_multiple_models && !self.has_altlocs
    }
}

impl PdbStructure {
    /// Check if the structure contains only Cα atoms.
    ///
    /// Returns true if all ATOM records are Cα atoms, indicating
    /// a coarse-grained representation of the structure.
    ///
    /// # Returns
    ///
    /// `true` if the structure contains only Cα atoms, `false` otherwise.
    /// Returns `false` for empty structures.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use pdbrust::PdbStructure;
    ///
    /// let structure = PdbStructure::from_file("protein.pdb")?;
    ///
    /// if structure.has_ca_only() {
    ///     println!("Coarse-grained structure detected");
    /// }
    /// ```
    pub fn has_ca_only(&self) -> bool {
        if self.atoms.is_empty() {
            return false;
        }

        self.atoms.iter().all(|atom| atom.name.trim() == "CA")
    }

    /// Check if the structure has multiple models.
    ///
    /// Returns true if the structure contains more than one model,
    /// typically indicating an NMR ensemble or molecular dynamics trajectory.
    ///
    /// # Returns
    ///
    /// `true` if multiple models are present, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use pdbrust::PdbStructure;
    ///
    /// let structure = PdbStructure::from_file("nmr_ensemble.pdb")?;
    ///
    /// if structure.has_multiple_models() {
    ///     println!("NMR ensemble with {} models", structure.num_models());
    /// }
    /// ```
    pub fn has_multiple_models(&self) -> bool {
        self.models.len() > 1
    }

    /// Get the number of models in the structure.
    ///
    /// # Returns
    ///
    /// The number of models. Returns 1 for single-model structures
    /// (even if no explicit MODEL record is present).
    pub fn num_models(&self) -> usize {
        if self.models.is_empty() {
            1 // Implicit single model
        } else {
            self.models.len()
        }
    }

    /// Check if any atoms have alternate location indicators.
    ///
    /// Alternate locations indicate that an atom exists in multiple
    /// conformations, representing local disorder or flexibility.
    ///
    /// # Returns
    ///
    /// `true` if any atom has an alternate location indicator.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use pdbrust::PdbStructure;
    ///
    /// let structure = PdbStructure::from_file("protein.pdb")?;
    ///
    /// if structure.has_altlocs() {
    ///     println!("Structure has conformational heterogeneity");
    /// }
    /// ```
    pub fn has_altlocs(&self) -> bool {
        self.atoms.iter().any(|atom| atom.alt_loc.is_some())
    }

    /// Get all unique alternate location identifiers.
    ///
    /// # Returns
    ///
    /// A sorted vector of alternate location characters (e.g., ['A', 'B']).
    pub fn get_altloc_ids(&self) -> Vec<char> {
        let mut altlocs: Vec<char> = self.atoms.iter().filter_map(|atom| atom.alt_loc).collect();

        altlocs.sort();
        altlocs.dedup();
        altlocs
    }

    /// Check if the structure contains HETATM records.
    ///
    /// HETATM records represent non-standard residues like ligands,
    /// water molecules, ions, and modified amino acids.
    ///
    /// # Returns
    ///
    /// `true` if any non-standard residues are present.
    pub fn has_hetatm(&self) -> bool {
        // Check if any residue is not a standard amino acid or nucleotide
        #[cfg(feature = "filter")]
        {
            use crate::filter::is_standard_residue;
            self.atoms
                .iter()
                .any(|atom| !is_standard_residue(&atom.residue_name))
        }

        #[cfg(not(feature = "filter"))]
        {
            // Fallback: check for common HETATM residue names
            const NON_STANDARD: &[&str] = &["HOH", "WAT", "DOD", "H2O", "TIP"];
            self.atoms
                .iter()
                .any(|atom| NON_STANDARD.contains(&atom.residue_name.trim()))
        }
    }

    /// Check if the structure contains hydrogen atoms.
    ///
    /// # Returns
    ///
    /// `true` if any hydrogen atoms are present.
    pub fn has_hydrogens(&self) -> bool {
        self.atoms.iter().any(|atom| atom.is_hydrogen())
    }

    /// Check if the structure has disulfide bonds defined.
    ///
    /// # Returns
    ///
    /// `true` if SSBOND records are present.
    pub fn has_ssbonds(&self) -> bool {
        !self.ssbonds.is_empty()
    }

    /// Check if the structure has connectivity records.
    ///
    /// # Returns
    ///
    /// `true` if CONECT records are present.
    pub fn has_conect(&self) -> bool {
        !self.connects.is_empty()
    }

    /// Count the number of atoms with alternate locations.
    ///
    /// # Returns
    ///
    /// The number of atoms that have alternate location indicators.
    pub fn count_altloc_atoms(&self) -> usize {
        self.atoms
            .iter()
            .filter(|atom| atom.alt_loc.is_some())
            .count()
    }

    /// Count the number of hydrogen atoms.
    ///
    /// # Returns
    ///
    /// The number of hydrogen atoms in the structure.
    pub fn count_hydrogens(&self) -> usize {
        self.atoms.iter().filter(|atom| atom.is_hydrogen()).count()
    }

    /// Get a comprehensive quality report for the structure.
    ///
    /// This method computes all quality metrics in a single pass
    /// and returns them in a structured format.
    ///
    /// # Returns
    ///
    /// A `QualityReport` struct containing all quality metrics.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use pdbrust::PdbStructure;
    ///
    /// let structure = PdbStructure::from_file("protein.pdb")?;
    /// let report = structure.quality_report();
    ///
    /// println!("Chains: {}", report.num_chains);
    /// println!("Models: {}", report.num_models);
    /// println!("Has altlocs: {}", report.has_altlocs);
    ///
    /// if report.is_analysis_ready() {
    ///     println!("Structure is ready for analysis");
    /// }
    /// ```
    pub fn quality_report(&self) -> QualityReport {
        QualityReport {
            has_ca_only: self.has_ca_only(),
            has_multiple_models: self.has_multiple_models(),
            has_altlocs: self.has_altlocs(),
            num_chains: self.get_num_chains(),
            num_models: self.num_models(),
            num_atoms: self.get_num_atoms(),
            num_residues: self.get_num_residues(),
            has_hetatm: self.has_hetatm(),
            has_hydrogens: self.has_hydrogens(),
            has_ssbonds: self.has_ssbonds(),
            has_conect: self.has_conect(),
        }
    }

    /// Check if the structure is empty.
    ///
    /// # Returns
    ///
    /// `true` if the structure has no atoms.
    pub fn is_empty(&self) -> bool {
        self.atoms.is_empty()
    }

    /// Get resolution information from REMARK 2 records.
    ///
    /// # Returns
    ///
    /// The resolution in Angstroms if available, `None` otherwise.
    pub fn get_resolution(&self) -> Option<f64> {
        for remark in &self.remarks {
            if remark.number == 2 {
                // Try to parse resolution from REMARK 2
                // Format: "RESOLUTION.    X.XX ANGSTROMS."
                let content = remark.content.to_uppercase();
                if content.contains("RESOLUTION") {
                    // Extract the numeric value
                    for word in content.split_whitespace() {
                        if let Ok(value) = word.parse::<f64>() {
                            if value > 0.0 && value < 20.0 {
                                return Some(value);
                            }
                        }
                    }
                }
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::records::{Atom, Model, Remark};

    fn create_atom(
        serial: i32,
        name: &str,
        residue_name: &str,
        chain_id: &str,
        alt_loc: Option<char>,
    ) -> Atom {
        Atom {
            serial,
            name: name.to_string(),
            alt_loc,
            residue_name: residue_name.to_string(),
            chain_id: chain_id.to_string(),
            residue_seq: 1,
            ins_code: None,
            is_hetatm: false,
            x: 0.0,
            y: 0.0,
            z: 0.0,
            occupancy: 1.0,
            temp_factor: 20.0,
            element: if name.trim().starts_with('H') {
                "H".to_string()
            } else {
                "C".to_string()
            },
        }
    }

    #[test]
    fn test_has_ca_only_true() {
        let mut structure = PdbStructure::new();
        structure.atoms = vec![
            create_atom(1, " CA ", "ALA", "A", None),
            create_atom(2, " CA ", "GLY", "A", None),
            create_atom(3, " CA ", "VAL", "A", None),
        ];

        assert!(structure.has_ca_only());
    }

    #[test]
    fn test_has_ca_only_false() {
        let mut structure = PdbStructure::new();
        structure.atoms = vec![
            create_atom(1, " N  ", "ALA", "A", None),
            create_atom(2, " CA ", "ALA", "A", None),
            create_atom(3, " C  ", "ALA", "A", None),
        ];

        assert!(!structure.has_ca_only());
    }

    #[test]
    fn test_has_ca_only_empty() {
        let structure = PdbStructure::new();
        assert!(!structure.has_ca_only());
    }

    #[test]
    fn test_has_multiple_models_true() {
        let mut structure = PdbStructure::new();
        structure.models = vec![
            Model {
                serial: 1,
                atoms: vec![],
                remarks: vec![],
            },
            Model {
                serial: 2,
                atoms: vec![],
                remarks: vec![],
            },
        ];

        assert!(structure.has_multiple_models());
        assert_eq!(structure.num_models(), 2);
    }

    #[test]
    fn test_has_multiple_models_false() {
        let structure = PdbStructure::new();
        assert!(!structure.has_multiple_models());
        assert_eq!(structure.num_models(), 1);
    }

    #[test]
    fn test_has_altlocs_true() {
        let mut structure = PdbStructure::new();
        structure.atoms = vec![
            create_atom(1, " CA ", "ALA", "A", Some('A')),
            create_atom(2, " CA ", "ALA", "A", Some('B')),
        ];

        assert!(structure.has_altlocs());
    }

    #[test]
    fn test_has_altlocs_false() {
        let mut structure = PdbStructure::new();
        structure.atoms = vec![
            create_atom(1, " CA ", "ALA", "A", None),
            create_atom(2, " CA ", "GLY", "A", None),
        ];

        assert!(!structure.has_altlocs());
    }

    #[test]
    fn test_get_altloc_ids() {
        let mut structure = PdbStructure::new();
        structure.atoms = vec![
            create_atom(1, " CA ", "ALA", "A", Some('A')),
            create_atom(2, " CA ", "ALA", "A", Some('B')),
            create_atom(3, " CB ", "ALA", "A", Some('A')),
        ];

        let altlocs = structure.get_altloc_ids();
        assert_eq!(altlocs, vec!['A', 'B']);
    }

    #[test]
    fn test_has_hydrogens() {
        let mut structure = PdbStructure::new();
        structure.atoms = vec![
            create_atom(1, " CA ", "ALA", "A", None),
            Atom {
                serial: 2,
                name: "H   ".to_string(), // Hydrogen names start with H
                alt_loc: None,
                residue_name: "ALA".to_string(),
                chain_id: "A".to_string(),
                residue_seq: 1,
                ins_code: None,
                is_hetatm: false,
                x: 0.0,
                y: 0.0,
                z: 0.0,
                occupancy: 1.0,
                temp_factor: 20.0,
                element: "H".to_string(),
            },
        ];

        assert!(structure.has_hydrogens());
        assert_eq!(structure.count_hydrogens(), 1);
    }

    #[test]
    fn test_has_ssbonds() {
        let mut structure = PdbStructure::new();
        assert!(!structure.has_ssbonds());

        structure.ssbonds = vec![crate::records::SSBond {
            serial: 1,
            residue1_name: "CYS".to_string(),
            chain1_id: "A".to_string(),
            residue1_seq: 10,
            icode1: None,
            residue2_name: "CYS".to_string(),
            chain2_id: "A".to_string(),
            residue2_seq: 20,
            icode2: None,
            sym1: 1,
            sym2: 1,
            length: 2.03,
        }];

        assert!(structure.has_ssbonds());
    }

    #[test]
    fn test_quality_report() {
        let mut structure = PdbStructure::new();
        structure.atoms = vec![
            create_atom(1, " N  ", "ALA", "A", None),
            create_atom(2, " CA ", "ALA", "A", None),
            create_atom(3, " C  ", "ALA", "A", None),
        ];

        let report = structure.quality_report();

        assert!(!report.has_ca_only);
        assert!(!report.has_multiple_models);
        assert!(!report.has_altlocs);
        assert_eq!(report.num_chains, 1);
        assert_eq!(report.num_models, 1);
        assert_eq!(report.num_atoms, 3);
    }

    #[test]
    fn test_quality_report_is_clean() {
        let report = QualityReport {
            has_ca_only: false,
            has_multiple_models: false,
            has_altlocs: false,
            num_chains: 1,
            num_models: 1,
            num_atoms: 100,
            num_residues: 10,
            has_hetatm: false,
            has_hydrogens: false,
            has_ssbonds: false,
            has_conect: false,
        };

        assert!(report.is_clean());
        assert!(report.is_analysis_ready());
    }

    #[test]
    fn test_quality_report_not_clean() {
        let report = QualityReport {
            has_ca_only: true,
            has_multiple_models: false,
            has_altlocs: false,
            num_chains: 1,
            num_models: 1,
            num_atoms: 100,
            num_residues: 10,
            has_hetatm: false,
            has_hydrogens: false,
            has_ssbonds: false,
            has_conect: false,
        };

        assert!(!report.is_clean()); // CA-only is not clean
    }

    #[test]
    fn test_is_empty() {
        let structure = PdbStructure::new();
        assert!(structure.is_empty());

        let mut structure2 = PdbStructure::new();
        structure2.atoms = vec![create_atom(1, " CA ", "ALA", "A", None)];
        assert!(!structure2.is_empty());
    }

    #[test]
    fn test_get_resolution() {
        let mut structure = PdbStructure::new();
        structure.remarks = vec![Remark {
            number: 2,
            content: "RESOLUTION.    2.50 ANGSTROMS.".to_string(),
        }];

        let resolution = structure.get_resolution();
        assert!(resolution.is_some());
        assert!((resolution.unwrap() - 2.50).abs() < 0.01);
    }

    #[test]
    fn test_get_resolution_none() {
        let structure = PdbStructure::new();
        assert!(structure.get_resolution().is_none());
    }

    #[test]
    fn test_count_altloc_atoms() {
        let mut structure = PdbStructure::new();
        structure.atoms = vec![
            create_atom(1, " CA ", "ALA", "A", Some('A')),
            create_atom(2, " CA ", "ALA", "A", Some('B')),
            create_atom(3, " CB ", "ALA", "A", None),
        ];

        assert_eq!(structure.count_altloc_atoms(), 2);
    }
}