1pub const R_J_MOL_K: f64 = 8.314_462_618;
45
46const 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
67fn atomic_weight(symbol: &str) -> f64 {
70 ATOMIC_WEIGHTS
71 .iter()
72 .find(|(s, _)| *s == symbol)
73 .map(|(_, w)| *w)
74 .unwrap_or(12.0) }
76
77const 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
97pub 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#[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 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 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
148pub 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 '(' => {
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 '-' => {
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 '.' => {
235 current_atom = None;
236 pending_bond = None;
237 pos += 1;
238 }
239 '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 '%' 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 '[' => {
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 '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 '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 if !ring_map.is_empty() {
348 error = Some(format!(
349 "Unclosed ring bonds: {:?}",
350 ring_map.keys().collect::<Vec<_>>()
351 ));
352 }
353
354 fill_implicit_hydrogens(&mut atoms, &bonds);
356 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
368fn 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
402fn parse_bracket_atom(
404 chars: &[char],
405 start: usize,
406) -> (&'static str, bool, i8, Option<u16>, u8, usize) {
407 let mut pos = start + 1; let end = chars.len();
409
410 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 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 let is_aromatic = sym_start < chars.len() && chars[sym_start].is_ascii_lowercase();
431
432 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 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; } else {
456 charge = sign;
457 }
458 }
459
460 while pos < end && chars[pos] != ']' {
462 pos += 1;
463 }
464 let advance = pos - start + 1; 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
489fn fill_implicit_hydrogens(atoms: &mut Vec<Atom>, bonds: &[Bond]) {
495 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 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
529fn mark_ring_bonds(atoms: &[Atom], bonds: &mut Vec<Bond>) {
531 let n = atoms.len();
535 let mut adj: Vec<Vec<(usize, usize)>> = vec![vec![]; n]; 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
549fn 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
571pub 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
586pub 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
607pub 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#[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
634pub 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 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 let hba = mol
649 .atoms
650 .iter()
651 .filter(|a| a.element == "N" || a.element == "O")
652 .count() as u32;
653
654 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 let aro_ring = count_aromatic_rings(&mol.atoms, &mol.bonds);
671 let ring_ct = count_all_rings(&mol.bonds);
672
673 let logp = compute_logp(mol);
675
676 let tpsa = compute_tpsa(mol);
678
679 let chiral = count_chiral_centers(mol);
681
682 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
711fn 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
721fn 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
730fn count_aromatic_rings(_atoms: &[Atom], bonds: &[Bond]) -> u32 {
735 let ring_bonds = bonds
737 .iter()
738 .filter(|b| b.in_ring && b.order == BondOrder::Aromatic)
739 .count();
740 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 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
756fn count_all_rings(bonds: &[Bond]) -> u32 {
759 bonds.iter().filter(|b| b.in_ring).count() as u32 / 3 }
761
762pub 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 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
859fn 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
887fn 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
894pub 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 else if total_h >= 1.0 {
912 16.61
913 }
914 else if is_adjacent_amide(atom, mol) {
916 29.42
917 } else {
918 11.49
919 } }
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 else if is_carbonyl_oxygen(atom, mol) {
931 17.07
932 } else {
933 9.23
934 } }
936 "S" => {
937 if atom.is_aromatic {
938 0.0
939 } else if total_h >= 1.0 {
940 38.80
941 }
942 else {
944 32.09
945 } }
947 "P" => 34.14,
948 _ => 0.0,
949 };
950 tpsa += contrib;
951 }
952 tpsa
953}
954
955#[derive(Debug, Clone)]
958pub struct LipinskiResult {
959 pub mw_ok: bool,
961 pub logp_ok: bool,
963 pub hbd_ok: bool,
965 pub hba_ok: bool,
967 pub violations: u8,
969 pub passes: bool,
970}
971
972pub 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 pub rot_bonds_ok: bool,
994 pub tpsa_ok: bool,
996 pub passes: bool,
997}
998
999pub 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 pub mw_ok: bool,
1015 pub logp_ok: bool,
1017 pub atoms_ok: bool,
1019 pub mr_ok: bool,
1021 pub passes: bool,
1022}
1023
1024pub 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 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 pub tpsa_ok: bool,
1048 pub logp_ok: bool,
1050 pub passes: bool,
1051}
1052
1053pub 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1068pub enum FunctionalGroup {
1069 Hydroxyl, PrimaryAmine, SecondaryAmine, TertiaryAmine, AromaticAmine, Amide, CarboxylicAcid, Ester, Ketone, Aldehyde, Ether, Thiol, Sulfide, Sulfonamide, Halide, AromaticRing,
1085 Nitrile, Nitro, Phosphate, Imidazole,
1089 GuanidiniumLike,
1090}
1091
1092#[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 if is_adjacent_amide(atom, mol) {
1162 found.insert(FunctionalGroup::Amide);
1163 }
1164 if nbrs.iter().any(|n| n.element == "S") {
1166 found.insert(FunctionalGroup::Sulfonamide);
1167 }
1168 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
1231pub 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
1244pub 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 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#[derive(Debug, Clone)]
1284pub struct PkaEstimate {
1285 pub group: FunctionalGroup,
1286 pub pka: f64,
1287 pub is_acid: bool,
1288}
1289
1290pub 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#[derive(Debug, Clone)]
1323pub struct SmilesValidation {
1324 pub is_valid: bool,
1325 pub atom_count: usize,
1326 pub error: Option<String>,
1327}
1328
1329pub 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
1355pub fn validate_inchi(inchi: &str) -> InchiValidation {
1360 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
1378pub 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
1387pub 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
1393pub fn gibbs_free_energy(delta_h: f64, delta_s: f64, temp_k: f64) -> f64 {
1395 delta_h - temp_k * delta_s
1396}
1397
1398pub 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
1403pub fn gibbs_from_equilibrium(k_eq: f64, temp_k: f64) -> f64 {
1405 -R_J_MOL_K * temp_k * k_eq.ln()
1406}
1407
1408pub 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
1413pub 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
1418pub 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
1426pub 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
1466pub 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
1473pub 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
1487pub 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 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 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 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 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
1553pub fn ionisation_fraction(ph: f64, pka: f64) -> f64 {
1555 1.0 / (1.0 + 10f64.powf(pka - ph))
1556}
1557
1558#[derive(Debug, Clone)]
1561pub struct GreenMetrics {
1562 pub atom_economy_pct: f64,
1564 pub yield_corrected_ae_pct: f64,
1566 pub e_factor: f64,
1568 pub process_mass_intensity: f64,
1570 pub reaction_mass_efficiency_pct: f64,
1572 pub carbon_efficiency_pct: f64,
1574}
1575
1576pub fn green_metrics(
1578 reactant_mws: &[f64],
1579 product_mw: f64,
1580 byproduct_mws: &[f64],
1581 yield_fraction: f64, 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
1635pub 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
1645pub 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#[derive(Debug, Clone, Copy)]
1657pub struct BbbPermeationResult {
1658 pub clark_score: u8, pub is_cns_penetrant: bool, }
1661
1662pub 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
1685pub 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
1695pub fn lipophilic_ligand_efficiency(pic50: f64, log_p: f64) -> f64 {
1698 pic50 - log_p
1699}
1700
1701#[derive(Debug, Clone, Copy)]
1704pub struct IsotopeDistribution {
1705 pub m_peak: f64, pub m1_peak: f64, pub m2_peak: f64, }
1709
1710pub 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 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; let m1 = (c as f64) * c13 + (n as f64) * n15 + (s as f64) * s33;
1731
1732 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#[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(ðanol());
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 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 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 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; 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 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 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(ðanol(), 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"); 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}