dreid-typer 0.1.0

A pure Rust library for DREIDING atom typing and molecular topology perception.
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
//! Topology construction from processed molecular graphs.
//!
//! This module implements the building phase of the dreid-typer pipeline, converting a
//! `ProcessingGraph` with assigned atom types into a complete `MolecularTopology` containing
//! atoms, bonds, angles, and dihedrals for molecular simulation.

use crate::core::Hybridization;
use crate::core::error::TyperError;
use crate::core::graph::{
    Angle, Atom, Bond, ImproperDihedral, MolecularGraph, MolecularTopology, ProperDihedral,
};
use crate::processor::ProcessingGraph;
use std::collections::HashSet;

/// Constructs a complete molecular topology from processed graphs and atom types.
///
/// This function orchestrates the final building phase, combining information from the
/// initial molecular graph and the processed graph with assigned types to create all
/// topological elements needed for force field calculations.
///
/// # Arguments
///
/// * `initial_graph` - The original molecular graph with basic connectivity.
/// * `processing_graph` - The annotated processing graph with chemical properties.
/// * `atom_types` - The assigned DREIDING atom types for each atom.
///
/// # Returns
///
/// A complete `MolecularTopology` with atoms, bonds, angles, and dihedrals.
pub(crate) fn build_topology(
    initial_graph: &MolecularGraph,
    processing_graph: &ProcessingGraph,
    atom_types: &[String],
) -> Result<MolecularTopology, TyperError> {
    let atoms = build_atoms(processing_graph, atom_types);
    let bonds = build_bonds(initial_graph);
    let angles = build_angles(processing_graph);
    let proper_dihedrals = build_proper_dihedrals(processing_graph);
    let improper_dihedrals = build_improper_dihedrals(processing_graph);

    Ok(MolecularTopology {
        atoms,
        bonds: bonds.into_iter().collect(),
        angles: angles.into_iter().collect(),
        proper_dihedrals: proper_dihedrals.into_iter().collect(),
        improper_dihedrals: improper_dihedrals.into_iter().collect(),
    })
}

/// Creates topology atoms from processing graph atoms and assigned types.
///
/// Maps each atom view to a topology atom, incorporating the assigned DREIDING type
/// and hybridization information for force field calculations.
///
/// # Arguments
///
/// * `processing_graph` - The graph containing atom properties.
/// * `atom_types` - The assigned atom types corresponding to each atom.
///
/// # Returns
///
/// A vector of topology atoms.
fn build_atoms(processing_graph: &ProcessingGraph, atom_types: &[String]) -> Vec<Atom> {
    processing_graph
        .atoms
        .iter()
        .map(|atom_view| Atom {
            id: atom_view.id,
            element: atom_view.element,
            atom_type: atom_types[atom_view.id].clone(),
            hybridization: atom_view.hybridization,
        })
        .collect()
}

/// Extracts bond topology from the initial molecular graph.
///
/// Converts the graph's edge list into a set of topology bonds, preserving
/// bond orders for force field parameterization.
///
/// # Arguments
///
/// * `initial_graph` - The molecular graph with bond connectivity.
///
/// # Returns
///
/// A set of topology bonds.
fn build_bonds(initial_graph: &MolecularGraph) -> HashSet<Bond> {
    initial_graph
        .bonds
        .iter()
        .map(|edge| {
            let (u, v) = edge.atom_ids;
            Bond::new(u, v, edge.order)
        })
        .collect()
}

/// Generates all three-atom angles from the molecular connectivity.
///
/// For each atom with multiple neighbors, creates angles between all pairs of neighbors.
/// This ensures complete angle coverage for force field calculations.
///
/// # Arguments
///
/// * `graph` - The processing graph with adjacency information.
///
/// # Returns
///
/// A set of topology angles.
fn build_angles(graph: &ProcessingGraph) -> HashSet<Angle> {
    let mut angles = HashSet::new();
    for j in 0..graph.atoms.len() {
        let neighbors = &graph.adjacency[j];
        if neighbors.len() < 2 {
            continue;
        }

        // Generate angles between all pairs of neighbors around atom j.
        for i_idx in 0..neighbors.len() {
            for k_idx in (i_idx + 1)..neighbors.len() {
                let i = neighbors[i_idx].0;
                let k = neighbors[k_idx].0;
                angles.insert(Angle::new(i, j, k));
            }
        }
    }
    angles
}

/// Generates all four-atom proper dihedrals from molecular connectivity.
///
/// Enumerates all paths of length 3 (i-j-k-l) where j and k are connected,
/// ensuring each dihedral is represented in canonical order to avoid duplicates.
///
/// # Arguments
///
/// * `graph` - The processing graph with adjacency information.
///
/// # Returns
///
/// A set of topology proper dihedrals.
fn build_proper_dihedrals(graph: &ProcessingGraph) -> HashSet<ProperDihedral> {
    let mut dihedrals = HashSet::new();
    for j in 0..graph.atoms.len() {
        for &(k, _) in &graph.adjacency[j] {
            if j >= k {
                continue;
            }

            // Avoid duplicate dihedrals by canonical ordering.
            for &(i, _) in &graph.adjacency[j] {
                if i == k {
                    continue;
                }

                for &(l, _) in &graph.adjacency[k] {
                    if l == j {
                        continue;
                    }

                    dihedrals.insert(ProperDihedral::new(i, j, k, l));
                }
            }
        }
    }
    dihedrals
}

/// Generates improper dihedrals for planar atoms in DREIDING force field.
///
/// Creates improper dihedrals for atoms with three neighbors and SP2 or resonant hybridization,
/// which require planarity constraints in molecular mechanics.
///
/// # Arguments
///
/// * `graph` - The processing graph with hybridization information.
///
/// # Returns
///
/// A set of topology improper dihedrals.
fn build_improper_dihedrals(graph: &ProcessingGraph) -> HashSet<ImproperDihedral> {
    let mut dihedrals = HashSet::new();
    for i in 0..graph.atoms.len() {
        let atom = &graph.atoms[i];

        if atom.degree == 3 {
            // Only planar atoms (SP2 or resonant) need improper dihedrals for planarity.
            if matches!(
                atom.hybridization,
                Hybridization::SP2 | Hybridization::Resonant
            ) {
                let neighbors = &graph.adjacency[i];
                let j = neighbors[0].0;
                let k = neighbors[1].0;
                let l = neighbors[2].0;

                dihedrals.insert(ImproperDihedral::new(j, k, i, l));
            }
        }
    }
    dihedrals
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::graph::AtomNode;
    use crate::core::{BondOrder, Element};
    use crate::processor::{AtomView, ProcessingGraph};

    struct TestMolecule {
        initial_graph: MolecularGraph,
        processing_graph: ProcessingGraph,
        atom_types: Vec<String>,
    }

    impl TestMolecule {
        fn new(atoms: &[(Element, Hybridization, &str)]) -> Self {
            let mut initial_graph = MolecularGraph::new();
            let mut atom_views = Vec::new();
            let mut atom_types = Vec::new();

            for (i, (element, hybridization, atom_type)) in atoms.iter().enumerate() {
                initial_graph.atoms.push(AtomNode {
                    id: i,
                    element: *element,
                    formal_charge: 0,
                });
                atom_views.push(AtomView {
                    id: i,
                    element: *element,
                    formal_charge: 0,
                    degree: 0,
                    valence_electrons: 0,
                    bonding_electrons: 0,
                    lone_pairs: 0,
                    steric_number: 0,
                    hybridization: *hybridization,
                    is_in_ring: false,
                    smallest_ring_size: None,
                    is_aromatic: *hybridization == Hybridization::Resonant,
                    perception_source: None,
                });
                atom_types.push(atom_type.to_string());
            }

            Self {
                initial_graph,
                processing_graph: ProcessingGraph {
                    atoms: atom_views,
                    adjacency: vec![],
                },
                atom_types,
            }
        }

        fn with_bond(mut self, u: usize, v: usize, order: BondOrder) -> Self {
            self.initial_graph.add_bond(u, v, order).unwrap();
            self
        }

        fn build(mut self) -> Self {
            let num_atoms = self.initial_graph.atoms.len();
            let mut adjacency = vec![vec![]; num_atoms];
            for bond in &self.initial_graph.bonds {
                let (u, v) = bond.atom_ids;
                adjacency[u].push((v, bond.order));
                adjacency[v].push((u, bond.order));
            }

            for i in 0..num_atoms {
                self.processing_graph.atoms[i].degree = adjacency[i].len() as u8;
            }
            self.processing_graph.adjacency = adjacency;

            self
        }
    }

    #[test]
    fn test_build_methane_topology() {
        let molecule = TestMolecule::new(&[
            (Element::C, Hybridization::SP3, "C_3"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
        ])
        .with_bond(0, 1, BondOrder::Single)
        .with_bond(0, 2, BondOrder::Single)
        .with_bond(0, 3, BondOrder::Single)
        .with_bond(0, 4, BondOrder::Single)
        .build();

        let topology = build_topology(
            &molecule.initial_graph,
            &molecule.processing_graph,
            &molecule.atom_types,
        )
        .unwrap();

        assert_eq!(topology.atoms.len(), 5);
        assert_eq!(topology.bonds.len(), 4);
        assert_eq!(topology.angles.len(), 6);
        assert_eq!(topology.proper_dihedrals.len(), 0);
        assert_eq!(topology.improper_dihedrals.len(), 0);
    }

    #[test]
    fn test_build_ethane_topology() {
        let molecule = TestMolecule::new(&[
            (Element::C, Hybridization::SP3, "C_3"),
            (Element::C, Hybridization::SP3, "C_3"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
        ])
        .with_bond(0, 1, BondOrder::Single)
        .with_bond(0, 2, BondOrder::Single)
        .with_bond(0, 3, BondOrder::Single)
        .with_bond(0, 4, BondOrder::Single)
        .with_bond(1, 5, BondOrder::Single)
        .with_bond(1, 6, BondOrder::Single)
        .with_bond(1, 7, BondOrder::Single)
        .build();

        let topology = build_topology(
            &molecule.initial_graph,
            &molecule.processing_graph,
            &molecule.atom_types,
        )
        .unwrap();

        assert_eq!(topology.atoms.len(), 8);
        assert_eq!(topology.bonds.len(), 7);
        assert_eq!(topology.angles.len(), 12);
        assert_eq!(topology.proper_dihedrals.len(), 9);
        assert_eq!(topology.improper_dihedrals.len(), 0);
    }

    #[test]
    fn test_build_ethylene_topology() {
        let molecule = TestMolecule::new(&[
            (Element::C, Hybridization::SP2, "C_2"),
            (Element::C, Hybridization::SP2, "C_2"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
        ])
        .with_bond(0, 1, BondOrder::Double)
        .with_bond(0, 2, BondOrder::Single)
        .with_bond(0, 3, BondOrder::Single)
        .with_bond(1, 4, BondOrder::Single)
        .with_bond(1, 5, BondOrder::Single)
        .build();

        let topology = build_topology(
            &molecule.initial_graph,
            &molecule.processing_graph,
            &molecule.atom_types,
        )
        .unwrap();

        assert_eq!(topology.bonds.len(), 5);
        assert_eq!(topology.angles.len(), 6);
        assert_eq!(topology.proper_dihedrals.len(), 4);
        assert_eq!(topology.improper_dihedrals.len(), 2);

        assert!(
            topology
                .improper_dihedrals
                .contains(&ImproperDihedral::new(1, 2, 0, 3))
        );
        assert!(
            topology
                .improper_dihedrals
                .contains(&ImproperDihedral::new(0, 4, 1, 5))
        );
    }

    #[test]
    fn test_build_formaldehyde_topology() {
        let molecule = TestMolecule::new(&[
            (Element::C, Hybridization::SP2, "C_2"),
            (Element::O, Hybridization::SP2, "O_2"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
        ])
        .with_bond(0, 1, BondOrder::Double)
        .with_bond(0, 2, BondOrder::Single)
        .with_bond(0, 3, BondOrder::Single)
        .build();

        let topology = build_topology(
            &molecule.initial_graph,
            &molecule.processing_graph,
            &molecule.atom_types,
        )
        .unwrap();

        assert_eq!(topology.bonds.len(), 3);
        assert_eq!(topology.angles.len(), 3);
        assert_eq!(topology.proper_dihedrals.len(), 0);
        assert_eq!(topology.improper_dihedrals.len(), 1);
        assert!(
            topology
                .improper_dihedrals
                .contains(&ImproperDihedral::new(1, 2, 0, 3))
        );
    }

    #[test]
    fn test_build_benzene_topology() {
        let mut molecule_builder = TestMolecule::new(&[
            (Element::C, Hybridization::Resonant, "C_R"),
            (Element::C, Hybridization::Resonant, "C_R"),
            (Element::C, Hybridization::Resonant, "C_R"),
            (Element::C, Hybridization::Resonant, "C_R"),
            (Element::C, Hybridization::Resonant, "C_R"),
            (Element::C, Hybridization::Resonant, "C_R"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
        ]);

        for i in 0..6 {
            molecule_builder = molecule_builder.with_bond(i, (i + 1) % 6, BondOrder::Aromatic);
        }
        for i in 0..6 {
            molecule_builder = molecule_builder.with_bond(i, i + 6, BondOrder::Single);
        }

        let molecule = molecule_builder.build();

        let topology = build_topology(
            &molecule.initial_graph,
            &molecule.processing_graph,
            &molecule.atom_types,
        )
        .unwrap();

        let num_atoms = 12;
        let num_bonds = 12;
        let num_angles = 18;
        let num_proper_dihedrals = 24;
        let num_improper_dihedrals = 6;

        assert_eq!(topology.atoms.len(), num_atoms);
        assert_eq!(topology.bonds.len(), num_bonds);
        assert_eq!(topology.angles.len(), num_angles);
        assert_eq!(topology.proper_dihedrals.len(), num_proper_dihedrals);
        assert_eq!(topology.improper_dihedrals.len(), num_improper_dihedrals);

        assert!(
            topology
                .improper_dihedrals
                .contains(&ImproperDihedral::new(1, 5, 0, 6))
        );
    }

    #[test]
    fn test_build_diatomic_no_angles_or_dihedrals() {
        let molecule = TestMolecule::new(&[
            (Element::H, Hybridization::None, "H_"),
            (Element::H, Hybridization::None, "H_"),
        ])
        .with_bond(0, 1, BondOrder::Single)
        .build();

        let topology = build_topology(
            &molecule.initial_graph,
            &molecule.processing_graph,
            &molecule.atom_types,
        )
        .unwrap();

        assert_eq!(topology.bonds.len(), 1);
        assert_eq!(topology.angles.len(), 0);
        assert_eq!(topology.proper_dihedrals.len(), 0);
        assert_eq!(topology.improper_dihedrals.len(), 0);
    }
}