mordred-core 0.1.0

Core molecular descriptor calculator — Rust port of mordred
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
/// SMILES parser — supports a practical subset for descriptor calculation.
///
/// Supports: organic subset atoms (B, C, N, O, P, S, F, Cl, Br, I),
/// bracket atoms [Fe], bonds (-, =, #, :), branches, ring closures,
/// aromatic atoms (c, n, o, s, p), charges, and hydrogen counts.
use petgraph::graph::NodeIndex;

use super::atom::Atom;
use super::bond::{Bond, BondOrder};
use super::element::Element;
use super::mol::Molecule;
use crate::error::MordredError;

/// Parse a SMILES string into a Molecule.
pub fn parse_smiles(smiles: &str) -> Result<Molecule, MordredError> {
    let mut parser = SmilesParser::new(smiles);
    parser.parse()?;
    parser.fill_implicit_hydrogens();
    Ok(parser.mol)
}

struct SmilesParser {
    chars: Vec<char>,
    pos: usize,
    mol: Molecule,
    stack: Vec<NodeIndex>,
    ring_opens: std::collections::HashMap<u8, (NodeIndex, Option<BondOrder>)>,
    pending_bond: Option<BondOrder>,
}

impl SmilesParser {
    fn new(smiles: &str) -> Self {
        Self {
            chars: smiles.chars().collect(),
            pos: 0,
            mol: Molecule::new(),
            stack: Vec::new(),
            ring_opens: std::collections::HashMap::new(),
            pending_bond: None,
        }
    }

    fn peek(&self) -> Option<char> {
        self.chars.get(self.pos).copied()
    }

    fn advance(&mut self) -> Option<char> {
        let c = self.chars.get(self.pos).copied();
        if c.is_some() {
            self.pos += 1;
        }
        c
    }

    fn parse(&mut self) -> Result<(), MordredError> {
        while self.pos < self.chars.len() {
            match self.peek() {
                Some('(') => {
                    self.advance();
                    // Push current atom onto branch stack
                    if let Some(&top) = self.stack.last() {
                        self.stack.push(top);
                    }
                }
                Some(')') => {
                    self.advance();
                    self.stack.pop();
                }
                Some('-') => {
                    self.advance();
                    self.pending_bond = Some(BondOrder::Single);
                }
                Some('=') => {
                    self.advance();
                    self.pending_bond = Some(BondOrder::Double);
                }
                Some('#') => {
                    self.advance();
                    self.pending_bond = Some(BondOrder::Triple);
                }
                Some(':') => {
                    self.advance();
                    self.pending_bond = Some(BondOrder::Aromatic);
                }
                Some('[') => {
                    let atom = self.parse_bracket_atom()?;
                    self.add_atom_and_bond(atom);
                }
                Some(c) if c.is_ascii_digit() => {
                    self.advance();
                    let ring_num = c as u8 - b'0';
                    self.handle_ring_closure(ring_num)?;
                }
                Some('%') => {
                    // Two-digit ring closure
                    self.advance();
                    let d1 = self.advance().ok_or(MordredError::SmilesParseError(
                        "unexpected end after %".into(),
                    ))?;
                    let d2 = self.advance().ok_or(MordredError::SmilesParseError(
                        "unexpected end after %digit".into(),
                    ))?;
                    let ring_num = (d1 as u8 - b'0') * 10 + (d2 as u8 - b'0');
                    self.handle_ring_closure(ring_num)?;
                }
                Some('/') | Some('\\') => {
                    self.advance();
                    // Cis/trans bond stereo — skip (no-op for 2D descriptors)
                }
                Some('.') => {
                    self.advance();
                    // Disconnected fragment — reset stack connection
                    self.stack.clear();
                }
                Some(c) => {
                    let atom = self.parse_organic_atom(c)?;
                    self.add_atom_and_bond(atom);
                }
                None => break,
            }
        }
        Ok(())
    }

    fn parse_organic_atom(&mut self, c: char) -> Result<Atom, MordredError> {
        self.advance();
        let is_aromatic = c.is_ascii_lowercase();
        let symbol = if is_aromatic {
            c.to_ascii_uppercase().to_string()
        } else {
            // Check for two-letter elements
            let mut s = c.to_string();
            if let Some(next) = self.peek() {
                if next.is_ascii_lowercase() && !is_aromatic_organic(next) {
                    let two = format!("{}{}", c, next);
                    if Element::from_symbol(&two).is_some() {
                        self.advance();
                        s = two;
                    }
                }
            }
            s
        };

        let element = Element::from_symbol(&symbol).ok_or_else(|| {
            MordredError::SmilesParseError(format!("unknown element: {}", symbol))
        })?;

        let mut atom = Atom::new(element);
        atom.is_aromatic = is_aromatic;
        Ok(atom)
    }

    fn parse_bracket_atom(&mut self) -> Result<Atom, MordredError> {
        self.advance(); // consume '['

        let mut isotope = None;
        // Parse optional isotope
        if self.peek().is_some_and(|c| c.is_ascii_digit()) {
            let mut num = 0u16;
            while self.peek().is_some_and(|c| c.is_ascii_digit()) {
                num = num * 10 + (self.advance().unwrap() as u16 - '0' as u16);
            }
            isotope = Some(num);
        }

        // Parse element symbol
        let first = self.advance().ok_or(MordredError::SmilesParseError(
            "unexpected end in bracket atom".into(),
        ))?;

        let is_aromatic = first.is_ascii_lowercase();
        let mut symbol = if is_aromatic {
            first.to_ascii_uppercase().to_string()
        } else {
            first.to_string()
        };

        // Check for second lowercase letter (two-letter element)
        if self.peek().is_some_and(|c| c.is_ascii_lowercase()) {
            let two = format!("{}{}", symbol.chars().next().unwrap(), self.peek().unwrap());
            if Element::from_symbol(&two).is_some() {
                self.advance();
                symbol = two;
            }
        }

        let element = Element::from_symbol(&symbol).ok_or_else(|| {
            MordredError::SmilesParseError(format!("unknown element: {}", symbol))
        })?;

        let mut atom = Atom::new(element);
        atom.is_aromatic = is_aromatic;
        atom.isotope = isotope;

        // Parse optional H count
        if self.peek() == Some('H') {
            self.advance();
            if self.peek().is_some_and(|c| c.is_ascii_digit()) {
                atom.implicit_h = self.advance().unwrap() as u8 - b'0';
            } else {
                atom.implicit_h = 1;
            }
        }

        // Parse optional charge
        if self.peek() == Some('+') {
            self.advance();
            if self.peek().is_some_and(|c| c.is_ascii_digit()) {
                atom.charge = (self.advance().unwrap() as u8 - b'0') as i8;
            } else if self.peek() == Some('+') {
                self.advance();
                atom.charge = 2;
            } else {
                atom.charge = 1;
            }
        } else if self.peek() == Some('-') {
            self.advance();
            if self.peek().is_some_and(|c| c.is_ascii_digit()) {
                atom.charge = -((self.advance().unwrap() as u8 - b'0') as i8);
            } else if self.peek() == Some('-') {
                self.advance();
                atom.charge = -2;
            } else {
                atom.charge = -1;
            }
        }

        // Skip to closing bracket (ignore stereo, etc.)
        while self.peek() != Some(']') && self.peek().is_some() {
            self.advance();
        }
        self.advance(); // consume ']'

        Ok(atom)
    }

    fn add_atom_and_bond(&mut self, atom: Atom) {
        let is_aromatic = atom.is_aromatic;
        let idx = self.mol.add_atom(atom);

        if let Some(&prev) = self.stack.last() {
            let order = self.pending_bond.take().unwrap_or_else(|| {
                if is_aromatic && self.mol.graph[prev].is_aromatic {
                    BondOrder::Aromatic
                } else {
                    BondOrder::Single
                }
            });
            self.mol.add_bond(prev, idx, Bond::new(order));
        }
        self.pending_bond = None;

        // Replace top of stack with current atom
        if self.stack.is_empty() {
            self.stack.push(idx);
        } else {
            *self.stack.last_mut().unwrap() = idx;
        }
    }

    fn handle_ring_closure(&mut self, ring_num: u8) -> Result<(), MordredError> {
        let current = *self.stack.last().ok_or(MordredError::SmilesParseError(
            "ring closure with no current atom".into(),
        ))?;

        if let Some((open_idx, open_bond)) = self.ring_opens.remove(&ring_num) {
            let order = self.pending_bond.take().or(open_bond).unwrap_or_else(|| {
                if self.mol.graph[current].is_aromatic && self.mol.graph[open_idx].is_aromatic {
                    BondOrder::Aromatic
                } else {
                    BondOrder::Single
                }
            });
            let mut bond = Bond::new(order);
            bond.is_ring = true;
            self.mol.add_bond(open_idx, current, bond);
        } else {
            self.ring_opens
                .insert(ring_num, (current, self.pending_bond.take()));
        }
        Ok(())
    }

    /// Fill implicit hydrogen counts for organic-subset atoms that don't have them set.
    fn fill_implicit_hydrogens(&mut self) {
        let indices: Vec<NodeIndex> = self.mol.graph.node_indices().collect();
        for idx in indices {
            let atom = &self.mol.graph[idx];
            // Only fill for atoms that came from organic subset (not bracket atoms)
            // Bracket atoms already have explicit H counts.
            // We detect bracket atoms by checking if implicit_h was already set or isotope is present.
            if atom.isotope.is_some() {
                continue; // bracket atom, already handled
            }

            let valence = atom.element.default_valence();
            if valence == 0 {
                continue; // can't compute implicit H
            }

            let bond_valence: u8 = self
                .mol
                .graph
                .edges(idx)
                .map(|e| e.weight().order.valence_contribution())
                .sum();

            let atom = &mut self.mol.graph[idx];
            if atom.implicit_h == 0 && !atom.is_aromatic {
                atom.implicit_h = valence.saturating_sub(bond_valence);
            } else if atom.is_aromatic && atom.implicit_h == 0 {
                // Aromatic atoms have an additional bond from the pi system
                // that isn't represented as an explicit edge.
                // e.g. aromatic C has valence 4, 2 aromatic bonds + 1 pi = 3, so 1 implicit H.
                atom.implicit_h = valence.saturating_sub(bond_valence + 1);
            }
        }
    }
}

fn is_aromatic_organic(c: char) -> bool {
    matches!(c, 'c' | 'n' | 'o' | 's' | 'p')
}

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

    #[test]
    fn test_parse_methane() {
        let mol = parse_smiles("C").unwrap();
        assert_eq!(mol.atom_count(), 1);
        assert_eq!(mol.graph[NodeIndex::new(0)].implicit_h, 4);
    }

    #[test]
    fn test_parse_ethanol() {
        let mol = parse_smiles("CCO").unwrap();
        assert_eq!(mol.atom_count(), 3);
        assert_eq!(mol.bond_count(), 2);
    }

    #[test]
    fn test_parse_benzene() {
        let mol = parse_smiles("c1ccccc1").unwrap();
        assert_eq!(mol.atom_count(), 6);
        assert_eq!(mol.bond_count(), 6);
    }

    #[test]
    fn test_parse_double_bond() {
        let mol = parse_smiles("C=O").unwrap();
        assert_eq!(mol.atom_count(), 2);
        assert_eq!(mol.bond_count(), 1);
    }

    #[test]
    fn test_parse_branch() {
        let mol = parse_smiles("CC(=O)O").unwrap(); // acetic acid
        assert_eq!(mol.atom_count(), 4);
        assert_eq!(mol.bond_count(), 3);
    }

    #[test]
    fn test_parse_bracket_atom() {
        let mol = parse_smiles("[Fe]").unwrap();
        assert_eq!(mol.atom_count(), 1);
        assert_eq!(mol.graph[NodeIndex::new(0)].element, Element::Fe);
    }

    #[test]
    fn test_parse_charged() {
        let mol = parse_smiles("[NH4+]").unwrap();
        assert_eq!(mol.graph[NodeIndex::new(0)].charge, 1);
        assert_eq!(mol.graph[NodeIndex::new(0)].implicit_h, 4);
    }

    #[test]
    fn test_parse_stereo_cis_trans() {
        // cis-2-butene: C/C=C\C
        let mol = parse_smiles("C/C=C\\C").unwrap();
        assert_eq!(mol.atom_count(), 4);
        assert_eq!(mol.bond_count(), 3);
    }

    #[test]
    fn test_parse_stereo_slash_forward() {
        // trans-2-butene: C/C=C/C
        let mol = parse_smiles("C/C=C/C").unwrap();
        assert_eq!(mol.atom_count(), 4);
        assert_eq!(mol.bond_count(), 3);
    }

    #[test]
    fn test_parse_chiral() {
        // L-alanine
        let mol = parse_smiles("[C@@H](N)(C)C(=O)O").unwrap();
        assert!(mol.atom_count() > 0);
    }

    #[test]
    fn test_parse_chiral_single_at() {
        // Chiral center with single @
        let mol = parse_smiles("[C@H](F)(Cl)Br").unwrap();
        assert_eq!(mol.atom_count(), 4);
    }
}