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
//! Canonical residue and ligand templates shared across topology-generating code.
//!
//! `Template` captures the authoritative atom list and bond connectivity for a residue so
//! that topology builders, repair passes, and solvation routines can reason about expected
//! atoms and their relationships before manipulating a structure.

use super::types::BondOrder;
use std::fmt;

/// Describes the atom inventory and connectivity for a residue or ligand template.
///
/// Templates originate from the embedded parameter database and encapsulate the minimal
/// information needed to validate coordinate files, seed missing atoms, or emit force-field
/// compatible topologies.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Template {
    /// External identifier such as a three-letter residue code.
    pub name: String,
    /// Ordered atom name list defining the template's expected atoms.
    atom_names: Vec<String>,
    /// Bond definitions captured as atom-name pairs with multiplicity information.
    bonds: Vec<(String, String, BondOrder)>,
}

impl Template {
    /// Constructs a template from explicit atom and bond data.
    ///
    /// The constructor enforces (in debug builds) that every bond references atoms present
    /// in the provided `atom_names` list, preventing malformed templates from entering the
    /// store.
    ///
    /// # Arguments
    ///
    /// * `name` - Short identifier for the template (e.g., three-letter code).
    /// * `atom_names` - Complete list of atom names belonging to the template.
    /// * `bonds` - Connectivity tuples describing bonded atom pairs and their `BondOrder`.
    ///
    /// # Returns
    ///
    /// A fully owned `Template` instance containing the supplied data.
    ///
    /// # Panics
    ///
    /// Panics in debug builds if any bond references an atom not listed in `atom_names`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bio_forge::{BondOrder, Template};
    ///
    /// let atoms = vec!["O".into(), "H1".into(), "H2".into()];
    /// let bonds = vec![
    ///     ("O".into(), "H1".into(), BondOrder::Single),
    ///     ("O".into(), "H2".into(), BondOrder::Single),
    /// ];
    /// let template = Template::new("HOH", atoms, bonds);
    ///
    /// assert_eq!(template.atom_count(), 3);
    /// assert_eq!(template.bond_count(), 2);
    /// ```
    pub fn new<S: Into<String>>(
        name: S,
        atom_names: Vec<String>,
        bonds: Vec<(String, String, BondOrder)>,
    ) -> Self {
        debug_assert!(
            bonds
                .iter()
                .all(|(a1, a2, _)| { atom_names.contains(a1) && atom_names.contains(a2) }),
            "Bond in template '{}' refers to an atom name that does not exist in the atom list.",
            name.into()
        );

        Self {
            name: name.into(),
            atom_names,
            bonds,
        }
    }

    /// Reports whether the template defines a bond between the provided atom names.
    ///
    /// Lookup is order-independent, allowing callers to check connectivity without sorting
    /// the names first.
    ///
    /// # Arguments
    ///
    /// * `name1` - Name of the first atom.
    /// * `name2` - Name of the second atom.
    ///
    /// # Returns
    ///
    /// `true` if a bond exists between the atoms, otherwise `false`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bio_forge::{BondOrder, Template};
    ///
    /// let atoms = vec!["C1".into(), "C2".into()];
    /// let bonds = vec![("C1".into(), "C2".into(), BondOrder::Single)];
    /// let template = Template::new("ETH", atoms, bonds);
    ///
    /// assert!(template.has_bond("C1", "C2"));
    /// assert!(template.has_bond("C2", "C1"));
    /// assert!(!template.has_bond("C1", "H1"));
    /// ```
    pub fn has_bond(&self, name1: &str, name2: &str) -> bool {
        self.bonds
            .iter()
            .any(|(a1, a2, _)| (a1 == name1 && a2 == name2) || (a1 == name2 && a2 == name1))
    }

    /// Checks whether an atom name is present in the template definition.
    ///
    /// # Arguments
    ///
    /// * `name` - Atom name to search for.
    ///
    /// # Returns
    ///
    /// `true` if the atom exists in `atom_names`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bio_forge::{BondOrder, Template};
    ///
    /// let atoms = vec!["N".into(), "CA".into(), "C".into()];
    /// let template = Template::new("GLY", atoms, Vec::new());
    ///
    /// assert!(template.has_atom("CA"));
    /// assert!(!template.has_atom("OXT"));
    /// ```
    pub fn has_atom(&self, name: &str) -> bool {
        self.atom_names.contains(&name.to_string())
    }

    /// Returns the ordered slice of atom names defined for the template.
    ///
    /// # Returns
    ///
    /// Borrowed slice referencing the internal atom list.
    ///
    /// # Examples
    ///
    /// ```
    /// use bio_forge::{BondOrder, Template};
    ///
    /// let atoms = vec!["P".into(), "O5'".into()];
    /// let template = Template::new("PO4", atoms.clone(), Vec::new());
    ///
    /// assert_eq!(template.atom_names(), atoms.as_slice());
    /// ```
    pub fn atom_names(&self) -> &[String] {
        &self.atom_names
    }

    /// Returns the list of bond definitions stored within the template.
    ///
    /// # Returns
    ///
    /// Borrowed slice of `(atom_a, atom_b, BondOrder)` tuples.
    ///
    /// # Examples
    ///
    /// ```
    /// use bio_forge::{BondOrder, Template};
    ///
    /// let atoms = vec!["C1".into(), "O1".into()];
    /// let bonds = vec![("C1".into(), "O1".into(), BondOrder::Double)];
    /// let template = Template::new("CO", atoms, bonds.clone());
    ///
    /// assert_eq!(template.bonds(), bonds.as_slice());
    /// ```
    pub fn bonds(&self) -> &[(String, String, BondOrder)] {
        &self.bonds
    }

    /// Counts atoms described by the template.
    ///
    /// # Returns
    ///
    /// Number of atom entries in `atom_names`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bio_forge::{BondOrder, Template};
    ///
    /// let template = Template::new("ION", vec!["K".into()], Vec::new());
    /// assert_eq!(template.atom_count(), 1);
    /// ```
    pub fn atom_count(&self) -> usize {
        self.atom_names.len()
    }

    /// Counts bonds described by the template.
    ///
    /// # Returns
    ///
    /// Number of bond tuples stored in `bonds`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bio_forge::{BondOrder, Template};
    ///
    /// let atoms = vec!["C".into(), "O".into()];
    /// let bonds = vec![("C".into(), "O".into(), BondOrder::Double)];
    /// let template = Template::new("CO", atoms, bonds);
    ///
    /// assert_eq!(template.bond_count(), 1);
    /// ```
    pub fn bond_count(&self) -> usize {
        self.bonds.len()
    }
}

impl fmt::Display for Template {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Template {{ name: \"{}\", atoms: {}, bonds: {} }}",
            self.name,
            self.atom_count(),
            self.bond_count()
        )
    }
}

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

    #[test]
    fn template_new_creates_correct_template() {
        let atom_names = vec!["C1".to_string(), "C2".to_string(), "O1".to_string()];
        let bonds = vec![
            ("C1".to_string(), "C2".to_string(), BondOrder::Single),
            ("C2".to_string(), "O1".to_string(), BondOrder::Double),
        ];

        let template = Template::new("LIG", atom_names.clone(), bonds.clone());

        assert_eq!(template.name, "LIG");
        assert_eq!(template.atom_names, atom_names);
        assert_eq!(template.bonds, bonds);
    }

    #[test]
    fn template_new_with_empty_atom_names() {
        let atom_names = Vec::new();
        let bonds = Vec::new();

        let template = Template::new("EMPTY", atom_names, bonds);

        assert_eq!(template.name, "EMPTY");
        assert_eq!(template.atom_count(), 0);
        assert_eq!(template.bond_count(), 0);
    }

    #[test]
    fn template_new_with_empty_bonds() {
        let atom_names = vec!["C1".to_string(), "C2".to_string()];
        let bonds = Vec::new();

        let template = Template::new("NO_BONDS", atom_names.clone(), bonds);

        assert_eq!(template.name, "NO_BONDS");
        assert_eq!(template.atom_names, atom_names);
        assert_eq!(template.bonds, Vec::new());
    }

    #[test]
    fn template_new_with_string_name() {
        let atom_names = vec!["N1".to_string()];
        let bonds = Vec::new();

        let template = Template::new(String::from("ATP"), atom_names.clone(), bonds);

        assert_eq!(template.name, "ATP");
        assert_eq!(template.atom_names, atom_names);
    }

    #[test]
    fn template_has_bond_returns_true_for_existing_bond() {
        let atom_names = vec!["C1".to_string(), "C2".to_string(), "O1".to_string()];
        let bonds = vec![
            ("C1".to_string(), "C2".to_string(), BondOrder::Single),
            ("C2".to_string(), "O1".to_string(), BondOrder::Double),
        ];
        let template = Template::new("LIG", atom_names, bonds);

        assert!(template.has_bond("C1", "C2"));
        assert!(template.has_bond("C2", "O1"));
    }

    #[test]
    fn template_has_bond_returns_true_for_reverse_order() {
        let atom_names = vec!["C1".to_string(), "C2".to_string()];
        let bonds = vec![("C1".to_string(), "C2".to_string(), BondOrder::Single)];
        let template = Template::new("LIG", atom_names, bonds);

        assert!(template.has_bond("C2", "C1"));
    }

    #[test]
    fn template_has_bond_returns_false_for_nonexistent_bond() {
        let atom_names = vec!["C1".to_string(), "C2".to_string(), "O1".to_string()];
        let bonds = vec![("C1".to_string(), "C2".to_string(), BondOrder::Single)];
        let template = Template::new("LIG", atom_names, bonds);

        assert!(!template.has_bond("C1", "O1"));
        assert!(!template.has_bond("O1", "C2"));
    }

    #[test]
    fn template_has_bond_returns_false_for_empty_template() {
        let template = Template::new("EMPTY", Vec::new(), Vec::new());

        assert!(!template.has_bond("C1", "C2"));
    }

    #[test]
    fn template_has_atom_returns_true_for_existing_atom() {
        let atom_names = vec!["C1".to_string(), "C2".to_string(), "O1".to_string()];
        let bonds = Vec::new();
        let template = Template::new("LIG", atom_names, bonds);

        assert!(template.has_atom("C1"));
        assert!(template.has_atom("C2"));
        assert!(template.has_atom("O1"));
    }

    #[test]
    fn template_has_atom_returns_false_for_nonexistent_atom() {
        let atom_names = vec!["C1".to_string(), "C2".to_string()];
        let bonds = Vec::new();
        let template = Template::new("LIG", atom_names, bonds);

        assert!(!template.has_atom("O1"));
        assert!(!template.has_atom("N1"));
    }

    #[test]
    fn template_has_atom_returns_false_for_empty_template() {
        let template = Template::new("EMPTY", Vec::new(), Vec::new());

        assert!(!template.has_atom("C1"));
    }

    #[test]
    fn template_atom_names_returns_correct_slice() {
        let atom_names = vec!["C1".to_string(), "C2".to_string(), "O1".to_string()];
        let bonds = Vec::new();
        let template = Template::new("LIG", atom_names.clone(), bonds);

        let names = template.atom_names();

        assert_eq!(names, atom_names.as_slice());
        assert_eq!(names.len(), 3);
        assert_eq!(names[0], "C1");
        assert_eq!(names[1], "C2");
        assert_eq!(names[2], "O1");
    }

    #[test]
    fn template_atom_names_returns_empty_slice_for_empty_template() {
        let template = Template::new("EMPTY", Vec::new(), Vec::new());

        let names = template.atom_names();

        assert_eq!(names, &[] as &[String]);
        assert_eq!(names.len(), 0);
    }

    #[test]
    fn template_bonds_returns_correct_slice() {
        let atom_names = vec!["C1".to_string(), "C2".to_string(), "O1".to_string()];
        let bonds = vec![
            ("C1".to_string(), "C2".to_string(), BondOrder::Single),
            ("C2".to_string(), "O1".to_string(), BondOrder::Double),
        ];
        let template = Template::new("LIG", atom_names, bonds.clone());

        let template_bonds = template.bonds();

        assert_eq!(template_bonds, bonds.as_slice());
        assert_eq!(template_bonds.len(), 2);
        assert_eq!(
            template_bonds[0],
            ("C1".to_string(), "C2".to_string(), BondOrder::Single)
        );
        assert_eq!(
            template_bonds[1],
            ("C2".to_string(), "O1".to_string(), BondOrder::Double)
        );
    }

    #[test]
    fn template_bonds_returns_empty_slice_for_empty_template() {
        let template = Template::new("EMPTY", Vec::new(), Vec::new());

        let bonds = template.bonds();

        assert_eq!(bonds, &[]);
        assert_eq!(bonds.len(), 0);
    }

    #[test]
    fn template_atom_count_returns_correct_count() {
        let atom_names = vec![
            "C1".to_string(),
            "C2".to_string(),
            "O1".to_string(),
            "N1".to_string(),
        ];
        let bonds = Vec::new();
        let template = Template::new("LIG", atom_names, bonds);

        assert_eq!(template.atom_count(), 4);
    }

    #[test]
    fn template_atom_count_returns_zero_for_empty_template() {
        let template = Template::new("EMPTY", Vec::new(), Vec::new());

        assert_eq!(template.atom_count(), 0);
    }

    #[test]
    fn template_bond_count_returns_correct_count() {
        let atom_names = vec!["C1".to_string(), "C2".to_string(), "O1".to_string()];
        let bonds = vec![
            ("C1".to_string(), "C2".to_string(), BondOrder::Single),
            ("C2".to_string(), "O1".to_string(), BondOrder::Double),
            ("C1".to_string(), "O1".to_string(), BondOrder::Single),
        ];
        let template = Template::new("LIG", atom_names, bonds);

        assert_eq!(template.bond_count(), 3);
    }

    #[test]
    fn template_bond_count_returns_zero_for_empty_template() {
        let template = Template::new("EMPTY", Vec::new(), Vec::new());

        assert_eq!(template.bond_count(), 0);
    }

    #[test]
    fn template_display_formats_correctly() {
        let atom_names = vec!["C1".to_string(), "C2".to_string(), "O1".to_string()];
        let bonds = vec![
            ("C1".to_string(), "C2".to_string(), BondOrder::Single),
            ("C2".to_string(), "O1".to_string(), BondOrder::Double),
        ];
        let template = Template::new("LIG", atom_names, bonds);

        let display = format!("{}", template);
        let expected = "Template { name: \"LIG\", atoms: 3, bonds: 2 }";

        assert_eq!(display, expected);
    }

    #[test]
    fn template_display_formats_empty_template_correctly() {
        let template = Template::new("EMPTY", Vec::new(), Vec::new());

        let display = format!("{}", template);
        let expected = "Template { name: \"EMPTY\", atoms: 0, bonds: 0 }";

        assert_eq!(display, expected);
    }

    #[test]
    fn template_display_formats_template_with_special_characters() {
        let atom_names = vec!["C1".to_string()];
        let bonds = Vec::new();
        let template = Template::new("LIG-123", atom_names, bonds);

        let display = format!("{}", template);
        let expected = "Template { name: \"LIG-123\", atoms: 1, bonds: 0 }";

        assert_eq!(display, expected);
    }

    #[test]
    fn template_clone_creates_identical_copy() {
        let atom_names = vec!["C1".to_string(), "C2".to_string()];
        let bonds = vec![("C1".to_string(), "C2".to_string(), BondOrder::Single)];
        let template = Template::new("LIG", atom_names.clone(), bonds.clone());

        let cloned = template.clone();

        assert_eq!(template, cloned);
        assert_eq!(template.name, cloned.name);
        assert_eq!(template.atom_names, cloned.atom_names);
        assert_eq!(template.bonds, cloned.bonds);
    }

    #[test]
    fn template_partial_eq_compares_correctly() {
        let atom_names = vec!["C1".to_string(), "C2".to_string()];
        let bonds = vec![("C1".to_string(), "C2".to_string(), BondOrder::Single)];

        let template1 = Template::new("LIG", atom_names.clone(), bonds.clone());
        let template2 = Template::new("LIG", atom_names.clone(), bonds.clone());
        let template3 = Template::new("DIF", atom_names.clone(), bonds.clone());

        assert_eq!(template1, template2);
        assert_ne!(template1, template3);
    }

    #[test]
    fn template_with_complex_molecule() {
        let atom_names = vec![
            "C1".to_string(),
            "C2".to_string(),
            "O1".to_string(),
            "H11".to_string(),
            "H12".to_string(),
            "H13".to_string(),
            "H21".to_string(),
            "H22".to_string(),
            "H1".to_string(),
        ];
        let bonds = vec![
            ("C1".to_string(), "C2".to_string(), BondOrder::Single),
            ("C2".to_string(), "O1".to_string(), BondOrder::Single),
            ("C1".to_string(), "H11".to_string(), BondOrder::Single),
            ("C1".to_string(), "H12".to_string(), BondOrder::Single),
            ("C1".to_string(), "H13".to_string(), BondOrder::Single),
            ("C2".to_string(), "H21".to_string(), BondOrder::Single),
            ("C2".to_string(), "H22".to_string(), BondOrder::Single),
            ("O1".to_string(), "H1".to_string(), BondOrder::Single),
        ];

        let template = Template::new("ETOH", atom_names, bonds);

        assert_eq!(template.name, "ETOH");
        assert_eq!(template.atom_count(), 9);
        assert_eq!(template.bond_count(), 8);

        assert!(template.has_bond("C1", "C2"));
        assert!(template.has_bond("C2", "O1"));
        assert!(template.has_bond("O1", "H1"));

        assert!(template.has_atom("C1"));
        assert!(template.has_atom("H1"));
        assert!(!template.has_atom("C3"));
    }

    #[test]
    fn template_with_aromatic_bonds() {
        let atom_names = vec!["C1".to_string(), "C2".to_string(), "C3".to_string()];
        let bonds = vec![
            ("C1".to_string(), "C2".to_string(), BondOrder::Aromatic),
            ("C2".to_string(), "C3".to_string(), BondOrder::Aromatic),
            ("C3".to_string(), "C1".to_string(), BondOrder::Aromatic),
        ];

        let template = Template::new("BENZENE_RING", atom_names, bonds);

        assert_eq!(template.bond_count(), 3);
        assert!(template.has_bond("C1", "C2"));
        assert!(template.has_bond("C2", "C3"));
        assert!(template.has_bond("C3", "C1"));
    }

    #[test]
    fn template_with_triple_bond() {
        let atom_names = vec!["N1".to_string(), "N2".to_string()];
        let bonds = vec![("N1".to_string(), "N2".to_string(), BondOrder::Triple)];

        let template = Template::new("N2", atom_names, bonds);

        assert_eq!(template.bond_count(), 1);
        assert!(template.has_bond("N1", "N2"));
        assert!(!template.has_bond("N1", "N3"));
    }
}