robert 2.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (261) hide show
  1. robert/__init__.py +9 -0
  2. robert/__main__.py +20 -0
  3. robert/_version.py +3 -0
  4. robert/api.py +646 -0
  5. robert/aqme.py +280 -0
  6. robert/argument_parser.py +98 -0
  7. robert/checkml.py +433 -0
  8. robert/checkml_score.py +50 -0
  9. robert/curate.py +217 -0
  10. robert/evaluate_bot_retrieval.py +125 -0
  11. robert/evaluate_bot_support.py +102 -0
  12. robert/evaluate_workflow_summaries.py +87 -0
  13. robert/export_bot_docs_knowledge.py +1632 -0
  14. robert/generate.py +249 -0
  15. robert/generate_utils.py +311 -0
  16. robert/gui_easyrob/__init__.py +0 -0
  17. robert/gui_easyrob/assets/gif_easyrob.gif +0 -0
  18. robert/gui_easyrob/bot/__init__.py +47 -0
  19. robert/gui_easyrob/bot/answer_metadata.py +198 -0
  20. robert/gui_easyrob/bot/bot_context.py +679 -0
  21. robert/gui_easyrob/bot/bot_engine.py +1100 -0
  22. robert/gui_easyrob/bot/bot_panel.py +1231 -0
  23. robert/gui_easyrob/bot/bot_rag.py +1178 -0
  24. robert/gui_easyrob/bot/bot_window.py +39 -0
  25. robert/gui_easyrob/bot/bot_worker.py +149 -0
  26. robert/gui_easyrob/bot/credential_store.py +143 -0
  27. robert/gui_easyrob/bot/error_parser.py +105 -0
  28. robert/gui_easyrob/bot/evidence_policy.py +164 -0
  29. robert/gui_easyrob/bot/heuristics.py +859 -0
  30. robert/gui_easyrob/bot/icons.py +56 -0
  31. robert/gui_easyrob/bot/input_csv_audit.py +212 -0
  32. robert/gui_easyrob/bot/knowledge/aqme_context.json +5907 -0
  33. robert/gui_easyrob/bot/knowledge/robert_context.json +4817 -0
  34. robert/gui_easyrob/bot/knowledge/ui_context.json +8293 -0
  35. robert/gui_easyrob/bot/knowledge_schema.py +1252 -0
  36. robert/gui_easyrob/bot/knowledge_sources/aqme_user_guidance.json +442 -0
  37. robert/gui_easyrob/bot/knowledge_sources/coverage_manifest.json +95 -0
  38. robert/gui_easyrob/bot/knowledge_sources/robert_user_guidance.json +471 -0
  39. robert/gui_easyrob/bot/knowledge_sources/ui_user_guidance.json +1312 -0
  40. robert/gui_easyrob/bot/llm_providers.py +1573 -0
  41. robert/gui_easyrob/bot/online_docs.py +105 -0
  42. robert/gui_easyrob/bot/prompt_policy.py +575 -0
  43. robert/gui_easyrob/bot/question_intent.py +562 -0
  44. robert/gui_easyrob/bot/response_quality.py +104 -0
  45. robert/gui_easyrob/bot/result_insights.py +225 -0
  46. robert/gui_easyrob/bot/token_usage.py +75 -0
  47. robert/gui_easyrob/bot/workflow_results.py +1396 -0
  48. robert/gui_easyrob/checkml_launcher.py +15 -0
  49. robert/gui_easyrob/easyrob.py +29 -0
  50. robert/gui_easyrob/easyrob_launcher.py +113 -0
  51. robert/gui_easyrob/main/__init__.py +9 -0
  52. robert/gui_easyrob/main/window.py +5152 -0
  53. robert/gui_easyrob/result_navigation.py +14 -0
  54. robert/gui_easyrob/tabs/__init__.py +23 -0
  55. robert/gui_easyrob/tabs/advanced_options.py +370 -0
  56. robert/gui_easyrob/tabs/aqme.py +1234 -0
  57. robert/gui_easyrob/tabs/checkml.py +898 -0
  58. robert/gui_easyrob/tabs/images.py +427 -0
  59. robert/gui_easyrob/tabs/interactive_predictions.py +555 -0
  60. robert/gui_easyrob/tabs/molssi.py +447 -0
  61. robert/gui_easyrob/tabs/predictions.py +484 -0
  62. robert/gui_easyrob/tabs/result_catalog.py +170 -0
  63. robert/gui_easyrob/tabs/results.py +490 -0
  64. robert/gui_easyrob/tabs/results_workspace.py +120 -0
  65. robert/gui_easyrob/test_bot_input_csv_audit.py +152 -0
  66. robert/gui_easyrob/test_bot_question_routing.py +383 -0
  67. robert/gui_easyrob/test_bot_result_analysis.py +356 -0
  68. robert/gui_easyrob/test_bot_retrieval_evaluation.py +110 -0
  69. robert/gui_easyrob/test_bot_ui_integration.py +278 -0
  70. robert/gui_easyrob/test_checkml_app_mode.py +124 -0
  71. robert/gui_easyrob/test_checkml_completion.py +57 -0
  72. robert/gui_easyrob/test_checkml_defaults.py +37 -0
  73. robert/gui_easyrob/test_checkml_result_summary.py +113 -0
  74. robert/gui_easyrob/test_checkml_web_mode.py +57 -0
  75. robert/gui_easyrob/test_dialog_layout.py +33 -0
  76. robert/gui_easyrob/test_gui_bot_regressions.py +320 -0
  77. robert/gui_easyrob/test_molssi_auto.py +569 -0
  78. robert/gui_easyrob/test_tutorial_view.py +215 -0
  79. robert/gui_easyrob/tutorials/check_model.md +25 -0
  80. robert/gui_easyrob/tutorials/chemdraw.md +49 -0
  81. robert/gui_easyrob/tutorials/csv.md +53 -0
  82. robert/gui_easyrob/tutorials/descriptors.md +21 -0
  83. robert/gui_easyrob/tutorials/overview.md +65 -0
  84. robert/gui_easyrob/tutorials/predictions.md +25 -0
  85. robert/gui_easyrob/tutorials/robbot.md +29 -0
  86. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_1.png +0 -0
  87. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_2.png +0 -0
  88. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_3.png +0 -0
  89. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_4.png +0 -0
  90. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_5.png +0 -0
  91. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_6.png +0 -0
  92. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_7.png +0 -0
  93. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_1.png +0 -0
  94. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_10.png +0 -0
  95. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_11.png +0 -0
  96. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_12.png +0 -0
  97. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_13.png +0 -0
  98. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_2.png +0 -0
  99. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_3.png +0 -0
  100. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_4.png +0 -0
  101. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_5.png +0 -0
  102. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_6.png +0 -0
  103. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_7.png +0 -0
  104. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_8.png +0 -0
  105. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_9.png +0 -0
  106. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1.png +0 -0
  107. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_1.png +0 -0
  108. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_2.png +0 -0
  109. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_3.png +0 -0
  110. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_4.png +0 -0
  111. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_5.png +0 -0
  112. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_2.png +0 -0
  113. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_3.png +0 -0
  114. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_4.png +0 -0
  115. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_5.png +0 -0
  116. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_6.png +0 -0
  117. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_7.png +0 -0
  118. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_8.png +0 -0
  119. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_9.png +0 -0
  120. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_1.png +0 -0
  121. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_2.png +0 -0
  122. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_3.png +0 -0
  123. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_4.png +0 -0
  124. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_5.png +0 -0
  125. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_6.png +0 -0
  126. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1.png +0 -0
  127. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_1.png +0 -0
  128. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_2.png +0 -0
  129. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_3.png +0 -0
  130. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_4.png +0 -0
  131. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_5.png +0 -0
  132. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_6.png +0 -0
  133. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_7.png +0 -0
  134. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_8.png +0 -0
  135. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_2.png +0 -0
  136. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_3.png +0 -0
  137. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_4.png +0 -0
  138. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5.png +0 -0
  139. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_1.png +0 -0
  140. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_2.png +0 -0
  141. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_3.png +0 -0
  142. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_6.png +0 -0
  143. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1.png +0 -0
  144. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1_1.png +0 -0
  145. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_2.png +0 -0
  146. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_3.png +0 -0
  147. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_4.png +0 -0
  148. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_5.png +0 -0
  149. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_6.png +0 -0
  150. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_1.png +0 -0
  151. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_2.png +0 -0
  152. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_3.png +0 -0
  153. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_4.png +0 -0
  154. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_5.png +0 -0
  155. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_6.png +0 -0
  156. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_7.png +0 -0
  157. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_8.png +0 -0
  158. robert/gui_easyrob/utils/__init__.py +0 -0
  159. robert/gui_easyrob/utils/aqme_utils.py +238 -0
  160. robert/gui_easyrob/utils/molssi_utils.py +584 -0
  161. robert/gui_easyrob/utils/predictions_utils.py +985 -0
  162. robert/gui_easyrob/utils/utils_gui.py +738 -0
  163. robert/gui_easyrob/version.py +68 -0
  164. robert/gui_easyrob/web/app.css +484 -0
  165. robert/gui_easyrob/web/app.html +134 -0
  166. robert/gui_easyrob/web/app.js +764 -0
  167. robert/gui_easyrob/web/checkml_brand.png +0 -0
  168. robert/gui_easyrob/web/easyrob_background.gif +0 -0
  169. robert/gui_easyrob/web/easyrob_background.png +0 -0
  170. robert/gui_easyrob/web/images.css +89 -0
  171. robert/gui_easyrob/web/images.html +39 -0
  172. robert/gui_easyrob/web/images.js +101 -0
  173. robert/gui_easyrob/web/results.js +499 -0
  174. robert/gui_easyrob/web/robert_brand.png +0 -0
  175. robert/gui_easyrob/web_dialogs.py +64 -0
  176. robert/gui_easyrob/web_results.py +253 -0
  177. robert/gui_easyrob/web_shell.py +684 -0
  178. robert/gui_easyrob/workflow_progress.py +89 -0
  179. robert/gui_easyrob/workflow_run_lock.py +27 -0
  180. robert/icons/CheckML_icon.png +0 -0
  181. robert/icons/Robert_icon.png +0 -0
  182. robert/icons/Robert_logo.jpg +0 -0
  183. robert/icons/Robert_logo_transparent.png +0 -0
  184. robert/icons/documentation_icon.png +0 -0
  185. robert/icons/info_icon.png +0 -0
  186. robert/icons/pdf_icon.png +0 -0
  187. robert/icons/play_icon.png +0 -0
  188. robert/icons/stop_icon.png +0 -0
  189. robert/icons/youtube_icon.ico +0 -0
  190. robert/predict.py +193 -0
  191. robert/predict_utils.py +410 -0
  192. robert/report/CheckML_logo.jpg +0 -0
  193. robert/report/GENERATE.png +0 -0
  194. robert/report/Robert_icon.ico +0 -0
  195. robert/report/Robert_logo.jpg +0 -0
  196. robert/report/Robert_logo1.jpg +0 -0
  197. robert/report/abbrev.png +0 -0
  198. robert/report/adv_anal.png +0 -0
  199. robert/report/checkml_pass.svg +3 -0
  200. robert/report/checkml_unclear.svg +3 -0
  201. robert/report/checkml_warning.svg +3 -0
  202. robert/report/features.png +0 -0
  203. robert/report/outliers.png +0 -0
  204. robert/report/pred.png +0 -0
  205. robert/report/repro.png +0 -0
  206. robert/report/robust_x.png +0 -0
  207. robert/report/robust_y_high.png +0 -0
  208. robert/report/robust_y_low.png +0 -0
  209. robert/report/score.png +0 -0
  210. robert/report/score_0.jpg +0 -0
  211. robert/report/score_1.jpg +0 -0
  212. robert/report/score_10.jpg +0 -0
  213. robert/report/score_2.jpg +0 -0
  214. robert/report/score_3.jpg +0 -0
  215. robert/report/score_4.jpg +0 -0
  216. robert/report/score_5.jpg +0 -0
  217. robert/report/score_6.jpg +0 -0
  218. robert/report/score_7.jpg +0 -0
  219. robert/report/score_8.jpg +0 -0
  220. robert/report/score_9.jpg +0 -0
  221. robert/report/score_gray_0.jpg +0 -0
  222. robert/report/score_gray_1.jpg +0 -0
  223. robert/report/score_gray_10.jpg +0 -0
  224. robert/report/score_gray_2.jpg +0 -0
  225. robert/report/score_gray_3.jpg +0 -0
  226. robert/report/score_gray_4.jpg +0 -0
  227. robert/report/score_gray_5.jpg +0 -0
  228. robert/report/score_gray_6.jpg +0 -0
  229. robert/report/score_gray_7.jpg +0 -0
  230. robert/report/score_gray_8.jpg +0 -0
  231. robert/report/score_gray_9.jpg +0 -0
  232. robert/report/score_w_1_0.jpg +0 -0
  233. robert/report/score_w_1_1.jpg +0 -0
  234. robert/report/score_w_2_0.jpg +0 -0
  235. robert/report/score_w_2_1.jpg +0 -0
  236. robert/report/score_w_2_2.jpg +0 -0
  237. robert/report/score_w_2_gray_0.jpg +0 -0
  238. robert/report/score_w_2_gray_1.jpg +0 -0
  239. robert/report/score_w_2_gray_2.jpg +0 -0
  240. robert/report/score_w_3_0.jpg +0 -0
  241. robert/report/score_w_3_1.jpg +0 -0
  242. robert/report/score_w_3_2.jpg +0 -0
  243. robert/report/score_w_3_3.jpg +0 -0
  244. robert/report/score_w_4_0.jpg +0 -0
  245. robert/report/score_w_4_1.JPG +0 -0
  246. robert/report/score_w_4_2.jpg +0 -0
  247. robert/report/score_w_4_3.jpg +0 -0
  248. robert/report/score_w_4_4.jpg +0 -0
  249. robert/report/transpa.png +0 -0
  250. robert/report/y_distrib.png +0 -0
  251. robert/report.py +2880 -0
  252. robert/report_utils.py +2270 -0
  253. robert/robert.py +181 -0
  254. robert/utils.py +4763 -0
  255. robert/verify.py +606 -0
  256. robert-2.2.0.dist-info/METADATA +55 -0
  257. robert-2.2.0.dist-info/RECORD +261 -0
  258. robert-2.2.0.dist-info/WHEEL +5 -0
  259. robert-2.2.0.dist-info/entry_points.txt +3 -0
  260. robert-2.2.0.dist-info/licenses/LICENSE +21 -0
  261. robert-2.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1234 @@
1
+ """
2
+ AQME integration tab for easyROB.
3
+
4
+ This module implements the AQME advanced options part of the GUI, handling
5
+ molecular preprocessing, SMARTS pattern detection, and ChemDraw integration.
6
+
7
+ Responsibilities:
8
+ - Load and validate molecular datasets (SMILES, CDXML, SDF)
9
+ - Detect common substructures (MCS/SMARTS)
10
+ - Enable interactive atom selection for descriptor generation
11
+ - Generate mapped SMILES and curated CSV files
12
+ - Provide ChemDraw-to-CSV conversion tools
13
+
14
+ Import strategy:
15
+ - Supports dual execution modes:
16
+ 1. Local (portable execution)
17
+ 2. Installed package (environment / entry point)
18
+
19
+ - Uses try/except fallback to resolve imports accordingly.
20
+
21
+ Notes:
22
+ - Combines UI logic with domain-specific chemistry operations (RDKit).
23
+ - Acts as a bridge between user input and AQME descriptor workflows.
24
+
25
+ """
26
+
27
+ # ------------------------------------------------------------
28
+ # Import resolution (local vs installed package)
29
+ # ------------------------------------------------------------
30
+ try:
31
+ from utils.utils_gui import (
32
+ AssetLibrary,
33
+ BytesIO,
34
+ Chem,
35
+ Draw,
36
+ QCheckBox,
37
+ QComboBox,
38
+ QDesktopServices,
39
+ QDialog,
40
+ QFileDialog,
41
+ QFormLayout,
42
+ QGridLayout,
43
+ QGroupBox,
44
+ QHBoxLayout,
45
+ QIcon,
46
+ QImage,
47
+ QInputDialog,
48
+ QLabel,
49
+ QLineEdit,
50
+ QMessageBox,
51
+ QMouseEvent,
52
+ QPixmap,
53
+ QPushButton,
54
+ QSizePolicy,
55
+ QTableWidget,
56
+ QTableWidgetItem,
57
+ QUrl,
58
+ QVBoxLayout,
59
+ QWidget,
60
+ Qt,
61
+ smart_read_csv,
62
+ GetMolFrags,
63
+ MolsFromCDXMLFile,
64
+ rdDepictor,
65
+ rdMolDraw2D,
66
+ rdkit,
67
+ )
68
+
69
+ from utils.aqme_utils import ChemDrawFileDialog, MCSProcessWorker
70
+
71
+ except ImportError as e:
72
+ from robert.gui_easyrob.utils.utils_gui import (
73
+ AssetLibrary,
74
+ BytesIO,
75
+ Chem,
76
+ Draw,
77
+ QCheckBox,
78
+ QComboBox,
79
+ QDesktopServices,
80
+ QDialog,
81
+ QFileDialog,
82
+ QFormLayout,
83
+ QGridLayout,
84
+ QGroupBox,
85
+ QHBoxLayout,
86
+ QIcon,
87
+ QImage,
88
+ QInputDialog,
89
+ QLabel,
90
+ QLineEdit,
91
+ QMessageBox,
92
+ QMouseEvent,
93
+ QPixmap,
94
+ QPushButton,
95
+ QSizePolicy,
96
+ QTableWidget,
97
+ QTableWidgetItem,
98
+ QUrl,
99
+ QVBoxLayout,
100
+ QWidget,
101
+ Qt,
102
+ smart_read_csv,
103
+ GetMolFrags,
104
+ MolsFromCDXMLFile,
105
+ rdDepictor,
106
+ rdMolDraw2D,
107
+ rdkit,
108
+ )
109
+
110
+ from robert.gui_easyrob.utils.aqme_utils import ChemDrawFileDialog, MCSProcessWorker
111
+
112
+ # ---- Standard library (keep explicit) ----
113
+ import os
114
+ import csv
115
+ from functools import partial
116
+
117
+ class AQMETab(QWidget):
118
+ """Tab responsible for AQME-oriented chemistry preparation workflows."""
119
+ def __init__(self, tab_parent=None, main_window=None):
120
+
121
+ super().__init__(tab_parent) # tab_parent = QTabWidget
122
+ self.main_tab_widget = tab_parent # Reference to the main QTabWidget
123
+ self.main_window = main_window # Reference to the main window, accessible to csv_df, csv_path, etc...
124
+ self.selected_atoms = []
125
+ self.smarts_targets = []
126
+ self.unified_smiles = []
127
+ self.bot_context_message = ""
128
+ self.bot_context_tooltip = ""
129
+ self.bot_context_info = ""
130
+ self.box_features = "QGroupBox { font-weight: bold; }"
131
+
132
+ # === Main vertical layout ===
133
+ main_layout = QVBoxLayout(self)
134
+
135
+ # --- ChemDraw Button (modern purple style + top spacing) ---
136
+ self.chemdraw_button = QPushButton("Generate CSV from ChemDraw Files or SDF file")
137
+ self.chemdraw_button.setCursor(Qt.PointingHandCursor)
138
+ self.chemdraw_button.setFixedSize(400, 42)
139
+
140
+ self.chemdraw_button.setStyleSheet("""
141
+ QPushButton {
142
+ background-color: #7E57C2;
143
+ color: white;
144
+ border-radius: 8px;
145
+ font-size: 14px;
146
+ font-weight: bold;
147
+ padding: 10px;
148
+ }
149
+ QPushButton:hover {
150
+ background-color: #6A42B8;
151
+ }
152
+ QPushButton:pressed {
153
+ background-color: #5E35B1;
154
+ }
155
+ """)
156
+
157
+ self.chemdraw_button.clicked.connect(self.open_chemdraw_popup)
158
+
159
+ # Center button horizontally
160
+ button_layout = QHBoxLayout()
161
+ button_layout.addStretch()
162
+ button_layout.addWidget(self.chemdraw_button)
163
+ button_layout.addStretch()
164
+
165
+ # Add vertical spacing above the button
166
+ button_container = QVBoxLayout()
167
+ button_container.addSpacing(50)
168
+ button_container.addLayout(button_layout)
169
+
170
+ main_layout.addLayout(button_container)
171
+
172
+
173
+ # === Viewer container with label + viewer stacked ===
174
+ self.mol_viewer_container = QWidget()
175
+ self.mol_viewer_container.setFixedSize(400, 400)
176
+ self.mol_viewer_container.setStyleSheet("background: transparent;")
177
+
178
+ # Layout with relative positioning
179
+ mol_layout = QGridLayout(self.mol_viewer_container)
180
+ mol_layout.setContentsMargins(0, 0, 0, 0)
181
+ mol_layout.setSpacing(0)
182
+
183
+ # === mol_viewer (molecule display) ===
184
+ self.mol_viewer = QLabel(self.mol_viewer_container)
185
+ self.mol_viewer.setAlignment(Qt.AlignmentFlag.AlignCenter)
186
+ self.mol_viewer.setWordWrap(True)
187
+
188
+ # Allow text selection
189
+ self.mol_viewer.setTextInteractionFlags(
190
+ Qt.TextSelectableByMouse | Qt.TextSelectableByKeyboard
191
+ )
192
+ self.set_mol_viewer_message("📄 Select a CSV with a SMILES column to display a common SMARTS pattern.")
193
+ self.mol_viewer.setFixedSize(400, 400)
194
+
195
+ # === mol_info_label ===
196
+ self.mol_info_label = QLabel("🔬 Info here", self.mol_viewer_container)
197
+ self.mol_info_label.setStyleSheet("""
198
+ color: #222;
199
+ background-color: rgba(240, 240, 240, 220);
200
+ font-size: 11px;
201
+ font-style: italic;
202
+ padding: 4px 8px;
203
+ margin: 6px;
204
+ border-radius: 6px;
205
+ border: 1px solid #aaa;
206
+ """)
207
+
208
+ self.mol_info_label.setWordWrap(True)
209
+ self.mol_info_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
210
+ self.mol_info_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)
211
+ self.mol_info_label.setMaximumWidth(600)
212
+ self.mol_info_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop)
213
+
214
+ # === Set up the molecule viewer ===
215
+ mol_layout.addWidget(self.mol_viewer, 0, 0)
216
+ mol_layout.addWidget(self.mol_info_label, 0, 0, alignment=Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
217
+ mol_wrapper_layout = QHBoxLayout()
218
+ mol_wrapper_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
219
+ mol_wrapper_layout.addWidget(self.mol_viewer_container)
220
+ main_layout.addLayout(mol_wrapper_layout)
221
+
222
+ # === AQME Box at the bottom ===
223
+ aqme_box = QGroupBox("AQME")
224
+ aqme_box.setMaximumHeight(200)
225
+ aqme_box.setStyleSheet(self.box_features)
226
+ aqme_layout = QFormLayout()
227
+
228
+ self.atoms = QLineEdit(placeholderText="e.g., Au or C=O")
229
+ self.descriptor_level = QComboBox()
230
+ self.descriptor_level.addItems(["interpret", "denovo", "full"])
231
+ self.solvent = QComboBox()
232
+ self.solvent.addItems([
233
+ "None",
234
+ # "Acetone",
235
+ # "Acetonitrile",
236
+ # "Aniline",
237
+ # "Benzaldehyde",
238
+ # "Benzene",
239
+ # "CH2Cl2",
240
+ # "CHCl3",
241
+ # "CS2",
242
+ # "Dioxane",
243
+ # "DMF",
244
+ # "DMSO",
245
+ # "Ether",
246
+ # "Ethylacetate",
247
+ # "Furane",
248
+ # "Hexadecane",
249
+ # "Hexane",
250
+ # "Methanol",
251
+ # "Nitromethane",
252
+ # "Octanol",
253
+ # "Octanol (wet)",
254
+ # "Phenol",
255
+ # "Toluene",
256
+ # "THF",
257
+ # "Water"
258
+ ])
259
+
260
+ aqme_layout.addRow(QLabel("QDESCP Atoms:"), self.atoms)
261
+ aqme_layout.addRow(QLabel("Descriptor Level:"), self.descriptor_level)
262
+ aqme_layout.addRow(QLabel("Solvent:"), self.solvent)
263
+
264
+ # Help button
265
+ help_button = QPushButton("Help AQME parameters")
266
+ with AssetLibrary.Info_icon.get_path() as icon_path:
267
+ help_button.setIcon(QIcon(str(icon_path)))
268
+
269
+ help_button.setCursor(Qt.PointingHandCursor)
270
+ help_button.setStyleSheet("padding: 4px; font-weight: bold;")
271
+ help_button.clicked.connect(lambda: self.go_to_help_section("AQME"))
272
+
273
+ aqme_layout.addRow("", help_button)
274
+ aqme_layout.setAlignment(help_button, Qt.AlignRight)
275
+
276
+ aqme_box.setLayout(aqme_layout)
277
+ main_layout.addWidget(aqme_box)
278
+
279
+ def go_to_help_section(self, anchor):
280
+ """Open the corresponding documentation section in the browser."""
281
+
282
+ base_url = "https://robert.readthedocs.io/en/latest/Technical/defaults.html"
283
+
284
+ if anchor:
285
+ full_url = f"{base_url}#{anchor.lower()}"
286
+ else:
287
+ full_url = base_url
288
+
289
+ QDesktopServices.openUrl(QUrl(full_url))
290
+
291
+ def set_mol_viewer_message(self, message, tooltip=None):
292
+ """Display a styled message in the molecule viewer, with optional tooltip."""
293
+ self.bot_context_message = str(message or "")
294
+ self.bot_context_tooltip = str(tooltip or "")
295
+ self.mol_viewer.setText(message)
296
+ self.mol_viewer.setToolTip(tooltip if tooltip else "")
297
+ self.mol_viewer.setStyleSheet("""
298
+ color: #222;
299
+ background-color: rgba(255, 255, 255, 230);
300
+ font-size: 11px;
301
+ font-style: italic;
302
+ padding: 4px 8px;
303
+ margin: 6px;
304
+ border-radius: 6px;
305
+ border: 1px solid #aaa;
306
+ """)
307
+
308
+ def detect_patterns_and_display(self):
309
+ """Detects patterns in the loaded CSV and displays the first molecule."""
310
+
311
+ try:
312
+ self.csv_df = smart_read_csv(self.file_path) # Store the DataFrame for later use
313
+ self.smiles_column = next((col for col in self.csv_df.columns if col.lower() == "smiles"), None)
314
+
315
+ self.set_mol_viewer_message("🔬 Detecting common SMARTS pattern...")
316
+
317
+ # === Auto SMARTS detection ===
318
+ self.auto_pattern()
319
+
320
+ except Exception as e:
321
+ self.set_mol_viewer_message("❌ Failed to load or process the CSV.")
322
+ self.mol_info_label.setText("🔬 Info here")
323
+
324
+ def _on_mcs_success(self, smarts):
325
+ """Handle successful MCS detection."""
326
+ self.mcs_worker = None
327
+ self.smarts_targets.append(smarts)
328
+ self.mol_info_label.setText("🔬 Info here")
329
+ self.bot_context_message = ""
330
+ self.bot_context_tooltip = ""
331
+ self.bot_context_info = "🔬 Info here"
332
+ self.display_molecule()
333
+
334
+ def _on_mcs_error(self, message):
335
+ """Handle MCS detection error."""
336
+ self.mcs_worker = None
337
+ self.set_mol_viewer_message(
338
+ message,
339
+ tooltip="SMARTS pattern detection failed."
340
+ )
341
+ self.mol_info_label.setText("🔬 Info here")
342
+ self.bot_context_info = "🔬 Info here"
343
+
344
+ def _on_mcs_timeout(self):
345
+ """Handle MCS detection timeout."""
346
+ self.mcs_worker = None
347
+ self.set_mol_viewer_message(
348
+ "⏱️ Timeout: MCS (Maximum Common Substructure) took too long and was aborted.",
349
+ tooltip="SMARTS pattern detection failed."
350
+ )
351
+ self.mol_info_label.setText("🔬 Info here")
352
+ self.bot_context_info = "🔬 Info here"
353
+
354
+ def build_unified_smiles_context(self, train_csv_path, test_csv_path=None):
355
+ """
356
+ Returns a list of SMILES for train/test CSVs (if test exists). This is used ONLY for chemical validation.
357
+ (FMCS, ambiguity checks, metal detection).
358
+ """
359
+ train_df = smart_read_csv(train_csv_path)
360
+ smiles_col = next(
361
+ (c for c in train_df.columns if c.lower() == "smiles"),
362
+ None
363
+ )
364
+ if smiles_col is None:
365
+ raise ValueError("TRAIN CSV has no SMILES column")
366
+
367
+ unified_smiles = (
368
+ train_df[smiles_col]
369
+ .dropna()
370
+ .astype(str)
371
+ .tolist()
372
+ )
373
+
374
+ if test_csv_path:
375
+ test_df = smart_read_csv(test_csv_path)
376
+ test_smiles_col = next(
377
+ (c for c in test_df.columns if c.lower() == "smiles"),
378
+ None
379
+ )
380
+ if test_smiles_col is None:
381
+ raise ValueError("TEST CSV has no SMILES column")
382
+
383
+ unified_smiles.extend(
384
+ test_df[test_smiles_col]
385
+ .dropna()
386
+ .astype(str)
387
+ .tolist()
388
+ )
389
+
390
+ return unified_smiles
391
+
392
+ def generate_mapped_csv_from_smiles(
393
+ self,
394
+ csv_path,
395
+ smarts,
396
+ selected_atoms,
397
+ suffix="_mapped"
398
+ ):
399
+ """Generate a new CSV file with mapped SMILES based on the provided SMARTS pattern"""
400
+
401
+ df = smart_read_csv(csv_path)
402
+ smiles_col = next(
403
+ (c for c in df.columns if c.lower() == "smiles"),
404
+ None
405
+ )
406
+
407
+ if smiles_col is None:
408
+ raise ValueError("CSV has no SMILES column")
409
+
410
+ pattern_mol = Chem.MolFromSmarts(smarts)
411
+ mapped_smiles = []
412
+
413
+ for smiles in df[smiles_col]:
414
+ mol = Chem.AddHs(Chem.MolFromSmiles(smiles))
415
+ if mol is None:
416
+ mapped_smiles.append(None)
417
+ continue
418
+
419
+ matches = mol.GetSubstructMatches(pattern_mol)
420
+ if len(matches) != 1:
421
+ mapped_smiles.append(None)
422
+ continue
423
+
424
+ match = matches[0]
425
+ for atom in mol.GetAtoms():
426
+ atom.SetAtomMapNum(0)
427
+
428
+ for i, idx in enumerate(selected_atoms):
429
+ mol.GetAtomWithIdx(match[idx]).SetAtomMapNum(i + 1)
430
+
431
+ mapped_smiles.append(Chem.MolToSmiles(mol))
432
+
433
+ df_out = df.copy()
434
+ df_out[smiles_col] = mapped_smiles
435
+
436
+ base, _ = os.path.splitext(csv_path)
437
+ out_csv = f"{base}{suffix}.csv"
438
+ df_out.to_csv(out_csv, index=False)
439
+
440
+ return out_csv
441
+
442
+ def auto_pattern(self):
443
+ """
444
+ Auto-detect common SMARTS pattern.
445
+ - TRAIN only → exploratory mode
446
+ - TRAIN + TEST → mapping mode (contract must hold for all)
447
+ """
448
+
449
+ self.mol_info_label.setText("🔬 Info here")
450
+ self.smarts_targets = []
451
+
452
+ if self.smiles_column is None:
453
+ return
454
+
455
+ # -------------------------------
456
+ # Decide FMCS context (ROBUST)
457
+ # -------------------------------
458
+ unified_smiles = getattr(self, "unified_smiles", None)
459
+
460
+ if unified_smiles:
461
+ # TRAIN + TEST → strong contract
462
+ smiles_list = unified_smiles
463
+ else:
464
+ # TRAIN only → exploratory
465
+ smiles_list = (
466
+ self.csv_df[self.smiles_column]
467
+ .dropna()
468
+ .astype(str)
469
+ .tolist()
470
+ )
471
+
472
+ if not smiles_list:
473
+ self.set_mol_viewer_message(
474
+ "⚠️ No molecules available for SMARTS detection."
475
+ )
476
+ return
477
+
478
+ # -------------------------------
479
+ # Launch MCS worker
480
+ # -------------------------------
481
+ existing_worker = getattr(self, "mcs_worker", None)
482
+ if existing_worker is not None:
483
+ try:
484
+ existing_worker.finished.disconnect(self._on_mcs_success)
485
+ except Exception:
486
+ pass
487
+ try:
488
+ existing_worker.error.disconnect(self._on_mcs_error)
489
+ except Exception:
490
+ pass
491
+ try:
492
+ existing_worker.timeout.disconnect(self._on_mcs_timeout)
493
+ except Exception:
494
+ pass
495
+
496
+ self.mcs_worker = MCSProcessWorker(
497
+ smiles_list,
498
+ timeout_ms=60000
499
+ )
500
+
501
+ self.mcs_worker.finished.connect(self._on_mcs_success)
502
+ self.mcs_worker.error.connect(self._on_mcs_error)
503
+ self.mcs_worker.timeout.connect(self._on_mcs_timeout)
504
+
505
+ self.mcs_worker.start()
506
+
507
+ def display_molecule(self):
508
+ """Display a SMARTS molecule and highlight atoms based on user selection."""
509
+ rdkit.rdBase.DisableLog('rdApp.*')
510
+ rdDepictor.SetPreferCoordGen(True)
511
+
512
+ self.metal_atomic_numbers = {
513
+ 3, 11, 19, 37, 55, 87,
514
+ 4, 12, 20, 38, 56, 88,
515
+ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
516
+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
517
+ 72, 73, 74, 75, 76, 77, 78, 79, 80,
518
+ 13, 49, 50, 81, 82, 83
519
+ }
520
+
521
+ try:
522
+ self.metal_found = False
523
+ self.metal_atoms_to_highlight = set()
524
+ metal_found_in_this_mol = False
525
+
526
+ if not self.smarts_targets:
527
+ self.set_mol_viewer_message("⚠️ No SMARTS patterns available.")
528
+ self.mol_info_label.setText("🔬 Info here")
529
+ self.bot_context_info = "🔬 Info here"
530
+ return
531
+
532
+ pattern_mol = Chem.MolFromSmarts(self.smarts_targets[0])
533
+ if pattern_mol is None:
534
+ self.set_mol_viewer_message("⚠️ Invalid SMARTS pattern.")
535
+ self.mol_info_label.setText("🔬 Info here")
536
+ self.bot_context_info = "🔬 Info here"
537
+ return
538
+
539
+ self.multiple_matches_detected = False
540
+
541
+ unified_smiles = getattr(self, "unified_smiles", None)
542
+ if not unified_smiles:
543
+ self.set_mol_viewer_message(
544
+ "⚠️ No molecules available for pattern matching."
545
+ )
546
+ self.mol_info_label.setText("🔬 Info here")
547
+ self.bot_context_info = "🔬 Info here"
548
+ return
549
+
550
+ for smiles in unified_smiles:
551
+ metal_found_in_this_mol = False
552
+
553
+ mol = Chem.AddHs(Chem.MolFromSmiles(smiles))
554
+ if mol is None:
555
+ continue
556
+
557
+ matches = mol.GetSubstructMatches(pattern_mol)
558
+
559
+ for match in matches:
560
+ for idx in match:
561
+ atom = mol.GetAtomWithIdx(idx)
562
+ if atom.GetAtomicNum() in self.metal_atomic_numbers:
563
+ metal_found_in_this_mol = True
564
+ self.metal_found = True
565
+ self.metal_atoms_to_highlight.add(idx)
566
+ break
567
+ if metal_found_in_this_mol:
568
+ break
569
+
570
+ if len(matches) > 1:
571
+ self.multiple_matches_detected = True
572
+ if not metal_found_in_this_mol:
573
+ self.set_mol_viewer_message(
574
+ f"⚠️ <b>Multiple matches detected<b>: the common substructure "
575
+ f"'{self.smarts_targets[0]}' appears more than once in the molecule "
576
+ f"'{smiles}'. Atomic descriptor selection has been disabled to avoid ambiguity."
577
+ )
578
+ self.mol_info_label.setText("🔬 Info here")
579
+ self.bot_context_info = "🔬 Info here"
580
+ return
581
+
582
+ self.mol = pattern_mol
583
+ self.molecule_image_width = self.mol_viewer_container.width()
584
+ self.molecule_image_height = self.mol_viewer_container.height()
585
+
586
+ if self.metal_found and self.multiple_matches_detected:
587
+ highlight_atoms = set(self.metal_atoms_to_highlight)
588
+ else:
589
+ highlight_atoms = set(self.selected_atoms)
590
+
591
+ png_bytes, atom_coords = self._draw_pattern_molecule(
592
+ self.mol,
593
+ highlight_atoms=highlight_atoms,
594
+ selected_atoms=self.selected_atoms,
595
+ width=self.molecule_image_width,
596
+ height=self.molecule_image_height,
597
+ )
598
+ pixmap = QPixmap()
599
+ pixmap.loadFromData(png_bytes)
600
+ self.atom_coords = atom_coords
601
+
602
+ if self.mol_viewer:
603
+ if pixmap.isNull():
604
+ self.set_mol_viewer_message("⚠️ Could not render molecule image.")
605
+ self.mol_info_label.setText("🔬 Info here")
606
+ self.bot_context_info = "🔬 Info here"
607
+ else:
608
+ self.mol_viewer.setPixmap(pixmap)
609
+ self.bot_context_message = (
610
+ f"SMARTS pattern loaded for common substructure `{self.smarts_targets[0]}`."
611
+ )
612
+ self.bot_context_tooltip = ""
613
+
614
+ if self.metal_found and self.multiple_matches_detected:
615
+ info_text = (
616
+ '🧪 <b>SMARTS pattern loaded. Metal atom(s) automatically selected.</b><br>'
617
+ '<span style="color:red;">⚠️ Multiple matches were found. '
618
+ 'Atomic descriptors will be generated for the detected metal atom(s). '
619
+ 'Manual atom selection has been disabled to avoid ambiguity.</span>'
620
+ )
621
+ self.mol_info_label.setText(info_text)
622
+ self.bot_context_info = info_text
623
+ elif self.metal_found and not self.selected_atoms:
624
+ info_text = (
625
+ '🧪 <b>SMARTS pattern loaded. Click to select atoms.</b><br>'
626
+ '<span style="color:red;">⚠️ No atoms selected. '
627
+ 'Descriptors will only be generated for the detected metal.</span>'
628
+ )
629
+ self.mol_info_label.setText(info_text)
630
+ self.bot_context_info = info_text
631
+ else:
632
+ if highlight_atoms:
633
+ info_text = f"🔬 {len(highlight_atoms)} atom(s) selected."
634
+ self.mol_info_label.setText(info_text)
635
+ self.bot_context_info = info_text
636
+ else:
637
+ info_text = (
638
+ '🧪 <b>SMARTS pattern loaded. Click to select atoms.</b><br>'
639
+ '<span style="color:red;">⚠️ WARNING! No atoms selected. '
640
+ 'Atomic descriptors will not be generated.</span>'
641
+ )
642
+ self.mol_info_label.setText(info_text)
643
+ self.bot_context_info = info_text
644
+
645
+ except Exception as e:
646
+ self.set_mol_viewer_message(
647
+ "❌ Error displaying molecule.",
648
+ tooltip=str(e)
649
+ )
650
+ self.mol_info_label.setText("🔬 Info here")
651
+ self.bot_context_info = "🔬 Info here"
652
+
653
+ def _prepare_pattern_molecule_for_drawing(self, pattern_mol, selected_atoms=None):
654
+ """Return a copy of the SMARTS pattern with visible atom-order labels."""
655
+
656
+ mol_for_draw = Chem.Mol(pattern_mol)
657
+ selected_atoms = list(selected_atoms or [])
658
+
659
+ for atom in mol_for_draw.GetAtoms():
660
+ if atom.HasProp("atomNote"):
661
+ atom.ClearProp("atomNote")
662
+
663
+ for order, atom_idx in enumerate(selected_atoms, start=1):
664
+ if 0 <= atom_idx < mol_for_draw.GetNumAtoms():
665
+ mol_for_draw.GetAtomWithIdx(atom_idx).SetProp(
666
+ "atomNote",
667
+ str(order)
668
+ )
669
+
670
+ return mol_for_draw
671
+
672
+ def _draw_pattern_molecule(
673
+ self,
674
+ pattern_mol,
675
+ highlight_atoms,
676
+ selected_atoms,
677
+ width,
678
+ height,
679
+ ):
680
+ """Draw the SMARTS pattern with highlight and click-order numbering."""
681
+
682
+ highlight_atoms = set(highlight_atoms or [])
683
+ highlight_colors = (
684
+ {idx: (0.698, 0.4, 1.0) for idx in highlight_atoms}
685
+ if highlight_atoms else {}
686
+ )
687
+
688
+ draw_mol = self._prepare_pattern_molecule_for_drawing(
689
+ pattern_mol,
690
+ selected_atoms=selected_atoms,
691
+ )
692
+
693
+ drawer = rdMolDraw2D.MolDraw2DCairo(
694
+ max(1, int(width)),
695
+ max(1, int(height))
696
+ )
697
+ options = drawer.drawOptions()
698
+ options.bondLineWidth = 1.5
699
+ options.annotationFontScale = 1.0
700
+ drawer.DrawMolecule(
701
+ draw_mol,
702
+ highlightAtoms=list(highlight_atoms),
703
+ highlightAtomColors=highlight_colors
704
+ )
705
+ drawer.FinishDrawing()
706
+
707
+ png_bytes = drawer.GetDrawingText()
708
+ atom_coords = [
709
+ drawer.GetDrawCoords(i)
710
+ for i in range(draw_mol.GetNumAtoms())
711
+ ]
712
+ return png_bytes, atom_coords
713
+
714
+ def save_atom_mapping_image(
715
+ self,
716
+ output_path,
717
+ smarts=None,
718
+ selected_atoms=None,
719
+ width=900,
720
+ height=700,
721
+ ):
722
+ """Save the numbered SMARTS render used for atom mapping as a PNG."""
723
+
724
+ smarts = smarts or (self.smarts_targets[0] if self.smarts_targets else None)
725
+ selected_atoms = list(self.selected_atoms if selected_atoms is None else selected_atoms)
726
+
727
+ if not smarts or not selected_atoms:
728
+ return None
729
+
730
+ pattern_mol = Chem.MolFromSmarts(smarts)
731
+ if pattern_mol is None:
732
+ raise ValueError("Invalid SMARTS pattern")
733
+
734
+ png_bytes, _ = self._draw_pattern_molecule(
735
+ pattern_mol,
736
+ highlight_atoms=set(selected_atoms),
737
+ selected_atoms=selected_atoms,
738
+ width=width,
739
+ height=height,
740
+ )
741
+
742
+ with open(output_path, "wb") as f:
743
+ f.write(png_bytes)
744
+
745
+ return output_path
746
+
747
+ def handle_atom_selection(self, atom_idx):
748
+ """Handle the selection of an atom in the pattern."""
749
+
750
+ if not hasattr(self, 'selected_atoms'):
751
+ self.selected_atoms = []
752
+
753
+ if getattr(self, 'metal_found', False) and getattr(self, 'multiple_matches_detected', False):
754
+ # Prevent manual selection when metal match has been auto-selected due to ambiguity
755
+ return
756
+
757
+ # If the atom is already selected, deselect it
758
+ if atom_idx in self.selected_atoms:
759
+ self.selected_atoms.remove(atom_idx)
760
+ else:
761
+ # Otherwise, add the atom to the selection list
762
+ self.selected_atoms.append(atom_idx)
763
+
764
+ self.display_molecule() # Update the visualization
765
+
766
+ # Update the mapping regardless of selection or deselection
767
+ self.generate_mapped_smiles(
768
+ self.smarts_targets[0],
769
+ self.selected_atoms,
770
+ self.csv_df[self.smiles_column].dropna()
771
+ )
772
+
773
+
774
+ def generate_mapped_smiles(self, smarts_pattern, selected_pattern_indices, smiles_list):
775
+ """
776
+ Generate mapped SMILES using a SMARTS pattern and selected atom indices.
777
+ Updates self.df_mapped_smiles with a copy of the original CSV where 'SMILES' is replaced.
778
+
779
+ """
780
+
781
+ # Parse the SMARTS pattern to a molecule object
782
+ pattern_mol = Chem.MolFromSmarts(smarts_pattern)
783
+ if pattern_mol is None:
784
+ raise ValueError("Invalid SMARTS pattern")
785
+
786
+ mapped_smiles = []
787
+
788
+ for smiles in smiles_list:
789
+ mol = Chem.AddHs(Chem.MolFromSmiles(smiles))
790
+ if mol is None:
791
+ mapped_smiles.append(None)
792
+ continue
793
+
794
+ # Get *all* substructure matches, continue processing if only one match is found
795
+ matches = mol.GetSubstructMatches(pattern_mol)
796
+ if len(matches) > 1:
797
+ return # Multiple matches found, return without processing
798
+ elif not matches:
799
+ mapped_smiles.append(None)
800
+ continue
801
+
802
+ # One match only → proceed
803
+ match = matches[0]
804
+
805
+ # Clear existing atom map numbers
806
+ for atom in mol.GetAtoms():
807
+ atom.SetAtomMapNum(0)
808
+
809
+ # Assign map numbers to selected atoms
810
+ for i, pattern_idx in enumerate(selected_pattern_indices):
811
+ if pattern_idx < len(match):
812
+ mol.GetAtomWithIdx(match[pattern_idx]).SetAtomMapNum(i + 1)
813
+
814
+ mapped_smiles.append(Chem.MolToSmiles(mol))
815
+
816
+ # Replace SMILES column in CSV
817
+ df = smart_read_csv(self.file_path)
818
+ df_mapped = df.copy()
819
+ df_mapped[self.smiles_column] = mapped_smiles
820
+ self.df_mapped_smiles = df_mapped
821
+
822
+
823
+ def mousePressEvent(self, event: QMouseEvent):
824
+ """Handle mouse press events to select atoms and crate pattern.
825
+ The logic is to check if the mouse press event is within the molecule_viewer area."""
826
+
827
+ if event.button() == Qt.MouseButton.LeftButton:
828
+ pos = event.position()
829
+ if self.mol_viewer_container and self.mol_viewer_container.geometry().contains(pos.toPoint()):
830
+ relative_pos = self.mol_viewer_container.mapFrom(self, pos.toPoint())
831
+ x = relative_pos.x()
832
+ y = relative_pos.y()
833
+ selected_atom = self.get_atom_at_position(x, y)
834
+ if selected_atom is not None:
835
+ self.handle_atom_selection(selected_atom)
836
+ self.display_molecule()
837
+
838
+ def get_atom_at_position(self, x, y):
839
+ """Get the atom index at the given position by
840
+ checking the distance from the atom coordinates.
841
+ The atom coordinates are found using RDKit.
842
+ The logic is to check if the distance between the mouse click
843
+ and the atom coordinates is less than a threshold."""
844
+
845
+ if not hasattr(self, 'atom_coords'):
846
+ return None
847
+ elif self.atom_coords is not None:
848
+ for idx, coord in enumerate(self.atom_coords):
849
+ if len(self.smarts_targets[0]) <= 30: # small molecule = bigger click area
850
+ if (coord.x - x) ** 2 + (coord.y - y) ** 2 < 300:
851
+ return idx
852
+ if len(self.smarts_targets[0]) <= 50 and len(self.smarts_targets[0]) > 30: # medium molecule = medium click area
853
+ if (coord.x - x) ** 2 + (coord.y - y) ** 2 < 200:
854
+ return idx
855
+ elif len(self.smarts_targets[0]) > 50 : # big molecule = smaller click area
856
+ if (coord.x - x) ** 2 + (coord.y - y) ** 2 < 100:
857
+ return idx
858
+ return None
859
+
860
+ def open_chemdraw_popup(self):
861
+ """Open the ChemDraw file dialog and process selected file."""
862
+ # Pre-dialog notice about file quality and format
863
+ QMessageBox.information(
864
+ self,
865
+ "Before Selecting Your File",
866
+ (
867
+ "<b>Before continuing:</b><br><br>"
868
+ "Please ensure your ChemDraw file is saved in <b>CDXML</b> format. Verify that the molecular structures are valid and free from editing errors such as:<br><br>"
869
+ "• Red highlights in ChemDraw (invalid valences or atoms)<br>"
870
+ "• Incorrect or broken bonds<br>"
871
+ "• Unconnected fragments or misdrawn connections<br><br>"
872
+ "<i>When everything looks correct, click OK to select your file.</i>"
873
+ )
874
+ )
875
+
876
+ dialog = ChemDrawFileDialog(self)
877
+ if dialog.exec():
878
+ main_path = dialog.main_chemdraw_path
879
+ self.load_chemdraw_file(main_path)
880
+
881
+ def load_chemdraw_file(self, main_path, molecule_handler=None):
882
+ """Opens a ChemDraw file and displays the molecules in a table."""
883
+ def load_mols_from_path(path):
884
+ """Load molecules from a ChemDraw or SDF file."""
885
+ if path.endswith('.cdxml'):
886
+ try:
887
+ mols = MolsFromCDXMLFile(path, sanitize=False, removeHs=False)
888
+ total_count = len(mols)
889
+ valid_mols = []
890
+
891
+ for mol in mols:
892
+ if mol is not None:
893
+ fragments = GetMolFrags(mol, asMols=True, sanitizeFrags=False)
894
+ valid_mols.extend(fragments)
895
+
896
+ valid_count = len(valid_mols)
897
+
898
+ if valid_count == 0:
899
+ QMessageBox.warning(self, "CDXML Warning", f"No valid molecules found in the file:\n{path}")
900
+ return []
901
+
902
+ elif valid_count < total_count:
903
+ failed_count = total_count - valid_count
904
+ QMessageBox.warning(
905
+ self,
906
+ "CDXML Partial Load",
907
+ f"File loaded with partial success.\n{failed_count} out of {total_count} molecules failed sanitization and were skipped."
908
+ )
909
+
910
+ return valid_mols
911
+
912
+ except Exception as e:
913
+ QMessageBox.critical(self, "CDXML Read Error", f"Failed to read {path}:\n{str(e)}")
914
+ return []
915
+
916
+ elif path.endswith('.sdf'):
917
+ return [mol for mol in Chem.SDMolSupplier(path) if mol is not None]
918
+
919
+ elif path.endswith(".cdx"):
920
+ QMessageBox.warning(
921
+ self,
922
+ " Unsupported File Format",
923
+ (
924
+ "<b>CDX format is not supported! No issue — it only requires exporting to CDXML format.</b><br><br>"
925
+ "<b>How to convert your file:</b><br>"
926
+ "1. Open your CDX file in ChemDraw.<br>"
927
+ "2. Go to <b>File → Save As</b> or <b>Export</b>.<br>"
928
+ "3. Choose <b>CDXML (*.cdxml)</b> as the format.<br><br>"
929
+ "<b>If this method does not work, you can manually convert individual molecules:</b><br>"
930
+ "1. Open the CDX file in ChemDraw.<br>"
931
+ "2. Select a molecule.<br>"
932
+ "3. Press <b>Ctrl+C</b> (or <b>Cmd+C</b> on Mac).<br>"
933
+ "4. Paste it into a new ChemDraw document.<br>"
934
+ "5. Save it as <b>CDXML</b>.<br><br>"
935
+ "This ensures proper structure recognition and full compatibility with easyROB."
936
+ )
937
+ )
938
+ return None
939
+
940
+ else:
941
+ mol = Chem.MolFromMolFile(path)
942
+ return [mol] if mol else []
943
+
944
+ mols_main = load_mols_from_path(main_path)
945
+
946
+ # If the function returned None, it means we already handled a special case (like .cdx)
947
+ if mols_main is None:
948
+ return
949
+
950
+ # If the function returned an empty list, it means there were no valid molecules
951
+ if not mols_main:
952
+ QMessageBox.warning(self, "Error", "No valid molecules found in the file.")
953
+ return
954
+
955
+ if molecule_handler is not None:
956
+ molecule_handler(mols_main)
957
+ else:
958
+ self.show_molecule_table_dialog(mols_main)
959
+
960
+ def show_molecule_table_dialog(self, mols):
961
+ """
962
+ Create and display a dialog showing a table of molecules,
963
+ with the ability to add/remove columns, edit 'target' column name,
964
+ and save the table as CSV. Includes various field validations.
965
+ """
966
+ # --- Dialog Setup ---
967
+ dialog = QDialog(self)
968
+ dialog.setWindowTitle("ChemDraw Molecules")
969
+ dialog.setWindowFlags(dialog.windowFlags() | Qt.WindowMaximizeButtonHint)
970
+ dialog.setSizeGripEnabled(True)
971
+ dialog.resize(800, 600)
972
+
973
+ layout = QVBoxLayout(dialog)
974
+
975
+ # --- Table Columns ---
976
+ base_headers = ["Image", "SMILES", "code_name", "target"]
977
+ extra_columns = ["charge", "mult", "complex_type", "sample", "geom"]
978
+ complex_type_options = ["", "squareplanar", "squarepyramidal", "linear", "trigonalplanar"]
979
+
980
+ # Table widget setup
981
+ table = QTableWidget(len(mols), len(base_headers))
982
+ table.setHorizontalHeaderLabels(base_headers)
983
+
984
+ # Save indexes of required columns
985
+ self.smiles_col_index = base_headers.index("SMILES")
986
+ self.code_name_col_index = base_headers.index("code_name")
987
+ self.target_col_index = base_headers.index("target")
988
+
989
+ # --- Header Double Click Handler (for renaming 'target') ---
990
+ def on_header_double_clicked(index):
991
+ """
992
+ Allow renaming ONLY for the 'target' column when double-clicked.
993
+ """
994
+ target_index = self.target_col_index
995
+ if index != target_index:
996
+ return # Only allow renaming for the 'target' column
997
+ current_text = table.horizontalHeaderItem(index).text()
998
+ new_text, ok = QInputDialog.getText(
999
+ dialog, "Edit Column Name",
1000
+ f"Rename column '{current_text}':", text=current_text
1001
+ )
1002
+ if ok and new_text.strip():
1003
+ table.setHorizontalHeaderItem(index, QTableWidgetItem(new_text.strip()))
1004
+
1005
+ # Connect header double click signal
1006
+ table.horizontalHeader().sectionDoubleClicked.connect(on_header_double_clicked)
1007
+
1008
+ # --- Populate Table with Molecule Data ---
1009
+ for row, mol in enumerate(mols):
1010
+ # Create image for molecule and put in cell (column 0)
1011
+ img = Draw.MolToImage(mol, size=(100, 100))
1012
+ buffer = BytesIO()
1013
+ img.save(buffer, format="PNG")
1014
+ qimg = QImage.fromData(buffer.getvalue())
1015
+ label = QLabel()
1016
+ label.setPixmap(QPixmap.fromImage(qimg).scaled(100, 100, Qt.KeepAspectRatio, Qt.SmoothTransformation))
1017
+
1018
+ widget = QWidget()
1019
+ hbox = QHBoxLayout()
1020
+ hbox.addWidget(label)
1021
+ hbox.setAlignment(Qt.AlignmentFlag.AlignCenter)
1022
+ widget.setLayout(hbox)
1023
+ table.setRowHeight(row, 110)
1024
+ table.setCellWidget(row, 0, widget)
1025
+
1026
+ # Set SMILES (column 1)
1027
+ smi = Chem.MolToSmiles(mol, canonical=False)
1028
+ table.setItem(row, 1, QTableWidgetItem(smi))
1029
+ # code_name (column 2), target (column 3) initialized empty
1030
+ table.setItem(row, 2, QTableWidgetItem(""))
1031
+ table.setItem(row, 3, QTableWidgetItem(""))
1032
+
1033
+ # --- Set Default Table Column Widths ---
1034
+ default_width = 150
1035
+ for col in range(table.columnCount()):
1036
+ table.setColumnWidth(col, default_width)
1037
+ layout.addWidget(table)
1038
+
1039
+ # --- Checkbox Controls for Optional Columns ---
1040
+ checkbox_layout = QHBoxLayout()
1041
+ checkboxes = {}
1042
+
1043
+ def toggle_column(col_name, state):
1044
+ """
1045
+ Add or remove an extra column based on the corresponding checkbox.
1046
+ Handles special widget for 'complex_type' column.
1047
+ """
1048
+ def set_all_column_widths(width):
1049
+ for col in range(table.columnCount()):
1050
+ table.setColumnWidth(col, width)
1051
+
1052
+ current_headers = [table.horizontalHeaderItem(i).text() for i in range(table.columnCount())]
1053
+ if state: # Checkbox checked: add column if not present
1054
+ if col_name not in current_headers:
1055
+ idx = table.columnCount()
1056
+ table.insertColumn(idx)
1057
+ header_item = QTableWidgetItem(col_name)
1058
+ header_item.setFlags(header_item.flags() & ~Qt.ItemIsEditable)
1059
+ table.setHorizontalHeaderItem(idx, header_item)
1060
+ for row in range(table.rowCount()):
1061
+ if col_name == "complex_type":
1062
+ combo = QComboBox()
1063
+ combo.addItems(complex_type_options)
1064
+ combo.setCurrentIndex(0)
1065
+ table.setCellWidget(row, idx, combo)
1066
+ else:
1067
+ table.setItem(row, idx, QTableWidgetItem(""))
1068
+ else: # Checkbox unchecked: remove column if present
1069
+ if col_name in current_headers:
1070
+ idx = current_headers.index(col_name)
1071
+ table.removeColumn(idx)
1072
+ set_all_column_widths(default_width)
1073
+
1074
+ # Create checkboxes for each optional column
1075
+ for col_name in extra_columns:
1076
+ cb = QCheckBox(col_name)
1077
+ cb.stateChanged.connect(partial(toggle_column, col_name))
1078
+ checkbox_layout.addWidget(cb)
1079
+ checkboxes[col_name] = cb
1080
+
1081
+ layout.addLayout(checkbox_layout)
1082
+
1083
+ # --- Save as CSV Button ---
1084
+ save_button = QPushButton("💾 Save as CSV")
1085
+ save_button.setStyleSheet("padding: 6px; font-weight: bold;")
1086
+ layout.addWidget(save_button, alignment=Qt.AlignmentFlag.AlignRight)
1087
+
1088
+ def save_to_csv():
1089
+ """
1090
+ Collect all table data and save to a CSV file.
1091
+ Includes validation for required fields, uniqueness, types, and empty checks.
1092
+ """
1093
+ headers = [table.horizontalHeaderItem(i).text() for i in range(table.columnCount())]
1094
+
1095
+ # --- Mandatory column presence check ---
1096
+ try:
1097
+ smiles_idx = headers.index("SMILES")
1098
+ code_name_idx = headers.index("code_name")
1099
+ except ValueError as e:
1100
+ QMessageBox.warning(dialog, "WARNING!", f"Column missing: {str(e)}")
1101
+ return
1102
+
1103
+ # --- Data validation ---
1104
+ code_names = []
1105
+ for row in range(table.rowCount()):
1106
+ # Check 'SMILES' not empty
1107
+ item = table.item(row, smiles_idx)
1108
+ if not item or not item.text().strip():
1109
+ QMessageBox.warning(dialog, "WARNING!", f"Please fill in all 'SMILES' fields before saving.")
1110
+ return
1111
+
1112
+ # Check 'code_name' not empty
1113
+ item = table.item(row, code_name_idx)
1114
+ if not item or not item.text().strip():
1115
+ QMessageBox.warning(dialog, "WARNING!", f"Please fill in all 'code_name' fields before saving.")
1116
+ return
1117
+
1118
+ code_names.append(table.item(row, code_name_idx).text().strip())
1119
+
1120
+ # Validate 'charge' column if present (must be int, not empty)
1121
+ if "charge" in headers:
1122
+ charge_idx = headers.index("charge")
1123
+ item = table.item(row, charge_idx)
1124
+ val = item.text().strip() if item else ""
1125
+ if val == "":
1126
+ QMessageBox.warning(dialog, "WARNING!", f"Column 'charge' cannot be empty.")
1127
+ return
1128
+ if not (val.lstrip('-').isdigit() and '.' not in val):
1129
+ QMessageBox.warning(dialog, "WARNING!", f"Column 'charge' must be an integer.")
1130
+ return
1131
+
1132
+ # Validate 'mult' column if present (must be int, not empty)
1133
+ if "mult" in headers:
1134
+ mult_idx = headers.index("mult")
1135
+ item = table.item(row, mult_idx)
1136
+ val = item.text().strip() if item else ""
1137
+ if val == "":
1138
+ QMessageBox.warning(dialog, "WARNING!", f"Column 'mult' cannot be empty.")
1139
+ return
1140
+ if not (val.lstrip('-').isdigit() and '.' not in val):
1141
+ QMessageBox.warning(dialog, "WARNING!", f"Column 'mult' must be an integer.")
1142
+ return
1143
+
1144
+ # Validate 'complex_type' if present (must be selected)
1145
+ if "complex_type" in headers:
1146
+ complex_type_idx = headers.index("complex_type")
1147
+ combo = table.cellWidget(row, complex_type_idx)
1148
+ if combo is not None and combo.currentText().strip() == "":
1149
+ QMessageBox.warning(
1150
+ dialog, "WARNING!",
1151
+ f"Column 'complex_type' cannot be empty. Please select a value."
1152
+ )
1153
+ return
1154
+
1155
+ # Validate 'sample' column if present (must be int, not empty)
1156
+ if "sample" in headers:
1157
+ sample_idx = headers.index("sample")
1158
+ for row in range(table.rowCount()):
1159
+ item = table.item(row, sample_idx)
1160
+ val = item.text().strip() if item else ""
1161
+ if val == "":
1162
+ QMessageBox.warning(dialog, "WARNING!", f"Column 'sample' cannot be empty.")
1163
+ return
1164
+ if not (val.lstrip('-').isdigit() and '.' not in val):
1165
+ QMessageBox.warning(dialog, "WARNING!", f"Column 'sample' must be an integer.")
1166
+ return
1167
+
1168
+ # Validate 'GEOM' column if present (must not be empty)
1169
+ if "geom" in headers:
1170
+ geom_idx = headers.index("geom")
1171
+ for row in range(table.rowCount()):
1172
+ item = table.item(row, geom_idx)
1173
+ val = item.text().strip() if item else ""
1174
+ if val == "":
1175
+ QMessageBox.warning(dialog, "WARNING!", f"Column 'geom' cannot be empty.")
1176
+ return
1177
+
1178
+
1179
+ # --- Uniqueness check for 'code_name' ---
1180
+ duplicates = [name for name in set(code_names) if code_names.count(name) > 1]
1181
+ if duplicates:
1182
+ QMessageBox.warning(
1183
+ dialog, "WARNING!",
1184
+ f"The following 'code_name' values are duplicated:\n\n{', '.join(duplicates)}\n\nPlease make them unique before saving."
1185
+ )
1186
+ return
1187
+
1188
+ # --- Numeric check for 'target' column ---
1189
+ for row in range(table.rowCount()):
1190
+ item = table.item(row, self.target_col_index)
1191
+ val = item.text().strip() if item else ""
1192
+ if not val:
1193
+ QMessageBox.warning(dialog, "WARNING!", f"Target column is empty.")
1194
+ return
1195
+ try:
1196
+ float(val)
1197
+ except ValueError:
1198
+ QMessageBox.warning(dialog, "WARNING!", f"Target column must be numeric.")
1199
+ return
1200
+
1201
+ # --- File dialog to select save path ---
1202
+ path, _ = QFileDialog.getSaveFileName(dialog, "Save CSV", "", "CSV Files (*.csv)")
1203
+ if not path:
1204
+ return
1205
+
1206
+ # --- Prepare headers and write CSV ---
1207
+ save_headers = [h for h in headers if h != "Image"]
1208
+ with open(path, "w", newline="", encoding="utf-8") as f:
1209
+ writer = csv.writer(f)
1210
+ writer.writerow(save_headers)
1211
+ for row in range(table.rowCount()):
1212
+ row_values = []
1213
+ for col in range(table.columnCount()):
1214
+ header = headers[col]
1215
+ if header == "Image":
1216
+ continue
1217
+ if header == "complex_type":
1218
+ combo = table.cellWidget(row, col)
1219
+ row_values.append(combo.currentText() if combo else "")
1220
+ else:
1221
+ item = table.item(row, col)
1222
+ row_values.append(item.text() if item else "")
1223
+ writer.writerow(row_values)
1224
+
1225
+ # --- Optional: Update main window file path and show message ---
1226
+ if hasattr(self, "main_window") and self.main_window:
1227
+ self.main_window.set_file_path(path)
1228
+ dialog.accept()
1229
+ QMessageBox.information(dialog, "Success", "CSV file saved and loaded successfully!")
1230
+
1231
+ save_button.clicked.connect(save_to_csv)
1232
+
1233
+ dialog.setLayout(layout)
1234
+ dialog.exec()