Coverage for SynRBL/SynRuleImputer/synthetic_rule_imputer.py: 82%

40 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-04-11 11:17 +0200

1import copy 

2 

3from rdkit import Chem 

4from SynRBL.SynRuleImputer.synthetic_rule_matcher import SyntheticRuleMatcher 

5from joblib import Parallel, delayed 

6from typing import List, Dict, Any, Union, Optional 

7from rdkit import RDLogger 

8 

9lg = RDLogger.logger() 

10lg.setLevel(RDLogger.ERROR) 

11RDLogger.DisableLog("rdApp.info") 

12 

13 

14class SyntheticRuleImputer(SyntheticRuleMatcher): 

15 """ 

16 A class for imputing missing chemical data based on provided rules. 

17 

18 Example: 

19 rule_dict = [{'smiles': 'C1=CC=CC=C1', 'Composition': {'C': 6, 'H': 6}}, 

20 {'smiles': 'CCO', 'Composition': {'C': 2, 'H': 6, 'O': 1}}] 

21 

22 missing_data = [{'Diff_formula': {'C': 4, 'H': 4}, 'Unbalance': 'Products', 

23 'reactants': 'C2H6', 'products': 'C2H6.C1=CC=CC=C1'}, 

24 {'Diff_formula': {'C': 3, 'H': 6}, 'Unbalance': 'Reactants', 

25 'reactants': 'C2H6', 'products': 'C2H6.C1=CC=CC=C1'}] 

26 

27 imputer = SyntheticRuleImputer(rule_dict, select='best', ranking='longest') 

28 imputed_data = imputer.impute(missing_data) 

29 

30 print(imputed_data) 

31 # Output: 

32 # [{'Diff_formula': {'C': 4, 'H': 4}, 'Unbalance': 'Products', 

33 # 'reactants': 'C2H6', 'products': 'C2H6.C1=CC=CC=C1.CCO', 

34 # 'new_reaction': 'C2H6>>C2H6.C1=CC=CC=C1.CCO'}, 

35 # {'Diff_formula': {'C': 3, 'H': 6}, 'Unbalance': 'Reactants', 

36 # 'reactants': 'C2H6', 'products': 'C2H6.C1=CC=CC=C1', 

37 # 'new_reaction': 'C2H6>>C2H6.C1=CC=CC=C1'}] 

38 """ 

39 

40 def __init__( 

41 self, 

42 rule_dict: List[Dict[str, Any]], 

43 select: str = "best", 

44 ranking: str = "longest", 

45 ) -> None: 

46 """ 

47 Initialize the SyntheticRuleImputer. 

48 

49 Args: 

50 rule_dict: A list of dictionaries representing chemical rules. 

51 select: Selection mode, either 'best' for the best solution or 

52 'all' for all solutions. 

53 ranking: Ranking mode for solutions, options are 'longest', 

54 'least', 'greatest'. 

55 """ 

56 self.rule_dict = rule_dict 

57 self.select = select 

58 self.ranking = ranking 

59 

60 @staticmethod 

61 def single_impute( 

62 missing_dict: List[Dict[str, Any]], 

63 rule_dict: Dict[str, Any], 

64 select: str = "best", 

65 ranking: str = "longest", 

66 ) -> List[Dict[str, Any]]: 

67 """ 

68 Impute missing chemical data based on the provided rules. 

69 

70 Args: 

71 missing_dict (List[Dict[str, Any]]): A list of dictionaries 

72 representing missing chemical data. 

73 rule_dict (Dict[str, Any]): A dictionary representing the rules for 

74 imputing missing data. 

75 select (str, optional): The selection strategy for choosing the 

76 best rule. Defaults to 'best'. 

77 ranking (str, optional): The ranking strategy for ordering the 

78 rules. Defaults to 'longest'. 

79 

80 Returns: 

81 List[Dict[str, Any]]: A list of dictionaries with imputed data. 

82 """ 

83 dict_impute = copy.deepcopy(missing_dict) 

84 

85 matcher = SyntheticRuleMatcher( 

86 rule_dict, dict_impute["Diff_formula"], select=select, ranking=ranking 

87 ) 

88 solution = matcher.match() 

89 

90 if solution: 

91 if len(solution[0]) > 0: 

92 valid_smiles = SyntheticRuleImputer.get_and_validate_smiles(solution[0]) 

93 if valid_smiles: 

94 key = ( 

95 "products" 

96 if dict_impute["Unbalance"] == "Products" 

97 else "reactants" 

98 ) 

99 dict_impute[key] += "." + valid_smiles 

100 

101 # Construct the new_reaction key 

102 dict_impute["new_reaction"] = ( 

103 dict_impute["reactants"] + ">>" + dict_impute["products"] 

104 ) 

105 

106 return dict_impute 

107 

108 def parallel_impute(self, missing_dict: List[Dict], n_jobs: int = 4) -> List[Dict]: 

109 """ 

110 Impute missing chemical data in parallel. 

111 

112 Args: 

113 missing_dict: A list of dictionaries representing missing chemical 

114 data. 

115 

116 Returns: 

117 A list of dictionaries with imputed data. 

118 """ 

119 dict_impute = Parallel(n_jobs=n_jobs, verbose=0)( 

120 delayed(self.single_impute)(item, self.rule_dict, self.select, self.ranking) 

121 for item in missing_dict 

122 ) 

123 return dict_impute 

124 

125 @staticmethod 

126 def get_and_validate_smiles( 

127 solution: List[Dict[str, Union[str, int]]] 

128 ) -> Optional[str]: 

129 """ 

130 Concatenate smiles strings based on their ratios and validate the 

131 result using RDKit. 

132 

133 Args: 

134 solution: A list of dictionaries representing chemical solutions, 

135 each with a 'smiles' string and a 'Ratio' integer. 

136 

137 Returns: 

138 A validated smiles string or None if validation fails. 

139 """ 

140 # Concatenate smiles strings based on their ratios 

141 smiles_parts = [] 

142 for item in solution: 

143 if "smiles" in item and "Ratio" in item: 

144 smiles_parts.extend([item["smiles"]] * item["Ratio"]) 

145 new_smiles = ".".join(smiles_parts) 

146 

147 # Validate the smiles string using RDKit 

148 if Chem.MolFromSmiles(new_smiles) is not None: 

149 return new_smiles 

150 return None