Coverage for SynRBL/SynProcessor/rsmi_processing.py: 100%
46 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 pandas as pd
2import rdkit.Chem as Chem
4from joblib import Parallel, delayed
5from SynRBL.rsmi_utils import save_database
7from typing import Tuple
10class RSMIProcessing:
11 """
12 A class to process reaction SMILES (RSMI) data.
14 Parameters
15 ----------
16 rsmi : str, optional
17 The reaction SMILES string to be processed.
18 data : DataFrame, optional
19 The DataFrame containing the RSMI data.
20 rsmi_col : str, optional
21 The column name in the DataFrame that contains the RSMI data.
22 symbol : str, optional
23 The symbol that separates reactants and products in the RSMI string (default is '>>').
24 n_jobs : int, optional
25 The number of jobs to run in parallel (default is 10).
26 verbose : int, optional
27 The verbosity level (default is 1).
28 parallel : bool, optional
29 Whether to use parallel processing (default is True).
30 save_json : bool, optional
31 Whether to save the processed data to a JSON file (default is True).
32 save_path_name : str, optional
33 The path and name of the JSON file to save (default is 'reaction.json.gz').
34 orient : str, optional
35 The orientation of the JSON file (default is 'records').
36 compression : str, optional
37 The compression type for the JSON file (default is 'gzip').
39 Example
40 -------
41 # Create an instance of the RSMIProcessing class with a DataFrame
42 >>> data = pd.DataFrame({'rsmi': ['CCO>>CCOCC', 'CC>>C']})
43 >>> processor = RSMIProcessing(data=data, rsmi_col='rsmi', parallel=False)
44 # Split the RSMI data into reactants and products
45 >>> processed_data = processor.data_splitter()
46 # Display the processed data
47 >>> print(processed_data)
48 """
50 def __init__(
51 self,
52 reaction_smiles: str = None,
53 data: pd.DataFrame = None,
54 data_name: str = "USPTO_50K",
55 index_col: str = "R-id",
56 rsmi_col: str = None,
57 symbol: str = ">>",
58 n_jobs: int = 4,
59 drop_duplicates: bool = True,
60 verbose: int = 1,
61 parallel: bool = True,
62 save_json: bool = True,
63 save_path_name: str = "reaction.json.gz",
64 orient: str = "records",
65 compression: str = "gzip",
66 ) -> None:
67 self.reaction_smiles = reaction_smiles
68 self.symbol = symbol
69 self.n_jobs = n_jobs
70 self.verbose = verbose
71 self.parallel = parallel
72 self.data = data
73 self.data_name = data_name
74 self.index_col = index_col
75 self.drop_duplicates = drop_duplicates
76 self.rsmi_col = rsmi_col
77 self.save_json = save_json
78 self.save_path_name = save_path_name
79 self.orient = orient
80 self.compression = compression
82 @staticmethod
83 def smi_splitter(rsmi: str, symbol: str = ">>") -> Tuple[str, str]:
84 """
85 Split a RSMI string into reactants and products.
87 Returns
88 -------
89 tuple
90 The reactants and products as separate strings, if the RSMI string can be parsed.
91 str
92 A message indicating the RSMI string can't be parsed, if applicable.
93 """
95 # Check if the RSMI string can be parsed
96 if RSMIProcessing.can_parse(rsmi, symbol):
97 # Split the RSMI string into reactants and products
98 return rsmi.split(symbol)
99 else:
100 # Return a message if the RSMI string cannot be parsed
101 return "Can't parse"
103 def data_splitter(self) -> pd.DataFrame:
104 """
105 Split the RSMI data in the DataFrame into reactants and products.
107 Returns
108 -------
109 DataFrame
110 The processed DataFrame with separate columns for reactants and products.
112 Example
113 -------
114 >>> data = pd.DataFrame({'rsmi': ['C>>CC', 'CC>>CCC']})
115 >>> processor = RSMIProcessing(data=data, rsmi_col='rsmi', parallel=False)
116 >>> processed_data = processor.data_splitter()
117 >>> print(processed_data)
118 """
119 # Check if parallel processing is enabled
120 if self.parallel:
121 # Use joblib's Parallel to concurrently process each RSMI string in the DataFrame
122 # 'can_parse' function is applied to each RSMI string to check if it's parsable
123 parsable = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
124 delayed(RSMIProcessing.can_parse)(rsmi)
125 for rsmi in self.data[self.rsmi_col].values
126 )
127 # Filter the data to include only parsable RSMI strings
128 self.data = self.data[parsable]
129 else:
130 # If parallel processing is not enabled, apply 'can_parse' function sequentially
131 # to each RSMI string in the DataFrame and filter parsable ones
132 self.data = self.data[
133 self.data[self.rsmi_col].apply(RSMIProcessing.can_parse)
134 ]
136 # Split each RSMI string in the DataFrame into reactants and products
137 # 'expand=True' splits the string into separate columns
138 split_smiles = self.data[self.rsmi_col].str.split(self.symbol, expand=True)
140 # Assign the first part of the split (reactants) to a new column in the DataFrame
141 self.data["reactants"] = split_smiles[0]
142 # Assign the second part of the split (products) to another new column
143 self.data["products"] = split_smiles[1]
145 if self.drop_duplicates:
146 self.data.drop_duplicates(subset=self.rsmi_col, inplace=True)
147 self.data.reset_index(drop=True, inplace=True)
148 self.data[self.index_col] = [
149 self.data_name + "_" if self.data_name is not None else "" + str(i)
150 for i in self.data.index
151 ]
152 # Check if there's a need to save the processed data to a JSON file
153 if self.save_json:
154 data = self.data.to_dict(orient=self.orient)
155 save_database(data, self.save_path_name)
156 # Save the DataFrame to a JSON file with specified format and compression
157 # self.data.to_json(self.save_path_name, orient=self.orient, compression=self.compression)
159 # Return the processed DataFrame with separate columns for reactants and products
160 return self.data
162 @staticmethod
163 def can_parse(rsmi: str, symbol: str = ">>") -> bool:
164 """
165 Check if a RSMI string can be parsed into reactants and products.
167 Parameters
168 ----------
169 rsmi : str
170 The reaction smiles (RSMI) string to be checked for parsability.
171 symbol : str, optional
172 The symbol used to separate reactants and products in the RSMI string (default is '>>').
174 Returns
175 -------
176 bool
177 True if the RSMI string can be parsed into valid reactant and product SMILES, False otherwise.
178 """
180 # Split the RSMI string into reactants and products using the provided symbol
181 react, prod = rsmi.split(symbol)
183 # Check if both reactants and products can be converted into RDKit molecule objects
184 return (
185 Chem.MolFromSmiles(prod) is not None
186 and Chem.MolFromSmiles(react) is not None
187 )