bio-forge 0.4.1

A pure Rust library and CLI for the automated repair, preparation, and topology construction of biological macromolecules.
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
//! Representation of a polymer residue and its atom inventory.
//!
//! Residues bridge raw template data, readers/writers, and structure-level operations by
//! tracking naming metadata, chain position, and owned atoms. Higher-level components use
//! this module to inspect or mutate residues while preserving biochemical context.

use super::atom::Atom;
use super::types::{ResidueCategory, ResiduePosition, StandardResidue};
use smol_str::SmolStr;
use std::fmt;

/// A residue within a biomolecular structure.
///
/// Residues capture crystallographic identifiers (sequence number and insertion code), the
/// original and normalized names, classification metadata, and the atoms that belong to the
/// residue. They are the primary unit passed between IO routines, topology builders, and
/// structure editing operations.
#[derive(Debug, Clone, PartialEq)]
pub struct Residue {
    /// Author-provided sequence identifier (can be negative for certain files).
    pub id: i32,
    /// Optional insertion code differentiating records that share the same `id`.
    pub insertion_code: Option<char>,
    /// Original residue name as encountered during parsing.
    pub name: SmolStr,
    /// Canonical residue assignment if the name maps to a standard alphabet entry.
    pub standard_name: Option<StandardResidue>,
    /// Category describing whether the residue is standard, heterogen, or ion.
    pub category: ResidueCategory,
    /// Chain position annotation (terminus, internal, or nucleic end).
    pub position: ResiduePosition,
    /// Owned atoms that comprise the residue.
    atoms: Vec<Atom>,
}

impl Residue {
    /// Creates a residue with the provided identifiers and classification.
    ///
    /// The residue starts without atoms and defaults to `ResiduePosition::None` until the
    /// caller updates it based on chain topology.
    ///
    /// # Arguments
    ///
    /// * `id` - Sequence number pulled from the original structure file.
    /// * `insertion_code` - Optional insertion code for distinguishing alternate residues.
    /// * `name` - Author-provided residue label (e.g., `"ALA"`, `"DN1"`).
    /// * `standard_name` - Canonical assignment when the residue matches a standard entry.
    /// * `category` - Classification describing standard, hetero, or ion behavior.
    ///
    /// # Returns
    ///
    /// A `Residue` ready for atoms to be added.
    pub fn new(
        id: i32,
        insertion_code: Option<char>,
        name: &str,
        standard_name: Option<StandardResidue>,
        category: ResidueCategory,
    ) -> Self {
        Self {
            id,
            insertion_code,
            name: SmolStr::new(name),
            standard_name,
            category,
            position: ResiduePosition::None,
            atoms: Vec::new(),
        }
    }

    /// Reports whether the residue maps to a standard residue definition.
    ///
    /// # Returns
    ///
    /// `true` when `standard_name` is set.
    pub fn is_standard(&self) -> bool {
        self.standard_name.is_some()
    }

    /// Appends an atom to the residue.
    ///
    /// Duplicate atom names are guarded with a debug assertion to prevent inconsistent
    /// topologies while still allowing release builds to proceed.
    ///
    /// # Arguments
    ///
    /// * `atom` - The atom to insert; ownership moves into the residue.
    ///
    /// # Panics
    ///
    /// Panics in debug builds if an atom with the same `name` already exists.
    pub fn add_atom(&mut self, atom: Atom) {
        debug_assert!(
            self.atom(&atom.name).is_none(),
            "Attempted to add a duplicate atom name '{}' to residue '{}'",
            atom.name,
            self.name
        );
        self.atoms.push(atom);
    }

    /// Removes an atom by name and returns ownership to the caller.
    ///
    /// # Arguments
    ///
    /// * `name` - Atom name to remove (case-sensitive).
    ///
    /// # Returns
    ///
    /// `Some(atom)` if the atom existed, otherwise `None`.
    pub fn remove_atom(&mut self, name: &str) -> Option<Atom> {
        if let Some(index) = self.atoms.iter().position(|a| a.name == name) {
            Some(self.atoms.remove(index))
        } else {
            None
        }
    }

    /// Retrieves an immutable reference to an atom by name.
    ///
    /// # Arguments
    ///
    /// * `name` - Atom name to search for.
    ///
    /// # Returns
    ///
    /// `Some(&Atom)` when the atom exists, otherwise `None`.
    pub fn atom(&self, name: &str) -> Option<&Atom> {
        self.atoms.iter().find(|a| a.name == name)
    }

    /// Retrieves a mutable reference to an atom by name.
    ///
    /// # Arguments
    ///
    /// * `name` - Atom name to search for.
    ///
    /// # Returns
    ///
    /// `Some(&mut Atom)` when the atom exists, otherwise `None`.
    pub fn atom_mut(&mut self, name: &str) -> Option<&mut Atom> {
        self.atoms.iter_mut().find(|a| a.name == name)
    }

    /// Checks whether an atom with the provided name exists.
    ///
    /// # Arguments
    ///
    /// * `name` - Atom name to test.
    ///
    /// # Returns
    ///
    /// `true` if the atom is present.
    pub fn has_atom(&self, name: &str) -> bool {
        self.atom(name).is_some()
    }

    /// Returns an immutable slice of all atoms contained in the residue.
    ///
    /// Enables zero-copy iteration when only read-only access is required.
    ///
    /// # Returns
    ///
    /// A slice view over the internal atom vector.
    pub fn atoms(&self) -> &[Atom] {
        &self.atoms
    }

    /// Counts the number of atoms owned by the residue.
    ///
    /// # Returns
    ///
    /// Number of atoms currently stored.
    pub fn atom_count(&self) -> usize {
        self.atoms.len()
    }

    /// Indicates whether the residue has no atoms.
    ///
    /// # Returns
    ///
    /// `true` if `atom_count()` equals zero.
    pub fn is_empty(&self) -> bool {
        self.atoms.is_empty()
    }

    /// Provides an iterator over immutable atom references.
    ///
    /// This mirrors `atoms()` but allows idiomatic `for` loops without exposing the backing
    /// vector.
    ///
    /// # Returns
    ///
    /// An iterator yielding `&Atom` values.
    pub fn iter_atoms(&self) -> std::slice::Iter<'_, Atom> {
        self.atoms.iter()
    }

    /// Provides an iterator over mutable atom references.
    ///
    /// # Returns
    ///
    /// An iterator yielding `&mut Atom` values so callers can edit coordinates or metadata.
    pub fn iter_atoms_mut(&mut self) -> std::slice::IterMut<'_, Atom> {
        self.atoms.iter_mut()
    }

    /// Provides a parallel iterator over immutable atoms.
    ///
    /// # Returns
    ///
    /// A parallel iterator yielding `&Atom`.
    #[cfg(feature = "parallel")]
    pub fn par_atoms(&self) -> impl crate::utils::parallel::IndexedParallelIterator<Item = &Atom> {
        use crate::utils::parallel::IntoParallelRefIterator;
        self.atoms.par_iter()
    }

    /// Provides a parallel iterator over immutable atoms (internal fallback).
    #[cfg(not(feature = "parallel"))]
    pub(crate) fn par_atoms(
        &self,
    ) -> impl crate::utils::parallel::IndexedParallelIterator<Item = &Atom> {
        use crate::utils::parallel::IntoParallelRefIterator;
        self.atoms.par_iter()
    }

    /// Provides a parallel iterator over mutable atoms.
    ///
    /// # Returns
    ///
    /// A parallel iterator yielding `&mut Atom`.
    #[cfg(feature = "parallel")]
    pub fn par_atoms_mut(
        &mut self,
    ) -> impl crate::utils::parallel::IndexedParallelIterator<Item = &mut Atom> {
        use crate::utils::parallel::IntoParallelRefMutIterator;
        self.atoms.par_iter_mut()
    }

    /// Provides a parallel iterator over mutable atoms (internal fallback).
    #[cfg(not(feature = "parallel"))]
    pub(crate) fn par_atoms_mut(
        &mut self,
    ) -> impl crate::utils::parallel::IndexedParallelIterator<Item = &mut Atom> {
        use crate::utils::parallel::IntoParallelRefMutIterator;
        self.atoms.par_iter_mut()
    }

    /// Removes all hydrogen atoms from the residue.
    ///
    /// Used by cleaning operations when preparing structures for solvation or heavy-atom
    /// analysis.
    pub fn strip_hydrogens(&mut self) {
        self.atoms
            .retain(|a| a.element != crate::model::types::Element::H);
    }
}

impl fmt::Display for Residue {
    /// Formats the residue with identifier, canonical name, category, and atom count.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let insertion_code_str = self
            .insertion_code
            .map(|c| format!(" (ic: {})", c))
            .unwrap_or_default();

        if let Some(std_name) = self.standard_name {
            write!(
                f,
                "Residue {{ id: {}{}, name: \"{}\" ({}), category: {}, atoms: {} }}",
                self.id,
                insertion_code_str,
                self.name,
                std_name,
                self.category,
                self.atom_count()
            )
        } else {
            write!(
                f,
                "Residue {{ id: {}{}, name: \"{}\", category: {}, atoms: {} }}",
                self.id,
                insertion_code_str,
                self.name,
                self.category,
                self.atom_count()
            )
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::types::{Element, Point};

    #[test]
    fn residue_new_creates_correct_residue() {
        let residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        assert_eq!(residue.id, 1);
        assert_eq!(residue.insertion_code, None);
        assert_eq!(residue.name, "ALA");
        assert_eq!(residue.standard_name, Some(StandardResidue::ALA));
        assert_eq!(residue.category, ResidueCategory::Standard);
        assert_eq!(residue.position, ResiduePosition::None);
        assert!(residue.atoms.is_empty());
    }

    #[test]
    fn residue_new_with_insertion_code() {
        let residue = Residue::new(
            1,
            Some('A'),
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        assert_eq!(residue.id, 1);
        assert_eq!(residue.insertion_code, Some('A'));
    }

    #[test]
    fn residue_new_with_none_standard_name() {
        let residue = Residue::new(2, None, "UNK", None, ResidueCategory::Hetero);

        assert_eq!(residue.id, 2);
        assert_eq!(residue.name, "UNK");
        assert_eq!(residue.standard_name, None);
        assert_eq!(residue.category, ResidueCategory::Hetero);
    }

    #[test]
    fn residue_is_standard_returns_true_for_standard_residue() {
        let residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        assert!(residue.is_standard());
    }

    #[test]
    fn residue_is_standard_returns_false_for_non_standard_residue() {
        let residue = Residue::new(2, None, "UNK", None, ResidueCategory::Hetero);
        assert!(!residue.is_standard());
    }

    #[test]
    fn residue_add_atom_adds_atom_correctly() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));

        residue.add_atom(atom);

        assert_eq!(residue.atom_count(), 1);
        assert!(residue.has_atom("CA"));
        assert_eq!(residue.atom("CA").unwrap().name, "CA");
    }

    #[test]
    fn residue_remove_atom_removes_existing_atom() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        residue.add_atom(atom);

        let removed = residue.remove_atom("CA");

        assert!(removed.is_some());
        assert_eq!(removed.unwrap().name, "CA");
        assert_eq!(residue.atom_count(), 0);
        assert!(!residue.has_atom("CA"));
    }

    #[test]
    fn residue_remove_atom_returns_none_for_nonexistent_atom() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        let removed = residue.remove_atom("NONEXISTENT");

        assert!(removed.is_none());
    }

    #[test]
    fn residue_atom_returns_correct_atom() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        residue.add_atom(atom);

        let retrieved = residue.atom("CA");

        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "CA");
    }

    #[test]
    fn residue_atom_returns_none_for_nonexistent_atom() {
        let residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        let retrieved = residue.atom("NONEXISTENT");

        assert!(retrieved.is_none());
    }

    #[test]
    fn residue_atom_mut_returns_correct_mutable_atom() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        residue.add_atom(atom);

        let retrieved = residue.atom_mut("CA");

        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "CA");
    }

    #[test]
    fn residue_atom_mut_returns_none_for_nonexistent_atom() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        let retrieved = residue.atom_mut("NONEXISTENT");

        assert!(retrieved.is_none());
    }

    #[test]
    fn residue_has_atom_returns_true_for_existing_atom() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        residue.add_atom(atom);

        assert!(residue.has_atom("CA"));
    }

    #[test]
    fn residue_has_atom_returns_false_for_nonexistent_atom() {
        let residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        assert!(!residue.has_atom("NONEXISTENT"));
    }

    #[test]
    fn residue_atoms_returns_correct_slice() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom1 = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        let atom2 = Atom::new("CB", Element::C, Point::new(1.0, 0.0, 0.0));
        residue.add_atom(atom1);
        residue.add_atom(atom2);

        let atoms = residue.atoms();

        assert_eq!(atoms.len(), 2);
        assert_eq!(atoms[0].name, "CA");
        assert_eq!(atoms[1].name, "CB");
    }

    #[test]
    fn residue_atom_count_returns_correct_count() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        assert_eq!(residue.atom_count(), 0);

        let atom = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        residue.add_atom(atom);

        assert_eq!(residue.atom_count(), 1);
    }

    #[test]
    fn residue_is_empty_returns_true_for_empty_residue() {
        let residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        assert!(residue.is_empty());
    }

    #[test]
    fn residue_is_empty_returns_false_for_non_empty_residue() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        residue.add_atom(atom);

        assert!(!residue.is_empty());
    }

    #[test]
    fn residue_iter_atoms_iterates_correctly() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom1 = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        let atom2 = Atom::new("CB", Element::C, Point::new(1.0, 0.0, 0.0));
        residue.add_atom(atom1);
        residue.add_atom(atom2);

        let mut names = Vec::new();
        for atom in residue.iter_atoms() {
            names.push(atom.name.clone());
        }

        assert_eq!(names, vec!["CA", "CB"]);
    }

    #[test]
    fn residue_iter_atoms_mut_iterates_correctly() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom1 = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        residue.add_atom(atom1);

        for atom in residue.iter_atoms_mut() {
            atom.translate_by(&nalgebra::Vector3::new(1.0, 0.0, 0.0));
        }

        assert!((residue.atom("CA").unwrap().pos.x - 1.0).abs() < 1e-10);
    }

    #[test]
    fn residue_par_atoms_iterates_correctly() {
        use crate::utils::parallel::ParallelIterator;

        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom1 = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        let atom2 = Atom::new("CB", Element::C, Point::new(1.0, 0.0, 0.0));
        residue.add_atom(atom1);
        residue.add_atom(atom2);

        let count = residue.par_atoms().count();
        assert_eq!(count, 2);

        let names: Vec<String> = residue.par_atoms().map(|a| a.name.to_string()).collect();
        assert_eq!(names, vec!["CA", "CB"]);
    }

    #[test]
    fn residue_par_atoms_mut_iterates_correctly() {
        use crate::utils::parallel::ParallelIterator;

        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom1 = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        residue.add_atom(atom1);

        residue.par_atoms_mut().for_each(|atom| {
            atom.translate_by(&nalgebra::Vector3::new(1.0, 0.0, 0.0));
        });

        assert!((residue.atom("CA").unwrap().pos.x - 1.0).abs() < 1e-10);
    }

    #[test]
    fn residue_strip_hydrogens_removes_hydrogen_atoms() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let carbon = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        let hydrogen1 = Atom::new("HA", Element::H, Point::new(1.0, 0.0, 0.0));
        let hydrogen2 = Atom::new("HB", Element::H, Point::new(2.0, 0.0, 0.0));
        residue.add_atom(carbon);
        residue.add_atom(hydrogen1);
        residue.add_atom(hydrogen2);

        residue.strip_hydrogens();

        assert_eq!(residue.atom_count(), 1);
        assert!(residue.has_atom("CA"));
        assert!(!residue.has_atom("HA"));
        assert!(!residue.has_atom("HB"));
    }

    #[test]
    fn residue_strip_hydrogens_preserves_non_hydrogen_atoms() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let carbon = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        let nitrogen = Atom::new("N", Element::N, Point::new(1.0, 0.0, 0.0));
        let oxygen = Atom::new("O", Element::O, Point::new(2.0, 0.0, 0.0));
        residue.add_atom(carbon);
        residue.add_atom(nitrogen);
        residue.add_atom(oxygen);

        residue.strip_hydrogens();

        assert_eq!(residue.atom_count(), 3);
        assert!(residue.has_atom("CA"));
        assert!(residue.has_atom("N"));
        assert!(residue.has_atom("O"));
    }

    #[test]
    fn residue_display_formats_standard_residue_correctly() {
        let residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        let display = format!("{}", residue);
        let expected =
            "Residue { id: 1, name: \"ALA\" (ALA), category: Standard Residue, atoms: 0 }";

        assert_eq!(display, expected);
    }

    #[test]
    fn residue_display_formats_residue_with_insertion_code_correctly() {
        let residue = Residue::new(
            1,
            Some('A'),
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        let display = format!("{}", residue);
        let expected =
            "Residue { id: 1 (ic: A), name: \"ALA\" (ALA), category: Standard Residue, atoms: 0 }";

        assert_eq!(display, expected);
    }

    #[test]
    fn residue_display_formats_non_standard_residue_correctly() {
        let residue = Residue::new(2, None, "UNK", None, ResidueCategory::Hetero);

        let display = format!("{}", residue);
        let expected = "Residue { id: 2, name: \"UNK\", category: Hetero Residue, atoms: 0 }";

        assert_eq!(display, expected);
    }

    #[test]
    fn residue_display_includes_atom_count() {
        let mut residue = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom1 = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        let atom2 = Atom::new("CB", Element::C, Point::new(1.0, 0.0, 0.0));
        residue.add_atom(atom1);
        residue.add_atom(atom2);

        let display = format!("{}", residue);
        let expected =
            "Residue { id: 1, name: \"ALA\" (ALA), category: Standard Residue, atoms: 2 }";

        assert_eq!(display, expected);
    }

    #[test]
    fn residue_clone_creates_identical_copy() {
        let mut residue = Residue::new(
            1,
            Some('A'),
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        residue.add_atom(atom);
        residue.position = ResiduePosition::Internal;

        let cloned = residue.clone();

        assert_eq!(residue, cloned);
        assert_eq!(residue.id, cloned.id);
        assert_eq!(residue.insertion_code, cloned.insertion_code);
        assert_eq!(residue.name, cloned.name);
        assert_eq!(residue.standard_name, cloned.standard_name);
        assert_eq!(residue.category, cloned.category);
        assert_eq!(residue.position, cloned.position);
        assert_eq!(residue.atoms, cloned.atoms);
    }

    #[test]
    fn residue_partial_eq_compares_correctly() {
        let mut residue1 = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let mut residue2 = Residue::new(
            1,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );
        let atom = Atom::new("CA", Element::C, Point::new(0.0, 0.0, 0.0));
        residue1.add_atom(atom.clone());
        residue2.add_atom(atom);

        let residue3 = Residue::new(
            2,
            None,
            "ALA",
            Some(StandardResidue::ALA),
            ResidueCategory::Standard,
        );

        assert_eq!(residue1, residue2);
        assert_ne!(residue1, residue3);
    }
}