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/utils.py ADDED
@@ -0,0 +1,4763 @@
1
+ ######################################################.
2
+ # This file stores functions used #
3
+ # in multiple modules #
4
+ ######################################################.
5
+
6
+ import os
7
+ import sys
8
+ import time
9
+ import getopt
10
+ import glob
11
+ import json
12
+ import yaml
13
+ import ast
14
+ import shutil
15
+ from pathlib import Path
16
+ import pandas as pd
17
+ import numpy as np
18
+
19
+ # Force single-threaded execution for reproducibility across platforms
20
+ # This prevents numerical differences between Windows/Ubuntu in parallel operations
21
+ os.environ["LOKY_MAX_CPU_COUNT"] = "1"
22
+ from matplotlib import pyplot as plt
23
+ import importlib
24
+ import matplotlib.patches as mpatches
25
+ import matplotlib.colors as mcolor
26
+ from matplotlib.legend_handler import HandlerPatch
27
+ from matplotlib.ticker import FormatStrFormatter
28
+ import shap
29
+ import seaborn as sb
30
+ from scipy import stats
31
+ from scipy.spatial.distance import cdist
32
+ from importlib.resources import files
33
+ # sklearnex was deactivated in ROBERT v2.1 because it only accelerated RF
34
+ # try:
35
+ # from sklearnex import patch_sklearn
36
+ # patch_sklearn(verbose=True)
37
+ # except (ModuleNotFoundError,ImportError):
38
+ # pass
39
+ from sklearn.metrics import (mean_absolute_error, mean_squared_error, r2_score,
40
+ matthews_corrcoef, accuracy_score, f1_score, make_scorer,
41
+ ConfusionMatrixDisplay)
42
+ from sklearn.feature_selection import RFECV
43
+ from sklearn.preprocessing import StandardScaler
44
+ from sklearn.ensemble import (
45
+ RandomForestRegressor,
46
+ GradientBoostingRegressor,
47
+ AdaBoostRegressor,
48
+ RandomForestClassifier,
49
+ GradientBoostingClassifier,
50
+ AdaBoostClassifier,
51
+ )
52
+ from sklearn.gaussian_process import GaussianProcessRegressor, GaussianProcessClassifier
53
+ from sklearn.neural_network import MLPRegressor, MLPClassifier
54
+ from sklearn.linear_model import LinearRegression, Ridge, LogisticRegression
55
+ from sklearn.impute import KNNImputer
56
+ from sklearn.base import clone
57
+ from sklearn.model_selection import train_test_split, cross_val_score, StratifiedShuffleSplit, RepeatedKFold, KFold, StratifiedKFold
58
+ from sklearn.cluster import KMeans
59
+ from sklearn.inspection import permutation_importance
60
+ from sklearn.exceptions import ConvergenceWarning
61
+ from robert.argument_parser import set_options, var_dict
62
+ from robert._version import ROBERT_VERSION
63
+ from bayes_opt import BayesianOptimization
64
+ import warnings # this avoids warnings from sklearn
65
+ warnings.filterwarnings("ignore")
66
+
67
+
68
+ robert_version = ROBERT_VERSION
69
+ time_run = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
70
+ robert_ref = "Dalmau, D.; Alegre Requena, J. V. WIREs Comput. Mol. Sci. 2024, 14, e1733."
71
+ checkml_ref = "CheckML citation TBD."
72
+
73
+ def _parse_class_mapping_reverse(mapping):
74
+ """
75
+ Return a class-code -> original-label mapping with integer keys.
76
+ """
77
+
78
+ if mapping is None or (isinstance(mapping, float) and pd.isna(mapping)):
79
+ return None
80
+ if isinstance(mapping, str):
81
+ try:
82
+ mapping = json.loads(mapping)
83
+ except (json.JSONDecodeError, TypeError):
84
+ mapping = ast.literal_eval(mapping)
85
+ if not isinstance(mapping, dict):
86
+ return None
87
+ return {int(key): value for key, value in mapping.items()}
88
+
89
+
90
+ def _sorted_class_values(values):
91
+ """
92
+ Sort class labels deterministically, including mixed string/numeric labels.
93
+ """
94
+
95
+ return sorted(pd.unique(values), key=lambda value: (str(type(value)), str(value)))
96
+
97
+
98
+ def _integer_like_class_values(values):
99
+ try:
100
+ numeric_values = pd.to_numeric(pd.Series(values), errors="raise")
101
+ except (TypeError, ValueError):
102
+ return False
103
+ return np.all(np.isfinite(numeric_values)) and np.all(
104
+ np.equal(np.mod(numeric_values, 1), 0)
105
+ )
106
+
107
+
108
+ def is_smiles_column(column):
109
+ """
110
+ AQME workflows read SMILES from a column named SMILES, or SMILES_suffix when there are
111
+ several of them (i.e. SMILES_1 and SMILES_2, each one gets its own AQME run - see aqme.py).
112
+ Case-insensitive.
113
+ """
114
+
115
+ return "SMILES" == str(column).upper() or "SMILES_" in str(column).upper()
116
+
117
+
118
+ def _csv_row_numbers_txt(mask,max_rows=10):
119
+ """
120
+ Row numbers (as they appear in Excel or a text editor: +2 since the header is line 1 and
121
+ counting starts at 1) of the rows flagged in a boolean mask, capped to max_rows
122
+ """
123
+
124
+ rows = [int(idx) + 2 for idx in mask[mask].index]
125
+ txt = ', '.join(str(row) for row in rows[:max_rows])
126
+ return txt + (', ...' if len(rows) > max_rows else '')
127
+
128
+
129
+ def _classification_vote(values):
130
+ """
131
+ Combine repeated classification predictions with majority voting.
132
+ """
133
+
134
+ class_values, counts = np.unique(np.asarray(values), return_counts=True)
135
+ return int(class_values[np.argmax(counts)])
136
+
137
+
138
+ # load paramters from yaml file
139
+ def load_from_yaml(self):
140
+ """
141
+ Loads the parameters for the calculation from a yaml if specified. Otherwise
142
+ does nothing.
143
+ """
144
+
145
+ txt_yaml = f"\no Importing ROBERT parameters from {self.varfile}"
146
+ error_yaml = False
147
+ # Variables will be updated from YAML file
148
+ try:
149
+ if os.path.exists(self.varfile):
150
+ # suffix of the real extension (a name such as "params.v2.yaml" has more than one dot)
151
+ if Path(self.varfile).suffix.lower().lstrip('.') in ["yaml", "yml", "txt"]:
152
+ with open(self.varfile, "r", encoding="utf-8") as file:
153
+ try:
154
+ param_list = yaml.load(file, Loader=yaml.SafeLoader)
155
+ except (yaml.scanner.ScannerError,yaml.parser.ParserError):
156
+ txt_yaml = f'\nx Error while reading {self.varfile}. Edit the yaml file and try again (i.e. use ":" instead of "=" to specify variables)'
157
+ error_yaml = True
158
+ if not error_yaml:
159
+ for param in param_list:
160
+ if hasattr(self, param):
161
+ if getattr(self, param) != param_list[param]:
162
+ setattr(self, param, param_list[param])
163
+
164
+ except UnboundLocalError:
165
+ txt_yaml = "\nx The specified yaml file containing parameters was not found! Make sure that the valid params file is in the folder where you are running the code."
166
+
167
+ return self, txt_yaml
168
+
169
+
170
+ # class for logging
171
+ class Logger:
172
+ """
173
+ Class that wraps a file object to abstract the logging.
174
+ """
175
+
176
+ # Class Logger to writargs.input.split('.')[0] output to a file
177
+ def __init__(self, filein, append, suffix="dat"):
178
+ self.log = open(f"{filein}_{append}.{suffix}", "w", encoding="utf-8")
179
+
180
+ def write(self, message):
181
+ """
182
+ Appends a newline character to the message and writes it into the file.
183
+
184
+ Parameters
185
+ ----------
186
+ message : str
187
+ Text to be written in the log file.
188
+ """
189
+ self.log.write(f"{message}\n")
190
+ print(f"{message}\n")
191
+
192
+ def finalize(self):
193
+ """
194
+ Closes the file
195
+ """
196
+ self.log.close()
197
+
198
+
199
+ def command_line_args(exe_type,sys_args):
200
+ """
201
+ Load default and user-defined arguments specified through command lines. Arrguments are loaded as a dictionary
202
+ """
203
+
204
+ if exe_type == 'exe':
205
+ # Simulate sys.argv for use in an executable environment
206
+ sys.argv = ["launcher.exe"]
207
+ for k, v in sys_args.items():
208
+ sys.argv.append(k)
209
+ if v is not None:
210
+ sys.argv.append(str(v))
211
+
212
+ # First, create dictionary with user-defined arguments
213
+ kwargs = {}
214
+ available_args = ["help"]
215
+ bool_args = [
216
+ "curate",
217
+ "generate",
218
+ "verify",
219
+ "predict",
220
+ "aqme",
221
+ "report",
222
+ "cheers",
223
+ "checkml",
224
+ ]
225
+ list_args = [
226
+ "discard",
227
+ "ignore",
228
+ "train",
229
+ "model",
230
+ "report_modules",
231
+ ]
232
+ int_args = [
233
+ 'pfi_epochs',
234
+ 'epochs',
235
+ 'nprocs',
236
+ 'pfi_max',
237
+ 'kfold',
238
+ 'repeat_kfolds',
239
+ 'shap_show',
240
+ 'pfi_show',
241
+ "seed",
242
+ "init_points",
243
+ "n_iter",
244
+ ]
245
+ float_args = [
246
+ 'pfi_threshold',
247
+ 't_value',
248
+ 'thres_x',
249
+ 'thres_y',
250
+ 'test_set',
251
+ 'desc_thres',
252
+ 'alpha',
253
+ 'expect_improv'
254
+ ]
255
+
256
+ for arg in var_dict:
257
+ if arg in bool_args:
258
+ available_args.append(f"{arg}")
259
+ else:
260
+ # no space before '=' - getopt.long_has_args() checks for an exact "arg=" entry
261
+ # to resolve exact option matches (e.g. "--model") before falling back to prefix-
262
+ # uniqueness checks; a stray space here ("arg =") defeated that exact-match check,
263
+ # which stayed silent as long as no other option shared a prefix with this one, but
264
+ # started raising "option --model not a unique prefix" once model_obj/model_file/
265
+ # model_params (CHECKML) were added as options sharing the "model" prefix
266
+ available_args.append(f"{arg}=")
267
+
268
+ try:
269
+ opts, _ = getopt.getopt(sys.argv[1:], "h", available_args)
270
+ except getopt.GetoptError as err:
271
+ print(err)
272
+ # a nonzero exit code (bare sys.exit() defaults to 0, i.e. "success") so callers that
273
+ # check the exit code - e.g. easyROB's RobertWorker - correctly detect this as a failed
274
+ # run instead of reporting it as finished successfully
275
+ sys.exit(1)
276
+
277
+ for arg, value in opts:
278
+ if arg.find("--") > -1:
279
+ arg_name = arg.split("--")[1].strip()
280
+ elif arg.find("-") > -1:
281
+ arg_name = arg.split("-")[1].strip()
282
+
283
+ if arg_name in ("h", "help"):
284
+ print(f"""\n
285
+ ###########################################################################################
286
+ # #
287
+ # ROBERT v {robert_version} is installed correctly, thanks for using the program! #
288
+ # #
289
+ ###########################################################################################
290
+
291
+
292
+ o How to run a full workflow with ROBERT in the command line?
293
+ -------------------------------------------------------------
294
+
295
+ * From a CSV database: python -m robert --ignore "[COL1,COL2,etc]" --names "names_COL" --y "y_COL" --csv_name "FILENAME.csv"
296
+ * From a CSV with SMILES: python -m robert --aqme --y "y_COL" --csv_name "FILENAME.csv"
297
+
298
+
299
+ o Required options:
300
+ -------------------
301
+
302
+ --ignore "[COL1,COL2,etc]" (default=[]) : CSV columns that will be ignored (i.e., names, ID, etc.)
303
+ --names "names_COL" (default="") : CSV columns containing the names of the datapoints
304
+ --y "y_COL" (default="") : CSV column containing the y values
305
+ --csv_name "FILENAME.csv" (default="") : name of the input CSV
306
+
307
+
308
+ o Other common options:
309
+ -----------------------
310
+
311
+ * General:
312
+ --csv_test "FILENAME.csv" (default="") : name of the CSV containing the external test set
313
+ --discard "[COL1,COL2,etc]" (default=[]) : CSV columns that will be removed
314
+
315
+ * Affecting data curation in CURATE:
316
+ --kfold INT (default=5) : number of folds for k-fold cross-validation of the RFECV feature selector
317
+ --categorical "onehot" or "numbers" (default="onehot") : type of conversion for categorical variables
318
+ --corr_filter_x BOOL (default=True) : activate/disable the correlation filter of descriptors X
319
+ --rfecv_filter BOOL (default=True) : activate/disable RFECV/PFI descriptor selection (runs
320
+ independently of --corr_filter_x, only when descriptors outnumber one-third of the datapoints
321
+ after the correlation filter)
322
+
323
+ * Affecting model screening in GENERATE:
324
+ --model "[MODEL1,MODEL2,etc]" (default=["RF","GB","NN","MVL"]) : ML models to use in the ML scan. To scan a custom subset instead of the default four, list only those (i.e., --model "[RF,GB]" scans just RF and GB). Options:
325
+ - Regression and classification: 'RF', 'GB', 'NN', 'GP', 'AdaB'
326
+ - Regression only: 'MVL', 'RIDGE'
327
+ - Classification only: 'LOGISTIC'
328
+ --type "reg" or "clas" (default="reg") : regression or classification models
329
+ --pfi_max INT (default=0) : number of features to keep in the PFI models
330
+
331
+ * Affecting tests, VERIFY:
332
+ --kfold INT (default=5) : number of folds for k-fold cross-validation
333
+
334
+ * Affecting predictions, PREDICT:
335
+ --t_value INT (default=2) : t-value threshold to identify outliers
336
+ --shap_show INT (default=10) : maximum number of descriptors shown in the SHAP plot
337
+
338
+ * Affecting SMILES workflows, AQME:
339
+ --qdescp_keywords STR (default="") : extra keywords in QDESCP (i.e. "--qdescp_atoms [Ir] --alpb h2o")
340
+ --csearch_keywords STR (default="--sample 50") : extra keywords in CSEARCH
341
+ --descp_lvl (default="interpret") "interpret", "denovo" or "full" : type of descriptor calculation
342
+
343
+
344
+ o How to cite ROBERT and CheckML:
345
+ ---------------------------------
346
+
347
+ ROBERT: {robert_ref}
348
+
349
+ CheckML: {checkml_ref}
350
+
351
+ o Complete documentation:
352
+ -------------------------
353
+
354
+ For more information, see the complete documentation in https://robert.readthedocs.io""")
355
+ sys.exit()
356
+ else:
357
+ # this "if" allows to use * to select multiple files in multiple OS
358
+ if arg_name.lower() == 'files' and value.find('*') > -1:
359
+ kwargs[arg_name] = glob.glob(value)
360
+ else:
361
+ # converts the string parameters from command line to the right format
362
+ if arg_name in bool_args:
363
+ value = True
364
+ elif arg_name.lower() in list_args:
365
+ value = format_lists(value)
366
+ elif arg_name.lower() in int_args:
367
+ value = int(value)
368
+ elif arg_name.lower() in float_args:
369
+ value = float(value)
370
+ elif value == "None":
371
+ value = None
372
+ elif value == "False":
373
+ value = False
374
+ elif value == "True":
375
+ value = True
376
+
377
+ kwargs[arg_name] = value
378
+
379
+ # Second, load all the default variables as an "add_option" object
380
+ args = load_variables(kwargs, "command")
381
+
382
+ return args
383
+
384
+
385
+ def format_lists(value):
386
+ '''
387
+ Transforms strings into a list
388
+ '''
389
+
390
+ if not isinstance(value, list):
391
+ try:
392
+ value = ast.literal_eval(value)
393
+ except (SyntaxError, ValueError):
394
+ # this line fixes issues when using "[X]" or ["X"] instead of "['X']" when using lists
395
+ value = value.replace('[',']').replace(',',']').replace("'",']').split(']')
396
+ while('' in value):
397
+ value.remove('')
398
+
399
+ # remove extra spaces that sometimes are included by mistake
400
+ value = [ele.strip() if isinstance(ele, str) else ele for ele in value]
401
+
402
+ return value
403
+
404
+
405
+ def build_params_dirs(self):
406
+ '''
407
+ Builds the (params_dirs, suffixes, suffix_titles, model_names) quadruplet that
408
+ VERIFY/PREDICT loop over. Normally this is just the winning No_PFI/PFI model
409
+ (GENERATE/Best_model), and model_names is [None, None] (one shared log file, as before).
410
+ With --all_models active, GENERATE also stages every model's own files into
411
+ GENERATE/All_models/{No_PFI,PFI}/{MODEL}/ (see stage_all_models() in generate_utils.py) -
412
+ this discovers whichever of those per-model folders actually exist (not every model
413
+ necessarily has a PFI variant) and loops over all of them instead, so each model gets its
414
+ own full VERIFY/PREDICT pass. model_names then carries the actual model name per entry,
415
+ which the caller uses to split the log file per model (see verify.py/predict.py) instead
416
+ of merging every model's output into one shared VERIFY_data.dat/PREDICT_data.dat, where
417
+ REPORT would have no reliable way to tell which lines belong to which model.
418
+ '''
419
+
420
+ if 'GENERATE/Best_model' in self.args.params_dir:
421
+ if getattr(self.args, 'all_models', False):
422
+ params_dirs, suffixes, suffix_titles, model_names = [], [], [], []
423
+ all_models_dir = self.args.params_dir.replace('Best_model', 'All_models')
424
+ # group entries by MODEL first (No_PFI then PFI for that model), not by PFI
425
+ # variant first - verify.py/predict.py write both entries of a model into the
426
+ # SAME per-model log file, only opening a new Logger (which truncates via mode
427
+ # 'w') when the model name changes. Grouping by PFI variant first would revisit
428
+ # each model a second, non-consecutive time (once per variant), so the later
429
+ # visit would reopen and wipe out the earlier variant's already-written block
430
+ discovered = {}
431
+ for pfi_variant in ['No_PFI', 'PFI']:
432
+ for model_dir in sorted(glob.glob(f'{all_models_dir}/{pfi_variant}/*')):
433
+ discovered.setdefault(os.path.basename(model_dir), {})[pfi_variant] = model_dir
434
+ for model_name in sorted(discovered):
435
+ for pfi_variant, pfi_label in [('No_PFI', 'no PFI filter'), ('PFI', 'PFI filter')]:
436
+ if pfi_variant in discovered[model_name]:
437
+ params_dirs.append(discovered[model_name][pfi_variant])
438
+ suffixes.append(f'(with {pfi_label}, model {model_name})')
439
+ # NOT f'{model_name}_{pfi_variant}': every downstream filename/path
440
+ # builder (save_predictions, plot_metrics, etc.) already independently
441
+ # prepends model_data['model'] to suffix_title (see e.g. predict_utils.py's
442
+ # base_csv_name = f"PREDICT/{model_data['model']}_{suffix_title}") - adding
443
+ # the model name here too would double it up (e.g. "GB_GB_No_PFI")
444
+ suffix_titles.append(pfi_variant)
445
+ model_names.append(model_name)
446
+ else:
447
+ params_dirs = [f'{self.args.params_dir}/No_PFI',f'{self.args.params_dir}/PFI']
448
+ suffixes = ['(with no PFI filter)','(with PFI filter)']
449
+ suffix_titles = ['No_PFI','PFI']
450
+ model_names = [None, None]
451
+ else:
452
+ params_dirs = [self.args.params_dir]
453
+ suffixes = ['custom']
454
+ suffix_titles = ['custom']
455
+ model_names = [None]
456
+
457
+ return params_dirs, suffixes, suffix_titles, model_names
458
+
459
+
460
+ def load_variables(kwargs, robert_module):
461
+ """
462
+ Load default and user-defined variables
463
+ """
464
+
465
+ # first, load default values and options manually added to the function
466
+ self = set_options(kwargs)
467
+
468
+ # this part loads variables from yaml files (if varfile is used)
469
+ txt_yaml = ""
470
+ if self.varfile is not None:
471
+ self, txt_yaml = load_from_yaml(self)
472
+
473
+ # CHECKML always scores exactly one, user-provided model - GENERATE never runs for it, so
474
+ # it never stages a GENERATE/All_models folder (see stage_all_models() in
475
+ # generate_utils.py). CURATE/VERIFY/PREDICT/REPORT chained after CHECKML (the same
476
+ # CHECKML/CHECKML_data.dat marker report.py's eval_only uses) would otherwise keep
477
+ # all_models's True default, have build_params_dirs() look for that folder, find nothing,
478
+ # and silently skip every check instead of evaluating the model. Forced off unconditionally
479
+ # (not just when unset by the caller) since even an explicit all_models=True can't do
480
+ # anything useful here - the underlying per-model data simply doesn't exist.
481
+ # robert_module=='checkml' is excluded so this never touches CHECKML's own (unused)
482
+ # self.all_models: at that point CHECKML_data.dat doesn't exist yet anyway (this call is
483
+ # what's about to create it) - only the modules chained AFTER it are affected
484
+ if robert_module.lower() != 'checkml' and os.path.exists(f'{os.getcwd()}/CHECKML/CHECKML_data.dat'):
485
+ self.all_models = False
486
+
487
+ # check if user used .csv in csv_name
488
+ if not os.path.exists(f"{self.csv_name}") and os.path.exists(f'{self.csv_name}.csv'):
489
+ self.csv_name = f'{self.csv_name}.csv'
490
+
491
+ # check if user used .csv in csv_test
492
+ if self.csv_test and not os.path.exists(f"{self.csv_test}") and os.path.exists(f'{self.csv_test}.csv'):
493
+ self.csv_test = f'{self.csv_test}.csv'
494
+
495
+ # check for spaces in csv file names
496
+ if " " in str(os.path.basename(self.csv_name)):
497
+ print("\nx ERROR: The input CSV file name contains spaces. Please remove spaces from the file name and try again. Spaces in file names can cause problems. Example: use 'my_data.csv' instead of 'my data.csv'.")
498
+ sys.exit()
499
+ if self.csv_test and " " in str(os.path.basename(self.csv_test)):
500
+ print("\nx ERROR: The test CSV file name contains spaces. Please remove spaces from the file name and try again. Spaces in file names can cause problems. Example: use 'test_data.csv' instead of 'test data.csv'.")
501
+ sys.exit()
502
+
503
+ if robert_module != "command":
504
+ self.initial_dir = Path(os.getcwd())
505
+
506
+ # adds --names to --ignore
507
+ if self.names not in self.ignore and self.names != '':
508
+ self.ignore.append(self.names)
509
+
510
+ # creates destination folder
511
+ if robert_module.upper() != 'REPORT':
512
+ self = destination_folder(self,robert_module)
513
+
514
+ # start a log file
515
+ logger_1 = 'ROBERT'
516
+ logger_1, logger_2 = robert_module.upper(), "data"
517
+
518
+ if txt_yaml not in [
519
+ "",
520
+ f"\no Importing ROBERT parameters from {self.varfile}",
521
+ "\nx The specified yaml file containing parameters was not found! Make sure that the valid params file is in the folder where you are running the code.\n",
522
+ ]:
523
+ self.log = Logger(self.destination / logger_1, logger_2)
524
+ self.log.write(txt_yaml)
525
+ self.log.finalize()
526
+ sys.exit()
527
+
528
+ self.log = Logger(self.destination / logger_1, logger_2)
529
+ self.log.write(f"ROBERT v {robert_version} {time_run} \nHow to cite: {robert_ref} {checkml_ref}\n")
530
+
531
+ if self.command_line:
532
+ cmd_print = ''
533
+ cmd_args = sys.argv[1:]
534
+ if self.extra_cmd != '':
535
+ for arg in self.extra_cmd.split():
536
+ cmd_args.append(arg)
537
+ for i,elem in enumerate(cmd_args):
538
+ if elem[0] in ['"',"'"]:
539
+ elem = elem[1:]
540
+ if elem[-1] in ['"',"'"]:
541
+ elem = elem[:-1]
542
+ if elem != '-h' and elem.split('--')[-1] not in var_dict:
543
+ # parse single elements of the list as strings (otherwise the commands cannot be reproduced)
544
+ if '--qdescp_atoms' in elem:
545
+ new_arg = []
546
+ list_qdescp = elem.replace(', ',',').replace(' ,',',').split()
547
+ for j,qdescp_elem in enumerate(list_qdescp):
548
+ if list_qdescp[j-1] == '--qdescp_atoms':
549
+ qdescp_elem = qdescp_elem[1:-1]
550
+ new_elem = []
551
+ for smarts_strings in qdescp_elem.split(','):
552
+ new_elem.append(f'{smarts_strings}'.replace("'",''))
553
+ new_arg.append(f'{new_elem}'.replace(" ",""))
554
+ else:
555
+ new_arg.append(qdescp_elem)
556
+ new_arg = ' '.join(new_arg)
557
+ elem = new_arg
558
+ if cmd_args[i-1].split('--')[-1] in var_dict: # check if the previous word is an arg
559
+ cmd_print += f'"{elem}'
560
+ if i == len(cmd_args)-1 or cmd_args[i+1].split('--')[-1] in var_dict: # check if the next word is an arg, or last word in command
561
+ cmd_print += f'"'
562
+ else:
563
+ cmd_print += f'{elem}'
564
+ if i != len(cmd_args)-1:
565
+ cmd_print += ' '
566
+
567
+ self.log.write(f"Command line used in ROBERT: python -m robert {cmd_print}\n")
568
+
569
+ elif robert_module.upper() == 'REPORT':
570
+ self.path_icons = files("robert").joinpath("report")
571
+
572
+ # sklearnex was deactivated in ROBERT v2.1 because it only accelerated RF
573
+ # using or not the intelex accelerator might affect the results
574
+ # if robert_module.upper() in ['GENERATE','VERIFY','PREDICT']:
575
+ # try:
576
+ # import sklearnex
577
+ # pass
578
+ # except (ModuleNotFoundError,ImportError):
579
+ # self.log.write(f"\nx WARNING! The scikit-learn-intelex accelerator is not installed, the results might vary if it is installed and the execution times might become much longer (if available, use 'pip install scikit-learn-intelex')")
580
+
581
+ if robert_module.upper() in ['GENERATE', 'VERIFY', 'CHECKML']:
582
+ # adjust the default value of error_type for classification
583
+ if self.type.lower() == 'clas':
584
+ if self.error_type not in ['acc', 'mcc', 'f1']:
585
+ self.error_type = 'mcc'
586
+
587
+ if robert_module.upper() in ['PREDICT','VERIFY','REPORT']:
588
+ if self.params_dir == '':
589
+ self.params_dir = 'GENERATE/Best_model'
590
+
591
+ if robert_module.upper() in ['CURATE','GENERATE']:
592
+ if self.type.lower() == 'clas':
593
+ # MVL is a regressor: its linear counterpart for classification is LOGISTIC,
594
+ # so the default screening always keeps one simple linear model (like MVL in
595
+ # regression) next to the tree ensembles and NN
596
+ if any(x.upper() == 'MVL' for x in self.model):
597
+ self.model = [x if x.upper() != 'MVL' else 'LOGISTIC' for x in self.model]
598
+
599
+ models_gen = [] # use capital letters in all the models
600
+ for model_type in self.model:
601
+ models_gen.append(model_type.upper())
602
+ self.model = models_gen
603
+
604
+ if robert_module.upper() == 'CURATE':
605
+ self.log.write(f"\no Starting data curation with the CURATE module")
606
+
607
+ elif robert_module.upper() == 'GENERATE':
608
+ self.log.write(f"\no Starting generation of ML models with the GENERATE module")
609
+
610
+ # Check if the folders exist and if they do, delete and replace them
611
+ folder_names = [self.initial_dir.joinpath('GENERATE/Best_model/No_PFI'), self.initial_dir.joinpath('GENERATE/Raw_data/No_PFI')]
612
+ if self.pfi_filter:
613
+ folder_names.append(self.initial_dir.joinpath('GENERATE/Best_model/PFI'))
614
+ folder_names.append(self.initial_dir.joinpath('GENERATE/Raw_data/PFI'))
615
+ _ = create_folders(folder_names)
616
+
617
+ # if there are missing options, look for them from a previous CURATE job (if any)
618
+ options_dict = {
619
+ 'y': self.y,
620
+ 'names': self.names,
621
+ 'ignore': self.ignore,
622
+ 'csv_name': self.csv_name
623
+ }
624
+ curate_folder = Path(self.initial_dir).joinpath('CURATE')
625
+ curate_csv = f'{curate_folder}/CURATE_options.csv'
626
+ if os.path.exists(curate_csv):
627
+ curate_df = pd.read_csv(curate_csv, encoding='utf-8')
628
+
629
+ for option in options_dict:
630
+ if option == 'ignore':
631
+ # ignore is a list (never ''): merge the columns ignored in CURATE (they
632
+ # are still in the curated CSV, i.e. SMILES) with the ones given here
633
+ curate_ignore = curate_df['ignore'][0]
634
+ curate_ignore = format_lists(curate_ignore) if isinstance(curate_ignore, str) else []
635
+ for col in curate_ignore:
636
+ if col not in self.ignore:
637
+ self.ignore.append(col)
638
+ elif options_dict[option] == '':
639
+ if option == 'y':
640
+ self.y = curate_df['y'][0]
641
+ elif option == 'names':
642
+ self.names = curate_df['names'][0]
643
+ elif option == 'csv_name':
644
+ self.csv_name = curate_df['csv_name'][0]
645
+ # names loaded from CURATE must be ignored as descriptors too (see above)
646
+ if self.names != '' and self.names not in self.ignore:
647
+ self.ignore.append(self.names)
648
+
649
+ # Load class labels if they exist (for classification with string labels)
650
+ if 'class_mapping_reverse' in curate_df.columns:
651
+ self.class_mapping_reverse = _parse_class_mapping_reverse(curate_df['class_mapping_reverse'][0])
652
+ if 'class_0_label' in curate_df.columns and 'class_1_label' in curate_df.columns:
653
+ self.class_0_label = curate_df['class_0_label'][0]
654
+ self.class_1_label = curate_df['class_1_label'][0]
655
+
656
+ elif robert_module.upper() in ['PREDICT','VERIFY']:
657
+ if robert_module.upper() == 'PREDICT':
658
+ self.log.write(f"\no Representation of predictions and analysis of ML models with the PREDICT module")
659
+ elif robert_module.upper() == 'VERIFY':
660
+ self.log.write(f"\no Starting tests to verify the prediction ability of the ML models with the VERIFY module")
661
+
662
+ if '' in [self.names,self.y,self.csv_name]:
663
+ # tries to get names from GENERATE
664
+ if 'GENERATE/Best_model' in self.params_dir:
665
+ params_dirs = [f'{self.params_dir}/No_PFI',f'{self.params_dir}/PFI']
666
+ else:
667
+ params_dirs = [self.params_dir]
668
+ self.args = self
669
+ _,_,_,model_data,csv_name = load_dfs(self,params_dirs[0],'predict',sanity_check=True)
670
+
671
+ self.names = model_data["names"]
672
+ self.y = model_data["y"]
673
+ self.csv_name = csv_name
674
+ # Load error_type if present
675
+ if "error_type" in model_data:
676
+ self.error_type = model_data["error_type"]
677
+ # Ensure we also load the type if present
678
+ if "type" in model_data:
679
+ self.type = model_data["type"]
680
+
681
+ elif robert_module.upper() in ['AQME', 'AQME_TEST']:
682
+ # Check if the csv has 2 columns named smiles or smiles_Suffix. The file is read as text because pandas assigns automatically
683
+ # .1 to duplicate columns. (i.e. SMILES and SMILES.1 if there are two columns named SMILES)
684
+ unique_columns=[]
685
+ with open(self.csv_name, 'r') as datfile:
686
+ lines = datfile.readlines()
687
+ for column in lines[0].split(','):
688
+ if column in unique_columns:
689
+ print(f"\nWARNING! The CSV file contains duplicate columns ({column}). Please, rename or remove these columns. If you want to use more than one SMILES column, use _Suffix (i.e. SMILES_1, SMILES_2, ...)")
690
+ sys.exit()
691
+ else:
692
+ unique_columns.append(column)
693
+
694
+ # Check if there is a column with the name "smiles" or "smiles_" followed by any characters
695
+ if not any(col.lower().startswith("smiles") for col in unique_columns):
696
+ print("\nWARNING! The CSV file does not contain a column with the name 'smiles' or a column starting with 'smiles_'. Please make sure the column exists.")
697
+ sys.exit()
698
+
699
+ # Check if there are duplicate names in code_names in the csv file.
700
+ df = pd.read_csv(self.csv_name, encoding='utf-8')
701
+ unique_entries=[]
702
+ for entry in df['code_name']:
703
+ if entry in unique_entries:
704
+ print(f"\nWARNING! The code_name column in the CSV file contains duplicate entries ({entry}). Please, rename or remove these entries.")
705
+ sys.exit()
706
+ else:
707
+ unique_entries.append(entry)
708
+
709
+ self.log.write(f"\no Starting the generation of AQME descriptors with the AQME module")
710
+
711
+ # initial sanity checks
712
+ if robert_module.upper() != 'REPORT':
713
+ _ = sanity_checks(self, 'initial', robert_module, None)
714
+
715
+ return self
716
+
717
+
718
+ def destination_folder(self,dest_module):
719
+ if self.destination is None:
720
+ self.destination = Path(self.initial_dir).joinpath(dest_module.upper())
721
+ else:
722
+ self.log.write(f"\nx The destination option has not been implemented yet! Please, remove it from your input and stay tuned.")
723
+ sys.exit()
724
+ # this part does not work for know
725
+ # if Path(f"{self.destination}").exists():
726
+ # self.destination = Path(self.destination)
727
+ # else:
728
+ # self.destination = Path(self.initial_dir).joinpath(self.destination)
729
+
730
+ if os.path.exists(self.destination):
731
+ shutil.rmtree(self.destination)
732
+ self.destination.mkdir(exist_ok=True, parents=True)
733
+
734
+ return self
735
+
736
+
737
+ def missing_inputs(self,module,print_err=False):
738
+ """
739
+ Gives the option to input missing variables in the terminal
740
+ """
741
+
742
+ if module.lower() not in ['predict','verify','report','aqme_test']:
743
+ if self.csv_name == '':
744
+ self = check_csv_option(self,'csv_name',print_err)
745
+
746
+ if module.lower() not in ['predict','verify','report','aqme_test']:
747
+ if self.y == '':
748
+ if print_err:
749
+ print(f'\nx Specify a y value (column name) with the y option! (i.e. y="solubility")')
750
+ else:
751
+ self.log.write(f'\nx Specify a y value (column name) with the y option! (i.e. y="solubility")')
752
+ self.y = input('Enter the column with y values: ')
753
+ self.extra_cmd += f' --y {self.y}'
754
+ if not print_err:
755
+ self.log.write(f" - y option set to {self.y} by the user")
756
+
757
+ if module.lower() in ['full_workflow','predict','curate','generate','checkml']:
758
+ if self.names == '':
759
+ if print_err:
760
+ print(f'\nx Specify the column with the entry names! (i.e. names="code_name")')
761
+ else:
762
+ self.log.write(f'\nx Specify the column with the entry names! (i.e. names="code_name")')
763
+ self.names = input('Enter the column with the entry names: ')
764
+ self.extra_cmd += f' --names {self.names}'
765
+ if not print_err:
766
+ self.log.write(f" - names option set to {self.names} by the user")
767
+ if self.names != '' and self.names not in self.ignore:
768
+ self.ignore.append(self.names)
769
+
770
+ return self
771
+
772
+
773
+ def correlation_filter(self, csv_df):
774
+ """
775
+ Discards a) correlated variables and b) variables that do not correlate with the y values, based
776
+ on R**2 values c) reduces the number of descriptors to one third of the datapoints using RFECV.
777
+
778
+ REPRODUCIBILITY GUARANTEES:
779
+ - Columns are sorted alphabetically before any operation
780
+ - Rows are sorted by y value to ensure consistent ordering
781
+ - Tie-breaking in correlations uses alphabetical order
782
+ - RFECV descriptor selection uses sorted feature importances with alphabetical tie-breaking
783
+ """
784
+
785
+ txt_corr = ''
786
+
787
+ # Sort columns alphabetically and rows by y value for reproducibility
788
+ descriptor_cols = [col for col in csv_df.columns if col not in self.args.ignore and col != self.args.y]
789
+ descriptor_cols_sorted = sorted(descriptor_cols)
790
+ other_cols = [col for col in csv_df.columns if col in self.args.ignore or col == self.args.y]
791
+ csv_df = csv_df[descriptor_cols_sorted + other_cols].copy()
792
+ csv_df = csv_df.reset_index(drop=True).sort_values(by=self.args.y, kind='stable').reset_index(drop=True)
793
+
794
+ txt_corr += f'\no Correlation filter activated with these thresholds: thres_x = {self.args.thres_x}'
795
+ if self.args.corr_filter_y:
796
+ txt_corr += f', thres_y = {self.args.thres_y}'
797
+
798
+ descriptors_drop = []
799
+ txt_corr += f'\n Excluded descriptors:'
800
+
801
+ # First pass: remove constant descriptors and those with low correlation to y
802
+ for _,column in enumerate(csv_df.columns):
803
+ if column not in descriptors_drop and column not in self.args.ignore and column != self.args.y:
804
+ # Remove descriptors where all values are the same
805
+ if len(set(csv_df[column])) == 1:
806
+ descriptors_drop.append(column)
807
+ txt_corr += f'\n - {column}: all the values are the same'
808
+
809
+ # Remove descriptors with low correlation to the response values
810
+ # (skip columns already dropped above as constant - no fresh rsquared_y to check)
811
+ if self.args.corr_filter_y and column not in descriptors_drop:
812
+ # Calculate correlation with y for remaining descriptors
813
+ res_y = stats.linregress(csv_df[column],csv_df[self.args.y])
814
+ rsquared_y = res_y.rvalue**2
815
+ if rsquared_y < self.args.thres_y:
816
+ descriptors_drop.append(column)
817
+ txt_corr += f'\n - {column}: R**2 = {rsquared_y:.2} with the {self.args.y} values'
818
+
819
+ self.args.log.write(txt_corr)
820
+
821
+ # Second pass: remove highly correlated descriptors (always removing the most correlated first)
822
+ txt_corr = ''
823
+ csv_df_filtered = csv_df.drop(descriptors_drop, axis=1)
824
+ # only the ignored columns that are actually in the database (e.g. a SMILES column added
825
+ # automatically to --ignore might not exist), otherwise drop() raises a KeyError and the
826
+ # number of descriptors below is miscounted
827
+ ignore_present = [col for col in self.args.ignore if col in csv_df.columns and col != self.args.y]
828
+ csv_df_X_filtered = csv_df_filtered.drop([self.args.y] + ignore_present, axis=1)
829
+ if self.args.corr_filter_x and len(csv_df_X_filtered.columns) > 1:
830
+ # Calculate R2 correlation matrix between descriptors
831
+ corr_matrix = csv_df_X_filtered.corr().abs()
832
+ corr_matrix_r2 = corr_matrix ** 2
833
+ upper = corr_matrix_r2.where(np.triu(np.ones(corr_matrix_r2.shape), k=1).astype(bool))
834
+
835
+ # Calculate R2 of each descriptor with y (for deciding which one to drop)
836
+ r2_with_y = {}
837
+ for col in csv_df_X_filtered.columns:
838
+ res_y = stats.linregress(csv_df_filtered[col], csv_df_filtered[self.args.y])
839
+ r2_with_y[col] = res_y.rvalue**2
840
+
841
+ # Iteratively remove the most correlated descriptors
842
+ while True:
843
+ # Find the maximum R2 correlation
844
+ max_r2 = upper.max().max()
845
+ if max_r2 <= self.args.thres_x or str(max_r2).lower() == 'nan':
846
+ break
847
+
848
+ # Get ALL pairs with maximum correlation, round to avoid floating point issues
849
+ upper_rounded = upper.round(10)
850
+ max_r2_rounded = upper_rounded.max().max()
851
+ row_idx, col_idx = np.where(upper_rounded == max_r2_rounded)
852
+
853
+ # Sort pairs alphabetically for deterministic selection
854
+ pairs = [(upper.index[row_idx[i]], upper.columns[col_idx[i]]) for i in range(len(row_idx))]
855
+ pairs.sort()
856
+ col_name_1, col_name_2 = pairs[0]
857
+
858
+ # Drop the descriptor with lower R2 to y, round for comparison
859
+ r2_1 = round(r2_with_y[col_name_1], 10)
860
+ r2_2 = round(r2_with_y[col_name_2], 10)
861
+
862
+ if r2_1 == r2_2:
863
+ # Tied on R2 with y, drop alphabetically later one
864
+ drop_col = col_name_1 if col_name_1 > col_name_2 else col_name_2
865
+ keep_col = col_name_2 if col_name_1 > col_name_2 else col_name_1
866
+ elif r2_1 < r2_2:
867
+ drop_col = col_name_1
868
+ keep_col = col_name_2
869
+ else:
870
+ drop_col = col_name_2
871
+ keep_col = col_name_1
872
+
873
+ descriptors_drop.append(drop_col)
874
+ txt_corr += f'\n - {drop_col} removed (R2 = {max_r2:.2f} with {keep_col}), kept more predictive descriptor'
875
+
876
+ upper = upper.drop(index=drop_col, columns=drop_col)
877
+ del r2_with_y[drop_col]
878
+
879
+ # Collect all descriptors that were removed
880
+ to_drop = [col for col in csv_df_X_filtered.columns if col not in upper.columns]
881
+
882
+ if to_drop:
883
+ txt_corr += f'\n - Total: {len(to_drop)} descriptors removed due to high correlation with other descriptors'
884
+
885
+ # drop descriptors that did not pass the filters
886
+ csv_df_filtered = csv_df.drop(descriptors_drop, axis=1)
887
+
888
+ # recompute n_descps AFTER the correlation filter (not before it, at line ~731) - the RFECV/
889
+ # PFI check below decides whether descriptor selection is still needed on what's left post-
890
+ # correlation-filter, not on the original pre-filter count. Using the pre-filter count here
891
+ # triggered RFECV/PFI even when the correlation filter alone had already brought the
892
+ # descriptor count under the one-third threshold, running an expensive per-model selection
893
+ # step for no benefit
894
+ n_descps = len(csv_df_filtered.columns)-len(ignore_present)-1
895
+
896
+ if len(descriptors_drop) == 0:
897
+ txt_corr += f'\n - No descriptors were removed'
898
+
899
+ self.args.log.write(txt_corr)
900
+
901
+ # Check if descriptors are more than one third of datapoints
902
+ txt_corr = ''
903
+ descriptors_used = {}
904
+ csv_df_per_model = {}
905
+
906
+ num_descriptors = round(len(csv_df[self.args.y]) / 3)
907
+ if self.args.rfecv_filter and n_descps > num_descriptors:
908
+ cv_type = f'{self.args.repeat_kfolds}x {self.args.kfold}_fold_cv'
909
+ txt_corr += f'\no There are more descriptors than one-third of the data points. A Recursive Feature Elimination with Cross-Validation (RFECV) or permutation feature importance (PFI) using {cv_type} will be performed to select the most relevant descriptors for each model'
910
+ self.args.log.write(txt_corr)
911
+ txt_corr = ''
912
+
913
+ # Perform RFECV for each model specified by the user
914
+ X_df = csv_df_filtered.drop([self.args.y] + ignore_present, axis=1)
915
+ X_scaled_df,_ = scale_df(X_df,None)
916
+ y_df = csv_df_filtered[self.args.y]
917
+
918
+ for model in sorted(self.args.model):
919
+ # Load the parameters of the minimalist model used for RFECV
920
+ rfecv_params = load_minimal_model(model)
921
+ rfecv_params = model_adjust_params(self, model, rfecv_params)
922
+
923
+ estimator = load_model(self, model, **rfecv_params)
924
+
925
+ # Repeated kfold-CV type
926
+ cv_model = RepeatedKFold(n_splits=self.args.kfold, n_repeats=self.args.repeat_kfolds, random_state=self.args.seed)
927
+
928
+ # Select scoring function for RFECV analysis based on the error type
929
+ scoring = get_scoring_key(self.args.type,self.args.error_type)
930
+
931
+ # Use different strategies for models without feature_importances_
932
+ if model.upper() in ['NN', 'GP']:
933
+ # For NN and GP, use a simpler approach: select top features by correlation with y
934
+ # after initial fit, then use permutation importance to rank them
935
+
936
+ # Train the model once on all features
937
+ estimator.fit(X_scaled_df, y_df)
938
+
939
+ # Use permutation importance to rank features
940
+ perm_result = permutation_importance(estimator, X_scaled_df, y_df,
941
+ n_repeats=self.args.pfi_epochs,
942
+ random_state=self.args.seed,
943
+ scoring=scoring,
944
+ n_jobs=1) # Force single thread for reproducibility
945
+
946
+ # Round to reduce floating point variance
947
+ feature_importances = np.round(perm_result.importances_mean, decimals=10)
948
+
949
+ # Create list of (importance, name) tuples for ALL features
950
+ importance_with_names = [(feature_importances[i], X_scaled_df.columns[i])
951
+ for i in range(len(feature_importances))]
952
+
953
+ # Sort by importance (descending) and break ties alphabetically for determinism
954
+ importance_with_names.sort(key=lambda x: (-x[0], x[1])) # Sort by importance DESC, then name ASC
955
+
956
+ # Select top num_descriptors features (or all with positive importance if fewer)
957
+ positive_features = [(imp, name) for imp, name in importance_with_names if imp > 0]
958
+ if len(positive_features) > num_descriptors:
959
+ descriptors_used[model] = [name for _, name in positive_features[:num_descriptors]]
960
+ elif positive_features:
961
+ descriptors_used[model] = [name for _, name in positive_features]
962
+ else:
963
+ # no feature had positive importance (plausible on a small/noisy dataset) -
964
+ # unlike the RFECV branch below (min_features_to_select=2), this had no
965
+ # floor at all, so the model-specific CURATE CSV could end up with ZERO
966
+ # descriptor columns, which later crashes GENERATE's StandardScaler with an
967
+ # opaque sklearn error ("at least one array or dtype is required") instead
968
+ # of a clear message. Fall back to the top-ranked features regardless of
969
+ # sign, same floor of 2 (or fewer if there aren't that many to begin with)
970
+ min_descriptors = min(2,len(importance_with_names))
971
+ descriptors_used[model] = [name for _, name in importance_with_names[:min_descriptors]]
972
+
973
+ # Sort final list alphabetically for consistent ordering in output
974
+ descriptors_used[model] = sorted(descriptors_used[model])
975
+
976
+ txt_corr += f'\n - {model}: {len(descriptors_used[model])} descriptors selected (using PFI)'
977
+
978
+ else:
979
+ # Linear models use coefficients; tree models use feature importances.
980
+ # Set step=1 for most stable/deterministic feature elimination
981
+ selector = RFECV(estimator, scoring=scoring, min_features_to_select=2, cv=cv_model, step=1, n_jobs=1)
982
+ selector.fit(X_scaled_df, y_df)
983
+
984
+ # Get selected features
985
+ selected_mask = selector.support_
986
+ selected_features_list = list(X_scaled_df.columns[selected_mask])
987
+
988
+ # Get feature importances for selected features only
989
+ if model.upper() in ['MVL', 'RIDGE', 'LOGISTIC']:
990
+ coefficients = np.asarray(selector.estimator_.coef_)
991
+ feature_importances = (
992
+ np.abs(coefficients) if coefficients.ndim == 1
993
+ else np.linalg.norm(coefficients, axis=0)
994
+ )
995
+ else:
996
+ # RF, GB and ADAB have feature_importances_.
997
+ feature_importances = selector.estimator_.feature_importances_
998
+
999
+ # Round importances to reduce floating point variance
1000
+ feature_importances = np.round(feature_importances, decimals=10)
1001
+
1002
+ # Create (importance, name) pairs for selected features
1003
+ importance_with_names = list(zip(feature_importances, selected_features_list))
1004
+
1005
+ # Sort by importance (descending) with alphabetical tie-breaking for determinism
1006
+ importance_with_names.sort(key=lambda x: (-x[0], x[1])) # Sort by importance DESC, then name ASC
1007
+
1008
+ # Select top num_descriptors (or all if fewer selected)
1009
+ n_to_select = min(num_descriptors, len(importance_with_names))
1010
+ descriptors_used[model] = [name for _, name in importance_with_names[:n_to_select]]
1011
+
1012
+ # Sort final list alphabetically for consistent ordering in output
1013
+ descriptors_used[model] = sorted(descriptors_used[model])
1014
+
1015
+ txt_corr += f'\n - {model}: {len(descriptors_used[model])} descriptors selected (using RFECV)'
1016
+
1017
+ # Create model-specific dataframe with sorted columns for reproducibility
1018
+ keep_cols = descriptors_used[model] + [self.args.y] + self.args.ignore
1019
+ keep_cols = list(dict.fromkeys(keep_cols)) # Remove duplicates preserving order
1020
+ keep_cols = [col for col in keep_cols if col in csv_df_filtered.columns]
1021
+
1022
+ # Sort descriptor columns alphabetically, keep y and ignore at the end
1023
+ descriptor_cols = [col for col in keep_cols if col not in self.args.ignore and col != self.args.y]
1024
+ other_cols = [col for col in keep_cols if col in self.args.ignore or col == self.args.y]
1025
+ sorted_cols = sorted(descriptor_cols) + sorted([col for col in other_cols if col in self.args.ignore]) + [self.args.y]
1026
+
1027
+ csv_df_per_model[model] = csv_df_filtered[sorted_cols].copy()
1028
+
1029
+ else:
1030
+ if not self.args.rfecv_filter:
1031
+ txt_corr += f'\n x The RFECV/PFI filter was disabled (--rfecv_filter False), descriptor selection was skipped'
1032
+ else:
1033
+ txt_corr += f'\n x The RFECV filter was not applied, there are less descriptors than one-third of the data points ({n_descps} <= {num_descriptors})'
1034
+ # If RFECV is not applied, all models use the same filtered dataframe
1035
+ for model in self.args.model:
1036
+ csv_df_per_model[model] = csv_df_filtered
1037
+
1038
+ self.args.log.write(txt_corr)
1039
+
1040
+ # Return both the general filtered dataframe and model-specific dataframes
1041
+ return csv_df_filtered, csv_df_per_model
1042
+
1043
+
1044
+ def load_minimal_model(model):
1045
+ '''
1046
+ Load the parameters of the minimalist models used for REFCV
1047
+ '''
1048
+
1049
+ minimal_params = {
1050
+ 'RF' : {
1051
+ 'n_estimators': 30,
1052
+ 'max_depth': 10,
1053
+ 'min_samples_split': 2,
1054
+ 'min_samples_leaf': 1,
1055
+ 'min_weight_fraction_leaf': 0,
1056
+ 'max_features': 1,
1057
+ 'ccp_alpha': 0.0,
1058
+ 'max_samples': None
1059
+ },
1060
+ 'GB': {
1061
+ 'n_estimators': 30,
1062
+ 'learning_rate': 0.1,
1063
+ 'max_depth': 10,
1064
+ 'min_samples_split': 2,
1065
+ 'min_samples_leaf': 1,
1066
+ 'subsample': 1.0,
1067
+ 'max_features': None,
1068
+ 'validation_fraction': 0.2,
1069
+ 'min_weight_fraction_leaf': 0.0,
1070
+ 'ccp_alpha': 0.0
1071
+ },
1072
+ 'NN': {
1073
+ 'hidden_layer_1': 4,
1074
+ 'hidden_layer_2': 4,
1075
+ 'max_iter': 200,
1076
+ 'alpha': 0.01,
1077
+ 'tol': 0.0001
1078
+ },
1079
+ 'ADAB': {
1080
+ 'learning_rate': 1.0,
1081
+ 'n_estimators': 30
1082
+ },
1083
+ 'GP': {
1084
+ 'n_restarts_optimizer': 30,
1085
+ },
1086
+ 'MVL': {
1087
+ },
1088
+ 'RIDGE': {
1089
+ 'alpha': 1.0
1090
+ },
1091
+ 'LOGISTIC': {
1092
+ 'C': 1.0
1093
+ }
1094
+ }
1095
+
1096
+ return minimal_params[model]
1097
+
1098
+ def mcc_scorer_clf(y_true,y_pred):
1099
+ """Forces classification predictions to integer for MCC."""
1100
+ # Even if .predict() returns floats, coerce them to integer:
1101
+ y_pred = np.round(y_pred).astype(int)
1102
+
1103
+ return matthews_corrcoef(y_true, y_pred)
1104
+
1105
+ def f1_scorer_clf(y_true,y_pred):
1106
+ """Use binary F1 when possible and micro F1 for multiclass."""
1107
+ y_pred = np.round(y_pred).astype(int)
1108
+ try:
1109
+ return f1_score(y_true, y_pred)
1110
+ except ValueError:
1111
+ return f1_score(y_true, y_pred, average='micro')
1112
+
1113
+ def get_scoring_key(problem_type,error_type):
1114
+ '''
1115
+ Load scoring function for evaluating models
1116
+ '''
1117
+
1118
+ if problem_type.lower() == 'reg':
1119
+ scoring = {
1120
+ 'rmse': 'neg_root_mean_squared_error',
1121
+ # mean (not median) absolute error, the same MAE reported everywhere else
1122
+ 'mae': 'neg_mean_absolute_error',
1123
+ 'r2': 'r2'
1124
+ }.get(error_type)
1125
+ else:
1126
+ # For classification
1127
+ if error_type == 'mcc':
1128
+ # Use the custom MCC scorer that ensures integer predictions
1129
+ scoring = make_scorer(mcc_scorer_clf)
1130
+ elif error_type == 'f1':
1131
+ scoring = make_scorer(f1_scorer_clf)
1132
+ else:
1133
+ scoring = {
1134
+ 'acc': 'accuracy'
1135
+ }.get(error_type)
1136
+
1137
+ return scoring
1138
+
1139
+
1140
+ def check_csv_option(self,csv_option,print_err):
1141
+ '''
1142
+ Checks missing values in input CSV options
1143
+ '''
1144
+
1145
+ if csv_option == 'csv_name':
1146
+ line_print = f'\nx Specify the CSV name for the {csv_option} option!'
1147
+ elif csv_option == 'csv_train':
1148
+ line_print = f'\nx Specify the CSV name containing the TRAINING set!'
1149
+ elif csv_option == 'csv_valid':
1150
+ line_print = f'\nx Specify the CSV name containing the VALIDATION set!'
1151
+
1152
+ if print_err:
1153
+ print(line_print)
1154
+ else:
1155
+ self.log.write(line_print)
1156
+ val_option = input('Enter the name of your CSV file: ')
1157
+ self.extra_cmd += f' --{csv_option} {val_option}'
1158
+ if not print_err:
1159
+ self.log.write(f" - {csv_option} option set to {val_option} by the user")
1160
+
1161
+ if csv_option == 'csv_name':
1162
+ self.csv_name = val_option
1163
+ elif csv_option == 'csv_train':
1164
+ self.csv_train = val_option
1165
+ elif csv_option == 'csv_valid':
1166
+ self.csv_valid = val_option
1167
+
1168
+ return self
1169
+
1170
+
1171
+ def sanity_checks(self, type_checks, module, csv_df):
1172
+ """
1173
+ Check that different variables are set correctly
1174
+ """
1175
+
1176
+ curate_valid = True
1177
+ # adds manual inputs missing from the command line
1178
+ self = missing_inputs(self,module)
1179
+
1180
+ if type_checks == 'initial' and module.lower() not in ['verify','predict']:
1181
+ curate_valid = locate_csv(self,self.csv_name,curate_valid)
1182
+
1183
+ if module.lower() == 'curate':
1184
+ if self.categorical.lower() not in ['onehot','numbers']:
1185
+ self.log.write(f"\nx The categorical option used is not valid! Options: 'onehot', 'numbers'")
1186
+ curate_valid = False
1187
+
1188
+ for thres,thres_name in zip([self.thres_x,self.thres_y],['thres_x','thres_y']):
1189
+ if float(thres) > 1 or float(thres) < 0:
1190
+ self.log.write(f"\nx The {thres_name} option should be between 0 and 1!")
1191
+ curate_valid = False
1192
+
1193
+ elif module.lower() in ['generate','checkml']:
1194
+
1195
+ if self.split.lower() not in ['kn','rnd','stratified','even','extra_q1','extra_q5','auto']:
1196
+ self.log.write(f"\nx The split option used is not valid! Options: 'KN', 'RND', 'stratified', 'even', 'extra_q1', 'extra_q5', 'auto'")
1197
+ curate_valid = False
1198
+
1199
+ if self.split == 'auto':
1200
+ if self.type.lower() == 'reg':
1201
+ self.split = 'even'
1202
+ elif self.type.lower() == 'clas':
1203
+ # stratified guarantees both train and test keep the same class
1204
+ # proportions as the full dataset - a plain random split can, by chance,
1205
+ # leave a class under/over-represented, especially on small datasets
1206
+ self.split = 'stratified'
1207
+
1208
+ if self.type.lower() not in ['reg','clas']:
1209
+ self.log.write(f"\nx The 'type' option used is not valid! Options: 'reg', 'clas'")
1210
+ curate_valid = False
1211
+
1212
+ if module.lower() == 'generate':
1213
+ if len(self.model) == 0:
1214
+ self.log.write(f"\nx The model option used is not valid! Options: 'RF', 'MVL', 'GB', 'ADAB', 'NN', 'GP', 'RIDGE', 'LOGISTIC'")
1215
+ curate_valid = False
1216
+ else:
1217
+ for model_type in self.model:
1218
+ if model_type.upper() not in ['RF','MVL','GB','GP','ADAB','NN','RIDGE','LOGISTIC']:
1219
+ self.log.write(f"\nx The model option used is not valid! Options: 'RF', 'MVL', 'GB', 'ADAB', 'NN', 'GP', 'RIDGE', 'LOGISTIC'")
1220
+ curate_valid = False
1221
+ if model_type.upper() == 'MVL' and self.type.lower() == 'clas':
1222
+ self.log.write(f"\nx Multivariate linear models (MVL in the model_type option) are not compatible with classificaton!")
1223
+ curate_valid = False
1224
+ if model_type.upper() == 'RIDGE' and self.type.lower() == 'clas':
1225
+ self.log.write(f"\nx Ridge regression (RIDGE in the model_type option) is not compatible with classification! Use LOGISTIC instead.")
1226
+ curate_valid = False
1227
+ if model_type.upper() == 'LOGISTIC' and self.type.lower() == 'reg':
1228
+ self.log.write(f"\nx Logistic regression (LOGISTIC in the model_type option) is not compatible with regression, it's a classifier despite the name! Use RIDGE instead.")
1229
+ curate_valid = False
1230
+
1231
+ if module.lower() == 'checkml':
1232
+ # eval_model ('MVL', the legacy default) is only actually used as a fallback when none
1233
+ # of model_obj/model_file/model_params are given - those resolve (and validate) an
1234
+ # arbitrary scikit-learn model instead, see checkml.py's resolve_eval_model()
1235
+ using_custom_model = bool(self.model_obj is not None or self.model_file or self.model_params)
1236
+ if not using_custom_model and self.eval_model.lower() not in ['mvl']:
1237
+ self.log.write(f"\nx The eval_model option used is not valid! Options: 'MVL', or provide model_obj/model_file/model_params for an arbitrary scikit-learn model (i.e., --model_file model.pkl or --model_params model_params.csv)")
1238
+ curate_valid = False
1239
+
1240
+ if type_checks == 'initial' and module.lower() in ['generate','verify','predict','report','checkml']:
1241
+
1242
+ if type_checks == 'initial' and module.lower() in ['generate','verify','checkml']:
1243
+ if self.type.lower() == 'reg' and self.error_type.lower() not in ['rmse','mae','r2']:
1244
+ self.log.write(f"\nx The error_type option is not valid! Options for regression: 'rmse', 'mae', 'r2'")
1245
+ curate_valid = False
1246
+
1247
+ if self.type.lower() == 'clas' and self.error_type.lower() not in ['mcc','f1','acc']:
1248
+ self.log.write(f"\nx The error_type option is not valid! Options for classification: 'mcc', 'f1', 'acc'")
1249
+ curate_valid = False
1250
+
1251
+ if module.lower() in ['verify','predict']:
1252
+ if os.getcwd() in f"{self.params_dir}":
1253
+ path_db = self.params_dir
1254
+ else:
1255
+ path_db = f"{Path(os.getcwd()).joinpath(self.params_dir)}"
1256
+
1257
+ if not os.path.exists(path_db):
1258
+ self.log.write(f'\nx The path of your CSV files doesn\'t exist! Set the folder containing the two CSV files with 1) the parameters of the model and 2) the Xy database with the params_dir option')
1259
+ curate_valid = False
1260
+
1261
+ if module.lower() in ['predict','checkml']:
1262
+ if self.t_value < 0:
1263
+ self.log.write(f"\nx t_value ({self.t_value}) should be higher 0!")
1264
+ curate_valid = False
1265
+
1266
+ if self.csv_test != '':
1267
+ if os.getcwd() in f"{self.csv_test}":
1268
+ path_test = self.csv_test
1269
+ else:
1270
+ path_test = f"{Path(os.getcwd()).joinpath(self.csv_test)}"
1271
+ if not os.path.exists(path_test):
1272
+ self.log.write(f'\nx The path of your CSV file with the test set doesn\'t exist! You specified: {self.csv_test}')
1273
+ curate_valid = False
1274
+
1275
+ if module.lower() == 'report':
1276
+ if len(self.report_modules) == 0:
1277
+ self.log.write(f'\nx No modules were provided in the report_modules option! Options: "CURATE", "GENERATE", "VERIFY", "PREDICT"')
1278
+ curate_valid = False
1279
+
1280
+ for module in self.report_modules:
1281
+ if module.upper() not in ['CURATE','GENERATE','VERIFY','PREDICT','AQME']:
1282
+ self.log.write(f'\nx Module {module} specified in the report_modules option is not a valid module! Options: "CURATE", "GENERATE", "VERIFY", "PREDICT", "AQME"')
1283
+ curate_valid = False
1284
+
1285
+ elif type_checks == 'csv_db':
1286
+ if module.lower() != 'predict':
1287
+ self.y = check_y_column(self.y, self.log, self.discard, self.ignore, csv_df, self.csv_name)
1288
+
1289
+ if not curate_valid:
1290
+ self.log.finalize()
1291
+ sys.exit()
1292
+
1293
+
1294
+ def locate_csv(self,csv_input,curate_valid):
1295
+ '''
1296
+ Assesses whether the input CSV databases can be located
1297
+ '''
1298
+
1299
+ path_csv = ''
1300
+ if os.path.exists(f"{csv_input}"):
1301
+ path_csv = csv_input
1302
+ elif os.path.exists(f"{Path(os.getcwd()).joinpath(csv_input)}"):
1303
+ path_csv = f"{Path(os.getcwd()).joinpath(csv_input)}"
1304
+ if not os.path.exists(path_csv) or csv_input == '':
1305
+ self.log.write(f'\nx The path of your CSV file doesn\'t exist! You specified: --csv_name {csv_input}')
1306
+ curate_valid = False
1307
+
1308
+ return curate_valid
1309
+
1310
+
1311
+ def check_clas_problem(self,csv_df):
1312
+ '''
1313
+ Changes type to classification if there are only two different y values.
1314
+ Automatically converts non-integer class labels to integer codes.
1315
+ Stores the original labels for later reconversion in outputs.
1316
+ '''
1317
+
1318
+ # changes type to classification if there are only two different y values
1319
+ if self.args.type.lower() == 'reg' and self.args.auto_type:
1320
+ num_unique = len(set(csv_df[self.args.y]))
1321
+ if num_unique == 2:
1322
+ self.args.type = 'clas'
1323
+ if self.args.error_type not in ['acc', 'mcc', 'f1']:
1324
+ self.args.error_type = 'mcc'
1325
+ # linear counterpart of MVL for classification (see load_variables())
1326
+ if any(x.upper() == 'MVL' for x in self.args.model):
1327
+ self.args.model = [x if x.upper() != 'MVL' else 'LOGISTIC' for x in self.args.model]
1328
+
1329
+ # sorted (not list(set(...))) for deterministic output regardless of string-hash
1330
+ # randomization, matching this file's reproducibility guarantees elsewhere
1331
+ unique_vals = _sorted_class_values(csv_df[self.args.y])
1332
+ y_val_detect = f'{unique_vals[0]} and {unique_vals[1]}'
1333
+ self.args.log.write(f'\no Only two different y values were detected ({y_val_detect})! The program will consider classification models (same effect as using "--type clas"). This option can be disabled with "--auto_type False"')
1334
+
1335
+ if self.args.type.lower() == 'clas':
1336
+ unique_values = _sorted_class_values(csv_df[self.args.y])
1337
+ if _integer_like_class_values(unique_values):
1338
+ csv_df[self.args.y] = pd.to_numeric(csv_df[self.args.y]).astype(int)
1339
+ else:
1340
+ self.args.class_mapping = {
1341
+ original_label: class_code
1342
+ for class_code, original_label in enumerate(unique_values)
1343
+ }
1344
+ self.args.class_mapping_reverse = {
1345
+ class_code: original_label
1346
+ for original_label, class_code in self.args.class_mapping.items()
1347
+ }
1348
+ if len(unique_values) >= 2:
1349
+ self.args.class_0_label = str(unique_values[0])
1350
+ self.args.class_1_label = str(unique_values[1])
1351
+
1352
+ csv_df[self.args.y] = csv_df[self.args.y].map(self.args.class_mapping).astype(int)
1353
+
1354
+ mapping_txt = ', '.join(
1355
+ f'{original_label} -> {class_code}'
1356
+ for original_label, class_code in self.args.class_mapping.items()
1357
+ )
1358
+ self.args.log.write(f'\no Classification labels converted: {mapping_txt}')
1359
+ self.args.log.write(f' Original labels will be restored in output files')
1360
+
1361
+ # Check that each class has at least 5 points
1362
+ class_counts = csv_df[self.args.y].value_counts()
1363
+ min_class_count = class_counts.min()
1364
+ min_class_label = class_counts.idxmin()
1365
+
1366
+ if min_class_count < 5:
1367
+ # Get original label if available
1368
+ if hasattr(self.args, 'class_mapping_reverse') and min_class_label in self.args.class_mapping_reverse:
1369
+ original_label = self.args.class_mapping_reverse[min_class_label]
1370
+ else:
1371
+ original_label = min_class_label
1372
+
1373
+ class_dist = {}
1374
+ for class_label, count in class_counts.items():
1375
+ if hasattr(self.args, 'class_mapping_reverse') and class_label in self.args.class_mapping_reverse:
1376
+ original_count_label = self.args.class_mapping_reverse[class_label]
1377
+ else:
1378
+ original_count_label = class_label
1379
+ class_dist[str(original_count_label)] = int(count)
1380
+
1381
+ self.args.log.write(f'\nx Insufficient data for classification! One of the classes has only {min_class_count} datapoints (class "{original_label}")')
1382
+ self.args.log.write(f' Each class must have at least 5 datapoints to ensure robust train/validation/test splits')
1383
+ self.args.log.write(f' Current distribution: {class_dist}')
1384
+ self.args.log.write(f' Please add more datapoints for the minority class or consider a different approach')
1385
+ self.args.log.finalize()
1386
+ sys.exit()
1387
+
1388
+ return self
1389
+
1390
+
1391
+ def load_database(self,csv_load,module,print_info=True,external_test=False):
1392
+ '''
1393
+ Loads either a Xy (params=False) or a parameter (params=True) database from a CSV file
1394
+ '''
1395
+
1396
+ # adjust external set in AQME workflows
1397
+ if module.lower() == 'aqme_test':
1398
+ external_test = True
1399
+
1400
+ txt_load = ''
1401
+ # this part fixes CSV files that use ";" as separator
1402
+ with open(csv_load, 'r', encoding='utf-8') as file:
1403
+ lines = file.readlines()
1404
+ if len(lines) > 1 and lines[1].count(';') > 1:
1405
+ new_csv_name = os.path.basename(csv_load).split('.csv')[0].split('.CSV')[0]+'_original.csv'
1406
+ shutil.move(csv_load, Path(os.path.dirname(csv_load)).joinpath(new_csv_name))
1407
+ new_csv_file = open(csv_load, "w", encoding='utf-8')
1408
+ for line in lines:
1409
+ line = line.replace(',','.')
1410
+ line = line.replace(';',',')
1411
+ # line = line.replace(':',',')
1412
+ new_csv_file.write(line)
1413
+ new_csv_file.close()
1414
+ txt_load += f'\nx WARNING! The original database was not a valid CSV (i.e., formatting issues from Microsoft Excel?). A new database using commas as separators was created and used instead, and the original database was stored as {new_csv_name}. To prevent this issue from happening again, you should use commas as separators: https://support.edapp.com/change-csv-separator.\n\n'
1415
+
1416
+ csv_df = pd.read_csv(csv_load, encoding='utf-8')
1417
+ csv_name_load = os.path.basename(csv_load)
1418
+
1419
+ # AQME workflows calculate descriptors from SMILES, so every row needs one: a missing SMILES
1420
+ # would either crash CSEARCH/QDESCP later or, when several are missing, get the whole SMILES
1421
+ # column silently dropped by the missing-data filters below. Includes the external test set
1422
+ # (csv_test), where the target is optional but the SMILES are not
1423
+ if module.lower() in ['aqme','aqme_test']:
1424
+ for column in csv_df.columns:
1425
+ if is_smiles_column(column) and column not in self.args.discard:
1426
+ rows_missing_smiles = csv_df[column].isna() | csv_df[column].astype(str).str.strip().eq('')
1427
+ if rows_missing_smiles.any():
1428
+ self.args.log.write(f'\nx The SMILES column ({column}) has empty values in row(s) {_csv_row_numbers_txt(rows_missing_smiles)} of {csv_name_load}! Descriptors can not be calculated without a SMILES, please fill them in (or remove those rows) and run ROBERT again.')
1429
+ self.args.log.finalize()
1430
+ sys.exit()
1431
+
1432
+ # Sort rows by a stable per-datapoint key (names) for reproducibility across ALL modules -
1433
+ # columns were already order-independent (see the alphabetical column sort below), but rows
1434
+ # weren't: CV-based steps downstream (RFECV/permutation importance in CURATE, hyperparameter
1435
+ # search in GENERATE, diagnostic folds in VERIFY/PREDICT) split the data by row POSITION, so
1436
+ # simply reordering the rows of the input CSV silently changed which datapoints landed in
1437
+ # which fold - and therefore the final score - even though the exact same datapoints were
1438
+ # used. Done after the row-number diagnostics above (which report positions in the ORIGINAL
1439
+ # file, so those need the original order) but before KNN imputation and any other
1440
+ # order-sensitive step
1441
+ if module.lower() not in ['aqme', 'aqme_test'] and self.args.names and self.args.names in csv_df.columns:
1442
+ csv_df = csv_df.sort_values(by=self.args.names, kind='stable').reset_index(drop=True)
1443
+
1444
+ descriptor_cols = [col for col in csv_df.columns if col not in self.args.ignore+self.args.discard and col != self.args.y]
1445
+ min_count = int(0.9 * len(csv_df))
1446
+
1447
+ # Remove columns with <90% data
1448
+ cols_to_drop = [col for col in descriptor_cols if csv_df[col].notna().sum() < min_count]
1449
+ if cols_to_drop:
1450
+ csv_df = csv_df.drop(columns=cols_to_drop)
1451
+ if module.lower() == 'curate':
1452
+ txt_load += f"\n - Removed {len(cols_to_drop)} column(s) with <90% data\n"
1453
+ descriptor_cols = [col for col in csv_df.columns if col not in self.args.ignore+self.args.discard and col != self.args.y]
1454
+
1455
+ # Remove rows with <50% data
1456
+ rows_too_missing = csv_df[descriptor_cols].isna().sum(axis=1) > (0.5 * len(descriptor_cols))
1457
+ if rows_too_missing.any():
1458
+ n_removed_rows = rows_too_missing.sum()
1459
+ csv_df = csv_df[~rows_too_missing].reset_index(drop=True)
1460
+ descriptor_cols = [col for col in csv_df.columns if col not in self.args.ignore+self.args.discard and col != self.args.y]
1461
+ if module.lower() == 'curate':
1462
+ txt_load += f"\n - Removed {n_removed_rows} row(s) with >50% missing descriptors\n"
1463
+
1464
+ # Apply KNN imputer only to numeric columns with missing values (when auto_fill is activated)
1465
+ if self.args.auto_fill:
1466
+ numeric_columns = csv_df.select_dtypes(include=['float']).columns.drop(self.args.y, errors='ignore')
1467
+ if csv_df[numeric_columns].isna().any().any():
1468
+ imputer = KNNImputer(n_neighbors=5)
1469
+ csv_df[numeric_columns] = pd.DataFrame(imputer.fit_transform(csv_df[numeric_columns]), columns=numeric_columns, index=csv_df.index)
1470
+ if module.lower() == 'curate':
1471
+ txt_load += f"\n - Applied KNN imputer to columns with missing values\n"
1472
+ else:
1473
+ # Remove columns with ANY missing value
1474
+ cols_with_missing = [col for col in descriptor_cols if csv_df[col].isna().any() and col not in self.args.ignore+self.args.discard]
1475
+ if cols_with_missing:
1476
+ csv_df = csv_df.drop(columns=cols_with_missing)
1477
+ if module.lower() == 'curate':
1478
+ txt_load += f"\n - Removed {len(cols_with_missing)} column(s) with missing values\n"
1479
+
1480
+ if print_info or module.lower() == 'checkml':
1481
+ sanity_checks(self.args,'csv_db',module,csv_df)
1482
+
1483
+ discard_cols = [col for col in self.args.discard if col in csv_df.columns]
1484
+ if discard_cols:
1485
+ csv_df = csv_df.drop(discard_cols, axis=1)
1486
+
1487
+ if print_info:
1488
+ total_amount = len(csv_df.columns)
1489
+ ignored_descs = len(self.args.ignore)
1490
+ accepted_descs = total_amount - ignored_descs - 1 # the y column is substracted
1491
+ # removes the column that tracks sets - but only if it isn't already counted via
1492
+ # self.args.ignore (CHECKML's robert.main() always appends 'Set' to ignore itself),
1493
+ # otherwise it gets double-subtracted: accepted_descs undercounts by one, and for a
1494
+ # model with exactly one real descriptor that false zero trips the hard "aren't any
1495
+ # valid descriptors" exit below even though the descriptor is actually there and used
1496
+ if 'Set' in csv_df.columns and 'Set' not in self.args.ignore:
1497
+ accepted_descs -= 1
1498
+ ignored_descs += 1
1499
+ if module.lower() not in ['aqme','aqme_test']:
1500
+ csv_name = os.path.basename(csv_load)
1501
+ if module.lower() not in ['predict']:
1502
+ txt_load += f'\no Database {csv_name} loaded successfully, including:'
1503
+ txt_load += f'\n - {len(csv_df[self.args.y])} datapoints'
1504
+ txt_load += f'\n - {accepted_descs} accepted descriptors'
1505
+ txt_load += f'\n - {ignored_descs} ignored descriptors'
1506
+ txt_load += (
1507
+ f"\n - {len(self.args.discard)} discarded descriptors"
1508
+ )
1509
+ else:
1510
+ txt_load += (
1511
+ f"\no External set {csv_name} loaded successfully, "
1512
+ "including:"
1513
+ )
1514
+ txt_load += f"\n - {len(csv_df)} datapoints (rows)"
1515
+ self.args.log.write(txt_load)
1516
+ if accepted_descs == 0:
1517
+ self.args.log.write(f"\nx There aren't any valid descriptors! Check the messages above to see whether the filters have discarded descriptors")
1518
+ sys.exit()
1519
+
1520
+ # Sort columns alphabetically for reproducibility across ALL modules
1521
+ if module.lower() not in ['aqme', 'aqme_test']:
1522
+ # Get descriptor columns (excluding y and ignore)
1523
+ descriptor_cols = [col for col in csv_df.columns if col not in self.args.ignore and col != self.args.y]
1524
+ descriptor_cols_sorted = sorted(descriptor_cols)
1525
+ # Get other columns (y and ignore)
1526
+ other_cols = [col for col in csv_df.columns if col in self.args.ignore or col == self.args.y]
1527
+ # Reorder dataframe with sorted descriptors + other columns
1528
+ sorted_all_cols = descriptor_cols_sorted + other_cols
1529
+ csv_df = csv_df[sorted_all_cols]
1530
+
1531
+ # ignore user-defined descriptors and assign X and y values (but keeps the original database)
1532
+ if module.lower() in ['generate','checkml']:
1533
+ # Only drop columns that actually exist in the dataframe (for model-specific CSVs from CURATE)
1534
+ cols_to_ignore = [col for col in self.args.ignore if col in csv_df.columns]
1535
+ # Also drop 'Set' column if it exists (for model-specific CSVs)
1536
+ if 'Set' in csv_df.columns and 'Set' not in cols_to_ignore:
1537
+ cols_to_ignore.append('Set')
1538
+ csv_df_ignore = csv_df.drop(cols_to_ignore, axis=1)
1539
+ csv_X = csv_df_ignore.drop([self.args.y], axis=1)
1540
+ csv_y = csv_df_ignore[self.args.y]
1541
+
1542
+ # Columns are already sorted from above, just extract them
1543
+ csv_X = csv_X[sorted([col for col in csv_X.columns])]
1544
+
1545
+ else:
1546
+ if external_test and self.args.y not in csv_df.columns:
1547
+ csv_X = csv_df
1548
+ csv_y = None
1549
+ else:
1550
+ csv_X = csv_df.drop([self.args.y], axis=1)
1551
+ csv_y = csv_df[self.args.y]
1552
+
1553
+ return csv_df,csv_X,csv_y
1554
+
1555
+
1556
+ def check_y_column(y_name, log_proc, discard_cols, ignore_cols, csv_df, csv_name_load):
1557
+ """Validate target values, reporting missing or mixed numeric/text entries.
1558
+
1559
+ Checks the target column for missing values in the y column, for values that mix numeric
1560
+ data with non-numeric text in y values, and for missing columns descriptors.
1561
+ On either issue, writes an error to the ROBERT
1562
+ log, finalizes it, and exits the program. Text-only target columns are
1563
+ allowed for classification.
1564
+ """
1565
+
1566
+ if y_name not in csv_df.columns:
1567
+ matching_columns = [
1568
+ column for column in csv_df.columns
1569
+ if isinstance(column, str) and column.casefold() == y_name.casefold()
1570
+ ]
1571
+ if len(matching_columns) == 1:
1572
+ y_name = matching_columns[0]
1573
+ elif len(matching_columns) > 1:
1574
+ log_proc.write(
1575
+ f"\nx The y option specified ({y_name}) matches multiple columns "
1576
+ f"in the csv selected ({csv_name_load}) when ignoring case: "
1577
+ f"{', '.join(str(column) for column in matching_columns)}. "
1578
+ "Please rename the columns so the target is unambiguous."
1579
+ )
1580
+ log_proc.finalize()
1581
+ sys.exit()
1582
+ else:
1583
+ log_proc.write(f"\nx The y option specified ({y_name}) is not a column in the csv selected ({csv_name_load})! If you are using command lines, make sure you add quotation marks like --y \"VALUE\"")
1584
+ log_proc.finalize()
1585
+ sys.exit()
1586
+
1587
+ for option,option_name in zip([discard_cols, ignore_cols],['discard','ignore']):
1588
+ for val in option:
1589
+ if val not in csv_df.columns:
1590
+ log_proc.write(f"\nx Descriptor {val} specified in the {option_name} option is not a column in the csv selected ({csv_name_load})!")
1591
+ log_proc.finalize()
1592
+ sys.exit()
1593
+
1594
+ y_values = csv_df[y_name]
1595
+
1596
+ rows_missing_y = y_values.isna()
1597
+ if rows_missing_y.any():
1598
+ log_proc.write(f'\nx The target column ({y_name}) has empty values in row(s) {_csv_row_numbers_txt(rows_missing_y)} of {csv_name_load}! Missing target values can not be predicted or imputed, please fill them in (or remove those rows) and run ROBERT again.')
1599
+ log_proc.finalize()
1600
+ sys.exit()
1601
+
1602
+ # a column mixing numbers and text (i.e. a stray "N/A" or ">10" in a regression y) is read
1603
+ # by pandas as all-text, so every value is tried as a number instead: all convert = numeric
1604
+ # column, none convert = text class labels (valid in classification), only some = mixed
1605
+ rows_non_numeric_y = pd.to_numeric(y_values, errors='coerce').isna()
1606
+ if rows_non_numeric_y.any() and not rows_non_numeric_y.all():
1607
+ offending_values = ', '.join(f'"{val}"' for val in y_values[rows_non_numeric_y].unique()[:5])
1608
+ log_proc.write(f'\nx The target column ({y_name}) mixes numbers and text! Row(s) {_csv_row_numbers_txt(rows_non_numeric_y)} of {csv_name_load} contain non-numeric values ({offending_values}) while the rest of the column is numeric. Please fix these values (or remove those rows) and run ROBERT again.')
1609
+ log_proc.finalize()
1610
+ sys.exit()
1611
+
1612
+ return y_name
1613
+
1614
+
1615
+ def categorical_transform(self,csv_df,module):
1616
+ ''' converts all columns with strings into categorical values (one hot encoding
1617
+ by default, can be set to numerical 1,2,3... with categorical = True).
1618
+ Troubleshooting! For one-hot encoding, don't use variable names that are
1619
+ also column headers! i.e. DESCRIPTOR "C_atom" contain C2 as a value,
1620
+ but C2 is already a header of a different column in the database. Same applies
1621
+ for multiple columns containing the same variable names.
1622
+ '''
1623
+
1624
+ if module.lower() == 'curate':
1625
+ txt_categor = f'\no Analyzing categorical variables'
1626
+
1627
+ descriptors_to_drop, categorical_vars, new_categor_desc = [],[],[]
1628
+ for column in csv_df.columns:
1629
+ if column not in self.args.ignore and column != self.args.y:
1630
+ if(csv_df[column].dtype == 'object'):
1631
+ descriptors_to_drop.append(column)
1632
+ categorical_vars.append(column)
1633
+ if self.args.categorical.lower() == 'numbers':
1634
+ csv_df[column] = csv_df[column].astype('category')
1635
+ csv_df[column] = csv_df[column].cat.codes
1636
+ else:
1637
+ _ = csv_df[column].unique() # is this necessary?
1638
+ categor_descs = pd.get_dummies(csv_df[column])
1639
+ csv_df = csv_df.drop(column, axis=1)
1640
+ csv_df = pd.concat([csv_df, categor_descs], axis=1)
1641
+ for desc in categor_descs:
1642
+ new_categor_desc.append(desc)
1643
+
1644
+ if module.lower() == 'curate':
1645
+ if len(categorical_vars) == 0:
1646
+ txt_categor += f'\n - No categorical variables were found'
1647
+ else:
1648
+ if self.args.categorical.lower() == 'numbers':
1649
+ txt_categor += f'\n A total of {len(categorical_vars)} categorical variables were converted using the {self.args.categorical} mode in the categorical option:\n'
1650
+ txt_categor += '\n'.join(f' - {var}' for var in categorical_vars)
1651
+ else:
1652
+ txt_categor += f'\n A total of {len(categorical_vars)} categorical variables were converted using the {self.args.categorical} mode in the categorical option'
1653
+ txt_categor += f'\n Initial descriptors:\n'
1654
+ txt_categor += '\n'.join(f' - {var}' for var in categorical_vars)
1655
+ txt_categor += f'\n Generated descriptors:\n'
1656
+ txt_categor += '\n'.join(f' - {var}' for var in new_categor_desc)
1657
+
1658
+ self.args.log.write(f'{txt_categor}')
1659
+
1660
+ return csv_df
1661
+
1662
+
1663
+ def create_folders(folder_names):
1664
+ for folder in folder_names:
1665
+ if os.path.exists(folder):
1666
+ shutil.rmtree(folder)
1667
+ folder.mkdir(exist_ok=True, parents=True)
1668
+
1669
+
1670
+ def finish_print(self,start_time,module):
1671
+ elapsed_time = round(time.time() - start_time, 2)
1672
+ self.args.log.write(f"\nTime {module.upper()}: {elapsed_time} seconds\n")
1673
+ self.args.log.finalize()
1674
+
1675
+
1676
+ def scale_df(csv_X,csv_X_external):
1677
+ '''
1678
+ Scale the X matrix for the training set and the external test set (if any)
1679
+ '''
1680
+
1681
+ scaler = StandardScaler()
1682
+ _ = scaler.fit(csv_X)
1683
+ X_scaled = scaler.transform(csv_X)
1684
+ X_scaled_df = pd.DataFrame(X_scaled, columns = csv_X.columns)
1685
+
1686
+ X_scaled_external_df = None
1687
+ if csv_X_external is not None:
1688
+ X_scaled_external = scaler.transform(csv_X_external)
1689
+ X_scaled_external_df = pd.DataFrame(X_scaled_external, columns = csv_X_external.columns)
1690
+
1691
+ return X_scaled_df,X_scaled_external_df
1692
+
1693
+
1694
+ def Xy_split(csv_df,csv_X,X_scaled_df,csv_y,csv_external_df,csv_X_external,X_scaled_external_df,csv_y_external,test_points,column_names):
1695
+ '''
1696
+ Returns a dictionary with the database divided into train and validation
1697
+ '''
1698
+
1699
+ Xy_data = {}
1700
+
1701
+ if len(test_points) == 0:
1702
+ Xy_data['X_train'] = csv_X
1703
+ Xy_data['X_train_scaled'] = X_scaled_df
1704
+ Xy_data['y_train'] = csv_y
1705
+ Xy_data['names_train'] = csv_df[column_names]
1706
+ # keep the X_test/y_test keys present (as empty) even without an internal test split -
1707
+ # this is a real, supported configuration (--csv_test with --auto_test False keeps the
1708
+ # whole database as training data), but most of this file reads Xy_data['X_test_scaled']
1709
+ # etc. unconditionally, so omitting these keys turns a supported option combo into a
1710
+ # KeyError deep inside VERIFY/PREDICT instead of a graceful "no internal test set"
1711
+ Xy_data['X_test'] = csv_X.iloc[0:0]
1712
+ Xy_data['X_test_scaled'] = X_scaled_df.iloc[0:0]
1713
+ Xy_data['y_test'] = csv_y.iloc[0:0]
1714
+ Xy_data['names_test'] = csv_df[column_names].iloc[0:0]
1715
+
1716
+ else:
1717
+ Xy_data['X_train'] = csv_X.drop(test_points)
1718
+ Xy_data['X_train_scaled'] = X_scaled_df.drop(test_points)
1719
+ Xy_data['y_train'] = csv_y.drop(test_points)
1720
+ Xy_data['X_test'] = csv_X.iloc[test_points]
1721
+ Xy_data['X_test_scaled'] = X_scaled_df.iloc[test_points]
1722
+ Xy_data['y_test'] = csv_y.iloc[test_points]
1723
+ Xy_data['names_train'] = csv_df.drop(test_points)[column_names]
1724
+ Xy_data['names_test'] = csv_df.iloc[test_points][column_names]
1725
+
1726
+ Xy_data['test_points'] = test_points
1727
+
1728
+ if X_scaled_external_df is not None:
1729
+ Xy_data['X_external'] = csv_X_external
1730
+ Xy_data['X_external_scaled'] = X_scaled_external_df
1731
+ if csv_y_external is not None:
1732
+ Xy_data['y_external'] = csv_y_external
1733
+ Xy_data['names_external'] = csv_external_df[column_names]
1734
+
1735
+ return Xy_data
1736
+
1737
+
1738
+ def test_select(self,X_scaled,csv_y):
1739
+ '''
1740
+ Selection of test set (if any)
1741
+ '''
1742
+
1743
+ # adjusts size of the test_set to include at least 4 points regardless of the number of datapoints
1744
+ test_input_size = round(self.args.test_set * len(csv_y))
1745
+ min_test_size = 4
1746
+ selected_size = max(test_input_size,min_test_size)
1747
+
1748
+ # normally sanity_checks() resolves the 'auto' default into a real split method ('even' for
1749
+ # regression, 'stratified' for classification) before this function ever runs - but CHECKML's
1750
+ # lightweight path calls load_database() with print_info=False, which skips sanity_checks()
1751
+ # entirely, so 'auto' can still reach here literally. None of the branches below match it,
1752
+ # which left test_points unassigned before the final test_points.sort() (UnboundLocalError) -
1753
+ # resolve it here too so this function is correct regardless of whether the caller already did
1754
+ if self.args.split.lower() == 'auto':
1755
+ self.args.split = 'stratified' if self.args.type.lower() == 'clas' else 'even'
1756
+
1757
+ # KN's classification branch only handles exactly 2 classes (hardcoded class_0/class_1
1758
+ # groups below); EVEN/EXTRA_Q1/EXTRA_Q5 rely on a continuous, ordered target value (the
1759
+ # "lowest/highest 20% of y", quantile bins, etc.) which has no meaningful equivalent for a
1760
+ # discrete class label, regardless of how many classes there are. RND is always safe.
1761
+ # STRATIFIED (below) stratifies directly by the class labels via StratifiedShuffleSplit, so
1762
+ # it doesn't need a fallback here - it works for any number of classes
1763
+ if self.args.type.lower() == 'clas':
1764
+ split_upper = self.args.split.upper()
1765
+ if split_upper in ('EVEN', 'EXTRA_Q1', 'EXTRA_Q5'):
1766
+ self.args.log.write(f'\nx WARNING! The {self.args.split} split relies on a continuous, ordered target value and isn\'t defined for classification, the STRATIFIED split was used instead.')
1767
+ self.args.split = 'STRATIFIED'
1768
+ elif split_upper == 'KN' and len(set(csv_y)) != 2:
1769
+ self.args.log.write(f'\nx WARNING! The KN split is only available for binary classification, the STRATIFIED split was used instead.')
1770
+ self.args.split = 'STRATIFIED'
1771
+
1772
+ if self.args.split.upper() == 'KN':
1773
+ # k-neighbours data split
1774
+
1775
+ # selects representative training points for each target value in classification problems
1776
+ if self.args.type.lower() == 'clas':
1777
+ class_0_idx = list(csv_y[csv_y == 0].index)
1778
+ class_1_idx = list(csv_y[csv_y == 1].index)
1779
+ class_0_test_size = round((len(class_0_idx)/len(csv_y))*selected_size)
1780
+ class_1_test_size = selected_size-class_0_test_size
1781
+ class_0_train_size = len(class_0_idx) - class_0_test_size
1782
+ class_1_train_size = len(class_1_idx) - class_1_test_size
1783
+
1784
+ # the k-means function internally selects the training points to be as diverse as possible,
1785
+ # but it returns the test points
1786
+ test_class_0 = k_means(self,X_scaled.iloc[class_0_idx],csv_y,class_0_train_size,self.args.seed,class_0_idx)
1787
+ test_class_1 = k_means(self,X_scaled.iloc[class_1_idx],csv_y,class_1_train_size,self.args.seed,class_1_idx)
1788
+ test_points = test_class_0+test_class_1
1789
+
1790
+ else:
1791
+ idx_list = csv_y.index
1792
+ training_size = len(csv_y)-selected_size
1793
+ test_points = k_means(self,X_scaled,csv_y,training_size,self.args.seed,idx_list)
1794
+
1795
+ elif self.args.split.upper() == 'RND':
1796
+ # pass selected_size directly as an exact point count - converting it to a percentage
1797
+ # and back (as done previously) round-trips through two roundings and can inflate the
1798
+ # test set by a point or two, so RND would pick a different-sized test set than the
1799
+ # other split methods for the same test_set/database
1800
+ _, X_test, _, _ = train_test_split(X_scaled, csv_y, test_size=selected_size, random_state=self.args.seed)
1801
+ test_points = X_test.index.tolist()
1802
+
1803
+ elif self.args.split.upper() == 'STRATIFIED':
1804
+
1805
+ if self.args.type.lower() == 'clas':
1806
+ # classification: the class labels themselves are already the natural strata, so
1807
+ # stratify directly on them - no capping extremes or quantile-binning a continuous
1808
+ # value (that's the regression path below). Works for any number of classes, not
1809
+ # just binary, since StratifiedShuffleSplit itself is class-count-agnostic
1810
+ splitter = StratifiedShuffleSplit(n_splits=1, test_size=selected_size, random_state=self.args.seed)
1811
+ # splitter.split() yields (train_idx, test_idx), in that order
1812
+ for _, test_idx in splitter.split(X_scaled, csv_y):
1813
+ test_points = csv_y.index[test_idx].tolist()
1814
+
1815
+ else:
1816
+ size = np.ceil(selected_size * 100 / (len(csv_y)))
1817
+ # Remove the max and min values so they don't end up in the training set
1818
+ # Calculate the number of bins based on the number of points
1819
+ csv_y_capped = csv_y.drop([csv_y.idxmin(), csv_y.idxmax()])
1820
+ X_scaled_capped = X_scaled.loc[csv_y_capped.index]
1821
+
1822
+ # StratifiedShuffleSplit needs at least 1 sample per class/bin in the smaller partition
1823
+ # (which has ~size% of the points), so the bin count can never exceed that partition's
1824
+ # size - otherwise it raises "train_size should be greater or equal to the number of classes"
1825
+ max_bins = max(2, int(size / 100 * len(csv_y_capped)))
1826
+ selected_size = min(selected_size, max_bins)
1827
+
1828
+ y_binned = pd.qcut(csv_y_capped, q=selected_size, labels=False, duplicates='drop')
1829
+
1830
+ # Adjust the number of bins until each class has at least 2 members
1831
+ while y_binned.value_counts().min() < 2 and selected_size > 2:
1832
+ selected_size -= 1
1833
+ y_binned = pd.qcut(csv_y_capped, q=selected_size, labels=False, duplicates='drop')
1834
+ splitter = StratifiedShuffleSplit(n_splits=1, test_size=size / 100, random_state=self.args.seed)
1835
+ # splitter.split() yields (train_idx, test_idx), in that order. test_idx are
1836
+ # positions within the capped (min/max removed) subset, so map them back to the
1837
+ # original row labels via csv_y_capped's index instead of using them directly
1838
+ for _, test_idx in splitter.split(X_scaled_capped, y_binned):
1839
+ test_points = csv_y_capped.index[test_idx].tolist()
1840
+
1841
+ elif self.args.split.upper() == 'EVEN':
1842
+ # Remove the max and min values so they don't end up in the training set
1843
+ csv_y_capped = csv_y.drop([csv_y.idxmin(), csv_y.idxmax()])
1844
+ # Calculate the number of bins based on the number of points
1845
+ y_binned = pd.qcut(csv_y_capped, q=selected_size, labels=False, duplicates='drop')
1846
+
1847
+ # Adjust bin count if any bin has fewer than two elements (happens in imbalanced data, see comment below)
1848
+ temp_size = selected_size
1849
+ while y_binned.value_counts().min() < 2 and temp_size > 2:
1850
+ temp_size -= 1
1851
+ y_binned = pd.qcut(csv_y_capped, q=temp_size, labels=False, duplicates='drop')
1852
+
1853
+ # Determine central validation points for each bin
1854
+ test_points = []
1855
+ for bin_label in y_binned.unique():
1856
+ bin_indices = y_binned[y_binned == bin_label].index
1857
+ sorted_indices = sorted(bin_indices, key=lambda idx: csv_y[idx])
1858
+ test_points.append(sorted_indices[round(len(sorted_indices)/2)])
1859
+
1860
+ # in umbalanced databases, the points cannot be selected entirely even (i.e., if a database
1861
+ # contains 10 points in th 0-10 range, and 1000 points in the 10-90 range, choosing 100
1862
+ # points might cause that all the 10 points in the 0-10 range are selected as test)
1863
+ # For this issue, the points discarded in pd.qcut() are selected randomly to complete the target
1864
+ # amount of points in the test set
1865
+ random_seed = self.args.seed
1866
+ while len(test_points) < selected_size:
1867
+ new_test_point = int(csv_y.sample(n=1, random_state=random_seed).index[0])
1868
+ if new_test_point not in [csv_y.idxmin(), csv_y.idxmax()] + test_points:
1869
+ test_points.append(new_test_point)
1870
+ random_seed += 1
1871
+
1872
+ elif self.args.split.upper() == 'EXTRA_Q1':
1873
+ # 20% lowest points
1874
+ portion = max(1, round(0.2 * len(csv_y)))
1875
+ test_points = csv_y.nsmallest(portion).index.tolist()
1876
+
1877
+ elif self.args.split.upper() == 'EXTRA_Q5':
1878
+ # 20%% highest points
1879
+ portion = max(1, round(0.2 * len(csv_y)))
1880
+ test_points = csv_y.nlargest(portion).index.tolist()
1881
+
1882
+ test_points.sort()
1883
+
1884
+ return test_points
1885
+
1886
+
1887
+ def round_int_param(value, bounds):
1888
+ '''
1889
+ Rounds a continuous BO suggestion to a valid integer value for an integer-type
1890
+ hyperparameter, snapping to the nearest allowed step (4th element of bounds, i.e.
1891
+ (lower, upper, int, step) - defaults to step=1, i.e. every integer, if not given) instead
1892
+ of every single integer. A large range like n_estimators (10-200) rarely needs single-unit
1893
+ resolution, so a coarser step lets each BO iteration cover more meaningfully different
1894
+ configurations instead of two iterations landing on e.g. 71 and 72 trees.
1895
+ '''
1896
+ lower, upper = bounds[0], bounds[1]
1897
+ step = bounds[3] if len(bounds) == 4 else 1
1898
+ n_steps = round((value - lower) / step)
1899
+ rounded = lower + n_steps * step
1900
+ return int(max(lower, min(upper, rounded)))
1901
+
1902
+
1903
+ def generate_lhs_points(pbounds, n_points, random_state=None):
1904
+ """
1905
+ Generate initial points using Latin Hypercube Sampling for better space coverage.
1906
+ LHS ensures uniform distribution across all dimensions of the hyperparameter space.
1907
+
1908
+ Args:
1909
+ pbounds: Dictionary with parameter bounds from BO_hyperparams
1910
+ n_points: Number of initial points to generate
1911
+ random_state: Random seed for reproducibility
1912
+
1913
+ Returns:
1914
+ List of dictionaries with parameter values
1915
+ """
1916
+ # use a local RNG instead of np.random.seed(), which would reset the process-global NumPy
1917
+ # random state and could silently perturb any other code in the process that relies on it
1918
+ rng = np.random.RandomState(random_state)
1919
+
1920
+ param_names = list(pbounds.keys())
1921
+ n_params = len(param_names)
1922
+
1923
+ # Generate LHS samples in [0, 1]^n_params
1924
+ # Each dimension is divided into n_points intervals, and one point is sampled from each interval
1925
+ samples = np.zeros((n_points, n_params))
1926
+ for i in range(n_params):
1927
+ # Create intervals and sample within each
1928
+ intervals = np.linspace(0, 1, n_points + 1)
1929
+ samples[:, i] = rng.uniform(intervals[:-1], intervals[1:])
1930
+ # Shuffle to break correlation between dimensions
1931
+ rng.shuffle(samples[:, i])
1932
+
1933
+ # Scale samples to actual parameter bounds
1934
+ initial_points = []
1935
+ for sample in samples:
1936
+ point = {}
1937
+ for i, param_name in enumerate(param_names):
1938
+ bounds = pbounds[param_name]
1939
+ lower, upper = bounds[:2]
1940
+ # Scale from [0, 1] to [lower, upper]
1941
+ value = lower + sample[i] * (upper - lower)
1942
+ if len(bounds) >= 3 and bounds[2] is int:
1943
+ value = round_int_param(value, bounds)
1944
+ point[param_name] = value
1945
+ initial_points.append(point)
1946
+
1947
+ return initial_points
1948
+
1949
+
1950
+ def BO_optimizer(self,bo_data,Xy_data):
1951
+ # bayes_opt expects plain (lower, upper) bounds, without the int type marker
1952
+ # used by generate_lhs_points() to round integer hyperparameters
1953
+ pbounds = {name: bounds[:2] for name, bounds in BO_hyperparams(bo_data['model']).items()}
1954
+
1955
+ # Initialize Bayesian optimization. No acquisition_function is passed on purpose: bayes_opt
1956
+ # then defaults to UpperConfidenceBound(kappa=2.576), which scales its exploration with the
1957
+ # model's own uncertainty (kappa*std) rather than a fixed absolute margin like Expected
1958
+ # Improvement's xi - the latter needs to be hand-tuned to each dataset's error scale to behave
1959
+ # consistently, which isn't practical across the arbitrary datasets ROBERT is run on
1960
+ optimizer = BayesianOptimization(
1961
+ f=lambda **p: BO_iteration(self, bo_data, Xy_data, **p),
1962
+ pbounds=pbounds,
1963
+ verbose=2,
1964
+ random_state=self.args.seed
1965
+ )
1966
+
1967
+ # this manual probe/suggest loop replaces optimizer.maximize() (see comment below), which is
1968
+ # the only place bayes_opt prints the table header - since maximize() is never called, the
1969
+ # header row is otherwise silently skipped and only the data rows (from probe()) get printed
1970
+ optimizer.logger.log_optimization_start(optimizer.space.keys)
1971
+
1972
+ # Generate initial points using Latin Hypercube Sampling for better space coverage
1973
+ if self.args.init_points > 0:
1974
+ initial_points = generate_lhs_points(
1975
+ pbounds=BO_hyperparams(bo_data['model']),
1976
+ n_points=self.args.init_points,
1977
+ random_state=self.args.seed
1978
+ )
1979
+ # Probe the initial points (evaluated immediately, not lazily queued, since the
1980
+ # manual suggest/probe loop below replaces optimizer.maximize() and needs these
1981
+ # already registered to base its first suggestion on)
1982
+ for params in initial_points:
1983
+ optimizer.probe(params=params, lazy=False)
1984
+
1985
+ # int-type hyperparameters, so they can be rounded below. bayes_opt's own suggest() has no
1986
+ # notion of integer dimensions (pbounds only carries (lower, upper)) - only the LHS points
1987
+ # above get rounded, by generate_lhs_points(). Using optimizer.maximize() directly would
1988
+ # let every iteration from here on suggest and register raw continuous values for these,
1989
+ # even though model_adjust_params() rounds them right before actually building the model -
1990
+ # so the model itself was always fine, but the registered/reported point (and the "best
1991
+ # params" ultimately saved) would misleadingly show decimals for e.g. n_estimators.
1992
+ int_params = {name: bounds for name, bounds in BO_hyperparams(bo_data['model']).items()
1993
+ if len(bounds) >= 3 and bounds[2] is int}
1994
+
1995
+ # Run the optimization (with warnings suppressed for Convergence issues)
1996
+ with warnings.catch_warnings():
1997
+ warnings.filterwarnings("ignore", category=ConvergenceWarning)
1998
+ for _ in range(self.args.n_iter):
1999
+ next_point = optimizer.suggest()
2000
+ for name, bounds in int_params.items():
2001
+ next_point[name] = round_int_param(next_point[name], bounds)
2002
+ optimizer.probe(params=next_point, lazy=False)
2003
+
2004
+ if bo_data['error_type'].upper() in ['RMSE','MAE']:
2005
+ BO_target = -optimizer.max['target']
2006
+ else:
2007
+ BO_target = optimizer.max['target']
2008
+ self.args.log.write(f" o Best combined {bo_data['error_type'].upper()} (target) found in BO for {bo_data['model']} (no PFI filter): {BO_target:.2}")
2009
+
2010
+ # Retrieve best parameters and best result
2011
+ return optimizer.max['params'], BO_target
2012
+
2013
+
2014
+ def BO_iteration(self, bo_data, Xy_data, **params):
2015
+ '''
2016
+ Evaluate a model with given parameters using cross-validation.
2017
+ Returns the mean negative root mean squared error (higher is better).
2018
+ '''
2019
+
2020
+ bo_data['params'] = model_adjust_params(self, bo_data['model'], params)
2021
+ BO_iter_score = load_n_predict(self, bo_data, Xy_data, BO_opt=True)
2022
+
2023
+ return BO_iter_score
2024
+
2025
+
2026
+ def BO_hyperparams(model_name):
2027
+ '''
2028
+ Hyperparameter search space per model, as (lower, upper) for continuous parameters or
2029
+ (lower, upper, int) / (lower, upper, int, step) for integer ones (step defaults to 1,
2030
+ i.e. every integer, if omitted - see round_int_param()).
2031
+
2032
+ Bounds are tuned for ROBERT's typical dataset sizes (mostly 20-100 datapoints, up to
2033
+ ~10,000 at most), which is far smaller than the sample sizes scikit-learn's own defaults
2034
+ assume - so several ranges deliberately sit in a more heavily-regularized/lower-capacity
2035
+ region than scikit-learn's generic defaults (e.g. NN's hidden_layer_1/2, RF/GB's shallower
2036
+ max_depth). A few parameters are intentionally left out of the search entirely:
2037
+
2038
+ - GB's validation_fraction: only has any effect if n_iter_no_change is set, which ROBERT
2039
+ never does, so scikit-learn silently ignores it - searching it wastes BO budget on a
2040
+ parameter with zero effect on the fitted model.
2041
+
2042
+ - RF/GB's min_weight_fraction_leaf: constrains leaf size by weighted sample fraction, but
2043
+ ROBERT never passes sample_weight to fit(), so with implicit uniform weights this is a
2044
+ weaker, redundant echo of min_samples_leaf/min_samples_split (already searched).
2045
+
2046
+ - NN's tol (lbfgs convergence tolerance): affects when the solver stops, not the quality of
2047
+ the fit for the max_iter budget already given, so it's left at scikit-learn's default.
2048
+
2049
+ '''
2050
+
2051
+ model_BO_params = {
2052
+ 'RF' : {
2053
+ 'n_estimators': (10, 200, int, 10),
2054
+ 'max_depth': (5, 20, int),
2055
+ 'min_samples_split': (2, 10, int),
2056
+ 'min_samples_leaf': (2, 10, int),
2057
+ 'max_features': (0.1, 1.0),
2058
+ 'ccp_alpha': (0, 0.05),
2059
+ 'max_samples': (0.5, 1.0)
2060
+ },
2061
+ 'GB': {
2062
+ 'n_estimators': (10, 200, int, 10),
2063
+ 'learning_rate': (0.01, 0.3),
2064
+ 'max_depth': (2, 10, int), # boosting needs shallower trees than bagging (sklearn's own GB default is 3, vs RF's unlimited)
2065
+ 'min_samples_split': (2, 10, int),
2066
+ 'min_samples_leaf': (2, 10, int),
2067
+ 'subsample': (0.7, 1.0),
2068
+ 'max_features': (0.1, 1.0),
2069
+ 'ccp_alpha': (0, 0.05)
2070
+ },
2071
+ 'NN': {
2072
+ 'hidden_layer_1': (1, 10, int),
2073
+ 'hidden_layer_2': (0, 10, int),
2074
+ 'max_iter': (200, 500, int, 25),
2075
+ 'alpha': (0.0001, 0.1) # widened down to sklearn's own default (0.0001) - the previous
2076
+ # floor of 0.01 excluded that entire region from the search
2077
+ },
2078
+ 'ADAB': {
2079
+ 'learning_rate': (0.1, 5),
2080
+ 'n_estimators': (10, 100, int, 5)
2081
+ },
2082
+ 'GP': {
2083
+ 'n_restarts_optimizer': (0, 20, int), # scikit-learn's own guidance: 5-10 restarts is
2084
+ # typical in practice, the old upper bound of 100
2085
+ # went far past where more restarts help
2086
+ },
2087
+ 'RIDGE': {
2088
+ 'alpha': (0.01, 100) # standard grid-search range for L2 regularization strength -
2089
+ # spans from near-unregularized (close to MVL) to heavily
2090
+ # regularized
2091
+ },
2092
+ 'LOGISTIC': {
2093
+ 'C': (0.01, 100) # standard grid-search range for inverse regularization strength -
2094
+ # small C = more regularization, large C = closer to unregularized
2095
+ }
2096
+ }
2097
+
2098
+ return model_BO_params[model_name]
2099
+
2100
+
2101
+ def BO_metrics(self, bo_data, Xy_data):
2102
+ '''
2103
+ Get combined score for repeated k-fold and top-bottom sorted CVs (used in BO)
2104
+ '''
2105
+
2106
+ metric_combined = load_n_predict(self, bo_data, Xy_data, BO_opt=True)
2107
+ if bo_data['error_type'].upper() in ['RMSE','MAE']:
2108
+ metric_combined = -metric_combined
2109
+ bo_data[f"combined_{bo_data['error_type']}"] = metric_combined
2110
+
2111
+ return bo_data
2112
+
2113
+
2114
+ _SKLEARN_ESTIMATOR_CACHE = {}
2115
+
2116
+
2117
+ def resolve_sklearn_estimator(model_name, pred_type):
2118
+ '''
2119
+ Resolve a scikit-learn estimator CLASS (not yet instantiated) by its exact class name,
2120
+ restricted to sklearn's own registered estimators (sklearn.utils.all_estimators()) - this
2121
+ never imports/executes anything outside sklearn, even though the name can ultimately come
2122
+ from a user-provided file (CHECKML's --model_params/--model_file). Returns None if the
2123
+ name isn't a real sklearn regressor/classifier (or isn't available in this sklearn version).
2124
+ '''
2125
+
2126
+ key = 'regressor' if pred_type.lower() == 'reg' else 'classifier'
2127
+ if key not in _SKLEARN_ESTIMATOR_CACHE:
2128
+ from sklearn.utils import all_estimators
2129
+ _SKLEARN_ESTIMATOR_CACHE[key] = dict(all_estimators(type_filter=key))
2130
+ return _SKLEARN_ESTIMATOR_CACHE[key].get(model_name)
2131
+
2132
+
2133
+ def model_adjust_params(self,model_name,params):
2134
+ '''
2135
+ Add seed and convert parameters to integers, since they come as floats with decimals in the iterations
2136
+
2137
+ '''
2138
+
2139
+ known_models = ['RF','GB','NN','ADAB','GP','RIDGE','LOGISTIC']
2140
+
2141
+ if model_name in known_models:
2142
+ params['random_state'] = self.args.seed
2143
+
2144
+ if model_name in ['RF','GB']:
2145
+ params['n_estimators'] = round(params['n_estimators'])
2146
+ params['max_depth'] = round(params['max_depth'])
2147
+ params['min_samples_split'] = round(params['min_samples_split'])
2148
+ params['min_samples_leaf'] = round(params['min_samples_leaf'])
2149
+
2150
+ elif model_name == 'NN':
2151
+ # add solver first
2152
+ params['solver'] = 'lbfgs'
2153
+ params['max_iter'] = round(params['max_iter'])
2154
+ params['hidden_layer_1'] = round(params['hidden_layer_1'])
2155
+ params['hidden_layer_2'] = round(params['hidden_layer_2'])
2156
+
2157
+ elif model_name == 'ADAB':
2158
+ params['n_estimators'] = round(params['n_estimators'])
2159
+
2160
+ elif model_name == 'GP':
2161
+ params['n_restarts_optimizer'] = round(params['n_restarts_optimizer'])
2162
+
2163
+ elif model_name == 'LOGISTIC':
2164
+ # avoids lbfgs convergence warnings within scikit-learn's default max_iter=100 -
2165
+ # not searched (doesn't affect fit quality, only how long convergence takes)
2166
+ if 'max_iter' not in params:
2167
+ params['max_iter'] = 1000
2168
+
2169
+ elif model_name != 'MVL':
2170
+ # arbitrary scikit-learn model (see CHECKML's --model_params/--model_file) - only fill
2171
+ # in a seed if this class actually accepts one (most linear/neighbor-based models don't
2172
+ # take random_state at all and would raise a TypeError on instantiation) AND the user
2173
+ # didn't already set their own random_state - unlike ROBERT's own BO-tuned models above
2174
+ # (whose search space never includes random_state, so there's nothing to defer to), a
2175
+ # user-supplied value here was typed on purpose (e.g. to match how they originally
2176
+ # trained the model) and silently overwriting it would evaluate a different model than
2177
+ # the one the user thinks they're evaluating, while still looking fully reproducible
2178
+ if 'random_state' not in params:
2179
+ model_cls = resolve_sklearn_estimator(model_name, self.args.type)
2180
+ if model_cls is not None:
2181
+ import inspect
2182
+ if 'random_state' in inspect.signature(model_cls.__init__).parameters:
2183
+ params['random_state'] = self.args.seed
2184
+ self.args.log.write(f"\no The custom {model_name} parameters didn't include a random_state - using --seed ({self.args.seed}, always defined, default 0) as its random_state instead.")
2185
+
2186
+ return params
2187
+
2188
+
2189
+ def load_model(self, model_name, **params):
2190
+ """
2191
+ Load models with their corresponding parameters.
2192
+ """
2193
+
2194
+ if model_name == 'RF':
2195
+ # Ensure n_jobs=1 for reproducibility if not already in params
2196
+ if 'n_jobs' not in params:
2197
+ params['n_jobs'] = 1
2198
+ if self.args.type.lower() == 'reg':
2199
+ loaded_model = RandomForestRegressor(**params)
2200
+ else:
2201
+ loaded_model = RandomForestClassifier(**params)
2202
+
2203
+ elif model_name == 'GB':
2204
+ # GradientBoosting doesn't have n_jobs parameter, it's already deterministic
2205
+ if self.args.type.lower() == 'reg':
2206
+ loaded_model = GradientBoostingRegressor(**params)
2207
+ else:
2208
+ loaded_model = GradientBoostingClassifier(**params)
2209
+
2210
+ elif model_name == 'NN':
2211
+ # create the hidden layers architecture first
2212
+ params = setup_hidden_layers(params)
2213
+
2214
+ if self.args.type.lower() == 'reg':
2215
+ loaded_model = MLPRegressor(**params)
2216
+ else:
2217
+ loaded_model = MLPClassifier(**params)
2218
+
2219
+ elif model_name == 'ADAB':
2220
+ if self.args.type.lower() == 'reg':
2221
+ loaded_model = AdaBoostRegressor(**params)
2222
+ else:
2223
+ loaded_model = AdaBoostClassifier(**params)
2224
+
2225
+ elif model_name == 'GP':
2226
+ if self.args.type.lower() == 'reg':
2227
+ loaded_model = GaussianProcessRegressor(**params)
2228
+ else:
2229
+ loaded_model = GaussianProcessClassifier(**params)
2230
+
2231
+ elif model_name == 'MVL':
2232
+ loaded_model = LinearRegression(**params)
2233
+
2234
+ elif model_name == 'RIDGE':
2235
+ # regression only - unlike RF/GB/NN/ADAB/GP, Ridge has no natural classifier
2236
+ # counterpart under the same name (sanity_checks() already rejects RIDGE for type='clas')
2237
+ loaded_model = Ridge(**params)
2238
+
2239
+ elif model_name == 'LOGISTIC':
2240
+ # classification only - despite the name, LogisticRegression is a classifier, not a
2241
+ # regressor (sanity_checks() already rejects LOGISTIC for type='reg')
2242
+ loaded_model = LogisticRegression(**params)
2243
+
2244
+ else:
2245
+ # not one of ROBERT's built-in short codes - resolve it as an arbitrary scikit-learn
2246
+ # estimator by its exact class name instead (see CHECKML's --model_params/
2247
+ # --model_file/--model_obj, which is where a name like this comes from)
2248
+ model_cls = resolve_sklearn_estimator(model_name, self.args.type)
2249
+ if model_cls is None:
2250
+ self.args.log.write(f"\nx WARNING! '{model_name}' is not a valid scikit-learn {self.args.type} estimator name (or isn't available in this scikit-learn version). Check the exact class name (e.g., 'RandomForestRegressor').")
2251
+ sys.exit()
2252
+ try:
2253
+ loaded_model = model_cls(**params)
2254
+ except TypeError as error:
2255
+ self.args.log.write(f"\nx WARNING! Invalid hyperparameters for {model_name}: {error}")
2256
+ sys.exit()
2257
+
2258
+ return loaded_model
2259
+
2260
+
2261
+ def setup_hidden_layers(params):
2262
+ '''
2263
+ Build hidden layer structure from provided parameters
2264
+ '''
2265
+
2266
+ hidden_layer_sizes = []
2267
+ hidden_layer_1 = params.pop('hidden_layer_1')
2268
+ hidden_layer_2 = params.pop('hidden_layer_2')
2269
+ if hidden_layer_1 > 0:
2270
+ hidden_layer_sizes.append(hidden_layer_1)
2271
+ if hidden_layer_2 > 0:
2272
+ hidden_layer_sizes.append(hidden_layer_2)
2273
+ hidden_layer_sizes = tuple(hidden_layer_sizes) if hidden_layer_sizes else (1,)
2274
+
2275
+ params['hidden_layer_sizes'] = hidden_layer_sizes
2276
+
2277
+ return params
2278
+
2279
+
2280
+ def _conformal_abs_residual_quantile(abs_residuals, coverage):
2281
+ """
2282
+ Finite-sample quantile for split-style conformal symmetric intervals
2283
+ (nonconformity score = absolute residual).
2284
+ """
2285
+ abs_r = np.asarray(abs_residuals, dtype=float)
2286
+ n = int(abs_r.size)
2287
+ if n < 1:
2288
+ return float("nan")
2289
+ alpha = 1.0 - float(coverage)
2290
+ if not (0.0 < alpha < 1.0):
2291
+ return float("nan")
2292
+ level = min(1.0, np.ceil((n + 1) * (1 - alpha)) / n)
2293
+ return float(np.quantile(abs_r, level, method="higher"))
2294
+
2295
+
2296
+ def _apply_full_refit_split_conformal(
2297
+ self,
2298
+ model_data,
2299
+ Xy_data,
2300
+ loaded_model,
2301
+ y_cv_mean_train=None,
2302
+ overwrite_predictions=False,
2303
+ output_prefix="full_refit"):
2304
+ """
2305
+ Optional full-refit uncertainty path for API/BO experiments.
2306
+
2307
+ The normal ROBERT workflow uses repeated-CV predictions from
2308
+ ``repeated_kfold_cv``. This helper only overwrites ``y_pred_*`` when an
2309
+ explicit caller requests it; otherwise results are stored under
2310
+ ``{output_prefix}_*`` keys so the standard outputs remain untouched.
2311
+ """
2312
+ reg = model_data["type"].lower() == "reg"
2313
+ m_full = clone(loaded_model)
2314
+ X_tr = Xy_data["X_train_scaled"]
2315
+ y_tr = Xy_data["y_train"]
2316
+
2317
+ def select_rows(data, idx):
2318
+ if hasattr(data, "iloc"):
2319
+ return data.iloc[idx]
2320
+ return np.asarray(data)[idx]
2321
+
2322
+ def format_predictions(pred):
2323
+ pred_arr = np.asarray(pred).ravel()
2324
+ if reg:
2325
+ return np.asarray(pred_arr, dtype=float).tolist()
2326
+ return [int(round(float(v))) for v in pred_arr]
2327
+
2328
+ def pred_key(set_name):
2329
+ if overwrite_predictions:
2330
+ return f"y_pred_{set_name}"
2331
+ return f"{output_prefix}_y_pred_{set_name}"
2332
+
2333
+ m_full.fit(X_tr, y_tr)
2334
+ Xy_data[pred_key("train")] = format_predictions(m_full.predict(X_tr))
2335
+
2336
+ if "X_test_scaled" in Xy_data:
2337
+ Xy_data[pred_key("test")] = format_predictions(
2338
+ m_full.predict(Xy_data["X_test_scaled"])
2339
+ )
2340
+
2341
+ if "X_external_scaled" in Xy_data:
2342
+ Xy_data[pred_key("external")] = format_predictions(
2343
+ m_full.predict(Xy_data["X_external_scaled"])
2344
+ )
2345
+
2346
+ hw = float("nan")
2347
+ if reg and bool(getattr(self.args, "conformal_enable", True)):
2348
+ cov = float(getattr(self.args, "conformal_coverage", 0.9))
2349
+ cal_frac = float(getattr(self.args, "conformal_calib_frac", 0.15))
2350
+ y_flat = np.asarray(y_tr, dtype=float).ravel()
2351
+ n = len(y_flat)
2352
+ min_fit = 5
2353
+ min_cal = 3
2354
+ n_cal_target = max(min_cal, int(round(n * cal_frac)))
2355
+ n_fit = n - n_cal_target
2356
+ if n_cal_target >= min_cal and n_fit >= min_fit:
2357
+ idx = np.arange(n)
2358
+ fit_ix, cal_ix = train_test_split(
2359
+ idx,
2360
+ test_size=n_cal_target / n,
2361
+ random_state=int(self.args.seed),
2362
+ shuffle=True,
2363
+ )
2364
+ est_cal = clone(loaded_model)
2365
+ X_fit = select_rows(X_tr, fit_ix)
2366
+ X_cal = select_rows(X_tr, cal_ix)
2367
+ y_fit = select_rows(y_tr, fit_ix)
2368
+ y_cal_arr = np.asarray(select_rows(y_tr, cal_ix), dtype=float).ravel()
2369
+ est_cal.fit(X_fit, y_fit)
2370
+ pred_cal = np.asarray(est_cal.predict(X_cal), dtype=float).ravel()
2371
+ abs_res = np.abs(y_cal_arr - pred_cal)
2372
+ hw = _conformal_abs_residual_quantile(abs_res, cov)
2373
+ elif y_cv_mean_train is not None:
2374
+ y_cv = np.asarray(y_cv_mean_train, dtype=float).ravel()
2375
+ if y_cv.size == y_flat.size:
2376
+ finite_mask = np.isfinite(y_flat) & np.isfinite(y_cv)
2377
+ abs_res = np.abs(y_flat[finite_mask] - y_cv[finite_mask])
2378
+ hw = _conformal_abs_residual_quantile(abs_res, cov)
2379
+
2380
+ hw_key = "conformal_half_width" if overwrite_predictions else f"{output_prefix}_conformal_half_width"
2381
+ Xy_data[hw_key] = hw
2382
+ return Xy_data
2383
+
2384
+
2385
+ def load_n_predict(self, model_data, Xy_data, BO_opt=False, verify_job=False):
2386
+ '''
2387
+ Load model and calculate errors/precision and predicted values of the ML models
2388
+ '''
2389
+
2390
+ # set the parameters for the ML model and load it
2391
+ loaded_model = load_model(self, model_data['model'], **model_data['params'])
2392
+
2393
+ # calculate predicted y values using repeated k-fold CV
2394
+ Xy_data = repeated_kfold_cv(model_data,loaded_model,Xy_data,BO_opt)
2395
+
2396
+ # combine all the predictions from the repeated CV (metrics of the train set)
2397
+ y_all_list,y_pred_all_list = [],[]
2398
+ for y_val,y_pred_vals in zip(Xy_data['y_train'],Xy_data['y_pred_train_all']):
2399
+ for y_pred_val in y_pred_vals:
2400
+ y_all_list.append(y_val)
2401
+ y_pred_all_list.append(y_pred_val)
2402
+
2403
+ # get metrics for the different sets
2404
+ error_labels = {'reg': ['r2','mae','rmse'],
2405
+ 'clas': ['acc','f1','mcc']
2406
+ }
2407
+
2408
+ error1 = error_labels[model_data['type']][0]
2409
+ error2 = error_labels[model_data['type']][1]
2410
+ error3 = error_labels[model_data['type']][2]
2411
+ Xy_data[f'{error1}_train'], Xy_data[f'{error2}_train'], Xy_data[f'{error3}_train'] = get_prediction_results(model_data,y_all_list,y_pred_all_list)
2412
+ if not BO_opt:
2413
+ Xy_data[f'{error1}_test'], Xy_data[f'{error2}_test'], Xy_data[f'{error3}_test'] = get_prediction_results(model_data,Xy_data['y_test'],Xy_data['y_pred_test'])
2414
+ if 'y_external' in Xy_data and len(Xy_data['y_external']) > 0 and Xy_data['y_external'].notna().any():
2415
+ # external targets can be partially known (e.g. predicting on some new, unlabeled
2416
+ # compounds) - score only the rows with a known target instead of skipping every
2417
+ # external metric just because a few rows are NaN
2418
+ y_ext_mask = Xy_data['y_external'].notna().to_numpy()
2419
+ y_ext_known = Xy_data['y_external'][y_ext_mask]
2420
+ y_pred_ext_known = np.asarray(Xy_data['y_pred_external'])[y_ext_mask]
2421
+ Xy_data[f'{error1}_external'], Xy_data[f'{error2}_external'], Xy_data[f'{error3}_external'] = get_prediction_results(model_data,y_ext_known,y_pred_ext_known)
2422
+ if 'y_pred_train_infold' in Xy_data:
2423
+ # in-fold training fit (used for the train-vs-validation gap score)
2424
+ Xy_data[f'{error1}_train_infold'], Xy_data[f'{error2}_train_infold'], Xy_data[f'{error3}_train_infold'] = get_prediction_results(model_data,Xy_data['y_train'],Xy_data['y_pred_train_infold'])
2425
+ if BO_opt:
2426
+ # calculate sorted CV and its metrics
2427
+ # print the target that is above the BO
2428
+ # print the final result of the BO just after finishing all the iterations
2429
+ # include_test=verify_job: the Low/High report metrics (VERIFY's call, verify_job=True)
2430
+ # need the sorted CV over the whole dataset, but GENERATE's BO/PFI hyperparameter
2431
+ # search (verify_job=False here) must never let the test set leak into tuning
2432
+ Xy_data = sorted_kfold_cv(loaded_model, model_data, Xy_data, error_labels, include_test=verify_job)
2433
+ combined_score = (Xy_data[f'{model_data["error_type"]}_train'] + Xy_data[f'{model_data["error_type"]}_up_bottom']) / 2
2434
+
2435
+ # Return if this is part of a verify job
2436
+ if verify_job:
2437
+ return Xy_data
2438
+
2439
+ # Return negative score for MAE/RMSE in BO
2440
+ if model_data["error_type"].lower() in ['mae', 'rmse']:
2441
+ return -combined_score
2442
+ else:
2443
+ return combined_score
2444
+ else:
2445
+ return Xy_data
2446
+
2447
+
2448
+ def repeated_kfold_cv(model_data,loaded_model,Xy_data,BO_opt):
2449
+ '''
2450
+ Performs a repeated k-fold cross-validation on the Xy dataset
2451
+ '''
2452
+
2453
+ # create a list of lists with the same number of entries as y
2454
+ y_global,y_pred_global = [],[]
2455
+ y_pred_global_train_infold = []
2456
+ for _ in range(len(Xy_data['y_train'])):
2457
+ y_pred_global.append([])
2458
+ y_global.append([])
2459
+ y_pred_global_train_infold.append([])
2460
+
2461
+ y_pred_global_test = []
2462
+ for _ in range(len(Xy_data['y_test'])):
2463
+ y_pred_global_test.append([])
2464
+
2465
+ y_global_external,y_pred_global_external = [],[]
2466
+ if 'X_external' in Xy_data: # if there is an external test set
2467
+ for _ in range(len(Xy_data['X_external'])):
2468
+ y_pred_global_external.append([])
2469
+ y_global_external.append([])
2470
+
2471
+ # start the repeated CV
2472
+ for CV_repeat in range(int(model_data['repeat_kfolds'])):
2473
+ _,y_pred_global,y_pred_global_test,y_pred_global_external,y_pred_global_train_infold = kfold_cv(y_global,y_pred_global,
2474
+ y_pred_global_test,
2475
+ y_pred_global_external,
2476
+ model_data,loaded_model,
2477
+ Xy_data,CV_repeat,BO_opt=BO_opt,
2478
+ y_pred_global_train_infold=y_pred_global_train_infold)
2479
+
2480
+ # the per-point SDs are kept unrounded: rounding them here (e.g. to 2 decimals) made the
2481
+ # stability scores depend on the units of y, since small-scale targets (e.g. a y range of
2482
+ # 0.05) rounded every SD to 0.00 and got full points in item 6 regardless of the model
2483
+ y_train_pred, y_train_std = [],[]
2484
+ for y_val in y_pred_global:
2485
+ if model_data['type'].lower() == 'reg':
2486
+ y_train_pred.append(np.mean(y_val))
2487
+ elif model_data['type'].lower() == 'clas':
2488
+ y_train_pred.append(_classification_vote(y_val))
2489
+ y_train_std.append(float(np.std(y_val)))
2490
+
2491
+ Xy_data['y_pred_train_all'] = y_pred_global
2492
+ Xy_data['y_pred_train'] = y_train_pred
2493
+ Xy_data['y_pred_train_sd'] = y_train_std
2494
+
2495
+ if not BO_opt:
2496
+ y_test_pred, y_test_std = [],[]
2497
+ for y_val_test in y_pred_global_test:
2498
+ if model_data['type'].lower() == 'reg':
2499
+ y_test_pred.append(np.mean(y_val_test))
2500
+ elif model_data['type'].lower() == 'clas':
2501
+ y_test_pred.append(_classification_vote(y_val_test))
2502
+ y_test_std.append(float(np.std(y_val_test)))
2503
+
2504
+ Xy_data['y_pred_test_all'] = y_pred_global_test
2505
+ Xy_data['y_pred_test'] = y_test_pred
2506
+ Xy_data['y_pred_test_sd'] = y_test_std
2507
+
2508
+ if 'X_external' in Xy_data: # if there is an external test set
2509
+ y_external_pred, y_external_std = [],[]
2510
+ for y_val_external in y_pred_global_external:
2511
+ if model_data['type'].lower() == 'reg':
2512
+ y_external_pred.append(np.mean(y_val_external))
2513
+ elif model_data['type'].lower() == 'clas':
2514
+ y_external_pred.append(_classification_vote(y_val_external))
2515
+ y_external_std.append(float(np.std(y_val_external)))
2516
+
2517
+ Xy_data['y_pred_external_all'] = y_pred_global_external
2518
+ Xy_data['y_pred_external'] = y_external_pred
2519
+ Xy_data['y_pred_external_sd'] = y_external_std
2520
+
2521
+ # in-fold training fit (each point is predicted by the fold(s) where it was part of
2522
+ # the training portion, i.e. NOT held out) - used for the train-vs-validation gap score
2523
+ y_train_infold_pred = []
2524
+ for y_val_trin in y_pred_global_train_infold:
2525
+ if model_data['type'].lower() == 'reg':
2526
+ y_train_infold_pred.append(np.mean(y_val_trin))
2527
+ elif model_data['type'].lower() == 'clas':
2528
+ y_train_infold_pred.append(_classification_vote(y_val_trin))
2529
+ Xy_data['y_pred_train_infold'] = y_train_infold_pred
2530
+
2531
+ return Xy_data
2532
+
2533
+
2534
+ def kfold_cv(y_global,y_pred_global,
2535
+ y_pred_global_test,
2536
+ y_pred_global_external,
2537
+ model_data,loaded_model,Xy_data,random_state,
2538
+ BO_opt=False,shuffle=True,kfold_cv_type='repeated',
2539
+ y_pred_global_train_infold=None,include_test=False):
2540
+ '''
2541
+ Perform a k-fold CV
2542
+ Uses StratifiedKFold for classification problems to maintain class distribution
2543
+ '''
2544
+
2545
+ # load CV scheme
2546
+ if model_data['type'].lower() == 'clas':
2547
+ # Use StratifiedKFold for classification to maintain class distribution
2548
+ cv = StratifiedKFold(n_splits=int(model_data['kfold']), shuffle=shuffle, random_state=random_state)
2549
+ else:
2550
+ cv = KFold(n_splits=int(model_data['kfold']), shuffle=shuffle, random_state=random_state)
2551
+
2552
+ # # load Xy values and sort using y_train as the sorting reference
2553
+ if kfold_cv_type == 'sorted':
2554
+ X_init,y_init = sort_n_load(Xy_data,include_test=include_test) # do not use, currently it doesn't sort indices for X_train as well
2555
+
2556
+ else:
2557
+ # convert Xy values of training and validation for CV
2558
+ X_init = np.array(Xy_data['X_train_scaled'])
2559
+ y_init = np.array(Xy_data['y_train'])
2560
+
2561
+ # convert Xy values for the test set and external test set (if any) - only needed
2562
+ # outside BO, where these conversions would otherwise run (and be discarded unused)
2563
+ # on every fold of every repeat of every BO iteration
2564
+ if not BO_opt:
2565
+ X_test = np.array(Xy_data['X_test_scaled'])
2566
+ # sklearn estimators reject predict() on a 0-row array (ensure_min_samples=1),
2567
+ # so an empty internal test set (e.g. --csv_test with --auto_test False) needs an
2568
+ # explicit skip here rather than just being an empty-but-present array
2569
+ has_test = len(X_test) > 0
2570
+ if 'X_external_scaled' in Xy_data:
2571
+ X_external = np.array(Xy_data['X_external_scaled'])
2572
+
2573
+ ix_training, ix_valid = [], []
2574
+ # Loop through each fold and append the training & test indices to the empty lists above
2575
+ if model_data['type'].lower() == 'clas':
2576
+ # For classification, we need to pass y values to ensure stratification
2577
+ for fold in cv.split(X_init, y_init):
2578
+ ix_training.append(fold[0]), ix_valid.append(fold[1])
2579
+ else:
2580
+ for fold in cv.split(X_init):
2581
+ ix_training.append(fold[0]), ix_valid.append(fold[1])
2582
+
2583
+ # Loop through each outer fold, and extract predicted vs actual values and SHAP feature analysis
2584
+ for (train_outer_ix, test_outer_ix) in zip(ix_training, ix_valid):
2585
+ X_train, X_valid = X_init[train_outer_ix, :], X_init[test_outer_ix, :]
2586
+ y_train, y_valid = y_init[train_outer_ix], y_init[test_outer_ix]
2587
+
2588
+ try:
2589
+ fit = loaded_model.fit(X_train, y_train)
2590
+ except ValueError as error:
2591
+ if 'worse than random' not in str(error).lower():
2592
+ raise
2593
+ # AdaBoost (and similar boosting ensembles) raise this when the base estimator's
2594
+ # weighted training error exceeds 0.5 on its very first (unweighted) iteration -
2595
+ # expected on VERIFY's y-shuffle test, which deliberately randomizes labels, and
2596
+ # occasionally on small/near-balanced real splits too. A fit that can't even beat
2597
+ # random guessing IS the worst-case result these tests are meant to surface, so
2598
+ # fall back to a majority-class prediction instead of crashing the whole report
2599
+ from sklearn.dummy import DummyClassifier
2600
+ fit = DummyClassifier(strategy='most_frequent').fit(X_train, y_train)
2601
+ y_pred_valid = fit.predict(X_valid)
2602
+ if not BO_opt:
2603
+ y_pred_test = fit.predict(X_test) if has_test else np.array([])
2604
+ if 'X_external_scaled' in Xy_data:
2605
+ y_pred_external = fit.predict(X_external)
2606
+ if kfold_cv_type == 'repeated' and y_pred_global_train_infold is not None:
2607
+ y_pred_train_infold = fit.predict(X_train)
2608
+
2609
+ if kfold_cv_type == 'repeated':
2610
+ for y_val,y_pred_val,idx in zip(y_valid,y_pred_valid,test_outer_ix):
2611
+ y_global[idx].append(y_val)
2612
+ y_pred_global[idx].append(y_pred_val)
2613
+ if not BO_opt:
2614
+ for idx,y_pred_val_test in enumerate(y_pred_test):
2615
+ y_pred_global_test[idx].append(y_pred_val_test)
2616
+ if 'X_external_scaled' in Xy_data:
2617
+ for idx,y_pred_val_external in enumerate(y_pred_external):
2618
+ y_pred_global_external[idx].append(y_pred_val_external)
2619
+ if y_pred_global_train_infold is not None:
2620
+ for y_pred_val_trin,idx in zip(y_pred_train_infold,train_outer_ix):
2621
+ y_pred_global_train_infold[idx].append(y_pred_val_trin)
2622
+
2623
+ elif kfold_cv_type == 'sorted':
2624
+ y_global.append(y_valid)
2625
+ y_pred_global.append(y_pred_valid)
2626
+
2627
+ return y_global,y_pred_global,y_pred_global_test,y_pred_global_external,y_pred_global_train_infold
2628
+
2629
+
2630
+ def sort_n_load(Xy_data,include_test=False):
2631
+ '''
2632
+ Sort Xy data values to enhance reproducibility in cases where same databases are loaded
2633
+ with different row order, ensuring stable sorting across OS with kind='stable'.
2634
+
2635
+ include_test=True combines train+validation with the test set first, since the
2636
+ boundary robustness (Low/High) analysis needs the true bottom/top 20% of the whole dataset, not
2637
+ just of the train+validation split - otherwise the true extremes of y could be sitting in
2638
+ the (excluded) test set. This must stay False (the default) during GENERATE's Bayesian
2639
+ Optimization / PFI hyperparameter search (kfold_cv's BO_opt=True path also runs there,
2640
+ not just for the final VERIFY/PREDICT report analysis) - the test set must never leak into
2641
+ hyperparameter selection, and mid-PFI train/test can also briefly have different columns.
2642
+ '''
2643
+
2644
+ if include_test:
2645
+ X_all = np.concatenate([np.array(Xy_data['X_train_scaled']), np.array(Xy_data['X_test_scaled'])])
2646
+ y_all = np.concatenate([np.array(Xy_data['y_train']), np.array(Xy_data['y_test'])])
2647
+ else:
2648
+ X_all = np.array(Xy_data['X_train_scaled'])
2649
+ y_all = np.array(Xy_data['y_train'])
2650
+
2651
+ sorted_indices = np.argsort(y_all, kind='stable')
2652
+ sorted_X_all = X_all[sorted_indices]
2653
+ sorted_y_all = y_all[sorted_indices]
2654
+
2655
+ return sorted_X_all, sorted_y_all
2656
+
2657
+
2658
+ def sorted_kfold_cv(loaded_model,model_data,Xy_data,error_labels,include_test=False):
2659
+ '''
2660
+ Performs a sorted k-fold cross-validation on the Xy dataset. Returns the average of the two results
2661
+
2662
+ include_test=True runs it over the whole dataset (train+validation+test), for the final
2663
+ VERIFY/PREDICT report analysis. Must stay False for GENERATE's BO/PFI hyperparameter
2664
+ search (see sort_n_load()).
2665
+ '''
2666
+
2667
+ # perform sorted 5-fold CV
2668
+ Xy_data['y_sorted_cv'],Xy_data['y_pred_sorted_cv'] = [],[]
2669
+ Xy_data['y_sorted_cv'],Xy_data['y_pred_sorted_cv'],_,_,_ = kfold_cv(Xy_data['y_sorted_cv'],Xy_data['y_pred_sorted_cv'],
2670
+ None,
2671
+ None,
2672
+ model_data,loaded_model,Xy_data,None,BO_opt=True,shuffle=False,kfold_cv_type='sorted',
2673
+ include_test=include_test)
2674
+ error1 = error_labels[model_data['type']][0]
2675
+ error2 = error_labels[model_data['type']][1]
2676
+ error3 = error_labels[model_data['type']][2]
2677
+ if model_data['type'].lower() == 'reg':
2678
+ Xy_data[f'{error1}_train_sorted_CV'], Xy_data[f'{error2}_train_sorted_CV'], Xy_data[f'{error3}_train_sorted_CV'] = [],[],[]
2679
+ for y_cv,y_pred_cd in zip(Xy_data['y_sorted_cv'],Xy_data['y_pred_sorted_cv']):
2680
+ r2_train_sorted_CV, mae_train_sorted_CV, rmse_train_sorted_CV = get_prediction_results(model_data,y_cv,y_pred_cd)
2681
+ Xy_data[f'{error1}_train_sorted_CV'].append(r2_train_sorted_CV)
2682
+ Xy_data[f'{error2}_train_sorted_CV'].append(mae_train_sorted_CV)
2683
+ Xy_data[f'{error3}_train_sorted_CV'].append(rmse_train_sorted_CV)
2684
+
2685
+ # take the worst performing predictions from the top and bottom folds
2686
+ if model_data["error_type"].lower() in ['mae','rmse']:
2687
+ Xy_data[f'{model_data["error_type"]}_up_bottom'] = max(Xy_data[f'{model_data["error_type"]}_train_sorted_CV'][0], Xy_data[f'{model_data["error_type"]}_train_sorted_CV'][-1])
2688
+ Xy_data['r2_up_bottom'] = min(Xy_data['r2_train_sorted_CV'][0], Xy_data['r2_train_sorted_CV'][-1])
2689
+ else: # r2
2690
+ Xy_data[f'{model_data["error_type"]}_up_bottom'] = min(Xy_data[f'{model_data["error_type"]}_train_sorted_CV'][0], Xy_data[f'{model_data["error_type"]}_train_sorted_CV'][-1])
2691
+
2692
+ else: # classification
2693
+ Xy_data[f'{error1}_train_sorted_CV'], Xy_data[f'{error2}_train_sorted_CV'], Xy_data[f'{error3}_train_sorted_CV'] = [],[],[]
2694
+ for y_cv, y_pred_cd in zip(Xy_data['y_sorted_cv'], Xy_data['y_pred_sorted_cv']):
2695
+ acc_fold, f1_fold, mcc_fold = get_prediction_results(model_data, y_cv, y_pred_cd)
2696
+ Xy_data[f'{error1}_train_sorted_CV'].append(acc_fold)
2697
+ Xy_data[f'{error2}_train_sorted_CV'].append(f1_fold)
2698
+ Xy_data[f'{error3}_train_sorted_CV'].append(mcc_fold)
2699
+
2700
+ # Measure fold stability by difference between best and worst fold
2701
+ Xy_data[f'{model_data["error_type"]}_up_bottom'] = np.mean(np.abs(Xy_data[f'{model_data["error_type"]}_train_sorted_CV']))
2702
+
2703
+ return Xy_data
2704
+
2705
+
2706
+ def _cv_within_partition(self,model_data,X_train_pool,y_train_pool,X_test_pool,y_test_pool,return_cv_rmse=False):
2707
+ '''
2708
+ Runs the SAME 10x repeated 5-fold CV used for interpolation (repeated_kfold_cv), scoped to
2709
+ an arbitrary 80/20 partition instead of the "official" train/test split - so boundary
2710
+ robustness predictions (Low/High, applicability domain) are computed exactly like
2711
+ interpolation's "10x 5-fold CV"/"test" pair: each point in the 80% pool is averaged over
2712
+ its ~10 out-of-fold CV appearances, and each point in the 20% held-out pool is averaged
2713
+ over all repeat*kfold (e.g. 10*5=50) models fitted during the run - instead of a single
2714
+ train-once/test-once fit. The optional fourth return value is the CV RMSE pooled over
2715
+ every out-of-fold prediction, matching load_n_predict() and the full-data CV baseline.
2716
+ It differs from the RMSE of the per-point averaged predictions used by the plots and
2717
+ degradation baselines, which are retained unchanged.
2718
+ '''
2719
+
2720
+ loaded_model = load_model(self, model_data['model'], **model_data['params'])
2721
+ temp_Xy_data = {
2722
+ 'X_train_scaled': X_train_pool,
2723
+ 'y_train': y_train_pool,
2724
+ 'X_test_scaled': X_test_pool,
2725
+ 'y_test': y_test_pool,
2726
+ }
2727
+ temp_Xy_data = repeated_kfold_cv(model_data,loaded_model,temp_Xy_data,BO_opt=False)
2728
+
2729
+ # y_pred_test_sd: per-point SD computed directly over all repeat*kfold raw predictions
2730
+ # (same statistic interpolation's item 6 "Avg. standard deviation (SD)" already uses, via
2731
+ # Xy_data['y_pred_test_sd'] in repeated_kfold_cv) - kept in the same units/convention here
2732
+ # so boundary robustness's stability sub-metric is directly comparable to interpolation's
2733
+ predictions = (np.array(temp_Xy_data['y_pred_train']), np.array(temp_Xy_data['y_pred_test']), np.array(temp_Xy_data['y_pred_test_sd']))
2734
+ if return_cv_rmse:
2735
+ cv_predictions = np.asarray(temp_Xy_data['y_pred_train_all'])
2736
+ _, _, rmse_cv = get_prediction_results(
2737
+ model_data, np.repeat(np.asarray(y_train_pool), cv_predictions.shape[1]), cv_predictions.reshape(-1)
2738
+ )
2739
+ return (*predictions, rmse_cv)
2740
+ return predictions
2741
+
2742
+
2743
+ def boundary_n_points(n_total):
2744
+ '''
2745
+ Number of points held out in each boundary robustness partition (Low/High extremes and
2746
+ high-leverage points): 20% of the data, with a minimum of 4 points so small datasets
2747
+ (i.e. 16 points, where 20% rounds to 3) still give a meaningful RMSE on the held-out points
2748
+ '''
2749
+
2750
+ return max(4, round(n_total * 0.2))
2751
+
2752
+
2753
+ def boundary_plot(self,model_data,Xy_data,path_n_suffix):
2754
+ '''
2755
+ Plots predicted vs actual values for the High extreme (top 20% of y) and Low extreme
2756
+ (bottom 20%), each held out from its own 10x repeated 5-fold CV run on the OTHER 80% - the
2757
+ same methodology interpolation's "10x 5-fold CV"/"test" plot uses (repeated_kfold_cv), just
2758
+ scoped to each extreme's own 80/20 partition of the whole (sorted) dataset instead of the
2759
+ official train/test split. Both the 80%-pool points and the 20%-extreme points are
2760
+ therefore averaged over repeated CV appearances, not a single train-once/test-once fit.
2761
+ Test RMSEs use these ensemble means; the separately logged CV RMSEs pool all OOF
2762
+ predictions on each remaining 80% pool, just like the full-data CV baseline.
2763
+ '''
2764
+
2765
+ X_all,y_all = sort_n_load(Xy_data,include_test=True)
2766
+ n_extreme = boundary_n_points(len(X_all))
2767
+
2768
+ X_bottom80,y_bottom = X_all[:-n_extreme], y_all[:-n_extreme]
2769
+ X_high,y_high = X_all[-n_extreme:], y_all[-n_extreme:]
2770
+ X_top80,y_top = X_all[n_extreme:], y_all[n_extreme:]
2771
+ X_low,y_low = X_all[:n_extreme], y_all[:n_extreme]
2772
+
2773
+ y_pred_bottom,y_pred_high,s_high,rmse_cv_bottom80 = _cv_within_partition(
2774
+ self,model_data,X_bottom80,y_bottom,X_high,y_high,return_cv_rmse=True)
2775
+ y_pred_top,y_pred_low,s_low,rmse_cv_top80 = _cv_within_partition(
2776
+ self,model_data,X_top80,y_top,X_low,y_low,return_cv_rmse=True)
2777
+
2778
+ # RMSE of each extreme's own "remaining 80%" (from the same repeated-CV run), used as the
2779
+ # degradation ratio baseline - comparing against interpolation's own RMSE would still mix
2780
+ # two different dataset scopes (Low/High are drawn from the whole dataset, interpolation
2781
+ # only from train+validation), even though both are now the same repeated-CV procedure
2782
+ _,_,rmse_bottom80 = get_prediction_results(model_data,y_bottom,y_pred_bottom)
2783
+ _,_,rmse_top80 = get_prediction_results(model_data,y_top,y_pred_top)
2784
+
2785
+ # RMSE of the extreme folds themselves (Low/High vs their repeated-CV predictions) - this is
2786
+ # the actual "how well does the model do on the extreme 20%" number shown in the report,
2787
+ # replacing VERIFY's old single-pass sorted-CV RMSE now that the predictions come from the
2788
+ # same repeated-CV procedure as interpolation
2789
+ _,_,rmse_high = get_prediction_results(model_data,y_high,y_pred_high)
2790
+ _,_,rmse_low = get_prediction_results(model_data,y_low,y_pred_low)
2791
+
2792
+ # Spearman rank correlation replaces R2 as the "is the fit trustworthy" check for the
2793
+ # extreme folds - R2 (a variance-ratio) is unstable on a small, narrow-range subset and
2794
+ # ends up punishing models regardless of actual quality, whereas rank correlation is far
2795
+ # more robust at small N. Two complementary checks:
2796
+ # - internal: within the Low/High fold's own points, does the model rank them correctly
2797
+ # (biggest actual value -> biggest predicted value)?
2798
+ # - global: over the WHOLE (sorted) dataset, does the model's ranking correctly place the
2799
+ # true extremes as extremes at all, rather than compressing them toward the middle?
2800
+ # Complements Bias (mean shift) with a rank-based view of the same failure mode.
2801
+ # fallbacks use 0.0 (float), not 0 (int) - the f"{value:.2}" format used when logging these
2802
+ # below raises ValueError ("Precision not allowed in integer format specifier") if value
2803
+ # ends up as a plain Python int, which happened on small/degenerate datasets (e.g. a
2804
+ # 2-descriptor, ~35-point dataset where a Low/High fold can have too few points or ties)
2805
+ spearman_high = stats.spearmanr(y_high,y_pred_high).correlation if len(y_high) > 1 else 0.0
2806
+ spearman_low = stats.spearmanr(y_low,y_pred_low).correlation if len(y_low) > 1 else 0.0
2807
+ spearman_high = 0.0 if np.isnan(spearman_high) else spearman_high
2808
+ spearman_low = 0.0 if np.isnan(spearman_low) else spearman_low
2809
+
2810
+ # bottom80 (indices [0:-n_extreme]) + high (indices [-n_extreme:]) covers the whole sorted
2811
+ # dataset exactly once, with no gap or overlap - no need to also pull in the Low run's data
2812
+ y_all_sorted = np.concatenate([y_bottom,y_high])
2813
+ y_pred_all_sorted = np.concatenate([y_pred_bottom,y_pred_high])
2814
+ spearman_global = stats.spearmanr(y_all_sorted,y_pred_all_sorted).correlation
2815
+ spearman_global = 0.0 if np.isnan(spearman_global) else spearman_global
2816
+
2817
+ # sub-metric 3: real range extension - does the model actually dare to predict beyond the
2818
+ # range it was trained on, or does it just clip toward the training boundary (a subtler
2819
+ # form of regression-to-the-mean that scaled RMSE/Spearman alone don't catch, since a model
2820
+ # that never leaves the training range can still rank/fit reasonably within it)?
2821
+ y_max_train = y_bottom.max() # High's model only ever saw up to this value while training
2822
+ y_min_train = y_top.min() # Low's model only ever saw down to this value while training
2823
+ crossing_high = np.mean(y_pred_high > y_max_train)
2824
+ crossing_low = np.mean(y_pred_low < y_min_train)
2825
+
2826
+ # sub-metric 4: prediction uncertainty usefulness - s_high/s_low (per-point SD across all
2827
+ # repeat*kfold raw predictions, same statistic as interpolation's item 6) define a
2828
+ # +-2*SD "repeated-CV prediction band" per point (not a calibrated confidence interval).
2829
+ # 4a. coverage: does the true value actually fall inside that band?
2830
+ y_extreme = np.concatenate([y_high,y_low])
2831
+ pred_extreme = np.concatenate([y_pred_high,y_pred_low])
2832
+ s_extreme = np.concatenate([s_high,s_low])
2833
+ covered = (y_extreme >= pred_extreme-2*s_extreme) & (y_extreme <= pred_extreme+2*s_extreme)
2834
+ coverage = np.mean(covered)
2835
+
2836
+ # 4b. does a higher SD actually flag the harder (higher-error) points? split the extreme
2837
+ # points by their own median SD and compare RMSE between the high-SD and low-SD halves
2838
+ err_extreme = np.abs(y_extreme-pred_extreme)
2839
+ median_s = np.median(s_extreme)
2840
+ low_sd_mask,high_sd_mask = s_extreme <= median_s, s_extreme > median_s
2841
+ if low_sd_mask.sum() > 0 and high_sd_mask.sum() > 0:
2842
+ rmse_low_sd = np.sqrt(np.mean(err_extreme[low_sd_mask]**2))
2843
+ rmse_high_sd = np.sqrt(np.mean(err_extreme[high_sd_mask]**2))
2844
+ sd_rmse_ratio = rmse_high_sd/rmse_low_sd if rmse_low_sd > 0 else float('inf')
2845
+ else: # not enough spread in SD to split into two groups
2846
+ sd_rmse_ratio = 0.0
2847
+
2848
+ _boundary_scatter(self,model_data,path_n_suffix,'high_',
2849
+ y_bottom,y_pred_bottom,y_high,y_pred_high,'Bottom 80%','Top 20%')
2850
+ _boundary_scatter(self,model_data,path_n_suffix,'low_',
2851
+ y_top,y_pred_top,y_low,y_pred_low,'Top 80%','Bottom 20%')
2852
+
2853
+ # calculate SD
2854
+ sd_high = np.std(y_high)
2855
+ sd_pred_high = np.std(y_pred_high)
2856
+ spread_ratio_high = sd_pred_high/sd_high
2857
+ sd_low = np.std(y_low)
2858
+ sd_pred_low = np.std(y_pred_low)
2859
+ spread_ratio_low = sd_pred_low/sd_low
2860
+
2861
+ # calculate ranges y
2862
+ range_high = max(y_high) - min(y_high)
2863
+ range_pred_high = max(y_pred_high) - min(y_pred_high)
2864
+ range_ratio_high = range_pred_high/range_high
2865
+ range_low = max(y_low) - min(y_low)
2866
+ range_pred_low = max(y_pred_low) - min(y_pred_low)
2867
+ range_ratio_low = range_pred_low/range_low
2868
+
2869
+ # print results
2870
+ high_low_text = ''
2871
+ # REPORT parses these RMSE values to calculate scale-independent scores. Use significant
2872
+ # digits rather than fixed decimal places so small target scales don't round them to zero.
2873
+ high_low_text += f" - Sorted CV extremes (repeated) : Test RMSE Low = {rmse_low:.2g}, Test RMSE High = {rmse_high:.2g}\n"
2874
+ high_low_text += f" - Sorted CV training pools (repeated) : CV RMSE Low = {rmse_cv_top80:.2g}, CV RMSE High = {rmse_cv_bottom80:.2g}\n"
2875
+ high_low_text += f" - Real range extension (Low/High) : Low crossing = {crossing_low:.2f}, High crossing = {crossing_high:.2f}\n"
2876
+ high_low_text += f" - Degradation baseline (remaining 80%) : CV RMSE of averaged OOF predictions, vs Low (top 80%) RMSE = {rmse_top80:.2g}, vs High (bottom 80%) RMSE = {rmse_bottom80:.2g}\n"
2877
+ high_low_text += f" - y SD at high extreme : Measured = {sd_high:.2f}; Predicted = {sd_pred_high:.2f}. Spread ratio = {spread_ratio_high:.2f}\n"
2878
+ high_low_text += f" - y SD at low extreme : Measured = {sd_low:.2f}; Predicted = {sd_pred_low:.2f}. Spread ratio = {spread_ratio_low:.2f}\n"
2879
+ high_low_text += f" - y range at high extreme : Measured = {range_high:.2g}; Predicted = {range_pred_high:.2g}. Range ratio = {range_ratio_high:.2f}\n"
2880
+ high_low_text += f" - y range at low extreme : Measured = {range_low:.2g}; Predicted = {range_pred_low:.2g}. Range ratio = {range_ratio_low:.2f}\n"
2881
+ high_low_text += f" - Spearman rank (Low/High) : Low (internal) = {spearman_low:.2f}, High (internal) = {spearman_high:.2f}, global = {spearman_global:.2f}\n"
2882
+ high_low_text += f" - Uncertainty coverage (+/-2SD band) : {coverage:.2f}\n"
2883
+ high_low_text += f" - Uncertainty RMSE ratio (high-SD/low-SD) : {sd_rmse_ratio:.3f}\n"
2884
+ self.args.log.write(high_low_text)
2885
+
2886
+ def applicability_domain_plot(self,model_data,Xy_data,path_n_suffix):
2887
+ '''
2888
+ Boundary robustness in X-descriptor space (Section B sub-metric 3), complementing the
2889
+ Low/High sorted-CV analysis (boundary robustness in y-space). Ranks every point in the whole dataset by
2890
+ leverage - h_i = x_i^T (X_train^T X_train)^-1 x_i, the standard QSAR/regression
2891
+ "applicability domain" metric, which (unlike a per-descriptor or plain Euclidean check)
2892
+ accounts for correlations between descriptors - holds out the top 20% highest-leverage
2893
+ (most structurally/descriptor-wise extreme) points as a test set, trains on the remaining
2894
+ 80% "typical" points, and scores how well the model extrapolates to those descriptor
2895
+ outliers.
2896
+
2897
+ Leverage is computed using ONLY the training-candidate 80% (X_train above), not the whole
2898
+ dataset, so the holdout points never contribute to defining their own "how extreme am I"
2899
+ reference domain. Resolved in two passes: an initial leverage over the whole dataset picks
2900
+ a provisional 80/20 split, then leverage is recomputed using only that provisional 80% and
2901
+ the split is redone from those (now contamination-free) values.
2902
+ '''
2903
+
2904
+ X_all = np.concatenate([np.array(Xy_data['X_train_scaled']), np.array(Xy_data['X_test_scaled'])])
2905
+ y_all = np.concatenate([np.array(Xy_data['y_train']), np.array(Xy_data['y_test'])])
2906
+ n_test = boundary_n_points(len(X_all))
2907
+
2908
+ def _leverage(X_ref,X_query):
2909
+ XtX_inv = np.linalg.pinv(X_ref.T @ X_ref)
2910
+ return np.einsum('ij,jk,ik->i', X_query, XtX_inv, X_query)
2911
+
2912
+ # pass 1: provisional split using leverage over the whole dataset (self-contaminated)
2913
+ leverage_provisional = _leverage(X_all,X_all)
2914
+ provisional_train_idx = np.argsort(leverage_provisional, kind='stable')[:-n_test]
2915
+
2916
+ # pass 2: recompute leverage using only the provisional 80% training candidates, then
2917
+ # re-split from these contamination-free values
2918
+ leverage = _leverage(X_all[provisional_train_idx],X_all)
2919
+ sorted_idx = np.argsort(leverage, kind='stable')
2920
+ train_idx, test_idx = sorted_idx[:-n_test], sorted_idx[-n_test:]
2921
+
2922
+ X_train_ad, y_train_ad = X_all[train_idx], y_all[train_idx]
2923
+ X_test_ad, y_test_ad = X_all[test_idx], y_all[test_idx]
2924
+
2925
+ # 10x repeated 5-fold CV within the 80% "typical" pool (same methodology as interpolation
2926
+ # and the Low/High boundary robustness plots - see _cv_within_partition()), instead of a
2927
+ # single train-once/test-once fit. Keep the held-out ensemble RMSE for scoring
2928
+ # and calculate the pooled OOF CV RMSE separately for the split comparison.
2929
+ y_pred_train_ad,y_pred_test_ad,_,rmse_cv_ad = _cv_within_partition(
2930
+ self,model_data,X_train_ad,y_train_ad,X_test_ad,y_test_ad,return_cv_rmse=True)
2931
+
2932
+ _,_,rmse_ad = get_prediction_results(model_data,y_test_ad,y_pred_test_ad)
2933
+
2934
+ # two complementary plots: an actual-vs-predicted scatter (same style as Low/High) shows how
2935
+ # close predictions are to actual values, tying visually to the Scaled RMSE this item is
2936
+ # scored on; a Williams plot (leverage vs standardized residual, with the standard QSAR
2937
+ # warning-leverage h* = 3(p+1)/n and +-3 SD bounds) shows the whole dataset at once and
2938
+ # flags which points are structurally outside the domain / have suspicious residuals
2939
+ _boundary_scatter(self,model_data,path_n_suffix,'ad_',
2940
+ y_train_ad,y_pred_train_ad,y_test_ad,y_pred_test_ad,'Typical 80%','High leverage 20%',
2941
+ title='Applicability domain (leverage)',legend_fontsize=12)
2942
+
2943
+ n_train_ad, p = X_train_ad.shape
2944
+ h_star = 3*(p+1)/n_train_ad
2945
+ residuals_all = np.concatenate([y_train_ad-y_pred_train_ad, y_test_ad-y_pred_test_ad])
2946
+ resid_sd = np.std(residuals_all) if np.std(residuals_all) > 0 else 1
2947
+ std_resid_train = (y_train_ad-y_pred_train_ad)/resid_sd
2948
+ std_resid_test = (y_test_ad-y_pred_test_ad)/resid_sd
2949
+ point_ids = np.concatenate([np.array(Xy_data['names_train']), np.array(Xy_data['names_test'])])
2950
+
2951
+ _williams_plot(path_n_suffix,
2952
+ leverage[train_idx],std_resid_train,leverage[test_idx],std_resid_test,h_star,
2953
+ point_ids=np.concatenate([point_ids[train_idx],point_ids[test_idx]]),
2954
+ name_column=model_data['names'],
2955
+ observed=np.concatenate([y_train_ad,y_test_ad]),
2956
+ predicted=np.concatenate([y_pred_train_ad,y_pred_test_ad]))
2957
+
2958
+ self.args.log.write(f" - Applicability domain (leverage) : Test RMSE = {rmse_ad:.2}, CV RMSE = {rmse_cv_ad:.2}, h* = {h_star:.2}")
2959
+
2960
+
2961
+ def _place_legend(ax,all_x,all_y,labels,fontsize=14):
2962
+ '''
2963
+ Places the legend at the same fixed bottom-right anchor (0.70, 0.15) used by the main
2964
+ "10x 5-fold CV / test" plot (graph_reg), so the margin matches across the report, unless a
2965
+ data point actually falls behind it, in which case (and only then) it falls back to
2966
+ matplotlib's loc='best', which auto-avoids overlapping data.
2967
+ '''
2968
+
2969
+ legend_kwargs = dict(handletextpad=0, fancybox=True, shadow=True, ncol=5, labels=labels, fontsize=fontsize)
2970
+
2971
+ legend = ax.legend(loc='upper center', bbox_to_anchor=(0.70, 0.15), **legend_kwargs)
2972
+
2973
+ # get_window_extent() needs an explicit renderer on the Agg backend (used for saving
2974
+ # figures without a display) - without it, it silently returns a stale/degenerate bbox and
2975
+ # the overlap check below never triggers, which is why the auto-move wasn't working
2976
+ ax.figure.canvas.draw()
2977
+ renderer = ax.figure.canvas.get_renderer()
2978
+ bbox = legend.get_window_extent(renderer=renderer)
2979
+
2980
+ inv = ax.transData.inverted()
2981
+ (x0,y0),(x1,y1) = inv.transform([[bbox.x0,bbox.y0],[bbox.x1,bbox.y1]])
2982
+ x_lo,x_hi = sorted([x0,x1])
2983
+ y_lo,y_hi = sorted([y0,y1])
2984
+
2985
+ overlap = any(x_lo <= x <= x_hi and y_lo <= y <= y_hi for x,y in zip(all_x,all_y))
2986
+ if overlap:
2987
+ legend.remove()
2988
+ legend = ax.legend(loc='best', **legend_kwargs)
2989
+
2990
+ return legend
2991
+
2992
+
2993
+ def _williams_plot(path_n_suffix,leverage_train,resid_train,leverage_test,resid_test,h_star,
2994
+ print_fun=True,point_ids=None,name_column=None,observed=None,predicted=None):
2995
+ '''
2996
+ Standard QSAR "Williams plot": leverage (x) vs standardized residual (y), marking the
2997
+ warning leverage h* and the +-3 SD bounds that define the applicability domain.
2998
+ print_fun=False skips the in-image title - used for the small (270px-wide) Section B
2999
+ thumbnails, where the container height crops it anyway (see print_img_tag()) and the
3000
+ surrounding item text already says what the plot shows
3001
+ '''
3002
+
3003
+ importlib.reload(plt) # needed to avoid threading issues
3004
+ sb.set(style="ticks")
3005
+ graph_style = get_graph_style()
3006
+
3007
+ _, ax = plt.subplots(figsize=(7.45,6))
3008
+ plt.xticks(fontsize=14)
3009
+ plt.yticks(fontsize=14)
3010
+
3011
+ if print_fun:
3012
+ plt.text(0.5, 1.08, f'Applicability domain (Williams plot) of {os.path.basename(path_n_suffix)}', horizontalalignment='center',
3013
+ fontsize=14, fontweight='bold', transform = ax.transAxes)
3014
+
3015
+ _ = ax.scatter(leverage_train, resid_train,
3016
+ c = graph_style['color_train'], s = graph_style['dot_size'], edgecolor = 'k', linewidths = 0.8, alpha = graph_style['alpha'], zorder=2)
3017
+ _ = ax.scatter(leverage_test, resid_test,
3018
+ c = graph_style['color_test'], s = graph_style['dot_size'], edgecolor = 'k', linewidths = 0.8, alpha = graph_style['alpha'], zorder=3)
3019
+
3020
+ ax.axhline(3, color='dimgray', linestyle='--', linewidth=1, zorder=1)
3021
+ ax.axhline(-3, color='dimgray', linestyle='--', linewidth=1, zorder=1)
3022
+ ax.axvline(h_star, color='dimgray', linestyle='--', linewidth=1, zorder=1)
3023
+
3024
+ _place_legend(ax,np.concatenate([leverage_train,leverage_test]),np.concatenate([resid_train,resid_test]),
3025
+ ['Typical 80%','High leverage 20%'],fontsize=12)
3026
+
3027
+ plt.ylabel('Standardized residual', fontsize=14)
3028
+ plt.xlabel('Leverage', fontsize=14)
3029
+
3030
+ all_leverage = np.concatenate([leverage_train, leverage_test])
3031
+ all_resid = np.concatenate([resid_train, resid_test])
3032
+ x_max = max(max(all_leverage)*1.1, h_star*1.2)
3033
+ y_max = max(max(np.abs(all_resid))*1.1, 3.5)
3034
+
3035
+ ax.grid(linestyle='--', linewidth=1)
3036
+ plt.xlim(0, x_max)
3037
+ plt.ylim(-y_max, y_max)
3038
+
3039
+ williams_plot_file = f'{os.path.dirname(path_n_suffix)}/Results_boundary_williams_{os.path.basename(path_n_suffix)}.png'
3040
+ plt.savefig(f'{williams_plot_file}', dpi=300, bbox_inches='tight')
3041
+ plt.close()
3042
+ if point_ids is not None:
3043
+ point_count = len(leverage_train) + len(leverage_test)
3044
+ pd.DataFrame({
3045
+ 'point_id': point_ids,
3046
+ 'name_column': [name_column] * point_count,
3047
+ 'group': ['Typical 80%'] * len(leverage_train) + ['High leverage 20%'] * len(leverage_test),
3048
+ 'leverage': np.concatenate([leverage_train,leverage_test]),
3049
+ 'standardized_residual': np.concatenate([resid_train,resid_test]),
3050
+ 'h_star': [h_star] * point_count,
3051
+ 'observed': observed,
3052
+ 'predicted': predicted,
3053
+ }).to_csv(f'{os.path.splitext(williams_plot_file)[0]}.csv', index=False)
3054
+
3055
+
3056
+ def _boundary_scatter(self,model_data,path_n_suffix,file_prefix,y_rest,y_pred_rest,y_extreme,y_pred_extreme,rest_label,extreme_label,title='Boundary robustness (sorted CV)',legend_fontsize=14,print_fun=True):
3057
+ '''
3058
+ Shared plotting logic for boundary_plot()'s High and Low scatter plots: "rest" of the
3059
+ data in blue, the highlighted extreme fold in red.
3060
+ print_fun=False skips the in-image title - used for the small (270px-wide) Section B
3061
+ thumbnails, where the container height crops it anyway (see print_img_tag()) and the
3062
+ surrounding item text already says what the plot shows
3063
+ '''
3064
+
3065
+ importlib.reload(plt) # needed to avoid threading issues
3066
+ sb.set(style="ticks")
3067
+ graph_style = get_graph_style()
3068
+
3069
+ _, ax = plt.subplots(figsize=(7.45,6))
3070
+ plt.xticks(fontsize=14)
3071
+ plt.yticks(fontsize=14)
3072
+
3073
+ if print_fun:
3074
+ plt.text(0.5, 1.08, f'{title} of {os.path.basename(path_n_suffix)}', horizontalalignment='center',
3075
+ fontsize=14, fontweight='bold', transform = ax.transAxes)
3076
+
3077
+ _ = ax.scatter(y_rest, y_pred_rest,
3078
+ c = graph_style['color_train'], s = graph_style['dot_size'], edgecolor = 'k', linewidths = 0.8, alpha = graph_style['alpha'], zorder=2)
3079
+ _ = ax.scatter(y_extreme, y_pred_extreme,
3080
+ c = graph_style['color_test'], s = graph_style['dot_size'], edgecolor = 'k', linewidths = 0.8, alpha = graph_style['alpha'], zorder=3)
3081
+
3082
+ _place_legend(ax,np.concatenate([y_rest,y_extreme]),np.concatenate([y_pred_rest,y_pred_extreme]),
3083
+ [rest_label,extreme_label],fontsize=legend_fontsize)
3084
+
3085
+ plt.ylabel(f'Predicted {model_data["y"]}', fontsize=14)
3086
+ plt.xlabel(f'{model_data["y"]}', fontsize=14)
3087
+
3088
+ y_all = np.concatenate([y_rest, y_extreme])
3089
+ y_pred_all = np.concatenate([y_pred_rest, y_pred_extreme])
3090
+ size_space = 0.1*abs(min(y_all)-max(y_all)) if max(y_all) != min(y_all) else 1
3091
+ min_value_graph = min(min(y_all),min(y_pred_all))-size_space
3092
+ max_value_graph = max(max(y_all),max(y_pred_all))+size_space
3093
+
3094
+ ax.grid(linestyle='--', linewidth=1)
3095
+ # ideal y = y_pred diagonal as the only reference line (no regression line fitted through
3096
+ # the points): R2/RMSE measure the distance to this line, and a fitted line would hide bias
3097
+ # or scale errors of the predictions (see get_prediction_results())
3098
+ ax.plot([min_value_graph, max_value_graph], [min_value_graph, max_value_graph],
3099
+ color='#7f7f7f', linestyle='-', linewidth=1.2, zorder=0.5)
3100
+ plt.xlim(min_value_graph, max_value_graph)
3101
+ plt.ylim(min_value_graph, max_value_graph)
3102
+
3103
+ boundary_plot_file = f'{os.path.dirname(path_n_suffix)}/Results_boundary_{file_prefix}{os.path.basename(path_n_suffix)}.png'
3104
+ plt.savefig(f'{boundary_plot_file}', dpi=300, bbox_inches='tight')
3105
+ plt.close()
3106
+
3107
+ path_reduced = '/'.join(f'{boundary_plot_file}'.replace('\\','/').split('/')[-2:])
3108
+ self.args.log.write(f" - Graph in: {path_reduced}")
3109
+
3110
+
3111
+
3112
+
3113
+ def k_means(self,X_scaled,csv_y,size,seed,idx_list):
3114
+ '''
3115
+
3116
+ Uses k-means clustering to select the test points to be as diverse as possible,
3117
+ but it returns the test pointsReturns the data points that will be used as training set based on the k-means clustering
3118
+
3119
+ '''
3120
+
3121
+ # number of clusters in the training set from the k-means clustering (based on the
3122
+ # training set size specified above)
3123
+ X_scaled_array = np.asarray(X_scaled)
3124
+ number_of_clusters = size
3125
+
3126
+ # to avoid points from the validation set outside the training set, the 2 first training
3127
+ # points are automatically set as the 2 points with minimum/maximum response value
3128
+ if self.args.type.lower() == 'reg':
3129
+ test_points = []
3130
+ training_idx = [csv_y.idxmin(),csv_y.idxmax()]
3131
+ number_of_clusters -= 2
3132
+ else:
3133
+ test_points = []
3134
+ training_idx = []
3135
+
3136
+ # runs the k-means algorithm and keeps the closest point to the center of each cluster
3137
+ kmeans = KMeans(n_clusters=number_of_clusters,random_state=seed)
3138
+ try:
3139
+ kmeans.fit(X_scaled_array)
3140
+ except ValueError:
3141
+ self.args.log.write("\nx The K-means clustering process failed! This might be due to having NaN or strings as descriptors (curate the data first with CURATE) or having too few datapoints!")
3142
+ sys.exit()
3143
+ centers = kmeans.cluster_centers_
3144
+
3145
+ # Euclidean distance from every point to every cluster center, computed once with a
3146
+ # vectorized pairwise distance call instead of a per-point/per-descriptor Python triple loop
3147
+ dists_to_centers = cdist(X_scaled_array, centers)
3148
+
3149
+ claimed = np.zeros(len(X_scaled_array), dtype=bool)
3150
+ claimed[list(training_idx)] = True
3151
+ for i in range(number_of_clusters):
3152
+ dists_i = np.where(claimed, np.inf, dists_to_centers[:, i])
3153
+ training_point = int(np.argmin(dists_i))
3154
+ if np.isinf(dists_i[training_point]):
3155
+ # every point is already claimed by an earlier cluster (e.g. more clusters than
3156
+ # remaining unclaimed points) - skip instead of silently re-appending a duplicate
3157
+ continue
3158
+ training_idx.append(training_point)
3159
+ claimed[training_point] = True
3160
+
3161
+ test_idx = [idx for idx in range(len(X_scaled_array[:, 0])) if idx not in training_idx]
3162
+ test_points = [idx_list[i] for i in test_idx]
3163
+ test_points.sort()
3164
+
3165
+ return test_points
3166
+
3167
+
3168
+ def PFI_filter(self, Xy_data, model_data):
3169
+ '''
3170
+ Performs the PFI calculation and returns a list of the descriptors that are not important
3171
+ '''
3172
+
3173
+ # load and fit model
3174
+ loaded_model = load_model(self,model_data['model'],**model_data['params'])
3175
+ loaded_model.fit(Xy_data['X_train_scaled'], Xy_data['y_train'])
3176
+
3177
+ # select scoring function for PFI analysis based on the error type
3178
+ scoring, score_model, _ = scoring_n_score(self,model_data,Xy_data,loaded_model)
3179
+
3180
+ perm_importance = permutation_importance(loaded_model, Xy_data['X_train_scaled'], Xy_data['y_train'], scoring=scoring, n_repeats=self.args.pfi_epochs, random_state=self.args.seed, n_jobs=1)
3181
+
3182
+ # transforms the values into a list and sort the PFI values with the descriptor names
3183
+ descp_cols_pfi, PFI_values, PFI_sd = [],[],[]
3184
+ for i,desc in enumerate(Xy_data['X_train_scaled'].columns):
3185
+ descp_cols_pfi.append(desc) # includes lists of descriptors not column names!
3186
+ PFI_values.append(perm_importance.importances_mean[i])
3187
+ PFI_sd.append(perm_importance.importances_std[i])
3188
+
3189
+ PFI_values, PFI_sd, descp_cols_pfi = (list(t) for t in zip(*sorted(zip(PFI_values, PFI_sd, descp_cols_pfi), reverse=True)))
3190
+
3191
+ # PFI filter
3192
+ PFI_discard_cols = []
3193
+ # the threshold is based either on the RMSE of the model or the importance of the most important descriptor
3194
+ PFI_thres = max([abs(self.args.pfi_threshold*score_model),abs(self.args.pfi_threshold*PFI_values[0])])
3195
+ for i in range(len(PFI_values)):
3196
+ if PFI_values[i] < PFI_thres:
3197
+ PFI_discard_cols.append(descp_cols_pfi[i])
3198
+
3199
+ return PFI_discard_cols,descp_cols_pfi
3200
+
3201
+
3202
+ def scoring_n_score(self,model_data,Xy_data,loaded_model):
3203
+ '''
3204
+ Get scoring system and score of the original model with CV
3205
+ '''
3206
+
3207
+ error_type = model_data['error_type'].lower()
3208
+ scoring = get_scoring_key(model_data['type'],error_type)
3209
+ cv_model = RepeatedKFold(n_splits=self.args.kfold, n_repeats=self.args.repeat_kfolds, random_state=self.args.seed)
3210
+ score_model = cross_val_score(estimator = loaded_model, X=Xy_data['X_train_scaled'], y=Xy_data['y_train'],scoring=scoring, cv =cv_model)
3211
+ score_model = score_model.mean()
3212
+
3213
+ if model_data['error_type'].lower() in ['rmse','mae']:
3214
+ score_model = -score_model
3215
+
3216
+ return scoring, score_model, error_type
3217
+
3218
+
3219
+ def create_heatmap(self,csv_df,suffix,path_raw):
3220
+ """
3221
+ Graph the heatmap
3222
+ """
3223
+
3224
+ importlib.reload(plt) # needed to avoid threading issues
3225
+ csv_df = csv_df.sort_index(ascending=False)
3226
+ sb.set(font_scale=1.2, style='ticks')
3227
+ _, ax = plt.subplots(figsize=(7.45,6))
3228
+ cmap_blues_75_percent_512 = [mcolor.rgb2hex(c) for c in plt.cm.Blues(np.linspace(0, 0.8, 512))]
3229
+ # Replace inf values with NaN for proper heatmap visualization
3230
+ csv_df.replace([np.inf, -np.inf], np.nan, inplace=True)
3231
+ ax = sb.heatmap(csv_df, annot=True, linewidth=1, cmap=cmap_blues_75_percent_512, cbar_kws={'label': f'Combined {self.args.error_type.upper()}'}, mask=csv_df.isnull())
3232
+ fontsize = 14
3233
+ ax.set_xlabel("ML Model",fontsize=fontsize)
3234
+ ax.set_ylabel("",fontsize=fontsize)
3235
+ ax.tick_params(axis='x', which='major', labelsize=fontsize)
3236
+ ax.tick_params(axis='y', which='both', left=False, right=False, labelleft=False)
3237
+ title_fig = f'Heatmap ML models {suffix}'
3238
+ plt.title(title_fig, y=1.04, fontsize = fontsize, fontweight="bold")
3239
+ sb.despine(top=False, right=False)
3240
+ name_fig = '_'.join(title_fig.split())
3241
+ plt.savefig(f'{path_raw.joinpath(name_fig)}.png', dpi=300, bbox_inches='tight')
3242
+ plt.close()
3243
+
3244
+ path_reduced = '/'.join(f'{path_raw}'.replace('\\','/').split('/')[-2:])
3245
+ self.args.log.write(f'\no {name_fig} succesfully created in {path_reduced}')
3246
+
3247
+
3248
+ def create_score_heatmap(csv_df,save_path):
3249
+ '''
3250
+ Heatmap of each model's final score (0-10) for ONE metric (Interpolation or
3251
+ Boundary robustness - one call per side), used in Section F of the report instead of
3252
+ GENERATE's combined-RMSE heatmap when --all_models is active - the raw BO objective
3253
+ (combined RMSE) only reflects the search criterion used to tune each model's
3254
+ hyperparameters, not the richer final score (test performance, stability, boundary
3255
+ behavior, etc.) that the rest of the report is built around, so it isn't the most useful
3256
+ basis for comparing models against each other. Kept as two single-row images (not one
3257
+ combined 2-row image) so Interpolation can sit in the report's left column and Boundary
3258
+ robustness in the right, matching the same left/right separation used by every other
3259
+ section
3260
+ '''
3261
+
3262
+ importlib.reload(plt)
3263
+ sb.set(font_scale=1.2, style='ticks')
3264
+ _, ax = plt.subplots(figsize=(7.45,4))
3265
+ cmap_blues_75_percent_512 = [mcolor.rgb2hex(c) for c in plt.cm.Blues(np.linspace(0, 0.8, 512))]
3266
+ ax = sb.heatmap(csv_df, annot=True, linewidth=1, cmap=cmap_blues_75_percent_512,
3267
+ vmin=0, vmax=10, cbar_kws={'label': 'Score (0-10)'}, mask=csv_df.isnull())
3268
+ fontsize = 14
3269
+ ax.set_xlabel("ML Model",fontsize=fontsize)
3270
+ ax.set_ylabel("",fontsize=fontsize)
3271
+ ax.tick_params(axis='x', which='major', labelsize=fontsize)
3272
+ ax.tick_params(axis='y', which='both', left=False, right=False, labelleft=False)
3273
+ # no in-image title: the report embeds this at a fixed width with auto height (no crop),
3274
+ # and the report page already prints an "Interpolation"/"Boundary robustness" bold caption
3275
+ # right above it (see print_generate() in report.py), so a second, redundant title would
3276
+ # just eat into the image's vertical space
3277
+ sb.despine(top=False, right=False)
3278
+ plt.savefig(f'{save_path}', dpi=300, bbox_inches='tight')
3279
+ plt.close()
3280
+
3281
+
3282
+ def graph_reg(self,Xy_data,params_dict,set_types,path_n_suffix,graph_style,csv_test=False,print_fun=True,sd_graph=False,sd_set='test',show_title=True):
3283
+ '''
3284
+ Plot regression graphs of predicted vs actual values for train, validation and test sets.
3285
+ sd_set (only used when sd_graph=True and csv_test=False) picks which averaged-CV ± SD set
3286
+ to plot: 'test' (default, unchanged) or 'train' (out-of-fold CV predictions in
3287
+ train+validation, used for Interpolation item 6's train+validation SD sub-metric).
3288
+ show_title=False skips the in-image title only (print_fun still controls the "Graph in:"
3289
+ log line independently) - used for the small (270px-wide) Section B thumbnails, where the
3290
+ container height crops the title anyway (see print_img_tag()) and the surrounding item
3291
+ text already says what the plot shows
3292
+ '''
3293
+
3294
+ # Create graph
3295
+ importlib.reload(plt) # needed to avoid threading issues
3296
+ sb.set(style="ticks")
3297
+
3298
+ _, ax = plt.subplots(figsize=(7.45,6))
3299
+
3300
+ # Set tick sizes
3301
+ plt.xticks(fontsize=14)
3302
+ plt.yticks(fontsize=14)
3303
+
3304
+ error_bars = sd_set if (sd_graph and not csv_test) else "test"
3305
+
3306
+ title_graph = graph_title(self,csv_test,sd_graph,error_bars)
3307
+
3308
+ if show_title:
3309
+ plt.text(0.5, 1.08, f'{title_graph} of {os.path.basename(path_n_suffix)}', horizontalalignment='center',
3310
+ fontsize=14, fontweight='bold', transform = ax.transAxes)
3311
+
3312
+ # Plot the data (also used for the train/out-of-fold ± SD variant, sd_set='train' - same
3313
+ # blue "10x 5-fold CV" dots as the regular plot, with the ± SD error bars added on top
3314
+ # below, instead of the plain "fmt='none'" error bars showing with no dots underneath)
3315
+ if not sd_graph or sd_set == 'train':
3316
+ _ = ax.scatter(Xy_data["y_train"], Xy_data["y_pred_train"],
3317
+ c = graph_style['color_train'], s = graph_style['dot_size'], edgecolor = 'k', linewidths = 0.8, alpha = graph_style['alpha'], zorder=2)
3318
+
3319
+ if csv_test:
3320
+ error_bars = "external"
3321
+ _ = ax.scatter(Xy_data["y_external"], Xy_data["y_pred_external"],
3322
+ c = graph_style['color_test'], s = graph_style['dot_size'], edgecolor = 'k', linewidths = 0.8, alpha = graph_style['alpha'], zorder=2)
3323
+
3324
+ # skipped for the train/out-of-fold ± SD variant (sd_set='train') - that variant only
3325
+ # shows the train+validation errorbar plot below, not the (unrelated) test points
3326
+ elif not (sd_graph and sd_set == 'train'):
3327
+ _ = ax.scatter(Xy_data["y_test"], Xy_data["y_pred_test"],
3328
+ c = graph_style['color_test'], s = graph_style['dot_size'], edgecolor = 'k', linewidths = 0.8, alpha = graph_style['alpha'], zorder=3)
3329
+
3330
+ # average CV ± SD graphs
3331
+ if sd_graph:
3332
+ if not csv_test:
3333
+ # Plot the data with the error bars
3334
+ _ = ax.errorbar(Xy_data[f"y_{error_bars}"], Xy_data[f"y_pred_{error_bars}"], yerr=Xy_data[f"y_pred_{error_bars}_sd"], fmt='none', ecolor="gray", capsize=3, zorder=1)
3335
+ # Adjust labels from legend
3336
+ set_types=[error_bars,f'± SD']
3337
+
3338
+ else:
3339
+ _ = ax.errorbar(Xy_data[f"y_{error_bars}"], Xy_data[f"y_pred_{error_bars}"], yerr=Xy_data[f"y_pred_{error_bars}_sd"], fmt='none', ecolor="gray", capsize=3, zorder=1)
3340
+ set_types=['External test',f'± SD']
3341
+
3342
+ # legend (no regression line is drawn: the y = x diagonal below is the only reference line)
3343
+ legend_coords = None
3344
+ if 'CV' in set_types[0]: # CV in VERIFY
3345
+ legend_coords = (0.70, 0.15)
3346
+ elif len(set_types) == 2: # external test or sets with ± SD
3347
+ if 'External test' in set_types:
3348
+ legend_coords = (0.66, 0.15)
3349
+ else:
3350
+ legend_coords = (0.735, 0.15)
3351
+ ax.legend(loc='upper center', bbox_to_anchor=legend_coords,
3352
+ handletextpad=0,
3353
+ fancybox=True, shadow=True, ncol=5, labels=set_types, fontsize=14)
3354
+
3355
+
3356
+ # Title and labels of the axis
3357
+ plt.ylabel(f'Predicted {params_dict["y"]}', fontsize=14)
3358
+ plt.xlabel(f'{params_dict["y"]}', fontsize=14)
3359
+
3360
+ # set axis limits and graph PATH
3361
+ min_value_graph,max_value_graph,reg_plot_file,path_reduced = graph_vars(Xy_data,set_types,csv_test,path_n_suffix,sd_graph,sd_set)
3362
+
3363
+ # track the range of predictions (used in CheckML score) - an empty internal test set
3364
+ # (e.g. --csv_test with --auto_test False) has no y_test values to fold in
3365
+ if len(Xy_data["y_test"]) > 0:
3366
+ pred_min = min(min(Xy_data["y_train"]),min(Xy_data["y_test"]))
3367
+ pred_max = max(max(Xy_data["y_train"]),max(Xy_data["y_test"]))
3368
+ else:
3369
+ pred_min = min(Xy_data["y_train"])
3370
+ pred_max = max(Xy_data["y_train"])
3371
+ pred_range = np.abs(pred_max-pred_min)
3372
+ Xy_data['pred_min'] = pred_min
3373
+ Xy_data['pred_max'] = pred_max
3374
+ Xy_data['pred_range'] = pred_range
3375
+
3376
+ # Add gridlines
3377
+ ax.grid(linestyle='--', linewidth=1)
3378
+
3379
+ # main graphs: SD of each point's predictions across the CV repeats as thin gray error
3380
+ # bars behind the points (the ± SD graphs already draw their own). Added after the legend
3381
+ # so its labels stay the same
3382
+ if not sd_graph:
3383
+ for set_sd in ('train','test'):
3384
+ if len(Xy_data.get(f'y_{set_sd}',[])) > 0 and len(Xy_data.get(f'y_pred_{set_sd}_sd',[])) == len(Xy_data[f'y_{set_sd}']):
3385
+ _ = ax.errorbar(Xy_data[f"y_{set_sd}"], Xy_data[f"y_pred_{set_sd}"], yerr=Xy_data[f"y_pred_{set_sd}_sd"],
3386
+ fmt='none', ecolor='#a0a0a0', elinewidth=0.8, capsize=2, alpha=0.7, zorder=1)
3387
+
3388
+ # ideal y = y_pred diagonal (perfect predictions) behind every other object: it's the only
3389
+ # reference line, since R2/Q2 and the errors compare the predictions directly against the
3390
+ # targets. No regression line is fitted through the points - it would absorb bias or scale
3391
+ # errors and is not what any reported metric measures (Alexander et al., J. Chem. Inf.
3392
+ # Model. 2015, recommend plotting observed vs predicted values with just the y = x line)
3393
+ ax.plot([min_value_graph, max_value_graph], [min_value_graph, max_value_graph],
3394
+ color='#7f7f7f', linestyle='-', linewidth=1.2, zorder=0.5)
3395
+
3396
+ # set axis limits
3397
+ plt.xlim(min_value_graph, max_value_graph)
3398
+ plt.ylim(min_value_graph, max_value_graph)
3399
+
3400
+ # save graph
3401
+ plt.savefig(f'{reg_plot_file}', dpi=300, bbox_inches='tight')
3402
+ plt.close()
3403
+ if print_fun:
3404
+ self.args.log.write(f" - Graph in: {path_reduced}")
3405
+
3406
+
3407
+ def graph_title(self,csv_test,sd_graph,error_bars):
3408
+ '''
3409
+ Retrieves the corresponding graph title.
3410
+ '''
3411
+
3412
+ # set title for regular graphs
3413
+ if not sd_graph:
3414
+ if not csv_test:
3415
+ # regular graphs
3416
+ title_graph = f'Predictions CV and test set'
3417
+ else:
3418
+ title_graph = f'{os.path.basename(self.args.csv_test)}'
3419
+ if len(title_graph) > 30:
3420
+ title_graph = f'{title_graph[:27]}...'
3421
+
3422
+ # set title for averaged CV ± SD graphs
3423
+ else:
3424
+ if not csv_test:
3425
+ # 'train' here means the out-of-fold CV predictions in train+validation, not a
3426
+ # literal in-fold training fit - name it accordingly to avoid confusion
3427
+ sets_title = 'out-of-fold CV' if error_bars == 'train' else error_bars
3428
+ else:
3429
+ sets_title = 'external test'
3430
+
3431
+ title_graph = f'{sets_title} set ± SD (CV)'
3432
+
3433
+ return title_graph
3434
+
3435
+
3436
+ def graph_vars(Xy_data,set_types,csv_test,path_n_suffix,sd_graph,sd_set='test'):
3437
+ '''
3438
+ Set axis limits for regression plots and PATH to save the graphs
3439
+ '''
3440
+
3441
+ # x and y axis limits for graphs with multiple sets
3442
+ if not csv_test:
3443
+ # an empty internal test set (e.g. --csv_test with --auto_test False) has no y_test
3444
+ # values to fold into the axis limits - min()/max() reject empty sequences outright
3445
+ has_test = len(Xy_data["y_test"]) > 0
3446
+
3447
+ size_space = 0.1*abs(min(Xy_data["y_train"])-max(Xy_data["y_train"]))
3448
+ min_value_graph = min(min(Xy_data["y_train"]),min(Xy_data["y_pred_train"]))
3449
+ if has_test:
3450
+ min_value_graph = min(min_value_graph,min(Xy_data["y_test"]),min(Xy_data["y_pred_test"]))
3451
+ min_value_graph = min_value_graph-size_space
3452
+
3453
+ max_value_graph = max(max(Xy_data["y_train"]),max(Xy_data["y_pred_train"]))
3454
+ if has_test:
3455
+ max_value_graph = max(max_value_graph,max(Xy_data["y_test"]),max(Xy_data["y_pred_test"]))
3456
+ max_value_graph = max_value_graph+size_space
3457
+
3458
+ else: # limits for graphs with only one set
3459
+ set_type = 'external'
3460
+ size_space = 0.1*abs(min(Xy_data[f'y_{set_type}'])-max(Xy_data[f'y_{set_type}']))
3461
+ min_value_graph = min(min(Xy_data[f'y_{set_type}']),min(Xy_data[f'y_pred_{set_type}']))
3462
+ min_value_graph = min_value_graph-size_space
3463
+ max_value_graph = max(max(Xy_data[f'y_{set_type}']),max(Xy_data[f'y_pred_{set_type}']))
3464
+ max_value_graph = max_value_graph+size_space
3465
+
3466
+ # PATH of the graph
3467
+ if not csv_test:
3468
+ if not sd_graph:
3469
+ reg_plot_file = f'{os.path.dirname(path_n_suffix)}/Results_{os.path.basename(path_n_suffix)}.png'
3470
+ elif sd_set == 'train':
3471
+ reg_plot_file = f'{os.path.dirname(path_n_suffix)}/CV_variability_cv_{os.path.basename(path_n_suffix)}.png'
3472
+ else:
3473
+ reg_plot_file = f'{os.path.dirname(path_n_suffix)}/CV_variability_{os.path.basename(path_n_suffix)}.png'
3474
+ path_reduced = '/'.join(f'{reg_plot_file}'.replace('\\','/').split('/')[-2:])
3475
+
3476
+ else:
3477
+ folder_graph = f'{os.path.dirname(path_n_suffix)}/csv_test'
3478
+ if not sd_graph:
3479
+ reg_plot_file = f'{folder_graph}/Results_{os.path.basename(path_n_suffix)}_{set_type}.png'
3480
+ else:
3481
+ reg_plot_file = f'{folder_graph}/CV_variability_{os.path.basename(path_n_suffix)}_{set_type}.png'
3482
+ path_reduced = '/'.join(f'{reg_plot_file}'.replace('\\','/').split('/')[-3:])
3483
+
3484
+ return min_value_graph,max_value_graph,reg_plot_file,path_reduced
3485
+
3486
+
3487
+ def graph_clas(self,Xy_data,params_dict,set_type,path_n_suffix,csv_test=False,print_fun=True):
3488
+ '''
3489
+ Plot a confusion matrix with the prediction vs actual values
3490
+ '''
3491
+
3492
+ importlib.reload(plt) # needed to avoid threading issues
3493
+
3494
+ # get confusion matrix
3495
+ if 'CV' in set_type: # CV graphs
3496
+ y_train_binary = np.round(Xy_data[f'y_train']).astype(int)
3497
+ y_pred_train_binary = np.round(Xy_data[f'y_pred_train']).astype(int)
3498
+ class_labels = sorted(np.unique(np.concatenate([y_train_binary, y_pred_train_binary])))
3499
+ y_actual = y_train_binary
3500
+ y_pred = y_pred_train_binary
3501
+ else: # other graphs
3502
+ y_binary = np.round(Xy_data[f'y_{set_type}']).astype(int)
3503
+ y_pred_binary = np.round(Xy_data[f'y_pred_{set_type}']).astype(int)
3504
+ class_labels = sorted(np.unique(np.concatenate([y_binary, y_pred_binary])))
3505
+ y_actual = y_binary
3506
+ y_pred = y_pred_binary
3507
+
3508
+ display_labels = None
3509
+ class_mapping_reverse = params_dict.get('class_mapping_reverse')
3510
+ if class_mapping_reverse:
3511
+ class_mapping_reverse = _parse_class_mapping_reverse(class_mapping_reverse)
3512
+ class_labels = sorted(class_mapping_reverse)
3513
+ display_labels = [class_mapping_reverse[label] for label in class_labels]
3514
+ elif 'class_0_label' in params_dict and 'class_1_label' in params_dict:
3515
+ class_labels = [0, 1]
3516
+ display_labels = [params_dict['class_0_label'], params_dict['class_1_label']]
3517
+
3518
+ # plot directly onto a pre-created figure (same format/size used in reg graphs) instead
3519
+ # of letting from_predictions() create and leak its own internal figure when ax=None
3520
+ _, ax = plt.subplots(figsize=(7.45,6))
3521
+ matrix = ConfusionMatrixDisplay.from_predictions(
3522
+ y_actual,
3523
+ y_pred,
3524
+ labels=class_labels,
3525
+ normalize=None,
3526
+ cmap='Blues',
3527
+ display_labels=display_labels,
3528
+ ax=ax,
3529
+ )
3530
+
3531
+ if print_fun:
3532
+ if 'CV' not in set_type:
3533
+ title_set = f'{set_type} set'
3534
+ else:
3535
+ title_set = set_type
3536
+ plt.text(0.5, 1.08, f'{title_set} of {os.path.basename(path_n_suffix)}', horizontalalignment='center',
3537
+ fontsize=14, fontweight='bold', transform = ax.transAxes)
3538
+
3539
+ plt.xlabel(f'Predicted {params_dict["y"]}', fontsize=14)
3540
+ plt.ylabel(f'{params_dict["y"]}', fontsize=14)
3541
+ plt.xticks(fontsize=14)
3542
+ plt.yticks(fontsize=14)
3543
+
3544
+ # save fig
3545
+ if 'CV' in set_type: # CV graphs
3546
+ clas_plot_file = f'{os.path.dirname(path_n_suffix)}/CV_train_valid_predict_{os.path.basename(path_n_suffix)}.png'
3547
+ path_reduced = '/'.join(f'{clas_plot_file}'.replace('\\','/').split('/')[-2:])
3548
+
3549
+ elif not csv_test:
3550
+ clas_plot_file = f'{os.path.dirname(path_n_suffix)}/Results_{os.path.basename(path_n_suffix)}_{set_type}.png'
3551
+ path_reduced = '/'.join(f'{clas_plot_file}'.replace('\\','/').split('/')[-2:])
3552
+
3553
+ else:
3554
+ folder_graph = f'{os.path.dirname(path_n_suffix)}/csv_test'
3555
+ clas_plot_file = f'{folder_graph}/Results_{os.path.basename(path_n_suffix)}_{set_type}.png'
3556
+ path_reduced = '/'.join(f'{clas_plot_file}'.replace('\\','/').split('/')[-3:])
3557
+
3558
+ plt.savefig(f'{clas_plot_file}', dpi=300, bbox_inches='tight')
3559
+ plt.close()
3560
+
3561
+ if print_fun:
3562
+ self.args.log.write(f" - Graph in: {path_reduced}")
3563
+
3564
+
3565
+ def linear_equation(self,Xy_data,model_data,loaded_model):
3566
+ '''
3567
+ Prints the linear regression equation for MVL models. Must be logged before shap_analysis()
3568
+ and PFI_plot(), since REPORT's print_features() reads this equation back out of the log file
3569
+ to display it above the SHAP/PFI plots. loaded_model must already be fitted on
3570
+ Xy_data['X_train_scaled']/['y_train'] (shared with shap_analysis()/PFI_plot() so the same
3571
+ model isn't refit 3 times in a row for the same data)
3572
+ '''
3573
+
3574
+ descriptors = list(Xy_data['X_train_scaled'].columns)
3575
+ coefs = np.ravel(loaded_model.coef_)
3576
+ intercept = float(np.ravel([loaded_model.intercept_])[0])
3577
+
3578
+ def build_equation(intercept_val,coef_vals,desc_labels,fmt='.3f'):
3579
+ terms = [f'{coef:{fmt}}*{desc}' for coef,desc in zip(coef_vals,desc_labels)]
3580
+ return (f"y = {intercept_val:{fmt}} + " + ' + '.join(terms)).replace('+ -', '- ')
3581
+
3582
+ # the model is fitted on STANDARDIZED descriptors, z = (x - mean)/SD (see scale_df(), fitted
3583
+ # on the whole database, train + test), so its coefficients apply to z, not to x - a
3584
+ # descriptor below its mean has a negative z and lowers the prediction even when the
3585
+ # coefficient and the original value are both positive
3586
+ equation_std = build_equation(intercept,coefs,[f'z({desc})' for desc in descriptors])
3587
+
3588
+ # same equation in the original units of each descriptor: coef/SD per descriptor and
3589
+ # intercept - sum(coef*mean/SD). Mean/SD are recomputed exactly like StandardScaler did
3590
+ # (population SD, and SD = 1 for constant columns)
3591
+ X_all = pd.concat([Xy_data['X_train'][descriptors], Xy_data['X_test'][descriptors]])
3592
+ means = X_all.mean().to_numpy(dtype=float)
3593
+ sds = X_all.std(ddof=0).to_numpy(dtype=float)
3594
+ sds[sds == 0] = 1.0
3595
+ coefs_orig = coefs/sds
3596
+ intercept_orig = intercept - float(np.sum(coefs*means/sds))
3597
+ # 4 significant figures: original-unit coefficients can be small (i.e. 0.087 per ppm) and
3598
+ # 3 fixed decimals would lose most of their precision
3599
+ equation_orig = build_equation(intercept_orig,coefs_orig,descriptors,fmt='.4g')
3600
+
3601
+ # REPORT's print_features() reads the line right after each "o Linear model equation" header
3602
+ print_eq = f"\n o Linear model equation (standardized descriptors, z = (x - mean)/SD)"
3603
+ print_eq += f"\n - {equation_std}"
3604
+ print_eq += f"\n o Linear model equation (original units of the descriptors)"
3605
+ print_eq += f"\n - {equation_orig}"
3606
+
3607
+ self.args.log.write(print_eq)
3608
+
3609
+
3610
+ def shap_analysis(self,Xy_data,model_data,path_n_suffix,loaded_model):
3611
+ '''
3612
+ Plots and prints the results of the SHAP analysis. loaded_model must already be fitted on
3613
+ Xy_data['X_train_scaled']/['y_train']
3614
+ '''
3615
+
3616
+ importlib.reload(plt) # needed to avoid threading issues
3617
+ _, _ = plt.subplots(figsize=(7.45,6))
3618
+
3619
+ shap_plot_file = f'{os.path.dirname(path_n_suffix)}/SHAP_{os.path.basename(path_n_suffix)}.png'
3620
+
3621
+ # run the SHAP analysis and save the plot
3622
+ shap_values = None
3623
+ if model_data['model'].upper() in ['RF', 'GB']:
3624
+ # exact Shapley values for tree ensembles in polynomial time, instead of
3625
+ # the Exact/Permutation fallback that shap.Explainer(model.predict, X) uses
3626
+ # (that fallback can't detect the tree structure and gets very slow on
3627
+ # datasets with many rows and/or descriptors). Some tree models aren't supported by
3628
+ # TreeExplainer (i.e. GradientBoostingClassifier with more than two classes) - those
3629
+ # use the generic fallback below instead of crashing PREDICT
3630
+ try:
3631
+ explainer = shap.TreeExplainer(loaded_model)
3632
+ shap_values = explainer(Xy_data['X_train_scaled'])
3633
+ except Exception:
3634
+ shap_values = None
3635
+ elif model_data['model'].upper() == 'MVL':
3636
+ # exact Shapley values in closed form for linear models (no repeated
3637
+ # model evaluations), instead of the black-box Exact/Permutation fallback
3638
+ explainer = shap.LinearExplainer(loaded_model, Xy_data['X_train_scaled'])
3639
+ shap_values = explainer(Xy_data['X_train_scaled'])
3640
+ if shap_values is None:
3641
+ # black-box models (NN, GP, AdaB) still need the generic Exact/Permutation
3642
+ # fallback, which gets slow because its cost scales with the size of the
3643
+ # background data. Summarizing the background speeds this up a lot on large
3644
+ # datasets; below 100 points summarizing barely helps and only adds
3645
+ # approximation error, so the full training set is used as-is in that case
3646
+ background = Xy_data['X_train_scaled']
3647
+ if len(background) > 100:
3648
+ background = shap.sample(background, nsamples=100, random_state=model_data['seed'])
3649
+ explainer = shap.Explainer(loaded_model.predict, background, seed=model_data['seed'])
3650
+ try:
3651
+ shap_values = explainer(Xy_data['X_train_scaled'])
3652
+ except ValueError:
3653
+ shap_values = explainer(Xy_data['X_train_scaled'],max_evals=(2*len(Xy_data['X_train_scaled'].columns))+1)
3654
+
3655
+ if np.asarray(shap_values.values).ndim == 3:
3656
+ # classifiers return SHAP values per class (n_samples, n_features, n_classes);
3657
+ # shap's own plotting code isn't reliable across class-axis sizes (e.g. size 1
3658
+ # for some binary fits), so pick the last class (the positive class in binary
3659
+ # problems) explicitly and plot/summarize a plain 2D array throughout
3660
+ shap_values = shap_values[..., -1]
3661
+
3662
+ shap_show = [self.args.shap_show,len(Xy_data['X_train_scaled'].columns)]
3663
+ aspect_shap = 25+((min(shap_show)-2)*5)
3664
+ height_shap = 1.2+min(shap_show)/4
3665
+
3666
+ # explainer = shap.TreeExplainer(loaded_model) # in case the standard version doesn't work
3667
+ _ = shap.summary_plot(shap_values, Xy_data['X_train_scaled'], max_display=self.args.shap_show,show=False, plot_size=[7.45,height_shap])
3668
+
3669
+ # set title
3670
+ plt.title(f'SHAP analysis of {os.path.basename(path_n_suffix)}', fontsize = 14, fontweight="bold")
3671
+
3672
+ path_reduced = '/'.join(f'{shap_plot_file}'.replace('\\','/').split('/')[-2:])
3673
+ print_shap = f"\n o SHAP plot saved in {path_reduced}"
3674
+
3675
+ # collect SHAP values and print (vectorized instead of looping over every row per descriptor)
3676
+ desc_list = list(Xy_data['X_train_scaled'].columns)
3677
+ min_list = shap_values.values.min(axis=0).tolist()
3678
+ max_list = shap_values.values.max(axis=0).tolist()
3679
+
3680
+ if max(max_list, key=abs) > max(min_list, key=abs):
3681
+ max_list, min_list, desc_list = (list(t) for t in zip(*sorted(zip(max_list, min_list, desc_list), reverse=True)))
3682
+ else:
3683
+ min_list, max_list, desc_list = (list(t) for t in zip(*sorted(zip(min_list, max_list, desc_list), reverse=False)))
3684
+
3685
+ for i,desc in enumerate(desc_list):
3686
+ print_shap += f"\n - {desc} = min: {min_list[i]:.2}, max: {max_list[i]:.2}"
3687
+
3688
+ self.args.log.write(print_shap)
3689
+
3690
+ # adjust width of the colorbar
3691
+ plt.gcf().axes[-1].set_aspect(aspect_shap)
3692
+ plt.gcf().axes[-1].set_box_aspect(aspect_shap)
3693
+
3694
+ plt.savefig(f'{shap_plot_file}', dpi=300, bbox_inches='tight')
3695
+ plt.close()
3696
+
3697
+
3698
+ def PFI_plot(self,Xy_data,model_data,path_n_suffix,loaded_model):
3699
+ '''
3700
+ Plots and prints the results of the PFI analysis. loaded_model must already be fitted on
3701
+ Xy_data['X_train_scaled']/['y_train']
3702
+ '''
3703
+
3704
+ importlib.reload(plt) # needed to avoid threading issues
3705
+ pfi_plot_file = f'{os.path.dirname(path_n_suffix)}/PFI_{os.path.basename(path_n_suffix)}.png'
3706
+
3707
+ # select scoring function for PFI analysis based on the error type
3708
+ scoring, _, error_type = scoring_n_score(self,model_data,Xy_data,loaded_model)
3709
+
3710
+ perm_importance = permutation_importance(loaded_model, Xy_data['X_train_scaled'], Xy_data['y_train'], scoring=scoring, n_repeats=self.args.pfi_epochs, random_state=model_data['seed'], n_jobs=1)
3711
+
3712
+ # sort descriptors and results from PFI
3713
+ desc_list, PFI_values, PFI_sd = [],[],[]
3714
+ for i,desc in enumerate(Xy_data['X_train_scaled']):
3715
+ desc_list.append(desc)
3716
+ PFI_values.append(perm_importance.importances_mean[i])
3717
+ PFI_sd.append(perm_importance.importances_std[i])
3718
+
3719
+ # sort from higher to lower values and keep only the top self.args.pfi_show descriptors
3720
+ PFI_values, PFI_sd, desc_list = (list(t) for t in zip(*sorted(zip(PFI_values, PFI_sd, desc_list), reverse=True)))
3721
+ PFI_values_plot = PFI_values[:self.args.pfi_show][::-1]
3722
+ desc_list_plot = desc_list[:self.args.pfi_show][::-1]
3723
+
3724
+ # plot and print results
3725
+ _, ax = plt.subplots(figsize=(7.45,6))
3726
+ y_ticks = np.arange(0, len(desc_list_plot))
3727
+ ax.barh(desc_list_plot, PFI_values_plot)
3728
+ ax.set_yticks(y_ticks,labels=desc_list_plot,fontsize=14)
3729
+ plt.text(0.5, 1.08, f'Permutation feature importances (PFIs) of {os.path.basename(path_n_suffix)}', horizontalalignment='center',
3730
+ fontsize=14, fontweight='bold', transform = ax.transAxes)
3731
+ ax.set(ylabel=None, xlabel='PFI')
3732
+
3733
+ plt.savefig(f'{pfi_plot_file}', dpi=300, bbox_inches='tight')
3734
+ plt.close()
3735
+
3736
+ path_reduced = '/'.join(f'{pfi_plot_file}'.replace('\\','/').split('/')[-2:])
3737
+ print_PFI = f"\n o PFI plot saved in {path_reduced}"
3738
+
3739
+ print_PFI += f'\n Influence on {error_type.upper()}'
3740
+
3741
+ for i,desc in enumerate(desc_list):
3742
+ print_PFI += f"\n - {desc} = {PFI_values[i]:.2} +- {PFI_sd[i]:.2}"
3743
+
3744
+ self.args.log.write(print_PFI)
3745
+
3746
+
3747
+ def outlier_plot(self,Xy_data,path_n_suffix,name_points,graph_style):
3748
+ '''
3749
+ Plots and prints the results of the outlier analysis
3750
+ '''
3751
+
3752
+ importlib.reload(plt) # needed to avoid threading issues
3753
+ # detect outliers
3754
+ outliers_data, print_outliers = outlier_filter(self, Xy_data, name_points)
3755
+
3756
+ # plot data in SD units
3757
+ sb.set(style="ticks")
3758
+
3759
+ _, ax = plt.subplots(figsize=(7.45,6))
3760
+ plt.text(0.5, 1.08, f'Outlier analysis of {os.path.basename(path_n_suffix)}', horizontalalignment='center',
3761
+ fontsize=14, fontweight='bold', transform = ax.transAxes)
3762
+
3763
+ plt.grid(linestyle='--', linewidth=1)
3764
+ _ = ax.scatter(outliers_data['train_scaled'], outliers_data['train_scaled'],
3765
+ c = graph_style['color_train'], s = graph_style['dot_size'], edgecolor = 'k', linewidths = 0.8, alpha = graph_style['alpha'], zorder=2)
3766
+ _ = ax.scatter(outliers_data['test_scaled'], outliers_data['test_scaled'],
3767
+ c = graph_style['color_test'], s = graph_style['dot_size'], edgecolor = 'k', linewidths = 0.8, alpha = graph_style['alpha'], zorder=2)
3768
+
3769
+ # Set styling preferences and graph limits
3770
+ plt.xlabel('SD of the errors',fontsize=14)
3771
+ plt.xticks(fontsize=14)
3772
+ plt.ylabel('SD of the errors',fontsize=14)
3773
+ plt.yticks(fontsize=14)
3774
+
3775
+ axis_limit = max(outliers_data['train_scaled'], key=abs)
3776
+ if outliers_data.get('test_scaled') is not None and len(outliers_data['test_scaled']) > 0:
3777
+ if max(outliers_data['test_scaled'], key=abs) > axis_limit:
3778
+ axis_limit = max(outliers_data['test_scaled'], key=abs)
3779
+ axis_limit = axis_limit+0.5
3780
+ if axis_limit < 2.5: # this fixes a problem when representing rectangles in graphs with low SDs
3781
+ axis_limit = 2.5
3782
+ plt.ylim(-axis_limit, axis_limit)
3783
+ plt.xlim(-axis_limit, axis_limit)
3784
+
3785
+ # plot rectangles in corners
3786
+ diff_tvalue = axis_limit - self.args.t_value
3787
+ Rectangle_top = mpatches.Rectangle(xy=(axis_limit, axis_limit), width=-diff_tvalue, height=-diff_tvalue, facecolor='grey', alpha=0.3)
3788
+ Rectangle_bottom = mpatches.Rectangle(xy=(-(axis_limit), -(axis_limit)), width=diff_tvalue, height=diff_tvalue, facecolor='grey', alpha=0.3)
3789
+ ax.add_patch(Rectangle_top)
3790
+ ax.add_patch(Rectangle_bottom)
3791
+
3792
+ # save plot and print results
3793
+ outliers_plot_file = f'{os.path.dirname(path_n_suffix)}/Outliers_{os.path.basename(path_n_suffix)}.png'
3794
+ plt.savefig(f'{outliers_plot_file}', dpi=300, bbox_inches='tight')
3795
+ plt.close()
3796
+
3797
+ path_reduced = '/'.join(f'{outliers_plot_file}'.replace('\\','/').split('/')[-2:])
3798
+ print_outliers += f"\n o Outliers plot saved in {path_reduced}"
3799
+
3800
+ if 'train' not in name_points:
3801
+ print_outliers += f'\n x No names option (or var missing in CSV file)! Outlier names will not be shown'
3802
+ else:
3803
+ if 'test_scaled' in outliers_data and 'test' not in name_points:
3804
+ print_outliers += f'\n x No names option (or var missing in CSV file in the test file)! Outlier names will not be shown'
3805
+
3806
+ print_outliers = outlier_analysis(print_outliers,outliers_data,'train')
3807
+ print_outliers = outlier_analysis(print_outliers,outliers_data,'test')
3808
+
3809
+ self.args.log.write(print_outliers)
3810
+
3811
+
3812
+ def outlier_analysis(print_outliers,outliers_data,outliers_set):
3813
+ '''
3814
+ Analyzes the outlier results
3815
+ '''
3816
+
3817
+ if outliers_set == 'train':
3818
+ label_set = 'Train'
3819
+ outliers_label = 'outliers_train'
3820
+ n_points_label = 'train_scaled'
3821
+ outliers_name = 'names_train'
3822
+ elif outliers_set == 'valid':
3823
+ label_set = 'Validation'
3824
+ outliers_label = 'outliers_valid'
3825
+ n_points_label = 'valid_scaled'
3826
+ outliers_name = 'names_valid'
3827
+ elif outliers_set == 'test':
3828
+ label_set = 'Test'
3829
+ outliers_label = 'outliers_test'
3830
+ n_points_label = 'test_scaled'
3831
+ outliers_name = 'names_test'
3832
+
3833
+ n_points = len(outliers_data[n_points_label])
3834
+ per_cent = (len(outliers_data[outliers_label])/n_points)*100 if n_points > 0 else 0.0
3835
+ print_outliers += f"\n {label_set}: {len(outliers_data[outliers_label])} outliers out of {n_points} datapoints ({per_cent:.1f}%)"
3836
+ for val,name in zip(outliers_data[outliers_label], outliers_data[outliers_name]):
3837
+ print_outliers += f"\n - {name} ({val:.2} SDs)"
3838
+ return print_outliers
3839
+
3840
+
3841
+ def outlier_filter(self, Xy_data, name_points):
3842
+ '''
3843
+ Calculates and stores absolute errors in SD units for all the sets
3844
+ '''
3845
+
3846
+ # calculate absolute errors between predicted y and actual values
3847
+ outliers_train = [abs(x-y) for x,y in zip(Xy_data['y_train'],Xy_data['y_pred_train'])]
3848
+ outliers_test = [abs(x-y) for x,y in zip(Xy_data['y_test'],Xy_data['y_pred_test'])]
3849
+
3850
+ # the errors are scaled using standard deviation units. When the absolute
3851
+ # error is larger than the t-value, the point is considered an outlier. All the sets
3852
+ # use the mean and SD of the train set
3853
+ outliers_mean = np.mean(outliers_train)
3854
+ outliers_sd = np.std(outliers_train)
3855
+ # a train set with (near-)identical errors across all points gives SD = 0, which would
3856
+ # turn every scaled error into inf/nan instead of correctly showing "no outliers"
3857
+ if outliers_sd == 0:
3858
+ outliers_sd = 1
3859
+
3860
+ outliers_data = {}
3861
+ outliers_data['train_scaled'] = (outliers_train-outliers_mean)/outliers_sd
3862
+ outliers_data['test_scaled'] = (outliers_test-outliers_mean)/outliers_sd
3863
+
3864
+ print_outliers, naming, naming_test = '', False, False
3865
+ if 'train' in name_points:
3866
+ naming = True
3867
+ if 'test' in name_points:
3868
+ naming_test = True
3869
+
3870
+ outliers_data['outliers_train'], outliers_data['names_train'] = detect_outliers(self, outliers_data['train_scaled'], name_points, naming, 'train')
3871
+ outliers_data['outliers_test'], outliers_data['names_test'] = detect_outliers(self, outliers_data['test_scaled'], name_points, naming_test, 'test')
3872
+
3873
+ return outliers_data, print_outliers
3874
+
3875
+
3876
+ def detect_outliers(self, outliers_scaled, name_points, naming_detect, set_type):
3877
+ '''
3878
+ Detects and store outliers with their corresponding datapoint names
3879
+ '''
3880
+
3881
+ val_outliers = []
3882
+ name_outliers = []
3883
+ if naming_detect:
3884
+ name_points_list = name_points[set_type].to_list()
3885
+ for i,val in enumerate(outliers_scaled):
3886
+ if val > self.args.t_value or val < -self.args.t_value:
3887
+ val_outliers.append(val)
3888
+ if naming_detect:
3889
+ name_outliers.append(name_points_list[i])
3890
+
3891
+ return val_outliers, name_outliers
3892
+
3893
+
3894
+ def distribution_plot(self,Xy_data,path_n_suffix,params_dict):
3895
+ '''
3896
+ Plots histogram (reg) or bin plot (clas).
3897
+ '''
3898
+
3899
+ # make graph
3900
+ importlib.reload(plt) # needed to avoid threading issues
3901
+ sb.set(style="ticks")
3902
+
3903
+ _, ax = plt.subplots(figsize=(7.45,6))
3904
+ plt.text(0.5, 1.08, f'y-values distribution (CV + test) of {os.path.basename(path_n_suffix)}', horizontalalignment='center',
3905
+ fontsize=14, fontweight='bold', transform = ax.transAxes)
3906
+
3907
+ plt.grid(linestyle='--', linewidth=1)
3908
+
3909
+ # combine train and validation sets
3910
+ y_combined = pd.concat([Xy_data['y_train'],Xy_data['y_test']], axis=0).reset_index(drop=True)
3911
+
3912
+ # plot histogram, quartile lines and the points in each quartile
3913
+ if params_dict['type'].lower() == 'reg':
3914
+ y_dist_dict,ax = plot_quartiles(y_combined,ax)
3915
+
3916
+ # plot a bar plot with the count of each y type
3917
+ elif params_dict['type'].lower() == 'clas':
3918
+ class_mapping_reverse = params_dict.get('class_mapping_reverse')
3919
+ if class_mapping_reverse:
3920
+ class_mapping_reverse = _parse_class_mapping_reverse(class_mapping_reverse)
3921
+ y_dist_dict,ax = plot_y_count(y_combined,ax,class_mapping_reverse)
3922
+
3923
+ # set styling preferences and graph limits
3924
+ plt.xlabel(f'{params_dict["y"]} values',fontsize=14)
3925
+ plt.xticks(fontsize=14)
3926
+ plt.ylabel('Frequency',fontsize=14)
3927
+ plt.yticks(fontsize=14)
3928
+
3929
+ # set limits
3930
+ if params_dict['type'].lower() == 'reg':
3931
+ border_y_range = 0.1*np.abs(max(y_combined)-min(y_combined))
3932
+ plt.xlim(min(y_combined)-border_y_range, max(y_combined)+border_y_range)
3933
+
3934
+ # save plot and print results
3935
+ orig_distrib_file = f'y_distribution_{os.path.basename(path_n_suffix)}.png'
3936
+ plt.savefig(f'{orig_distrib_file}', dpi=300, bbox_inches='tight')
3937
+ plt.close()
3938
+ # for a VERY weird reason, I need to save the figure in the working directory and then move it into PREDICT
3939
+ final_distrib_file = f'{os.path.dirname(path_n_suffix)}/y_distribution_{os.path.basename(path_n_suffix)}.png'
3940
+ shutil.move(orig_distrib_file, final_distrib_file)
3941
+
3942
+ path_reduced = '/'.join(f'{final_distrib_file}'.replace('\\','/').split('/')[-2:])
3943
+ print_distrib = f"\n o y-values distribution plot saved in {path_reduced}"
3944
+
3945
+ # print the quartile results
3946
+ if params_dict['type'].lower() == 'reg':
3947
+ # Q1-Q4 are four EQUAL-WIDTH intervals of the y range (see plot_quartiles()), not
3948
+ # quartiles of the data (which would hold 25% of the points each by definition). The
3949
+ # "Ideally, the number of datapoints in" start and the 3-line layout are read by REPORT
3950
+ print_distrib += f"\n Ideally, the number of datapoints in the four equal-width intervals of the y range (Q1-Q4, from the lowest to the highest y values; not quartiles of the data) should be uniform (25% population in each) to have similar confidence intervals in the predictions across the y-range"
3951
+ quartile_pops = [len(y_dist_dict['q1_points']),len(y_dist_dict['q2_points']),len(y_dist_dict['q3_points']),len(y_dist_dict['q4_points'])]
3952
+ print_distrib += f"\n - The number of points in each interval is Q1: {quartile_pops[0]}, Q2: {quartile_pops[1]}, Q3: {quartile_pops[2]}, Q4: {quartile_pops[3]}"
3953
+ quartile_min_idx = quartile_pops.index(min(quartile_pops))
3954
+ quartile_max_idx = quartile_pops.index(max(quartile_pops))
3955
+ if 4*min(quartile_pops) < max(quartile_pops):
3956
+ print_distrib += f"\n x WARNING! Your data is not uniform (Q{quartile_min_idx+1} has {min(quartile_pops)} points while Q{quartile_max_idx+1} has {max(quartile_pops)})"
3957
+ elif 2*min(quartile_pops) < max(quartile_pops):
3958
+ print_distrib += f"\n x WARNING! Your data is slightly not uniform (Q{quartile_min_idx+1} has {min(quartile_pops)} points while Q{quartile_max_idx+1} has {max(quartile_pops)})"
3959
+ else:
3960
+ print_distrib += f"\n o Your data seems quite uniform"
3961
+
3962
+ # bimodality heuristic: a single large gap in the sorted y-values that splits the
3963
+ # dataset into two sizeable groups can mean the response is really two distinct
3964
+ # populations (e.g. "active"/"inactive") rather than one continuous variable - a cheap
3965
+ # largest-gap proxy (not a rigorous dip/KDE test) good enough to flag for a closer look.
3966
+ # Logged as its own marker line so report.py's warning box can pick it up (see
3967
+ # get_warning_lines() in report.py)
3968
+ sorted_y = sorted(y_combined)
3969
+ n_points_y = len(sorted_y)
3970
+ y_span = sorted_y[-1] - sorted_y[0]
3971
+ if n_points_y >= 8 and y_span > 0:
3972
+ gaps = [sorted_y[i+1] - sorted_y[i] for i in range(n_points_y - 1)]
3973
+ max_gap = max(gaps)
3974
+ max_gap_idx = gaps.index(max_gap)
3975
+ left_count = max_gap_idx + 1
3976
+ right_count = n_points_y - left_count
3977
+ min_side = max(2, round(0.2 * n_points_y))
3978
+ if max_gap > 0.25 * y_span and left_count >= min_side and right_count >= min_side:
3979
+ print_distrib += f"\n x WARNING! Your data seems to have two separate y-value groups, split by a gap of {max_gap:.2} ({round(100*max_gap/y_span)}% of the y-range) between {sorted_y[max_gap_idx]:.2} and {sorted_y[max_gap_idx+1]:.2}"
3980
+
3981
+ elif params_dict['type'].lower() == 'clas':
3982
+ n_classes = len(y_dist_dict['count_labels'])
3983
+ ideal_population = round(100 / n_classes, 1) if n_classes else 0
3984
+ print_distrib += f"\n Ideally, the number of datapoints in each prediction class should be uniform ({ideal_population}% population per class) to have similar reliability in the predictions across classes"
3985
+ distrib_counts = list(y_dist_dict['count_labels'])
3986
+ class_counts_txt = ', '.join(
3987
+ f"{label}: {count}"
3988
+ for label, count in zip(y_dist_dict['type_labels'], y_dist_dict['count_labels'])
3989
+ )
3990
+ print_distrib += f"\n - The number of points in each class is {class_counts_txt}"
3991
+ class_min_idx = distrib_counts.index(min(distrib_counts))
3992
+ class_max_idx = distrib_counts.index(max(distrib_counts))
3993
+ if 3*min(distrib_counts) < max(distrib_counts):
3994
+ print_distrib += f"\n x WARNING! Your data is not uniform (class {y_dist_dict['type_labels'][class_min_idx]} has {min(distrib_counts)} points while class {y_dist_dict['type_labels'][class_max_idx]} has {max(distrib_counts)})"
3995
+ elif 1.5*min(distrib_counts) < max(distrib_counts):
3996
+ print_distrib += f"\n x WARNING! Your data is slightly not uniform (class {y_dist_dict['type_labels'][class_min_idx]} has {min(distrib_counts)} points while class {y_dist_dict['type_labels'][class_max_idx]} has {max(distrib_counts)})"
3997
+ else:
3998
+ print_distrib += f"\n o Your data seems quite uniform"
3999
+
4000
+ self.args.log.write(print_distrib)
4001
+
4002
+
4003
+ def plot_quartiles(y_combined,ax):
4004
+ '''
4005
+ Plot histogram, quartile lines and the points in each quartile.
4006
+ '''
4007
+
4008
+ bins = max([round(len(y_combined)/5),5]) # at least 5 bins until 25 points
4009
+ # histogram
4010
+ y_hist, _, _ = ax.hist(y_combined, bins=bins,
4011
+ color='#1f77b4', edgecolor='k', linewidth=1, alpha=1)
4012
+
4013
+ # uniformity lines to plot
4014
+ separation_range = np.abs(max(y_combined)-min(y_combined))/4
4015
+ quart_dict = {'line_1': min(y_combined),
4016
+ 'line_2': min(y_combined) + separation_range,
4017
+ 'line_3': min(y_combined) + (2*separation_range),
4018
+ 'line_4': min(y_combined) + (3*separation_range),
4019
+ 'line_5': max(y_combined)}
4020
+
4021
+ lines_plot = [quart_dict[line] for line in quart_dict]
4022
+ ax.vlines([lines_plot], ymin=max(y_hist)*1.05, ymax=max(y_hist)*1.3, colors='crimson', linestyles='--')
4023
+
4024
+ # points in each quartile
4025
+ quart_dict['q1_points'] = []
4026
+ quart_dict['q2_points'] = []
4027
+ quart_dict['q3_points'] = []
4028
+ quart_dict['q4_points'] = []
4029
+
4030
+ # half-open intervals, so a value lying exactly on a boundary (common with integer y values)
4031
+ # is counted once instead of being left out of every interval
4032
+ for val in y_combined:
4033
+ if val < quart_dict['line_2']:
4034
+ quart_dict['q1_points'].append(val)
4035
+ elif val < quart_dict['line_3']:
4036
+ quart_dict['q2_points'].append(val)
4037
+ elif val < quart_dict['line_4']:
4038
+ quart_dict['q3_points'].append(val)
4039
+ else:
4040
+ quart_dict['q4_points'].append(val)
4041
+
4042
+ x_quart = 0.185
4043
+ for quart in quart_dict:
4044
+ if 'points' in quart:
4045
+ plt.text(x_quart, 0.845, f'Q{quart[1]}\n{len(quart_dict[quart])} points', horizontalalignment='center',
4046
+ fontsize=12, transform = ax.transAxes, backgroundcolor='w')
4047
+ x_quart += 0.209
4048
+
4049
+ return quart_dict,ax
4050
+
4051
+
4052
+ def plot_y_count(y_combined,ax,class_mapping_reverse=None):
4053
+ '''
4054
+ Plot a bar plot with the count of each y type.
4055
+ '''
4056
+
4057
+ # get the number of times that each y type is included
4058
+ labels_used = sorted(pd.unique(y_combined))
4059
+ type_labels,count_labels = [],[]
4060
+ for label in labels_used:
4061
+ if class_mapping_reverse:
4062
+ type_labels.append(class_mapping_reverse.get(int(label), label))
4063
+ else:
4064
+ type_labels.append(label)
4065
+ count_labels.append(len(y_combined[y_combined == label]))
4066
+
4067
+ x_labels = list(range(len(type_labels)))
4068
+ _ = ax.bar(x_labels, count_labels, tick_label=type_labels,
4069
+ color='#1f77b4', edgecolor='k', linewidth=1, alpha=1,
4070
+ width=0.4)
4071
+
4072
+ y_dist_dict = {'type_labels': type_labels,
4073
+ 'count_labels': count_labels}
4074
+
4075
+ return y_dist_dict,ax
4076
+
4077
+
4078
+ def get_prediction_results(model_data,y,y_pred_all):
4079
+ '''
4080
+ Calculate metrics based on y and y_pred
4081
+ '''
4082
+
4083
+ # an empty set (e.g. no internal test set when --csv_test is used with --auto_test False)
4084
+ # has no metrics to compute - sklearn's metric functions reject 0-sample arrays outright
4085
+ if len(y) == 0:
4086
+ return float('nan'), float('nan'), float('nan')
4087
+
4088
+ if model_data['type'].lower() == 'reg':
4089
+ mae = mean_absolute_error(y,y_pred_all)
4090
+ rmse = np.sqrt(mean_squared_error(y,y_pred_all))
4091
+ # R2 is the coefficient of determination of the predictions themselves (1 - SSres/SStot,
4092
+ # i.e. measured against the y = x line, like MAE/RMSE), NOT the squared Pearson
4093
+ # correlation of a regression fitted through the observed vs predicted points, which
4094
+ # ignores bias and scale errors and can only be equal or higher (see Alexander, Tropsha
4095
+ # and Winkler, J. Chem. Inf. Model. 2015, 55, 1316). It can be negative when the
4096
+ # predictions are worse than predicting the mean
4097
+ if len(np.unique(y)) > 1:
4098
+ r2 = r2_score(y,y_pred_all)
4099
+ else:
4100
+ r2 = 0.0
4101
+
4102
+ return r2, mae, rmse
4103
+
4104
+ elif model_data['type'].lower() == 'clas':
4105
+ # ensure true and predicted labels are integers
4106
+ acc = accuracy_score(y,np.round(y_pred_all).astype(int))
4107
+ # F1 by default uses average='binnary', to deal with predictions with more than 2 ouput values we use average='micro'
4108
+ # if len(set(y))==2:
4109
+ try:
4110
+ f1_score_val = f1_score(y,np.round(y_pred_all).astype(int))
4111
+ except ValueError:
4112
+ f1_score_val = f1_score(y,np.round(y_pred_all).astype(int),average='micro')
4113
+ mcc = matthews_corrcoef(y,np.round(y_pred_all).astype(int))
4114
+ return acc, f1_score_val, mcc
4115
+
4116
+
4117
+ def get_error_labels(model_type):
4118
+ """
4119
+ Returns the three error metric labels for the given model type.
4120
+
4121
+ Parameters
4122
+ ----------
4123
+ model_type : str
4124
+ The type of model: 'reg' for regression or 'clas' for classification
4125
+
4126
+ Returns
4127
+ -------
4128
+ tuple of str
4129
+ Three error labels appropriate for the model type:
4130
+ - Regression: ('r2', 'mae', 'rmse')
4131
+ - Classification: ('acc', 'f1', 'mcc')
4132
+ """
4133
+ error_labels = {
4134
+ 'reg': ('r2', 'mae', 'rmse'),
4135
+ 'clas': ('acc', 'f1', 'mcc')
4136
+ }
4137
+
4138
+ model_type_lower = model_type.lower()
4139
+
4140
+ return error_labels[model_type_lower]
4141
+
4142
+
4143
+ def load_db_n_params(self,params_dir,suffix,suffix_title,module,print_load):
4144
+ '''
4145
+ Loads the parameters and Xy databases from a folder, add scaled X data and print information
4146
+ about the databases
4147
+ '''
4148
+
4149
+ # load databases from CSV
4150
+ csv_df,csv_X,csv_y,model_data,_ = load_dfs(self,params_dir,module,print_info=print_load)
4151
+
4152
+ # detect points in the test set
4153
+ test_points = csv_X[csv_X['Set'] == 'Test'].index.tolist()
4154
+ csv_X = csv_X.drop(columns=['Set'])
4155
+
4156
+ # keep only the descriptors used in the model
4157
+ csv_X = csv_X[model_data['X_descriptors']]
4158
+
4159
+ # load and adjust external set (if any)
4160
+ csv_external_df, csv_X_external,csv_y_external = None,None,None
4161
+ if self.args.csv_test != '':
4162
+ csv_external_df,csv_X_external,csv_y_external = load_database(self,self.args.csv_test,'predict',external_test=True)
4163
+ if (
4164
+ model_data['type'].lower() == 'clas'
4165
+ and csv_y_external is not None
4166
+ and 'class_mapping_reverse' in model_data
4167
+ ):
4168
+ class_mapping_reverse = _parse_class_mapping_reverse(model_data['class_mapping_reverse'])
4169
+ if class_mapping_reverse:
4170
+ class_mapping = {str(label): code for code, label in class_mapping_reverse.items()}
4171
+ csv_y_external = csv_y_external.map(
4172
+ lambda value: class_mapping.get(str(value), value)
4173
+ ).astype(int)
4174
+ try:
4175
+ csv_X_external = csv_X_external[model_data['X_descriptors']]
4176
+ except KeyError:
4177
+ # this might fail if the initial categorical variables have not been transformed
4178
+ try:
4179
+ self.args.log.write(f"\n x There are missing descriptors in the test set! Looking for categorical variables converted from CURATE")
4180
+ csv_X_external = categorical_transform(self,csv_X_external,'predict')
4181
+ csv_X_external = csv_X_external[model_data['X_descriptors']]
4182
+ self.args.log.write(f" o The missing descriptors were successfully created")
4183
+ except KeyError:
4184
+ self.args.log.write(f" x There are still missing descriptors in the test set! The following descriptors are needed: {model_data['X_descriptors']}")
4185
+ self.args.log.finalize()
4186
+ sys.exit()
4187
+
4188
+ # split tests
4189
+ Xy_data = prepare_sets(self,csv_df,csv_X,csv_y,test_points,model_data['names'],csv_external_df,csv_X_external,csv_y_external,BO_opt=False)
4190
+
4191
+ # print information of loaded database
4192
+ params_name = os.path.basename(params_dir)
4193
+ if print_load:
4194
+ _ = load_print(self,params_name,suffix,model_data,Xy_data)
4195
+
4196
+ return Xy_data, model_data, suffix_title
4197
+
4198
+
4199
+ def prepare_sets(self,csv_df,csv_X,csv_y,test_points,column_names,csv_external_df,csv_X_external,csv_y_external,BO_opt=False):
4200
+ '''
4201
+ Standardizes and separate test set
4202
+ '''
4203
+
4204
+ # test_points stays None when csv_test is set and auto_test doesn't force a test_set (e.g.
4205
+ # --csv_test with --auto_test False); Xy_split() expects a list, an empty one meaning "no
4206
+ # test points carved out of the training data"
4207
+ if test_points is None:
4208
+ test_points = []
4209
+
4210
+ X_scaled_df,X_scaled_external_df = scale_df(csv_X,csv_X_external)
4211
+
4212
+ # separate test set and save it in the Xy data
4213
+ if BO_opt:
4214
+ # --csv_test is for getting predictions on new/external points, which may or may not
4215
+ # have known y values (e.g. compounds not yet made) - it is NOT a substitute for the
4216
+ # internal test split the score is calibrated on, so it must not suppress it. ROBERT
4217
+ # still carves its own internal test set as usual; the external file is used
4218
+ # separately, on top of that, wherever csv_test is actually consumed
4219
+ if self.args.auto_test:
4220
+ # test_set == 0 is treated as a deliberate "no test set" choice (train on 100% of
4221
+ # the data as train+valid), not a value that needs the safety net - only small,
4222
+ # possibly-accidental nonzero values get raised to 0.2 (--auto_test False bypasses
4223
+ # this entirely, but explicit 0 no longer needs it just for this specific case)
4224
+ if 0 < self.args.test_set < 0.2:
4225
+ user_test_set = self.args.test_set
4226
+ self.args.test_set = 0.2
4227
+ self.args.log.write(f'\nx WARNING! The test_set option was set to {user_test_set}, this value will be raised to 0.2 to include a meaningful amount of points in the test set. You can bypass this option and include less test points with "--auto_test False".')
4228
+
4229
+ if self.args.test_set > 0:
4230
+ try:
4231
+ test_points = test_select(self,X_scaled_df,csv_y)
4232
+ except TypeError:
4233
+ self.args.log.write(f' x The data split process failed! This is probably due to using strings/words as values (use --curate to curate the data first)')
4234
+ sys.exit()
4235
+
4236
+ if self.args.checkml:
4237
+ text_method = 'Before the CheckML evaluation, '
4238
+ else: # for GENERATE
4239
+ text_method = 'Before hyperoptimization, '
4240
+ # case-insensitive: --split may arrive as "RND"/"rnd", and classification sets
4241
+ # 'STRATIFIED' in upper case (see test_select())
4242
+ split_mode = str(self.args.split).lower()
4243
+ text_split = {
4244
+ # (EVEN's text is checked verbatim in test_2generate.py)
4245
+ 'even': ', using an even distribution of data points across the range of y values.',
4246
+ 'rnd': ', using a random distribution of data points.',
4247
+ 'stratified': ', using a stratified distribution of data points.',
4248
+ 'kn': ', using k-means clustering to keep the most diverse points in the training set.',
4249
+ }.get(split_mode, '.')
4250
+ if split_mode in ['extra_q1','extra_q5']:
4251
+ # EXTRA_Q1/Q5 always take a fixed 20% at one end of the y range, regardless of test_set
4252
+ zone = 'lowest' if split_mode == 'extra_q1' else 'highest'
4253
+ self.args.log.write(f'\no {text_method}the 20% of the data with the {zone} y values was separated as test set.')
4254
+ else:
4255
+ self.args.log.write(f'\no {text_method}{int(self.args.test_set*100)}% of the data (or 4 points at least) was separated as test set{text_split}')
4256
+
4257
+ # load predefined sets and save the info in Xy data
4258
+ Xy_data = Xy_split(csv_df,csv_X,X_scaled_df,csv_y,csv_external_df,csv_X_external,X_scaled_external_df,csv_y_external,test_points,column_names)
4259
+
4260
+ # also store the descriptors used (the labels disappear after test_select() )
4261
+ Xy_data['X_descriptors'] = csv_X.columns.tolist()
4262
+
4263
+ return Xy_data
4264
+
4265
+
4266
+ def load_dfs(self,folder_model,module,sanity_check=False,print_info=True):
4267
+ '''
4268
+ Loads the parameters and Xy databases from the GENERATE folder as dataframes
4269
+ '''
4270
+
4271
+ if os.getcwd() in f"{folder_model}":
4272
+ path_db = folder_model
4273
+ else:
4274
+ path_db = f"{Path(os.getcwd()).joinpath(folder_model)}"
4275
+ if os.path.exists(path_db):
4276
+ csv_files = glob.glob(f'{Path(path_db).joinpath("*.csv")}')
4277
+ csv_files.sort(key=lambda f: f.endswith('_db.csv')) # sort the database file to be the last one, depending on the OS was taking first the dabatase and then the parameters
4278
+ for csv_file in csv_files:
4279
+ if csv_file.endswith('_db.csv'):
4280
+ if not sanity_check:
4281
+ csv_df,csv_X,csv_y = load_database(self,csv_file,module,print_info=print_info)
4282
+ csv_name = csv_file
4283
+ else:
4284
+ csv_df,csv_X,csv_y = pd.DataFrame(),pd.DataFrame(),pd.DataFrame()
4285
+ # convert df to dict, then adjust params to a valid format
4286
+ model_data = load_params(self,csv_file)
4287
+ else:
4288
+ self.args.log.write(f"\nx The folder with the model and database ({path_db}) does not exist! Did you use the destination=PATH option in the other modules?")
4289
+ sys.exit()
4290
+
4291
+ return csv_df,csv_X,csv_y,model_data,csv_name
4292
+
4293
+
4294
+ def load_params(self,path_csv):
4295
+ '''
4296
+ Load parameters from a CSV and adjust the format
4297
+ '''
4298
+
4299
+ PFI_df = pd.read_csv(path_csv, encoding='utf-8')
4300
+ PFI_dict = pd_to_dict(PFI_df)
4301
+ PFI_dict = dict_formating(PFI_dict)
4302
+ PFI_dict['params'] = model_adjust_params(self, PFI_dict['model'], PFI_dict['params'])
4303
+
4304
+ return PFI_dict
4305
+
4306
+
4307
+ def load_print(self,params_name,suffix,model_data,Xy_data):
4308
+ '''
4309
+ Print information of the database loaded and type of model used
4310
+ '''
4311
+
4312
+ if '.csv' in params_name:
4313
+ params_name = params_name.split('.csv')[0]
4314
+ txt_load = f'\no ML model {params_name} {suffix} and Xy database were loaded, including:'
4315
+ txt_load += f'\n - Target value: {model_data["y"]}'
4316
+ txt_load += f'\n - Names: {model_data["names"]}'
4317
+ txt_load += f'\n - Model: {model_data["model"]}'
4318
+ txt_load += f'\n - k-fold CV: {model_data["kfold"]}'
4319
+ txt_load += f'\n - Repetitions CV: {model_data["repeat_kfolds"]}'
4320
+ txt_load += f'\n - Descriptors: {model_data["X_descriptors"]}'
4321
+ txt_load += f'\n - Training points: {len(Xy_data["y_train"])}'
4322
+ txt_load += f'\n - Test points: {len(Xy_data["y_test"])}'
4323
+ if 'X_external' in Xy_data:
4324
+ txt_load += f'\n - External test points: {len(Xy_data["X_external"])}'
4325
+ self.args.log.write(txt_load)
4326
+
4327
+
4328
+ def pd_to_dict(PFI_df):
4329
+ PFI_df_dict = {}
4330
+ for column in PFI_df.columns:
4331
+ PFI_df_dict[column] = PFI_df[column][0]
4332
+ return PFI_df_dict
4333
+
4334
+
4335
+ def print_pfi(self,params_dir):
4336
+ if 'No_PFI' in params_dir:
4337
+ self.args.log.write('\n\n------- Starting model with all variables (No PFI) -------')
4338
+ else:
4339
+ self.args.log.write('\n\n------- Starting model with PFI filter (only important descriptors used) -------')
4340
+
4341
+
4342
+ def get_graph_style():
4343
+ """
4344
+ Retrieves the graph style for regression plots
4345
+ """
4346
+
4347
+ graph_style = {'color_train' : 'b',
4348
+ 'color_valid' : 'orange',
4349
+ 'color_test' : 'r',
4350
+ 'dot_size' : 50,
4351
+ 'alpha' : 1 # from 0 (transparent) to 1 (opaque)
4352
+ }
4353
+
4354
+ return graph_style
4355
+
4356
+
4357
+ def pearson_map(self,csv_df_pearson,module,params_dir=None,suffix_title=None):
4358
+ '''
4359
+ Creates Pearson heatmap
4360
+ '''
4361
+
4362
+ importlib.reload(plt) # needed to avoid threading issues
4363
+ if module.lower() == 'curate': # only represent the final descriptors in CURATE
4364
+ # errors='ignore': an ignored column might not exist in the database
4365
+ csv_df_pearson = csv_df_pearson.drop([self.args.y] + self.args.ignore, axis=1, errors='ignore')
4366
+
4367
+ # numeric_only=True: in CHECKML mode, CURATE's categorical_transform() is skipped (only
4368
+ # this heatmap is drawn), so csv_df_pearson can still contain raw non-numeric descriptor
4369
+ # columns - .corr() raises ValueError outright on those instead of just excluding them
4370
+ corr_matrix = csv_df_pearson.corr(numeric_only=True)
4371
+ mask = np.zeros_like(corr_matrix, dtype=bool)
4372
+ mask[np.triu_indices_from(mask)]= True
4373
+
4374
+ # with only the lower triangle unmasked, the first row (only cell = the diagonal, itself
4375
+ # masked) and the last column (would only be unmasked by a row below the last one, which
4376
+ # doesn't exist) are always entirely blank. bbox_inches='tight' does not crop them away
4377
+ # (they are still valid, if invisible, axes content), which left a large empty gap above
4378
+ # the heatmap - most noticeable with very few descriptors, where it could leave just a
4379
+ # single visible cell. Trimming them keeps every remaining cell meaningful. This is only
4380
+ # for the plot - the function still returns the full, untrimmed corr_matrix, since callers
4381
+ # (e.g. pearson_map_predict()'s correlation-warning scan) index it by original position and
4382
+ # trimming would silently shift some pairs onto the (skipped) diagonal
4383
+ if len(corr_matrix.columns) > 1:
4384
+ corr_matrix_plot = corr_matrix.iloc[1:, :-1]
4385
+ mask_plot = mask[1:, :-1]
4386
+ else:
4387
+ corr_matrix_plot = corr_matrix
4388
+ mask_plot = mask
4389
+
4390
+ # no representatoins when there are more than 30 descriptors
4391
+ if len(csv_df_pearson.columns) > 30:
4392
+ disable_plot = True
4393
+ else:
4394
+ disable_plot = False
4395
+ _, ax = plt.subplots(figsize=(7.45,6))
4396
+ size_title = 14
4397
+ size_font = 14-2*((len(csv_df_pearson.columns)/5))
4398
+
4399
+ if disable_plot:
4400
+ if module.lower() == 'curate':
4401
+ self.args.log.write(f'\nx The Pearson heatmap was not generated because the number of features and the y value ({len(csv_df_pearson.columns)}) is higher than 30.')
4402
+ if module.lower() == 'predict':
4403
+ self.args.log.write(f'\n x The Pearson heatmap was not generated because the number of features and the y value ({len(csv_df_pearson.columns)}) is higher than 30.')
4404
+
4405
+ else:
4406
+ sb.set(font_scale=1.2, style='ticks')
4407
+
4408
+ _ = sb.heatmap(corr_matrix_plot,
4409
+ mask = mask_plot,
4410
+ square = True,
4411
+ linewidths = .5,
4412
+ cmap = 'coolwarm',
4413
+ cbar = False,
4414
+ cbar_kws = {'shrink': .4,
4415
+ 'ticks' : [-1, -.5, 0, 0.5, 1]},
4416
+ vmin = -1,
4417
+ vmax = 1,
4418
+ annot = True,
4419
+ annot_kws = {'size': size_font})
4420
+
4421
+ plt.tick_params(labelsize=size_font)
4422
+ # Explicitly align tick positions with the full correlation matrix.
4423
+ # Newer matplotlib/seaborn combinations can auto-reduce the locator
4424
+ # ticks, which then makes set_*ticklabels fail if all labels are passed.
4425
+ tick_positions_y = np.arange(len(corr_matrix_plot.index)) + 0.5
4426
+ tick_positions_x = np.arange(len(corr_matrix_plot.columns)) + 0.5
4427
+ ax.set_yticks(tick_positions_y)
4428
+ ax.set_xticks(tick_positions_x)
4429
+ ax.set_yticklabels(corr_matrix_plot.index, rotation=0)
4430
+ ax.set_xticklabels(corr_matrix_plot.columns)
4431
+
4432
+ title_fig = 'Pearson\'s r heatmap'
4433
+ if module.lower() == 'predict':
4434
+ # prefer the caller-provided suffix_title (always correct, including per-model
4435
+ # folders like GENERATE/All_models/No_PFI/RF, whose basename is the model name,
4436
+ # not "No_PFI"/"PFI") - fall back to guessing from the folder name only if it
4437
+ # wasn't given
4438
+ if suffix_title is None:
4439
+ if os.path.basename(Path(params_dir)) == 'No_PFI':
4440
+ suffix_title = 'No_PFI'
4441
+ elif os.path.basename(Path(params_dir)) == 'PFI':
4442
+ suffix_title = 'PFI'
4443
+ title_fig += f'_{suffix_title}'
4444
+
4445
+ plt.title(title_fig, y=1.04, fontsize = size_title, fontweight="bold")
4446
+ sb.set_style({'xtick.bottom': True}, {'ytick.left': True})
4447
+
4448
+ if module.lower() == 'curate':
4449
+ heatmap_name = 'Pearson_heatmap.png'
4450
+ elif module.lower() == 'predict':
4451
+ heatmap_name = f'Pearson_heatmap_{suffix_title}.png'
4452
+
4453
+ heatmap_path = self.args.destination.joinpath(heatmap_name)
4454
+ plt.savefig(f'{heatmap_path}', dpi=300, bbox_inches='tight')
4455
+ plt.close()
4456
+
4457
+ path_reduced = '/'.join(f'{heatmap_path}'.replace('\\','/').split('/')[-2:])
4458
+ if module.lower() == 'curate':
4459
+ self.args.log.write(f'\no The Pearson heatmap was stored in {path_reduced}.')
4460
+ elif module.lower() == 'predict':
4461
+ self.args.log.write(f'\n o The Pearson heatmap was stored in {path_reduced}.')
4462
+
4463
+ return corr_matrix
4464
+
4465
+
4466
+ def plot_metrics(model_data,suffix_title,verify_metrics,verify_results,show_title=True):
4467
+ '''
4468
+ Creates a plot with the results of the flawed models in VERIFY.
4469
+ show_title=False skips the in-image title - used for the small (270px-wide) Section B
4470
+ thumbnail, where the container height crops it anyway (see print_img_tag()) and the
4471
+ surrounding item text already says what the plot shows
4472
+ '''
4473
+
4474
+ importlib.reload(plt) # needed to avoid threading issues
4475
+ sb.reset_defaults()
4476
+ sb.set(style="ticks")
4477
+ _, ax = plt.subplots(figsize=(7.45,6))
4478
+
4479
+ # define names
4480
+ csv_name = os.path.basename(model_data['model']).split('_db.csv')[0]
4481
+ base_csv_name = f'VERIFY/{csv_name}'
4482
+ base_csv_path = f"{Path(os.getcwd()).joinpath(base_csv_name)}"
4483
+ path_n_suffix = f'{base_csv_path}_{suffix_title}'
4484
+
4485
+ # unscored MVL baseline bar (see verify.mvl_baseline_test()), drawn apart from the tests
4486
+ baseline = verify_metrics.get('baseline')
4487
+ all_vals = list(verify_metrics['metrics']) + ([baseline['value']] if baseline else [])
4488
+
4489
+ # axis limits
4490
+ max_val = max(all_vals)
4491
+ min_val = min(all_vals)
4492
+ range_vals = np.abs(max_val - min_val)
4493
+ if verify_results['error_type'].lower() in ['mae','rmse']:
4494
+ max_lim = 1.2*max_val
4495
+ min_lim = 0
4496
+ else:
4497
+ max_lim = max_val + (0.2*range_vals)
4498
+ min_lim = min_val - (0.1*range_vals)
4499
+ plt.ylim(min_lim, max_lim)
4500
+ plt.ylim(min_lim, max_lim)
4501
+
4502
+ # adjust number of significative numbers shown
4503
+ ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
4504
+
4505
+ width_bar = 0.55
4506
+ label_count = 0
4507
+ for test_metric,test_name,test_color in zip(verify_metrics['metrics'],verify_metrics['test_names'],verify_metrics['colors']):
4508
+ rects = ax.bar(test_name, test_metric, label=test_name,
4509
+ width=width_bar, linewidth=1, edgecolor='k',
4510
+ color=test_color, zorder=2)
4511
+ # plot whether the tests pass or fail
4512
+ if test_name != 'Model':
4513
+ if test_metric >= 0:
4514
+ offset_txt = test_metric+(0.05*range_vals)
4515
+ else:
4516
+ offset_txt = test_metric-(0.05*range_vals)
4517
+ if test_color == '#1f77b4':
4518
+ txt_bar = 'pass'
4519
+ elif test_color == '#cd5c5c':
4520
+ txt_bar = 'fail'
4521
+ elif test_color == '#c5c57d':
4522
+ txt_bar = 'unclear'
4523
+ elif test_color == '#a9a9a9':
4524
+ txt_bar = 'N/A'
4525
+ ax.text(label_count, offset_txt, txt_bar, color=test_color,
4526
+ fontstyle='italic', horizontalalignment='center')
4527
+ label_count += 1
4528
+ n_scored_bars = label_count
4529
+
4530
+ if baseline:
4531
+ # dotted divider: the MVL bar isn't a flawed-model test and isn't scored. Its reference
4532
+ # is the model's own score +-band (shaded), not the dashed pass/unclear limits
4533
+ ax.axvline(n_scored_bars - 0.5, color='#7f7f7f', ls=':', linewidth=1.5, zorder=1)
4534
+ cv_score = verify_metrics['metrics'][0]
4535
+ band = baseline['band']*abs(cv_score)
4536
+ ax.fill_between([n_scored_bars - 0.42, n_scored_bars + 0.42], cv_score - band, cv_score + band,
4537
+ color='#7f7f7f', alpha=0.18, linewidth=0, zorder=1)
4538
+ ax.hlines(cv_score, n_scored_bars - 0.42, n_scored_bars + 0.42, colors='#7f7f7f',
4539
+ linestyles='-', linewidth=1, zorder=1)
4540
+ ax.bar(baseline['name'], baseline['value'], width=width_bar, linewidth=1, edgecolor='k',
4541
+ color=baseline['color'], hatch='//' if baseline['label'] == 'N/A' else None, zorder=2)
4542
+ base_val = baseline['value']
4543
+ base_offset = base_val + (0.05*range_vals) if base_val >= 0 else base_val - (0.05*range_vals)
4544
+ ax.text(n_scored_bars, max(base_offset, cv_score + band + 0.03*range_vals) if base_val >= 0 else base_offset,
4545
+ baseline['label'], color=baseline['color'], fontstyle='italic', horizontalalignment='center',
4546
+ verticalalignment='bottom', linespacing=1.0)
4547
+
4548
+ # Set tick sizes
4549
+ plt.xticks(fontsize=14)
4550
+ plt.yticks(fontsize=14)
4551
+
4552
+ # title and labels of the axis
4553
+ plt.ylabel(f'{verify_results["error_type"].upper()}', fontsize=14)
4554
+
4555
+ if show_title:
4556
+ plt.text(0.5, 1.08, f'VERIFY tests of {os.path.basename(path_n_suffix)}', horizontalalignment='center',
4557
+ fontsize=14, fontweight='bold', transform = ax.transAxes)
4558
+
4559
+ # add threshold line and arrow indicating passed test direction
4560
+ arrow_length = np.abs(max_lim-min_lim)/11
4561
+
4562
+ if verify_results['error_type'].lower() in ['mae','rmse']:
4563
+ thres_line = verify_metrics['higher_thres']
4564
+ unclear_thres_line = verify_metrics['unclear_higher_thres']
4565
+ else:
4566
+ thres_line = verify_metrics['lower_thres']
4567
+ unclear_thres_line = verify_metrics['unclear_lower_thres']
4568
+ arrow_length = -arrow_length
4569
+
4570
+ width = 2
4571
+ if baseline:
4572
+ # limits only over the scored tests (from between Model/y_mean to the MVL divider)
4573
+ thres = ax.hlines(thres_line, 0.5, n_scored_bars - 0.5, color='black', ls='--', label='thres', zorder=0)
4574
+ thres = ax.hlines(unclear_thres_line, 0.5, n_scored_bars - 0.5, color='black', ls='--', label='thres', zorder=0)
4575
+ ax.set_xlim(-0.5, n_scored_bars + 0.5)
4576
+ else:
4577
+ xmin = 0.237
4578
+ thres = ax.axhline(thres_line,xmin=xmin, color='black',ls='--', label='thres', zorder=0)
4579
+ thres = ax.axhline(unclear_thres_line,xmin=xmin, color='black',ls='--', label='thres', zorder=0)
4580
+
4581
+ x_arrow = 0.5
4582
+ style = mpatches.ArrowStyle('simple', head_length=4.5*width, head_width=3.5*width, tail_width=width)
4583
+ arrow = mpatches.FancyArrowPatch((x_arrow, thres_line), (x_arrow, thres_line+arrow_length),
4584
+ arrowstyle=style, color='k') # (x1,y1), (x2,y2) vector direction
4585
+ ax.add_patch(arrow)
4586
+
4587
+ # invisible "dummy" arrows to make the graph wider so the real arrows fit in the right place
4588
+ ax.arrow(x_arrow, thres_line, 0, 0, width=0, fc='k', ec='k') # x,y,dx,dy format
4589
+
4590
+ # legend with the "pass test" arrow
4591
+ def make_legend_arrow(legend, orig_handle,
4592
+ xdescent, ydescent,
4593
+ width, height, fontsize):
4594
+ p = mpatches.FancyArrow(0, 0.5*height, width, 0, width=1.5, length_includes_head=True, head_width=0.58*height )
4595
+ return p
4596
+
4597
+ arrow = plt.arrow(0, 0, 0, 0, label='arrow', width=0, fc='k', ec='k') # arrow for the legend
4598
+ plt.figlegend([thres,arrow], [f'Limits: {thres_line:.2} (pass), {unclear_thres_line:.2} (unclear)','Pass test'], handler_map={mpatches.FancyArrow : HandlerPatch(patch_func=make_legend_arrow),},
4599
+ loc="lower center", ncol=2, bbox_to_anchor=(0.5, -0.05),
4600
+ fancybox=True, shadow=True, fontsize=14)
4601
+
4602
+ # Add gridlines
4603
+ ax.grid(linestyle='--', linewidth=1)
4604
+
4605
+ # save plot
4606
+ verify_plot_file = f'{os.path.dirname(path_n_suffix)}/VERIFY_tests_{os.path.basename(path_n_suffix)}.png'
4607
+ plt.savefig(verify_plot_file, dpi=300, bbox_inches='tight')
4608
+ plt.close()
4609
+
4610
+ path_reduced = '/'.join(f'{verify_plot_file}'.replace('\\','/').split('/')[-2:])
4611
+ print_ver = f"\n o VERIFY plot saved in {path_reduced}"
4612
+
4613
+ return print_ver
4614
+
4615
+
4616
+ _PICKLED_PARAM_KEY = '__robert_pickled_param__'
4617
+
4618
+
4619
+ def _is_json_native(value):
4620
+ '''
4621
+ True if JSON stores the value exactly as it is (str/int/float/bool/None, and lists or
4622
+ str-keyed dicts of those). Tuples, dicts with non-string keys (i.e. class_weight={0: 1, 1: 3})
4623
+ and objects (kernels, base estimators) don't survive a JSON round trip unchanged.
4624
+ '''
4625
+
4626
+ if value is None or type(value) in (str, int, float, bool):
4627
+ return True
4628
+ if type(value) is list:
4629
+ return all(_is_json_native(val) for val in value)
4630
+ if type(value) is dict:
4631
+ return all(type(key) is str for key in value) and all(_is_json_native(val) for val in value.values())
4632
+ return False
4633
+
4634
+
4635
+ def _to_builtin(value):
4636
+ '''
4637
+ numpy scalars/arrays (common in hyperparameters from grid searches or optuna) to plain
4638
+ Python types - otherwise json.dumps(default=str) saves i.e. np.int64(3) as the text '3',
4639
+ which scikit-learn then rejects (max_depth must be an int, got '3')
4640
+ '''
4641
+
4642
+ if isinstance(value, np.generic):
4643
+ return value.item()
4644
+ if isinstance(value, np.ndarray):
4645
+ return value.tolist()
4646
+ return value
4647
+
4648
+
4649
+ def serialize_model_params(params):
4650
+ '''
4651
+ Text version of a model's hyperparameters, saved in the GENERATE CSV and read back by
4652
+ VERIFY/PREDICT/REPORT (see deserialize_model_params()). Values JSON can't store exactly
4653
+ (objects such as GP kernels or base estimators, tuples, dicts with numeric keys such as
4654
+ class_weight) are pickled and base64-encoded so they come back exactly as they were.
4655
+ '''
4656
+
4657
+ import base64
4658
+ import pickle
4659
+
4660
+ serializable = {}
4661
+ for param, value in params.items():
4662
+ value = _to_builtin(value)
4663
+ if _is_json_native(value):
4664
+ serializable[param] = value
4665
+ else:
4666
+ serializable[param] = {_PICKLED_PARAM_KEY: base64.b64encode(pickle.dumps(value)).decode('ascii')}
4667
+ return json.dumps(serializable)
4668
+
4669
+
4670
+ def _restore_numeric_keys(value):
4671
+ '''
4672
+ Params saved before serialize_model_params() existed stored dict keys as text (JSON), so
4673
+ class_weight={0: 1, 1: 3} came back as {"0": 1, "1": 3} and scikit-learn failed with
4674
+ "The classes, [0, 1], are not in class_weight". Numeric-looking keys are converted back
4675
+ to int/float, and any other key (i.e. a class name) is kept as it is.
4676
+ '''
4677
+
4678
+ if not isinstance(value, dict):
4679
+ return value
4680
+ restored = {}
4681
+ for key, val in value.items():
4682
+ if isinstance(key, str):
4683
+ for cast in (int, float):
4684
+ try:
4685
+ key = cast(key)
4686
+ break
4687
+ except ValueError:
4688
+ pass
4689
+ restored[key] = val
4690
+ return restored
4691
+
4692
+
4693
+ def deserialize_model_params(params):
4694
+ '''
4695
+ Inverse of serialize_model_params(): accepts the saved text (JSON, or the older
4696
+ Python-literal format) or an already-parsed dict, and returns the hyperparameters with
4697
+ their original Python types.
4698
+ '''
4699
+
4700
+ import base64
4701
+ import pickle
4702
+
4703
+ if isinstance(params, str):
4704
+ try:
4705
+ params = json.loads(params)
4706
+ except (json.JSONDecodeError, TypeError):
4707
+ params = ast.literal_eval(params)
4708
+ if not isinstance(params, dict):
4709
+ return params
4710
+
4711
+ restored = {}
4712
+ for param, value in params.items():
4713
+ if isinstance(value, dict) and set(value) == {_PICKLED_PARAM_KEY}:
4714
+ restored[param] = pickle.loads(base64.b64decode(value[_PICKLED_PARAM_KEY]))
4715
+ else:
4716
+ restored[param] = _restore_numeric_keys(value)
4717
+ return restored
4718
+
4719
+
4720
+ def parse_param_value(value):
4721
+ '''
4722
+ Recover the Python type of a hyperparameter typed in a CSV (CHECKML's --model_params):
4723
+ numbers, lists, tuples, dicts and quoted strings via ast.literal_eval, plus the spellings
4724
+ literal_eval doesn't understand - empty cells and none/null -> None, true/false in any case
4725
+ (Excel writes TRUE/FALSE) -> bool. Anything else is kept as a plain string (i.e. 'gini').
4726
+ '''
4727
+
4728
+ if value is None or (isinstance(value, float) and np.isnan(value)):
4729
+ return None
4730
+ text = str(value).strip()
4731
+ if text.lower() in ('', 'none', 'null', 'nan'):
4732
+ return None
4733
+ if text.lower() in ('true', 'false'):
4734
+ return text.lower() == 'true'
4735
+ try:
4736
+ return ast.literal_eval(text)
4737
+ except (ValueError, SyntaxError):
4738
+ return text
4739
+
4740
+
4741
+ def dict_formating(dict_csv):
4742
+ '''
4743
+ Adapt format of dictionaries that come from dataframes loaded from CSV
4744
+ '''
4745
+
4746
+ import json
4747
+
4748
+ if 'X_descriptors' in dict_csv:
4749
+ # Try JSON first (new format), fall back to ast.literal_eval (old format)
4750
+ try:
4751
+ dict_csv['X_descriptors'] = json.loads(dict_csv['X_descriptors'])
4752
+ except (json.JSONDecodeError, TypeError):
4753
+ dict_csv['X_descriptors'] = ast.literal_eval(dict_csv['X_descriptors'])
4754
+
4755
+ if 'params' in dict_csv:
4756
+ dict_csv['params'] = deserialize_model_params(dict_csv['params'])
4757
+
4758
+ if 'class_mapping_reverse' in dict_csv:
4759
+ dict_csv['class_mapping_reverse'] = _parse_class_mapping_reverse(
4760
+ dict_csv['class_mapping_reverse']
4761
+ )
4762
+
4763
+ return dict_csv