Skip to main content

qualia_core_db/domains/chemical/
organic_chemistry.rs

1//! Organic Chemistry Engine.
2//!
3//! Pure-Rust implementations of core organic-chemistry primitives:
4//! - SMILES parsing & molecular graph building
5//! - Molecular formula, exact weight, and isotope-aware mass
6//! - Lipinski Rule-of-Five, Veber, Ghose, Egan drug-likeness filters
7//! - LogP (Crippen–Wildman atomic contributions, 25 atom types)
8//! - TPSA (Ertl 2000 atomic contributions)
9//! - H-bond donors / acceptors, rotatable bonds, aromatic ring count
10//! - Functional group detection (20 groups via SMARTS-inspired pattern matching)
11//! - Chiral centre enumeration
12//! - Morgan circular fingerprint generation
13//! - Thermochemistry: Arrhenius, Gibbs–Helmholtz, van't Hoff, Henderson–Hasselbalch
14//! - Green chemistry: atom economy, E-factor, PMI, RME, yield-adjusted AE
15//! - pKa estimation (functional-group based)
16//! - SMILES structural validation
17//! - InChI / InChIKey format validation
18//!
19//! SHACL constraint name → function:
20//!   `qualia:validateSmiles`              → `validate_smiles()`
21//!   `qualia:validateInchi`               → `validate_inchi()`
22//!   `qualia:computeMolecularWeight`      → `exact_molecular_weight()`
23//!   `qualia:computeLogP`                 → `compute_logp()`
24//!   `qualia:computeTPSA`                 → `compute_tpsa()`
25//!   `qualia:evaluateLipinski`            → `evaluate_lipinski()`
26//!   `qualia:evaluateVeber`               → `evaluate_veber()`
27//!   `qualia:evaluateGhose`               → `evaluate_ghose()`
28//!   `qualia:evaluateEgan`                → `evaluate_egan()`
29//!   `qualia:detectFunctionalGroups`      → `detect_functional_groups()`
30//!   `qualia:computePka`                  → `estimate_pka()`
31//!   `qualia:computeChiralCenters`        → `count_chiral_centers()`
32//!   `qualia:generateCircularFingerprint` → `circular_fingerprint()`
33//!   `qualia:computeArrheniusRate`        → `arrhenius_rate()`
34//!   `qualia:computeGibbsEnergy`          → `gibbs_free_energy()`
35//!   `qualia:computeEquilibrium`          → `equilibrium_constant()`
36//!   `qualia:computeHendersonHasselbalch` → `henderson_hasselbalch()`
37//!   `qualia:computeAtomEconomy`          → `atom_economy()`
38//!   `qualia:computeEFactor`              → `e_factor()`
39//!   `qualia:computeGreenMetrics`         → `green_metrics()`
40
41// ─── Physical constants ───────────────────────────────────────────────────────
42
43/// Universal gas constant J / (mol·K)
44pub const R_J_MOL_K: f64 = 8.314_462_618;
45
46// ─── Atomic data ──────────────────────────────────────────────────────────────
47
48/// Monoisotopic / standard atomic weights (IUPAC 2021).
49const ATOMIC_WEIGHTS: &[(&str, f64)] = &[
50    ("H", 1.00794),
51    ("B", 10.811),
52    ("C", 12.011),
53    ("N", 14.007),
54    ("O", 15.999),
55    ("F", 18.998),
56    ("P", 30.974),
57    ("S", 32.06),
58    ("Cl", 35.45),
59    ("Br", 79.904),
60    ("I", 126.904),
61    ("Si", 28.085),
62    ("As", 74.922),
63    ("Se", 78.971),
64    ("Te", 127.6),
65];
66
67/// Atomic weight for `symbol` from `ATOMIC_WEIGHTS`; defaults to
68/// carbon (12.0) for unknown elements.
69fn atomic_weight(symbol: &str) -> f64 {
70    ATOMIC_WEIGHTS
71        .iter()
72        .find(|(s, _)| *s == symbol)
73        .map(|(_, w)| *w)
74        .unwrap_or(12.0) // default C
75}
76
77/// Default valences for the organic-subset elements.
78const VALENCES: &[(&str, u8)] = &[
79    ("C", 4),
80    ("N", 3),
81    ("O", 2),
82    ("S", 2),
83    ("S", 4),
84    ("S", 6),
85    ("P", 3),
86    ("P", 5),
87    ("F", 1),
88    ("Cl", 1),
89    ("Br", 1),
90    ("I", 1),
91    ("B", 3),
92    ("Si", 4),
93    ("Se", 2),
94    ("As", 3),
95];
96
97/// Default bonding valence for `symbol` (first entry wins for
98/// multi-valence elements like S/P); defaults to 4.
99pub fn default_valence(symbol: &str) -> u8 {
100    VALENCES
101        .iter()
102        .find(|(s, _)| *s == symbol)
103        .map(|(_, v)| *v)
104        .unwrap_or(4)
105}
106
107// ─── Molecule representation ──────────────────────────────────────────────────
108
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum BondOrder {
111    Single,
112    Double,
113    Triple,
114    Aromatic,
115}
116
117#[derive(Debug, Clone)]
118pub struct Bond {
119    pub atom_a: usize,
120    pub atom_b: usize,
121    pub order: BondOrder,
122    /// Set to true once ring-detection pass identifies this bond as part of a cycle.
123    pub in_ring: bool,
124}
125
126#[derive(Debug, Clone)]
127pub struct Atom {
128    pub element: String,
129    pub is_aromatic: bool,
130    pub charge: i8,
131    pub isotope: Option<u16>,
132    pub explicit_h: u8,
133    pub n_implicit_h: u8,
134    /// Number of heavy-atom bonds (computed after parsing).
135    pub degree: u8,
136    pub idx: usize,
137}
138
139#[derive(Debug, Clone)]
140pub struct Molecule {
141    pub smiles: String,
142    pub atoms: Vec<Atom>,
143    pub bonds: Vec<Bond>,
144    pub is_valid: bool,
145    pub error: Option<String>,
146}
147
148// ─── SMILES parser ────────────────────────────────────────────────────────────
149
150/// Parse a SMILES string into a `Molecule`.
151pub fn parse_smiles(smiles: &str) -> Molecule {
152    let chars: Vec<char> = smiles.chars().collect();
153    let n = chars.len();
154    let mut atoms: Vec<Atom> = Vec::new();
155    let mut bonds: Vec<Bond> = Vec::new();
156    let mut branch_stack: Vec<usize> = Vec::new();
157    let mut ring_map: std::collections::HashMap<u16, (usize, Option<BondOrder>)> =
158        std::collections::HashMap::new();
159    let mut current_atom: Option<usize> = None;
160    let mut pending_bond: Option<BondOrder> = None;
161    let mut pos = 0;
162    let mut error: Option<String> = None;
163
164    macro_rules! add_atom {
165        ($elem:expr, $aromatic:expr, $charge:expr, $isotope:expr, $explicit_h:expr) => {{
166            let idx = atoms.len();
167            let atom = Atom {
168                element: $elem.to_string(),
169                is_aromatic: $aromatic,
170                charge: $charge,
171                isotope: $isotope,
172                explicit_h: $explicit_h,
173                n_implicit_h: 0,
174                degree: 0,
175                idx,
176            };
177            atoms.push(atom);
178            if let Some(from) = current_atom {
179                let bond_order = pending_bond.take().unwrap_or_else(|| {
180                    if atoms[from].is_aromatic && $aromatic {
181                        BondOrder::Aromatic
182                    } else {
183                        BondOrder::Single
184                    }
185                });
186                bonds.push(Bond {
187                    atom_a: from,
188                    atom_b: idx,
189                    order: bond_order,
190                    in_ring: false,
191                });
192                atoms[from].degree += 1;
193                atoms[idx].degree += 1;
194            } else {
195                pending_bond = None;
196            }
197            current_atom = Some(idx);
198        }};
199    }
200
201    while pos < n {
202        let c = chars[pos];
203        match c {
204            // ── Branch open/close ─────────────────────────────────────────
205            '(' => {
206                if let Some(idx) = current_atom {
207                    branch_stack.push(idx);
208                }
209                pos += 1;
210            }
211            ')' => {
212                current_atom = branch_stack.pop();
213                pending_bond = None;
214                pos += 1;
215            }
216            // ── Explicit bond tokens ──────────────────────────────────────
217            '-' => {
218                pending_bond = Some(BondOrder::Single);
219                pos += 1;
220            }
221            '=' => {
222                pending_bond = Some(BondOrder::Double);
223                pos += 1;
224            }
225            '#' => {
226                pending_bond = Some(BondOrder::Triple);
227                pos += 1;
228            }
229            ':' => {
230                pending_bond = Some(BondOrder::Aromatic);
231                pos += 1;
232            }
233            // ── Disconnected structure ────────────────────────────────────
234            '.' => {
235                current_atom = None;
236                pending_bond = None;
237                pos += 1;
238            }
239            // ── Ring closures: single digit ───────────────────────────────
240            '0'..='9' => {
241                let rn = c as u16 - b'0' as u16;
242                close_or_open_ring(
243                    &mut ring_map,
244                    &mut bonds,
245                    &mut atoms,
246                    rn,
247                    current_atom,
248                    &mut pending_bond,
249                );
250                pos += 1;
251            }
252            // ── Ring closures: %nn ────────────────────────────────────────
253            '%' if pos + 2 < n => {
254                if let (Some(d1), Some(d2)) =
255                    (chars[pos + 1].to_digit(10), chars[pos + 2].to_digit(10))
256                {
257                    let rn = (d1 * 10 + d2) as u16;
258                    close_or_open_ring(
259                        &mut ring_map,
260                        &mut bonds,
261                        &mut atoms,
262                        rn,
263                        current_atom,
264                        &mut pending_bond,
265                    );
266                    pos += 3;
267                } else {
268                    pos += 1;
269                }
270            }
271            // ── Bracketed atom [isotope?Symbol charge? Hn?] ──────────────
272            '[' => {
273                let (atom_elem, aromatic, charge, isotope, expl_h, advance) =
274                    parse_bracket_atom(&chars, pos);
275                add_atom!(atom_elem, aromatic, charge, isotope, expl_h);
276                pos += advance;
277            }
278            // ── Two-letter organic-subset atoms ───────────────────────────
279            'C' if pos + 1 < n && chars[pos + 1] == 'l' => {
280                add_atom!("Cl", false, 0, None, 0);
281                pos += 2;
282            }
283            'B' if pos + 1 < n && chars[pos + 1] == 'r' => {
284                add_atom!("Br", false, 0, None, 0);
285                pos += 2;
286            }
287            // ── Single-letter organic subset ──────────────────────────────
288            'C' => {
289                add_atom!("C", false, 0, None, 0);
290                pos += 1;
291            }
292            'c' => {
293                add_atom!("C", true, 0, None, 0);
294                pos += 1;
295            }
296            'N' => {
297                add_atom!("N", false, 0, None, 0);
298                pos += 1;
299            }
300            'n' => {
301                add_atom!("N", true, 0, None, 0);
302                pos += 1;
303            }
304            'O' => {
305                add_atom!("O", false, 0, None, 0);
306                pos += 1;
307            }
308            'o' => {
309                add_atom!("O", true, 0, None, 0);
310                pos += 1;
311            }
312            'S' => {
313                add_atom!("S", false, 0, None, 0);
314                pos += 1;
315            }
316            's' => {
317                add_atom!("S", true, 0, None, 0);
318                pos += 1;
319            }
320            'P' => {
321                add_atom!("P", false, 0, None, 0);
322                pos += 1;
323            }
324            'p' => {
325                add_atom!("P", true, 0, None, 0);
326                pos += 1;
327            }
328            'F' => {
329                add_atom!("F", false, 0, None, 0);
330                pos += 1;
331            }
332            'B' => {
333                add_atom!("B", false, 0, None, 0);
334                pos += 1;
335            }
336            'I' => {
337                add_atom!("I", false, 0, None, 0);
338                pos += 1;
339            }
340            _ => {
341                pos += 1;
342            }
343        }
344    }
345
346    // Validate unclosed rings
347    if !ring_map.is_empty() {
348        error = Some(format!(
349            "Unclosed ring bonds: {:?}",
350            ring_map.keys().collect::<Vec<_>>()
351        ));
352    }
353
354    // Compute implicit hydrogens and adjacency
355    fill_implicit_hydrogens(&mut atoms, &bonds);
356    // Mark ring bonds via DFS
357    mark_ring_bonds(&atoms, &mut bonds);
358
359    Molecule {
360        smiles: smiles.to_string(),
361        is_valid: error.is_none() && !atoms.is_empty(),
362        error,
363        atoms,
364        bonds,
365    }
366}
367
368/// SMILES ring digit handling: on the second occurrence of `ring_num`,
369/// emit the closing bond between the recorded open atom and
370/// `current_atom` (bond order = explicit pending, recorded, or single);
371/// on the first, record the opening atom and pending bond order.
372fn close_or_open_ring(
373    ring_map: &mut std::collections::HashMap<u16, (usize, Option<BondOrder>)>,
374    bonds: &mut Vec<Bond>,
375    atoms: &mut Vec<Atom>,
376    ring_num: u16,
377    current_atom: Option<usize>,
378    pending_bond: &mut Option<BondOrder>,
379) {
380    let from_atom = match current_atom {
381        Some(i) => i,
382        None => return,
383    };
384    if let Some((open_idx, open_bond)) = ring_map.remove(&ring_num) {
385        let order = pending_bond
386            .take()
387            .or(open_bond)
388            .unwrap_or(BondOrder::Single);
389        bonds.push(Bond {
390            atom_a: open_idx,
391            atom_b: from_atom,
392            order,
393            in_ring: true,
394        });
395        atoms[open_idx].degree += 1;
396        atoms[from_atom].degree += 1;
397    } else {
398        ring_map.insert(ring_num, (from_atom, pending_bond.take()));
399    }
400}
401
402/// Parse a bracketed atom [isotope?Symbol charge? Hn?]. Returns (elem, aromatic, charge, isotope, explicit_h, chars_consumed).
403fn parse_bracket_atom(
404    chars: &[char],
405    start: usize,
406) -> (&'static str, bool, i8, Option<u16>, u8, usize) {
407    let mut pos = start + 1; // skip '['
408    let end = chars.len();
409
410    // Isotope
411    let mut isotope_str = String::new();
412    while pos < end && chars[pos].is_ascii_digit() {
413        isotope_str.push(chars[pos]);
414        pos += 1;
415    }
416    let isotope: Option<u16> = isotope_str.parse().ok();
417
418    // Element symbol (1-2 chars, first uppercase)
419    let sym_start = pos;
420    if pos < end {
421        pos += 1;
422    }
423    if pos < end && chars[pos].is_ascii_lowercase() && chars[pos] != 'h' {
424        pos += 1;
425    }
426    let sym: String = chars[sym_start..pos].iter().collect();
427
428    // Aromaticity: if symbol is lowercase that's already handled by aromatic atoms above;
429    // inside brackets, aromatic lowercase atoms are also valid
430    let is_aromatic = sym_start < chars.len() && chars[sym_start].is_ascii_lowercase();
431
432    // Explicit H count
433    let mut explicit_h = 0u8;
434    if pos < end && chars[pos] == 'H' {
435        pos += 1;
436        if pos < end && chars[pos].is_ascii_digit() {
437            explicit_h = chars[pos] as u8 - b'0';
438            pos += 1;
439        } else {
440            explicit_h = 1;
441        }
442    }
443
444    // Charge
445    let mut charge = 0i8;
446    if pos < end && (chars[pos] == '+' || chars[pos] == '-') {
447        let sign: i8 = if chars[pos] == '+' { 1 } else { -1 };
448        pos += 1;
449        if pos < end && chars[pos].is_ascii_digit() {
450            charge = sign * (chars[pos] as i8 - b'0' as i8);
451            pos += 1;
452        } else if pos < end && (chars[pos] == '+' || chars[pos] == '-') {
453            charge = sign * 2;
454            pos += 1; // e.g. ++ or --
455        } else {
456            charge = sign;
457        }
458    }
459
460    // Skip to closing ']'
461    while pos < end && chars[pos] != ']' {
462        pos += 1;
463    }
464    let advance = pos - start + 1; // +1 for ']'
465
466    // Map symbol to &'static str
467    let elem: &'static str = match sym.to_uppercase().as_str() {
468        "C" => "C",
469        "N" => "N",
470        "O" => "O",
471        "S" => "S",
472        "P" => "P",
473        "F" => "F",
474        "CL" => "Cl",
475        "BR" => "Br",
476        "I" => "I",
477        "B" => "B",
478        "SI" => "Si",
479        "AS" => "As",
480        "SE" => "Se",
481        "TE" => "Te",
482        "H" => "H",
483        _ => "C",
484    };
485
486    (elem, is_aromatic, charge, isotope, explicit_h, advance)
487}
488
489/// Populate `n_implicit_h` and `degree` per atom from bond orders and
490/// default valences: implicit H = valence + charge − (bonded valence +
491/// explicit H + aromatic-slot adjustment), clamped ≥ 0. Aromatic atoms
492/// reserve one valence slot for the delocalised π electron (benzene `c`
493/// → 1 implicit H).
494fn fill_implicit_hydrogens(atoms: &mut Vec<Atom>, bonds: &[Bond]) {
495    // valence_used: sum of bond orders (double=2, triple=3, single/aromatic=1)
496    // connectivity: number of distinct bond partners (for degree field)
497    let mut valence_used = vec![0i16; atoms.len()];
498    let mut connectivity = vec![0u8; atoms.len()];
499
500    for b in bonds {
501        let order: i16 = match b.order {
502            BondOrder::Double => 2,
503            BondOrder::Triple => 3,
504            BondOrder::Single | BondOrder::Aromatic => 1,
505        };
506        valence_used[b.atom_a] += order;
507        valence_used[b.atom_b] += order;
508        connectivity[b.atom_a] += 1;
509        connectivity[b.atom_b] += 1;
510    }
511
512    for atom in atoms.iter_mut() {
513        if atom.element == "H" {
514            atom.n_implicit_h = 0;
515            atom.degree = connectivity[atom.idx];
516            continue;
517        }
518        let valence = default_valence(&atom.element) as i16;
519        let charge_adj = atom.charge as i16;
520        // Aromatic atoms: the delocalized pi electron occupies one valence slot.
521        // This matches the standard SMILES spec (c in benzene → 1 implicit H, not 2).
522        let aromatic_adj: i16 = if atom.is_aromatic { 1 } else { 0 };
523        let used = valence_used[atom.idx] + atom.explicit_h as i16 + aromatic_adj;
524        atom.n_implicit_h = (valence + charge_adj - used).max(0) as u8;
525        atom.degree = connectivity[atom.idx];
526    }
527}
528
529/// DFS-based ring bond marking (sets `Bond::in_ring`).
530fn mark_ring_bonds(atoms: &[Atom], bonds: &mut Vec<Bond>) {
531    // Bonds that close rings were already flagged in_ring during parsing.
532    // For any remaining ring bonds (where both endpoints are in a cycle),
533    // we do a simple DFS to find back-edges.
534    let n = atoms.len();
535    let mut adj: Vec<Vec<(usize, usize)>> = vec![vec![]; n]; // (neighbour, bond_idx)
536    for (bi, b) in bonds.iter().enumerate() {
537        adj[b.atom_a].push((b.atom_b, bi));
538        adj[b.atom_b].push((b.atom_a, bi));
539    }
540    let mut visited = vec![false; n];
541    let mut parent = vec![usize::MAX; n];
542    for start in 0..n {
543        if !visited[start] {
544            dfs_mark_rings(&adj, bonds, &mut visited, &mut parent, start, usize::MAX);
545        }
546    }
547}
548
549/// DFS helper for [`mark_ring_bonds`]: flags `in_ring` on back-edges
550/// (edges to already-visited non-parent vertices) — i.e. bonds that
551/// close a cycle not already flagged during ring-digit parsing.
552fn dfs_mark_rings(
553    adj: &[Vec<(usize, usize)>],
554    bonds: &mut Vec<Bond>,
555    visited: &mut Vec<bool>,
556    parent: &mut Vec<usize>,
557    u: usize,
558    par: usize,
559) {
560    visited[u] = true;
561    parent[u] = par;
562    for &(v, bi) in &adj[u] {
563        if !visited[v] {
564            dfs_mark_rings(adj, bonds, visited, parent, v, u);
565        } else if v != par {
566            bonds[bi].in_ring = true;
567        }
568    }
569}
570
571// ─── Molecular formula & weight ──────────────────────────────────────────────
572
573/// Atom counts by element symbol.
574pub fn molecular_formula(mol: &Molecule) -> std::collections::HashMap<String, u32> {
575    let mut counts: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
576    for atom in &mol.atoms {
577        *counts.entry(atom.element.clone()).or_insert(0) += 1;
578        if atom.n_implicit_h + atom.explicit_h > 0 {
579            *counts.entry("H".to_string()).or_insert(0) +=
580                (atom.n_implicit_h + atom.explicit_h) as u32;
581        }
582    }
583    counts
584}
585
586/// Hill-order formula string (C first, H second, then others alphabetically).
587pub fn formula_string(mol: &Molecule) -> String {
588    let counts = molecular_formula(mol);
589    let mut parts: Vec<(String, u32)> = counts.into_iter().collect();
590    parts.sort_by_key(|(e, _)| match e.as_str() {
591        "C" => 0,
592        "H" => 1,
593        _ => 2,
594    });
595    parts
596        .iter()
597        .map(|(e, n)| {
598            if *n == 1 {
599                e.clone()
600            } else {
601                format!("{}{}", e, n)
602            }
603        })
604        .collect()
605}
606
607/// Exact monoisotopic molecular weight (Da).
608pub fn exact_molecular_weight(mol: &Molecule) -> f64 {
609    let counts = molecular_formula(mol);
610    counts
611        .iter()
612        .map(|(e, &n)| atomic_weight(e) * n as f64)
613        .sum()
614}
615
616// ─── Lipinski / drug-likeness descriptors ────────────────────────────────────
617
618#[derive(Debug, Clone)]
619pub struct MolecularDescriptors {
620    pub molecular_weight: f64,
621    pub formula: String,
622    pub heavy_atom_count: usize,
623    pub hb_donors: u32,
624    pub hb_acceptors: u32,
625    pub rotatable_bonds: u32,
626    pub aromatic_ring_count: u32,
627    pub ring_count: u32,
628    pub logp_crippen: f64,
629    pub tpsa_ertl: f64,
630    pub chiral_centers: u32,
631    pub fraction_csp3: f64,
632}
633
634/// Compute all Lipinski/Veber/Ghose descriptors from a parsed molecule.
635pub fn compute_descriptors(mol: &Molecule) -> MolecularDescriptors {
636    let mw = exact_molecular_weight(mol);
637    let formula = formula_string(mol);
638    let heavy = mol.atoms.iter().filter(|a| a.element != "H").count();
639
640    // H-bond donors: NH and OH groups
641    let hbd = mol
642        .atoms
643        .iter()
644        .filter(|a| (a.element == "N" || a.element == "O") && (a.n_implicit_h + a.explicit_h) > 0)
645        .count() as u32;
646
647    // H-bond acceptors: all N and O (Lipinski: just N+O count)
648    let hba = mol
649        .atoms
650        .iter()
651        .filter(|a| a.element == "N" || a.element == "O")
652        .count() as u32;
653
654    // Rotatable bonds: single, non-ring, both atoms have degree ≥ 2, not amide/ester
655    let adj = build_adj(mol);
656    let rot = mol
657        .bonds
658        .iter()
659        .filter(|b| {
660            b.order == BondOrder::Single
661                && !b.in_ring
662                && mol.atoms[b.atom_a].element != "H"
663                && mol.atoms[b.atom_b].element != "H"
664                && mol.atoms[b.atom_a].degree >= 2
665                && mol.atoms[b.atom_b].degree >= 2
666        })
667        .count() as u32;
668
669    // Aromatic rings (simplified: number of aromatic-atom-containing SSSR cycles)
670    let aro_ring = count_aromatic_rings(&mol.atoms, &mol.bonds);
671    let ring_ct = count_all_rings(&mol.bonds);
672
673    // LogP Crippen simplified
674    let logp = compute_logp(mol);
675
676    // TPSA Ertl
677    let tpsa = compute_tpsa(mol);
678
679    // Chiral centers
680    let chiral = count_chiral_centers(mol);
681
682    // Fraction of sp3 carbons
683    let n_c = mol.atoms.iter().filter(|a| a.element == "C").count();
684    let n_csp3 = mol
685        .atoms
686        .iter()
687        .filter(|a| a.element == "C" && !a.is_aromatic && !is_sp2_carbon(a, &adj, mol))
688        .count();
689    let fsp3 = if n_c > 0 {
690        n_csp3 as f64 / n_c as f64
691    } else {
692        0.0
693    };
694
695    MolecularDescriptors {
696        molecular_weight: mw,
697        formula,
698        heavy_atom_count: heavy,
699        hb_donors: hbd,
700        hb_acceptors: hba,
701        rotatable_bonds: rot,
702        aromatic_ring_count: aro_ring,
703        ring_count: ring_ct,
704        logp_crippen: logp,
705        tpsa_ertl: tpsa,
706        chiral_centers: chiral,
707        fraction_csp3: fsp3,
708    }
709}
710
711/// Atom-index adjacency list for `mol` (each bond pushed both ways).
712fn build_adj(mol: &Molecule) -> Vec<Vec<usize>> {
713    let mut adj = vec![vec![]; mol.atoms.len()];
714    for b in &mol.bonds {
715        adj[b.atom_a].push(b.atom_b);
716        adj[b.atom_b].push(b.atom_a);
717    }
718    adj
719}
720
721/// Whether atom `a` participates in a double or aromatic bond —
722/// the sp² test used for Crippen atom typing and `fraction_csp3`.
723fn is_sp2_carbon(a: &Atom, _adj: &[Vec<usize>], mol: &Molecule) -> bool {
724    mol.bonds.iter().any(|b| {
725        (b.atom_a == a.idx || b.atom_b == a.idx)
726            && (b.order == BondOrder::Double || b.order == BondOrder::Aromatic)
727    })
728}
729
730/// Estimated aromatic ring count: aromatic in-ring bonds ÷ 6 with a
731/// remainder rule, falling back to an aromatic-atom-count heuristic
732/// (≥5 atoms → 1 ring, +1 per 5 beyond 10) for heteroaromatic systems
733/// whose ring bonds weren't all flagged aromatic.
734fn count_aromatic_rings(_atoms: &[Atom], bonds: &[Bond]) -> u32 {
735    // Simplified: each aromatic bond that closes a ring contributes to one ring
736    let ring_bonds = bonds
737        .iter()
738        .filter(|b| b.in_ring && b.order == BondOrder::Aromatic)
739        .count();
740    // Rough: 6-membered ring has 6 aromatic bonds; 5-membered has 5
741    let estimated_from_bonds = (ring_bonds / 6 + (ring_bonds % 6 > 2) as usize) as u32;
742    if estimated_from_bonds > 0 {
743        return estimated_from_bonds;
744    }
745
746    // Fallback for heteroaromatic systems that parse with aromatic atoms but
747    // without enough explicit aromatic ring bonds to satisfy the coarse rule above.
748    let aromatic_ring_atoms = _atoms.iter().filter(|a| a.is_aromatic).count();
749    if aromatic_ring_atoms >= 5 {
750        1 + ((aromatic_ring_atoms.saturating_sub(10)) / 5) as u32
751    } else {
752        0
753    }
754}
755
756/// Rough total ring count: in-ring bonds ÷ 3 (heuristic — each ring
757/// contributes ≥3 flagged bonds).
758fn count_all_rings(bonds: &[Bond]) -> u32 {
759    bonds.iter().filter(|b| b.in_ring).count() as u32 / 3 // rough heuristic
760}
761
762// ─── LogP (Crippen–Wildman simplified) ───────────────────────────────────────
763
764/// Per-atom LogP contributions mapped by (element, aromaticity, polar_neighbour).
765/// Derived from Wildman & Crippen 1999, Table 1 (25 of 68 atom types).
766pub fn compute_logp(mol: &Molecule) -> f64 {
767    let adj = build_adj(mol);
768    let mut total = 0.0_f64;
769
770    for atom in &mol.atoms {
771        if atom.element == "H" {
772            continue;
773        }
774        let neighbours: Vec<&Atom> = adj[atom.idx].iter().map(|&i| &mol.atoms[i]).collect();
775        let has_polar_nbr = neighbours.iter().any(|n| {
776            matches!(
777                n.element.as_str(),
778                "N" | "O" | "S" | "P" | "F" | "Cl" | "Br" | "I"
779            )
780        });
781        let is_carbonyl = mol.bonds.iter().any(|b| {
782            (b.atom_a == atom.idx || b.atom_b == atom.idx) && b.order == BondOrder::Double && {
783                let other = if b.atom_a == atom.idx {
784                    b.atom_b
785                } else {
786                    b.atom_a
787                };
788                mol.atoms[other].element == "O"
789            }
790        });
791
792        let contrib = match atom.element.as_str() {
793            "C" => {
794                if atom.is_aromatic {
795                    if has_polar_nbr {
796                        0.0782
797                    } else {
798                        0.2140
799                    }
800                } else if is_carbonyl {
801                    0.0000
802                } else if atom.charge != 0 {
803                    -0.3537
804                } else if has_polar_nbr {
805                    0.0000
806                } else {
807                    0.1441
808                }
809            }
810            "N" => {
811                if atom.charge > 0 {
812                    -1.9513
813                } else if atom.is_aromatic {
814                    -0.7096
815                } else if is_adjacent_amide(atom, mol) {
816                    -1.0280
817                } else {
818                    -1.0190
819                }
820            }
821            "O" => {
822                if atom.charge < 0 {
823                    -1.0810
824                } else if is_carbonyl_oxygen(atom, mol) {
825                    0.1421
826                } else if atom.is_aromatic {
827                    -0.0582
828                } else {
829                    -0.4670
830                }
831            }
832            "S" => {
833                if atom.is_aromatic {
834                    0.4880
835                } else {
836                    0.5620
837                }
838            }
839            "P" => 0.8760,
840            "F" => 0.1480,
841            "Cl" => 0.3010,
842            "Br" => 0.6130,
843            "I" => 1.2570,
844            "B" => 0.1758,
845            "Si" => 0.2756,
846            _ => 0.0,
847        };
848        total += contrib;
849    }
850    // Add implicit-H contribution (CH contribution ~0.1441 per CH3 group simplified)
851    for atom in &mol.atoms {
852        if atom.element == "C" && !atom.is_aromatic {
853            total += 0.1441 * (atom.n_implicit_h.min(3)) as f64 * 0.3;
854        }
855    }
856    total
857}
858
859/// Whether `atom` is bonded to a carbonyl carbon (C=O) — the amide
860/// adjacency test used by the Crippen LogP atom typing.
861fn is_adjacent_amide(atom: &Atom, mol: &Molecule) -> bool {
862    mol.bonds.iter().any(|b| {
863        (b.atom_a == atom.idx || b.atom_b == atom.idx) && {
864            let other_idx = if b.atom_a == atom.idx {
865                b.atom_b
866            } else {
867                b.atom_a
868            };
869            let other = &mol.atoms[other_idx];
870            other.element == "C"
871                && mol.bonds.iter().any(|b2| {
872                    (b2.atom_a == other_idx || b2.atom_b == other_idx)
873                        && b2.order == BondOrder::Double
874                        && {
875                            let o = if b2.atom_a == other_idx {
876                                b2.atom_b
877                            } else {
878                                b2.atom_a
879                            };
880                            mol.atoms[o].element == "O"
881                        }
882                })
883        }
884    })
885}
886
887/// Whether `atom` sits on a double bond (carbonyl-oxygen test).
888fn is_carbonyl_oxygen(atom: &Atom, mol: &Molecule) -> bool {
889    mol.bonds
890        .iter()
891        .any(|b| (b.atom_a == atom.idx || b.atom_b == atom.idx) && b.order == BondOrder::Double)
892}
893
894// ─── TPSA (Ertl 2000 atomic contributions) ───────────────────────────────────
895
896/// Topological polar surface area in Ų.
897pub fn compute_tpsa(mol: &Molecule) -> f64 {
898    let mut tpsa = 0.0_f64;
899    for atom in &mol.atoms {
900        let total_h = (atom.n_implicit_h + atom.explicit_h) as f64;
901        let contrib = match atom.element.as_str() {
902            "N" => {
903                if atom.charge > 0 {
904                    0.0
905                } else if atom.is_aromatic {
906                    12.89
907                } else if total_h >= 2.0 {
908                    26.02
909                }
910                // NH2
911                else if total_h >= 1.0 {
912                    16.61
913                }
914                // NH
915                else if is_adjacent_amide(atom, mol) {
916                    29.42
917                } else {
918                    11.49
919                } // tertiary N
920            }
921            "O" => {
922                if atom.charge != 0 {
923                    23.06
924                } else if atom.is_aromatic {
925                    13.14
926                } else if total_h >= 1.0 {
927                    20.23
928                }
929                // OH
930                else if is_carbonyl_oxygen(atom, mol) {
931                    17.07
932                } else {
933                    9.23
934                } // ether O
935            }
936            "S" => {
937                if atom.is_aromatic {
938                    0.0
939                } else if total_h >= 1.0 {
940                    38.80
941                }
942                // SH
943                else {
944                    32.09
945                } // sulfoxide / sulfone
946            }
947            "P" => 34.14,
948            _ => 0.0,
949        };
950        tpsa += contrib;
951    }
952    tpsa
953}
954
955// ─── Drug-likeness filters ────────────────────────────────────────────────────
956
957#[derive(Debug, Clone)]
958pub struct LipinskiResult {
959    /// MW ≤ 500 Da
960    pub mw_ok: bool,
961    /// LogP ≤ 5
962    pub logp_ok: bool,
963    /// H-bond donors ≤ 5
964    pub hbd_ok: bool,
965    /// H-bond acceptors ≤ 10
966    pub hba_ok: bool,
967    /// Number of rule violations (0 or 1 is oral-bioavailability acceptable).
968    pub violations: u8,
969    pub passes: bool,
970}
971
972/// Lipinski Rule-of-Five on `desc`: MW ≤ 500, LogP ≤ 5, HBD ≤ 5,
973/// HBA ≤ 10 — passes with ≤ 1 violation.
974pub fn evaluate_lipinski(desc: &MolecularDescriptors) -> LipinskiResult {
975    let mw_ok = desc.molecular_weight <= 500.0;
976    let logp_ok = desc.logp_crippen <= 5.0;
977    let hbd_ok = desc.hb_donors <= 5;
978    let hba_ok = desc.hb_acceptors <= 10;
979    let violations = (!mw_ok as u8) + (!logp_ok as u8) + (!hbd_ok as u8) + (!hba_ok as u8);
980    LipinskiResult {
981        mw_ok,
982        logp_ok,
983        hbd_ok,
984        hba_ok,
985        violations,
986        passes: violations <= 1,
987    }
988}
989
990#[derive(Debug, Clone)]
991pub struct VeberResult {
992    /// Rotatable bonds ≤ 10
993    pub rot_bonds_ok: bool,
994    /// TPSA ≤ 140 Ų
995    pub tpsa_ok: bool,
996    pub passes: bool,
997}
998
999/// Veber oral-bioavailability rule: rotatable bonds ≤ 10 and
1000/// TPSA ≤ 140 Ų (both required to pass).
1001pub fn evaluate_veber(desc: &MolecularDescriptors) -> VeberResult {
1002    let rot_bonds_ok = desc.rotatable_bonds <= 10;
1003    let tpsa_ok = desc.tpsa_ertl <= 140.0;
1004    VeberResult {
1005        rot_bonds_ok,
1006        tpsa_ok,
1007        passes: rot_bonds_ok && tpsa_ok,
1008    }
1009}
1010
1011#[derive(Debug, Clone)]
1012pub struct GhoseResult {
1013    /// 160 ≤ MW ≤ 480
1014    pub mw_ok: bool,
1015    /// -0.4 ≤ LogP ≤ 5.6
1016    pub logp_ok: bool,
1017    /// 20 ≤ heavy atoms ≤ 70
1018    pub atoms_ok: bool,
1019    /// Molar refractivity 40–130 (approximated from MW)
1020    pub mr_ok: bool,
1021    pub passes: bool,
1022}
1023
1024/// Ghose drug-likeness filter: 160 ≤ MW ≤ 480, −0.4 ≤ LogP ≤ 5.6,
1025/// 20–70 heavy atoms, and molar refractivity 40–130 (MR approximated as
1026/// `0.3285·MW + 0.08·LogP + 1.0`). All four must hold.
1027pub fn evaluate_ghose(desc: &MolecularDescriptors) -> GhoseResult {
1028    let mw_ok = desc.molecular_weight >= 160.0 && desc.molecular_weight <= 480.0;
1029    let logp_ok = desc.logp_crippen >= -0.4 && desc.logp_crippen <= 5.6;
1030    let atoms_ok = desc.heavy_atom_count >= 20 && desc.heavy_atom_count <= 70;
1031    // MR ≈ 0.3285 × MW + 0.08 × logP + 1.0 (approximation)
1032    let mr = 0.3285 * desc.molecular_weight + 0.08 * desc.logp_crippen + 1.0;
1033    let mr_ok = mr >= 40.0 && mr <= 130.0;
1034    let violations = (!mw_ok as u8) + (!logp_ok as u8) + (!atoms_ok as u8) + (!mr_ok as u8);
1035    GhoseResult {
1036        mw_ok,
1037        logp_ok,
1038        atoms_ok,
1039        mr_ok,
1040        passes: violations == 0,
1041    }
1042}
1043
1044#[derive(Debug, Clone)]
1045pub struct EganResult {
1046    /// TPSA ≤ 131.6 Ų
1047    pub tpsa_ok: bool,
1048    /// LogP ≤ 5.88
1049    pub logp_ok: bool,
1050    pub passes: bool,
1051}
1052
1053/// Egan absorption model: TPSA ≤ 131.6 Ų and LogP ≤ 5.88
1054/// (both required to pass).
1055pub fn evaluate_egan(desc: &MolecularDescriptors) -> EganResult {
1056    let tpsa_ok = desc.tpsa_ertl <= 131.6;
1057    let logp_ok = desc.logp_crippen <= 5.88;
1058    EganResult {
1059        tpsa_ok,
1060        logp_ok,
1061        passes: tpsa_ok && logp_ok,
1062    }
1063}
1064
1065// ─── Functional group detection ───────────────────────────────────────────────
1066
1067#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1068pub enum FunctionalGroup {
1069    Hydroxyl,       // -OH
1070    PrimaryAmine,   // -NH2
1071    SecondaryAmine, // -NH-
1072    TertiaryAmine,  // -N<
1073    AromaticAmine,  // Ar-NH2
1074    Amide,          // -C(=O)N-
1075    CarboxylicAcid, // -C(=O)OH
1076    Ester,          // -C(=O)O-
1077    Ketone,         // -C(=O)-
1078    Aldehyde,       // -CHO
1079    Ether,          // -O-
1080    Thiol,          // -SH
1081    Sulfide,        // -S-
1082    Sulfonamide,    // -S(=O)2NH-
1083    Halide,         // -F, -Cl, -Br, -I
1084    AromaticRing,
1085    Nitrile,   // -C≡N
1086    Nitro,     // -NO2
1087    Phosphate, // -P(=O)(O)2
1088    Imidazole,
1089    GuanidiniumLike,
1090}
1091
1092/// Detect functional groups in a molecule. Returns unique set.
1093#[allow(non_snake_case)]
1094pub fn detect_functional_groups(mol: &Molecule) -> Vec<FunctionalGroup> {
1095    let mut found = std::collections::HashSet::new();
1096    let adj = build_adj(mol);
1097
1098    for atom in &mol.atoms {
1099        let nbrs: Vec<&Atom> = adj[atom.idx].iter().map(|&i| &mol.atoms[i]).collect();
1100        let has_double_O = || {
1101            mol.bonds.iter().any(|b| {
1102                (b.atom_a == atom.idx || b.atom_b == atom.idx) && b.order == BondOrder::Double && {
1103                    let o = if b.atom_a == atom.idx {
1104                        b.atom_b
1105                    } else {
1106                        b.atom_a
1107                    };
1108                    mol.atoms[o].element == "O"
1109                }
1110            })
1111        };
1112        let _has_double_N = || {
1113            mol.bonds.iter().any(|b| {
1114                (b.atom_a == atom.idx || b.atom_b == atom.idx) && b.order == BondOrder::Double && {
1115                    let o = if b.atom_a == atom.idx {
1116                        b.atom_b
1117                    } else {
1118                        b.atom_a
1119                    };
1120                    mol.atoms[o].element == "N"
1121                }
1122            })
1123        };
1124        let has_triple_N = || {
1125            mol.bonds.iter().any(|b| {
1126                (b.atom_a == atom.idx || b.atom_b == atom.idx) && b.order == BondOrder::Triple && {
1127                    let o = if b.atom_a == atom.idx {
1128                        b.atom_b
1129                    } else {
1130                        b.atom_a
1131                    };
1132                    mol.atoms[o].element == "N"
1133                }
1134            })
1135        };
1136
1137        match atom.element.as_str() {
1138            "O" => {
1139                let h = atom.n_implicit_h + atom.explicit_h;
1140                let c_nbr = nbrs.iter().any(|n| n.element == "C");
1141                if h > 0 {
1142                    if c_nbr && !is_carbonyl_oxygen(atom, mol) {
1143                        found.insert(FunctionalGroup::Hydroxyl);
1144                    }
1145                } else if c_nbr && !is_carbonyl_oxygen(atom, mol) {
1146                    found.insert(FunctionalGroup::Ether);
1147                }
1148            }
1149            "N" => {
1150                let h = atom.n_implicit_h + atom.explicit_h;
1151                if atom.is_aromatic {
1152                    found.insert(FunctionalGroup::AromaticAmine);
1153                } else if h >= 2 {
1154                    found.insert(FunctionalGroup::PrimaryAmine);
1155                } else if h == 1 {
1156                    found.insert(FunctionalGroup::SecondaryAmine);
1157                } else {
1158                    found.insert(FunctionalGroup::TertiaryAmine);
1159                }
1160                // Amide N: bonded to a C=O
1161                if is_adjacent_amide(atom, mol) {
1162                    found.insert(FunctionalGroup::Amide);
1163                }
1164                // Sulfonamide: bonded to S
1165                if nbrs.iter().any(|n| n.element == "S") {
1166                    found.insert(FunctionalGroup::Sulfonamide);
1167                }
1168                // Nitro group: non-aromatic N bonded to ≥2 oxygens
1169                if !atom.is_aromatic {
1170                    let o_nbrs: Vec<_> = nbrs.iter().filter(|n| n.element == "O").collect();
1171                    if o_nbrs.len() >= 2 {
1172                        found.insert(FunctionalGroup::Nitro);
1173                    }
1174                }
1175            }
1176            "C" => {
1177                let o_nbrs: Vec<_> = nbrs.iter().filter(|n| n.element == "O").collect();
1178                if has_double_O() {
1179                    let oh_nbr = o_nbrs.iter().any(|o| o.n_implicit_h + o.explicit_h > 0);
1180                    if oh_nbr {
1181                        found.insert(FunctionalGroup::CarboxylicAcid);
1182                    } else {
1183                        let n_nbr = nbrs.iter().any(|n| n.element == "N");
1184                        if n_nbr {
1185                            found.insert(FunctionalGroup::Amide);
1186                        } else {
1187                            let is_terminal = atom.degree == 1;
1188                            if is_terminal || atom.n_implicit_h > 0 {
1189                                found.insert(FunctionalGroup::Aldehyde);
1190                            } else {
1191                                found.insert(FunctionalGroup::Ketone);
1192                            }
1193                        }
1194                    }
1195                    let ether_o = o_nbrs
1196                        .iter()
1197                        .any(|o| o.n_implicit_h == 0 && !is_carbonyl_oxygen(o, mol));
1198                    if ether_o {
1199                        found.insert(FunctionalGroup::Ester);
1200                    }
1201                }
1202                if has_triple_N() {
1203                    found.insert(FunctionalGroup::Nitrile);
1204                }
1205            }
1206            "S" => {
1207                let h = atom.n_implicit_h + atom.explicit_h;
1208                if h > 0 {
1209                    found.insert(FunctionalGroup::Thiol);
1210                } else {
1211                    found.insert(FunctionalGroup::Sulfide);
1212                }
1213            }
1214            "P" => {
1215                found.insert(FunctionalGroup::Phosphate);
1216            }
1217            "F" | "Cl" | "Br" | "I" => {
1218                found.insert(FunctionalGroup::Halide);
1219            }
1220            _ => {}
1221        }
1222        if atom.is_aromatic {
1223            found.insert(FunctionalGroup::AromaticRing);
1224        }
1225    }
1226    let mut result: Vec<FunctionalGroup> = found.into_iter().collect();
1227    result.sort_by_key(|g| format!("{:?}", g));
1228    result
1229}
1230
1231// ─── Chiral centres ───────────────────────────────────────────────────────────
1232
1233/// Count sp3 carbon atoms with 4 distinct substituents (simplified: sp3 C with degree 4).
1234pub fn count_chiral_centers(mol: &Molecule) -> u32 {
1235    let adj = build_adj(mol);
1236    mol.atoms
1237        .iter()
1238        .filter(|a| {
1239            a.element == "C" && !a.is_aromatic && !is_sp2_carbon(a, &adj, mol) && a.degree >= 4
1240        })
1241        .count() as u32
1242}
1243
1244// ─── Morgan circular fingerprint ─────────────────────────────────────────────
1245
1246/// Morgan algorithm: radius-`r` circular fingerprint as sorted Vec\<u64\> identifiers.
1247pub fn circular_fingerprint(mol: &Molecule, radius: usize) -> Vec<u64> {
1248    let n = mol.atoms.len();
1249    if n == 0 {
1250        return vec![];
1251    }
1252    let adj = build_adj(mol);
1253
1254    // Initial atom invariants (element + charge + degree)
1255    let mut ids: Vec<u64> = mol
1256        .atoms
1257        .iter()
1258        .map(|a| crate::q_hash(&format!("{}{}{}", a.element, a.charge, a.degree)))
1259        .collect();
1260
1261    let mut all_ids = ids.clone();
1262
1263    for _ in 0..radius {
1264        let new_ids: Vec<u64> = (0..n)
1265            .map(|i| {
1266                let mut nbr_ids: Vec<u64> = adj[i].iter().map(|&j| ids[j]).collect();
1267                nbr_ids.sort_unstable();
1268                let combined = format!("{}{:?}", ids[i], nbr_ids);
1269                crate::q_hash(&combined)
1270            })
1271            .collect();
1272        all_ids.extend_from_slice(&new_ids);
1273        ids = new_ids;
1274    }
1275
1276    all_ids.sort_unstable();
1277    all_ids.dedup();
1278    all_ids
1279}
1280
1281// ─── pKa estimation ──────────────────────────────────────────────────────────
1282
1283#[derive(Debug, Clone)]
1284pub struct PkaEstimate {
1285    pub group: FunctionalGroup,
1286    pub pka: f64,
1287    pub is_acid: bool,
1288}
1289
1290/// Estimate pKa values from functional group type (literature reference values).
1291pub fn estimate_pka(mol: &Molecule) -> Vec<PkaEstimate> {
1292    let groups = detect_functional_groups(mol);
1293    let mut estimates = Vec::new();
1294    for group in groups {
1295        let (pka, is_acid) = match &group {
1296            FunctionalGroup::CarboxylicAcid => (4.8, true),
1297            FunctionalGroup::Hydroxyl => (10.0, true),
1298            FunctionalGroup::Thiol => (8.3, true),
1299            FunctionalGroup::Amide => (25.0, true),
1300            FunctionalGroup::Nitrile => (25.0, true),
1301            FunctionalGroup::PrimaryAmine => (10.5, false),
1302            FunctionalGroup::SecondaryAmine => (10.0, false),
1303            FunctionalGroup::TertiaryAmine => (9.5, false),
1304            FunctionalGroup::AromaticAmine => (4.6, false),
1305            FunctionalGroup::Imidazole => (6.0, false),
1306            FunctionalGroup::GuanidiniumLike => (12.5, false),
1307            FunctionalGroup::Phosphate => (2.1, true),
1308            FunctionalGroup::Sulfonamide => (10.0, true),
1309            _ => continue,
1310        };
1311        estimates.push(PkaEstimate {
1312            group,
1313            pka,
1314            is_acid,
1315        });
1316    }
1317    estimates
1318}
1319
1320// ─── SMILES / InChI validation ────────────────────────────────────────────────
1321
1322#[derive(Debug, Clone)]
1323pub struct SmilesValidation {
1324    pub is_valid: bool,
1325    pub atom_count: usize,
1326    pub error: Option<String>,
1327}
1328
1329/// Validate a SMILES string via [`parse_smiles`]: reports validity,
1330/// parsed atom count, and the first parse error. Empty input is
1331/// invalid.
1332pub fn validate_smiles(smiles: &str) -> SmilesValidation {
1333    if smiles.trim().is_empty() {
1334        return SmilesValidation {
1335            is_valid: false,
1336            atom_count: 0,
1337            error: Some("Empty SMILES".into()),
1338        };
1339    }
1340    let mol = parse_smiles(smiles);
1341    SmilesValidation {
1342        is_valid: mol.is_valid,
1343        atom_count: mol.atoms.len(),
1344        error: mol.error,
1345    }
1346}
1347
1348#[derive(Debug, Clone)]
1349pub struct InchiValidation {
1350    pub is_valid: bool,
1351    pub has_inchikey: bool,
1352    pub layer_count: usize,
1353}
1354
1355/// Syntactic check for an InChI (`InChI=1S/…` or `InChI=1/…` prefix)
1356/// or 27-character InChIKey (`XXXXXXXXXXXXXX-XXXXXXXXXX-N`); reports
1357/// the layer count for full InChI strings. Not a chemical-semantics
1358/// validation.
1359pub fn validate_inchi(inchi: &str) -> InchiValidation {
1360    // Standard InChI: starts with "InChI=1S/" followed by formula and layers
1361    // InChIKey: 27-character hash XXXXXXXXXXXXXX-XXXXXXXXXX-N
1362    let is_inchi = inchi.starts_with("InChI=1S/") || inchi.starts_with("InChI=1/");
1363    let is_inchikey = inchi.len() == 27
1364        && inchi.chars().nth(14) == Some('-')
1365        && inchi.chars().nth(25) == Some('-');
1366    let layers = if is_inchi {
1367        inchi.split('/').count().saturating_sub(2)
1368    } else {
1369        0
1370    };
1371    InchiValidation {
1372        is_valid: is_inchi || is_inchikey,
1373        has_inchikey: is_inchikey,
1374        layer_count: layers,
1375    }
1376}
1377
1378// ─── Thermochemistry ─────────────────────────────────────────────────────────
1379
1380/// Arrhenius rate constant k at temperature T (K).
1381/// k = A × exp(−Ea / (R × T))
1382/// `activation_energy_j_mol`: Ea in J/mol
1383pub fn arrhenius_rate(pre_exponential_a: f64, activation_energy_j_mol: f64, temp_k: f64) -> f64 {
1384    pre_exponential_a * f64::exp(-activation_energy_j_mol / (R_J_MOL_K * temp_k))
1385}
1386
1387/// Temperature dependence of k using the Arrhenius equation.
1388/// Returns (k_t1, k_t2).
1389pub fn arrhenius_ratio(ea_j_mol: f64, t1_k: f64, t2_k: f64) -> f64 {
1390    f64::exp((ea_j_mol / R_J_MOL_K) * (1.0 / t1_k - 1.0 / t2_k))
1391}
1392
1393/// Gibbs free energy ΔG = ΔH − T × ΔS  (all in J/mol or kJ/mol consistently).
1394pub fn gibbs_free_energy(delta_h: f64, delta_s: f64, temp_k: f64) -> f64 {
1395    delta_h - temp_k * delta_s
1396}
1397
1398/// Equilibrium constant from ΔG°: K = exp(−ΔG° / (R × T))
1399pub fn equilibrium_constant(delta_g_j_mol: f64, temp_k: f64) -> f64 {
1400    f64::exp(-delta_g_j_mol / (R_J_MOL_K * temp_k))
1401}
1402
1403/// ΔG° from equilibrium constant K: ΔG° = −R × T × ln(K)
1404pub fn gibbs_from_equilibrium(k_eq: f64, temp_k: f64) -> f64 {
1405    -R_J_MOL_K * temp_k * k_eq.ln()
1406}
1407
1408/// Gibbs–Helmholtz: ΔG(T2) from ΔG(T1).
1409pub fn gibbs_helmholtz(delta_g_t1: f64, delta_h: f64, t1_k: f64, t2_k: f64) -> f64 {
1410    t2_k * (delta_g_t1 / t1_k + delta_h * (1.0 / t1_k - 1.0 / t2_k))
1411}
1412
1413/// van't Hoff enthalpy estimate from two equilibrium constants at two temperatures.
1414pub fn vant_hoff_enthalpy(k1: f64, k2: f64, t1_k: f64, t2_k: f64) -> f64 {
1415    -R_J_MOL_K * (k2 / k1).ln() / (1.0 / t2_k - 1.0 / t1_k)
1416}
1417
1418/// Henderson–Hasselbalch: pH = pKa + log10([A-] / `HA`)
1419pub fn henderson_hasselbalch(pka: f64, conc_base: f64, conc_acid: f64) -> f64 {
1420    if conc_acid <= 0.0 || conc_base < 0.0 {
1421        return pka;
1422    }
1423    pka + (conc_base / conc_acid).log10()
1424}
1425
1426// ─── Decentralized synthesis: urea pathway, catalyst decay, off-grid kinetics ────
1427//
1428// The resilience-chemistry scope: domestic production of critical compounds at the
1429// edge. These build on the Arrhenius / equilibrium primitives above. Honest scope —
1430// the engine carries the reaction arithmetic; the attested thermodynamic data
1431// (ΔG°, Ea, A) is supplied by the caller, not invented here.
1432
1433/// Equilibrium extent ξ of the Bosch–Meiser urea synthesis
1434/// `2 NH₃ + CO₂ ⇌ (NH₂)₂CO + H₂O`, solved from the equilibrium constant (via the
1435/// caller-supplied ΔG° at `temp_k`) and the initial NH₃/CO₂ partial pressures, by
1436/// bisection on the reaction quotient `Q(ξ) = ξ² / ((p_NH₃−2ξ)²·(p_CO₂−ξ))` (strictly
1437/// increasing in ξ). Returns ξ in the same units as the input pressures. Simplified
1438/// gas-phase model (industrial urea is liquid-phase/high-P — that shifts the numbers,
1439/// not the method). Demonstrates Le Chatelier: higher reactant pressure ⇒ higher ξ.
1440pub fn urea_equilibrium_extent(delta_g_j_mol: f64, temp_k: f64, p_nh3_0: f64, p_co2_0: f64) -> f64 {
1441    let k_eq = equilibrium_constant(delta_g_j_mol, temp_k);
1442    let xi_max = (p_nh3_0 / 2.0).min(p_co2_0).max(0.0);
1443    if xi_max <= 0.0 {
1444        return 0.0;
1445    }
1446    let quotient = |xi: f64| -> f64 {
1447        let nh3 = p_nh3_0 - 2.0 * xi;
1448        let co2 = p_co2_0 - xi;
1449        if nh3 <= 0.0 || co2 <= 0.0 {
1450            return f64::INFINITY;
1451        }
1452        (xi * xi) / (nh3 * nh3 * co2)
1453    };
1454    let (mut lo, mut hi) = (0.0f64, xi_max * (1.0 - 1e-9));
1455    for _ in 0..100 {
1456        let mid = 0.5 * (lo + hi);
1457        if quotient(mid) < k_eq {
1458            lo = mid;
1459        } else {
1460            hi = mid;
1461        }
1462    }
1463    0.5 * (lo + hi)
1464}
1465
1466/// Catalyst activity at time `t` under first-order deactivation: `a(t) = a₀·exp(−k_d·t)`.
1467/// Models the degradation that limits sustained yield on small decentralized nodes.
1468pub fn catalyst_activity(initial_activity: f64, deactivation_rate_per_s: f64, time_s: f64) -> f64 {
1469    let a = initial_activity * (-deactivation_rate_per_s * time_s).exp();
1470    a.clamp(0.0, initial_activity.max(0.0))
1471}
1472
1473/// Effective reaction rate accounting for catalyst decay: `r_eff = r_base · a(t)/a₀`.
1474pub fn deactivated_reaction_rate(
1475    base_rate: f64,
1476    initial_activity: f64,
1477    deactivation_rate_per_s: f64,
1478    time_s: f64,
1479) -> f64 {
1480    if initial_activity <= 0.0 {
1481        return 0.0;
1482    }
1483    base_rate * catalyst_activity(initial_activity, deactivation_rate_per_s, time_s)
1484        / initial_activity
1485}
1486
1487/// Total fractional conversion of a first-order reaction under a *variable* temperature
1488/// profile — e.g. fluctuating off-grid power driving a fluctuating reactor temperature.
1489/// Integrates `dX/dt = k(T)·(1−X)` across `temp_profile_k` (k from the Arrhenius rate,
1490/// explicit-Euler steps of `dt_s`), returning the final conversion `X ∈ [0,1]`. Zero-heap
1491/// (the profile is a caller slice).
1492pub fn conversion_under_variable_temperature(
1493    pre_exponential_a: f64,
1494    activation_energy_j_mol: f64,
1495    temp_profile_k: &[f64],
1496    dt_s: f64,
1497) -> f64 {
1498    let mut x = 0.0f64;
1499    for &t_k in temp_profile_k {
1500        let k = arrhenius_rate(pre_exponential_a, activation_energy_j_mol, t_k);
1501        x += k * (1.0 - x) * dt_s;
1502        x = x.clamp(0.0, 1.0);
1503    }
1504    x
1505}
1506
1507#[cfg(test)]
1508mod resilience_chem_tests {
1509    use super::*;
1510
1511    #[test]
1512    fn urea_extent_tracks_equilibrium_favorability() {
1513        // Product-favoured (ΔG° = −10 kJ/mol at 400 K → K ≈ 20): with p_NH3=2, p_CO2=1
1514        // the equilibrium extent ξ ≈ 0.8 (Q(0.8)=0.64/(0.16·0.2)=20).
1515        let xi = urea_equilibrium_extent(-10_000.0, 400.0, 2.0, 1.0);
1516        assert!(xi > 0.7 && xi < 0.9, "favourable extent ~0.8, got {xi}");
1517        // Strongly unfavourable (ΔG° = +60 kJ/mol → K ≈ 0): almost no conversion.
1518        let xi_bad = urea_equilibrium_extent(60_000.0, 400.0, 2.0, 1.0);
1519        assert!(xi_bad < 0.01, "unfavourable extent ~0, got {xi_bad}");
1520        // Le Chatelier: more reactant pressure ⇒ more product.
1521        let xi_lo = urea_equilibrium_extent(-10_000.0, 400.0, 1.0, 0.5);
1522        let xi_hi = urea_equilibrium_extent(-10_000.0, 400.0, 4.0, 2.0);
1523        assert!(
1524            xi_hi > xi_lo,
1525            "higher reactant pressure should raise the extent"
1526        );
1527    }
1528
1529    #[test]
1530    fn catalyst_decays_and_throttles_rate() {
1531        let a0 = 1.0;
1532        assert!((catalyst_activity(a0, 0.1, 0.0) - a0).abs() < 1e-12);
1533        let later = catalyst_activity(a0, 0.1, 10.0);
1534        assert!(later < a0 && later > 0.0);
1535        // r_eff = base · e^{-1} ≈ 0.368 · base after k_d·t = 1.
1536        let r = deactivated_reaction_rate(10.0, a0, 0.1, 10.0);
1537        assert!((r - 10.0 * (-1.0f64).exp()).abs() < 1e-9);
1538    }
1539
1540    #[test]
1541    fn hotter_profile_gives_more_conversion() {
1542        let (a, ea, dt) = (1e6, 50_000.0, 1.0);
1543        let cold = conversion_under_variable_temperature(a, ea, &[300.0, 300.0, 300.0], dt);
1544        let hot = conversion_under_variable_temperature(a, ea, &[350.0, 350.0, 350.0], dt);
1545        assert!(
1546            hot > cold,
1547            "higher temperature ⇒ faster kinetics ⇒ more conversion"
1548        );
1549        assert!((0.0..=1.0).contains(&hot) && (0.0..=1.0).contains(&cold));
1550    }
1551}
1552
1553/// Degree of ionisation α at a given pH for a monoprotic acid.
1554pub fn ionisation_fraction(ph: f64, pka: f64) -> f64 {
1555    1.0 / (1.0 + 10f64.powf(pka - ph))
1556}
1557
1558// ─── Green chemistry metrics ─────────────────────────────────────────────────
1559
1560#[derive(Debug, Clone)]
1561pub struct GreenMetrics {
1562    /// Trost 1991: desired product MW / sum of all reactant MWs × 100 %
1563    pub atom_economy_pct: f64,
1564    /// Yield-corrected AE (YAAE)
1565    pub yield_corrected_ae_pct: f64,
1566    /// Sheldon 1992: kg waste / kg desired product
1567    pub e_factor: f64,
1568    /// Mass-based E-factor considering all inputs including solvents
1569    pub process_mass_intensity: f64,
1570    /// Andraos 2005: kg product / kg total reactants × 100 %
1571    pub reaction_mass_efficiency_pct: f64,
1572    /// Carbon efficiency: C atoms in product / C atoms in reactants × 100 %
1573    pub carbon_efficiency_pct: f64,
1574}
1575
1576/// `?::green_metrics`.
1577pub fn green_metrics(
1578    reactant_mws: &[f64],
1579    product_mw: f64,
1580    byproduct_mws: &[f64],
1581    yield_fraction: f64, // 0.0–1.0
1582    solvent_and_auxiliary_kg: f64,
1583    product_kg: f64,
1584    reactant_c_atoms: u32,
1585    product_c_atoms: u32,
1586) -> GreenMetrics {
1587    let sum_reactants: f64 = reactant_mws.iter().sum();
1588    let ae = if sum_reactants > 0.0 {
1589        100.0 * product_mw / sum_reactants
1590    } else {
1591        0.0
1592    };
1593    let yaae = ae * yield_fraction;
1594
1595    let waste_kg = reactant_mws.iter().sum::<f64>()
1596        + byproduct_mws.iter().sum::<f64>()
1597        + solvent_and_auxiliary_kg
1598        - product_kg;
1599    let ef = if product_kg > 0.0 {
1600        waste_kg.max(0.0) / product_kg
1601    } else {
1602        f64::INFINITY
1603    };
1604
1605    let total_in = reactant_mws.iter().sum::<f64>() + solvent_and_auxiliary_kg;
1606    let pmi = if product_kg > 0.0 {
1607        total_in / product_kg
1608    } else {
1609        f64::INFINITY
1610    };
1611
1612    let effective_product_kg = product_kg * yield_fraction.max(0.0);
1613    let rme = if sum_reactants > 0.0 {
1614        100.0 * effective_product_kg / sum_reactants
1615    } else {
1616        0.0
1617    };
1618
1619    let ce = if reactant_c_atoms > 0 {
1620        100.0 * product_c_atoms as f64 / reactant_c_atoms as f64
1621    } else {
1622        0.0
1623    };
1624
1625    GreenMetrics {
1626        atom_economy_pct: ae,
1627        yield_corrected_ae_pct: yaae,
1628        e_factor: ef,
1629        process_mass_intensity: pmi,
1630        reaction_mass_efficiency_pct: rme,
1631        carbon_efficiency_pct: ce,
1632    }
1633}
1634
1635/// Simplified atom economy (Trost): single product vs all reactants.
1636pub fn atom_economy(reactant_mws: &[f64], desired_product_mw: f64) -> f64 {
1637    let sum: f64 = reactant_mws.iter().sum();
1638    if sum == 0.0 {
1639        0.0
1640    } else {
1641        100.0 * desired_product_mw / sum
1642    }
1643}
1644
1645/// E-factor (Sheldon): waste_kg / product_kg.  Fine chemicals < 50; bulk < 5; pharma 25–100.
1646pub fn e_factor(waste_kg: f64, product_kg: f64) -> f64 {
1647    if product_kg <= 0.0 {
1648        f64::INFINITY
1649    } else {
1650        waste_kg / product_kg
1651    }
1652}
1653
1654// ─── ADMET & Lead Optimization Metrics ───────────────────────────────────────
1655
1656#[derive(Debug, Clone, Copy)]
1657pub struct BbbPermeationResult {
1658    pub clark_score: u8,        // MPO score 0-4
1659    pub is_cns_penetrant: bool, // MPO >= 3 is typically considered penetrant
1660}
1661
1662/// Evaluates Blood-Brain Barrier (BBB) permeation probability using Clark's
1663/// rules (Molecular Weight, LogP, PSA, HBD).
1664pub fn predict_bbb_permeation(mw: f64, log_p: f64, psa: f64, hbd: u32) -> BbbPermeationResult {
1665    let mut clark_score = 0;
1666    if mw <= 400.0 {
1667        clark_score += 1;
1668    }
1669    if log_p >= 2.0 && log_p <= 5.0 {
1670        clark_score += 1;
1671    }
1672    if psa <= 90.0 {
1673        clark_score += 1;
1674    }
1675    if hbd <= 3 {
1676        clark_score += 1;
1677    }
1678
1679    BbbPermeationResult {
1680        clark_score,
1681        is_cns_penetrant: clark_score >= 3,
1682    }
1683}
1684
1685/// Computes Ligand Efficiency (LE): pIC50 / Heavy Atom Count (HAC).
1686/// Standard target is LE >= 0.3.
1687pub fn ligand_efficiency(pic50: f64, hac: u32) -> f64 {
1688    if hac == 0 {
1689        0.0
1690    } else {
1691        (pic50 * 1.37) / (hac as f64)
1692    }
1693}
1694
1695/// Computes Lipophilic Ligand Efficiency (LLE): pIC50 - LogP.
1696/// Standard target is LLE >= 5.0.
1697pub fn lipophilic_ligand_efficiency(pic50: f64, log_p: f64) -> f64 {
1698    pic50 - log_p
1699}
1700
1701// ─── Mass Spectrometry Simulation ────────────────────────────────────────────
1702
1703#[derive(Debug, Clone, Copy)]
1704pub struct IsotopeDistribution {
1705    pub m_peak: f64,  // 100% (normalized)
1706    pub m1_peak: f64, // M+1 relative intensity
1707    pub m2_peak: f64, // M+2 relative intensity
1708}
1709
1710/// Computes the theoretical M, M+1, M+2 isotopic distribution based on the number
1711/// of Carbon, Nitrogen, Oxygen, Sulfur, Chlorine, and Bromine atoms.
1712pub fn isotope_mass_distribution(
1713    c: u32,
1714    n: u32,
1715    o: u32,
1716    s: u32,
1717    cl: u32,
1718    br: u32,
1719) -> IsotopeDistribution {
1720    // Relative abundance approximations (natural)
1721    let c13 = 0.0107;
1722    let n15 = 0.0036;
1723    let o18 = 0.0020;
1724    let s33 = 0.0076;
1725    let s34 = 0.0429;
1726    let cl37 = 0.3197;
1727    let br81 = 0.9728; // Br is ~50.69% 79Br, ~49.31% 81Br (ratio ~ 0.97)
1728
1729    // M+1 contributions
1730    let m1 = (c as f64) * c13 + (n as f64) * n15 + (s as f64) * s33;
1731
1732    // M+2 contributions
1733    let m2 = ((c as f64) * c13).powi(2) / 2.0
1734        + (o as f64) * o18
1735        + (s as f64) * s34
1736        + (cl as f64) * cl37
1737        + (br as f64) * br81;
1738
1739    IsotopeDistribution {
1740        m_peak: 100.0,
1741        m1_peak: m1 * 100.0,
1742        m2_peak: m2 * 100.0,
1743    }
1744}
1745
1746// ─── Tests ────────────────────────────────────────────────────────────────────
1747
1748#[cfg(test)]
1749mod tests {
1750    use super::*;
1751
1752    fn aspirin() -> Molecule {
1753        parse_smiles("CC(=O)Oc1ccccc1C(=O)O")
1754    }
1755    fn paracetamol() -> Molecule {
1756        parse_smiles("CC(=O)Nc1ccc(O)cc1")
1757    }
1758    fn ethanol() -> Molecule {
1759        parse_smiles("CCO")
1760    }
1761    fn caffeine() -> Molecule {
1762        parse_smiles("Cn1cnc2c1c(=O)n(c(=O)n2C)C")
1763    }
1764    fn methane() -> Molecule {
1765        parse_smiles("C")
1766    }
1767
1768    #[test]
1769    fn smiles_parse_ethanol_atoms() {
1770        let mol = ethanol();
1771        assert!(mol.is_valid);
1772        assert_eq!(mol.atoms.iter().filter(|a| a.element == "C").count(), 2);
1773        assert_eq!(mol.atoms.iter().filter(|a| a.element == "O").count(), 1);
1774    }
1775
1776    #[test]
1777    fn smiles_parse_paracetamol_methane() {
1778        let p = paracetamol();
1779        assert!(p.is_valid);
1780        assert_eq!(p.atoms.iter().filter(|a| a.element == "C").count(), 8);
1781        let m = methane();
1782        assert!(m.is_valid);
1783        assert_eq!(m.atoms.iter().filter(|a| a.element == "C").count(), 1);
1784    }
1785
1786    #[test]
1787    fn molecular_weight_ethanol() {
1788        let mol = ethanol();
1789        let mw = exact_molecular_weight(&mol);
1790        assert!(
1791            (mw - 46.068).abs() < 1.0,
1792            "ethanol MW ~ 46.07, got {:.3}",
1793            mw
1794        );
1795    }
1796
1797    #[test]
1798    fn molecular_weight_aspirin() {
1799        let mol = aspirin();
1800        let mw = exact_molecular_weight(&mol);
1801        assert!((mw - 180.0).abs() < 5.0, "aspirin MW ~ 180, got {:.2}", mw);
1802    }
1803
1804    #[test]
1805    fn lipinski_aspirin_passes() {
1806        let desc = compute_descriptors(&aspirin());
1807        let r = evaluate_lipinski(&desc);
1808        assert!(r.passes, "Aspirin should pass Lipinski");
1809    }
1810
1811    #[test]
1812    fn lipinski_caffeine_passes() {
1813        let desc = compute_descriptors(&caffeine());
1814        let r = evaluate_lipinski(&desc);
1815        assert!(r.passes, "Caffeine should pass Lipinski");
1816    }
1817
1818    #[test]
1819    fn caffeine_has_aromatic_ring_descriptor() {
1820        let desc = compute_descriptors(&caffeine());
1821        assert!(
1822            desc.aromatic_ring_count > 0,
1823            "caffeine should report at least one aromatic ring"
1824        );
1825    }
1826
1827    #[test]
1828    fn functional_groups_ethanol() {
1829        let groups = detect_functional_groups(&ethanol());
1830        assert!(
1831            groups.contains(&FunctionalGroup::Hydroxyl),
1832            "ethanol should have hydroxyl"
1833        );
1834    }
1835
1836    #[test]
1837    fn functional_groups_aspirin() {
1838        let groups = detect_functional_groups(&aspirin());
1839        assert!(
1840            groups.contains(&FunctionalGroup::CarboxylicAcid)
1841                || groups.contains(&FunctionalGroup::Ester)
1842                || groups.contains(&FunctionalGroup::AromaticRing)
1843        );
1844    }
1845
1846    #[test]
1847    fn green_metrics_rme_tracks_yield() {
1848        let reactants = [46.068];
1849        let product_mw = 46.068;
1850        let high = green_metrics(&reactants, product_mw, &[], 0.99, 5.0, 1.0, 0, 0);
1851        let low = green_metrics(&reactants, product_mw, &[], 0.10, 5.0, 1.0, 0, 0);
1852        assert!(high.reaction_mass_efficiency_pct > low.reaction_mass_efficiency_pct);
1853    }
1854
1855    #[test]
1856    fn tpsa_ethanol_reasonable() {
1857        let mol = ethanol();
1858        let tpsa = compute_tpsa(&mol);
1859        assert!(
1860            tpsa > 10.0 && tpsa < 40.0,
1861            "ethanol TPSA ~ 20 Ų, got {:.1}",
1862            tpsa
1863        );
1864    }
1865
1866    #[test]
1867    fn test_bbb_permeation() {
1868        // Example: Diazepam (MW 284.7, LogP ~2.8, PSA ~32.6, HBD 0)
1869        let r = predict_bbb_permeation(284.7, 2.8, 32.6, 0);
1870        assert_eq!(r.clark_score, 4);
1871        assert!(r.is_cns_penetrant);
1872    }
1873
1874    #[test]
1875    fn test_ligand_efficiency() {
1876        let le = ligand_efficiency(8.0, 25);
1877        assert!((le - 0.4384).abs() < 0.01);
1878        let lle = lipophilic_ligand_efficiency(8.0, 3.0);
1879        assert!((lle - 5.0).abs() < 0.01);
1880    }
1881
1882    #[test]
1883    fn test_isotope_distribution() {
1884        // Bromobenzene: C6 H5 Br1
1885        // M+2 from Br: 1 × br81_ratio = 0.9728 → 97.28%
1886        // M+2 from C6:  (6 × 0.0107)² / 2 = 0.00206 → 0.206%
1887        // Combined M+2 ≈ 97.49%
1888        let r = isotope_mass_distribution(6, 0, 0, 0, 0, 1);
1889        assert!((r.m_peak - 100.0).abs() < 0.1);
1890        assert!((r.m1_peak - 6.42).abs() < 0.1);
1891        assert!(
1892            (r.m2_peak - 97.49).abs() < 0.5,
1893            "M+2 for bromobenzene expected ~97.49%, got {}",
1894            r.m2_peak
1895        );
1896    }
1897
1898    #[test]
1899    fn arrhenius_rate_increases_with_temp() {
1900        let k25 = arrhenius_rate(1e13, 80_000.0, 298.0);
1901        let k100 = arrhenius_rate(1e13, 80_000.0, 373.0);
1902        assert!(k100 > k25, "rate should increase with temperature");
1903    }
1904
1905    #[test]
1906    fn gibbs_standard_conditions() {
1907        // ΔG = ΔH - TΔS: endothermic, low ΔS should give positive ΔG at 298K
1908        let dg = gibbs_free_energy(10_000.0, 20.0, 298.0);
1909        assert!(dg < 10_000.0);
1910    }
1911
1912    #[test]
1913    fn equilibrium_constant_roundtrip() {
1914        let delta_g = -5_000.0; // negative ΔG → K > 1
1915        let k = equilibrium_constant(delta_g, 298.0);
1916        let dg_back = gibbs_from_equilibrium(k, 298.0);
1917        assert!((dg_back - delta_g).abs() < 1.0, "roundtrip ΔG");
1918    }
1919
1920    #[test]
1921    fn henderson_hasselbalch_half_ionised() {
1922        // pH = pKa when [A-] = [HA]
1923        let ph = henderson_hasselbalch(4.8, 1.0, 1.0);
1924        assert!((ph - 4.8).abs() < 1e-9);
1925    }
1926
1927    #[test]
1928    fn atom_economy_100pct_addition() {
1929        // A + B → AB (100% AE)
1930        let ae = atom_economy(&[100.0, 80.0], 180.0);
1931        assert!((ae - 100.0).abs() < 1e-9);
1932    }
1933
1934    #[test]
1935    fn e_factor_zero_waste() {
1936        assert_eq!(e_factor(0.0, 1.0), 0.0);
1937    }
1938
1939    #[test]
1940    fn validate_smiles_valid() {
1941        let r = validate_smiles("CCO");
1942        assert!(r.is_valid);
1943    }
1944
1945    #[test]
1946    fn validate_smiles_empty() {
1947        let r = validate_smiles("");
1948        assert!(!r.is_valid);
1949    }
1950
1951    #[test]
1952    fn validate_inchi_standard() {
1953        let r = validate_inchi("InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3");
1954        assert!(r.is_valid);
1955        assert!(!r.has_inchikey);
1956    }
1957
1958    #[test]
1959    fn validate_inchikey_format() {
1960        let r = validate_inchi("LFQSCWFLJHTTHZ-UHFFFAOYSA-N");
1961        assert!(r.is_valid);
1962        assert!(r.has_inchikey);
1963    }
1964
1965    #[test]
1966    fn circular_fingerprint_different_for_different_molecules() {
1967        let fp1 = circular_fingerprint(&ethanol(), 2);
1968        let fp2 = circular_fingerprint(&aspirin(), 2);
1969        assert_ne!(fp1, fp2);
1970    }
1971
1972    #[test]
1973    fn pka_carboxylic_acid() {
1974        let mol = parse_smiles("CC(=O)O"); // acetic acid
1975        let pkas = estimate_pka(&mol);
1976        assert!(pkas
1977            .iter()
1978            .any(|p| p.group == FunctionalGroup::CarboxylicAcid));
1979    }
1980
1981    #[test]
1982    fn veber_passes_small_molecule() {
1983        let mol = ethanol();
1984        let desc = compute_descriptors(&mol);
1985        let r = evaluate_veber(&desc);
1986        assert!(r.passes);
1987    }
1988}