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,985 @@
1
+ """
2
+ Prediction utilities and UI components for the easyROB Predictions tab.
3
+
4
+ This module provides all data-processing logic and supporting Qt components
5
+ required to visualize and evaluate ROBERT prediction results.
6
+
7
+ Responsibilities:
8
+ - Discover and load prediction CSV files from workflow outputs
9
+ - Extract relevant information from ROBERT PDF reports (scores, fragments)
10
+ - Evaluate model performance and generate diagnostic summaries
11
+ - Provide Qt models and widgets for interactive data visualization
12
+ - Render molecular structures (SMILES → images) using RDKit
13
+
14
+ Architecture:
15
+ - Combines pure utility functions (file discovery, parsing, evaluation)
16
+ with Qt-based components (table models, dashboard widgets, async tasks)
17
+ - Uses QRunnable and QThreadPool for asynchronous CSV loading
18
+ - Implements caching strategies to optimize table sorting and rendering
19
+
20
+ Notes:
21
+ - Designed as a bridge between backend data (CSV, PDF, chemistry) and UI
22
+ - Handles partial failures gracefully (e.g., missing PDFs or invalid data)
23
+ - Centralizes prediction-related logic to keep the main GUI clean
24
+
25
+ """
26
+
27
+ # ------------------------------------------------------------
28
+ # Standard library
29
+ # ------------------------------------------------------------
30
+ from io import BytesIO
31
+ from pathlib import Path
32
+ import re
33
+
34
+ from robert.checkml_score import checkml_score_color, checkml_score_tier, checkml_tier_color, round_checkml_score
35
+
36
+ # ------------------------------------------------------------
37
+ # Third-party libraries
38
+ # ------------------------------------------------------------
39
+ import numpy as np
40
+ import pandas as pd
41
+
42
+ import pymupdf as fitz
43
+ import pdfplumber
44
+
45
+ from rdkit import Chem
46
+ from rdkit.Chem import Draw
47
+
48
+ from PySide6.QtCore import (
49
+ QByteArray,
50
+ QAbstractTableModel,
51
+ QModelIndex,
52
+ QObject,
53
+ QRunnable,
54
+ QSortFilterProxyModel,
55
+ Qt,
56
+ Signal,
57
+ )
58
+ from PySide6.QtGui import (
59
+ QFontMetrics,
60
+ QIcon,
61
+ QImage,
62
+ QPixmap,
63
+ )
64
+ from PySide6.QtWidgets import (
65
+ QHeaderView,
66
+ QHBoxLayout,
67
+ QLabel,
68
+ QPushButton,
69
+ QScrollArea,
70
+ QSizePolicy,
71
+ QSplitter,
72
+ QStyle,
73
+ QStyleOptionHeader,
74
+ QVBoxLayout,
75
+ QWidget,
76
+ )
77
+
78
+ def get_predict_dir(selected_file_path: str) -> Path:
79
+ """Given the path to a selected file, return the corresponding PREDICT/csv_test directory."""
80
+ return Path(selected_file_path).parent / "PREDICT" / "csv_test"
81
+
82
+ def find_prediction_csvs(selected_file_path: str) -> dict[str, Path]:
83
+ """Search for prediction CSV files in the PREDICT/csv_test directory related to the selected file."""
84
+ predict_dir = get_predict_dir(selected_file_path)
85
+ if not predict_dir.exists():
86
+ return {}
87
+
88
+ results: dict[str, Path] = {}
89
+ for path in predict_dir.glob("*.csv"):
90
+ name = path.name
91
+ if name.endswith("_No_PFI.csv"):
92
+ results["No_PFI"] = path
93
+ elif name.endswith("_PFI.csv"):
94
+ results["PFI"] = path
95
+ return results
96
+
97
+ def get_robert_report_path(selected_file_path: str | Path, model_key: str) -> Path:
98
+ """Given the path to a selected file and model key ("No_PFI" or "PFI"), return the
99
+ corresponding ROBERT report PDF file - v2.2 generates one PDF per suffix instead of a
100
+ single combined report, so the path must depend on which tab/model is being displayed."""
101
+ return Path(selected_file_path).parent / f"ROBERT_report_{model_key}.pdf"
102
+
103
+ def find_external_test_pixmaps(base_path: str | Path, include_path=None) -> dict[str, QPixmap]:
104
+ """Search for external test images in the PREDICT/csv_test directory related to the selected file."""
105
+ base_path = Path(base_path)
106
+ if base_path.is_file():
107
+ base_path = base_path.parent
108
+
109
+ csv_test_dir = base_path / "PREDICT" / "csv_test"
110
+ if not csv_test_dir.exists():
111
+ return {}
112
+
113
+ results: dict[str, QPixmap] = {}
114
+ for path in csv_test_dir.glob("*.png"):
115
+ if include_path is not None and not include_path(path):
116
+ continue
117
+ name = path.name
118
+ pixmap = QPixmap(str(path))
119
+ if pixmap.isNull():
120
+ continue
121
+
122
+ if name.endswith("_No_PFI_external.png"):
123
+ results["No_PFI"] = pixmap
124
+ elif name.endswith("_PFI_external.png"):
125
+ results["PFI"] = pixmap
126
+
127
+ return results
128
+
129
+ def extract_scores_from_robert_report(pdf_path: Path) -> dict | None:
130
+ """Extract the Interpolation score details (the report's headline score) from the ROBERT
131
+ report PDF file. The file itself is already specific to one model/suffix - see
132
+ get_robert_report_path() - so there's a single score to extract, not one per model."""
133
+ return _extract_robert_score_details(pdf_path)
134
+
135
+ def extract_boundary_fragment(pdf_path: Path) -> QPixmap | None:
136
+ """Render the boundary robustness block from parsed ROBERT report data (regression only -
137
+ classification has no Boundary robustness score, see _extract_boundary_details())."""
138
+ details = _extract_boundary_details(pdf_path)
139
+ if not details:
140
+ return None
141
+ return _render_robert_score_pixmap(details)
142
+
143
+ def extract_robert_fragment_image(pdf_path: Path) -> QPixmap | None:
144
+ """Render the CheckML score block from parsed report data."""
145
+ details = _extract_robert_score_details(pdf_path)
146
+ if not details:
147
+ return None
148
+ return _render_robert_score_pixmap(details)
149
+
150
+ # v2.2 generates one full-width PDF per model/suffix (see get_robert_report_path()) instead
151
+ # of a single combined report with a No_PFI/PFI side-by-side layout. Section A's own layout
152
+ # now uses that same left/right split for a DIFFERENT pair of columns: Interpolation (the
153
+ # report's headline score) on the left, Boundary robustness on the right (regression only -
154
+ # blank for classification, see docs/Report/score.rst). Model/suffix selection is handled
155
+ # entirely by which PDF gets opened now, so these bboxes are fixed, not model-dependent.
156
+ def _score_bbox(page):
157
+ """Left half of page 0: the Interpolation score block."""
158
+ return (0, 0, 300, page.height)
159
+
160
+
161
+ def _boundary_bbox(page):
162
+ """Right half of page 0: the Boundary robustness score block."""
163
+ return (300, 0, page.width, page.height)
164
+
165
+
166
+ def _normalize_boundary_lines(text: str) -> list[str]:
167
+ """Collapse noisy PDF whitespace while preserving the content of each line."""
168
+ return [re.sub(r"\s+", " ", line).strip() for line in text.splitlines() if line.strip()]
169
+
170
+
171
+ def _parse_boundary_block(text: str) -> dict | None:
172
+ """Parse the Boundary robustness summary block into structured data. Boundary robustness
173
+ is scored 0-10, the same scale and "Title . Score N" heading as Interpolation (see
174
+ _parse_robert_score_block()), with two headline metrics instead of the model/points lines
175
+ - shaped to match that function's output so both scores can share
176
+ _render_robert_score_pixmap()."""
177
+ if not text:
178
+ return None
179
+
180
+ lines = _normalize_boundary_lines(text)
181
+ title_line = next(
182
+ (line for line in lines if "Boundary robustness" in line and re.search(r"\bScore\s+\d+(?:\.\d+)?\b", line, re.IGNORECASE)),
183
+ None,
184
+ )
185
+ if not title_line:
186
+ return None
187
+
188
+ score_match = re.search(r"\bScore\s+(\d+(?:\.\d+)?)\b", title_line, re.IGNORECASE)
189
+ if not score_match:
190
+ return None
191
+
192
+ low_line = next((line for line in lines if "Scaled RMSE (Low" in line), "")
193
+ high_line = next((line for line in lines if "Scaled RMSE (High" in line), "")
194
+
195
+ return {
196
+ "title": "Boundary robustness",
197
+ "score": round_checkml_score(score_match.group(1)),
198
+ "model_line": low_line,
199
+ "points_line": high_line,
200
+ }
201
+
202
+
203
+ def _extract_boundary_details(pdf_path: Path) -> dict | None:
204
+ """Extract structured boundary robustness information from the ROBERT report. Returns
205
+ None for classification reports, whose Section A right column has no Boundary robustness
206
+ block at all (not scored for classification - see docs/Report/score.rst)."""
207
+ if not pdf_path.exists():
208
+ return None
209
+
210
+ try:
211
+ with pdfplumber.open(pdf_path) as pdf:
212
+ if not pdf.pages:
213
+ return None
214
+ page = pdf.pages[0]
215
+ text = page.within_bbox(_boundary_bbox(page)).extract_text()
216
+ return _parse_boundary_block(text or "")
217
+ except Exception:
218
+ return None
219
+
220
+
221
+ def _parse_robert_score_block(text: str) -> dict | None:
222
+ """Parse the CheckML score text block into structured data."""
223
+ if not text:
224
+ return None
225
+
226
+ lines = [re.sub(r"\s+", " ", line).strip() for line in text.splitlines() if line.strip()]
227
+ if not lines:
228
+ return None
229
+
230
+ title_line = next((line for line in lines if re.search(r"\bScore\s+\d+(?:\.\d+)?\b", line, re.IGNORECASE)), None)
231
+ if not title_line:
232
+ joined_text = " ".join(lines)
233
+ score_match = re.search(r"\bScore\s+(\d+(?:\.\d+)?)\b", joined_text, re.IGNORECASE)
234
+ if not score_match:
235
+ return None
236
+ title_match = re.search(r"(.+?)\s*[.\-·]?\s*Score\s+\d+(?:\.\d+)?\b", joined_text, re.IGNORECASE)
237
+ title = title_match.group(1).strip() if title_match else "CheckML Score"
238
+ return {
239
+ "title": title,
240
+ "score": round_checkml_score(score_match.group(1)),
241
+ "model_line": _extract_robert_model_line(lines, title),
242
+ "points_line": _extract_robert_points_line(lines, title),
243
+ }
244
+
245
+ score_match = re.search(r"\bScore\s+(\d+(?:\.\d+)?)\b", title_line, re.IGNORECASE)
246
+ if not score_match:
247
+ return None
248
+
249
+ title = re.sub(r"\s*[·\.-]?\s*Score\s+\d+(?:\.\d+)?\b.*$", "", title_line, flags=re.IGNORECASE).strip()
250
+ return {
251
+ "title": title,
252
+ "score": round_checkml_score(score_match.group(1)),
253
+ "model_line": _extract_robert_model_line(lines, title),
254
+ "points_line": _extract_robert_points_line(lines, title),
255
+ }
256
+
257
+
258
+ def _extract_robert_model_line(lines: list[str], title: str) -> str:
259
+ """Find the line describing model, CV split and test split."""
260
+ for line in lines:
261
+ if line == title or "Score" in line:
262
+ continue
263
+ if "Model" in line or "CV" in line or "Test" in line:
264
+ if "ROBERT Report" in line:
265
+ continue
266
+ if re.search(r"\b\d{4}/\d{2}/\d{2}\b", line):
267
+ continue
268
+ return line
269
+ return ""
270
+
271
+
272
+ def _extract_robert_points_line(lines: list[str], title: str) -> str:
273
+ """Find the line describing training points and descriptors."""
274
+ for line in lines:
275
+ if line == title or "Score" in line:
276
+ continue
277
+ if "Points" in line:
278
+ return line
279
+ return ""
280
+
281
+
282
+ def _extract_robert_score_details(pdf_path: Path) -> dict | None:
283
+ """Extract structured Interpolation score information (the report's headline score) from
284
+ the ROBERT report."""
285
+ if not pdf_path.exists():
286
+ return None
287
+
288
+ try:
289
+ with pdfplumber.open(pdf_path) as pdf:
290
+ if not pdf.pages:
291
+ return None
292
+ page = pdf.pages[0]
293
+ text = page.within_bbox(_score_bbox(page)).extract_text()
294
+ return _parse_robert_score_block(text or "")
295
+ except Exception:
296
+ return None
297
+
298
+
299
+ def _robert_score_style(score: int | None) -> dict:
300
+ """Return the visual style associated with a CheckML score."""
301
+ if score is None:
302
+ return {"label": "UNKNOWN", "segments": 0, "fill": (0.92, 0.90, 0.96), "text": (0.35, 0.35, 0.35)}
303
+ score = round_checkml_score(score)
304
+ tier = checkml_score_tier(score)
305
+ color = checkml_score_color(score)
306
+ if score <= 0:
307
+ segments = 0
308
+ else:
309
+ segments = min(score, 10)
310
+ return {"label": tier, "segments": segments, "fill": color, "text": color}
311
+
312
+
313
+ def _render_robert_score_pixmap(details: dict) -> QPixmap | None:
314
+ """Render a synthetic CheckML score card for the GUI using parsed PDF data."""
315
+ width = 620
316
+ height = 255
317
+ margin = 24
318
+ style = _robert_score_style(details.get("score"))
319
+
320
+ doc = fitz.open()
321
+ try:
322
+ page = doc.new_page(width=width, height=height)
323
+ page.draw_rect(
324
+ fitz.Rect(6, 6, width - 6, height - 6),
325
+ color=(0.72, 0.72, 0.72),
326
+ fill=(1.0, 1.0, 1.0),
327
+ width=1.2,
328
+ )
329
+ page.draw_rect(
330
+ fitz.Rect(14, 14, width - 14, height - 14),
331
+ color=(0.86, 0.86, 0.86),
332
+ fill=None,
333
+ width=0.8,
334
+ )
335
+
336
+ page.insert_text(
337
+ fitz.Point(margin, 42),
338
+ f"{details['title']} . Score {details['score']}",
339
+ fontsize=24,
340
+ fontname="hebo",
341
+ color=(0.05, 0.05, 0.05),
342
+ )
343
+ if details.get("model_line"):
344
+ page.insert_text(
345
+ fitz.Point(margin, 78),
346
+ details["model_line"],
347
+ fontsize=20,
348
+ fontname="helv",
349
+ color=(0.05, 0.05, 0.05),
350
+ )
351
+ if details.get("points_line"):
352
+ page.insert_text(
353
+ fitz.Point(margin, 110),
354
+ details["points_line"],
355
+ fontsize=20,
356
+ fontname="helv",
357
+ color=(0.05, 0.05, 0.05),
358
+ )
359
+
360
+ bar_left = margin
361
+ bar_top = 138
362
+ bar_width = width - (margin * 2)
363
+ segments = 10
364
+ gap = 0
365
+ segment_width = bar_width / segments
366
+ segment_height = 20
367
+ empty_fill = (0.92, 0.90, 0.96)
368
+ filled_segments = max(0, min(style["segments"], segments))
369
+
370
+ for idx in range(segments):
371
+ x0 = bar_left + idx * (segment_width + gap)
372
+ rect = fitz.Rect(x0, bar_top, x0 + segment_width, bar_top + segment_height)
373
+ fill = style["fill"] if idx < filled_segments else empty_fill
374
+ page.draw_rect(rect, color=(0.05, 0.05, 0.05), fill=fill, width=1.0)
375
+
376
+ label = style["label"]
377
+ label_width_map = {
378
+ "VERY WEAK": 210,
379
+ "WEAK": 110,
380
+ "MODERATE": 180,
381
+ "STRONG": 150,
382
+ "UNKNOWN": 160,
383
+ }
384
+ label_x = width - margin - label_width_map.get(label, 160)
385
+ page.insert_text(
386
+ fitz.Point(label_x, 220),
387
+ label,
388
+ fontsize=20,
389
+ fontname="hebo",
390
+ color=style["text"],
391
+ )
392
+
393
+ pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0), alpha=False)
394
+ qimg = QImage.fromData(QByteArray(pix.tobytes("png")))
395
+ return QPixmap.fromImage(qimg)
396
+ except Exception:
397
+ return None
398
+ finally:
399
+ doc.close()
400
+
401
+
402
+ def extract_boundary_scores(pdf_path: Path) -> int | None:
403
+ """Extract the Boundary robustness score (0-10) from the ROBERT report PDF file.
404
+ Returns None for classification reports, which have no Boundary robustness score."""
405
+ details = _extract_boundary_details(pdf_path)
406
+ return details.get("score") if details else None
407
+
408
+ def extract_prediction_info(df: pd.DataFrame) -> dict:
409
+ """Extract prediction information from a DataFrame."""
410
+ pred_cols = [col for col in df.columns if col.endswith("_pred")]
411
+ result = {
412
+ "has_pred_column": False,
413
+ "pred_column": None,
414
+ "predictions_identical": None,
415
+ "n_unique": None,
416
+ "n_rows": len(df),
417
+ }
418
+
419
+ if len(pred_cols) != 1:
420
+ return result
421
+
422
+ col = pred_cols[0]
423
+ series = df[col].dropna()
424
+ result["has_pred_column"] = True
425
+ result["pred_column"] = col
426
+ result["n_unique"] = series.nunique()
427
+ result["predictions_identical"] = None if result["n_unique"] == 0 else result["n_unique"] == 1
428
+ return result
429
+
430
+ def evaluate_model_scenario(score: int | None, predictions_identical: bool | None) -> dict:
431
+ """Evaluate the model scenario based on CheckML score and predictions."""
432
+ almos_link = "https://github.com/MiguelMartzFdez/almos"
433
+ almos_html = f'<a href="{almos_link}">ALMOS</a>'
434
+ result = {"state": "UNKNOWN", "messages": [], "recommendations": []}
435
+
436
+ if score is None:
437
+ result["messages"].append("No valid CheckML score was detected. Model reliability cannot be evaluated.")
438
+ result["recommendations"].append("You may verify that ROBERT_report_No_PFI.pdf was generated correctly.")
439
+ return result
440
+
441
+ if predictions_identical is True:
442
+ result["state"] = "FAILED"
443
+ result["messages"].append(
444
+ f"CheckML score is {score}, but all predictions are identical. "
445
+ "The model cannot discriminate between candidates."
446
+ )
447
+ result["recommendations"].append(
448
+ "You may discard these predictions and introduce structural diversity "
449
+ f"with Clustering module in {almos_html}."
450
+ )
451
+ return result
452
+
453
+ if 0 <= score <= 3:
454
+ result["state"] = "FAILED"
455
+ result["messages"].append(f"CheckML score is {score}. Model performance is critically low.")
456
+ result["recommendations"].append(
457
+ "You may avoid using these predictions and rebuild the dataset "
458
+ f"using Clustering module in {almos_html}."
459
+ )
460
+ return result
461
+
462
+ if 4 <= score <= 6:
463
+ result["state"] = "WEAK"
464
+ result["messages"].append(f"CheckML score is {score}. The model works, but reliability is limited.")
465
+ result["recommendations"].append(
466
+ "You may use predictions cautiously and improve robustness "
467
+ f"through Active Learning module with {almos_html}."
468
+ )
469
+ return result
470
+
471
+ if 7 <= score <= 8:
472
+ result["state"] = "DECENT"
473
+ result["messages"].append(f"CheckML score is {score}. The model is solid but can still improve.")
474
+ result["recommendations"].append(
475
+ "You may use these predictions while considering further optimization "
476
+ f"through Active Learning module with {almos_html}."
477
+ )
478
+ return result
479
+
480
+ if score > 8:
481
+ result["state"] = "STRONG"
482
+ result["messages"].append(f"CheckML score is {score}. The model shows strong predictive performance.")
483
+ result["recommendations"].append(
484
+ "You may confidently use these predictions for candidate prioritization."
485
+ )
486
+ return result
487
+
488
+ return result
489
+
490
+ def evaluate_predictions_for_model(
491
+ selected_file_path: str | Path, df: pd.DataFrame, model_key: str,
492
+ report_path: Path | None = None,
493
+ ) -> dict:
494
+ """Evaluate predictions for a specific model."""
495
+ pdf_path = report_path or get_robert_report_path(selected_file_path, model_key)
496
+ details = extract_scores_from_robert_report(pdf_path)
497
+ score = details.get("score") if details else None
498
+ prediction_info = extract_prediction_info(df)
499
+ scenario = evaluate_model_scenario(
500
+ score=score,
501
+ predictions_identical=prediction_info["predictions_identical"],
502
+ )
503
+ return {
504
+ "model": model_key,
505
+ "pdf_path": pdf_path,
506
+ "score": score,
507
+ "prediction_info": prediction_info,
508
+ "scenario": scenario,
509
+ }
510
+
511
+ class PredictionDashboardPanel(QWidget):
512
+ """A collapsible dashboard panel to display ROBERT prediction evaluation results and diagnostics."""
513
+ def __init__(self, scenario: dict, pdf_image=None, boundary_score=None, boundary_image=None, external_plot=None, parent=None):
514
+ super().__init__(parent)
515
+ self._pdf_image = pdf_image
516
+ self._boundary_score = boundary_score
517
+ self._boundary_image = boundary_image
518
+ self._external_plot = external_plot
519
+ self.setObjectName("PredictionDashboard")
520
+ self.setStyleSheet(
521
+ "QWidget#PredictionDashboard { background: palette(base); "
522
+ "border-left: 1px solid palette(mid); }"
523
+ )
524
+ self.expanded_width = 360
525
+ self.collapsed_width = 48
526
+ self._expanded = True
527
+
528
+ unknown_color = checkml_tier_color("UNKNOWN", output="text_hex")
529
+ state_colors = {
530
+ "FAILED": checkml_tier_color("VERY WEAK", output="text_hex"),
531
+ "WEAK": checkml_tier_color("WEAK", output="text_hex"),
532
+ "DECENT": checkml_tier_color("STRONG", output="text_hex"),
533
+ "STRONG": checkml_tier_color("VERY STRONG", output="text_hex"),
534
+ "UNKNOWN": unknown_color,
535
+ }
536
+ self.main_color = state_colors.get(scenario.get("state", "UNKNOWN"), unknown_color)
537
+ self._build_ui(scenario)
538
+ self._apply_initial_state()
539
+
540
+ def _apply_initial_state(self):
541
+ """Apply the initial state based on the expansion status."""
542
+ if self._expanded:
543
+ self.main_layout.setContentsMargins(12, 10, 12, 10)
544
+ self.setMinimumWidth(260)
545
+ self.setMaximumWidth(16777215)
546
+ self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
547
+ self.title_label.show()
548
+ self.scroll.show()
549
+ self.collapse_spacer.hide()
550
+ self.toggle_btn.setText("Hide info ›")
551
+ self.toggle_btn.setFixedWidth(96)
552
+ self.toggle_btn.setToolTip("Hide model insights")
553
+ self.toggle_btn.setAccessibleName("Hide model insights")
554
+ else:
555
+ self.main_layout.setContentsMargins(6, 10, 6, 10)
556
+ self.setMinimumWidth(self.collapsed_width)
557
+ self.setMaximumWidth(self.collapsed_width)
558
+ self.title_label.hide()
559
+ self.scroll.hide()
560
+ self.collapse_spacer.show()
561
+ self.toggle_btn.setText("‹")
562
+ self.toggle_btn.setFixedWidth(34)
563
+ self.toggle_btn.setToolTip("More info: show model insights")
564
+ self.toggle_btn.setAccessibleName("Show model insights")
565
+
566
+ def _build_ui(self, scenario):
567
+ """Build the user interface."""
568
+ self.main_layout = QVBoxLayout(self)
569
+ self.main_layout.setContentsMargins(10, 8, 10, 8)
570
+ self.main_layout.setSpacing(12)
571
+
572
+ header_widget = QWidget()
573
+ header_widget.setFixedHeight(32)
574
+ header = QHBoxLayout(header_widget)
575
+ header.setContentsMargins(0, 0, 0, 0)
576
+ self.title_label = QLabel("Model insights")
577
+ self.title_label.setStyleSheet("font-size: 14px; font-weight: 600;")
578
+ header.addWidget(self.title_label)
579
+ header.addStretch()
580
+
581
+ self.toggle_btn = QPushButton()
582
+ self.toggle_btn.setObjectName("insightsToggle")
583
+ self.toggle_btn.setFixedHeight(32)
584
+ self.toggle_btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
585
+ self.toggle_btn.setStyleSheet(
586
+ "QPushButton#insightsToggle { background: palette(highlight); "
587
+ "color: palette(highlighted-text); border: none; "
588
+ "border-radius: 16px; padding: 5px 10px; font-weight: 600; }"
589
+ "QPushButton#insightsToggle:hover { border: 1px solid palette(mid); }"
590
+ )
591
+ self.toggle_btn.clicked.connect(self.toggle)
592
+ header.addWidget(self.toggle_btn)
593
+ self.main_layout.addWidget(header_widget)
594
+
595
+ scroll = QScrollArea()
596
+ scroll.setWidgetResizable(True)
597
+ scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
598
+ scroll.setStyleSheet("QScrollArea { border: none; background: transparent; }")
599
+ self.scroll = scroll
600
+
601
+ self.content = QWidget()
602
+ content_layout = QVBoxLayout(self.content)
603
+ content_layout.setSpacing(8)
604
+
605
+ self._build_status_block(content_layout, scenario)
606
+ self._build_pdf_snapshot_block(content_layout)
607
+ self._build_boundary_block(content_layout, self._boundary_score, self._boundary_image)
608
+ self._build_external_validation_block(content_layout, self._external_plot)
609
+ content_layout.addStretch()
610
+
611
+ scroll.setWidget(self.content)
612
+ self.main_layout.addWidget(scroll)
613
+ self.collapse_spacer = QWidget()
614
+ self.collapse_spacer.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
615
+ self.main_layout.addWidget(self.collapse_spacer)
616
+
617
+ def _build_status_block(self, layout, scenario):
618
+ """Build the status block with messages and recommendations."""
619
+
620
+ msg_label = QLabel(" ".join(scenario.get("messages", [])))
621
+ msg_label.setWordWrap(True)
622
+ msg_label.setStyleSheet(f"color: {self.main_color}; font-weight: bold;")
623
+ layout.addWidget(msg_label)
624
+
625
+ recommendations = scenario.get("recommendations", [])
626
+ if recommendations:
627
+ rec_label = QLabel(" ".join(recommendations))
628
+ rec_label.setWordWrap(True)
629
+ rec_label.setTextFormat(Qt.RichText)
630
+ rec_label.setTextInteractionFlags(Qt.TextBrowserInteraction)
631
+ rec_label.setOpenExternalLinks(True)
632
+ layout.addWidget(rec_label)
633
+
634
+ def _build_pdf_snapshot_block(self, layout):
635
+ """Build the PDF snapshot block with a PDF image."""
636
+ if not self._pdf_image:
637
+ return
638
+
639
+ layout.addSpacing(15)
640
+ container = QWidget()
641
+ container.setObjectName("dashboardBlock")
642
+ container.setStyleSheet("QWidget#dashboardBlock { background: palette(window); border: 1px solid palette(mid); border-radius: 10px; }")
643
+ container_layout = QVBoxLayout(container)
644
+ container_layout.setContentsMargins(14, 14, 14, 14)
645
+ container_layout.setSpacing(10)
646
+
647
+ title = QLabel("Model Performance Overview")
648
+ title.setStyleSheet("font-weight: bold; font-size: 13px;")
649
+ container_layout.addWidget(title)
650
+
651
+ image_frame = QWidget()
652
+ image_frame.setObjectName("imageFrame")
653
+ image_frame.setStyleSheet("QWidget#imageFrame { border: none; background: transparent; }")
654
+ image_layout = QVBoxLayout(image_frame)
655
+ image_layout.setContentsMargins(6, 6, 6, 6)
656
+
657
+ image_label = QLabel()
658
+ image_label.setAlignment(Qt.AlignCenter)
659
+ image_label.setPixmap(self._pdf_image.scaledToWidth(self.expanded_width - 120, Qt.SmoothTransformation))
660
+ image_layout.addWidget(image_label)
661
+ container_layout.addWidget(image_frame)
662
+ layout.addWidget(container)
663
+
664
+ def _build_boundary_block(self, layout, score, pixmap):
665
+ """Build the boundary robustness block with a score and image."""
666
+ if score is None and not pixmap:
667
+ return
668
+
669
+ layout.addSpacing(15)
670
+ container = QWidget()
671
+ container.setObjectName("dashboardBlock")
672
+ container.setStyleSheet("QWidget#dashboardBlock { background: palette(window); border: 1px solid palette(mid); border-radius: 10px; }")
673
+ container_layout = QVBoxLayout(container)
674
+ container_layout.setContentsMargins(14, 14, 14, 14)
675
+ container_layout.setSpacing(10)
676
+
677
+ title = QLabel("Boundary Robustness")
678
+ title.setStyleSheet("font-weight: bold; font-size: 13px;")
679
+ container_layout.addWidget(title)
680
+
681
+ subtitle = QLabel("Assessment of how well the model holds up at the edges of the training data range and beyond.")
682
+ subtitle.setWordWrap(True)
683
+ subtitle.setStyleSheet("font-size: 11px;")
684
+ container_layout.addWidget(subtitle)
685
+
686
+ if pixmap:
687
+ image_frame = QWidget()
688
+ image_frame.setObjectName("imageFrame")
689
+ image_frame.setStyleSheet("QWidget#imageFrame { border: none; background: transparent; }")
690
+ image_layout = QVBoxLayout(image_frame)
691
+ image_layout.setContentsMargins(6, 6, 6, 6)
692
+ image_label = QLabel()
693
+ image_label.setAlignment(Qt.AlignCenter)
694
+ image_label.setPixmap(pixmap.scaledToWidth(self.expanded_width - 120, Qt.SmoothTransformation))
695
+ image_layout.addWidget(image_label)
696
+ container_layout.addWidget(image_frame)
697
+
698
+ # Boundary robustness is scored 0-10 (regression only), the same scale used for the
699
+ # main CheckML score - see _robert_score_style() for the five displayed score tiers
700
+ if score is not None:
701
+ label = _robert_score_style(score)["label"]
702
+ color = checkml_score_color(score, output="text_hex")
703
+ summary_texts = {
704
+ "VERY WEAK": (
705
+ "No boundary robustness" if score <= 0 else "Very weak boundary robustness",
706
+ "The model is unreliable at the edges of the training range and beyond. Predictions outside the original data range are unreliable.",
707
+ ),
708
+ "WEAK": (
709
+ "Weak boundary robustness",
710
+ "The model may tolerate slight deviations beyond the training range, but predictions near extremes can become unstable.",
711
+ ),
712
+ "MODERATE": (
713
+ "Moderate boundary robustness",
714
+ "The model holds up reasonably well at the edges of the training range, although uncertainty increases further from the original data distribution.",
715
+ ),
716
+ "STRONG": (
717
+ "Strong boundary robustness",
718
+ "The model remains reliable at the edges of the training range and beyond, showing robust predictions even for extreme values.",
719
+ ),
720
+ "VERY STRONG": (
721
+ "Very strong boundary robustness",
722
+ "The model remains reliable at the edges of the training range and beyond, showing robust predictions even for extreme values.",
723
+ ),
724
+ }
725
+ summary, explanation = summary_texts[label]
726
+
727
+ summary_label = QLabel(summary)
728
+ summary_label.setStyleSheet(f"color: {color}; font-weight: bold;")
729
+ container_layout.addWidget(summary_label)
730
+
731
+ explanation_label = QLabel(explanation)
732
+ explanation_label.setWordWrap(True)
733
+ container_layout.addWidget(explanation_label)
734
+
735
+ layout.addWidget(container)
736
+
737
+ def _build_external_validation_block(self, layout, pixmap):
738
+ """Build the external validation block with an image."""
739
+ if not pixmap:
740
+ return
741
+
742
+ layout.addSpacing(15)
743
+ container = QWidget()
744
+ container.setObjectName("dashboardBlock")
745
+ container.setStyleSheet("QWidget#dashboardBlock { background: palette(window); border: 1px solid palette(mid); border-radius: 10px; }")
746
+ container_layout = QVBoxLayout(container)
747
+ container_layout.setContentsMargins(14, 14, 14, 14)
748
+ container_layout.setSpacing(10)
749
+
750
+ title = QLabel("External Test Set Validation")
751
+ title.setStyleSheet("font-weight: bold; font-size: 13px;")
752
+ container_layout.addWidget(title)
753
+
754
+ subtitle = QLabel("Predicted vs experimental values for molecules with known target data.")
755
+ subtitle.setWordWrap(True)
756
+ subtitle.setStyleSheet("font-size: 11px;")
757
+ container_layout.addWidget(subtitle)
758
+
759
+ image_frame = QWidget()
760
+ image_frame.setObjectName("imageFrame")
761
+ image_frame.setStyleSheet("QWidget#imageFrame { border: none; background: transparent; }")
762
+ image_layout = QVBoxLayout(image_frame)
763
+ image_layout.setContentsMargins(6, 6, 6, 6)
764
+ image_label = QLabel()
765
+ image_label.setAlignment(Qt.AlignCenter)
766
+ image_label.setPixmap(pixmap.scaledToWidth(self.expanded_width - 120, Qt.SmoothTransformation))
767
+ image_layout.addWidget(image_label)
768
+ container_layout.addWidget(image_frame)
769
+
770
+ guidance = QLabel(
771
+ "Interpretation:\n"
772
+ "• Alignment with the diagonal indicates agreement between predicted and experimental values.\n"
773
+ "• Larger deviations reflect increased prediction error.\n"
774
+ "• Systematic offsets may suggest model bias or calibration issues."
775
+ )
776
+ guidance.setWordWrap(True)
777
+ guidance.setStyleSheet("font-size: 11px;")
778
+ container_layout.addWidget(guidance)
779
+ layout.addWidget(container)
780
+
781
+ def toggle(self):
782
+ if self._expanded:
783
+ self._last_expanded_width = self.width()
784
+ self._expanded = not self._expanded
785
+ self._apply_initial_state()
786
+ target_width = (
787
+ max(260, getattr(self, "_last_expanded_width", 260))
788
+ if self._expanded else self.collapsed_width
789
+ )
790
+ splitter = self.parentWidget()
791
+ if isinstance(splitter, QSplitter):
792
+ sizes = splitter.sizes()
793
+ index = splitter.indexOf(self)
794
+ if len(sizes) == 2 and index in (0, 1):
795
+ total = sum(sizes)
796
+ sizes[index] = min(target_width, total - 1)
797
+ sizes[1 - index] = total - sizes[index]
798
+ splitter.setSizes(sizes)
799
+ elif self._expanded:
800
+ self.resize(target_width, self.height())
801
+
802
+
803
+ class PandasTableModel(QAbstractTableModel):
804
+ """A Qt table model that wraps a pandas DataFrame, with special handling for SMILES rendering and sorting optimization."""
805
+ def __init__(self, df: pd.DataFrame):
806
+ super().__init__()
807
+ self._df = df
808
+ self._sort_cache: dict[int, np.ndarray] = {}
809
+
810
+ def rowCount(self, parent=QModelIndex()):
811
+ """Return the number of rows in the DataFrame."""
812
+ return len(self._df)
813
+
814
+ def columnCount(self, parent=QModelIndex()):
815
+ """Return the number of columns in the DataFrame."""
816
+ return len(self._df.columns)
817
+
818
+ def data(self, index, role=Qt.DisplayRole):
819
+ """Return the data for a given index and role, with special handling for SMILES rendering."""
820
+ if not index.isValid():
821
+ return None
822
+
823
+ value = self._df.iat[index.row(), index.column()]
824
+ column_name = self._df.columns[index.column()]
825
+
826
+ if column_name == "Image":
827
+ if role in (Qt.DecorationRole, Qt.DisplayRole):
828
+ smiles = "" if pd.isna(value) else str(value)
829
+ mol = Chem.MolFromSmiles(smiles)
830
+ if mol:
831
+ img = Draw.MolToImage(mol, size=(120, 120))
832
+ buffer = BytesIO()
833
+ img.save(buffer, format="PNG")
834
+ qimg = QImage.fromData(buffer.getvalue())
835
+ return QPixmap.fromImage(qimg)
836
+ return None
837
+
838
+ if role == Qt.DisplayRole:
839
+ return "" if pd.isna(value) else str(value)
840
+
841
+ if role == Qt.TextAlignmentRole:
842
+ return Qt.AlignCenter
843
+
844
+ return None
845
+
846
+ def headerData(self, section, orientation, role=Qt.DisplayRole):
847
+ """Return the header data for a given section and orientation and role."""
848
+ if role != Qt.DisplayRole:
849
+ return None
850
+ if orientation == Qt.Horizontal:
851
+ return self._df.columns[section]
852
+ return section + 1
853
+
854
+ def sort_key(self, column: int) -> np.ndarray:
855
+ """Return the sorting key for a given column, with special handling for numeric columns."""
856
+ if column not in self._sort_cache:
857
+ col = self._df.iloc[:, column]
858
+ if pd.api.types.is_numeric_dtype(col):
859
+ self._sort_cache[column] = col.to_numpy(dtype=float, copy=False)
860
+ else:
861
+ self._sort_cache[column] = col.astype(str).to_numpy()
862
+ return self._sort_cache[column]
863
+
864
+ class StatsHeader(QHeaderView):
865
+ """A custom header view that displays column names and basic statistics for numeric columns."""
866
+ def __init__(self, df: pd.DataFrame, orientation, parent=None):
867
+ super().__init__(orientation, parent)
868
+ self._df = df
869
+ self.setDefaultAlignment(Qt.AlignCenter)
870
+ self.setSectionResizeMode(QHeaderView.ResizeToContents)
871
+ self._stats_cache = {}
872
+
873
+ for col in df.columns:
874
+ series = df[col]
875
+ if pd.api.types.is_numeric_dtype(series):
876
+ self._stats_cache[col] = {
877
+ "min": series.min(),
878
+ "median": series.median(),
879
+ "mean": series.mean(),
880
+ "max": series.max(),
881
+ }
882
+
883
+ self.setMinimumHeight(100)
884
+
885
+ def sizeHint(self):
886
+ """Return the size hint for the header view."""
887
+ size = super().sizeHint()
888
+ size.setHeight(100)
889
+ return size
890
+
891
+ def paintSection(self, painter, rect, logical_index):
892
+ """Paint the header section with column name and statistics."""
893
+ painter.save()
894
+
895
+ option = QStyleOptionHeader()
896
+ self.initStyleOption(option)
897
+ option.rect = rect
898
+ option.text = ""
899
+ option.icon = QIcon()
900
+ option.sortIndicator = QStyleOptionHeader.None_
901
+ self.style().drawControl(QStyle.CE_HeaderSection, option, painter, self)
902
+
903
+ col_name = self._df.columns[logical_index]
904
+ stats = self._stats_cache.get(col_name)
905
+ margin = 6
906
+ r = rect.adjusted(margin, margin, -margin, -margin)
907
+
908
+ bold_font = painter.font()
909
+ bold_font.setBold(True)
910
+ painter.setFont(bold_font)
911
+ fm = QFontMetrics(bold_font)
912
+ name_height = fm.boundingRect(0, 0, r.width(), 1000, Qt.AlignHCenter | Qt.TextWordWrap, col_name).height()
913
+
914
+ name_rect = rect.adjusted(margin, margin, -margin, -margin)
915
+ name_rect.setHeight(name_height)
916
+ painter.drawText(name_rect, Qt.AlignHCenter | Qt.AlignTop | Qt.TextWordWrap, col_name)
917
+
918
+ if stats is not None:
919
+ normal_font = painter.font()
920
+ normal_font.setBold(False)
921
+ painter.setFont(normal_font)
922
+ metrics_text = (
923
+ f"min: {stats['min']:.4g}\n"
924
+ f"median: {stats['median']:.4g}\n"
925
+ f"mean: {stats['mean']:.4g}\n"
926
+ f"max: {stats['max']:.4g}"
927
+ )
928
+ metrics_rect = r
929
+ metrics_rect.setTop(name_rect.bottom() + 6)
930
+ painter.drawText(metrics_rect, Qt.AlignHCenter | Qt.AlignTop | Qt.TextWordWrap, metrics_text)
931
+
932
+ painter.restore()
933
+
934
+ class ColumnStatsWidget(QWidget):
935
+ """A widget that displays basic statistics for numeric columns in a DataFrame."""
936
+ def __init__(self, df: pd.DataFrame, parent=None):
937
+ super().__init__(parent)
938
+ layout = QHBoxLayout(self)
939
+ layout.setContentsMargins(4, 4, 4, 4)
940
+ numeric_df = df.select_dtypes(include="number")
941
+
942
+ if numeric_df.empty:
943
+ layout.addWidget(QLabel("No numeric columns"))
944
+ layout.addStretch()
945
+ return
946
+
947
+ stats = numeric_df.agg(["min", "max", "mean"])
948
+ for col in numeric_df.columns:
949
+ label = QLabel(
950
+ f"<b>{col}</b><br>"
951
+ f"min: {stats[col]['min']:.4g}<br>"
952
+ f"max: {stats[col]['max']:.4g}<br>"
953
+ f"mean: {stats[col]['mean']:.4g}"
954
+ )
955
+ label.setStyleSheet("QLabel { padding: 4px; }")
956
+ layout.addWidget(label)
957
+
958
+ layout.addStretch()
959
+
960
+
961
+ class LoadCsvSignals(QObject):
962
+ """Signals for the LoadCsvTask."""
963
+ done = Signal(str, pd.DataFrame)
964
+
965
+ class LoadCsvTask(QRunnable):
966
+ """A task for loading a CSV file."""
967
+ def __init__(self, key: str, path: Path):
968
+ super().__init__()
969
+ self.key = key
970
+ self.path = path
971
+ self.signals = LoadCsvSignals()
972
+
973
+ def run(self):
974
+ try:
975
+ df = pd.read_csv(self.path)
976
+ self.signals.done.emit(self.key, df)
977
+ except Exception as exc:
978
+ print(f"Failed to load CSV {self.path}: {exc}")
979
+
980
+ class NumericSortProxy(QSortFilterProxyModel):
981
+ """A proxy model that optimizes sorting for numeric columns by caching sort keys."""
982
+ def lessThan(self, left, right):
983
+ model = self.sourceModel()
984
+ keys = model.sort_key(left.column())
985
+ return bool(keys[left.row()] < keys[right.row()])