Coverage for SynRBL/SynRuleImputer/synthetic_rule_matcher.py: 81%
75 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 SynRBL.SynUtils.data_utils import find_shortest_sublists
2from SynRBL.SynUtils.chem_utils import calculate_net_charge
3from typing import List, Dict, Any
4from typing import Union
7class SyntheticRuleMatcher:
8 """
9 A class to match rules based on given chemical data using a depth-first
10 search algorithm. Implements backtracking to revert to previous states if a
11 dead end is reached. Allows selection between finding the 'best' single
12 solution or 'all' possible solutions.
14 Example:
15 rule_dict = [{'smiles': 'C1=CC=CC=C1', 'Composition': {'C': 6, 'H': 6}},
16 {'smiles': 'CCO', 'Composition': {'C': 2, 'H': 6, 'O': 1}}]
17 data_dict = {'C': 6, 'H': 6,}
18 matcher = RSMIRuleMatcher(rule_dict, data_dict, select='best', ranking=False)
19 best_solution = matcher.match()
20 print(best_solution)
21 # Output: [{'smiles': 'C1=CC=CC=C1', 'Ratio': 1}]
23 Attributes:
24 rule_dict (list): A list of dictionaries representing chemical rules,
25 each containing 'smiles' and 'Composition'.
26 data_dict (dict): A dictionary representing available chemical data,
27 with element symbols as keys and counts as values.
28 select (str): Selection mode, either 'best' for the best solution or
29 'all' for all solutions.
30 ranking (str or bool): Ranking mode for solutions, options are
31 'longest', 'least', 'greatliest', or False.
33 Methods:
34 match(): Find matching solutions based on the specified selection and
35 ranking mode.
36 """
38 def __init__(
39 self,
40 rule_dict: List[Dict[str, Any]],
41 data_dict: Dict[str, int],
42 select: str = "best",
43 ranking: bool = False,
44 ) -> None:
45 """
46 Initialize the class.
48 Args:
49 rule_dict: A list of dictionaries representing rules.
50 data_dict: A dictionary with data.
51 select: A string indicating the selection method.
52 ranking: A boolean indicating whether ranking is enabled.
53 """
54 # Sort rules by composition length in descending order for efficient matching.
55 self.rule_dict = sorted(
56 rule_dict, key=lambda r: len(r["Composition"]), reverse=True
57 )
58 self.data_dict = data_dict
59 self.select = select
60 if self.select == "all":
61 self.all_solutions = []
62 self.ranking = ranking
64 # Ensure 'Q' key exists in data_dict and remove elements with zero counts.
65 if "Q" not in self.data_dict:
66 self.data_dict["Q"] = 0
67 self.data_dict = {k: v for k, v in self.data_dict.items() if v != 0 or k == "Q"}
69 def match(self) -> List[List[Dict[str, Any]]]:
70 """Find matching solutions based on the specified selection and ranking
71 mode.
73 Args:
74 self (obj): The instance of the class.
76 Returns:
77 List[List[Dict[str, Any]]]: List of matching solutions, each
78 represented as a list of dictionaries.
79 """
80 if self.select == "all":
81 self.dfs(self.data_dict, [])
82 self.all_solutions = self.remove_overlapping_solutions(self.all_solutions)
83 return self.rank_solutions(self.all_solutions, self.ranking)
84 else:
85 solution = self.dfs(self.data_dict, [])
86 return [solution] if solution is not None else []
88 def dfs(self, data: dict, path: list) -> Union[dict, None]:
89 """
90 Depth-First Search (DFS) algorithm to find solutions by exploring
91 possible paths.
93 Args:
94 data (dict): Current chemical data to match against.
95 path (list): List of dictionaries representing the current
96 path/solution.
98 Returns:
99 Union[dict, None]: A solution (path) if found, None otherwise.
100 """
101 if self.exit_strategy_solution(data):
102 if self.select == "all":
103 self.all_solutions.append(path)
104 return None
105 else:
106 return path
108 for rule in self.rule_dict:
109 new_data, new_path = self.apply_rule(data, path, rule)
110 if new_data is not None:
111 result = self.dfs(new_data, new_path)
112 if result is not None:
113 if self.select != "all":
114 return result
115 return None
117 def apply_rule(self, data: dict, path: list, rule: dict) -> tuple[dict, list]:
118 """
119 Apply a chemical rule to the current data and path.
121 Args:
122 data: Current chemical data to match against.
123 path: List of dictionaries representing the current path/solution.
124 rule: Chemical rule to apply, containing 'Composition' and 'smiles'.
126 Returns:
127 A tuple containing the updated chemical data and path if the rule
128 can be applied, None otherwise.
129 """
130 if not self.can_match(rule["Composition"], data):
131 return None, None
133 ratio = abs(
134 min(
135 (data[k] // v if v != 0 else 0)
136 for k, v in rule["Composition"].items()
137 if k != "Q"
138 )
139 )
140 new_data = data.copy()
141 for k, v in rule["Composition"].items():
142 if k in new_data:
143 new_data[k] -= v * ratio
144 if new_data[k] == 0 and k != "Q":
145 del new_data[k]
147 new_path = path + [{"smiles": rule["smiles"], "Ratio": ratio}]
148 return new_data, new_path
150 def can_match(self, rule: dict, data: dict) -> bool:
151 """
152 Check if a chemical rule can be matched with the current data.
154 Args:
155 rule: Chemical rule to apply, containing element symbols and counts.
156 data: Current chemical data to match against.
158 Returns:
159 True if the rule can be matched, False otherwise.
160 """
161 # Iterate over each key-value pair in the rule dictionary
162 # Check if the key is in the data dictionary and if the corresponding
163 # value in the data dictionary is greater than or equal to the value in
164 # the rule dictionary
165 # Exclude the key 'Q' from the check
166 # Return True if all the conditions are met, False otherwise
167 return all(k in data and data[k] >= v for k, v in rule.items() if k != "Q")
169 @staticmethod
170 def rank_solutions(
171 solutions: List[List[Dict[str, Any]]], ranking: Union[str, bool]
172 ) -> List[List[Dict[str, Any]]]:
173 """
174 Rank a list of solutions based on the specified ranking mode.
176 Args:
177 solutions: List of solutions, each represented as a list of
178 dictionaries.
179 ranking: Ranking mode for solutions.
181 Returns:
182 List of ranked solutions.
183 """
184 if ranking == "longest":
185 return sorted(solutions, key=lambda sol: -len(sol), reverse=True)
186 elif ranking == "least":
187 return sorted(solutions, key=lambda sol: sum(len(item) for item in sol))
188 elif ranking == "greatest":
189 return sorted(
190 solutions, key=lambda sol: sum(len(item) for item in sol), reverse=True
191 )
192 elif ranking == "ion_priority":
193 shortest_sublists = find_shortest_sublists(solutions)
194 return sorted(shortest_sublists, key=calculate_net_charge, reverse=True)
195 else:
196 return solutions
198 @staticmethod
199 def exit_strategy_solution(data: dict) -> bool:
200 """
201 Check if the exit strategy condition for finding a solution is met.
203 Args:
204 data (dict): Current chemical data.
206 Returns:
207 bool: True if the exit strategy condition is met, False otherwise.
208 """
209 return len(data) == 1 and data.get("Q", 0) == 0
211 @staticmethod
212 def remove_overlapping_solutions(
213 solutions: List[List[Dict[str, str]]]
214 ) -> List[List[Dict[str, str]]]:
215 """
216 Remove overlapping solutions from the list of solutions.
218 Args:
219 solutions: List of solutions, each represented as a list of
220 dictionaries. Each dictionary should have 'smiles' and 'Ratio'
221 keys with string values.
223 Returns:
224 List of unique solutions with overlapping solutions removed.
225 """
226 unique_solutions = []
227 seen = set()
229 for solution in solutions:
230 # Convert each solution to a set of tuples for comparison
231 solution_set = frozenset(
232 (item["smiles"], item["Ratio"]) for item in solution
233 )
234 if solution_set not in seen:
235 seen.add(solution_set)
236 unique_solutions.append(solution)
238 return unique_solutions