Coverage for SynRBL/SynProcessor/rsmi_comparator.py: 80%
51 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 joblib import Parallel, delayed
2from typing import List, Dict, Tuple
5class RSMIComparator:
6 """
7 A class to compare two lists of dictionaries representing reactants and products.
8 It determines if the reaction is balanced and calculates the difference in atomic compositions.
10 Parameters
11 ----------
12 reactants : list of dict
13 List of dictionaries, each representing atomic composition of a reactant.
14 products : list of dict
15 List of dictionaries, each representing atomic composition of a product.
16 n_jobs : int
17 Number of jobs to run in parallel.
18 verbose : int
19 Verbosity level.
21 Example
22 -------
23 # Example usage of RSMIComparator
24 >>> reactants = [{'C': 1, 'H': 4}]
25 >>> products = [{'C': 1, 'H': 6}]
26 >>> comparator = RSMIComparator(reactants, products)
27 >>> comparison_results, difference_results = comparator.run_parallel()
28 >>> print(comparison_results, difference_results)
29 """
31 def __init__(
32 self,
33 reactants: List[str],
34 products: List[str],
35 n_jobs: int = 4,
36 verbose: int = 1,
37 ) -> None:
38 """
39 Initialize the RSMIComparator object.
41 Args:
42 reactants (List[str]): List of reactant molecules.
43 products (List[str]): List of product molecules.
44 n_jobs (int, optional): Number of parallel jobs. Defaults to 10.
45 verbose (int, optional): Verbosity level. Defaults to 1.
46 """
47 self.reactants = reactants
48 self.products = products
49 self.n_jobs = n_jobs
50 self.verbose = verbose
52 @staticmethod
53 def check_keys(dict1: dict, dict2: dict) -> bool:
54 """
55 Check if all keys in the second dictionary are present in the first dictionary.
57 Args:
58 dict1 (dict): The first dictionary to compare.
59 dict2 (dict): The second dictionary to compare.
61 Returns:
62 bool: Returns True if all keys in dict2 are present in dict1, otherwise False.
64 Example:
65 >>> RSMIComparator.check_keys({'C': 2, 'H': 6}, {'C': 1})
66 True
67 """
68 return all(key in dict1 for key in dict2)
70 @staticmethod
71 def compare_dicts(reactant: dict, product: dict) -> str:
72 """
73 Compare two dictionaries representing atomic compositions of reactants and products.
75 Args:
76 - reactant (dict): Dictionary representing atomic composition of reactants.
77 - product (dict): Dictionary representing atomic composition of products.
79 Returns:
80 - str: A string indicating whether the reaction is balanced, reactant-heavy, product-heavy, or both.
81 """
83 # Check if the keys in both dictionaries are the same
84 if reactant.keys() != product.keys():
85 if RSMIComparator.check_keys(
86 reactant, product
87 ) and not RSMIComparator.check_keys(product, reactant):
88 if all(reactant[key] >= product[key] for key in product.keys()):
89 return "Products"
90 else:
91 return "Both"
92 elif RSMIComparator.check_keys(
93 product, reactant
94 ) and not RSMIComparator.check_keys(reactant, product):
95 if all(reactant[key] <= product[key] for key in reactant.keys()):
96 return "Reactants"
97 else:
98 return "Both"
99 else:
100 return "Both"
101 else:
102 equal = all(reactant[key] == product[key] for key in reactant.keys())
103 greater = all(reactant[key] >= product[key] for key in reactant.keys())
104 lower = all(reactant[key] <= product[key] for key in reactant.keys())
105 if equal:
106 return "Balance"
107 elif greater:
108 return "Products"
109 elif lower:
110 return "Reactants"
111 else:
112 return "Both"
114 @staticmethod
115 def diff_dicts(reactant: dict, product: dict) -> dict:
116 """
117 Calculate the difference in atomic compositions between two dictionaries.
119 Arguments:
120 - reactant (dict): Dictionary representing atomic composition of reactants.
121 - product (dict): Dictionary representing atomic composition of products.
123 Returns:
124 - diff_dict (dict): Dictionary with absolute differences in atomic counts between reactants and products.
126 Example:
127 >>> RSMIComparator.diff_dicts({'C': 2, 'H': 6}, {'C': 2, 'H': 4})
128 {'H': 2}
129 """
130 diff_dict = {}
132 # Calculate differences for keys present in both dictionaries
133 for key in reactant.keys():
134 if key in product:
135 diff_value = abs(reactant[key] - product[key])
136 if diff_value != 0:
137 diff_dict[key] = diff_value
138 else:
139 # Add the count if the key is only in the reactant
140 if reactant[key] != 0:
141 diff_dict[key] = reactant[key]
143 # Add counts for keys that are only in the product
144 for key in product.keys():
145 if key not in reactant and product[key] != 0:
146 diff_dict[key] = product[key]
148 return diff_dict
150 def run_parallel(
151 self, reactants: List[Dict], products: List[Dict]
152 ) -> Tuple[List, List]:
153 """
154 Run comparison and difference calculation in parallel for reactants and products.
156 Parameters
157 ----------
158 reactants : List[Dict]
159 A list of dictionaries representing the reactants.
160 products : List[Dict]
161 A list of dictionaries representing the products.
163 Returns
164 -------
165 Tuple[List, List]
166 A tuple containing two lists: one for comparison results, and one for differences in compositions.
167 """
168 # Run comparisons and difference calculations in parallel using joblib
169 comparison_results = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
170 delayed(self.compare_dicts)(reactant, product)
171 for reactant, product in zip(reactants, products)
172 )
174 difference_results = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
175 delayed(self.diff_dicts)(reactant, product)
176 for reactant, product in zip(reactants, products)
177 )
179 return comparison_results, difference_results