Coverage for SynRBL/SynProcessor/check_carbon_balance.py: 53%
55 statements
« prev ^ index » next coverage.py v7.4.3, created at 2024-04-11 11:17 +0200
« prev ^ index » next coverage.py v7.4.3, created at 2024-04-11 11:17 +0200
1import logging
2from rdkit.rdBase import BlockLogs
3from typing import List, Dict
4from rdkit import Chem
5from joblib import Parallel, delayed
8class InvalidSmilesException(Exception):
9 """Custom exception for invalid SMILES strings."""
11 pass
14class CheckCarbonBalance:
15 """
16 A class to check the atom balance in chemical reactions using parallel processing.
18 Class Variables
19 ---------------
20 rsmi_col : str
21 Column name for the reaction SMILES string.
22 symbol : str
23 Symbol separating reactants and products in the SMILES string.
24 atom_type : str
25 Type of atom to check the balance for.
26 smiles_cache : dict
27 Cache for storing counts of previously processed SMILES strings.
29 Methods
30 -------
31 count_atoms(smiles: str, atom_type: str) -> int:
32 Count the number of specified atoms in a molecule represented by a SMILES string.
33 process_reaction(reaction: Dict[str, str]) -> Dict[str, str]:
34 Process a single reaction to check atom balance.
35 check_atom_balance() -> List[Dict[str, str]]:
36 Check and return the atom balance status for each reaction using parallel processing.
37 """
39 def __init__(
40 self,
41 reactions_data: List[Dict[str, str]],
42 rsmi_col="reactions",
43 symbol=">>",
44 atom_type="C",
45 n_jobs=4,
46 ):
47 self.reactions_data = reactions_data
48 self.rsmi_col = rsmi_col
49 self.symbol = symbol
50 self.atom_type = atom_type
51 self.n_jobs = n_jobs
52 self.smiles_cache = {}
54 @staticmethod
55 def count_atoms(smiles: str, atom_type: str, smiles_cache: Dict[str, int]) -> int:
56 if smiles in smiles_cache:
57 return smiles_cache[smiles]
59 try:
60 mol = Chem.MolFromSmiles(smiles)
61 count = (
62 sum(1 for atom in mol.GetAtoms() if atom.GetSymbol() == atom_type)
63 if mol
64 else 0
65 )
66 smiles_cache[smiles] = count
67 return count
68 except Exception as e:
69 raise InvalidSmilesException(f"Invalid SMILES string {smiles}: {e}")
71 @staticmethod
72 def process_reaction(
73 reaction: Dict[str, str],
74 rsmi_col: str,
75 symbol: str,
76 atom_type: str,
77 smiles_cache: Dict[str, int],
78 ) -> Dict[str, str]:
79 block = BlockLogs()
80 new_reaction = reaction.copy()
81 try:
82 reactants_smiles, products_smiles = new_reaction[rsmi_col].split(symbol)
83 reactants_carbon = sum(
84 CheckCarbonBalance.count_atoms(smiles, atom_type, smiles_cache)
85 for smiles in reactants_smiles.split(".")
86 )
87 products_carbon = sum(
88 CheckCarbonBalance.count_atoms(smiles, atom_type, smiles_cache)
89 for smiles in products_smiles.split(".")
90 )
92 if reactants_carbon == products_carbon:
93 new_reaction["carbon_balance_check"] = "balanced"
94 elif reactants_carbon > products_carbon:
95 new_reaction["carbon_balance_check"] = "products"
96 else:
97 new_reaction["carbon_balance_check"] = "reactants"
98 except InvalidSmilesException as e:
99 logging.error(e)
100 new_reaction["carbon_balance_check"] = "error"
101 except KeyError as e:
102 logging.error(f"Key error in reaction data: {e}")
103 new_reaction["carbon_balance_check"] = "error"
104 except ValueError as e:
105 logging.error(f"Value error in parsing SMILES: {e}")
106 new_reaction["carbon_balance_check"] = "error"
108 del block
109 return new_reaction
111 def check_carbon_balance(self) -> List[Dict[str, str]]:
112 if not all(isinstance(reaction, dict) for reaction in self.reactions_data):
113 raise ValueError("Each item in reactions_data should be a dictionary.")
115 parallel_results = Parallel(n_jobs=self.n_jobs, verbose=0)(
116 delayed(self.process_reaction)(
117 reaction, self.rsmi_col, self.symbol, self.atom_type, self.smiles_cache
118 )
119 for reaction in self.reactions_data
120 )
121 return parallel_results