1use crate::types::OrganicInorganic;
12use serde::{Deserialize, Serialize};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum FunctionalGroup {
26 Anhydride,
28 Isocyanate,
30 Nitrile,
32 Nitro,
34 Epoxide,
36 SulphonicAcid,
38 Phosphate,
40 Amide,
42 Ester,
44 CarboxylicAcid,
46 Aldehyde,
48 Ketone,
50 Phenol,
52 Thiol,
54 Sulphide,
56 Alcohol,
58 Ether,
60 Amine,
62 Halide,
64 AromaticRing,
66}
67
68impl FunctionalGroup {
69 pub fn label(self) -> &'static str {
71 match self {
72 Self::Anhydride => "Anhydride",
73 Self::Isocyanate => "Isocyanate",
74 Self::Nitrile => "Nitrile",
75 Self::Nitro => "Nitro",
76 Self::Epoxide => "Epoxide",
77 Self::SulphonicAcid => "SulphonicAcid",
78 Self::Phosphate => "Phosphate",
79 Self::Amide => "Amide",
80 Self::Ester => "Ester",
81 Self::CarboxylicAcid => "CarboxylicAcid",
82 Self::Aldehyde => "Aldehyde",
83 Self::Ketone => "Ketone",
84 Self::Phenol => "Phenol",
85 Self::Thiol => "Thiol",
86 Self::Sulphide => "Sulphide",
87 Self::Alcohol => "Alcohol",
88 Self::Ether => "Ether",
89 Self::Amine => "Amine",
90 Self::Halide => "Halide",
91 Self::AromaticRing => "AromaticRing",
92 }
93 }
94}
95
96pub fn classify_organic(smiles: &str) -> OrganicInorganic {
107 if !smiles.chars().any(|c| c == 'C' || c == 'c') {
109 return OrganicInorganic::Inorganic;
110 }
111
112 let normalised = smiles.replace(' ', "");
114 let inorganic_exact: &[&str] = &[
115 "O=C=O", "[O-]C(=O)[O-]", "[O-]C([O-])=O",
118 "[C-]#[O+]", "[C+]#[O-]",
120 "S=C=S", "[C-]#N", "[N+]#[C-]",
123 "C(=O)([O-])[O-]", ];
125 if inorganic_exact.iter().any(|p| normalised == *p) {
126 return OrganicInorganic::Inorganic;
127 }
128
129 let metal_symbols: &[&str] = &[
132 "[Fe]", "[Co]", "[Ni]", "[Cr]", "[Mn]", "[Mo]", "[W]",
133 "[Ti]", "[V]", "[Ru]", "[Rh]", "[Pd]", "[Os]", "[Ir]",
134 "[Pt]", "[Zn]", "[Al]", "[Pb]", "[Sn]", "[Hg]", "[Tl]",
135 ];
136 for metal in metal_symbols {
139 if smiles.contains(metal) {
140 let idx = smiles.find(metal).unwrap_or(usize::MAX);
143 let after = smiles.get(idx + metal.len()..).unwrap_or("");
144 let before = smiles.get(..idx).unwrap_or("");
145 let bonded = after.starts_with('C')
146 || after.starts_with('c')
147 || before.ends_with('C')
148 || before.ends_with('c');
149 if bonded {
150 return OrganicInorganic::Organometallic;
151 }
152 }
153 }
154
155 OrganicInorganic::Organic
156}
157
158pub fn detect_functional_groups(smiles: &str) -> Vec<FunctionalGroup> {
173 let mut groups: Vec<FunctionalGroup> = Vec::new();
174
175 let any = |patterns: &[&str]| -> bool { patterns.iter().any(|p| smiles.contains(p)) };
177
178 let cyclic_anhydride = (1u8..=9).any(|n| {
182 smiles.contains(&format!("O=C{}OC(=O)", n))
183 });
184 if smiles.contains("C(=O)OC(=O)") || cyclic_anhydride {
185 groups.push(FunctionalGroup::Anhydride);
186 }
187
188 if any(&["N=C=O", "O=C=N"]) {
190 groups.push(FunctionalGroup::Isocyanate);
191 }
192
193 if any(&["C#N", "N#C"]) {
195 groups.push(FunctionalGroup::Nitrile);
196 }
197
198 if any(&[
201 "O=[N+]([O-])", "[N+](=O)[O-]", "N(=O)=O",
204 "[N+]([O-])=O",
205 "[N+](=O)([O-])",
206 ]) {
207 groups.push(FunctionalGroup::Nitro);
208 }
209
210 if any(&[
214 "C1CO1", "C1OC1", "[C@@H]1O[C@H]1", "[C@H]1O[C@@H]1",
218 ]) {
219 groups.push(FunctionalGroup::Epoxide);
220 }
221
222 if any(&["S(=O)(=O)O", "S(=O)(=O)[OH]", "S(O)(=O)=O", "[S](=O)(=O)O"]) {
224 groups.push(FunctionalGroup::SulphonicAcid);
225 }
226
227 if smiles.contains('P')
229 && any(&["P(=O)(O)", "P(=O)([O", "P(O)(O)", "P([OH])", "OP(=O)", "P(=O)O"])
230 {
231 groups.push(FunctionalGroup::Phosphate);
232 }
233
234 if any(&[
237 "NC(=O)", "NC(C", "C(N)=O", "C(=O)N", "C(=O)[NH", "[NH]C(=O)", "[NH2]C(=O)",
239 "N)=O", ]) {
241 let has_iso = groups.contains(&FunctionalGroup::Isocyanate);
243 let has_nitrile = groups.contains(&FunctionalGroup::Nitrile);
244 if !has_iso && !has_nitrile {
245 groups.push(FunctionalGroup::Amide);
246 }
247 }
248
249 let has_anhydride = groups.contains(&FunctionalGroup::Anhydride);
252 if !has_anhydride
253 && any(&[
254 "OC(C)=O", "OC(=O)C", "C(=O)OC", "C(=O)Oc", "OC(CC", "OC(c", ])
257 {
258 groups.push(FunctionalGroup::Ester);
259 }
260
261 let has_ester = groups.contains(&FunctionalGroup::Ester);
264 if !has_ester && !has_anhydride {
265 let has_acid_pattern = any(&[
268 "C(=O)O", "C(O)=O", "C(=O)[OH]", ]);
272 if has_acid_pattern {
274 groups.push(FunctionalGroup::CarboxylicAcid);
275 }
276 }
277
278 let has_higher_carbonyl = groups.iter().any(|g| {
282 matches!(
283 g,
284 FunctionalGroup::Amide
285 | FunctionalGroup::Ester
286 | FunctionalGroup::CarboxylicAcid
287 | FunctionalGroup::Anhydride
288 )
289 });
290 if !has_higher_carbonyl {
291 let aldehyde = smiles.ends_with("C=O")
292 || smiles.ends_with("[CH]=O")
293 || smiles.starts_with("O=C") || any(&["[CH]=O", "[CHO]"]);
295 if aldehyde {
296 groups.push(FunctionalGroup::Aldehyde);
297 }
298 }
299
300 if !has_higher_carbonyl {
303 let has_aldehyde = groups.contains(&FunctionalGroup::Aldehyde);
304 if !has_aldehyde
305 && any(&[
306 "C(C)=O", "C(CC)=O", "C(CCC)=O",
308 "C(c)=O", "c(=O)C", "C(=O)C", ])
312 {
313 groups.push(FunctionalGroup::Ketone);
314 }
315 }
316
317 if any(&[
319 "c1ccccc1O", "Oc1ccccc1",
320 "c(O)", "c([OH])", "Oc1cc", "Oc1ccc", "c1cc(O)", "c1ccc(O)",
323 ]) {
324 groups.push(FunctionalGroup::Phenol);
325 }
326
327 if any(&["[SH]", "C[SH]", "c[SH]"])
330 || smiles.ends_with("CS")
331 || smiles.ends_with("cS")
332 {
333 groups.push(FunctionalGroup::Thiol);
334 }
335
336 let has_sulphonic = groups.contains(&FunctionalGroup::SulphonicAcid);
338 let has_thiol = groups.contains(&FunctionalGroup::Thiol);
339 if !has_sulphonic
340 && !has_thiol
341 && smiles.contains('S')
342 && any(&["CSC", "cSC", "CSc", "cSc", "C(S)C"])
343 {
344 groups.push(FunctionalGroup::Sulphide);
345 }
346
347 let has_phenol = groups.contains(&FunctionalGroup::Phenol);
350 let has_acid = groups.contains(&FunctionalGroup::CarboxylicAcid);
351 let has_ester2 = groups.contains(&FunctionalGroup::Ester);
352 let has_anhydride2 = groups.contains(&FunctionalGroup::Anhydride);
353 let has_aldehyde_grp = groups.contains(&FunctionalGroup::Aldehyde);
355 if !has_phenol && !has_acid && !has_ester2 && !has_anhydride2 && !has_aldehyde_grp {
356 let alcohol = any(&["[OH]", "C[OH]"])
357 || smiles.ends_with("CO")
358 || smiles.ends_with("CCO")
359 || smiles.ends_with("O") || any(&["C(O)", "C([OH])"]);
361 if alcohol {
362 groups.push(FunctionalGroup::Alcohol);
363 }
364 }
365
366 let has_epoxide = groups.contains(&FunctionalGroup::Epoxide);
369 let has_ester3 = groups.contains(&FunctionalGroup::Ester);
370 let has_acid2 = groups.contains(&FunctionalGroup::CarboxylicAcid);
371 if !has_epoxide && !has_ester3 && !has_acid2 && !has_anhydride
372 && any(&["COC", "cOC", "COc", "cOc"]) {
373 groups.push(FunctionalGroup::Ether);
374 }
375
376 let has_amide = groups.contains(&FunctionalGroup::Amide);
379 let has_nitrile = groups.contains(&FunctionalGroup::Nitrile);
380 let has_nitro = groups.contains(&FunctionalGroup::Nitro);
381 if smiles.contains('N')
382 && !has_nitrile
383 && !has_nitro
384 {
385 let amine = any(&[
387 "CN", "NC", "[NH2]", "[NH3+]", "[NH]", "cN", "Nc",
388 ]);
389 if amine && (!has_amide || any(&["[NH2]", "[NH3+]", "CN(", "N(C)C"])) {
391 groups.push(FunctionalGroup::Amine);
392 }
393 }
394
395 if any(&[
397 "CF", "CCl", "CBr", "CI",
398 "Fc", "Clc", "Brc", "Ic",
399 "[F]", "[Cl]", "[Br]", "[I]",
400 "c[F]", "c[Cl]", "c[Br]", "c[I]",
401 "CF3", "CCl3", "CHF", "CHCl", "CHBr",
402 ]) {
403 groups.push(FunctionalGroup::Halide);
404 }
405
406 if smiles.chars().any(|c| matches!(c, 'c' | 'n' | 'o' | 's' | 'p')) {
408 groups.push(FunctionalGroup::AromaticRing);
409 }
410
411 groups
412}
413
414#[derive(Debug, Clone, Default, Serialize, Deserialize)]
426pub struct StructuralFeatures {
427 pub carbon_count: u32,
429 pub hydroxyl_count: u32,
435 pub carbonyl_count: u32,
437 pub has_ring: bool,
439 pub has_aromatic_ring: bool,
441 pub has_cc_double_bond: bool,
443 pub has_halogen: bool,
445}
446
447pub fn detect_structural_features(smiles: &str) -> StructuralFeatures {
452 StructuralFeatures {
453 carbon_count: count_carbons(smiles),
454 hydroxyl_count: count_hydroxyls(smiles),
455 carbonyl_count: smiles.matches("=O").count() as u32,
456 has_ring: ring_present(smiles),
457 has_aromatic_ring: smiles.contains('c'),
458 has_cc_double_bond: cc_double_bond_present(smiles),
459 has_halogen: smiles.contains('F')
460 || smiles.contains("Cl")
461 || smiles.contains("Br")
462 || (smiles.contains('I') && !smiles.contains("In")),
463 }
464}
465
466fn count_carbons(smiles: &str) -> u32 {
469 let mut count = 0u32;
470 let mut chars = smiles.chars().peekable();
471 let mut in_bracket = false;
472 let mut bracket_buf = String::new();
473
474 while let Some(ch) = chars.next() {
475 match ch {
476 '[' => {
477 in_bracket = true;
478 bracket_buf.clear();
479 }
480 ']' if in_bracket => {
481 in_bracket = false;
482 let sym = bracket_buf.trim_start_matches(|c: char| c.is_ascii_digit());
484 if sym.starts_with('C') || sym.starts_with('c') {
485 count += 1;
486 }
487 }
488 c if in_bracket => bracket_buf.push(c),
489 'C' => {
490 if chars.peek() == Some(&'l') {
491 chars.next(); } else {
493 count += 1;
494 }
495 }
496 'c' => count += 1,
497 _ => {}
498 }
499 }
500 count
501}
502
503fn count_hydroxyls(smiles: &str) -> u32 {
508 let chars: Vec<char> = smiles.chars().collect();
509 let n = chars.len();
510 let mut count = 0u32;
511 let mut i = 0;
512
513 while i < n {
514 if chars[i] == '[' {
516 i += 1;
517 let mut buf = String::new();
518 while i < n && chars[i] != ']' {
519 buf.push(chars[i]);
520 i += 1;
521 }
522 i += 1; let sym = buf.trim_start_matches(|c: char| c.is_ascii_digit());
524 if sym.starts_with("OH") {
525 count += 1;
526 }
527 continue;
528 }
529
530 if chars[i] == 'O' {
531 let prev = if i > 0 { chars[i - 1] } else { '\0' };
532 let next = if i + 1 < n { chars[i + 1] } else { '\0' };
533
534 if prev == '=' {
536 i += 1;
537 continue;
538 }
539
540 let prev_is_c = matches!(prev, 'C' | 'c' | ')');
542 let next_is_c = matches!(next, 'C' | 'c' | '(');
543 if prev_is_c && next_is_c {
544 i += 1;
545 continue;
546 }
547
548 count += 1;
549 }
550
551 i += 1;
552 }
553 count
554}
555
556fn ring_present(smiles: &str) -> bool {
558 let mut in_bracket = false;
559 for ch in smiles.chars() {
560 match ch {
561 '[' => in_bracket = true,
562 ']' => in_bracket = false,
563 c if c.is_ascii_digit() && !in_bracket => return true,
564 _ => {}
565 }
566 }
567 false
568}
569
570fn cc_double_bond_present(smiles: &str) -> bool {
572 smiles.contains("C=C")
574 || smiles.contains("c=c")
575 || smiles.contains("C=c")
576 || smiles.contains("c=C")
577 || smiles.contains("(=C)")
579 || smiles.contains("(=c)")
580}
581
582#[cfg(test)]
587mod tests {
588 use super::*;
589
590 fn fg(smiles: &str) -> Vec<FunctionalGroup> {
591 detect_functional_groups(smiles)
592 }
593
594 fn has(smiles: &str, g: FunctionalGroup) -> bool {
595 fg(smiles).contains(&g)
596 }
597
598 #[test]
601 fn co2_is_inorganic() {
602 assert_eq!(classify_organic("O=C=O"), OrganicInorganic::Inorganic);
603 }
604
605 #[test]
606 fn water_is_inorganic() {
607 assert_eq!(classify_organic("O"), OrganicInorganic::Inorganic);
608 }
609
610 #[test]
611 fn ethanol_is_organic() {
612 assert_eq!(classify_organic("CCO"), OrganicInorganic::Organic);
613 }
614
615 #[test]
616 fn benzene_is_organic() {
617 assert_eq!(classify_organic("c1ccccc1"), OrganicInorganic::Organic);
618 }
619
620 #[test]
623 fn acetic_acid_detected() {
624 assert!(has("CC(=O)O", FunctionalGroup::CarboxylicAcid));
626 assert!(!has("CC(=O)O", FunctionalGroup::Ester));
627 }
628
629 #[test]
630 fn ethyl_acetate_detected_as_ester() {
631 assert!(has("CCOC(C)=O", FunctionalGroup::Ester));
633 assert!(!has("CCOC(C)=O", FunctionalGroup::CarboxylicAcid));
634 }
635
636 #[test]
637 fn phthalic_anhydride_detected() {
638 let groups = fg("O=C1OC(=O)c2ccccc21");
640 assert!(groups.contains(&FunctionalGroup::Anhydride));
641 assert!(!groups.contains(&FunctionalGroup::Ester));
642 }
643
644 #[test]
645 fn acetaldehyde_detected() {
646 assert!(has("CC=O", FunctionalGroup::Aldehyde));
648 assert!(!has("CC=O", FunctionalGroup::Ketone));
649 }
650
651 #[test]
655 fn acetaldehyde_not_classified_as_alcohol() {
656 assert!(!has("CC=O", FunctionalGroup::Alcohol),
657 "aldehyde SMILES 'CC=O' must not produce Alcohol group");
658 }
659
660 #[test]
661 fn acetone_detected_as_ketone() {
662 assert!(has("CC(C)=O", FunctionalGroup::Ketone));
664 assert!(!has("CC(C)=O", FunctionalGroup::Aldehyde));
665 }
666
667 #[test]
668 fn ethanol_detected_as_alcohol() {
669 assert!(has("CCO", FunctionalGroup::Alcohol));
671 assert!(!has("CCO", FunctionalGroup::Ether));
672 }
673
674 #[test]
675 fn dimethyl_ether_detected() {
676 assert!(has("COC", FunctionalGroup::Ether));
678 assert!(!has("COC", FunctionalGroup::Alcohol));
679 }
680
681 #[test]
682 fn methylamine_detected() {
683 assert!(has("CN", FunctionalGroup::Amine));
685 }
686
687 #[test]
688 fn acetamide_detected() {
689 assert!(has("CC(N)=O", FunctionalGroup::Amide));
691 assert!(!has("CC(N)=O", FunctionalGroup::Ketone));
692 }
693
694 #[test]
695 fn acetonitrile_detected() {
696 assert!(has("CC#N", FunctionalGroup::Nitrile));
698 }
699
700 #[test]
701 fn chloromethane_detected() {
702 assert!(has("CCl", FunctionalGroup::Halide));
704 }
705
706 #[test]
707 fn ethylene_oxide_detected() {
708 assert!(has("C1CO1", FunctionalGroup::Epoxide));
710 }
711
712 #[test]
713 fn benzene_detected_as_aromatic() {
714 assert!(has("c1ccccc1", FunctionalGroup::AromaticRing));
715 }
716
717 #[test]
718 fn phenol_detected() {
719 assert!(has("Oc1ccccc1", FunctionalGroup::Phenol));
721 }
722
723 #[test]
724 fn nitrobenzene_detected() {
725 assert!(has("O=[N+]([O-])c1ccccc1", FunctionalGroup::Nitro));
727 }
728
729 #[test]
730 fn ethanesulfonic_acid_detected() {
731 assert!(has("CCS(=O)(=O)O", FunctionalGroup::SulphonicAcid));
733 }
734
735 #[test]
736 fn dimethyl_sulfide_detected() {
737 assert!(has("CSC", FunctionalGroup::Sulphide));
739 }
740
741 #[test]
742 fn methanethiol_detected() {
743 assert!(has("C[SH]", FunctionalGroup::Thiol));
745 }
746
747 #[test]
748 fn isocyanate_detected() {
749 assert!(has("CN=C=O", FunctionalGroup::Isocyanate));
751 }
752
753 #[test]
754 fn trimethyl_phosphate_detected() {
755 assert!(has("COP(=O)(OC)OC", FunctionalGroup::Phosphate));
757 }
758
759 fn sf(smiles: &str) -> StructuralFeatures {
762 detect_structural_features(smiles)
763 }
764
765 #[test]
766 fn acetone_carbon_count_3() {
767 let f = sf("CC(C)=O");
769 assert_eq!(f.carbon_count, 3);
770 assert!(!f.has_ring);
771 assert!(!f.has_aromatic_ring);
772 assert!(!f.has_cc_double_bond);
773 assert_eq!(f.carbonyl_count, 1);
774 }
775
776 #[test]
777 fn ethanol_hydroxyl_count_1() {
778 let f = sf("CCO");
780 assert_eq!(f.carbon_count, 2);
781 assert_eq!(f.hydroxyl_count, 1);
782 }
783
784 #[test]
785 fn ethylene_glycol_hydroxyl_count_2() {
786 let f = sf("OCCO");
788 assert_eq!(f.carbon_count, 2);
789 assert_eq!(f.hydroxyl_count, 2);
790 }
791
792 #[test]
793 fn glycerol_hydroxyl_count_3() {
794 let f = sf("OCC(O)CO");
796 assert_eq!(f.carbon_count, 3);
797 assert_eq!(f.hydroxyl_count, 3);
798 }
799
800 #[test]
801 fn ether_oxygen_not_counted_as_oh() {
802 let f = sf("COC");
804 assert_eq!(f.hydroxyl_count, 0);
805 }
806
807 #[test]
808 fn acetic_acid_one_oh() {
809 let f = sf("CC(=O)O");
811 assert_eq!(f.carbon_count, 2);
812 assert_eq!(f.hydroxyl_count, 1);
813 assert_eq!(f.carbonyl_count, 1);
814 }
815
816 #[test]
817 fn acrylic_acid_has_cc_double_bond() {
818 let f = sf("C=CC(=O)O");
820 assert!(f.has_cc_double_bond);
821 assert_eq!(f.carbon_count, 3);
822 }
823
824 #[test]
825 fn methacrylic_acid_has_cc_double_bond() {
826 let f = sf("CC(=C)C(=O)O");
828 assert!(f.has_cc_double_bond);
829 assert_eq!(f.carbon_count, 4);
830 }
831
832 #[test]
833 fn benzene_has_aromatic_ring() {
834 let f = sf("c1ccccc1");
835 assert!(f.has_ring);
836 assert!(f.has_aromatic_ring);
837 assert_eq!(f.carbon_count, 6);
838 }
839
840 #[test]
841 fn cyclohexanone_is_ring_no_aromatic() {
842 let f = sf("O=C1CCCCC1");
844 assert!(f.has_ring);
845 assert!(!f.has_aromatic_ring);
846 assert_eq!(f.carbon_count, 6);
847 }
848
849 #[test]
850 fn chlorobenzene_has_halogen() {
851 let f = sf("Clc1ccccc1");
852 assert!(f.has_halogen);
853 assert_eq!(f.carbon_count, 6);
854 }
855
856 #[test]
857 fn methanol_carbon_count_1() {
858 let f = sf("CO");
859 assert_eq!(f.carbon_count, 1);
860 assert_eq!(f.hydroxyl_count, 1);
861 }
862}