Coverage for SynRBL/SynRuleImputer/rule_data_manager.py: 95%
43 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 SynRBL.SynProcessor import RSMIDecomposer
3import pandas as pd
4from typing import List, Optional, Dict
7class RuleImputeManager(RSMIDecomposer):
8 """
9 A class for managing a database of chemical compounds, allowing for the
10 addition, removal, and standardization of compound entries.
12 Parameters
13 ----------
14 database : list
15 A list of dictionaries representing chemical compounds. Each dictionary
16 has keys: 'formula' (str), 'smiles' (str), and 'Composition' (dict).
18 Methods
19 -------
20 add_entry(formula, smiles):
21 Adds a new entry to the database.
22 add_entries(entries):
23 Adds multiple entries to the database.
24 remove_entry(formula):
25 Removes an entry from the database based on its formula.
26 canonicalize_smiles(smiles):
27 Returns the canonical form of the SMILES string.
28 is_valid_smiles(smiles):
29 Checks if the SMILES string is valid.
30 """
32 def __init__(self, database: Optional[List[dict]] = None) -> None:
33 """
34 Initializes the database with existing data if provided.
36 Args:
37 database (List[dict], optional): An existing database.
39 Example:
40 >>> existing_db = [{'formula': 'H2O', 'smiles': 'O'}]
41 >>> db = RSMIDataImpute(existing_db)
42 """
43 super().__init__()
44 if isinstance(database, pd.DataFrame):
45 self.database = database.to_dict("records")
46 else:
47 self.database = database or []
49 def add_entry(self, formula: str, smiles: str) -> None:
50 """
51 Adds a new entry to the database, ensuring no duplicates and valid
52 SMILES.
54 Args:
55 formula: The formula of the compound.
56 smiles: The SMILES string of the compound.
58 Raises:
59 ValueError: If the SMILES string is invalid or if the entry already
60 exists.
62 Example:
63 >>> db = RSMIDataImpute()
64 >>> db.add_entry('H2O', 'O')
65 Entry with formula 'H2O' and smiles 'O' added to the database.
66 """
67 if any(d["formula"] == formula for d in self.database):
68 raise ValueError(f"Entry with formula '{formula}' already exists.")
70 if any(d["smiles"] == smiles for d in self.database):
71 raise ValueError(f"Entry with SMILES '{smiles}' already exists.")
73 if not self.is_valid_smiles(smiles):
74 raise ValueError(f"Invalid SMILES string: {smiles}")
76 composition = self.decompose(smiles)
77 if "Q" not in composition:
78 composition["Q"] = 0
80 self.database.append(
81 {"formula": formula, "smiles": smiles, "Composition": composition}
82 )
84 print(
85 f"Entry with formula '{formula}' and smiles '{smiles}' added to the database."
86 )
88 def add_entries(self, entries: List[Dict[str, str]]) -> List[Dict[str, str]]:
89 """
90 Adds multiple entries to the database.
92 Args:
93 entries: A list of dictionaries with 'formula' and 'smiles' keys.
95 Returns:
96 A list of entries that were not added due to errors.
98 Example:
99 >>> db = RSMIDataImpute()
100 >>> invalid_entries = db.add_entries(
101 [
102 {"formula": "CO2", "smiles": "C=O"},
103 {"formula": "Invalid", "smiles": "Invalid"},
104 ]
105 )
106 Invalid entries: [{'formula': 'Invalid', 'smiles': 'Invalid'}]
107 """
108 invalid_entries = []
109 for entry in entries:
110 try:
111 self.add_entry(entry["formula"], entry["smiles"])
112 except ValueError:
113 invalid_entries.append(entry)
115 return invalid_entries
117 def remove_entry(self, formula: str) -> None:
118 """
119 Removes an entry from the database based on its formula.
121 Args:
122 formula (str): The formula of the compound to remove.
124 Example:
125 >>> db = RSMIDataImpute()
126 >>> db.add_entry('H2O', 'O')
127 >>> db.remove_entry('H2O')
128 Entry with formula 'H2O' removed from the database.
129 """
130 entry = next((d for d in self.database if d["formula"] == formula), None)
131 if entry:
132 self.database.remove(entry)
133 print(f"Entry with formula '{formula}' removed from the database.")
134 else:
135 print(f"No entry found with formula '{formula}'.")
137 @staticmethod
138 def canonicalize_smiles(smiles: str) -> str:
139 """
140 Converts a SMILES string to its canonical form.
142 Args:
143 - smiles (str): The SMILES string to canonicalize.
145 Returns:
146 - str: The canonicalized SMILES string.
148 Example:
149 >>> canonical_smiles = RSMIDataImpute.canonicalize_smiles('O')
150 >>> print(canonical_smiles)
151 O
152 """
153 mol = Chem.MolFromSmiles(smiles)
154 return Chem.MolToSmiles(mol, isomericSmiles=True) if mol else None
156 @staticmethod
157 def is_valid_smiles(smiles: str) -> bool:
158 """
159 Checks the validity of a SMILES string.
161 Args:
162 - smiles (str): The SMILES string to check.
164 Returns:
165 - bool: True if valid, False otherwise.
167 Example:
168 >>> is_valid = RSMIDataImpute.is_valid_smiles('O')
169 >>> print(is_valid)
170 True
171 """
172 return Chem.MolFromSmiles(smiles) is not None