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
robert/report.py ADDED
@@ -0,0 +1,2880 @@
1
+ """
2
+ Parameters
3
+ ----------
4
+
5
+ destination : str, default=None,
6
+ Directory to create the output file(s).
7
+ varfile : str, default=None
8
+ Option to parse the variables using a yaml file (specify the filename, i.e. varfile=FILE.yaml).
9
+ report_modules : list of str, default=['CURATE','GENERATE','VERIFY','PREDICT']
10
+ List of the modules to include in the report.
11
+ debug_report : bool, default=False
12
+ Debug mode using during the pytests of report.py
13
+
14
+ """
15
+ #####################################################.
16
+ # This file stores the REPORT class #
17
+ # used for generating the final PDF report #
18
+ #####################################################.
19
+
20
+ import os
21
+ import shutil
22
+ import re
23
+ import sys
24
+ import glob
25
+ import json
26
+ import math
27
+ import platform
28
+ import pandas as pd
29
+ from pathlib import Path
30
+ from robert.utils import (load_variables,
31
+ pd_to_dict,
32
+ create_score_heatmap,
33
+ )
34
+ from robert.checkml_score import round_checkml_score
35
+ from robert.report_utils import (
36
+ BOUNDARY_INDENT,
37
+ get_csv_names,
38
+ get_col_score,
39
+ calc_score,
40
+ adv_flawed,
41
+ adv_predict,
42
+ adv_test,
43
+ adv_diff_test,
44
+ adv_cv_sd,
45
+ adv_train_val_gap,
46
+ adv_sorted_cv_high,
47
+ adv_sorted_cv_low,
48
+ adv_applicability_domain,
49
+ get_col_text,
50
+ repro_info,
51
+ make_report,
52
+ css_content,
53
+ format_lines,
54
+ combine_cols,
55
+ get_metrics,
56
+ get_col_transpa,
57
+ get_outliers,
58
+ detect_predictions,
59
+ get_csv_metrics,
60
+ get_csv_pred
61
+ )
62
+
63
+ # suffixes -> output PDF filenames, one PDF per model
64
+ PDF_NAMES = {'No PFI': 'ROBERT_report_No_PFI.pdf', 'PFI': 'ROBERT_report_PFI.pdf'}
65
+
66
+ # grey section separators always CLOSE a section (never open one), so the line can't end up
67
+ # at the top of a page. Only Section A opens with one, below the header on page 1. Sections
68
+ # C onward whose own HTML doesn't already end with a line + page break get one in the main loop
69
+ # (see _close_section()); Section B also gets one, followed by a page break before Section C.
70
+ def _close_section(section_html):
71
+ '''
72
+ Closes a section that doesn't end with its own line/page break with a grey line (Section B
73
+ also gets a page break after it, so Section C always starts on a new page). The line is the bottom
74
+ border of a wrapper around the section (not a separate <hr>), so it's always attached to the
75
+ section's last line and can't end up alone at the top of the next page.
76
+ The 20px gap above it is a margin, which is dropped automatically at a page break
77
+ '''
78
+ tail = section_html[-400:]
79
+ if 'page-break-after: always' in tail or '<hr' in tail:
80
+ return section_html
81
+ # trailing empty spacer paragraphs could be pushed alone onto the next page, taking the
82
+ # border with them - the gap above the line is the wrapper's padding instead
83
+ section_html = re.sub(r'(\s*(<p[^>]*>\s*</p>|</p>))+\s*$', '', section_html)
84
+ if 'id="section-b"' in section_html:
85
+ # Section B closes with the same grey line, and Section C always starts on a new page.
86
+ # An explicit <hr> (as Section C uses) instead of the wrapper border: WeasyPrint drops
87
+ # the wrapper's bottom border after Section B's page-broken flex columns
88
+ return (f'{section_html}<hr style="margin-top: 20px; page-break-before: avoid;">'
89
+ '<p style="page-break-after: always;"></p>')
90
+ return (f'<div style="border-bottom: 1px solid #a0a0a0; padding-bottom: 15px; margin-bottom: 25px;">'
91
+ f'{section_html}</div>')
92
+
93
+ def _warning_section_key(warning):
94
+ """Sort report sections naturally, with warnings without a section reference first."""
95
+ section = re.search(r'\bsections?\s+([a-z])(?:\.(\d+))?([a-z]?)\b', warning, re.IGNORECASE)
96
+ if section is None:
97
+ return ('', 0, '')
98
+ return (section[1].upper(), int(section[2] or 0), section[3].lower())
99
+
100
+
101
+ # a descriptor whose importance is this small a fraction of the top descriptor's (or below
102
+ # this absolute value) contributes essentially nothing - used by _has_low_relevance_descp()
103
+ # below to flag when trimming near-irrelevant descriptors is worth trying (fewer, more
104
+ # relevant descriptors often generalize better than many diluted ones)
105
+ LOW_RELEVANCE_RELATIVE_THRESHOLD = 0.04
106
+ LOW_RELEVANCE_ABSOLUTE_THRESHOLD = 0.05
107
+
108
+
109
+
110
+ def _has_low_relevance_descp(lines,start_idx,shap=False):
111
+ '''
112
+ Scans the descriptor-importance lines right after a "PFI plot saved"/"SHAP plot saved"
113
+ marker (see PFI_plot()/shap_analysis() in utils.py for the exact format) and returns True
114
+ if any descriptor other than the top one is negligible: below
115
+ LOW_RELEVANCE_RELATIVE_THRESHOLD of the top descriptor's magnitude, or below
116
+ LOW_RELEVANCE_ABSOLUTE_THRESHOLD in absolute terms. Both PFI and SHAP list descriptors
117
+ sorted from most to least important already, so the first value found is the top one.
118
+ '''
119
+
120
+ # values are logged with :.2, which switches to scientific notation for small numbers
121
+ # (i.e. 1.2e-05) - without the exponent part, 1.2e-05 was read as 1.2
122
+ number = r'(-?\d+(?:\.\d*)?(?:[eE][-+]?\d+)?)'
123
+ values = []
124
+ for line in lines[start_idx+1:]:
125
+ stripped = line.strip()
126
+ if not stripped.startswith('-'):
127
+ break
128
+ if shap:
129
+ # "- {desc} = min: {min}, max: {max}" - use the larger-magnitude side as the
130
+ # importance proxy, matching how these lines are already sorted (utils.py)
131
+ min_match = re.search(rf'min:\s*{number}', stripped)
132
+ max_match = re.search(rf'max:\s*{number}', stripped)
133
+ if not (min_match and max_match):
134
+ continue
135
+ values.append(max(abs(float(min_match.group(1))), abs(float(max_match.group(1)))))
136
+ else:
137
+ # "- {desc} = {value} +- {sd}" - PFI values can be negative (a genuinely useless/
138
+ # noisy descriptor can shuffle-permute to a *better* score by chance), so compare
139
+ # magnitudes, not signed values
140
+ val_match = re.search(rf'=\s*{number}\s*\+-', stripped)
141
+ if not val_match:
142
+ continue
143
+ values.append(abs(float(val_match.group(1))))
144
+
145
+ if len(values) < 2:
146
+ return False
147
+
148
+ # the largest magnitude (SHAP lines are sorted by their max or min value, not by magnitude,
149
+ # so the first line isn't always the most important descriptor)
150
+ top_idx = max(range(len(values)), key=lambda idx: values[idx])
151
+ top = values[top_idx]
152
+ if top <= 0:
153
+ return False
154
+ for idx,val in enumerate(values):
155
+ if idx == top_idx:
156
+ continue
157
+ if val < LOW_RELEVANCE_RELATIVE_THRESHOLD * top or val < LOW_RELEVANCE_ABSOLUTE_THRESHOLD:
158
+ return True
159
+ return False
160
+
161
+
162
+ def _scan_outlier_block(lines,start_idx):
163
+ '''
164
+ Scans one "Outliers plot saved" block (see outlier_analysis() in utils.py) and returns
165
+ (max_sd, outlier_pct): the single largest SD value found (as before), and the combined
166
+ outlier percentage across every "{label}: {N} outliers out of {M} datapoints ({pct}%)"
167
+ summary line in the block (e.g. Train + Test combined), so "too many outliers overall"
168
+ can be flagged separately from "one very extreme outlier" (the existing 6.5 SD check).
169
+ '''
170
+
171
+ max_sd = 0.0
172
+ total_outliers, total_points = 0, 0
173
+ for line in lines[start_idx:]:
174
+ if '-------' in line:
175
+ break
176
+ sd_match = re.search(r'\(([\d.]+)\s*SDs\)', line)
177
+ if sd_match:
178
+ sd_line = float(sd_match.group(1))
179
+ if sd_line > max_sd:
180
+ max_sd = sd_line
181
+ continue
182
+ pct_match = re.search(r'(\d+) outliers out of (\d+) datapoints', line)
183
+ if pct_match:
184
+ total_outliers += int(pct_match.group(1))
185
+ total_points += int(pct_match.group(2))
186
+
187
+ outlier_pct = (total_outliers / total_points * 100) if total_points > 0 else 0.0
188
+ return max_sd, outlier_pct
189
+
190
+
191
+ class report:
192
+ """
193
+ Class containing all the functions from the REPORT module.
194
+
195
+ Parameters
196
+ ----------
197
+ kwargs : argument class
198
+ Specify any arguments from the REPORT module (for a complete list of variables, visit the ROBERT documentation)
199
+ """
200
+
201
+ # lines available in the Section A warnings box on page 1 (see print_warnings())
202
+ WARNING_LINE_BUDGET = 6
203
+
204
+ def __init__(self, **kwargs):
205
+ # check if there is a problem with weasyprint (required for this module)
206
+ # Suppress fontconfig warnings during import on Windows
207
+ if platform.system() == 'Windows':
208
+ import tempfile
209
+ temp_stderr = tempfile.TemporaryFile(mode='w+')
210
+ old_stderr = os.dup(2)
211
+ os.dup2(temp_stderr.fileno(), 2)
212
+
213
+ weasyprint_missing = False
214
+ try:
215
+ from weasyprint import HTML
216
+ except (OSError, ModuleNotFoundError):
217
+ weasyprint_missing = True
218
+ finally:
219
+ # stderr is restored only here (it used to be restored in the except block too, so
220
+ # the finally block then called os.dup2() on the already-closed descriptor and the
221
+ # run crashed with "OSError: Bad file descriptor" instead of the message below)
222
+ if platform.system() == 'Windows':
223
+ os.dup2(old_stderr, 2)
224
+ os.close(old_stderr)
225
+ temp_stderr.close()
226
+ if weasyprint_missing:
227
+ print(f"\nx The REPORT module requires some libraries that are missing, the PDF with the summary of the results has not been created. Try installing the libraries with 'conda install -y -c conda-forge glib gtk3 pango mscorefonts'")
228
+ sys.exit()
229
+
230
+ # load default and user-specified variables
231
+ self.args = load_variables(kwargs, "report")
232
+
233
+ # if CHECKML is activated, no PFI models are ever generated (it always scores the
234
+ # model as-is on the descriptors already in the input CSV, never re-curates them) - so
235
+ # the PFI PDF loop below is skipped whenever CHECKML was involved
236
+ path_eval = Path(f'{os.getcwd()}/CHECKML/CHECKML_data.dat')
237
+ eval_only = os.path.exists(path_eval)
238
+ # with --pfi_filter False, GENERATE never creates a Best_model/PFI (or All_models/.../PFI)
239
+ # folder, but the suffix loops below unconditionally tried 'PFI' too - get_transparency()
240
+ # found no CSV there and crashed with UnboundLocalError instead of just skipping it, the
241
+ # same way it already does for CHECKML (see eval_only above)
242
+ skip_pfi = eval_only or not self.args.pfi_filter
243
+ # stored on self too (not just the local var) so module_lines() can add a provenance
244
+ # note to Section A without needing this threaded through print_score()'s own call chain
245
+ self.eval_only = eval_only
246
+
247
+ # spacing used for the Boundary robustness (right) column in Sections A and B
248
+ self.spacing_PFI = f'{("&nbsp;")*4}'
249
+
250
+ # detects whether CHECKML evaluated a model with user-supplied hyperparameters
251
+ # (model_obj/model_file/model_params) rather than the trivial 'MVL' default - only
252
+ # those carry the optimistic-scores risk flagged in print_warnings() below, since 'MVL'
253
+ # has no hyperparameters that could have been tuned on data ROBERT now scores against.
254
+ # The model name is read off the actual GENERATE output (not re-derived from CLI args,
255
+ # which aren't available here) - CHECKML always narrows GENERATE to a single model, so
256
+ # the first non-'_db' CSV in Best_model/No_PFI names it
257
+ self.custom_model_used = False
258
+ if eval_only:
259
+ no_pfi_files = [f for f in glob.glob(f'{os.getcwd()}/GENERATE/Best_model/No_PFI/*.csv')
260
+ if not os.path.basename(f).endswith('_db.csv')]
261
+ if no_pfi_files:
262
+ resolved_model_name = os.path.splitext(os.path.basename(no_pfi_files[0]))[0]
263
+ self.custom_model_used = resolved_model_name != 'MVL'
264
+
265
+ # --all_models: VERIFY/PREDICT split their log into one VERIFY_{MODEL}_data.dat /
266
+ # PREDICT_{MODEL}_data.dat per model (see verify.py/predict.py) instead of a single
267
+ # shared file, since a merged log gives REPORT no reliable way to tell which lines
268
+ # belong to which model. Discover which models actually have both logs present, and
269
+ # generate a full set of PDFs (No PFI + PFI) per model instead of just one set.
270
+ if getattr(self.args, 'all_models', False):
271
+ model_names = sorted(
272
+ os.path.basename(f)[len('VERIFY_'):-len('_data.dat')]
273
+ for f in glob.glob(f'{os.getcwd()}/VERIFY/VERIFY_*_data.dat')
274
+ if os.path.exists(f"{os.getcwd()}/PREDICT/PREDICT_{os.path.basename(f)[len('VERIFY_'):-len('_data.dat')]}_data.dat")
275
+ )
276
+ # A REPORT-only run can follow a workflow that was generated with
277
+ # --all_models False. Those runs have shared VERIFY_data.dat and
278
+ # PREDICT_data.dat logs rather than per-model logs. If no paired
279
+ # per-model logs were found, process the shared logs as the single
280
+ # model report instead of silently producing no reports.
281
+ if not model_names and all(
282
+ os.path.exists(f'{os.getcwd()}/{module}/{module}_data.dat')
283
+ for module in ('VERIFY', 'PREDICT')
284
+ ):
285
+ model_names = [None]
286
+ else:
287
+ model_names = [None]
288
+
289
+ # collects each model's final Interpolation/Boundary robustness score, keyed by suffix
290
+ # ('No PFI'/'PFI') then model name - used to build the score-based Section F
291
+ # heatmap (create_score_heatmap()), which every model's own PDF embeds (each PDF
292
+ # shows the SAME heatmap, comparing all models). Since every model's PDF needs the
293
+ # finished heatmap, scores are collected here in a pre-pass over every model BEFORE
294
+ # the main per-model PDF loop below starts - the main loop re-derives its own
295
+ # data_score again per suffix as a side effect of building that PDF's HTML
296
+ # (print_score()), so this duplicates a bit of parsing, but keeps the heatmap logic
297
+ # independent of the (already long) main loop
298
+ model_scores = {'No PFI': {}, 'PFI': {}}
299
+ self.all_models_clas = False
300
+
301
+ if getattr(self.args, 'all_models', False) and model_names != [None]:
302
+ for score_model_name in model_names:
303
+ self.model_suffix = f'_{score_model_name}'
304
+ _, _, dat_files_pre, _, _ = self.get_repro(eval_only)
305
+
306
+ for suffix in ['No PFI', 'PFI']:
307
+ if skip_pfi and suffix == 'PFI':
308
+ continue
309
+
310
+ _, params_df_pre = self.get_transparency(suffix)
311
+ pred_type_pre = params_df_pre['type'][0].lower()
312
+ self.all_models_clas = pred_type_pre == 'clas'
313
+ data_score_pre = calc_score(dat_files_pre, suffix, pred_type_pre, {})
314
+ # rmse_bound: average of the Low/High sorted-CV scaled RMSEs (regression
315
+ # only) - used only as the 3rd tie-break criterion for best_models_text()
316
+ rmse_low = data_score_pre.get(f'scaled_rmse_low_{suffix}')
317
+ rmse_high = data_score_pre.get(f'scaled_rmse_high_{suffix}')
318
+ rmse_bound = (rmse_low+rmse_high)/2 if rmse_low is not None and rmse_high is not None else None
319
+ model_scores[suffix][score_model_name] = (
320
+ data_score_pre.get(f'interp_score_{suffix}'),
321
+ data_score_pre.get(f'extrap_score_{suffix}'),
322
+ data_score_pre.get(f'scaled_rmse_cv_{suffix}'),
323
+ rmse_bound,
324
+ )
325
+
326
+ for suffix in ['No PFI', 'PFI']:
327
+ if skip_pfi and suffix == 'PFI':
328
+ continue
329
+ if model_scores[suffix]:
330
+ self.save_score_heatmap(model_scores[suffix], suffix)
331
+
332
+ # kept on self (not just local) so print_generate() can build the informative
333
+ # "best model for Interpolation / Boundary robustness" line in Section F
334
+ self.model_scores = model_scores
335
+
336
+ for model_name in model_names:
337
+ self.model_suffix = f'_{model_name}' if model_name is not None else ''
338
+
339
+ # Reproducibility section (these functions only gather information, the sections
340
+ # will be print later in the report) - shared by both PDFs of this model
341
+ citation_dat, repro_dat, dat_files, csv_name, robert_version = self.get_repro(eval_only)
342
+
343
+ # generate one PDF per model (No PFI / PFI)
344
+ for suffix in ['No PFI', 'PFI']:
345
+ if skip_pfi and suffix == 'PFI':
346
+ continue
347
+
348
+ suffix_title = '_'.join(suffix.split())
349
+
350
+ # Transparency section
351
+ transpa_dat, params_df = self.get_transparency(suffix)
352
+ pred_type = params_df['type'][0].lower()
353
+ # model of this PDF, used by analyze_warnings() for the tree-based model warning
354
+ self.report_model_name = str(params_df['model'][0]) if 'model' in params_df.columns else ''
355
+
356
+ # print header
357
+ report_html = self.print_header(citation_dat)
358
+
359
+ # print CheckML score section
360
+ score_dat, metrics_dat, data_score = self.print_score(dat_files, pred_type, suffix, suffix_title)
361
+ report_html += score_dat
362
+
363
+ # Model metrics sit below Section A's score bars.
364
+ _, warnings_dict = self.print_warnings(dat_files, pred_type, data_score, suffix)
365
+ report_html += metrics_dat
366
+
367
+ # page 2: results summary with every warning (see print_summary_page())
368
+ report_html += self.print_summary_page(pred_type, data_score, warnings_dict, suffix, params_df)
369
+
370
+ # sections B onwards, each one closed by its own grey line (see _close_section())
371
+ sections = [
372
+ self.print_adv_anal(pred_type, data_score, suffix, suffix_title), # B
373
+ self.print_y_distrib(warnings_dict, suffix, suffix_title), # C
374
+ self.print_features(warnings_dict, suffix, suffix_title), # D
375
+ self.print_outliers(pred_type, suffix, suffix_title), # E
376
+ self.print_generate(eval_only, suffix_title), # F
377
+ repro_dat, # G
378
+ transpa_dat, # H
379
+ self.get_abbrev(), # I
380
+ self.print_predictions(pred_type, suffix, suffix_title), # J (if any)
381
+ self.print_misc(), # Miscellaneous
382
+ ]
383
+ for section_html in sections:
384
+ if section_html:
385
+ report_html += _close_section(section_html)
386
+
387
+ if self.args.debug_report:
388
+ with open(f"report_debug{self.model_suffix}_{suffix_title}.txt", "w", encoding="utf-8") as debug_text:
389
+ debug_text.write(report_html)
390
+
391
+ # create css
392
+ with open("report.css", "w", encoding="utf-8") as cssfile:
393
+ cssfile.write(css_content(csv_name,robert_version,getattr(self,'eval_only',False)))
394
+
395
+ pdf_name = PDF_NAMES[suffix] if model_name is None else f'ROBERT_report_{model_name}_{suffix_title}.pdf'
396
+
397
+ # Suppress fontconfig warnings from WeasyPrint on Windows
398
+ # These warnings come from the C library level, so we need to redirect at OS level
399
+ if platform.system() == 'Windows':
400
+ import tempfile
401
+
402
+ # Create a temporary file to redirect stderr
403
+ temp_stderr = tempfile.TemporaryFile(mode='w+')
404
+ old_stderr = os.dup(2) # Duplicate stderr file descriptor
405
+ os.dup2(temp_stderr.fileno(), 2) # Redirect stderr to temp file
406
+
407
+ try:
408
+ _ = make_report(report_html,HTML,pdf_name)
409
+ finally:
410
+ os.dup2(old_stderr, 2) # Restore stderr
411
+ os.close(old_stderr)
412
+ temp_stderr.close()
413
+ else:
414
+ _ = make_report(report_html,HTML,pdf_name)
415
+
416
+ # Remove report.css file
417
+ os.remove("report.css")
418
+
419
+ print(f'\no {pdf_name} was created successfully in the working directory!')
420
+
421
+ # --all_models: the working directory would otherwise end up with 8 PDFs (4 models x
422
+ # 2 PFI variants) - move all of them into REPORT_models/ and copy back only the single
423
+ # overall-best one (see _pick_best_overall()), so the working directory stays
424
+ # uncluttered by default
425
+ if getattr(self.args, 'all_models', False) and model_names != [None]:
426
+ self.organize_all_models_pdfs()
427
+
428
+
429
+ @staticmethod
430
+ def _pick_best_model(items,primary_idx,secondary_idx,rmse_idx):
431
+ """
432
+ Shared --all_models tie-break cascade (own score -> other axis's score -> lower RMSE),
433
+ used by both organize_all_models_pdfs() and best_models_text() so the two don't each
434
+ keep their own hand-indexed copy of the same cascade against differently-shaped
435
+ tuples (previously risked drifting out of sync if one tuple's shape ever changed
436
+ without mirroring the index shift in the other). items: list of
437
+ (key, interp, bound, rmse_cv, rmse_bound) tuples, always in this order regardless of
438
+ caller. Returns the single best tuple.
439
+ """
440
+ def sort_key(item):
441
+ primary = item[primary_idx] if item[primary_idx] is not None else -1
442
+ secondary = item[secondary_idx] if item[secondary_idx] is not None else -1
443
+ rmse = item[rmse_idx] if item[rmse_idx] is not None else float('inf')
444
+ return (-primary,-secondary,rmse)
445
+ return sorted(items, key=sort_key)[0]
446
+
447
+
448
+ # A candidate whose displayed integer tier is below this is "Very weak" on ROBERT's own
449
+ # scale (see checkml_score_tier()) - too weak on that axis to be a sensible
450
+ # "best overall" pick no matter how good its other axis is.
451
+ OVERALL_FLOOR = 3
452
+
453
+ def _pick_best_overall(self,items):
454
+ """
455
+ Picks a single overall-best (key, interp, bound, rmse_cv, rmse_bound) candidate,
456
+ combining Interpolation and Boundary robustness instead of ranking them separately
457
+ (which could point at two different models/suffixes). A candidate with either score
458
+ below OVERALL_FLOOR is disqualified first, regardless of how good its other axis is -
459
+ a model that can't be trusted at all on one axis isn't a safe overall pick just
460
+ because it excels at the other. Only if NO candidate clears that floor does the floor
461
+ get dropped entirely and every candidate is ranked by the normal Interpolation-primary
462
+ cascade (_pick_best_model) - a model that's merely weak on both axes is still a more
463
+ informative pick than refusing to choose. Classification has no Boundary robustness
464
+ score at all, so the floor never applies there - callers route that case straight to
465
+ _pick_best_model() instead of calling this.
466
+ """
467
+ survivors = [item for item in items
468
+ if item[1] is not None and round_checkml_score(item[1]) >= self.OVERALL_FLOOR
469
+ and item[2] is not None and round_checkml_score(item[2]) >= self.OVERALL_FLOOR]
470
+ pool = survivors if survivors else items
471
+ return self._pick_best_model(pool,1,2,3)
472
+
473
+
474
+ def organize_all_models_pdfs(self):
475
+ """
476
+ Moves every --all_models PDF (one per model x PFI variant) into a REPORT_models/
477
+ subfolder, then copies back into the working directory only the single overall-best
478
+ PDF - picked across BOTH models AND PFI variants together (unlike best_models_text(),
479
+ which picks per suffix) via _pick_best_overall(), so there's always exactly one PDF
480
+ left in the working directory, never two
481
+ """
482
+
483
+ candidates = []
484
+ for suffix, suffix_scores in getattr(self,'model_scores',{}).items():
485
+ suffix_title = '_'.join(suffix.split())
486
+ for model,vals in suffix_scores.items():
487
+ interp,bound,rmse_cv,rmse_bound = vals
488
+ pdf_name = f'ROBERT_report_{model}_{suffix_title}.pdf'
489
+ if os.path.exists(pdf_name):
490
+ candidates.append((pdf_name,interp,bound,rmse_cv,rmse_bound))
491
+
492
+ if not candidates:
493
+ return
494
+
495
+ # Boundary robustness isn't defined in classification, so Interpolation decides alone
496
+ # (no floor to apply - there's nothing to disqualify a candidate on)
497
+ if self.all_models_clas:
498
+ best_pdf = self._pick_best_model(candidates,1,2,3)[0]
499
+ else:
500
+ best_pdf = self._pick_best_overall(candidates)[0]
501
+
502
+ dest_dir = Path('REPORT_models')
503
+ dest_dir.mkdir(exist_ok=True)
504
+ for pdf_name,*_ in candidates:
505
+ shutil.move(pdf_name, str(dest_dir / pdf_name))
506
+
507
+ shutil.copy(str(dest_dir / best_pdf), best_pdf)
508
+
509
+ print(f'\no All {len(candidates)} model PDFs were moved to REPORT_models/')
510
+ print(f'o {best_pdf} (best overall model) was kept in the working directory')
511
+
512
+
513
+ def print_header(self,citation_dat):
514
+ """
515
+ Retrieves the header for the HTML string
516
+ """
517
+
518
+ # CHECKML scores a model the user already chose (not one ROBERT's own Bayesian search
519
+ # picked), so its reports use the CheckML logo instead of ROBERT's, to visually tell
520
+ # the two apart at a glance
521
+ logo_name = 'CheckML_logo.jpg' if getattr(self,'eval_only',False) else 'Robert_logo.jpg'
522
+
523
+ # combines the top image with the other sections of the header
524
+ header_lines = f"""
525
+ <h1 style="text-align: center; margin-bottom: 0.5em;">
526
+ <img src="file:///{self._posix_uri(self.args.path_icons)}/{logo_name}" alt="" style="display: block; margin-left: auto; margin-right: auto; width: 50%; margin-top: -12px;" />
527
+ <span style="font-weight:bold;"></span>
528
+ </h1>
529
+ {citation_dat}
530
+ """
531
+
532
+ return header_lines
533
+
534
+
535
+ @staticmethod
536
+ def print_radar_subheadings():
537
+ """Show the score breakdown heading above the retained interpolation radar."""
538
+
539
+ return (
540
+ '<p style="width:100%; margin:4px 0 2px 0; white-space:nowrap;">'
541
+ '<span style="display:inline-block; width:270px; margin-left:0; text-decoration:underline;">'
542
+ 'Score breakdown (see <a href="#section-b">Section B, left</a>)</span>'
543
+ '</p>'
544
+ )
545
+
546
+
547
+ def print_score(self,dat_files,pred_type,suffix,suffix_title):
548
+ """
549
+ Generates the CheckML score section (left = Interpolation, right = Boundary robustness)
550
+ """
551
+
552
+ # calculates the CheckML score (R2 is analogous for accuracy in classification)
553
+ data_score = {}
554
+ data_score = calc_score(dat_files,suffix,pred_type,data_score)
555
+
556
+ # a test set picked by the user (CHECKML's 'Set' column) is never the systematic split
557
+ # the score was calibrated for, even if it happens to have ~20% of the points (in which
558
+ # case the size check in calc_score() alone would still give a score)
559
+ path_eval_log = Path(f'{os.getcwd()}/CHECKML/CHECKML_data.dat')
560
+ eval_txt = path_eval_log.read_text(encoding='utf-8') if path_eval_log.exists() else ''
561
+ if "Using the 'Set' column" in eval_txt:
562
+ data_score[f'score_available_{suffix}'] = False
563
+ data_score[f'score_unavailable_reason_{suffix}'] = 'user_set'
564
+ # same for a CheckML run with a non-standard --split (RND, KN, EXTRA_Q1/Q5, or STRATIFIED
565
+ # in regression): the score is calibrated for the EVEN split (regression) or STRATIFIED
566
+ # split (classification), even if the test set has the standard ~20% size. A test-size
567
+ # or CV problem found by calc_score() keeps priority in the message
568
+ elif data_score.get(f'score_available_{suffix}', True):
569
+ split_line = re.search(r'Before (?:the CheckML evaluation|hyperoptimization), (.*)', eval_txt)
570
+ standard_split = 'an even distribution' if pred_type == 'reg' else 'a stratified distribution'
571
+ if split_line and standard_split not in split_line.group(1):
572
+ data_score[f'score_available_{suffix}'] = False
573
+ data_score[f'score_unavailable_reason_{suffix}'] = 'split'
574
+
575
+ # the score's thresholds were calibrated assuming the standard test_set=0.2 split (see
576
+ # calc_score()/get_predict_scores() for how score_available is derived, and the note in
577
+ # score.rst) - with a non-standard internal split (including 0, i.e. no held-out test
578
+ # set), the score isn't calibrated, so its bars/tier labels are replaced with grayed-out,
579
+ # "N/A"-labeled versions instead of a misleading STRONG/WEAK claim (see score_gray_N.jpg/
580
+ # score_w_2_gray_N.jpg below and in report_utils.py's score_badge_2()) - the underlying
581
+ # numbers, images and warnings are still real and shown exactly as usual. --csv_test does
582
+ # NOT affect this: it no longer suppresses the internal test split (see prepare_sets() in
583
+ # utils.py) precisely so the score keeps working normally even when an external test set
584
+ # is also provided. Defaults to available (fail open) if the underlying line wasn't found
585
+ # for some reason, rather than hiding the score by mistake
586
+ score_available = data_score.get(f'score_available_{suffix}', True)
587
+
588
+ # starts with the icon of CheckML score - when the score isn't calibrated, the standing
589
+ # intro paragraph is replaced (not just dropped) with the shorter "Score not available"
590
+ # notice, in the exact same slot/spacing (see explain_override in module_lines()) so the
591
+ # Interpolation/Boundary robustness columns right below keep the same tight spacing they
592
+ # always have under that slot, instead of sitting oddly close under a separately-appended
593
+ # paragraph
594
+ explain_override = None
595
+ if not score_available:
596
+ reason = data_score.get(f'score_unavailable_reason_{suffix}')
597
+ if reason == 'cv':
598
+ cv_type = data_score.get(f'cv_type_{suffix}', '')
599
+ reason_txt = f"this model used {cv_type} instead of the standard 10x repeated 5-fold CV the CheckML score was calibrated for. If you want a score, use the default --kfold 5 --repeat_kfolds 10"
600
+ elif reason == 'user_set':
601
+ reason_txt = "the test set was chosen by the user (Set column) instead of CheckML's systematic ~20% split the CheckML score was calibrated for. If you want a score, remove the Set column from the CSV and run CheckML again"
602
+ elif reason == 'split':
603
+ std_split = 'EVEN' if pred_type == 'reg' else 'STRATIFIED'
604
+ reason_txt = f"the test set was selected with a non-standard split method instead of the {std_split} split the CheckML score was calibrated for. If you want a score, use the default --split auto"
605
+ else:
606
+ n_test = data_score.get(f'n_test_{suffix}')
607
+ reason_txt = f"this model's test set has {n_test} point(s), not the standard ~20% split the CheckML score was calibrated for. If you want a score, use the default --test_set 0.2"
608
+ explain_override = f'<p style="margin-top:-7px;"><i style="text-align: justify;">Score not available: {reason_txt} (see <a href="https://robert.readthedocs.io/en/latest/Report/score.html">the CheckML score documentation</a>).</i>'
609
+
610
+ score_dat = ''
611
+ score_dat = self.module_lines('score',score_dat,pred_type=pred_type,explain_override=explain_override)
612
+
613
+ # Boundary robustness isn't defined for classification (no Low/High/applicability-
614
+ # domain analysis exists for a discrete MCC-based model - see boundary_plot(), which
615
+ # only runs for pred_type=='reg'), so only the Interpolation column is shown
616
+ score_cols = ['interpolation'] if pred_type == 'clas' else ['interpolation','boundary']
617
+
618
+ columns_score = []
619
+ boundary_sections = ''
620
+ if pred_type != 'clas':
621
+ boundary_sections = self.boundary_score_sections(data_score,suffix)
622
+ else:
623
+ boundary_sections = ''
624
+ for col in score_cols:
625
+ spacing = '' if col == 'interpolation' else self.spacing_PFI
626
+ score_key = 'interp_score' if col == 'interpolation' else 'extrap_score'
627
+ score_val = data_score.get(f'{score_key}_{suffix}', 0)
628
+ # Only integer score_N.jpg icons exist. Use the same half-up integer tier for the
629
+ # icon, assessment phrase, model-selection floor, and CheckML app display.
630
+ score_icon = round_checkml_score(score_val)
631
+ icon_name = f'score_{score_icon}' if score_available else f'score_gray_{score_icon}'
632
+ # The original half-page score image renders at 234.9pt = 313.2 CSS px.
633
+ # Keep that fixed size while the right-column text wrapper has its 10px inset.
634
+ score_image_width = '313.2px' if col == 'boundary' else '100%'
635
+ score_info = f"""<img src="file:///{self._posix_uri(self.args.path_icons)}/{icon_name}.jpg" style="width: {score_image_width}; margin-top:7px; margin-bottom:-18px;"></p>"""
636
+ columns_score.append(get_col_score(score_info,data_score,suffix,col,spacing))
637
+ if pred_type == 'clas':
638
+ # no Boundary robustness column (see comment above) - a short note instead of a
639
+ # blank column, so it reads as intentionally disabled rather than missing content,
640
+ # matching the wording used for the same reason in Section E (see module_lines())
641
+ indent = f'padding-left: {BOUNDARY_INDENT};' if self.spacing_PFI else ''
642
+ columns_score.append(f'''<div style="{indent} box-sizing: border-box;">
643
+ <p style="margin-top:-18px;"><span style="font-weight:bold;">Boundary robustness</span></p>
644
+ <p style="margin-top: -10px;"><i>Disabled in classification problems.</i></p>
645
+ </div>''')
646
+
647
+ # Combine both columns
648
+ score_dat += combine_cols(columns_score,right_offset=25)
649
+
650
+ if pred_type == 'clas':
651
+ return score_dat,self.classification_metrics(data_score,suffix,suffix_title),data_score
652
+
653
+ # add corresponding images (left: Results, right: Results_boundary_high - clas has no
654
+ # boundary image, see above, so the right side stays blank)
655
+ # the saved PNGs keep their in-image title (matplotlib plt.text) - height 218 is
656
+ # deliberately LESS than what the full titled image needs at 270px width (~237px,
657
+ # aspect 0.878), so object-fit:cover (anchored bottom, see print_img_tag) crops
658
+ # exactly the title strip off the top and nothing else. 218 = the image's own
659
+ # plot-only height at 270px width (aspect 0.806, measured directly with the title
660
+ # excluded) - don't "fix" this by raising the height to fit the title in, that brings
661
+ # the title back; don't lower it either, that starts cropping into the plot itself
662
+ diff_height = 25 # account for different graph sizes in reg and clas
663
+ height = 218
664
+ if pred_type == 'clas':
665
+ height += diff_height
666
+ # Keep the interpolation plot on the left and place the extrapolation details and
667
+ # Section A callouts together in the right column.
668
+ interp_tag,_ = self.get_score_image_tags(
669
+ suffix_title,height,pred_type,interp_width=285
670
+ )
671
+ if interp_tag:
672
+ interp_tag = interp_tag.replace(
673
+ 'style="', 'style="position:relative; left:-2px; ', 1
674
+ )
675
+ section_headings = combine_cols([
676
+ '<p style="margin:0; text-decoration:underline;">Model metrics</p>',
677
+ f'<p style="box-sizing:border-box; padding-left:{BOUNDARY_INDENT}; margin:0; text-decoration:underline;">'
678
+ 'Score breakdown (see <a href="#section-b">Section B, right</a>)</p>',
679
+ ],right_offset=25)
680
+ metrics_dat = (
681
+ f'<div style="margin-bottom:12px;">{section_headings}</div>'
682
+ + self.print_img_row_indent(
683
+ interp_tag,boundary_sections,3,right_offset=25,left_width=285
684
+ )
685
+ )
686
+
687
+ # metrics text row beneath the images
688
+ module_file = f'{os.getcwd()}/PREDICT/PREDICT{self.model_suffix}_data.dat'
689
+ interp_radar,_ = self.save_radar_plots(data_score,suffix,pred_type)
690
+ interp_radar_tag = (
691
+ f'<img src="file:///{self._posix_uri(interp_radar)}" '
692
+ 'style="display:block; flex:none; width:270px; height:auto; max-width:none; margin:0;"/>'
693
+ if interp_radar else ''
694
+ )
695
+ left_summary = f'''<div style="margin-left:-2px;">{get_metrics(module_file,suffix,'')}</div>
696
+ <div style="page-break-inside:avoid; margin-top:8px;">
697
+ {self.print_radar_subheadings()}
698
+ <div style="width:270px; margin-top:2px;">{interp_radar_tag}</div>
699
+ </div>'''
700
+ columns_summary = [left_summary]
701
+ columns_summary.append(self.section_a_callouts(data_score,suffix,pred_type,self.args.path_icons))
702
+ metrics_dat += combine_cols(columns_summary,right_offset=25)
703
+
704
+ return score_dat,metrics_dat,data_score
705
+
706
+
707
+ def classification_metrics(self,data_score,suffix,suffix_title):
708
+ """Keep classification's metrics, radar and notes together on page one.
709
+
710
+ Each column flows independently instead of sharing a second flex row
711
+ below the plot. Fixed table columns also preserve image dimensions in
712
+ WeasyPrint. Regression retains its existing layout in print_score().
713
+ """
714
+
715
+ interp_tag,_ = self.get_score_image_tags(suffix_title,243,'clas',interp_width=240)
716
+ if interp_tag:
717
+ interp_tag = interp_tag.replace('style="','style="position:relative; left:-2px; ',1)
718
+ module_file = f'{os.getcwd()}/PREDICT/PREDICT{self.model_suffix}_data.dat'
719
+ metrics = get_metrics(module_file,suffix,'').replace(
720
+ 'margin-top: 10px;',
721
+ 'margin:8px 0 0; font-size:11px; line-height:1.3; white-space:pre-wrap; text-align:left;',
722
+ )
723
+ interp_radar,_ = self.save_radar_plots(data_score,suffix,'clas')
724
+ radar_tag = (
725
+ f'<img src="file:///{self._posix_uri(interp_radar)}" '
726
+ 'style="display:block; width:220px; min-width:220px; max-width:220px; height:auto; margin:0;"/>'
727
+ if interp_radar else ''
728
+ )
729
+ notes = self.section_a_callouts(data_score,suffix,'clas',self.args.path_icons)
730
+ return f'''<table style="width:100%; table-layout:fixed; border-collapse:collapse; page-break-inside:avoid;">
731
+ <tr><td style="width:50%; padding:0; vertical-align:top;">
732
+ <p style="margin:0; text-decoration:underline;">Model metrics</p>
733
+ <div style="margin-top:8px;">{interp_tag}</div>
734
+ <div style="margin-left:-2px;">{metrics}</div>
735
+ <div style="page-break-inside:avoid; margin-top:8px;">
736
+ {self.print_radar_subheadings()}
737
+ <div style="width:220px; margin-top:2px;">{radar_tag}</div>
738
+ </div></td>
739
+ <td style="width:50%; padding:0 0 0 25px; vertical-align:top;">{notes}</td></tr>
740
+ </table>'''
741
+
742
+
743
+ def boundary_score_sections(self,data_score,suffix):
744
+ """Build the three summed boundary score rows for Section A."""
745
+
746
+ score_high = sum(
747
+ data_score.get(f'{key}_{suffix}',0) or 0
748
+ for key in (
749
+ 'sorted_cv_high_score',
750
+ 'spearman_score_high',
751
+ 'degradation_score_high',
752
+ )
753
+ )
754
+ score_low = sum(
755
+ data_score.get(f'{key}_{suffix}',0) or 0
756
+ for key in (
757
+ 'sorted_cv_low_score',
758
+ 'spearman_score_low',
759
+ 'degradation_score_low',
760
+ )
761
+ )
762
+ score_leverage = data_score.get(f'applicability_domain_score_{suffix}',0) or 0
763
+
764
+ icon_dir = f'file:///{self._posix_uri(self.args.path_icons)}'
765
+ icon_style = 'width:25px; height:25px; margin-right:13px; vertical-align:middle;'
766
+ first_row_style = 'display:block; margin:0 0 14px 0;'
767
+ next_row_style = 'display:block; padding-top:5px; margin:0 0 14px 0;'
768
+ text_style = 'display:inline-block; width:232px; vertical-align:middle;'
769
+ first_text_style = f'{text_style} margin-top:3px;'
770
+ score_line_style = 'display:block; margin-top:4px;'
771
+ score_high_badge = round_checkml_score(score_high)
772
+ score_low_badge = round_checkml_score(score_low)
773
+ score_leverage_badge = round_checkml_score(score_leverage)
774
+ # same "N/A" + muted bar as the rest of the report when the score isn't calibrated for
775
+ # this run (non-standard CV/test/split, see print_score()) - there are no gray versions
776
+ # of the 0-4 bars, so the bars are faded instead
777
+ score_available = data_score.get(f'score_available_{suffix}', True)
778
+ fade = '' if score_available else ' opacity:0.35;'
779
+
780
+ def score_label(value,max_score):
781
+ return f'{value:.1f} / {max_score}' if score_available else 'N/A'
782
+
783
+ def score_image(max_score,badge):
784
+ # The packaged score_w_4_1 asset is uppercase .JPG; keep the URI portable to
785
+ # case-sensitive filesystems as well as Windows.
786
+ extension = 'JPG' if max_score == 4 and badge == 1 else 'jpg'
787
+ image_width = 26 if max_score == 4 else 13
788
+ return (
789
+ f'<img src="{icon_dir}/score_w_{max_score}_{badge}.{extension}" '
790
+ f'alt="CheckML score" style="width:{image_width}%; vertical-align:middle;{fade}">'
791
+ )
792
+
793
+ image_high = score_image(4,score_high_badge)
794
+ image_low = score_image(4,score_low_badge)
795
+ image_leverage = score_image(2,score_leverage_badge)
796
+ rows = (
797
+ f'<span style="{first_row_style}"><img src="{icon_dir}/robust_y_high.png" alt="" style="{icon_style} margin-top:3px;">'
798
+ f'<span style="{first_text_style}"><strong>1. Extrapolation to higher y values</strong>'
799
+ f'<span style="{score_line_style}">{score_label(score_high,4)}&nbsp;&nbsp;{image_high}</span></span></span>'
800
+ )
801
+ rows += (
802
+ f'<span style="{next_row_style}"><img src="{icon_dir}/robust_y_low.png" alt="" style="{icon_style}">'
803
+ f'<span style="{text_style}"><strong>2. Extrapolation to lower y values</strong>'
804
+ f'<span style="{score_line_style}">{score_label(score_low,4)}&nbsp;&nbsp;{image_low}</span></span></span>'
805
+ )
806
+ rows += (
807
+ f'<span style="{next_row_style}"><img src="{icon_dir}/robust_x.png" alt="" style="{icon_style}">'
808
+ f'<span style="{text_style}"><strong>3. Descriptor-space extrapolation</strong>'
809
+ f'<span style="{score_line_style}">{score_label(score_leverage,2)}&nbsp;&nbsp;{image_leverage}</span></span></span>'
810
+ )
811
+
812
+ # Offset the evaluations visually past the overlay rule. Relative positioning keeps
813
+ # their original layout width and leaves the two-column row geometry unchanged.
814
+ return f'<span style="position:relative; left:4px; display:inline-block; width:270px; vertical-align:top;">{rows}</span>'
815
+
816
+
817
+ @staticmethod
818
+ def cv_test_diagnostic(data_score,suffix,pred_type='reg'):
819
+ """
820
+ Results of the CV-Test Split Diagnostic (CV metric with 80% vs. 100% of the data), shared by
821
+ Section A (page 1) and the results summary (page 2). Returns (metric_name, missing, rows), where
822
+ missing flags absent full-data/partition metrics and each row is
823
+ (status, icon_file, foreground, label, value).
824
+ """
825
+ if pred_type == 'reg':
826
+ metric_name, baseline_key = 'CV RMSE', 'rmse'
827
+ comparisons = (
828
+ ('cv', 'Interpolation'),
829
+ ('high', 'Extrapol. high y values'),
830
+ ('low', 'Extrapol. low y values'),
831
+ ('ad', 'Extrapol. descriptor-space'),
832
+ )
833
+ else:
834
+ metric_name, baseline_key = 'MCC', 'mcc'
835
+ comparisons = (('cv', 'Interpolation'),)
836
+ missing = (data_score.get(f'{baseline_key}_full_{suffix}') is None
837
+ or any(data_score.get(f'full_cv_diff_{metric}_{suffix}') is None for metric, _ in comparisons))
838
+ rows = []
839
+ for metric, label in comparisons:
840
+ difference = data_score.get(f'full_cv_diff_{metric}_{suffix}')
841
+ if difference is None or math.isnan(difference):
842
+ status, icon_file, foreground = 'N/A', None, '#555555'
843
+ value = 'unavailable'
844
+ else:
845
+ # Small tolerance includes the exact 15%/30% boundaries
846
+ # despite floating-point arithmetic in the percentage ratio.
847
+ if difference <= 15 + 1e-9:
848
+ status, icon_file, foreground = 'Pass', 'checkml_pass.svg', '#236c32'
849
+ elif difference <= 30 + 1e-9:
850
+ status, icon_file, foreground = 'Unclear', 'checkml_unclear.svg', '#806000'
851
+ else:
852
+ status, icon_file, foreground = 'Warning', 'checkml_warning.svg', '#a02828'
853
+ value = f'{difference:.1f}%' if math.isfinite(difference) else 'unbounded'
854
+ rows.append((status, icon_file, foreground, label, value))
855
+ return metric_name, missing, rows
856
+
857
+
858
+ @staticmethod
859
+ def diagnostic_icon(icon_dir,icon_file,size=10):
860
+ """Packaged Pass/Unclear/Warning vector icon (or a dash for N/A), no network or symbol fonts needed."""
861
+ if icon_file is None:
862
+ return f'<span style="display:inline-block; width:{size}px; text-align:center;">&minus;</span>'
863
+ return (f'<img src="{icon_dir}/{icon_file}" alt="" '
864
+ f'style="width:{size}px; height:{size}px; min-width:{size}px; max-width:{size}px; '
865
+ 'margin:0; vertical-align:middle;"/>')
866
+
867
+
868
+ @staticmethod
869
+ def section_a_callouts(data_score,suffix,pred_type='reg',path_icons=None):
870
+ """Build the explanatory callouts shown beneath the right-column score details."""
871
+
872
+ icon_dir = Path(path_icons or Path(__file__).resolve().parent / 'report').resolve().as_uri()
873
+
874
+ # separate boxes (full thin border) to the right of the central column rule, instead
875
+ # of a thick left stripe that doubled as the rule
876
+ def card(title,content,margin_top=8):
877
+ return f'''<div style="box-sizing:border-box; background:#f2f2f2; border:1px solid #c8c8c8; border-radius:4px; padding:4px 8px 5px 8px; margin:{margin_top}px 0 5px 10px; color:#222222; page-break-inside:avoid;">
878
+ <div style="font-size:10.5px; font-weight:bold; letter-spacing:0.3px; color:#000000;">{title}</div>
879
+ <div style="font-size:10.5px; line-height:1.25;">{content}</div></div>'''
880
+ metric_name, missing, diag_rows = report.cv_test_diagnostic(data_score,suffix,pred_type)
881
+ # "Unclear"/"Warning": the flagged sub-score must not be used, AND the user has to check
882
+ # that aspect of the model with their own analyses (a flag is not an excuse to skip it)
883
+ influence = (
884
+ 'Effect of holding out 20% of the data as a test set '
885
+ f'({metric_name} with 80% vs. 100% of the data).'
886
+ f'<br><u>{metric_name} difference vs. full-data CV:</u>')
887
+ if missing:
888
+ influence = 'Rerun PREDICT to calculate the missing full-data or partition CV metrics.'
889
+ for status, icon_file, foreground, label, value in diag_rows:
890
+ icon = report.diagnostic_icon(icon_dir,icon_file)
891
+ influence += (
892
+ f'<div style="color:{foreground}; '
893
+ f'padding:1px 4px; margin-top:2px;">{icon} <strong>{status}</strong>'
894
+ f' · {label}: {value}</div>'
895
+ )
896
+ # what to do with flagged rows, right after the results; the Pass/Unclear/Warning
897
+ # thresholds are in the linked documentation
898
+ influence += (
899
+ '<div style="margin-top:4px;"><strong>Unclear:</strong> potentially unreliable, use sub-score with caution.'
900
+ '<br><strong>Warning:</strong> unreliable sub-score, do not use it.'
901
+ '<br>In both cases, further assess that aspect of your model using your own analyses. More '
902
+ '<a href="https://robert.readthedocs.io/en/latest/Report/score.html#cv-test-split-diagnostic">'
903
+ 'details here.</a></div>'
904
+ )
905
+ disclaimer = (
906
+ '<u>Scores reflect your model, not an exact copy</u>'
907
+ '<br>CheckML retrains your model with standardized (not user-defined) splits '
908
+ 'and CV, so scores closely reflect, but do not exactly match, its performance. More '
909
+ '<a href="https://robert.readthedocs.io/en/latest/Report/score.html#protocols-followed-by-checkml">details here</a>.'
910
+ '<br><u>Scores are indicative</u>'
911
+ '<br>A low score does not make a model unusable: assess whether the limitation '
912
+ 'matters for its intended use. More '
913
+ '<a href="https://robert.readthedocs.io/en/latest/Report/score.html#overview-and-considerations">details here</a>.'
914
+ )
915
+ # Regression's notes sit just below the boundary score rows. Classification
916
+ # has no such rows, and its taller plot can push this block to a new page;
917
+ # keep it in normal vertical flow so it clears the running page header.
918
+ top, margin_top = (-5, -42) if pred_type == 'reg' else (0, 0)
919
+ # regression: continue Section A's central rule (same x and style, see
920
+ # print_score_section()) down to the bottom of the boxes. It starts above this block,
921
+ # overlapping the end of the upper rule so both read as a single line
922
+ rule = (
923
+ '<span aria-hidden="true" style="position:absolute; left:-8px; top:-95px; bottom:5px; '
924
+ 'width:1.5px; background:#999999; border-radius:1px; pointer-events:none;"></span>'
925
+ if pred_type == 'reg' else ''
926
+ )
927
+ return (
928
+ f'<div style="position:relative; top:{top}px; width:300px; margin-left:-10px; margin-top:{margin_top}px;">{rule}'
929
+ f'{card("CV-Test Split Diagnostic",influence,13)}'
930
+ f'{card("Considerations when using CheckML",disclaimer,13)}'
931
+ '</div>'
932
+ )
933
+
934
+
935
+ def get_score_image_tags(self,suffix_title,height,pred_type,interp_width=270):
936
+ """
937
+ Locates the interpolation (Results_*.png) and, for regression, boundary robustness
938
+ (Results_boundary_high_*.png) images for this model and returns them as ready-to-embed
939
+ <img> tags (right tag is '' for classification, where that analysis isn't defined - see
940
+ print_score())
941
+ """
942
+
943
+ module_path = Path(f'{os.getcwd()}/PREDICT')
944
+
945
+ # glob (not rglob): avoids picking up files from the PREDICT/csv_test subfolder
946
+ interp_images = [str(fp) for fp in module_path.glob('Results_*.png')
947
+ if self.matches_suffix(str(fp),suffix_title) and 'Results_boundary' not in str(fp)]
948
+
949
+ interp_images = self._filter_by_model(interp_images)
950
+ interp_image = interp_images[0] if interp_images else ''
951
+ interp_height = round(height * interp_width / 270)
952
+ left_tag = self.print_img_tag(interp_image,interp_height,width=interp_width)
953
+
954
+ if pred_type == 'clas':
955
+ return left_tag,''
956
+
957
+ # top 20% (High) plot only - the low/ad/williams variants have their own filenames now
958
+ # (Results_boundary_low_..., Results_boundary_ad_..., Results_boundary_williams_...)
959
+ bound_images = [str(fp) for fp in module_path.glob('Results_boundary_high_*.png')
960
+ if self.matches_suffix(str(fp),suffix_title)]
961
+ bound_images = self._filter_by_model(bound_images)
962
+ bound_image = bound_images[0] if bound_images else ''
963
+ right_tag = self.print_img_tag(bound_image,height)
964
+
965
+ return left_tag,right_tag
966
+
967
+
968
+ def print_score_images(self,suffix_title,height,pred_type):
969
+ """
970
+ Places the interpolation image for this model - alongside the boundary robustness image
971
+ for regression (see get_score_image_tags())
972
+ """
973
+
974
+ left_tag,right_tag = self.get_score_image_tags(suffix_title,height,pred_type)
975
+
976
+ # no boundary-robustness image for classification - keep the original two-column row
977
+ # layout/proportions with the right side blank
978
+ return self.print_img_row_indent(left_tag,right_tag,-5)
979
+
980
+
981
+ def print_warnings(self,dat_files,pred_type,data_score,suffix):
982
+ """
983
+ Analyzes warnings for the page-2 summary and returns the retained interpolation radar.
984
+ """
985
+
986
+ # load spacing, colors, and line and table formats
987
+ space,color_dict,style_lines,warnings_dat = self.get_warning_params()
988
+
989
+ # gather the lines from PREDICT (and VERIFY, for the cluster-test check) where the
990
+ # potential warnings are printed
991
+ warnings_dict = self.get_warning_lines(pred_type,dat_files.get('VERIFY',[]))
992
+
993
+ warnings_dict[f'severe_warnings_{suffix}'] = []
994
+ warnings_dict[f'moderate_warnings_{suffix}'] = []
995
+
996
+ # Build the warning lists in the order used by the documentation tables.
997
+ warnings_dict = self.analyze_warnings(data_score,suffix,warnings_dict,pred_type)
998
+
999
+ # Every warning is shown in the results summary on page 2 (see print_summary_page()).
1000
+
1001
+ # a big, impossible-to-miss banner (separate from the bulleted severe-warnings list
1002
+ # below, which uses a small 15px bullet) for the one risk ROBERT cannot itself measure
1003
+ # or correct: hyperparameters supplied by the user (CHECKML's model_obj/model_file/
1004
+ # model_params) rather than searched by ROBERT's own BO within a held-out split. If
1005
+ # those hyperparameters were chosen using a process that already saw data ROBERT now
1006
+ # scores against (CV folds or the test set), both scores are optimistic to an unknown
1007
+ # degree - this can't be detected from the CSV alone, so it's surfaced instead of silently
1008
+ # trusted. Doesn't apply to the plain 'MVL' default, which has nothing to tune
1009
+ #
1010
+ # disabled on request - commented out, not removed, so it's easy to bring back
1011
+ # if getattr(self,'custom_model_used',False):
1012
+ # warning_print += f'''
1013
+ # <div style="width:100%; box-sizing:border-box; background-color:{color_dict['red']}; padding:8px; margin-top:2px; margin-bottom:10px; text-align:center;">
1014
+ # <span style="font-size:17px; font-weight:bold; color:white;">&#9888; SCORES MAY BE OPTIMISTIC: user-provided hyperparameters</span><br>
1015
+ # <span style="font-size:11.5px; color:white;">This model's hyperparameters came from the user (CHECKML), not from ROBERT's own search within a held-out split. If they were tuned using a process that already saw this data (or part of it), <strong>both the CV and Test scores below may be optimistic</strong> - ROBERT cannot detect or correct for this. Only trust these results if the hyperparameters were chosen on data fully independent from this dataset.</span>
1016
+ # </div>'''
1017
+
1018
+ return '',warnings_dict
1019
+
1020
+
1021
+ # displayed size (px) of each radar plot on page 1 - 270px wide like every other report image
1022
+ # (extra height vs the old 270x215 holds the flawed-model sentence under the radar)
1023
+ RADAR_SIZE = (270, 240)
1024
+
1025
+ def save_radar_plots(self,data_score,suffix,pred_type):
1026
+ '''
1027
+ Saves the radar plots of the 0-2 components behind the Interpolation and Boundary
1028
+ robustness scores (same values as Section B). The flawed-model tests are a penalty
1029
+ (<= 0) rather than a 0-2 component, so they're summarized in text instead (see
1030
+ print_warnings()). Classification has no Boundary robustness, so only one radar is made.
1031
+ Returns (interpolation_png, boundary_png or '')
1032
+ '''
1033
+
1034
+ import numpy as np
1035
+ import matplotlib
1036
+ matplotlib.use('Agg')
1037
+ import matplotlib.pyplot as plt
1038
+
1039
+ diff_key = 'diff_scaled_rmse_score' if pred_type == 'reg' else 'diff_mcc_score'
1040
+ radars = [('interpolation', f'interp_score_{suffix}', [
1041
+ # short names (numbered as in Section B) so the labels don't crowd the plot.
1042
+ # 1. Flawed models is a penalty (<= 0), so it's written as a sentence under
1043
+ # the radar instead of being drawn as a bar
1044
+ ('2. CV', f'cv_score_combined_{suffix}'),
1045
+ ('3. Test', f'test_score_combined_{suffix}'),
1046
+ ('4. Train-val gap', f'train_val_gap_score_{suffix}'),
1047
+ ('5. CV vs test', f'{diff_key}_{suffix}'),
1048
+ ('6. Stability', f'cv_sd_score_{suffix}'),
1049
+ ])]
1050
+ if pred_type == 'reg':
1051
+ radars.append(('boundary', f'extrap_score_{suffix}', [
1052
+ ('1a. High sorted CV', f'sorted_cv_high_score_{suffix}'),
1053
+ ('1b. High Spearman', f'spearman_score_high_{suffix}'),
1054
+ ('1c. High degradation', f'degradation_score_high_{suffix}'),
1055
+ ('2a. Low sorted CV', f'sorted_cv_low_score_{suffix}'),
1056
+ ('2b. Low Spearman', f'spearman_score_low_{suffix}'),
1057
+ ('2c. Low degradation', f'degradation_score_low_{suffix}'),
1058
+ ('3. Applic. domain', f'applicability_domain_score_{suffix}'),
1059
+ ]))
1060
+
1061
+ score_available = data_score.get(f'score_available_{suffix}', True)
1062
+ out_folder = Path(f'{os.getcwd()}/PREDICT')
1063
+ out_folder.mkdir(exist_ok=True)
1064
+ suffix_title = '_'.join(suffix.split())
1065
+ paths = {'interpolation': '', 'boundary': ''}
1066
+ label_font_size = 8.928 # another 20% larger than the previous 7.44 pt
1067
+ value_font_size = 7.2 # another 20% larger than the previous 6 pt
1068
+
1069
+ for key,total_key,components in radars:
1070
+ labels = [label for label,_ in components]
1071
+ raw_values = [float(data_score.get(score_key,0) or 0) for _,score_key in components]
1072
+ flawed_score_key = f'flawed_mod_score_{suffix}'
1073
+ # The flawed-model component can be negative. Keep its bar pinned at zero,
1074
+ # while retaining the raw score for the value badge.
1075
+ values = [max(0.0,min(2.0,value)) for value in raw_values]
1076
+ display_values = [
1077
+ raw_value if score_key == flawed_score_key else value
1078
+ for (_,score_key),raw_value,value in zip(components,raw_values,values)
1079
+ ]
1080
+ # each bar coloured by its own 0-2 value with the score-card palette: red (<0.5),
1081
+ # orange (0.5-1), light blue (1-1.5), blue (>=1.5); grey when the score isn't
1082
+ # calibrated for this run (non-standard CV/test, see print_score())
1083
+ # flawed tests are colored differently: red (<=-1.5), orange (-1.5 to -1),
1084
+ # light blue (-1 to -0.5), blue (>-0.5)
1085
+ from robert.checkml_score import checkml_tier_color
1086
+ def bar_colour(value, is_flawed=False):
1087
+ if not score_available:
1088
+ return '#9e9e9e'
1089
+ if is_flawed:
1090
+ tier = (
1091
+ 'VERY STRONG' if value > -0.5 else
1092
+ 'STRONG' if value > -1 else
1093
+ 'WEAK' if value > -1.5 else
1094
+ 'VERY WEAK'
1095
+ )
1096
+ else:
1097
+ tier = 'VERY WEAK' if value < 0.5 else 'WEAK' if value < 1 else 'STRONG' if value < 1.5 else 'VERY STRONG'
1098
+ return checkml_tier_color(tier,'hex')
1099
+
1100
+ n = len(values)
1101
+ angles = np.linspace(0, 2*np.pi, n, endpoint=False)
1102
+ slot = 2*np.pi/n
1103
+ # figure inches = displayed px / 96, so font sizes in pt read as in the rest of the PDF
1104
+ fig = plt.figure(figsize=(self.RADAR_SIZE[0]/96, self.RADAR_SIZE[1]/96), dpi=300)
1105
+ # Use most of the original 270 x 215 canvas while leaving enough room for the
1106
+ # labels around the outer ring. Keeping the canvas size unchanged preserves the
1107
+ # PDF image aspect ratio and prevents object-fit from cropping the radar.
1108
+ # Same radar size in px as before (176 px tall); the bottom margin is larger to
1109
+ # fit the flawed-model sentence.
1110
+ ax = fig.add_axes([0.07, 0.175, 0.86, 0.733], polar=True)
1111
+ ax.set_theta_offset(np.pi/2)
1112
+ ax.set_theta_direction(-1)
1113
+ ax.set_facecolor('#fbfcfe')
1114
+ ax.set_ylim(0, 2.1)
1115
+ grid_color = '#b8c1cc'
1116
+ # Quiet reference rings keep attention on the bars and their value badges.
1117
+ ax.set_axisbelow(True)
1118
+ ax.set_yticks([0.5, 1, 1.5, 2.0])
1119
+ ax.set_yticklabels([])
1120
+ ax.yaxis.grid(True, color=grid_color, linewidth=0.45, linestyle='-')
1121
+ ax.set_xticks(angles)
1122
+ ax.set_xticklabels([])
1123
+ ax.xaxis.grid(False)
1124
+ # Black outlines separate adjacent bars and end at each bar's tip.
1125
+ ax.bar(angles, values, width=slot*0.62,
1126
+ color=[bar_colour(display_value, score_key == flawed_score_key)
1127
+ for (_,score_key),display_value in zip(components,display_values)],
1128
+ edgecolor='black', linewidth=0.5, zorder=2.5)
1129
+ # Radial dividers between sections: darker than the reference rings so each
1130
+ # section reads clearly, and the same weight as the outer circle so the
1131
+ # dividers and the circle look like one frame.
1132
+ frame_color = '#64748b'
1133
+ for edge in angles + slot/2:
1134
+ ax.plot([edge, edge], [0, 2.1], color=frame_color, linewidth=0.6, zorder=3)
1135
+ ax.spines['polar'].set_color(frame_color)
1136
+ ax.spines['polar'].set_linewidth(0.6)
1137
+ ax.spines['polar'].set_zorder(3)
1138
+ # Value badges use the same colored fill as their bars.
1139
+ for angle,value,display_value,(_,score_key) in zip(angles,values,display_values,components):
1140
+ color = bar_colour(display_value, score_key == flawed_score_key)
1141
+ # minimum radius of 0.65 so the badges of small bars (e.g. several 0.0) don't
1142
+ # pile up and overlap at the centre of the radar
1143
+ ax.text(angle, max(value - 0.18, 0.65), f'{display_value:.1f}', ha='center', va='center',
1144
+ fontsize=value_font_size, color='#0f172a', zorder=6,
1145
+ bbox=dict(boxstyle='round,pad=0.2', facecolor=color,
1146
+ edgecolor='black', linewidth=0.4))
1147
+ # component names around the circle, rotated along it (flipped on the bottom half
1148
+ # so they never read upside down); place each character along the arc so the
1149
+ # full label follows the circular edge instead of sitting on a straight baseline.
1150
+ fig.canvas.draw()
1151
+ renderer = fig.canvas.get_renderer()
1152
+ from matplotlib.font_manager import FontProperties
1153
+ label_font = FontProperties(size=label_font_size)
1154
+ label_radius = 2.38
1155
+ radius_px = ax.get_window_extent().width * 0.5 * label_radius / 2
1156
+ for label,angle in zip(labels,angles):
1157
+ char_widths = [
1158
+ renderer.get_text_width_height_descent(char, label_font, False)[0]
1159
+ for char in label
1160
+ ]
1161
+ arc_width = sum(char_widths) + max(len(label) - 1, 0) * 0.7
1162
+ offset = -arc_width / 2
1163
+ normalized_angle = angle % (2*np.pi)
1164
+ flip = np.pi/2 < normalized_angle < 3*np.pi/2
1165
+ direction = -1 if flip else 1
1166
+ for char,char_width in zip(label,char_widths):
1167
+ char_angle = angle + direction * (offset + char_width / 2) / radius_px
1168
+ rotation = -np.degrees(char_angle) + (180 if flip else 0)
1169
+ ax.text(char_angle, label_radius, char, ha='center', va='center',
1170
+ rotation=rotation, rotation_mode='anchor', fontsize=label_font_size,
1171
+ color='#1e293b')
1172
+ offset += char_width + 0.7
1173
+ if key == 'interpolation':
1174
+ # 1. Flawed models (VERIFY tests) as a sentence under the radar: it's a
1175
+ # penalty subtracted from the score (gradual, up to -2 per test)
1176
+ flawed_score = float(data_score.get(flawed_score_key,0) or 0)
1177
+ failed_tests = int(data_score.get(f'failed_tests_{suffix}',0) or 0)
1178
+ unclear_tests = int(data_score.get(f'unclear_tests_{suffix}',0) or 0)
1179
+ # Plain text (no coloured box), with only the penalty highlighted in red
1180
+ text_color, penalty_color = '#1e293b', '#c0392b'
1181
+ if flawed_score >= 0:
1182
+ parts = [('1. Flawed models: all tests passed, no penalty', text_color, 'normal')]
1183
+ else:
1184
+ # e.g. "1 failed, 2 unclear" - every test category that subtracts points
1185
+ counts = [f'{count} {label}' for count,label in ((failed_tests,'failed'),(unclear_tests,'unclear')) if count]
1186
+ # passed tests close to the threshold also subtract (gradual penalty)
1187
+ lead = ', '.join(counts) if counts else 'tests close to the thresholds'
1188
+ parts = [(f'1. Flawed models: {lead}, ', text_color, 'normal'),
1189
+ (f'{flawed_score:.1f} penalty', penalty_color, 'bold')]
1190
+ labels_flawed = [fig.text(0, 0.045, text, ha='left', va='center',
1191
+ fontsize=label_font_size, color=color, fontweight=weight)
1192
+ for text,color,weight in parts]
1193
+
1194
+ def flawed_widths():
1195
+ fig.canvas.draw()
1196
+ return [label.get_window_extent(renderer).width for label in labels_flawed]
1197
+
1198
+ # shrink the font until the sentence fits the image width (its length depends
1199
+ # on the number of failed tests and on the system font)
1200
+ max_width = fig.bbox.width * 0.96
1201
+ font_size = label_font_size
1202
+ widths = flawed_widths()
1203
+ while sum(widths) > max_width and font_size > 5:
1204
+ font_size -= 0.25
1205
+ for label in labels_flawed:
1206
+ label.set_fontsize(font_size)
1207
+ widths = flawed_widths()
1208
+ # place the pieces one after another, centred as a whole
1209
+ x_px = (fig.bbox.width - sum(widths)) / 2
1210
+ for label,width in zip(labels_flawed,widths):
1211
+ label.set_x(x_px / fig.bbox.width)
1212
+ x_px += width
1213
+ radar_path = out_folder / f'CheckML_radar_{key}{getattr(self,"model_suffix","")}_{suffix_title}.png'
1214
+ # Keep the original canvas ratio so the PDF's fixed-size image box cannot crop
1215
+ # the labels. The title is omitted so only the radar and component labels show.
1216
+ fig.savefig(radar_path, dpi=300)
1217
+ plt.close(fig)
1218
+ paths[key] = str(radar_path)
1219
+
1220
+ return paths['interpolation'],paths['boundary']
1221
+
1222
+
1223
+ SUMMARY_MODEL_NAMES = {
1224
+ 'RF': 'RandomForest', 'GB': 'GradientBoosting', 'NN': 'MLP',
1225
+ 'GP': 'GaussianProcess', 'ADAB': 'AdaBoost',
1226
+ }
1227
+ # report palette used by the summary page (same colours as the VERIFY bar chart and the
1228
+ # warning bullets used elsewhere in the report)
1229
+ SUMMARY_BLUE = '#1f77b4'
1230
+ SUMMARY_WARNING_STYLES = {
1231
+ # kind: (stripe colour, background tint, label colour)
1232
+ 'severe': ('#c56666', '#f7e6e6', '#9e3a3a'),
1233
+ 'moderate': ('#c5c57d', '#f5f5e6', '#6f6f2c'),
1234
+ 'none': ('#9ba5e3', '#eceefb', '#4a5596'),
1235
+ }
1236
+
1237
+ def _summary_score_style(self,score):
1238
+ '''
1239
+ Fill colour, text colour and rating of a 0-10 score - the same five tiers and colours
1240
+ as the score bars of Section A (see checkml_score.py)
1241
+ '''
1242
+ from robert.checkml_score import checkml_score_tier, checkml_tier_color
1243
+ if score is None:
1244
+ return '#9e9e9e','#666666','Not available'
1245
+ tier = checkml_score_tier(max(0,min(10,score)))
1246
+ return checkml_tier_color(tier,'hex'),checkml_tier_color(tier,'text_hex'),tier.title()
1247
+
1248
+
1249
+ def _summary_model_label(self,params_df,pred_type):
1250
+ '''Full scikit-learn name of the model (ROBERT short codes translated)'''
1251
+ model = str(params_df['model'][0]) if 'model' in params_df.columns else 'Not available'
1252
+ if model.upper() == 'MVL':
1253
+ return 'LinearRegression (MVL)'
1254
+ if model.upper() in ('RIDGE','LOGISTIC'):
1255
+ return {'RIDGE': 'Ridge', 'LOGISTIC': 'LogisticRegression'}[model.upper()]
1256
+ if model.upper() in self.SUMMARY_MODEL_NAMES:
1257
+ model_type = 'Regressor' if pred_type == 'reg' else 'Classifier'
1258
+ return f'{self.SUMMARY_MODEL_NAMES[model.upper()]}{model_type}'
1259
+ return model
1260
+
1261
+
1262
+ def print_summary_page(self,pred_type,data_score,warnings_dict,suffix,params_df):
1263
+ '''
1264
+ Results summary page (page 2): same content as the CheckML web summary sheet - evaluation
1265
+ setup, target distribution, hyperparameters, both scores and EVERY
1266
+ warning (the Section A box on page 1 may truncate moderate warnings with "..."), with
1267
+ each warning placed under the score it describes (Interpolation / Boundary robustness)
1268
+ '''
1269
+
1270
+ from html import escape
1271
+ from robert.utils import deserialize_model_params
1272
+
1273
+ navy, muted = self.SUMMARY_BLUE, '#555555'
1274
+ y_name = str(params_df['y'][0]) if 'y' in params_df.columns else ''
1275
+ names_col = str(params_df['names'][0]) if 'names' in params_df.columns else ''
1276
+
1277
+ # dataset information (from the database saved with the model, which has the Set column)
1278
+ dataset = pd.DataFrame()
1279
+ db_file = getattr(self,'report_db_file',None)
1280
+ if db_file and os.path.exists(db_file):
1281
+ try:
1282
+ dataset = pd.read_csv(db_file, encoding='utf-8')
1283
+ except Exception:
1284
+ dataset = pd.DataFrame()
1285
+ descriptors = []
1286
+ if 'X_descriptors' in params_df.columns:
1287
+ try:
1288
+ descriptors = json.loads(params_df['X_descriptors'][0])
1289
+ except (json.JSONDecodeError, TypeError):
1290
+ import ast
1291
+ try:
1292
+ descriptors = ast.literal_eval(params_df['X_descriptors'][0])
1293
+ except (ValueError, SyntaxError):
1294
+ descriptors = []
1295
+ set_txt = ''
1296
+ if 'Set' in dataset.columns:
1297
+ set_counts = dataset['Set'].value_counts()
1298
+ set_txt = ' | '.join(f'{name}: {count:,}' for name,count in set_counts.items())
1299
+
1300
+ # target distribution (classification labels restored with the saved class mapping)
1301
+ distribution = 'No target values available'
1302
+ if y_name in dataset.columns:
1303
+ if pred_type == 'clas':
1304
+ class_map = {}
1305
+ if 'class_mapping_reverse' in params_df.columns and pd.notna(params_df['class_mapping_reverse'][0]):
1306
+ try:
1307
+ class_map = {int(k): v for k,v in json.loads(params_df['class_mapping_reverse'][0]).items()}
1308
+ except (json.JSONDecodeError, TypeError, ValueError):
1309
+ class_map = {}
1310
+ counts = dataset[y_name].map(lambda v: class_map.get(int(v), v) if pd.notna(v) else v).value_counts()
1311
+ distribution = '; '.join(f'{label}: {count:,}' for label,count in counts.items())
1312
+ else:
1313
+ values = pd.to_numeric(dataset[y_name], errors='coerce').dropna()
1314
+ if not values.empty:
1315
+ distribution = (f'n = {len(values):,}; range = {values.min():.4g} to {values.max():.4g}; '
1316
+ f'mean = {values.mean():.4g}; SD = {values.std(ddof=0):.4g}')
1317
+
1318
+ # hyperparameters actually used by the model
1319
+ hyper_rows = ''
1320
+ if 'params' in params_df.columns:
1321
+ try:
1322
+ hyperparams = deserialize_model_params(params_df['params'][0])
1323
+ except Exception:
1324
+ hyperparams = {}
1325
+ if isinstance(hyperparams, dict):
1326
+ for name,value in hyperparams.items():
1327
+ value_txt = str(value)
1328
+ if len(value_txt) > 90:
1329
+ value_txt = value_txt[:87] + '...'
1330
+ hyper_rows += f'<tr><td>{escape(str(name))}</td><td>{escape(value_txt)}</td></tr>'
1331
+
1332
+ # no written verdict ("decent model", "weak model"...): it flipped on tiny score changes
1333
+ # (e.g. 6.9 vs 7.0), so the page relies on the scores and the warnings below instead
1334
+ severe_list = warnings_dict[f'severe_warnings_{suffix}']
1335
+ moderate_list = warnings_dict[f'moderate_warnings_{suffix}']
1336
+
1337
+ # score cards (same tier colours as Section A's score bars)
1338
+ def score_card(title,score,disabled=False):
1339
+ if disabled:
1340
+ return f'''<td style="width:50%; border:2px solid #b0b0b0; border-radius:9px; background:white; text-align:center; padding:10px 6px;">
1341
+ <div style="font-weight:bold; color:#222222; font-size:13px;">{title}</div>
1342
+ <div style="font-weight:bold; color:{muted}; font-size:12px; margin:22px 0;">Disabled for classification</div></td>'''
1343
+ fill,text_col,rating = self._summary_score_style(score)
1344
+ score_txt = f'{score:.1f}' if score is not None else 'N/A'
1345
+ return f'''<td style="width:50%; border:2px solid {fill}; border-radius:9px; background:{fill}22; text-align:center; padding:8px 6px;">
1346
+ <div style="font-weight:bold; color:#222222; font-size:13px;">{title}</div>
1347
+ <div style="font-weight:bold; color:{text_col}; font-size:30px; line-height:1.2;">{score_txt}</div>
1348
+ <div style="font-size:9px; color:{muted};">out of 10</div>
1349
+ <div style="font-weight:bold; color:{text_col}; font-size:11px; letter-spacing:0.5px;">{rating.upper()}</div></td>'''
1350
+
1351
+ interp_score = data_score.get(f'interp_score_{suffix}')
1352
+ extrap_score = data_score.get(f'extrap_score_{suffix}')
1353
+ # same as Section A: no number or tier when the score isn't calibrated for this run
1354
+ # (non-standard CV/test/split or user-defined test set, see print_score())
1355
+ if not data_score.get(f'score_available_{suffix}', True):
1356
+ interp_score = extrap_score = None
1357
+ cards = score_card('Interpolation',interp_score)
1358
+ cards += '<td style="width:12px; border:none;"></td>'
1359
+ cards += score_card('Boundary robustness<br><span style="font-size:10px; font-weight:normal;">(related to extrapolation)</span>',
1360
+ extrap_score,disabled=pred_type != 'reg')
1361
+
1362
+ # warnings, each one under the score it describes (all of them, never truncated)
1363
+ def warning_area(warning):
1364
+ text = warning.lower()
1365
+ # The ranking warning has no "extrapolation" in its description.
1366
+ # Its explicit boundary sub-section reference must keep it in the
1367
+ # right column after replacing the former generic boundary label.
1368
+ boundary_section = re.search(r'\bsections?\s+b\.[12][abc]\b|\bsection\s+b\.3,\s*right\b',text)
1369
+ is_boundary = 'boundary robustness' in text or 'extrapolat' in text or boundary_section is not None
1370
+ # a warning about both scores (i.e. "...in Interpolation and Boundary robustness")
1371
+ # goes in both columns
1372
+ if is_boundary and 'interpolation' in text:
1373
+ return ['interpolation','boundary']
1374
+ return ['boundary'] if is_boundary else ['interpolation']
1375
+
1376
+ groups = {'interpolation': [], 'boundary': []}
1377
+ for warning in severe_list:
1378
+ for area in warning_area(warning):
1379
+ groups[area].append(('Severe warning',warning,'severe'))
1380
+ for warning in moderate_list:
1381
+ for area in warning_area(warning):
1382
+ groups[area].append(('Moderate warning',warning,'moderate'))
1383
+
1384
+ def warning_cards(items,empty_txt):
1385
+ if not items:
1386
+ stripe,bg,label_col = self.SUMMARY_WARNING_STYLES['none']
1387
+ return f'''<div style="background:{bg}; border-left:4px solid {stripe}; border-radius:4px; padding:6px 8px; font-size:10px; color:{label_col};">{empty_txt}</div>'''
1388
+ cards_html = ''
1389
+ for kind,warning,style_key in items:
1390
+ stripe,bg,label_col = self.SUMMARY_WARNING_STYLES[style_key]
1391
+ # Keep the section pointers so readers can find the diagnostic
1392
+ # behind each warning, including the boundary sub-sections.
1393
+ cards_html += f'''<div style="background:{bg}; border-left:4px solid {stripe}; border-radius:4px; padding:4px 8px 5px 8px; margin-bottom:5px; color:#222222; page-break-inside:avoid;">
1394
+ <div style="font-size:8px; font-weight:bold; letter-spacing:0.3px; color:{label_col};">{kind.upper()}</div>
1395
+ <div style="font-size:10px; line-height:1.3;">{escape(warning)}</div></div>'''
1396
+ return cards_html
1397
+
1398
+ interp_col_html = warning_cards(groups['interpolation'],'No interpolation warnings detected.')
1399
+ if pred_type == 'reg':
1400
+ bound_col_html = warning_cards(groups['boundary'],'No boundary robustness warnings detected.')
1401
+ else:
1402
+ bound_col_html = f'<div style="font-size:10px; color:{muted};">Boundary robustness is not evaluated for classification.</div>'
1403
+
1404
+ section_title = lambda txt: f'<p style="font-weight:bold; color:{navy}; font-size:14px; margin:12px 0 5px 0;">{txt}</p>'
1405
+ problem_txt = 'Regression' if pred_type == 'reg' else 'Classification'
1406
+
1407
+ # CV-Test Split Diagnostic: this model's results (same as Section A) next to what each
1408
+ # status means for the sub-scores
1409
+ # (same fallback as section_a_callouts(): the packaged icons when args has no path_icons)
1410
+ path_icons = getattr(self.args, 'path_icons', None) or Path(__file__).resolve().parent / 'report'
1411
+ icon_dir = f'file:///{self._posix_uri(path_icons)}'
1412
+ metric_name, diag_missing, diag_rows = self.cv_test_diagnostic(data_score,suffix,pred_type)
1413
+ if diag_missing:
1414
+ diag_results = f'<div style="color:{muted};">Rerun PREDICT to calculate the missing full-data or partition CV metrics.</div>'
1415
+ else:
1416
+ diag_results = f'<div style="color:{muted}; margin-bottom:2px;">{metric_name} difference vs. full-data CV:</div>'
1417
+ for status, icon_file, foreground, label, value in diag_rows:
1418
+ diag_results += (f'<div style="color:{foreground}; margin-top:1px;">{self.diagnostic_icon(icon_dir,icon_file)} '
1419
+ f'<strong>{status}</strong> · {label}: {value}</div>')
1420
+ legend_rows = (
1421
+ ('checkml_pass.svg', '#236c32', 'Pass', 'this sub-score is reliable.'),
1422
+ ('checkml_unclear.svg', '#806000', 'Unclear', 'potentially unreliable sub-score, use it with caution '
1423
+ 'and further assess that aspect of your model with your own analyses.'),
1424
+ ('checkml_warning.svg', '#a02828', 'Warning', 'unreliable sub-score, do not use it and assess that '
1425
+ 'aspect of your model with your own analyses.'),
1426
+ )
1427
+ diag_legend = ''.join(
1428
+ f'<div style="margin-bottom:2px;">{self.diagnostic_icon(icon_dir,icon_file)} '
1429
+ f'<strong style="color:{foreground};">{status}:</strong> {text}</div>'
1430
+ for icon_file, foreground, status, text in legend_rows)
1431
+ diag_html = f'''
1432
+ {section_title('CV-Test Split Diagnostic')}
1433
+ <table style="width:100%; border-collapse:collapse; page-break-inside:avoid;"><tr>
1434
+ <td style="width:42%; vertical-align:top; padding:5px 8px; background:#f2f2f2; border:1px solid #c8c8c8; border-radius:4px; font-size:10px; line-height:1.3;">{diag_results}</td>
1435
+ <td style="width:12px; border:none;"></td>
1436
+ <td style="vertical-align:top; padding:2px 0; font-size:10px; line-height:1.3;">{diag_legend}
1437
+ <div style="color:{muted};">Effect of holding out 20% of the data as a test set. More
1438
+ <a href="https://robert.readthedocs.io/en/latest/Report/score.html#cv-test-split-diagnostic" style="color:{navy};">details here</a>.</div></td>
1439
+ </tr></table>'''
1440
+
1441
+ # model hyperparameters, right after the evaluation setup they belong to
1442
+ hyper_html = ''
1443
+ if hyper_rows:
1444
+ # Leave room for the warning guidance on page 2 when classifiers have many parameters.
1445
+ hyper_line_style = ' line-height:1.2;' if pred_type == 'clas' else ''
1446
+ hyper_html = f'''
1447
+ {section_title('Model hyperparameters')}
1448
+ <table style="width:100%; border-collapse:collapse; font-size:9.5px;{hyper_line_style}">
1449
+ <tr style="background:{navy}; color:white;"><th style="text-align:left; padding:3px 6px; width:40%;">Parameter</th><th style="text-align:left; padding:3px 6px;">Value</th></tr>
1450
+ {hyper_rows.replace('<td>', '<td style="border:1px solid #c8c8c8; padding:2px 6px;">')}
1451
+ </table>'''
1452
+ dataset_name = os.path.basename(str(getattr(self.args,'csv_name','')))
1453
+
1454
+ summary = f'''
1455
+ <div style="page-break-inside:avoid;">
1456
+ <div style="background:{navy}; color:white; border-radius:9px; padding:10px 14px; margin-top:4px;">
1457
+ <div style="font-size:19px; font-weight:bold;">Results summary</div>
1458
+ <div style="font-size:10px;">All scores and warnings of this report at a glance. Details of each item are in the sections that follow.</div>
1459
+ </div>
1460
+
1461
+ {section_title('Evaluation setup')}
1462
+ <div style="background:#eef4fa; border-left:4px solid {navy}; border-radius:4px; padding:7px 14px; font-size:11px; line-height:1.6;">
1463
+ <b>Dataset:</b> {escape(dataset_name) or 'Not available'}<br>
1464
+ <b>Datapoints:</b> {len(dataset):,}{f' ({escape(set_txt)})' if set_txt else ''} | <b>Descriptors:</b> {len(descriptors):,}<br>
1465
+ <b>Target:</b> {escape(y_name) or 'Not available'} | <b>Name / ID:</b> {escape(names_col) or 'Not available'} | <b>Problem type:</b> {problem_txt}<br>
1466
+ <b>Model:</b> {escape(self._summary_model_label(params_df,pred_type))}
1467
+ </div>
1468
+ {hyper_html}
1469
+ {section_title('Target distribution')}
1470
+ <div style="border:1px solid #c8c8c8; border-radius:4px; padding:5px 10px; font-size:11px; color:{muted};">{escape(distribution)}</div>
1471
+
1472
+ {section_title('Scores')}
1473
+ <table style="width:100%; border-collapse:separate; border-spacing:0;"><tr>{cards}</tr></table>
1474
+
1475
+ {section_title('Warnings')}
1476
+ <table style="width:100%; border-collapse:collapse;"><tr>
1477
+ <td style="width:50%; vertical-align:top; padding-right:6px;">
1478
+ <div style="font-weight:bold; color:{navy}; font-size:11px; margin-bottom:4px;">Interpolation warnings</div>{interp_col_html}</td>
1479
+ <td style="width:50%; vertical-align:top; padding-left:6px;">
1480
+ <div style="font-weight:bold; color:{navy}; font-size:11px; margin-bottom:4px;">Boundary robustness warnings</div>{bound_col_html}</td>
1481
+ </tr></table>
1482
+ <p style="margin:20px 0 0; font-size:10px; line-height:1.4; color:{muted};">
1483
+ For more information about the warnings and suggestions to fix them, please check the
1484
+ <a href="https://robert.readthedocs.io/en/latest/Report/score.html#list-of-warnings" style="color:{navy};">CheckML documentation</a>.
1485
+ </p>
1486
+ {diag_html}
1487
+ </div>'''
1488
+
1489
+ summary += '<p style="page-break-after: always;"></p>'
1490
+ return summary
1491
+
1492
+
1493
+ def get_warning_params(self):
1494
+ '''
1495
+ Load spacing, colors, and line and table formats
1496
+ '''
1497
+
1498
+ space = '&nbsp;'
1499
+ color_dict = {
1500
+ 'red': '#c56666',
1501
+ 'yellow': '#c5c57d',
1502
+ 'blue': '#9ba5e3'
1503
+ }
1504
+ # explicit, equal, small top/bottom margins (rather than relying on the browser's
1505
+ # default ~12px <p> margin collapsing against a negative margin-bottom) so consecutive
1506
+ # warning lines pack predictably tight, instead of depending on margin-collapsing
1507
+ # arithmetic that's easy to get wrong when tuning spacing
1508
+ style_lines = '<p style="font-size: 11px; margin: 2px 0;">'
1509
+
1510
+ warnings_dat = ''
1511
+
1512
+ return space,color_dict,style_lines,warnings_dat
1513
+
1514
+
1515
+ def analyze_warnings(self,data_score,suffix,warnings_dict,pred_type):
1516
+ '''
1517
+ Build severity-separated warning lists, ordered by report section as in the documentation.
1518
+ Warnings without section references come first within each severity group.
1519
+ '''
1520
+
1521
+ severe = warnings_dict[f'severe_warnings_{suffix}']
1522
+ moderate = warnings_dict[f'moderate_warnings_{suffix}']
1523
+
1524
+ # hyperparameters given as the integer 1 where scikit-learn also accepts the fraction 1.0
1525
+ # (one sample/feature instead of all of them) - a likely input error that can make the
1526
+ # predictions nearly constant (see validate_params() in checkml.py)
1527
+ for param in warnings_dict.get('ambiguous_params', []):
1528
+ moderate.append(f'{param} = 1 (integer) means ONE sample/feature in scikit-learn, use 1.0 if all of them were intended (Section H)')
1529
+
1530
+ # tests from flawed models
1531
+ if data_score[f'flawed_mod_score_{suffix}'] < 0:
1532
+ if data_score[f'failed_tests_{suffix}'] > 0:
1533
+ severe.append('Failing required tests (Section B.1)')
1534
+ else:
1535
+ # also shown when every test PASSED but one of them is within the 30-45%
1536
+ # degradation range, which still gets a small penalty (see get_verify_scores())
1537
+ moderate.append('Some tests are close to the thresholds (Section B.1)')
1538
+
1539
+ # train-vs-validation and CV-vs-test gaps at 0/2 both point to the same underlying
1540
+ # problem an inexperienced user is unlikely to recognize from the number alone: the
1541
+ # model looks fine on the data it was fit to, but that doesn't carry over - i.e.
1542
+ # overfitting. Severe (not moderate) because this directly undermines the model's main
1543
+ # purpose (predicting new points), regardless of how good the raw CV/test numbers look
1544
+ if data_score.get(f'train_val_gap_score_{suffix}', 1) == 0:
1545
+ severe.append('Overfitting observed between train and validation (Section B.4)')
1546
+ if pred_type == 'reg':
1547
+ diff_test_zero = data_score.get(f'diff_scaled_rmse_score_{suffix}', 1) == 0
1548
+ else:
1549
+ diff_test_zero = data_score.get(f'diff_mcc_score_{suffix}', 1) == 0
1550
+ if diff_test_zero:
1551
+ severe.append('Inconsistent results between CV and test (Section B.5)')
1552
+
1553
+ # unstable predictions across repeated CV runs: the prediction stability score (item 6)
1554
+ # is 0/2, for both regression and classification
1555
+ if data_score.get(f'cv_sd_score_{suffix}', 1) <= 0:
1556
+ moderate.append('Imprecise predictions (Section B.6)')
1557
+ if pred_type == 'reg':
1558
+ # flat or unordered predictions inside one half of the y range (Spearman <= 0.05,
1559
+ # i.e. at least half of that check's maximum penalty - see half_spearman_penalty())
1560
+ for half, zone in (('low', 'lower'), ('high', 'upper')):
1561
+ if data_score.get(f'spearman_50_{half}_penalty_{suffix}', 0) <= -1:
1562
+ moderate.append(f'Predictions do not rank the points in the {zone} half of the y range (Section B.6)')
1563
+
1564
+ # weak CV / test-set predictions on their own (0/2, Sections B.2/B.3) - distinct from
1565
+ # the overfitting checks above, which compare two numbers against each other; these
1566
+ # flag a single score that's just low
1567
+ if data_score.get(f'cv_score_combined_{suffix}', 1) == 0:
1568
+ moderate.append('Weak CV predictions (Section B.2)')
1569
+ if data_score.get(f'test_score_combined_{suffix}', 1) == 0:
1570
+ moderate.append('Weak test-set predictions (Section B.3)')
1571
+
1572
+ # low-relevance descriptor found in PFI and/or SHAP - suggests the model might improve
1573
+ # by trimming near-irrelevant descriptors rather than keeping them all (see
1574
+ # LOW_RELEVANCE_RELATIVE_THRESHOLD/LOW_RELEVANCE_ABSOLUTE_THRESHOLD above)
1575
+ if warnings_dict.get(f'low_relevance_descp_{suffix}', False):
1576
+ moderate.append('Low-relevance descriptor(s) detected, try removing them (Section D)')
1577
+
1578
+ # bimodal y-values and/or a failed VERIFY cluster test both hint the response might
1579
+ # really be two distinct groups rather than one continuous variable - classification
1580
+ # could describe the data better than regression here (regression only: the cluster
1581
+ # test is N/A for classification, and "bimodal" only means something for a continuous y)
1582
+ if pred_type == 'reg' and (warnings_dict.get(f'bimodal_y_{suffix}', False) or warnings_dict.get(f'cluster_test_failed_{suffix}', False)):
1583
+ moderate.append('Response may have two separate groups, classification might fit better (Section C)')
1584
+
1585
+ # Boundary robustness / extrapolation (regression only - not defined for classification)
1586
+ if pred_type == 'reg':
1587
+ # shown first in the Boundary robustness group and regardless of the boundary
1588
+ # metrics: a tree-based model can score well on one split's edges and still be
1589
+ # structurally unable to predict y values outside the training range
1590
+ # tree-based and nearest-neighbour models (see extrapolation_limitation())
1591
+ from robert.report_utils import extrapolation_limitation
1592
+ limitation = extrapolation_limitation(getattr(self, 'report_model_name', ''))
1593
+ if limitation:
1594
+ severe.append(f'{limitation[0]} algorithm, not designed to extrapolate outside the training range')
1595
+
1596
+ score_ad = data_score.get(f'applicability_domain_score_{suffix}')
1597
+ if score_ad is not None and score_ad < 1.0:
1598
+ moderate.append('Poor extrapolation to descriptors very different from training (Section B.3)')
1599
+
1600
+ for side,zone_txt,section_ref in (
1601
+ ('high','the upper zone','Section B.1'),
1602
+ ('low','the lower zone','Section B.2'),
1603
+ ):
1604
+ # Match the displayed 0-4 total in boundary_score_sections(),
1605
+ # not just the 0-2 predictions component. Unknown totals should
1606
+ # not introduce warnings into incomplete/legacy report data.
1607
+ components = [data_score.get(f'{key}_{suffix}') for key in (
1608
+ f'sorted_cv_{side}_score', f'spearman_score_{side}', f'degradation_score_{side}',
1609
+ )]
1610
+ if any(value is not None for value in components) and sum(value or 0 for value in components) < 2.0:
1611
+ moderate.append(f'Difficult to extrapolate new predictions in {zone_txt} ({section_ref})')
1612
+
1613
+ # simpler MVL model as good as this one: from Section F when several models were
1614
+ # screened (MVL included), otherwise from VERIFY's MVL baseline comparison (Section B.1)
1615
+ # (classification: logistic regression, ROBERT's LOGISTIC, instead of MVL)
1616
+ base_txt,base_code = ('MVL','MVL') if pred_type == 'reg' else ('logistic regression','LOGISTIC')
1617
+ mvl_warning = self._mvl_screening_warning(suffix,pred_type)
1618
+ if mvl_warning is None:
1619
+ mvl_status = warnings_dict.get(f'mvl_baseline_{suffix}')
1620
+ if mvl_status == 'similar':
1621
+ mvl_warning = f'A simpler {base_txt} model performs similarly (Section B.1), consider trying {base_code} with the same descriptors'
1622
+ elif mvl_status == 'baseline_better':
1623
+ mvl_warning = f'A simpler {base_txt} model performs better (Section B.1), consider trying {base_code} with the same descriptors'
1624
+ if mvl_warning:
1625
+ moderate.append(mvl_warning)
1626
+
1627
+ # y distribution (existing)
1628
+ if 'WARNING! Your data is not uniform' in warnings_dict[f'y_dist_info_{suffix}']:
1629
+ if pred_type == 'reg':
1630
+ moderate.append('Uneven y distribution (Section C)')
1631
+ elif pred_type == 'clas': # it's severe in clasification
1632
+ severe.append('Very uneven class distribution (Section C)')
1633
+ elif 'WARNING! Your data is slightly not uniform' in warnings_dict[f'y_dist_info_{suffix}']:
1634
+ if pred_type == 'reg':
1635
+ moderate.append('Slightly uneven y distribution (Section C)')
1636
+ elif pred_type == 'clas':
1637
+ moderate.append('Uneven class distribution (Section C)')
1638
+
1639
+ # feature correlation (existing)
1640
+ if 'WARNING! High correlations' in warnings_dict[f'pearson_info_{suffix}']:
1641
+ moderate.append('Highly correlated features (Section D)')
1642
+ elif 'WARNING! Noticeable correlations' in warnings_dict[f'pearson_info_{suffix}']:
1643
+ moderate.append('Moderately correlated features (Section D)')
1644
+
1645
+ # outliers - existing check (one very extreme point, > 6.5 SD, ~99.9% CI) plus a new,
1646
+ # separate check for too many outliers overall (> 5% of the dataset), regardless of
1647
+ # how extreme any single one is
1648
+ if pred_type == 'reg':
1649
+ if warnings_dict[f'max_sd_{suffix}'] > 6.5:
1650
+ moderate.append('Potential "faulty" outliers (Section E)')
1651
+ if warnings_dict.get(f'outlier_pct_{suffix}', 0) > 5:
1652
+ moderate.append('More than 5% of points are outliers, check and explain them (Section E)')
1653
+
1654
+ severe.sort(key=_warning_section_key)
1655
+ moderate.sort(key=_warning_section_key)
1656
+ return warnings_dict
1657
+
1658
+
1659
+ # an MVL within this fraction of the chosen model's error in the model screening counts as
1660
+ # "similar" (same tolerance as VERIFY's MVL baseline comparison, thres_mvl_baseline)
1661
+ MVL_SCREENING_TOLERANCE = 0.15
1662
+
1663
+ def _mvl_screening_warning(self,suffix,pred_type='reg'):
1664
+ '''
1665
+ When the linear baseline (MVL, or LOGISTIC for classification) was screened together
1666
+ with other models (Section F), compares it with the model of this report: with
1667
+ --all_models, through their Interpolation/Boundary robustness scores; otherwise,
1668
+ through GENERATE's combined error. Returns the warning text, '' when the baseline is
1669
+ clearly worse (no warning), or None when Section F has no baseline to compare with
1670
+ (then VERIFY's baseline comparison is used instead)
1671
+ '''
1672
+
1673
+ from robert.verify import _is_linear_model, linear_baseline_code
1674
+
1675
+ base_code,_ = linear_baseline_code(pred_type)
1676
+ base_txt = 'MVL' if pred_type == 'reg' else 'logistic regression'
1677
+ model_name = str(getattr(self, 'report_model_name', '') or '')
1678
+ if not model_name or _is_linear_model(model_name):
1679
+ return None
1680
+
1681
+ # --all_models: compare the final CheckML scores
1682
+ scores = getattr(self, 'model_scores', {}).get(suffix, {})
1683
+ current = getattr(self, 'model_suffix', '')[1:] or model_name
1684
+ mvl_key = next((key for key in scores if str(key).upper() == base_code), None)
1685
+ if mvl_key is not None and current in scores:
1686
+ mvl_scores,cur_scores = scores[mvl_key],scores[current]
1687
+ better_in = []
1688
+ if mvl_scores[0] is not None and cur_scores[0] is not None and mvl_scores[0] >= cur_scores[0]:
1689
+ better_in.append('Interpolation')
1690
+ # Boundary robustness only exists in regression (it's 0 for every classifier)
1691
+ if (pred_type == 'reg' and mvl_scores[1] is not None and cur_scores[1] is not None
1692
+ and mvl_scores[1] >= cur_scores[1]):
1693
+ better_in.append('Boundary robustness')
1694
+ if not better_in:
1695
+ return ''
1696
+ return f'A simpler {base_txt} model scores as high or higher in {" and ".join(better_in)} (Section F)'
1697
+
1698
+ # default mode: GENERATE's combined error of each screened model
1699
+ raw_dir = Path(f'{os.getcwd()}/GENERATE/Raw_data/{"_".join(suffix.split())}')
1700
+ error_type = str(getattr(self.args, 'error_type', 'rmse')).lower()
1701
+ model_errors = {}
1702
+ for csv_file in glob.glob(str(raw_dir / '*.csv')):
1703
+ if '_db' in os.path.basename(csv_file):
1704
+ continue
1705
+ try:
1706
+ params_df = pd.read_csv(csv_file, encoding='utf-8')
1707
+ model_errors[str(params_df['model'][0]).upper()] = float(params_df[f'combined_{error_type}'][0])
1708
+ except (KeyError, IndexError, ValueError, pd.errors.EmptyDataError):
1709
+ continue
1710
+ if base_code not in model_errors or model_name.upper() not in model_errors:
1711
+ return None
1712
+ mvl_err,cur_err = model_errors[base_code],model_errors[model_name.upper()]
1713
+ if error_type in ['mae','rmse']:
1714
+ similar_or_better = mvl_err <= (1+self.MVL_SCREENING_TOLERANCE)*cur_err
1715
+ else:
1716
+ similar_or_better = mvl_err >= cur_err - self.MVL_SCREENING_TOLERANCE*abs(cur_err)
1717
+ if not similar_or_better:
1718
+ return ''
1719
+ return f'A simpler {base_txt} model has a similar or lower error in the model screening (Section F)'
1720
+
1721
+
1722
+ def get_warning_lines(self,pred_type,dat_verify=None):
1723
+ '''
1724
+ Gather the lines from PREDICT (and VERIFY, for the cluster-test check) where the
1725
+ potential warnings are printed
1726
+ '''
1727
+
1728
+ warnings_dict = {}
1729
+ for suf_key in ('No PFI','PFI'):
1730
+ warnings_dict[f'bimodal_y_{suf_key}'] = False
1731
+ warnings_dict[f'outlier_pct_{suf_key}'] = 0.0
1732
+ warnings_dict[f'low_relevance_descp_{suf_key}'] = False
1733
+
1734
+ # get lines with warnings from PREDICT
1735
+ file_pred = f'{os.getcwd()}/PREDICT/PREDICT{self.model_suffix}_data.dat'
1736
+ with open(file_pred, 'r', encoding='utf-8') as datfile:
1737
+ lines = datfile.readlines()
1738
+ pfi_section_pearson = False # to get both No PFI and PFI information
1739
+ pfi_section_outlier = False
1740
+ pfi_section_pfi = False
1741
+ pfi_section_shap = False
1742
+ # the bimodal marker line only appears conditionally (unlike Pearson/y-dist/PFI/
1743
+ # SHAP/outliers, which always print something) - a plain "first vs second
1744
+ # occurrence" toggle would misattribute it to No PFI if it only fires for PFI (or
1745
+ # vice versa), so track which suffix we're in via the always-present y-dist marker
1746
+ # instead, and just read that state when (if) the bimodal line shows up
1747
+ y_dist_suffix = 'No PFI'
1748
+ seen_first_y_dist = False
1749
+ for i,line in enumerate(lines):
1750
+ if 'Ideally, variables should show low' in line and not pfi_section_pearson:
1751
+ warnings_dict['pearson_info_No PFI'] = lines[i+1][6:]
1752
+ pfi_section_pearson = True # the next line found will correspond to the PFI section
1753
+ elif 'Ideally, variables should show low' in line and pfi_section_pearson:
1754
+ warnings_dict['pearson_info_PFI'] = lines[i+1][6:]
1755
+
1756
+ if 'Ideally, the number of datapoints in' in line:
1757
+ if seen_first_y_dist:
1758
+ y_dist_suffix = 'PFI'
1759
+ warnings_dict[f'y_dist_info_{y_dist_suffix}'] = lines[i+2][6:]
1760
+ seen_first_y_dist = True
1761
+
1762
+ if 'WARNING! Your data seems to have two separate y-value groups' in line:
1763
+ warnings_dict[f'bimodal_y_{y_dist_suffix}'] = True
1764
+
1765
+ # PFI relative importance - flags a descriptor other than the top one whose
1766
+ # influence is negligible (< 4% of the top descriptor's, or < 0.05 in absolute
1767
+ # terms) once "PFI plot saved" is found, its descriptor lines are all
1768
+ # "- {desc} = {value} +- {sd}" until the next blank/section line (see
1769
+ # PFI_plot() in utils.py) - sorted descending, so the first value is the max
1770
+ if 'PFI plot saved' in line and not pfi_section_pfi:
1771
+ warnings_dict['low_relevance_descp_No PFI'] = _has_low_relevance_descp(lines,i)
1772
+ pfi_section_pfi = True
1773
+ elif 'PFI plot saved' in line and pfi_section_pfi:
1774
+ warnings_dict['low_relevance_descp_PFI'] = _has_low_relevance_descp(lines,i)
1775
+
1776
+ # SHAP relative importance - same idea, using max(|min|,|max|) per descriptor
1777
+ # as the magnitude proxy (see shap_analysis() in utils.py, "- {desc} = min:
1778
+ # {min}, max: {max}" lines, also sorted descending by that same magnitude)
1779
+ if 'SHAP plot saved' in line and not pfi_section_shap:
1780
+ if _has_low_relevance_descp(lines,i,shap=True):
1781
+ warnings_dict['low_relevance_descp_No PFI'] = True
1782
+ pfi_section_shap = True
1783
+ elif 'SHAP plot saved' in line and pfi_section_shap:
1784
+ if _has_low_relevance_descp(lines,i,shap=True):
1785
+ warnings_dict['low_relevance_descp_PFI'] = True
1786
+
1787
+ if pred_type == 'reg':
1788
+ if 'Outliers plot saved' in line and not pfi_section_outlier:
1789
+ max_SD, outlier_pct = _scan_outlier_block(lines,i)
1790
+ warnings_dict['max_sd_No PFI'] = max_SD
1791
+ warnings_dict['outlier_pct_No PFI'] = outlier_pct
1792
+ pfi_section_outlier = True
1793
+ elif 'Outliers plot saved' in line and pfi_section_outlier:
1794
+ max_SD, outlier_pct = _scan_outlier_block(lines,i)
1795
+ warnings_dict['max_sd_PFI'] = max_SD
1796
+ warnings_dict['outlier_pct_PFI'] = outlier_pct
1797
+
1798
+ # VERIFY's cluster test (regression only - N/A for classification, see
1799
+ # cluster_test() in verify.py) is the 4th of 4 fixed-order flawed-model tests
1800
+ # (y_mean, y_shuffle, onehot, cluster) printed right after the "Original {RMSE/MCC}
1801
+ # (" line - same fixed relative position get_verify_scores() relies on in
1802
+ # report_utils.py (dat_verify[i+4])
1803
+ for suf_key in ('No PFI','PFI'):
1804
+ warnings_dict[f'cluster_test_failed_{suf_key}'] = False
1805
+ if pred_type == 'reg' and dat_verify:
1806
+ error_keyword = 'RMSE'
1807
+ active_suffix = None
1808
+ for i,line in enumerate(dat_verify):
1809
+ if '------- ' in line and '(No PFI)' in line:
1810
+ active_suffix = 'No PFI'
1811
+ elif '------- ' in line and 'with PFI' in line:
1812
+ active_suffix = 'PFI'
1813
+ if active_suffix and f"Original {error_keyword} (" in line and i+4 < len(dat_verify):
1814
+ cluster_line = dat_verify[i+4]
1815
+ if 'cluster' in cluster_line and 'FAILED' in cluster_line:
1816
+ warnings_dict[f'cluster_test_failed_{active_suffix}'] = True
1817
+
1818
+ # ambiguous integer hyperparameters flagged by CHECKML (i.e. max_samples = 1 meaning ONE
1819
+ # sample instead of all of them, see validate_params() in checkml.py)
1820
+ warnings_dict['ambiguous_params'] = []
1821
+ checkml_log = Path(f'{os.getcwd()}/CHECKML/CHECKML_data.dat')
1822
+ if checkml_log.exists():
1823
+ for line in checkml_log.read_text(encoding='utf-8', errors='replace').splitlines():
1824
+ if 'WARNING! Ambiguous hyperparameter:' in line:
1825
+ param = line.split('Ambiguous hyperparameter:')[1].split('=')[0].strip()
1826
+ if param and param not in warnings_dict['ambiguous_params']:
1827
+ warnings_dict['ambiguous_params'].append(param)
1828
+
1829
+ # VERIFY's unscored MVL baseline comparison (see mvl_baseline_test() in verify.py),
1830
+ # logged after the Sorted CV line: SIMILAR / MVL_BETTER trigger a warning
1831
+ for suf_key in ('No PFI','PFI'):
1832
+ warnings_dict[f'mvl_baseline_{suf_key}'] = None
1833
+ active_suffix = None
1834
+ for line in (dat_verify or []):
1835
+ if '------- ' in line and '(No PFI)' in line:
1836
+ active_suffix = 'No PFI'
1837
+ elif '------- ' in line and 'with PFI' in line:
1838
+ active_suffix = 'PFI'
1839
+ # "MVL baseline" (regression) or "Logistic baseline" (classification)
1840
+ if active_suffix and 'baseline (not scored):' in line:
1841
+ status = line.split('baseline (not scored):')[1].split(',')[0].strip().lower()
1842
+ warnings_dict[f'mvl_baseline_{active_suffix}'] = status
1843
+
1844
+ return warnings_dict
1845
+
1846
+
1847
+ def print_line_warning(self,message,style_lines,color,space):
1848
+ '''
1849
+ Add line with warning
1850
+ '''
1851
+
1852
+ return f'''
1853
+ {style_lines}<span style='font-size:15px; color: {color};'>{space}&#9673;</span>
1854
+ {space}{message}</p>'''
1855
+
1856
+
1857
+ def print_adv_anal(self,pred_type,data_score,suffix,suffix_title):
1858
+ """
1859
+ Generates the advanced score analysis section (left = Interpolation, right = Boundary robustness)
1860
+ """
1861
+
1862
+ adv_score_dat = ''
1863
+
1864
+ adv_score_dat += self.module_lines('adv_anal',adv_score_dat,pred_type=pred_type)
1865
+
1866
+ # Section B is a breakdown of the score computed in Section A - when there's no standard
1867
+ # CV/test split to calibrate it (already noted in Section A, no need to repeat it here),
1868
+ # each sub-metric badge below shows a grayed-out "N/A" version instead of a colored 0-2
1869
+ # bar (see score_badge_2() in report_utils.py), but the real underlying metrics, graphs
1870
+ # and any warnings they trigger (see analyze_warnings(), not gated on score_available)
1871
+ # are still shown as usual
1872
+
1873
+ # Regression columns flow independently so each side's plots follow its own text.
1874
+ # Classification still uses row pairing because it has no Boundary robustness column.
1875
+ if pred_type == 'reg':
1876
+ interp_rows = [
1877
+ adv_flawed(suffix,data_score,'',pred_type),
1878
+ adv_predict(self,suffix,data_score,'',pred_type),
1879
+ adv_test(self,suffix,data_score,'',pred_type),
1880
+ adv_train_val_gap(self,suffix,data_score,''),
1881
+ adv_diff_test(self,suffix,data_score,'',pred_type),
1882
+ ]
1883
+ interp_stability = adv_cv_sd(self,suffix,data_score,'')
1884
+ interp_stability = interp_stability.replace(
1885
+ 'margin-top: 20px;', 'margin-top: 0px;', 1
1886
+ )
1887
+
1888
+ bound_rows = (
1889
+ adv_sorted_cv_high(self,suffix,data_score,self.spacing_PFI)
1890
+ + adv_sorted_cv_low(self,suffix,data_score,self.spacing_PFI)
1891
+ + [adv_applicability_domain(self,suffix,data_score,self.spacing_PFI)]
1892
+ )
1893
+
1894
+ else:
1895
+ # classification: Boundary robustness isn't defined for a discrete MCC-based model
1896
+ # (no Low/High/degradation/applicability-domain analysis - see print_score()), so
1897
+ # only the Interpolation column is shown. Interpolation items 4 (train vs
1898
+ # validation gap) and 6 (prediction stability) are defined for classification too -
1899
+ # see the 'clas' branch in get_predict_scores() - so the row structure/order now
1900
+ # matches regression's exactly (5 rows)
1901
+ interp_rows = [
1902
+ adv_flawed(suffix,data_score,'',pred_type),
1903
+ adv_predict(self,suffix,data_score,'',pred_type),
1904
+ adv_test(self,suffix,data_score,'',pred_type),
1905
+ adv_train_val_gap(self,suffix,data_score,'',pred_type),
1906
+ adv_diff_test(self,suffix,data_score,'',pred_type) + adv_cv_sd(self,suffix,data_score,'',pred_type),
1907
+ ]
1908
+
1909
+ bound_rows = []
1910
+
1911
+ # The saved PNGs keep their in-image title (matplotlib plt.text) - every height
1912
+ # below is deliberately the image's OWN plot-only height at 270px width (title
1913
+ # excluded), which is LESS than what the full titled image needs, so
1914
+ # object-fit:cover (anchored bottom, see print_img_tag) crops exactly the title strip
1915
+ # off the top of each one and nothing else. Each image type has a very slightly
1916
+ # different aspect ratio (VERIFY_tests' bar chart especially, and Williams has one
1917
+ # fewer legend entry than the others), so this only works if every declared height
1918
+ # matches its own image type - reusing one height for images with a different actual
1919
+ # aspect ratio brings back a visible (partial or full) title, or crops into the plot
1920
+ verify_height = 228 if pred_type == 'reg' else 232
1921
+
1922
+ if pred_type == 'reg':
1923
+ interp_tag1 = self.print_img_tag(self.find_img('VERIFY_tests','VERIFY',suffix_title),verify_height)
1924
+ bound_tag1 = self.print_img_tag(self.find_img('Results_boundary_high','PREDICT',suffix_title),218)
1925
+ # item 3 applicability domain gets both plots stacked in the boundary robustness (right)
1926
+ # column: the actual-vs-predicted scatter (ties to the Scaled RMSE score) on top, the
1927
+ # Williams plot (leverage vs standardized residual, flags which points are
1928
+ # structurally suspicious) below it
1929
+ williams_tag = self.print_img_tag(self.find_img('Results_boundary_williams','PREDICT',suffix_title),219)
1930
+ ad_tag = self.print_img_tag(self.find_img('Results_boundary_ad','PREDICT',suffix_title),218)
1931
+ cv_variability_tag = self.print_img_tag(self.find_img('CV_variability','PREDICT',suffix_title,exclude=['CV_variability_boundary','CV_variability_cv']),218)
1932
+ # item 6's 2nd SD plot: out-of-fold CV predictions in train+validation (vs the
1933
+ # existing cv_variability_tag, which is the test set) - see graph_reg(sd_set='train')
1934
+ cv_variability_cv_tag = self.print_img_tag(self.find_img('CV_variability_cv','PREDICT',suffix_title),218)
1935
+ low_tag = self.print_img_tag(
1936
+ self.find_img('Results_boundary_low','PREDICT',suffix_title),218
1937
+ )
1938
+ img_after_row = {}
1939
+ else:
1940
+ interp_tag1 = self.print_img_tag(self.find_img('VERIFY_tests','VERIFY',suffix_title),verify_height)
1941
+ img_after_row = {0: self.print_img_row_indent(interp_tag1,'',13)}
1942
+
1943
+ if pred_type == 'reg':
1944
+ # Render regression as independent per-page columns. Each side now owns its text
1945
+ # and plots in normal flow, so a taller text block or graph on one side cannot
1946
+ # leave a gap in the other side.
1947
+ left_heading = (
1948
+ '<p style="text-align:justify; font-weight:bold; font-size:12px; '
1949
+ 'margin-top:-33px; margin-bottom:5px;">Interpolation</p>'
1950
+ )
1951
+ right_heading = (
1952
+ '<p style="text-align:justify; font-weight:bold; font-size:12px; '
1953
+ 'margin-top:-33px; margin-bottom:5px;">'
1954
+ f'{self.spacing_PFI}Boundary robustness</p>'
1955
+ )
1956
+
1957
+ def section_image(tag,margin_top=10):
1958
+ if not tag:
1959
+ return ''
1960
+ return f'<p style="margin-top:{margin_top}px; margin-bottom:0;">{tag}</p>'
1961
+
1962
+ left_page1 = (
1963
+ left_heading + interp_rows[0] + section_image(interp_tag1,13) +
1964
+ interp_rows[1] + interp_rows[2] + interp_rows[3] + interp_rows[4]
1965
+ )
1966
+ right_page1 = (
1967
+ right_heading + bound_rows[0] + section_image(bound_tag1,13) +
1968
+ bound_rows[1] + bound_rows[2] +
1969
+ bound_rows[3].replace('margin-top:0;', 'margin-top:20px;', 1) +
1970
+ # 2a's Bottom 20% plot stays on the same page as its 2a text
1971
+ section_image(low_tag,13)
1972
+ )
1973
+
1974
+ first_page_rule = (
1975
+ '<span aria-hidden="true" style="position:absolute; left:5px; top:-34px; '
1976
+ 'width:1.5px; height:875px; background:#999999; border-radius:1px; '
1977
+ 'pointer-events:none;"></span>'
1978
+ )
1979
+ adv_score_dat += (
1980
+ '<div style="page-break-inside:avoid; width:100%;">'
1981
+ '<div style="display:inline-block; vertical-align:top; width:50%; '
1982
+ 'box-sizing:border-box;">' + left_page1 + '</div>'
1983
+ '<div style="display:inline-block; vertical-align:top; width:50%; '
1984
+ 'box-sizing:border-box; padding-left:25px; position:relative;">' +
1985
+ first_page_rule + right_page1 + '</div></div>'
1986
+ )
1987
+
1988
+ left_page2 = (
1989
+ interp_stability + section_image(cv_variability_tag,10) +
1990
+ section_image(cv_variability_cv_tag,10)
1991
+ )
1992
+ right_page2 = (
1993
+ bound_rows[4].replace('margin-top: 10px;', 'margin-top: 0;', 1) + bound_rows[5] +
1994
+ bound_rows[6] + section_image(ad_tag,10) +
1995
+ section_image(williams_tag,10)
1996
+ )
1997
+ # the separator is the right column's border in a stretched flex row, so it is
1998
+ # exactly as tall as the taller of the two columns (a fixed-height rule would run
1999
+ # into Section C when it starts on this same page)
2000
+ adv_score_dat += (
2001
+ '<div style="page-break-before:always; page-break-inside:avoid; width:100%; '
2002
+ 'display:flex; align-items:stretch;">'
2003
+ '<div style="width:50%; box-sizing:border-box;">' + left_page2 + '</div>'
2004
+ '<div style="flex:1; box-sizing:border-box; margin-left:5px; padding-left:20px; '
2005
+ 'border-left:1.5px solid #999999;">' + right_page2 + '</div></div>'
2006
+ )
2007
+ adv_score_dat += '<p style="margin-bottom:50px;"></p>'
2008
+ return adv_score_dat
2009
+
2010
+ for i in range(max(len(interp_rows),len(bound_rows))):
2011
+ left = interp_rows[i] if i < len(interp_rows) else ''
2012
+ # bound_rows is empty for clas (no Boundary robustness column) - right stays
2013
+ # blank and the two-column layout/proportions are kept as-is
2014
+ right = bound_rows[i] if i < len(bound_rows) else ''
2015
+ if i == 0:
2016
+ left = (
2017
+ '<p style="text-align:justify; font-weight:bold; font-size:12px; '
2018
+ 'margin-top:-33px; margin-bottom:5px;">'
2019
+ 'Interpolation</p>' + left
2020
+ )
2021
+ if pred_type == 'reg':
2022
+ right = (
2023
+ '<p style="text-align:justify; font-weight:bold; font-size:12px; '
2024
+ 'margin-top:-33px; margin-bottom:5px;">'
2025
+ f'{self.spacing_PFI}Boundary robustness</p>' + right
2026
+ )
2027
+ adv_score_dat += combine_cols(
2028
+ [left,right],align_top=True,right_offset=25
2029
+ )
2030
+ adv_score_dat += img_after_row.get(i,'')
2031
+
2032
+ adv_score_dat += '<p style="margin-bottom: 50px;"></p>'
2033
+
2034
+ return adv_score_dat
2035
+
2036
+
2037
+ def print_misc(self):
2038
+ """
2039
+ Generates the miscellaneous section
2040
+ """
2041
+
2042
+ misc_dat = ''
2043
+ misc_dat += self.module_lines('misc',misc_dat)
2044
+
2045
+ # get some tips
2046
+ style_line = '<p style="text-align: justify; margin-top: -5px;">' # reduces line separation separation
2047
+ misc_dat += f"""<p style="text-align: justify; margin-top: -3px; margin-bottom: -3px;"><u>Some general tips to improve the score</u></p>"""
2048
+ misc_dat += f'<p style="text-align: justify;">1. Adding meaningful datapoints might help to improve the model. Also, using a uniform population of datapoints across the whole range of y values usually helps to obtain reliable predictions across the whole range. More information about the range of y values used is available in Section C.</p>'
2049
+ misc_dat += f'{style_line}2. Adding meaningful descriptors or replacing/deleting the least useful descriptors used might help. Feature importances are gathered in Section D.</p>'
2050
+
2051
+
2052
+ # how to predict new values
2053
+ misc_dat += f"""
2054
+ <br><p style="text-align: justify; margin-top: -3px; margin-bottom: -3px;"><u>How to predict new values with these models?</u></p>
2055
+ <p style="text-align: justify;">1. Create a CSV database with the new points, including the necessary descriptors.</p>
2056
+ {style_line}2. Place the CSV file in the parent folder (i.e., where the module folders were created)</p>
2057
+ {style_line}3. Run the PREDICT module as 'python -m robert --predict --csv_test FILENAME.csv'.</p>
2058
+ {style_line}4. The predictions will be shown at the end of the resulting PDF report and will be stored in the FILENAME_MODEL_No_PFI.csv and FILENAME_MODEL_PFI.csv files of the PREDICT/csv_test folder.</p>"""
2059
+
2060
+ # add separator line
2061
+ misc_dat += '<hr style="margin-top: 20px;">'
2062
+
2063
+ return misc_dat
2064
+
2065
+
2066
+ def print_outliers(self,pred_type,suffix,suffix_title):
2067
+ """
2068
+ Generates the outliers section - shown once, in the left column's position (the
2069
+ content is the same regardless of suffix, there's no separate interpolation/boundary
2070
+ version of it, so repeating it on the right was pure duplication)
2071
+ """
2072
+
2073
+ # starts with the icon of outliers
2074
+ outlier_dat = ''
2075
+ outlier_dat = self.module_lines('outliers',outlier_dat,pred_type=pred_type)
2076
+
2077
+ if pred_type == 'reg':
2078
+ # get information about outliers
2079
+ module_file = f'{os.getcwd()}/PREDICT/PREDICT{self.model_suffix}_data.dat'
2080
+ column_outlier = get_outliers(module_file,suffix,'')
2081
+ outlier_dat += combine_cols([column_outlier,''])
2082
+
2083
+ # add corresponding image
2084
+ height = 217
2085
+ outlier_dat += self.print_img('Outliers',-5,height,'PREDICT',suffix_title)
2086
+
2087
+ # add separator line and page break
2088
+ outlier_dat += '<hr style="margin-top: 20px;">'
2089
+ outlier_dat += f"""<p style="page-break-after: always;"></p>"""
2090
+
2091
+ return outlier_dat
2092
+
2093
+
2094
+ def print_y_distrib(self,warnings_dict,suffix,suffix_title):
2095
+ """
2096
+ Generates the y distribution section - shown once, in the left column's position (the
2097
+ content is the same regardless of suffix, there's no separate interpolation/boundary
2098
+ version of it, so repeating it on the right was pure duplication)
2099
+ """
2100
+
2101
+ # starts with the icon of outliers
2102
+ distrib_dat = ''
2103
+ distrib_dat = self.module_lines('y_distrib',distrib_dat)
2104
+
2105
+ # add corresponding image
2106
+ height = 220
2107
+ distrib_dat += self.print_img('y_distribution',-5,height,'PREDICT',suffix_title)
2108
+
2109
+ # split the sentence into 1 column size and add spacing line by line
2110
+ y_distrib_sentence = format_lines(warnings_dict[f'y_dist_info_{suffix}'],max_width=55,one_column=True,spacing='')
2111
+
2112
+ column_y_distrib = f"""
2113
+ <p style='margin-top:25px; margin-bottom:-6px'><span style="font-weight:bold;">y distribution analysis</span></p>
2114
+ {y_distrib_sentence}
2115
+ <p style='margin-bottom:-15px'></p>
2116
+ """
2117
+
2118
+ distrib_dat += combine_cols([column_y_distrib,''])
2119
+
2120
+ distrib_dat += '<p style="margin-bottom: 30px;"></p>'
2121
+
2122
+ # add separator line and page break
2123
+ distrib_dat += '<hr style="margin-top: 20px;">'
2124
+ distrib_dat += f"""<p style="page-break-after: always;"></p>"""
2125
+
2126
+ return distrib_dat
2127
+
2128
+
2129
+ def print_features(self,warnings_dict,suffix,suffix_title):
2130
+ """
2131
+ Generates the feature analysis section (2 columns, same content on both sides for now)
2132
+ """
2133
+
2134
+ # starts with the icon of feature importances
2135
+ feature_dat = ''
2136
+ feature_dat = self.module_lines('features',feature_dat)
2137
+
2138
+ # Add the linear model equation (only shown when the model is MVL). Located within this
2139
+ # suffix's own "Summary of results" section instead of picking the Nth equation found in
2140
+ # the whole file by position, since only one of No_PFI/PFI may actually be an MVL model
2141
+ # PREDICT logs it twice: with standardized descriptors (z = (x - mean)/SD, what the model
2142
+ # is fitted on) and in the original units of the descriptors (see linear_equation())
2143
+ equations = []
2144
+ with open(f'{os.getcwd()}/PREDICT/PREDICT{self.model_suffix}_data.dat', 'r', encoding='utf-8') as file:
2145
+ lines = file.readlines()
2146
+ for i, line in enumerate(lines):
2147
+ if 'o Summary of results' in line and (('No_PFI:' in line) == (suffix == 'No PFI')):
2148
+ for j in range(i, len(lines)):
2149
+ if 'o SHAP' in lines[j]:
2150
+ break
2151
+ if 'o Linear model equation' in lines[j] and j + 1 < len(lines):
2152
+ header = lines[j].strip().replace('o Linear model equation','').strip()
2153
+ equations.append((header, lines[j + 1].strip().lstrip('- ')))
2154
+ break
2155
+
2156
+ if equations:
2157
+ feature_dat += "<p style='margin-top:-5px; margin-bottom:-6px'><span style='font-weight:bold;'>Linear model equation</span></p>"
2158
+ for k,(header,equation) in enumerate(equations):
2159
+ # older logs only have the standardized equation, without a header
2160
+ label = f'<i>{header.strip("()")}:</i><br>' if header else ''
2161
+ bottom = 35 if k == len(equations)-1 else 0
2162
+ feature_dat += f"<p style='margin-top:10px; margin-bottom:{bottom}px'>{label}{equation}</p>"
2163
+
2164
+ # add corresponding images
2165
+ module_path = Path(f'{os.getcwd()}/PREDICT')
2166
+
2167
+ shap_images = self._filter_by_model([img for img in glob.glob(f'{module_path}/SHAP_*.png') if self.matches_suffix(img,suffix_title)])
2168
+ pfi_images = self._filter_by_model([img for img in glob.glob(f'{module_path}/PFI_*.png') if self.matches_suffix(img,suffix_title)])
2169
+ pearson_images = self._filter_by_model([img for img in glob.glob(f'{module_path}/Pearson_*.png') if self.matches_suffix(img,suffix_title)])
2170
+
2171
+ margin_top, margin_bottom = -10,30
2172
+ missing_messages = {
2173
+ 'SHAP': 'SHAP plot not found.',
2174
+ 'PFI': 'PFI plot not found.',
2175
+ # Pearson maps aren't created when >30 descriptors - the one case with a known cause
2176
+ 'Pearson': 'Pearson maps not created if >30 descriptors.',
2177
+ }
2178
+ for label, images in [('SHAP', shap_images), ('PFI', pfi_images), ('Pearson', pearson_images)]:
2179
+ if len(images) == 1:
2180
+ # shown once, in the left column's position - this suffix's PDF has only this
2181
+ # one plot, not a second, different one to pair it with, so showing it twice
2182
+ # (or centering it, which reads as its own third position) was duplication
2183
+ pair_list = f'<p style="width: 91%; text-align: left; margin-bottom: {margin_bottom}px; margin-top: {margin_top}px"><img src="file:///{self._posix_uri(images[0])}" style="margin: 0; width: 55%;"/></p>'
2184
+ else:
2185
+ pair_list = f'<p style="width: 91%; margin-bottom: {margin_bottom}px; margin-top: {margin_top}px">{missing_messages[label]}</p>'
2186
+ feature_dat += pair_list
2187
+
2188
+ # split the sentence into 1 column size and add spacing line by line - shown once, in
2189
+ # the left column's position (same content regardless of suffix, so repeating it on
2190
+ # the right was pure duplication)
2191
+ pearson_sentence = format_lines(warnings_dict[f'pearson_info_{suffix}'],max_width=55,one_column=True,spacing='')
2192
+
2193
+ column_pearson = f"""
2194
+ <p style='margin-top:-10px; margin-bottom:-6px'><span style="font-weight:bold;">Correlation analysis</span></p>
2195
+ {pearson_sentence}
2196
+ """
2197
+
2198
+ feature_dat += combine_cols([column_pearson,''])
2199
+
2200
+ # add separator line and page break
2201
+ feature_dat += '<hr style="margin-top: 10px;">'
2202
+ feature_dat += f"""<p style="page-break-after: always;"></p>"""
2203
+
2204
+ return feature_dat
2205
+
2206
+
2207
+ def print_generate(self,eval_only,suffix_title):
2208
+ """
2209
+ Generates the GENERATE hyperoptimization section
2210
+ """
2211
+
2212
+ # starts with the icon of feature importances
2213
+ generate_dat = ''
2214
+ generate_dat = self.module_lines('generate',generate_dat,eval_only=eval_only)
2215
+
2216
+ # add corresponding image - with --all_models, every model's PDF embeds the SAME pair
2217
+ # of score-based heatmaps (Interpolation per model on the left, Boundary robustness on
2218
+ # the right, built in __init__'s pre-pass via save_score_heatmap()) instead of GENERATE's
2219
+ # raw combined-RMSE one, since the RMSE used to pick BO hyperparameters isn't the most
2220
+ # useful basis to compare models against each other once the full VERIFY/PREDICT
2221
+ # scores are known. Kept as two separate images (not one combined heatmap) so the
2222
+ # left/right split matches the Interpolation/Boundary robustness separation used
2223
+ # everywhere else in the report
2224
+ if not eval_only:
2225
+ height = 236
2226
+ if getattr(self.args, 'all_models', False):
2227
+ # NOTE: this deliberately does NOT use combine_cols() (flex divs) - WeasyPrint
2228
+ # silently ignores an explicit <img> width when the image sits inside a flex
2229
+ # item (same issue print_img_row_indent works around elsewhere in this file),
2230
+ # so both images rendered at a tiny, uncontrollable size (~150px) under
2231
+ # combine_cols. Plain inline flow (like print_img_row/print_img_row_indent) is
2232
+ # the only layout WeasyPrint sizes correctly here. Reuses the same image
2233
+ # width and gap as the other fixed-width paired-image rows in the report.
2234
+ img_w = 270
2235
+ gap_px = 86.2
2236
+ spacer = f'<span style="display: inline-block; width: {gap_px}px;"></span>'
2237
+
2238
+ interp_path = self.find_img('ScoreHeatmapInterp','GENERATE',suffix_title)
2239
+ bound_path = self.find_img('ScoreHeatmapBound','GENERATE',suffix_title)
2240
+ interp_tag = f'<img src="file:///{self._posix_uri(interp_path)}" style="margin: 0; width: {img_w}px;"/>' if interp_path else ''
2241
+ bound_tag = f'<img src="file:///{self._posix_uri(bound_path)}" style="margin: 0; width: {img_w}px;"/>' if bound_path else ''
2242
+ if self.all_models_clas:
2243
+ bound_tag = f'<span style="display: inline-block; width: {img_w}px; text-align: center; color: #808080; font-size: 12px;">Disabled in classification problems.</span>'
2244
+
2245
+ interp_cap = f'<span style="display: inline-block; width: {img_w}px; text-align: center; font-weight:bold;">Interpolation</span>'
2246
+ bound_cap = f'<span style="display: inline-block; width: {img_w}px; text-align: center; font-weight:bold;">Boundary robustness</span>'
2247
+
2248
+ generate_dat += f'<p style="margin-bottom: 6px;">{interp_cap}{spacer}{bound_cap}</p>'
2249
+ generate_dat += f'<p style="margin-top: -5px;">{interp_tag}{spacer}{bound_tag}</p>'
2250
+ generate_dat += self.best_models_text(suffix_title)
2251
+ else:
2252
+ generate_dat += self.print_img('Heatmap',-5,height,'GENERATE',suffix_title)
2253
+ generate_dat += self.default_best_model_text(suffix_title)
2254
+
2255
+ generate_dat += '<p style="margin-bottom: 50px;"></p>'
2256
+
2257
+ return generate_dat
2258
+
2259
+
2260
+ def default_best_model_text(self,suffix_title):
2261
+ """
2262
+ Informative-only line (doesn't change which model runs through VERIFY/PREDICT/REPORT)
2263
+ showing which of the screened algorithms GENERATE picked as the best for this PFI
2264
+ variant, and its combined error. Cheap equivalent of best_models_text() for the
2265
+ default (non --all_models) case: reads the same Raw_data CSVs GENERATE's own
2266
+ heatmap_workflow()/detect_best() already produce, instead of requiring the full
2267
+ --all_models pipeline (every model through VERIFY/PREDICT) just to report this.
2268
+ Skipped when only one model was screened - there's nothing to compare against.
2269
+ """
2270
+
2271
+ if len(self.args.model) <= 1:
2272
+ return ''
2273
+
2274
+ raw_dir = Path(f'{os.getcwd()}/GENERATE/Raw_data/{suffix_title}')
2275
+ error_type = self.args.error_type.lower()
2276
+
2277
+ model_errors = {}
2278
+ for csv_file in glob.glob(str(raw_dir / '*.csv')):
2279
+ if '_db' in os.path.basename(csv_file):
2280
+ continue
2281
+ try:
2282
+ params_df = pd.read_csv(csv_file, encoding='utf-8')
2283
+ model_name = str(params_df['model'][0]).upper()
2284
+ model_errors[model_name] = params_df[f'combined_{error_type}'][0]
2285
+ except (KeyError, IndexError, pd.errors.EmptyDataError):
2286
+ continue
2287
+
2288
+ if len(model_errors) <= 1:
2289
+ return ''
2290
+
2291
+ best_model = min(model_errors, key=model_errors.get) if error_type in ['mae','rmse'] else max(model_errors, key=model_errors.get)
2292
+ screened = ', '.join(model.upper() for model in self.args.model if model.upper() in model_errors)
2293
+
2294
+ return (f'<p style="margin-top: 10px; margin-bottom: 0px; font-size: 12.5px;"><i>'
2295
+ f'Best of [{screened}]: <b>{best_model}</b> (combined {error_type.upper()} = {model_errors[best_model]:.2})'
2296
+ f'</i></p>')
2297
+
2298
+
2299
+ def best_models_text(self,suffix_title):
2300
+ """
2301
+ Informative-only line (doesn't change which model(s) run through VERIFY/PREDICT/
2302
+ REPORT) showing, for this PFI variant, the single overall-best model - same
2303
+ combined-score pick as organize_all_models_pdfs() (see _pick_best_overall()), so this
2304
+ text always names the same model as the PDF that actually gets kept
2305
+ """
2306
+
2307
+ suffix = suffix_title.replace('_',' ')
2308
+ scores = getattr(self,'model_scores',{}).get(suffix,{})
2309
+ if not scores:
2310
+ return ''
2311
+
2312
+ # canonical (key, interp, bound, rmse_cv, rmse_bound) shape - same as
2313
+ # organize_all_models_pdfs()'s candidates, so _pick_best_model()/_pick_best_overall()
2314
+ # can use the exact same index arguments there instead of a second hand-shifted copy
2315
+ items = [(model,vals[0],vals[1],vals[2],vals[3]) for model,vals in scores.items()]
2316
+
2317
+ # Boundary robustness isn't defined in classification, so only Interpolation is ranked
2318
+ if self.all_models_clas:
2319
+ best_model = self._pick_best_model(items,1,2,3)[0]
2320
+ return (f'<p style="margin-top: 10px; margin-bottom: 0px; font-size: 12.5px;"><i>'
2321
+ f'Best overall model: <b>{best_model}</b></i></p>')
2322
+
2323
+ best_model,interp_val,bound_val,*_ = self._pick_best_overall(items)
2324
+
2325
+ return (f'<p style="margin-top: 10px; margin-bottom: 0px; font-size: 12.5px;"><i>'
2326
+ f'Best overall model: <b>{best_model}</b> (Interpolation {interp_val}, Boundary robustness {bound_val})'
2327
+ f'</i></p>')
2328
+
2329
+
2330
+ def save_score_heatmap(self,model_scores_suffix,suffix):
2331
+ """
2332
+ Builds Section F's Interpolation and Boundary robustness score heatmaps (one
2333
+ model-per-model image each, 0-10) for one PFI variant, from the interp/extrap scores
2334
+ collected across every model in the --all_models pre-pass (model_scores_suffix:
2335
+ {model_name: (interp_score, extrap_score)}). Two separate single-row images instead of
2336
+ one combined 2-row image, so Interpolation can be placed in the report's left column
2337
+ and Boundary robustness in the right, keeping the same left/right separation as the
2338
+ rest of the report
2339
+ """
2340
+
2341
+ # keep the same model order used everywhere else in the report (self.args.model)
2342
+ model_cols = [model.upper() for model in self.args.model if model.upper() in model_scores_suffix]
2343
+
2344
+ save_dir = Path(f'{os.getcwd()}/GENERATE/Raw_data')
2345
+ save_dir.mkdir(parents=True, exist_ok=True)
2346
+ suffix_title = '_'.join(suffix.split())
2347
+
2348
+ for score_idx,(label,file_name) in enumerate([('Interpolation','ScoreHeatmapInterp'),('Boundary robustness','ScoreHeatmapBound')]):
2349
+ # Boundary robustness isn't defined in classification (always 0), so no heatmap
2350
+ if score_idx == 1 and self.all_models_clas:
2351
+ continue
2352
+ csv_df = pd.DataFrame(
2353
+ {model: [model_scores_suffix[model][score_idx]] for model in model_cols},
2354
+ index=[label],
2355
+ )
2356
+ _ = create_score_heatmap(csv_df, save_dir / f'{file_name}_{suffix_title}.png')
2357
+
2358
+
2359
+ def get_repro(self,eval_only):
2360
+ """
2361
+ Generates the reproducibility section
2362
+ """
2363
+
2364
+ version_n_date, citation_main, citation_second, command_line, python_version, total_time, dat_files = repro_info(self.args.report_modules,self.model_suffix)
2365
+ citation_main = (citation_main
2366
+ .replace('WIREs Comput. Mol. Sci.', '<i>WIREs Comput. Mol. Sci.</i>')
2367
+ .replace('2024', '<b>2024</b>')
2368
+ .replace(', 14,', ', <i>14</i>,'))
2369
+ robert_version = version_n_date.split()[2]
2370
+
2371
+ if self.args.csv_name == '' or self.args.csv_test == '':
2372
+ self = get_csv_names(self,command_line)
2373
+
2374
+ repro_dat,citation_dat = '',''
2375
+
2376
+ # version, date and citation - the main ROBERT paper and the low-data-regimes one each
2377
+ # get their own row (still 2 lines total, same as before) instead of one long paragraph
2378
+ citation_dat += f"""<p style="text-align: justify; margin-top: -9px;"><br>{version_n_date}</p>
2379
+ <p style="text-align: justify; margin-top: -10px; margin-bottom: 0px;"><span style="font-weight:bold;">Please cite ROBERT:</span> {citation_main}</p>"""
2380
+ citation_dat += f"""<p style="text-align: justify; margin-top: 0px; margin-bottom: 5px;"><span style="font-weight:bold;">and CheckML score:</span> {citation_second}</p>"""
2381
+
2382
+ # QDESCP's own validation paper - only relevant when AQME generated the descriptors
2383
+ # (command_line already has the full "python -m robert ..." line at this point, so the
2384
+ # --aqme flag is checked here directly instead of waiting for aqme_workflow below)
2385
+ # kept on self so print_warnings() can leave room for this extra (2-line) header row
2386
+ self.qdescp_citation = '--aqme' in command_line
2387
+ if '--aqme' in command_line:
2388
+ qdescp_citation = "Dalmau, D.; Jacot-Descombes, L.; Kalikadien, A.; Manzanilla, B.; Pidko, E. A.; Jorner, K.; Sigman, M. S.; Alegre-Requena, J. V. ACS Catal. 2026, 16, 12565-12574."
2389
+ citation_dat += f"""
2390
+ <p style="text-align: justify; margin-top: 0px;"><span style="font-weight:bold;">QDESCP descriptors:</span> {qdescp_citation}</p>"""
2391
+
2392
+ aqme_workflow,aqme_updated = False,True
2393
+ crest_workflow = False
2394
+ if '--aqme' in command_line:
2395
+ original_command = command_line
2396
+ aqme_workflow = True
2397
+ command_line = command_line.replace('AQME-ROBERT_','')
2398
+ self.args.csv_name = f'{self.args.csv_name}'.replace('AQME-ROBERT_','')
2399
+ if self.args.csv_test != '':
2400
+ self.args.csv_test = f'{self.args.csv_test}'.replace('AQME-ROBERT_','')
2401
+
2402
+ if '--program crest' in command_line.lower():
2403
+ crest_workflow = True
2404
+
2405
+ # make the text more compact if --aqme is used (more lines are included)
2406
+ if aqme_workflow:
2407
+ first_line = f'<p style="text-align: justify; margin-bottom: 10px; margin-top: -16px;">' # reduces line separation separation
2408
+ else:
2409
+ first_line = f'<p style="text-align: justify; margin-bottom: 10px; margin-top: -8px;">' # reduces line separation separation
2410
+ reduced_line = f'<p style="text-align: justify; margin-top: -5px;">' # reduces line separation separation
2411
+ space = ('&nbsp;')*4
2412
+
2413
+ # just in case the command lines are so long
2414
+ command_line = format_lines(command_line,cmd_line=True)
2415
+
2416
+ # reproducibility section, starts with the icon of reproducibility
2417
+ repro_dat += f"""{first_line}<br><strong>1. Download these files <i>(the authors should have uploaded the files as supporting information!)</i>:</strong></p>"""
2418
+ repro_dat += f"""{reduced_line}{space}- CSV database ({self.args.csv_name})</p>"""
2419
+ if self.args.csv_test != '':
2420
+ repro_dat += f"""{reduced_line}{space}- External test set ({self.args.csv_test})</p>"""
2421
+
2422
+ if aqme_workflow:
2423
+ try:
2424
+ path_aqme = Path(f'{os.getcwd()}/AQME/CSEARCH_data.dat')
2425
+ with open(path_aqme, 'r', errors="replace") as datfile:
2426
+ outlines = datfile.readlines()
2427
+ aqme_version = outlines[0].split()[2]
2428
+ find_aqme = True
2429
+ except:
2430
+ find_aqme = False
2431
+ aqme_version = '0.0' # dummy number
2432
+ if int(aqme_version.split('.')[0]) in [0,1] and int(aqme_version.split('.')[1]) < 6:
2433
+ aqme_updated = False
2434
+ repro_dat += f"""{reduced_line}{space}<i>Warning! This workflow might not be exactly reproducible, update to AQME v1.6.0+ (pip install aqme --upgrade)</i></p>"""
2435
+ repro_dat += f"""{reduced_line}{space}To obtain the same results, download the descriptor database (AQME-ROBERT_{self.args.csv_name}) and run:</p>"""
2436
+ repro_line = []
2437
+ original_command = original_command.replace(self.args.csv_name,f'AQME-ROBERT_{self.args.csv_name}')
2438
+ for i,keyword in enumerate(original_command.split('"')):
2439
+ if i == 0:
2440
+ if '--aqme' not in keyword and '--qdescp_keywords' not in keyword and '--csearch_keywords' not in keyword:
2441
+ repro_line.append(keyword)
2442
+ else:
2443
+ repro_line.append('python -m robert ')
2444
+ if i > 0:
2445
+ if '--qdescp_keywords' not in original_command.split('"')[i-1] and '--csearch_keywords' not in original_command.split('"')[i-1]:
2446
+ if '--aqme' not in keyword and '--qdescp_keywords' not in keyword and '--csearch_keywords' not in keyword and keyword != '\n':
2447
+ repro_line.append(keyword)
2448
+ repro_line = '"'.join(repro_line)
2449
+ repro_line += '"'
2450
+ if '--names ' not in repro_line:
2451
+ repro_line += ' --names "code_name"'
2452
+ repro_line = f'{reduced_line}{space}- Run: {repro_line}'
2453
+ repro_line = format_lines(repro_line,cmd_line=True)
2454
+ repro_dat += f"""{reduced_line}{repro_line}</p>"""
2455
+
2456
+ if aqme_workflow and not aqme_updated:
2457
+ # I use a very reduced line in this title because the formatted command_line comes with an extra blank line
2458
+ # (if AQME is not updated the PDF contains a reproducibility warning)
2459
+ repro_dat += f"""<p style="text-align: justify; margin-top: -44px;"><br><strong>2. Install and adjust the versions of the following Python modules:</strong></p>"""
2460
+ else:
2461
+ repro_dat += f"""{first_line}<br><strong>2. Install and adjust the versions of the following Python modules:</strong></p>"""
2462
+ repro_dat += f"""{reduced_line}{space}- Install ROBERT and its dependencies: conda install -y -c conda-forge robert</p>"""
2463
+ repro_dat += f"""{reduced_line}{space}- Adjust ROBERT version: pip install robert=={robert_version}</p>"""
2464
+
2465
+ if aqme_workflow:
2466
+ if not find_aqme:
2467
+ repro_dat += f"""{reduced_line}{space}- AQME is required, but no version was found:</p>"""
2468
+ repro_dat += f"""{reduced_line}{space}- Install AQME and its dependencies: pip install aqme==VERSION_USED</p>"""
2469
+ if find_aqme:
2470
+ repro_dat += f"""{reduced_line}{space}- Install or adjust AQME version: pip install aqme=={aqme_version}</p>"""
2471
+
2472
+ try:
2473
+ path_xtb = Path(f'{os.getcwd()}/AQME/QDESCP')
2474
+ xtb_json = glob.glob(f'{path_xtb}/*.json')[0]
2475
+ with open(xtb_json, "r") as f: # Opening JSON file
2476
+ data = json.loads(f.read()) # read file
2477
+ xtb_version = data['xtb version'].split()[0]
2478
+ find_xtb = True
2479
+ except:
2480
+ find_xtb = False
2481
+ if not find_xtb:
2482
+ repro_dat += f"""{reduced_line}{space}- xTB is required, but no version was found:</p>"""
2483
+ repro_dat += f"""{reduced_line}{space}- Install xTB: conda install -y -c conda-forge xtb</p>"""
2484
+ if find_xtb:
2485
+ repro_dat += f"""{reduced_line}{space}- Adjust xTB version (if possible): conda install -y -c conda-forge xtb={xtb_version}</p>"""
2486
+
2487
+ if crest_workflow:
2488
+ try:
2489
+ from importlib.metadata import PackageNotFoundError, version as importlib_version
2490
+ crest_version = importlib_version("crest")
2491
+ find_crest = True
2492
+ except PackageNotFoundError:
2493
+ find_crest = False
2494
+ if not find_crest:
2495
+ repro_dat += f"""{reduced_line}{space}- CREST is required, but no version was found:</p>"""
2496
+ repro_dat += f"""{reduced_line}{space}- Install CREST: conda install -c conda-forge crest</p>"""
2497
+ if find_crest:
2498
+ repro_dat += f"""{reduced_line}{space}- Adjust CREST version: conda install -c conda-forge crest={crest_version}</p>"""
2499
+
2500
+ character_line = ''
2501
+ if self.args.csv_test != '':
2502
+ character_line += 's'
2503
+
2504
+ repro_dat += f"""{first_line}<br><strong>3. Run ROBERT using this command line in the folder with the CSV database{character_line}:</strong></p>{reduced_line}{command_line}</p>"""
2505
+
2506
+ # I use a very reduced line in this title because the formatted command_line comes with an extra blank line
2507
+ if aqme_workflow:
2508
+ repro_dat += f"""<p style="text-align: justify; margin-top: -44px;"><br><strong>4. Execution time, Python version and OS:</strong></p>"""
2509
+ else:
2510
+ repro_dat += f"""<p style="text-align: justify; margin-top: -37px;"><br><strong>4. Execution time, Python version and OS:</strong></p>"""
2511
+
2512
+ # add total execution time
2513
+ repro_dat += f"""{reduced_line}Originally run in Python {python_version} using {platform.system()} {platform.version()}</p>"""
2514
+ repro_dat += f"""{reduced_line}Total execution time: {total_time} seconds <i>(the number of processors should be specified by the user)</i></p>"""
2515
+
2516
+ # add separator line and page break
2517
+ repro_dat += '<hr style="margin-top: 20px;">'
2518
+ repro_dat += f"""<p style="page-break-after: always;"></p>"""
2519
+
2520
+ repro_dat = self.module_lines('repro',repro_dat)
2521
+
2522
+ return citation_dat, repro_dat, dat_files, self.args.csv_name, robert_version
2523
+
2524
+
2525
+ def get_transparency(self,suffix):
2526
+ """
2527
+ Generates the transparency section
2528
+ """
2529
+
2530
+ transpa_dat = ''
2531
+ titles_line = f'<p style="text-align: justify; margin-top: -12px; margin-bottom: 3px">' # reduces line separation separation
2532
+
2533
+ # add params of the model
2534
+ transpa_dat += f"""{titles_line}<br><strong>1. Parameters of the scikit-learn model (same keywords as used in scikit-learn):</strong></p>"""
2535
+
2536
+ model_dat, params_df = self.transpa_model_misc('model_section',suffix)
2537
+ transpa_dat += model_dat
2538
+
2539
+ # add misc params
2540
+ transpa_dat += f"""<p style="text-align: justify; margin-top: -95px; margin-bottom: 3px;"><br><strong>2. ROBERT options, including prediction type (REG or CLAS), folds and repeats used for CV, etc:</strong></p>"""
2541
+
2542
+ section_dat, params_df = self.transpa_model_misc('misc_section',suffix)
2543
+ transpa_dat += section_dat
2544
+
2545
+ transpa_dat = self.module_lines('transpa',transpa_dat)
2546
+
2547
+
2548
+ return transpa_dat,params_df
2549
+
2550
+
2551
+ def transpa_model_misc(self,section,suffix):
2552
+ """
2553
+ Collects the data for model parameters and misc options in the Reproducibility section -
2554
+ shown once, in the left column's position (same content regardless of suffix, so
2555
+ repeating it on the right was pure duplication)
2556
+ """
2557
+
2558
+ # set the parameters for the ML model
2559
+ params_dir = f'{self.args.params_dir}/{"_".join(suffix.split())}'
2560
+
2561
+ # --all_models: each model's PDF shows its own parameters (from the per-model folders
2562
+ # staged by GENERATE), not the ones from the best model in Best_model
2563
+ model_name = getattr(self,'model_suffix','')[1:]
2564
+ if getattr(self.args,'all_models',False) and model_name:
2565
+ params_dir_model = f'{self.args.params_dir.replace("Best_model","All_models")}/{"_".join(suffix.split())}/{model_name}'
2566
+ if os.path.isdir(params_dir_model):
2567
+ params_dir = params_dir_model
2568
+ files_param = glob.glob(f'{params_dir}/*.csv')
2569
+ for file_param in files_param:
2570
+ if '_db' not in file_param:
2571
+ params_df = pd.read_csv(file_param, encoding='utf-8')
2572
+ else:
2573
+ # database (with its Set column) of this model, used by print_summary_page()
2574
+ self.report_db_file = file_param
2575
+ params_dict = pd_to_dict(params_df) # (using a dict to keep the same format of load_model)
2576
+
2577
+ column_repro = get_col_transpa(params_dict,suffix,section,'')
2578
+ section_dat = combine_cols([column_repro,''])
2579
+ section_dat += '<p style="text-align: justify; margin-top: -70px;">'
2580
+
2581
+ return section_dat,params_df
2582
+
2583
+
2584
+ def get_abbrev(self):
2585
+ """
2586
+ Generates the abbreviations section
2587
+ """
2588
+
2589
+ # starts with the icon of abbreviation
2590
+ abbrev_dat = ''
2591
+ abbrev_dat = self.module_lines('abbrev',abbrev_dat)
2592
+
2593
+ columns_abbrev = []
2594
+ columns_abbrev.append(get_col_text('abbrev_1'))
2595
+ columns_abbrev.append(get_col_text('abbrev_2'))
2596
+ columns_abbrev.append(get_col_text('abbrev_3'))
2597
+
2598
+ abbrev_dat += combine_cols(columns_abbrev)
2599
+ abbrev_dat +=f'<hr style="margin-top: 15px;">'
2600
+
2601
+ abbrev_dat += f"""<p style="page-break-after: always;"></p>"""
2602
+
2603
+ return abbrev_dat
2604
+
2605
+
2606
+ def print_predictions(self,pred_type,suffix,suffix_title):
2607
+ """
2608
+ Generates the new predictions section - shown once, in the left column's position
2609
+ (same content regardless of suffix, so repeating it on the right was pure duplication)
2610
+ """
2611
+
2612
+ # detects whether there are predictions from an external test set
2613
+ module_file = f'{os.getcwd()}/PREDICT/PREDICT{self.model_suffix}_data.dat'
2614
+ csv_test_exists, y_value, names, path_csv_test = detect_predictions(module_file)
2615
+ if csv_test_exists:
2616
+ pred_dat = ''
2617
+ pred_dat = self.module_lines('pred',pred_dat,pred_type=pred_type)
2618
+
2619
+ # add metrics
2620
+ column_metrics = get_csv_metrics(module_file,suffix,'')
2621
+
2622
+ # add predictions table
2623
+ column_pred = get_csv_pred(suffix,path_csv_test,y_value,names,'')
2624
+
2625
+ pred_dat += combine_cols([column_metrics,''])
2626
+ pred_dat += combine_cols([column_pred,''])
2627
+
2628
+ # add corresponding image
2629
+ height = 217
2630
+ if pred_type == 'reg':
2631
+ prefix_img = 'CV_variability'
2632
+ elif pred_type == 'clas':
2633
+ prefix_img = 'Results'
2634
+ height += 17
2635
+ if len(glob.glob(f'{os.getcwd()}/PREDICT/csv_test/{prefix_img}*.png')) > 0:
2636
+ pred_dat += self.print_img(prefix_img,-5,height,'PREDICT/csv_test',suffix_title)
2637
+
2638
+ # add separator line and page break
2639
+ pred_dat += '<hr style="margin-top: 20px;">'
2640
+ pred_dat += f"""<p style="page-break-after: always;"></p>"""
2641
+
2642
+ return pred_dat
2643
+
2644
+ else:
2645
+ return ''
2646
+
2647
+
2648
+ def module_lines(self,module,module_data,pred_type='reg',eval_only=False,explain_override=None):
2649
+ """
2650
+ Returns the line with icon and module for section titles. explain_override replaces the
2651
+ standing intro paragraph with different text in the exact same slot (only used for
2652
+ 'score', when the score isn't calibrated for this run - print_score() passes a shorter
2653
+ "Score not available" notice instead, so the Interpolation/Boundary robustness columns
2654
+ right below keep their normal spacing instead of sitting under a separately-appended
2655
+ paragraph)
2656
+ """
2657
+
2658
+ if module == 'score':
2659
+ module_name = 'Section A. CheckML Score'
2660
+ if explain_override is not None:
2661
+ section_explain = explain_override
2662
+ elif pred_type == 'clas':
2663
+ # Boundary robustness isn't defined for classification (see print_score())
2664
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">Evaluation of interpolation (within the range of training data).</i>'
2665
+ else:
2666
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">Evaluation of interpolation (within the range of training data) and boundary robustness (related to extrapolation).</i>'
2667
+ elif module == 'adv_anal':
2668
+ module_name = 'Section B. Advanced Score Analysis'
2669
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">This section explains each component of the CheckML score. Further details on each test can be accessed through the hyperlinks in the underlined titles. Scoring thresholds are provided in the corresponding help icons.</i>'
2670
+ elif module == 'y_distrib':
2671
+ module_name = 'Section C. Distribution of y Values'
2672
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">This section shows the distribution of y values within the whole dataset (CV and test sets). In regression, Q1-Q4 are four equal-width intervals of the y range (from the lowest to the highest y value), not quartiles of the data: a uniform dataset would have about 25% of the points in each.</i>'
2673
+ elif module == 'features':
2674
+ module_name = 'Section D. Feature Importances'
2675
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">This section presents feature importances (SHAP and PFI) of the model fitted on the CV set (training and validation points).</i>'
2676
+ elif module == 'outliers':
2677
+ module_name = 'Section E. Outlier Analysis'
2678
+ if pred_type == 'clas':
2679
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">This feature is disabled in classification problems.</i>'
2680
+ else:
2681
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">This section detects outliers using the standard deviation (SD) of the errors of the CV predictions (training and validation points).</i>'
2682
+ elif module == 'generate':
2683
+ module_name = 'Section F. Model Screening'
2684
+ if eval_only:
2685
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">The screening of models is disabled when using the CHECKML module.</i>'
2686
+ else:
2687
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">This section compares the hyperoptimized algorithms. The combined error is the average of the 10x 5-fold CV error and the sorted CV error (worst of the lowest/highest y folds in regression).</i>'
2688
+ elif module == 'repro':
2689
+ module_name = 'Section G. Reproducibility'
2690
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">This section provides all the instructions to reproduce the results presented.</i>'
2691
+ elif module == 'transpa':
2692
+ module_name = 'Section H. Transparency'
2693
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">This section contains important parameters used in scikit-learn models and ROBERT.</i>'
2694
+ elif module == 'abbrev':
2695
+ module_name = 'Section I. Abbreviations'
2696
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">Reference section for the abbreviations used.</i>'
2697
+ elif module == 'pred':
2698
+ module_name = 'Section J. New Predictions'
2699
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">Predictions of the external test set added with the csv_test option.</i>'
2700
+ elif module == 'misc':
2701
+ module_name = 'Miscellaneous'
2702
+ section_explain = f'<p style="margin-top:-7px;"><i style="text-align: justify;">General tips to improve the models and instructions to predict new values.</i>'
2703
+
2704
+ if module not in ['repro','transpa','misc']:
2705
+ module_data = format_lines(module_data)
2706
+ module_data = '<div class="aqme-content"><pre>' + module_data + '</pre></div>'
2707
+
2708
+ # only Section A opens with a line (below the header on page 1); every other section
2709
+ # is separated by the closing line of the previous one (see _close_section())
2710
+ if module == 'score':
2711
+ separator_section = '<hr><p style="margin-top:25px;"></p>'
2712
+ else:
2713
+ separator_section = '<p style="margin-top:0px;"></p>'
2714
+
2715
+ # page-break-after: avoid keeps the title (and its explanation line) on the same page
2716
+ # as the start of the section, instead of stranding it at the bottom of a page
2717
+ section_explain = section_explain.replace('<p style="', '<p style="page-break-after: avoid; ', 1)
2718
+ title_position = ''
2719
+ if module == 'adv_anal':
2720
+ # Lift Section B's header and explanation while leaving its content in place,
2721
+ # creating a little more visual space before the Interpolation/Boundary headings.
2722
+ title_position = 'position:relative; top:-10px; '
2723
+ section_explain = section_explain.replace(
2724
+ '<p style="', '<p style="position:relative; top:-10px; ', 1
2725
+ )
2726
+ section_anchor = ' id="section-b"' if module == 'adv_anal' else ''
2727
+ title_line = f"""
2728
+ {separator_section}
2729
+ <p{section_anchor} style="page-break-after: avoid; {title_position}"><span style="font-weight:bold;">
2730
+ <img src="file:///{self._posix_uri(self.args.path_icons)}/{module}.png" alt="" style="width:20px; height:20px; margin-right:5px;">
2731
+ {module_name}
2732
+ </span></p>{section_explain}
2733
+ {module_data}
2734
+ </p>
2735
+ """
2736
+
2737
+ return title_line
2738
+
2739
+
2740
+ @staticmethod
2741
+ def matches_suffix(filepath,suffix_title):
2742
+ """
2743
+ Checks whether a file belongs to the No_PFI or PFI model. Plain substring matching isn't
2744
+ enough since 'No_PFI' ends in 'PFI', so a 'PFI' file would also match 'No_PFI' filenames.
2745
+ """
2746
+
2747
+ if suffix_title == 'PFI':
2748
+ return 'PFI' in filepath and 'No_PFI' not in filepath
2749
+
2750
+ return suffix_title in filepath
2751
+
2752
+
2753
+ def _filter_by_model(self,file_list):
2754
+ """
2755
+ --all_models: every model's images live in the SAME VERIFY/PREDICT folder with the
2756
+ SAME suffix_title (e.g. Results_GB_No_PFI.png, Results_NN_No_PFI.png, ...), so a
2757
+ suffix-only filter matches every model at once - narrow down to this model's own
2758
+ file. Some images (Section F's score heatmap in GENERATE) are intentionally SHARED
2759
+ across every model's PDF and have no model name in their filename at all, so only
2760
+ narrow when it actually finds a match - otherwise keep the list as given
2761
+ """
2762
+
2763
+ model_name = self.model_suffix[1:] if getattr(self, 'model_suffix', '') else None
2764
+ if not model_name:
2765
+ return file_list
2766
+
2767
+ model_matches = [f for f in file_list
2768
+ if f'_{model_name}_' in os.path.basename(f) or os.path.basename(f).endswith(f'_{model_name}.png')]
2769
+ if model_matches:
2770
+ return model_matches
2771
+
2772
+ # empty result: only fall back to the unfiltered list for genuinely shared files (no
2773
+ # model name in ANY of their filenames, e.g. GENERATE's score heatmap) - if other
2774
+ # models' names do appear in file_list, this model's own file is actually missing, and
2775
+ # falling back to the unfiltered list would silently show a DIFFERENT model's image as
2776
+ # if it were this model's own (a garbled/misleading PDF with no warning)
2777
+ other_models = [m for m in getattr(self.args, 'model', []) if m.upper() != model_name.upper()]
2778
+ is_shared = not any(
2779
+ f'_{m}_' in os.path.basename(f) or os.path.basename(f).endswith(f'_{m}.png')
2780
+ for f in file_list for m in other_models
2781
+ )
2782
+ return file_list if is_shared else []
2783
+
2784
+
2785
+ def find_img(self,file_name,module,suffix_title,exclude=None):
2786
+ """
2787
+ Finds the single image (matching suffix_title) for a given module/file_name prefix.
2788
+ 'exclude' filters out filenames containing that substring, or any substring in a
2789
+ list/tuple (e.g. so a search for ``CV_variability`` doesn't also match
2790
+ ``CV_variability_boundary_...`` files)
2791
+ """
2792
+
2793
+ module_path = Path(f'{os.getcwd()}/{module}')
2794
+ if exclude is None:
2795
+ exclude = []
2796
+ elif isinstance(exclude,str):
2797
+ exclude = [exclude]
2798
+
2799
+ # rglob (matches original behavior): GENERATE's heatmap lives in a Raw_data subfolder
2800
+ results_images = [str(file_path) for file_path in module_path.rglob(f'{file_name}_*.png')
2801
+ if self.matches_suffix(str(file_path),suffix_title) and not any(ex in str(file_path) for ex in exclude)]
2802
+
2803
+ results_images = self._filter_by_model(results_images)
2804
+
2805
+ if not results_images:
2806
+ return ''
2807
+
2808
+ return results_images[0]
2809
+
2810
+
2811
+ @staticmethod
2812
+ def _posix_uri(path) -> str:
2813
+ """
2814
+ POSIX-ify a path for embedding in a file:// URI. file:// URIs are only
2815
+ well-formed with forward slashes; str(Path) uses backslashes on Windows,
2816
+ which some file:// URI parsers don't tolerate.
2817
+ """
2818
+
2819
+ return str(path).replace('\\', '/')
2820
+
2821
+ def print_img_tag(self,image_path,height,width=270):
2822
+ """
2823
+ Generates an <img> tag at the requested width and height. The inline min/max widths
2824
+ override report.css's generic PFI image limit, which otherwise shrinks plots inside
2825
+ the new half-page columns and makes object-fit crop their sides.
2826
+ """
2827
+
2828
+ if not image_path:
2829
+ return ''
2830
+
2831
+ return f'<img src="file:///{self._posix_uri(image_path)}" style="margin: 0; width: {width}px; min-width: {width}px; max-width: {width}px; height: {height}px; object-fit: cover; object-position: 0 100%;"/>'
2832
+
2833
+
2834
+ def print_img_row_indent(self,left_tag,right_tag,margin_top,right_offset=0,left_width=270):
2835
+ """
2836
+ Places two DIFFERENT images (interpolation left, boundary robustness right) in a
2837
+ single flowing paragraph, like print_img_row, but with a precisely calculated spacer
2838
+ (not 22 nbsp) so the right image starts at the same x as the indented Boundary
2839
+ robustness caption/text above it. Flex columns and position:absolute were both tried
2840
+ first, but WeasyPrint silently shrinks a fixed-width <img> below its declared width
2841
+ whenever it's wrapped in a flex item or an absolutely positioned span - plain inline
2842
+ flow (like the original print_img_row) is the only layout that renders it at full size.
2843
+ 331.2px = row half-width (234.9pt, confirmed empirically via the width:100% score-bar
2844
+ image) + the 18px BOUNDARY_INDENT used for the text above, converted to px. The spacer
2845
+ is reduced by the displayed left image width so the right column keeps the same x
2846
+ position when that image is enlarged.
2847
+ """
2848
+
2849
+ spacer_px = (331.2 - left_width if left_tag else 331.2) + (right_offset if right_tag else 0)
2850
+ spacer = f'<span style="display: inline-block; width: {spacer_px}px;"></span>'
2851
+
2852
+ return f'<p style="width: 100%; margin-bottom: -2px; margin-top: {margin_top}px">{left_tag}{spacer}{right_tag}</p>'
2853
+
2854
+
2855
+ def print_img_row(self,left_tag,right_tag,margin_top):
2856
+ """
2857
+ Places two image tags side by side in a single full-width paragraph (matches the
2858
+ original report layout: fixed-width images separated by a fixed nbsp gap)
2859
+ """
2860
+
2861
+ pair_list = f'<p style="width: 100%; margin-bottom: -2px; margin-top: {margin_top}px">{left_tag}{("&nbsp;")*22}{right_tag}</p>'
2862
+
2863
+ return pair_list
2864
+
2865
+
2866
+ def print_img(self,file_name,margin_top,height,module,suffix_title):
2867
+ """
2868
+ Generates the row for a single image (matching suffix_title), shown once in the left
2869
+ column's position (not centered, not duplicated) - each suffix's PDF only ever has
2870
+ this one plot (not a second, different one to pair it with), so showing it twice side
2871
+ by side was pure visual duplication rather than an actual left/right comparison
2872
+ """
2873
+
2874
+ tag = self.print_img_tag(self.find_img(file_name,module,suffix_title),height)
2875
+ if not tag:
2876
+ return ''
2877
+
2878
+ return self.print_img_row(tag,'',margin_top)
2879
+
2880
+