Coverage for SynRBL/SynRuleImputer/auto_extract_smiles.py: 92%
40 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 rdkit import Chem
2from rdkit.Chem import Descriptors
3from joblib import Parallel, delayed
4from typing import List, Dict
7class AutomaticSmilesExtraction:
8 """
9 A class for automatically extracting information from reaction SMILES
10 (RSMI) data.
12 Parameters
13 ----------
14 reactions : list of dict
15 A list of dictionaries containing reaction data. Each dictionary should
16 contain 'reactants' and 'products' keys, where the values are SMILES strings.
17 n_jobs : int, optional
18 The number of jobs to run in parallel (default is -1 for maximum available).
19 verbose : int, optional
20 The verbosity level (default is 1).
22 Attributes
23 ----------
24 smiles_list : list of str
25 List of SMILES strings extracted from the reactions.
26 mw : list of float
27 List of molecular weights calculated from the SMILES strings.
28 n_C : list of int
29 List of counts of carbon atoms in the molecules represented by SMILES.
31 Example
32 -------
33 # Create an instance of the AutomaticSmilesExtraction class with a list of
34 reaction dictionaries
35 >>> reactions = [
36 ... {'reactants': 'CCO', 'products': 'CCOCC'},
37 ... {'reactants': 'CC', 'products': 'C'}
38 ... ]
39 >>> extractor = AutomaticSmilesExtraction(reactions, n_jobs=-1, verbose=1)
40 # Access extracted data
41 >>> print(extractor.mw)
42 [46.069, 74.123]
43 >>> print(extractor.n_C)
44 [2, 2]
45 """
47 def __init__(self, reactions: List[str], n_jobs: int = 4, verbose: int = 1) -> None:
48 self.reactions = reactions
49 self.smiles_list = self.get_smiles(reactions)
50 # Use n_jobs and verbose as arguments in Parallel
51 self.mw = Parallel(n_jobs=n_jobs, verbose=verbose)(
52 delayed(self.calculate_mol_weight)(smi) for smi in self.smiles_list
53 )
54 self.n_C = Parallel(n_jobs=n_jobs, verbose=verbose)(
55 delayed(self.count_carbon_atoms)(smi) for smi in self.smiles_list
56 )
58 @staticmethod
59 def get_smiles(list_of_dicts: List[Dict[str, str]]) -> List[str]:
60 """
61 Extract SMILES strings from a list of dictionaries containing reaction
62 data.
64 Parameters:
65 - list_of_dicts (List[Dict[str, str]]): A list of dictionaries
66 containing reaction data. Each dictionary should contain
67 'reactants' and 'products' keys, where the values are SMILES
68 strings.
70 Returns:
71 - List[str]: List of SMILES strings extracted from the reactions.
72 """
73 return [
74 smi
75 for reaction in list_of_dicts
76 for smi in reaction.get("reactants", "").split(".")
77 + reaction.get("products", "").split(".")
78 if smi
79 ]
81 @staticmethod
82 def calculate_mol_weight(smiles: str) -> float:
83 """
84 Calculate the molecular weight of a molecule represented by a SMILES
85 string.
87 Parameters:
88 - smiles (str): The SMILES string of the molecule.
90 Returns:
91 - float: The molecular weight of the molecule, or None if the SMILES
92 string is invalid.
93 """
94 molecule = Chem.MolFromSmiles(smiles)
95 if molecule:
96 return Descriptors.MolWt(molecule)
98 @staticmethod
99 def count_carbon_atoms(smiles: str) -> int:
100 """
101 Count the number of carbon (C) atoms in a molecule represented by its
102 SMILES string.
104 Parameters
105 ----------
106 smiles : str
107 The SMILES representation of the molecule.
109 Returns
110 -------
111 int
112 The number of carbon atoms in the molecule.
113 """
114 mol = Chem.MolFromSmiles(smiles)
115 if mol is None:
116 raise ValueError("Invalid SMILES string")
117 num_carbon_atoms = sum(1 for atom in mol.GetAtoms() if atom.GetSymbol() == "C")
119 return num_carbon_atoms
121 @staticmethod
122 def get_fragments(
123 input_dict: dict, mw: float = 100, n_C: int = 10, combination: str = "union"
124 ) -> dict:
125 """
126 Filter a dictionary of lists based on conditions specified by mw and n_C.
128 Parameters
129 ----------
130 input_dict : dict
131 A dictionary where each key corresponds to a list of values.
132 mw : float, optional
133 Maximum allowed molecular weight. Default is 100.
134 n_C : int, optional
135 Minimum required number of carbon atoms. Default is 10.
136 combination : str, optional
137 Filter combination ('union' or 'intersection'). Default is 'union'.
139 Returns
140 -------
141 dict
142 Filtered dictionary with the same keys and filtered lists of values.
143 """
144 filtered_dict = {key: [] for key in input_dict.keys()}
146 for i in range(len(input_dict["smiles"])):
147 include_fragment = False
149 if combination == "union":
150 if input_dict["mw"][i] <= mw or input_dict["n_C"][i] <= n_C:
151 include_fragment = True
153 if combination == "intersection":
154 if input_dict["mw"][i] <= mw and input_dict["n_C"][i] <= n_C:
155 include_fragment = True
157 if include_fragment:
158 for key in input_dict.keys():
159 filtered_dict[key].append(input_dict[key][i])
161 return filtered_dict