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,555 @@
1
+ """Interactive prediction diagnostics for the Results view."""
2
+
3
+ from io import BytesIO
4
+ from pathlib import Path
5
+ import re
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ import seaborn as sns
10
+ from matplotlib.image import imread
11
+ from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
12
+ from matplotlib.figure import Figure
13
+ from matplotlib.patches import Rectangle
14
+ from PySide6.QtCore import Qt
15
+ from PySide6.QtGui import QPixmap
16
+ from PySide6.QtWidgets import (
17
+ QComboBox, QHBoxLayout, QLabel, QPushButton, QStackedWidget, QVBoxLayout, QWidget,
18
+ )
19
+ from rdkit import Chem
20
+ from rdkit.Chem import Draw
21
+
22
+
23
+ def discover_prediction_csvs(run_dir):
24
+ """Find model outputs and optional external prediction outputs."""
25
+ predict_dir = Path(run_dir) / "PREDICT"
26
+ paths = list(predict_dir.glob("*.csv"))
27
+ paths.extend((predict_dir / "csv_test").glob("*.csv"))
28
+ return sorted(
29
+ (path for path in paths
30
+ if re.search(r"_(?:No_PFI|PFI)\.csv$", path.name)
31
+ and not path.name.startswith("Results_boundary_williams_")),
32
+ key=lambda path: (path.parent.name == "csv_test", path.name),
33
+ )
34
+
35
+
36
+ def _identifier_column(frame, sources):
37
+ reserved = {"Set", "SMILES"}
38
+ for source in sources:
39
+ for column in frame.columns:
40
+ if (column in source.columns and column not in reserved
41
+ and not column.endswith(("_pred", "_pred_sd"))
42
+ and column.lower() not in {"smiles", "target"}
43
+ and source[column].is_unique):
44
+ if column.lower() in {"code_name", "name", "id", "identifier"}:
45
+ return column
46
+ return None
47
+
48
+
49
+ def _molecule_smiles(frame, sources, name_column=None):
50
+ smiles_column = next((col for col in frame if col.lower() == "smiles"), None)
51
+ if smiles_column:
52
+ return [str(value) if pd.notna(value) and str(value).strip() else None
53
+ for value in frame[smiles_column]]
54
+
55
+ identifier = next(
56
+ (column for column in frame if name_column and column.casefold() == name_column.casefold()),
57
+ None,
58
+ ) or _identifier_column(frame, sources)
59
+ if not identifier:
60
+ return [None] * len(frame)
61
+ result = [None] * len(frame)
62
+ for source in sources:
63
+ smiles_column = next((col for col in source if col.lower() == "smiles"), None)
64
+ source_identifier = next(
65
+ (column for column in source if column.casefold() == identifier.casefold()), None,
66
+ )
67
+ if not smiles_column or source_identifier is None or not source[source_identifier].is_unique:
68
+ continue
69
+ lookup = dict(zip(source[source_identifier].astype(str), source[smiles_column]))
70
+ for index, value in enumerate(frame[identifier].astype(str)):
71
+ candidate = lookup.get(value)
72
+ if result[index] is None and pd.notna(candidate) and str(candidate).strip():
73
+ result[index] = str(candidate)
74
+ return result
75
+
76
+
77
+ def prepare_prediction_data(frame, sources, reference=None, name_column=None):
78
+ """Extract plot coordinates, using CV data as the diagnostic reference."""
79
+ frame = frame.reset_index(drop=True)
80
+ prediction_columns = [col for col in frame if col.endswith("_pred")]
81
+ if not prediction_columns:
82
+ raise ValueError("Prediction CSV has no predicted target column")
83
+ target = prediction_columns[0][:-5]
84
+ observed = pd.to_numeric(frame[target], errors="coerce") if target in frame else pd.Series(np.nan, index=frame.index)
85
+ predicted = pd.to_numeric(frame[prediction_columns[0]], errors="coerce")
86
+ residual = predicted - observed
87
+ reference = frame if reference is None else reference
88
+ reference_observed = pd.to_numeric(reference[target], errors="coerce") if target in reference else pd.Series(np.nan, index=reference.index)
89
+ reference_predicted = pd.to_numeric(reference[prediction_columns[0]], errors="coerce")
90
+ if "Set" in reference:
91
+ cv_mask = reference["Set"].astype(str).str.casefold() == "cv"
92
+ cv_errors = (reference_predicted[cv_mask] - reference_observed[cv_mask]).abs().dropna()
93
+ else:
94
+ cv_errors = (reference_predicted - reference_observed).abs().dropna()
95
+ error_mean = float(cv_errors.mean()) if len(cv_errors) else 0.0
96
+ error_sd = float(cv_errors.std(ddof=0)) if len(cv_errors) else 0.0
97
+ if not np.isfinite(error_sd) or error_sd == 0:
98
+ error_sd = 1.0
99
+ outlier_score = ((predicted - observed).abs() - error_mean) / error_sd
100
+
101
+ return {
102
+ "frame": frame, "target": target, "observed": observed.to_numpy(dtype=float),
103
+ "predicted": predicted.to_numpy(dtype=float), "residual": residual.to_numpy(dtype=float),
104
+ "outlier_score": outlier_score.to_numpy(dtype=float),
105
+ "name_column": name_column,
106
+ "smiles": _molecule_smiles(frame, sources, name_column),
107
+ }
108
+
109
+
110
+ def _prediction_log(run_dir, model=None):
111
+ """Find the log for a selected all-model run or a standard PREDICT run."""
112
+ predict_dir = Path(run_dir) / "PREDICT"
113
+ model_log = predict_dir / f"PREDICT_{model}_data.dat" if model else None
114
+ return model_log if model_log is not None and model_log.is_file() else predict_dir / "PREDICT_data.dat"
115
+
116
+
117
+ def _source_frames(run_dir, selected_file, external=False, model=None):
118
+ """Prefer the selected input; use the external input named in PREDICT_data.dat."""
119
+ candidates = [Path(selected_file)]
120
+ log_path = _prediction_log(run_dir, model)
121
+ if log_path.exists():
122
+ command = log_path.read_text(encoding="utf-8", errors="replace")
123
+ match = re.search(r'--csv_test\s+(?:"([^"]+)"|\'([^\']+)\'|(\S+))', command)
124
+ if match:
125
+ candidates.append(Path(run_dir) / next(group for group in match.groups() if group))
126
+ if external:
127
+ candidates.reverse()
128
+ sources = []
129
+ for path in candidates:
130
+ if path.is_file() and path.suffix.lower() == ".csv":
131
+ try:
132
+ source = pd.read_csv(path)
133
+ if any(column.lower() == "smiles" for column in source):
134
+ sources.append(source)
135
+ except (OSError, pd.errors.ParserError, UnicodeError):
136
+ continue
137
+ return sources
138
+
139
+
140
+ class InteractivePredictions(QWidget):
141
+ """Linked prediction diagnostics with a molecular structure panel."""
142
+
143
+ PLOTS = ("Observed vs predicted", "Outlier analysis", "Williams plot")
144
+
145
+ def __init__(self, parent=None):
146
+ super().__init__(parent)
147
+ self.paths = []
148
+ self.data = None
149
+ self.williams_data = None
150
+ self.williams_image = None
151
+ self.williams_smiles = []
152
+ self._artists = {}
153
+ self._legend_artists = {}
154
+ self.seed = 0
155
+ self.cv_label = "CV"
156
+ self.outlier_threshold = 2.0
157
+ layout = QVBoxLayout(self)
158
+ subtitle = QLabel(
159
+ "Hover over a point to inspect it. Click a legend entry to show or hide its points."
160
+ )
161
+ layout.addWidget(subtitle)
162
+ self.selector = QComboBox()
163
+ self.selector.currentIndexChanged.connect(self._load_selected)
164
+ layout.addWidget(self.selector)
165
+ content = QHBoxLayout()
166
+ chart_column = QVBoxLayout()
167
+ plot_selector = QHBoxLayout()
168
+ self.charts = QStackedWidget()
169
+ self.canvases = []
170
+ self.plot_buttons = []
171
+ for index, title in enumerate(self.PLOTS):
172
+ button = QPushButton(title)
173
+ button.setCheckable(True)
174
+ button.clicked.connect(lambda checked=False, plot=index: self._select_plot(plot))
175
+ plot_selector.addWidget(button)
176
+ self.plot_buttons.append(button)
177
+ canvas = FigureCanvasQTAgg(Figure(figsize=(7, 5), constrained_layout=True))
178
+ canvas.mpl_connect("motion_notify_event", lambda event, chart=canvas: self._hover(event, chart))
179
+ canvas.mpl_connect("button_press_event", lambda event, chart=canvas: self._hover(event, chart))
180
+ canvas.mpl_connect("pick_event", self._on_legend_pick)
181
+ self.charts.addWidget(canvas)
182
+ self.canvases.append(canvas)
183
+ plot_selector.addStretch()
184
+ chart_column.addLayout(plot_selector)
185
+ chart_column.addWidget(self.charts, 1)
186
+ content.addLayout(chart_column, 3)
187
+ self._select_plot(0)
188
+ detail = QVBoxLayout()
189
+ detail.addWidget(QLabel("Datapoint under cursor"))
190
+ self.structure = QLabel("Hover over a datapoint")
191
+ self.structure.setAlignment(Qt.AlignCenter)
192
+ self.structure.setFixedSize(260, 260)
193
+ self.structure.setStyleSheet("background: white; color: #555; border: 1px solid #bbb;")
194
+ detail.addWidget(self.structure)
195
+ self.details = QLabel("")
196
+ self.details.setWordWrap(True)
197
+ detail.addWidget(self.details)
198
+ detail.addStretch()
199
+ content.addLayout(detail, 1)
200
+ layout.addLayout(content, 1)
201
+
202
+ def _select_plot(self, index):
203
+ """Switch plot views without adding another level of tabs."""
204
+ self.charts.setCurrentIndex(index)
205
+ for position, button in enumerate(self.plot_buttons):
206
+ button.setChecked(position == index)
207
+
208
+ def refresh(self, run_dir, selected_file, paths=None, catalog=None):
209
+ self.run_dir = Path(run_dir)
210
+ self.selected_file = selected_file
211
+ self.catalog = catalog
212
+ self.paths = list(paths) if paths is not None else discover_prediction_csvs(run_dir)
213
+ log_path = _prediction_log(run_dir)
214
+ self.outlier_threshold = 2.0
215
+ if log_path.is_file():
216
+ command = log_path.read_text(encoding="utf-8", errors="replace")
217
+ match = re.search(r"--t_value(?:\s+|=)([0-9.]+)", command)
218
+ if match:
219
+ self.outlier_threshold = float(match.group(1))
220
+ self.selector.blockSignals(True)
221
+ self.selector.clear()
222
+ for path in self.paths:
223
+ group = "External" if path.parent.name == "csv_test" else "PREDICT"
224
+ self.selector.addItem(f"{group} / {path.stem}")
225
+ self.selector.blockSignals(False)
226
+ if self.paths:
227
+ self._load_selected(0)
228
+ else:
229
+ self.data = None
230
+ self.williams_data = None
231
+ self.williams_image = None
232
+ self._artists.clear()
233
+ self._legend_artists.clear()
234
+ self.structure.setPixmap(QPixmap())
235
+ self.structure.setText("No prediction data available")
236
+ self.details.clear()
237
+ for canvas in self.canvases:
238
+ canvas.figure.clear()
239
+ canvas.draw_idle()
240
+
241
+ def _load_selected(self, index):
242
+ if index < 0 or index >= len(self.paths):
243
+ return
244
+ path = self.paths[index]
245
+ try:
246
+ frame = pd.read_csv(path)
247
+ external = path.parent.name == "csv_test"
248
+ reference = None
249
+ if external:
250
+ candidates = [candidate for candidate in self.paths
251
+ if candidate.parent.name == "PREDICT"
252
+ and path.stem.endswith(candidate.stem)]
253
+ if candidates:
254
+ reference = pd.read_csv(max(candidates, key=lambda item: len(item.stem)))
255
+ model_path = max(candidates, key=lambda item: len(item.stem)) if external and candidates else path
256
+ suffix = "No_PFI" if model_path.stem.endswith("_No_PFI") else "PFI"
257
+ model = model_path.stem.removesuffix(f"_{suffix}")
258
+ model_log = _prediction_log(self.run_dir, model)
259
+ if model_log.is_file():
260
+ command = model_log.read_text(encoding="utf-8", errors="replace")
261
+ match = re.search(r"--t_value(?:\s+|=)([0-9.]+)", command)
262
+ if match:
263
+ self.outlier_threshold = float(match.group(1))
264
+ metadata_name = model if suffix == "No_PFI" else f"{model}_PFI"
265
+ metadata = self.run_dir / "GENERATE" / "Best_model" / suffix / f"{metadata_name}.csv"
266
+ if not metadata.is_file():
267
+ metadata = (
268
+ self.run_dir / "GENERATE" / "All_models" / suffix
269
+ / model / f"{metadata_name}.csv"
270
+ )
271
+ if metadata.is_file():
272
+ model_info = pd.read_csv(metadata).iloc[0]
273
+ self.seed = int(model_info["seed"])
274
+ self.cv_label = f"{int(model_info['repeat_kfolds'])}x {int(model_info['kfold'])}-fold CV"
275
+ name_column = ""
276
+ if "names" in model_info and pd.notna(model_info["names"]):
277
+ name_column = str(model_info["names"]).strip()
278
+ else:
279
+ self.seed = 0
280
+ self.cv_label = "CV"
281
+ name_column = ""
282
+ if not name_column and model_log.is_file():
283
+ match = re.search(
284
+ r"""(?<!\S)--names(?:\s+|=)(?:"([^"]+)"|'([^']+)'|(\S+))""",
285
+ command,
286
+ )
287
+ if match:
288
+ name_column = next(value for value in match.groups() if value is not None)
289
+ self.data = prepare_prediction_data(
290
+ frame,
291
+ _source_frames(self.run_dir, self.selected_file, external, model),
292
+ reference,
293
+ name_column=name_column,
294
+ )
295
+ self._load_williams(model_path)
296
+ except (OSError, ValueError, KeyError, pd.errors.ParserError) as error:
297
+ self.details.setText(f"Unable to load prediction data: {error}")
298
+ return
299
+ self.structure.setPixmap(QPixmap())
300
+ self.structure.setText("Hover over a datapoint")
301
+ self.details.setText("")
302
+ self._draw_charts()
303
+
304
+ def _load_williams(self, model_path):
305
+ """Read the exact coordinates saved with the selected model's Williams PNG."""
306
+ stem = f"Results_boundary_williams_{model_path.stem}"
307
+ sidecar = self.run_dir / "PREDICT" / f"{stem}.csv"
308
+ image = self.run_dir / "PREDICT" / f"{stem}.png"
309
+ self.williams_data = None
310
+ self.williams_image = image if image.is_file() else None
311
+ self.williams_smiles = []
312
+ if not sidecar.is_file():
313
+ return
314
+ table = pd.read_csv(sidecar, dtype={"point_id": str})
315
+ required = {"point_id", "name_column", "group", "leverage",
316
+ "standardized_residual", "h_star", "observed", "predicted"}
317
+ if not required.issubset(table.columns):
318
+ raise ValueError(f"Williams data is missing columns: {', '.join(sorted(required - set(table.columns)))}")
319
+ self.williams_data = table.reset_index(drop=True)
320
+ name_column = str(table["name_column"].iloc[0]) if len(table) else ""
321
+ point_ids = table["point_id"].astype(str)
322
+ smiles = [None] * len(table)
323
+ for source in _source_frames(self.run_dir, self.selected_file):
324
+ if name_column not in source or not source[name_column].is_unique:
325
+ continue
326
+ smiles_column = next((column for column in source if column.lower() == "smiles"), None)
327
+ if smiles_column is None:
328
+ continue
329
+ lookup = dict(zip(source[name_column].astype(str), source[smiles_column]))
330
+ for index, point_id in enumerate(point_ids):
331
+ candidate = lookup.get(point_id)
332
+ if smiles[index] is None and pd.notna(candidate) and str(candidate).strip():
333
+ smiles[index] = str(candidate)
334
+ self.williams_smiles = smiles
335
+
336
+ def _draw_charts(self):
337
+ data = self.data
338
+ self._artists.clear()
339
+ self._legend_artists.clear()
340
+ for plot_index, canvas in enumerate(self.canvases):
341
+ figure = canvas.figure
342
+ figure.clear()
343
+ axis = figure.add_subplot(111)
344
+ axis.grid(linestyle="--", linewidth=0.8, alpha=0.5)
345
+ axis.set_axisbelow(True)
346
+ legend_targets = {}
347
+ if plot_index == 2:
348
+ self._draw_williams(axis, legend_targets)
349
+ self._add_clickable_legend(axis, canvas, legend_targets)
350
+ canvas.draw_idle()
351
+ continue
352
+ if plot_index == 0:
353
+ x, y = data["observed"], data["predicted"]
354
+ axis.set(xlabel=data["target"], ylabel=f"Predicted {data['target']}",
355
+ title=f"Predictions CV and test set of {self.paths[self.selector.currentIndex()].stem}")
356
+ valid = np.isfinite(x) & np.isfinite(y)
357
+ if valid.any():
358
+ external = self.paths[self.selector.currentIndex()].parent.name == "csv_test"
359
+ cv_mask = data["frame"]["Set"].eq("CV").to_numpy() if "Set" in data["frame"] else valid
360
+ fit_mask = valid if external else valid & cv_mask
361
+ if fit_mask.sum() >= 10:
362
+ sns.regplot(x=x[fit_mask], y=y[fit_mask], scatter=False,
363
+ color=".1", truncate=True, seed=self.seed, ax=axis)
364
+ padding = 0.1 * np.ptp(x[valid])
365
+ lower = min(np.min(x[valid]), np.min(y[valid])) - padding
366
+ upper = max(np.max(x[valid]), np.max(y[valid])) + padding
367
+ axis.set_xlim(lower, upper)
368
+ axis.set_ylim(lower, upper)
369
+ elif plot_index == 1:
370
+ x = y = data["outlier_score"]
371
+ axis.set(xlabel="SD of the errors", ylabel="SD of the errors",
372
+ title=f"Outlier analysis of {self.paths[self.selector.currentIndex()].stem}")
373
+ valid = np.isfinite(x)
374
+ limit = max(2.5, float(np.max(np.abs(x[valid])) + 0.5)) if valid.any() else 2.5
375
+ threshold = self.outlier_threshold
376
+ if limit > threshold:
377
+ width = limit - threshold
378
+ axis.add_patch(Rectangle((threshold, threshold), width, width,
379
+ facecolor="grey", alpha=0.3))
380
+ axis.add_patch(Rectangle((-limit, -limit), width, width,
381
+ facecolor="grey", alpha=0.3))
382
+ axis.set_xlim(-limit, limit)
383
+ axis.set_ylim(-limit, limit)
384
+ sets = data["frame"]["Set"].fillna("Data").astype(str) if "Set" in data["frame"] else pd.Series(["External" if self.paths[self.selector.currentIndex()].parent.name == "csv_test" else "Data"] * len(x))
385
+ for label, color in (("CV", "b"), ("Test", "r"), ("External", "r"), ("Data", "b")):
386
+ indices = np.flatnonzero((sets.to_numpy() == label) & np.isfinite(x) & np.isfinite(y))
387
+ if len(indices):
388
+ legend_label = self.cv_label if label == "CV" else label.lower()
389
+ artist = axis.scatter(x[indices], y[indices], label=legend_label, color=color,
390
+ edgecolors="black", linewidths=0.8, s=50, picker=6, zorder=2)
391
+ self._artists[artist] = indices
392
+ related = []
393
+ if plot_index == 0 and external:
394
+ sd_column = f"{data['target']}_pred_sd"
395
+ if sd_column in data["frame"]:
396
+ errors = pd.to_numeric(
397
+ data["frame"][sd_column], errors="coerce"
398
+ ).to_numpy(dtype=float)
399
+ error_indices = indices[np.isfinite(errors[indices])]
400
+ if len(error_indices):
401
+ bars = axis.errorbar(
402
+ x[error_indices], y[error_indices], yerr=errors[error_indices],
403
+ fmt="none", ecolor="gray", capsize=3, zorder=1,
404
+ )
405
+ related.extend(bars.get_children())
406
+ legend_targets[artist] = (artist, related)
407
+ if not (np.isfinite(x) & np.isfinite(y)).any():
408
+ axis.text(0.5, 0.5, "Observed values are unavailable for this plot",
409
+ ha="center", va="center", transform=axis.transAxes)
410
+ self._add_clickable_legend(axis, canvas, legend_targets)
411
+ canvas.draw_idle()
412
+
413
+ def _draw_williams(self, axis, legend_targets):
414
+ table = self.williams_data
415
+ if table is None:
416
+ axis.set_title("Williams plot: interactive data unavailable")
417
+ axis.set_axis_off()
418
+ if self.williams_image is not None:
419
+ try:
420
+ axis.imshow(imread(self.williams_image))
421
+ except (OSError, ValueError):
422
+ axis.text(0.5, 0.5, "Williams image could not be read",
423
+ ha="center", va="center", transform=axis.transAxes)
424
+ else:
425
+ axis.text(0.5, 0.5, "No Williams plot is available for this model",
426
+ ha="center", va="center", transform=axis.transAxes)
427
+ return
428
+
429
+ axis.set(xlabel="Leverage", ylabel="Standardized residual",
430
+ title=f"Applicability domain (Williams plot) of {self.paths[self.selector.currentIndex()].stem}")
431
+ leverage = pd.to_numeric(table["leverage"], errors="coerce").to_numpy(dtype=float)
432
+ residual = pd.to_numeric(table["standardized_residual"], errors="coerce").to_numpy(dtype=float)
433
+ threshold = pd.to_numeric(table["h_star"], errors="coerce").to_numpy(dtype=float)
434
+ h_star = threshold[0] if len(threshold) else np.nan
435
+ for group, color in (("Typical 80%", "b"), ("High leverage 20%", "r")):
436
+ indices = np.flatnonzero((table["group"].to_numpy() == group)
437
+ & np.isfinite(leverage) & np.isfinite(residual))
438
+ if len(indices):
439
+ artist = axis.scatter(leverage[indices], residual[indices], label=group,
440
+ color=color, edgecolors="black", linewidths=0.8,
441
+ s=50, picker=6, zorder=2)
442
+ self._artists[artist] = indices
443
+ legend_targets[artist] = (artist, [])
444
+ for bound in (-3, 3):
445
+ axis.axhline(bound, color="dimgray", linestyle="--", linewidth=1)
446
+ if np.isfinite(h_star):
447
+ axis.axvline(h_star, color="dimgray", linestyle="--", linewidth=1)
448
+ valid = np.isfinite(leverage) & np.isfinite(residual)
449
+ x_max = max(float(np.max(leverage[valid]) * 1.1) if valid.any() else 0, h_star * 1.2)
450
+ y_max = max(float(np.max(np.abs(residual[valid])) * 1.1) if valid.any() else 0, 3.5)
451
+ axis.set_xlim(0, x_max)
452
+ axis.set_ylim(-y_max, y_max)
453
+
454
+ def _add_clickable_legend(self, axis, canvas, targets):
455
+ """Make each legend entry toggle its associated plotted points."""
456
+ handles, _ = axis.get_legend_handles_labels()
457
+ if not handles:
458
+ return
459
+ legend = axis.legend(loc="best", fontsize=8)
460
+ for handle, proxy, text in zip(handles, legend.legend_handles, legend.get_texts()):
461
+ if handle not in targets:
462
+ continue
463
+ for item in (proxy, text):
464
+ item.set_picker(True)
465
+ self._legend_artists[item] = (*targets[handle], canvas)
466
+
467
+ def _on_legend_pick(self, event):
468
+ """Handle a click on a legend symbol or its text."""
469
+ self._toggle_legend_artist(event.artist)
470
+
471
+ def _toggle_legend_artist(self, legend_artist):
472
+ target = self._legend_artists.get(legend_artist)
473
+ if target is None:
474
+ return
475
+ points, related, canvas = target
476
+ visible = not points.get_visible()
477
+ points.set_visible(visible)
478
+ for artist in related:
479
+ artist.set_visible(visible)
480
+ for proxy, (mapped_points, _, _) in self._legend_artists.items():
481
+ if mapped_points is points:
482
+ proxy.set_alpha(1.0 if visible else 0.3)
483
+ canvas.draw_idle()
484
+
485
+ def _hover(self, event, canvas):
486
+ if event.inaxes is None or self.data is None:
487
+ return
488
+ for artist, indices in self._artists.items():
489
+ if artist.axes.figure is not canvas.figure:
490
+ continue
491
+ if not artist.get_visible():
492
+ continue
493
+ contains, info = artist.contains(event)
494
+ if contains and len(info.get("ind", [])):
495
+ index = int(indices[info["ind"][0]])
496
+ if canvas is self.canvases[2]:
497
+ self._show_williams_point(index)
498
+ else:
499
+ self._show_point(index)
500
+ return
501
+
502
+ def _show_williams_point(self, index):
503
+ row = self.williams_data.iloc[index]
504
+ self.details.setText("\n".join([
505
+ str(row["point_id"]), f"Group: {row['group']}",
506
+ f"Leverage: {row['leverage']:.4g}",
507
+ f"Standardized residual: {row['standardized_residual']:.4g}",
508
+ f"Observed: {row['observed']:.4g}", f"Predicted: {row['predicted']:.4g}",
509
+ ]))
510
+ smiles = self.williams_smiles[index]
511
+ molecule = Chem.MolFromSmiles(smiles) if smiles else None
512
+ if molecule is None:
513
+ self.structure.setPixmap(QPixmap())
514
+ self.structure.setText("Molecule unavailable")
515
+ return
516
+ buffer = BytesIO()
517
+ Draw.MolToImage(molecule, size=(320, 320)).save(buffer, format="PNG")
518
+ pixmap = QPixmap()
519
+ pixmap.loadFromData(buffer.getvalue())
520
+ self.structure.setPixmap(pixmap.scaled(240, 240, Qt.KeepAspectRatio, Qt.SmoothTransformation))
521
+
522
+ def _show_point(self, index):
523
+ data = self.data
524
+ row = data["frame"].iloc[index]
525
+ preferred = data.get("name_column")
526
+ identifier_column = next(
527
+ (column for column in row.index if preferred and column.casefold() == preferred.casefold()),
528
+ None,
529
+ )
530
+ identifier = row[identifier_column] if identifier_column else next(
531
+ (row[column] for column in ("code_name", "Name", "name", "ID") if column in row), None,
532
+ )
533
+ label = str(identifier) if pd.notna(identifier) and str(identifier).strip() else f"Row {index + 1}"
534
+ lines = [label]
535
+ if "Set" in row:
536
+ lines.append(f"Set: {row['Set']}")
537
+ if np.isfinite(data["observed"][index]):
538
+ lines.append(f"Observed: {data['observed'][index]:.4g}")
539
+ lines.append(f"Predicted: {data['predicted'][index]:.4g}")
540
+ for label, key in (("Residual", "residual"), ("Outlier score", "outlier_score")):
541
+ value = data[key][index]
542
+ if np.isfinite(value):
543
+ lines.append(f"{label}: {value:.3g}")
544
+ self.details.setText("\n".join(lines))
545
+ smiles = data["smiles"][index]
546
+ molecule = Chem.MolFromSmiles(smiles) if smiles else None
547
+ if molecule is None:
548
+ self.structure.setPixmap(QPixmap())
549
+ self.structure.setText("Molecule unavailable")
550
+ return
551
+ buffer = BytesIO()
552
+ Draw.MolToImage(molecule, size=(320, 320)).save(buffer, format="PNG")
553
+ pixmap = QPixmap()
554
+ pixmap.loadFromData(buffer.getvalue())
555
+ self.structure.setPixmap(pixmap.scaled(240, 240, Qt.KeepAspectRatio, Qt.SmoothTransformation))