Coverage for SynRBL/SynProcessor/rsmi_decomposer.py: 82%
45 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
1from collections import defaultdict
2from rdkit import Chem
3from rdkit.Chem import Descriptors
4from joblib import Parallel, delayed
5import pandas as pd
7from typing import Dict, List, Tuple, Union
10class RSMIDecomposer:
11 """
12 A class for decomposing SMILES strings into atomic compositions and
13 calculating molecular weights.
15 Attributes
16 ----------
17 smiles : str, optional
18 The SMILES string to decompose.
19 data : list or DataFrame, optional
20 The data containing the SMILES strings to decompose.
21 reactant_col : str, optional
22 The column or key name in the data for reactant SMILES strings.
23 product_col : str, optional
24 The column or key name in the data for product SMILES strings.
25 parallel : bool, optional
26 Whether to use parallel processing (default is True).
27 n_jobs : int, optional
28 The number of jobs to run in parallel (default is 10).
29 verbose : int, optional
30 The verbosity level (default is 1).
31 """
33 atomic_symbols = {
34 0: "Q",
35 1: "H",
36 2: "He",
37 3: "Li",
38 4: "Be",
39 5: "B",
40 6: "C",
41 7: "N",
42 8: "O",
43 9: "F",
44 10: "Ne",
45 11: "Na",
46 12: "Mg",
47 13: "Al",
48 14: "Si",
49 15: "P",
50 16: "S",
51 17: "Cl",
52 18: "Ar",
53 19: "K",
54 20: "Ca",
55 21: "Sc",
56 22: "Ti",
57 23: "V",
58 24: "Cr",
59 25: "Mn",
60 26: "Fe",
61 27: "Co",
62 28: "Ni",
63 29: "Cu",
64 30: "Zn",
65 31: "Ga",
66 32: "Ge",
67 33: "As",
68 34: "Se",
69 35: "Br",
70 36: "Kr",
71 37: "Rb",
72 38: "Sr",
73 39: "Y",
74 40: "Zr",
75 41: "Nb",
76 42: "Mo",
77 43: "Tc",
78 44: "Ru",
79 45: "Rh",
80 46: "Pd",
81 47: "Ag",
82 48: "Cd",
83 49: "In",
84 50: "Sn",
85 51: "Sb",
86 52: "Te",
87 53: "I",
88 54: "Xe",
89 55: "Cs",
90 56: "Ba",
91 57: "La",
92 58: "Ce",
93 59: "Pr",
94 60: "Nd",
95 61: "Pm",
96 62: "Sm",
97 63: "Eu",
98 64: "Gd",
99 65: "Tb",
100 66: "Dy",
101 67: "Ho",
102 68: "Er",
103 69: "Tm",
104 70: "Yb",
105 71: "Lu",
106 72: "Hf",
107 73: "Ta",
108 74: "W",
109 75: "Re",
110 76: "Os",
111 77: "Ir",
112 78: "Pt",
113 79: "Au",
114 80: "Hg",
115 81: "Tl",
116 82: "Pb",
117 83: "Bi",
118 84: "Po",
119 85: "At",
120 86: "Rn"
121 # This covers elements up to Radon (Rn). Extend further if needed.
122 }
124 def __init__(
125 self,
126 smiles: str = None,
127 data: Union[List[str], pd.DataFrame] = None,
128 reactant_col: str = "reactants",
129 product_col: str = "products",
130 parallel: bool = True,
131 n_jobs: int = 4,
132 verbose: int = 1,
133 ) -> None:
134 """
135 Initialize the RSMIDecomposer object.
137 Args:
138 smiles (str): The SMILES string to decompose.
139 data (list or DataFrame): The data containing the SMILES strings to decompose.
140 reactant_col (str): The column or key name in the data for reactant SMILES strings.
141 product_col (str): The column or key name in the data for product SMILES strings.
142 parallel (bool): Whether to use parallel processing.
143 n_jobs (int): The number of jobs to run in parallel.
144 verbose (int): The verbosity level.
145 """
146 self.smiles = smiles
147 self.data = data
148 self.reactant_col = reactant_col
149 self.product_col = product_col
150 self.parallel = parallel
151 self.n_jobs = n_jobs
152 self.verbose = verbose
154 def calculate_mol_weight(self, smiles: str) -> float:
155 """
156 Calculates the molecular weight of a molecule represented by a SMILES string.
158 Args:
159 smiles: The SMILES string of the molecule.
161 Returns:
162 The molecular weight of the molecule, or None if the SMILES string is invalid.
164 Example:
165 >>> decomposer = RSMIDecomposer()
166 >>> decomposer.calculate_mol_weight('CCO')
167 46.069
168 """
169 molecule = Chem.MolFromSmiles(smiles)
170 if molecule:
171 return Descriptors.MolWt(molecule)
173 def data_decomposer(self) -> Tuple[List[Dict[str, int]], List[Dict[str, int]]]:
174 """
175 Decomposes SMILES strings in the data into atomic compositions for
176 reactants and products.
178 Returns:
179 tuple of lists: Two lists containing dictionaries of atomic
180 compositions for reactants and products.
182 Example:
183 >>> data = pd.DataFrame({'reactants': ['CCO', 'CC'], 'products': ['C=O', 'C=C']})
184 >>> decomposer = RSMIDecomposer(data=data, parallel=False)
185 >>> reactants, products = decomposer.data_decomposer()
186 >>> reactants # Outputs [{'C': 2, 'O': 1, 'H': 6}, {'C': 2, 'H': 6}]
187 >>> products # Outputs [{'C': 1, 'O': 1, 'H': 2}, {'C': 2, 'H': 4}]
188 """
189 # Extract reactants and products based on the provided data format
190 if isinstance(self.data, list):
191 reactants = [item[self.reactant_col] for item in self.data]
192 products = [item[self.product_col] for item in self.data]
193 else: # Assuming data is a DataFrame
194 reactants = self.data[self.reactant_col]
195 products = self.data[self.product_col]
197 # Decompose reactants and products using parallel processing if enabled
198 if self.parallel:
199 react_dict = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
200 delayed(RSMIDecomposer.decompose)(smiles) for smiles in reactants
201 )
202 prods_dict = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
203 delayed(RSMIDecomposer.decompose)(smiles) for smiles in products
204 )
205 else:
206 react_dict = [RSMIDecomposer.decompose(smiles) for smiles in reactants]
207 prods_dict = [RSMIDecomposer.decompose(smiles) for smiles in products]
209 return react_dict, prods_dict
211 @staticmethod
212 def decompose(smiles: str) -> Dict[str, int]:
213 """
214 Decomposes a SMILES string into a dictionary of atomic counts and charges.
216 Parameters:
217 smiles : str
218 The SMILES string to decompose.
220 Returns:
221 dict
222 A dictionary with atomic symbols as keys and counts as values.
223 Charge is represented as 'Q'.
225 Example:
226 >>> RSMIDecomposer.decompose('CCO')
227 {'C': 2, 'O': 1, 'H': 6, 'Q': 0}
228 """
229 molecule = Chem.MolFromSmiles(smiles)
230 comp = defaultdict(int)
231 if molecule:
232 molecule_with_Hs = Chem.AddHs(molecule)
234 for atom in molecule_with_Hs.GetAtoms():
235 atomic_symbol = RSMIDecomposer.atomic_symbols.get(
236 atom.GetAtomicNum(), "Unknown"
237 )
238 comp[atomic_symbol] += 1
240 charge = Chem.GetFormalCharge(molecule_with_Hs)
241 if charge != 0:
242 comp["Q"] = charge
244 return dict(comp)