robert 2.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (261) hide show
  1. robert/__init__.py +9 -0
  2. robert/__main__.py +20 -0
  3. robert/_version.py +3 -0
  4. robert/api.py +646 -0
  5. robert/aqme.py +280 -0
  6. robert/argument_parser.py +98 -0
  7. robert/checkml.py +433 -0
  8. robert/checkml_score.py +50 -0
  9. robert/curate.py +217 -0
  10. robert/evaluate_bot_retrieval.py +125 -0
  11. robert/evaluate_bot_support.py +102 -0
  12. robert/evaluate_workflow_summaries.py +87 -0
  13. robert/export_bot_docs_knowledge.py +1632 -0
  14. robert/generate.py +249 -0
  15. robert/generate_utils.py +311 -0
  16. robert/gui_easyrob/__init__.py +0 -0
  17. robert/gui_easyrob/assets/gif_easyrob.gif +0 -0
  18. robert/gui_easyrob/bot/__init__.py +47 -0
  19. robert/gui_easyrob/bot/answer_metadata.py +198 -0
  20. robert/gui_easyrob/bot/bot_context.py +679 -0
  21. robert/gui_easyrob/bot/bot_engine.py +1100 -0
  22. robert/gui_easyrob/bot/bot_panel.py +1231 -0
  23. robert/gui_easyrob/bot/bot_rag.py +1178 -0
  24. robert/gui_easyrob/bot/bot_window.py +39 -0
  25. robert/gui_easyrob/bot/bot_worker.py +149 -0
  26. robert/gui_easyrob/bot/credential_store.py +143 -0
  27. robert/gui_easyrob/bot/error_parser.py +105 -0
  28. robert/gui_easyrob/bot/evidence_policy.py +164 -0
  29. robert/gui_easyrob/bot/heuristics.py +859 -0
  30. robert/gui_easyrob/bot/icons.py +56 -0
  31. robert/gui_easyrob/bot/input_csv_audit.py +212 -0
  32. robert/gui_easyrob/bot/knowledge/aqme_context.json +5907 -0
  33. robert/gui_easyrob/bot/knowledge/robert_context.json +4817 -0
  34. robert/gui_easyrob/bot/knowledge/ui_context.json +8293 -0
  35. robert/gui_easyrob/bot/knowledge_schema.py +1252 -0
  36. robert/gui_easyrob/bot/knowledge_sources/aqme_user_guidance.json +442 -0
  37. robert/gui_easyrob/bot/knowledge_sources/coverage_manifest.json +95 -0
  38. robert/gui_easyrob/bot/knowledge_sources/robert_user_guidance.json +471 -0
  39. robert/gui_easyrob/bot/knowledge_sources/ui_user_guidance.json +1312 -0
  40. robert/gui_easyrob/bot/llm_providers.py +1573 -0
  41. robert/gui_easyrob/bot/online_docs.py +105 -0
  42. robert/gui_easyrob/bot/prompt_policy.py +575 -0
  43. robert/gui_easyrob/bot/question_intent.py +562 -0
  44. robert/gui_easyrob/bot/response_quality.py +104 -0
  45. robert/gui_easyrob/bot/result_insights.py +225 -0
  46. robert/gui_easyrob/bot/token_usage.py +75 -0
  47. robert/gui_easyrob/bot/workflow_results.py +1396 -0
  48. robert/gui_easyrob/checkml_launcher.py +15 -0
  49. robert/gui_easyrob/easyrob.py +29 -0
  50. robert/gui_easyrob/easyrob_launcher.py +113 -0
  51. robert/gui_easyrob/main/__init__.py +9 -0
  52. robert/gui_easyrob/main/window.py +5152 -0
  53. robert/gui_easyrob/result_navigation.py +14 -0
  54. robert/gui_easyrob/tabs/__init__.py +23 -0
  55. robert/gui_easyrob/tabs/advanced_options.py +370 -0
  56. robert/gui_easyrob/tabs/aqme.py +1234 -0
  57. robert/gui_easyrob/tabs/checkml.py +898 -0
  58. robert/gui_easyrob/tabs/images.py +427 -0
  59. robert/gui_easyrob/tabs/interactive_predictions.py +555 -0
  60. robert/gui_easyrob/tabs/molssi.py +447 -0
  61. robert/gui_easyrob/tabs/predictions.py +484 -0
  62. robert/gui_easyrob/tabs/result_catalog.py +170 -0
  63. robert/gui_easyrob/tabs/results.py +490 -0
  64. robert/gui_easyrob/tabs/results_workspace.py +120 -0
  65. robert/gui_easyrob/test_bot_input_csv_audit.py +152 -0
  66. robert/gui_easyrob/test_bot_question_routing.py +383 -0
  67. robert/gui_easyrob/test_bot_result_analysis.py +356 -0
  68. robert/gui_easyrob/test_bot_retrieval_evaluation.py +110 -0
  69. robert/gui_easyrob/test_bot_ui_integration.py +278 -0
  70. robert/gui_easyrob/test_checkml_app_mode.py +124 -0
  71. robert/gui_easyrob/test_checkml_completion.py +57 -0
  72. robert/gui_easyrob/test_checkml_defaults.py +37 -0
  73. robert/gui_easyrob/test_checkml_result_summary.py +113 -0
  74. robert/gui_easyrob/test_checkml_web_mode.py +57 -0
  75. robert/gui_easyrob/test_dialog_layout.py +33 -0
  76. robert/gui_easyrob/test_gui_bot_regressions.py +320 -0
  77. robert/gui_easyrob/test_molssi_auto.py +569 -0
  78. robert/gui_easyrob/test_tutorial_view.py +215 -0
  79. robert/gui_easyrob/tutorials/check_model.md +25 -0
  80. robert/gui_easyrob/tutorials/chemdraw.md +49 -0
  81. robert/gui_easyrob/tutorials/csv.md +53 -0
  82. robert/gui_easyrob/tutorials/descriptors.md +21 -0
  83. robert/gui_easyrob/tutorials/overview.md +65 -0
  84. robert/gui_easyrob/tutorials/predictions.md +25 -0
  85. robert/gui_easyrob/tutorials/robbot.md +29 -0
  86. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_1.png +0 -0
  87. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_2.png +0 -0
  88. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_3.png +0 -0
  89. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_4.png +0 -0
  90. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_5.png +0 -0
  91. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_6.png +0 -0
  92. robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_7.png +0 -0
  93. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_1.png +0 -0
  94. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_10.png +0 -0
  95. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_11.png +0 -0
  96. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_12.png +0 -0
  97. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_13.png +0 -0
  98. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_2.png +0 -0
  99. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_3.png +0 -0
  100. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_4.png +0 -0
  101. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_5.png +0 -0
  102. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_6.png +0 -0
  103. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_7.png +0 -0
  104. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_8.png +0 -0
  105. robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_9.png +0 -0
  106. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1.png +0 -0
  107. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_1.png +0 -0
  108. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_2.png +0 -0
  109. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_3.png +0 -0
  110. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_4.png +0 -0
  111. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_5.png +0 -0
  112. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_2.png +0 -0
  113. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_3.png +0 -0
  114. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_4.png +0 -0
  115. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_5.png +0 -0
  116. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_6.png +0 -0
  117. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_7.png +0 -0
  118. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_8.png +0 -0
  119. robert/gui_easyrob/tutorials/tutorial_images/csv/csv_9.png +0 -0
  120. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_1.png +0 -0
  121. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_2.png +0 -0
  122. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_3.png +0 -0
  123. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_4.png +0 -0
  124. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_5.png +0 -0
  125. robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_6.png +0 -0
  126. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1.png +0 -0
  127. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_1.png +0 -0
  128. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_2.png +0 -0
  129. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_3.png +0 -0
  130. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_4.png +0 -0
  131. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_5.png +0 -0
  132. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_6.png +0 -0
  133. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_7.png +0 -0
  134. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_8.png +0 -0
  135. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_2.png +0 -0
  136. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_3.png +0 -0
  137. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_4.png +0 -0
  138. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5.png +0 -0
  139. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_1.png +0 -0
  140. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_2.png +0 -0
  141. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_3.png +0 -0
  142. robert/gui_easyrob/tutorials/tutorial_images/overview/overview_6.png +0 -0
  143. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1.png +0 -0
  144. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1_1.png +0 -0
  145. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_2.png +0 -0
  146. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_3.png +0 -0
  147. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_4.png +0 -0
  148. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_5.png +0 -0
  149. robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_6.png +0 -0
  150. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_1.png +0 -0
  151. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_2.png +0 -0
  152. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_3.png +0 -0
  153. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_4.png +0 -0
  154. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_5.png +0 -0
  155. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_6.png +0 -0
  156. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_7.png +0 -0
  157. robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_8.png +0 -0
  158. robert/gui_easyrob/utils/__init__.py +0 -0
  159. robert/gui_easyrob/utils/aqme_utils.py +238 -0
  160. robert/gui_easyrob/utils/molssi_utils.py +584 -0
  161. robert/gui_easyrob/utils/predictions_utils.py +985 -0
  162. robert/gui_easyrob/utils/utils_gui.py +738 -0
  163. robert/gui_easyrob/version.py +68 -0
  164. robert/gui_easyrob/web/app.css +484 -0
  165. robert/gui_easyrob/web/app.html +134 -0
  166. robert/gui_easyrob/web/app.js +764 -0
  167. robert/gui_easyrob/web/checkml_brand.png +0 -0
  168. robert/gui_easyrob/web/easyrob_background.gif +0 -0
  169. robert/gui_easyrob/web/easyrob_background.png +0 -0
  170. robert/gui_easyrob/web/images.css +89 -0
  171. robert/gui_easyrob/web/images.html +39 -0
  172. robert/gui_easyrob/web/images.js +101 -0
  173. robert/gui_easyrob/web/results.js +499 -0
  174. robert/gui_easyrob/web/robert_brand.png +0 -0
  175. robert/gui_easyrob/web_dialogs.py +64 -0
  176. robert/gui_easyrob/web_results.py +253 -0
  177. robert/gui_easyrob/web_shell.py +684 -0
  178. robert/gui_easyrob/workflow_progress.py +89 -0
  179. robert/gui_easyrob/workflow_run_lock.py +27 -0
  180. robert/icons/CheckML_icon.png +0 -0
  181. robert/icons/Robert_icon.png +0 -0
  182. robert/icons/Robert_logo.jpg +0 -0
  183. robert/icons/Robert_logo_transparent.png +0 -0
  184. robert/icons/documentation_icon.png +0 -0
  185. robert/icons/info_icon.png +0 -0
  186. robert/icons/pdf_icon.png +0 -0
  187. robert/icons/play_icon.png +0 -0
  188. robert/icons/stop_icon.png +0 -0
  189. robert/icons/youtube_icon.ico +0 -0
  190. robert/predict.py +193 -0
  191. robert/predict_utils.py +410 -0
  192. robert/report/CheckML_logo.jpg +0 -0
  193. robert/report/GENERATE.png +0 -0
  194. robert/report/Robert_icon.ico +0 -0
  195. robert/report/Robert_logo.jpg +0 -0
  196. robert/report/Robert_logo1.jpg +0 -0
  197. robert/report/abbrev.png +0 -0
  198. robert/report/adv_anal.png +0 -0
  199. robert/report/checkml_pass.svg +3 -0
  200. robert/report/checkml_unclear.svg +3 -0
  201. robert/report/checkml_warning.svg +3 -0
  202. robert/report/features.png +0 -0
  203. robert/report/outliers.png +0 -0
  204. robert/report/pred.png +0 -0
  205. robert/report/repro.png +0 -0
  206. robert/report/robust_x.png +0 -0
  207. robert/report/robust_y_high.png +0 -0
  208. robert/report/robust_y_low.png +0 -0
  209. robert/report/score.png +0 -0
  210. robert/report/score_0.jpg +0 -0
  211. robert/report/score_1.jpg +0 -0
  212. robert/report/score_10.jpg +0 -0
  213. robert/report/score_2.jpg +0 -0
  214. robert/report/score_3.jpg +0 -0
  215. robert/report/score_4.jpg +0 -0
  216. robert/report/score_5.jpg +0 -0
  217. robert/report/score_6.jpg +0 -0
  218. robert/report/score_7.jpg +0 -0
  219. robert/report/score_8.jpg +0 -0
  220. robert/report/score_9.jpg +0 -0
  221. robert/report/score_gray_0.jpg +0 -0
  222. robert/report/score_gray_1.jpg +0 -0
  223. robert/report/score_gray_10.jpg +0 -0
  224. robert/report/score_gray_2.jpg +0 -0
  225. robert/report/score_gray_3.jpg +0 -0
  226. robert/report/score_gray_4.jpg +0 -0
  227. robert/report/score_gray_5.jpg +0 -0
  228. robert/report/score_gray_6.jpg +0 -0
  229. robert/report/score_gray_7.jpg +0 -0
  230. robert/report/score_gray_8.jpg +0 -0
  231. robert/report/score_gray_9.jpg +0 -0
  232. robert/report/score_w_1_0.jpg +0 -0
  233. robert/report/score_w_1_1.jpg +0 -0
  234. robert/report/score_w_2_0.jpg +0 -0
  235. robert/report/score_w_2_1.jpg +0 -0
  236. robert/report/score_w_2_2.jpg +0 -0
  237. robert/report/score_w_2_gray_0.jpg +0 -0
  238. robert/report/score_w_2_gray_1.jpg +0 -0
  239. robert/report/score_w_2_gray_2.jpg +0 -0
  240. robert/report/score_w_3_0.jpg +0 -0
  241. robert/report/score_w_3_1.jpg +0 -0
  242. robert/report/score_w_3_2.jpg +0 -0
  243. robert/report/score_w_3_3.jpg +0 -0
  244. robert/report/score_w_4_0.jpg +0 -0
  245. robert/report/score_w_4_1.JPG +0 -0
  246. robert/report/score_w_4_2.jpg +0 -0
  247. robert/report/score_w_4_3.jpg +0 -0
  248. robert/report/score_w_4_4.jpg +0 -0
  249. robert/report/transpa.png +0 -0
  250. robert/report/y_distrib.png +0 -0
  251. robert/report.py +2880 -0
  252. robert/report_utils.py +2270 -0
  253. robert/robert.py +181 -0
  254. robert/utils.py +4763 -0
  255. robert/verify.py +606 -0
  256. robert-2.2.0.dist-info/METADATA +55 -0
  257. robert-2.2.0.dist-info/RECORD +261 -0
  258. robert-2.2.0.dist-info/WHEEL +5 -0
  259. robert-2.2.0.dist-info/entry_points.txt +3 -0
  260. robert-2.2.0.dist-info/licenses/LICENSE +21 -0
  261. robert-2.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,410 @@
1
+ #####################################################.
2
+ # This file stores functions from PREDICT #
3
+ #####################################################.
4
+
5
+ import os
6
+ import ast
7
+ import json
8
+ from pathlib import Path
9
+ import pandas as pd
10
+ import numpy as np
11
+ from scipy import stats
12
+ from robert.utils import (
13
+ get_graph_style,
14
+ pearson_map,
15
+ graph_reg,
16
+ graph_clas,
17
+ get_error_labels,
18
+ mcc_scorer_clf,
19
+ get_prediction_results,
20
+ load_model,
21
+ repeated_kfold_cv,
22
+ )
23
+
24
+
25
+ def full_data_cv(self, Xy_data, model_data):
26
+ """Evaluate train+validation+test with the usual repeated out-of-fold CV.
27
+
28
+ Restore the database's canonical row order (retained in the pandas indices)
29
+ before assigning folds. Reuse its scaled descriptors and the saved model/CV
30
+ settings, and pool every out-of-fold prediction just as load_n_predict does
31
+ for interpolation. External data and the original prediction arrays stay
32
+ outside this diagnostic.
33
+ """
34
+
35
+ X_full = pd.concat([Xy_data['X_train_scaled'], Xy_data['X_test_scaled']]).sort_index(kind='stable')
36
+ y_full = pd.concat([Xy_data['y_train'], Xy_data['y_test']]).sort_index(kind='stable')
37
+ full_data = {'X_train_scaled': X_full, 'y_train': y_full, 'y_test': y_full.iloc[:0]}
38
+ loaded_model = load_model(self, model_data['model'], **model_data['params'])
39
+ # BO_opt here only suppresses unused held-out/in-fold predictions in the CV
40
+ # engine; this diagnostic never runs hyperparameter optimization or sorted CV.
41
+ full_data = repeated_kfold_cv(model_data, loaded_model, full_data, BO_opt=True)
42
+ predictions = np.asarray(full_data['y_pred_train_all'])
43
+ metrics = get_prediction_results(
44
+ model_data, np.repeat(y_full.to_numpy(), predictions.shape[1]), predictions.reshape(-1)
45
+ )
46
+ for metric, value in zip(get_error_labels(model_data['type']), metrics):
47
+ Xy_data[f'{metric}_full'] = value
48
+ return Xy_data
49
+
50
+
51
+ def _get_class_mapping_reverse(model_data):
52
+ mapping = model_data.get('class_mapping_reverse')
53
+ if isinstance(mapping, str):
54
+ try:
55
+ mapping = json.loads(mapping)
56
+ except (json.JSONDecodeError, TypeError):
57
+ mapping = ast.literal_eval(mapping)
58
+ if isinstance(mapping, dict):
59
+ return {int(key): value for key, value in mapping.items()}
60
+ if 'class_0_label' in model_data and 'class_1_label' in model_data:
61
+ return {
62
+ 0: model_data['class_0_label'],
63
+ 1: model_data['class_1_label']
64
+ }
65
+ return None
66
+
67
+
68
+ def plot_predictions(self, params_dict, Xy_data, path_n_suffix):
69
+ '''
70
+ Plot graphs of predicted vs actual values for train, validation and test sets
71
+ '''
72
+
73
+ set_types = [f"{params_dict['repeat_kfolds']}x {params_dict['kfold']}-fold CV",'test']
74
+
75
+ graph_style = get_graph_style()
76
+
77
+ self.args.log.write(f"\n o Saving graphs in:")
78
+
79
+ if params_dict['type'].lower() == 'reg':
80
+ # Plot graph with all sets (kept with its title - the saved PNG stays fully titled;
81
+ # the report crops the title out via a precisely-measured container height instead,
82
+ # see report.py's print_score_images height)
83
+ _ = graph_reg(self,Xy_data,params_dict,set_types,path_n_suffix,graph_style)
84
+ # Plot CV average ± SD graph of validation or test set
85
+ _ = graph_reg(self,Xy_data,params_dict,set_types,path_n_suffix,graph_style,sd_graph=True)
86
+ # Plot CV average ± SD graph of the out-of-fold train+validation predictions (item 6's
87
+ # 2nd stability facet - see print_predict()'s "Average SD in train+validation" line)
88
+ _ = graph_reg(self,Xy_data,params_dict,set_types,path_n_suffix,graph_style,sd_graph=True,sd_set='train')
89
+ if 'y_external' in Xy_data and not Xy_data['y_external'].isnull().values.any() and len(Xy_data['y_external']) > 0:
90
+ # Plot CV average ± SD graph of external set
91
+ set_type = 'external'
92
+ _ = graph_reg(self,Xy_data,params_dict,set_type,path_n_suffix,graph_style,csv_test=True,sd_graph=True)
93
+
94
+ elif params_dict['type'].lower() == 'clas':
95
+ for set_type in set_types:
96
+ _ = graph_clas(self,Xy_data,params_dict,set_type,path_n_suffix)
97
+ if 'y_external' in Xy_data and not Xy_data['y_external'].isnull().values.any() and len(Xy_data['y_external']) > 0:
98
+ set_type = 'external'
99
+ _ = graph_clas(self,Xy_data,params_dict,set_type,path_n_suffix,csv_test=True)
100
+
101
+ return graph_style
102
+
103
+
104
+ def save_predictions(self,Xy_data,model_data,suffix_title):
105
+ '''
106
+ Saves CSV files with the different sets and their predicted results
107
+ '''
108
+
109
+ # Check if we need to reconvert class labels (for classification with string labels)
110
+ class_mapping_reverse = _get_class_mapping_reverse(model_data)
111
+ reconvert_labels = class_mapping_reverse is not None
112
+
113
+ # save CV and test results as a single df
114
+ Xy_train, Xy_test = pd.DataFrame(Xy_data['names_train']), pd.DataFrame(Xy_data['names_test'])
115
+ for col in Xy_data['X_train']:
116
+ Xy_train[col] = Xy_data['X_train'][col].tolist()
117
+ Xy_test[col] = Xy_data['X_test'][col].tolist()
118
+
119
+ # Store y values and predictions, reconverting if needed
120
+ y_col = model_data['y']
121
+
122
+ # For training set
123
+ y_train_values = Xy_data['y_train'].tolist()
124
+ y_pred_train_values = Xy_data['y_pred_train']
125
+ if reconvert_labels:
126
+ y_train_values = [class_mapping_reverse[int(y)] for y in y_train_values]
127
+ y_pred_train_values = [class_mapping_reverse[int(y)] for y in y_pred_train_values]
128
+
129
+ Xy_train[y_col] = y_train_values
130
+ Xy_train[f"{y_col}_pred"] = y_pred_train_values
131
+ Xy_train[f"{y_col}_pred_sd"] = Xy_data['y_pred_train_sd']
132
+ include_conformal = bool(getattr(self.args, "_api_predict", False))
133
+ if include_conformal:
134
+ hw_scalar = float(Xy_data.get("conformal_half_width", float("nan")))
135
+ if model_data["type"].lower() != "reg":
136
+ hw_scalar = float("nan")
137
+ Xy_train[f"{y_col}_pred_conformal_hw"] = [hw_scalar] * len(Xy_train)
138
+
139
+ # For test set
140
+ y_test_values = Xy_data['y_test'].tolist()
141
+ y_pred_test_values = Xy_data['y_pred_test']
142
+ if reconvert_labels:
143
+ y_test_values = [class_mapping_reverse[int(y)] for y in y_test_values]
144
+ y_pred_test_values = [class_mapping_reverse[int(y)] for y in y_pred_test_values]
145
+
146
+ Xy_test[y_col] = y_test_values
147
+ Xy_test[f"{y_col}_pred"] = y_pred_test_values
148
+ Xy_test[f"{y_col}_pred_sd"] = Xy_data['y_pred_test_sd']
149
+ if include_conformal:
150
+ Xy_test[f"{y_col}_pred_conformal_hw"] = [hw_scalar] * len(Xy_test)
151
+
152
+ df_results = pd.concat([Xy_train, Xy_test], axis=0)
153
+
154
+ # add column with sets
155
+ train_list = ['CV' for _ in Xy_data['y_train']]
156
+ test_list = ['Test' for _ in Xy_data['y_test']]
157
+ col_set = train_list + test_list
158
+ df_results['Set'] = col_set
159
+
160
+ # save results as CSV
161
+ base_csv_name = f"PREDICT/{model_data['model']}_{suffix_title}"
162
+ base_csv_path = f"{Path(os.getcwd()).joinpath(base_csv_name)}"
163
+ path_n_suffix = f'{base_csv_path}'
164
+ _ = df_results.to_csv(f'{base_csv_path}.csv', index = None, header=True)
165
+
166
+ # also save results for performance of individual folds (useful for t-tests and Wilcoxon tests between the folds)
167
+ error1, error2, error3 = get_error_labels(model_data['type'])
168
+
169
+ # df_folds = pd.DataFrame()
170
+ # df_folds['Fold'] = [f'{i+1}' for i in range(len(Xy_data['idx_valid']))]
171
+ # df_folds['idx_valid'] = Xy_data['idx_valid']
172
+ # df_folds[f'{error1}_valid'] = Xy_data[f'fold_{error1}_valid']
173
+ # df_folds[f'{error2}_valid'] = Xy_data[f'fold_{error2}_valid']
174
+ # df_folds[f'{error3}_valid'] = Xy_data[f'fold_{error3}_valid']
175
+ # df_folds[f'{error1}_test'] = Xy_data[f'fold_{error1}_test']
176
+ # df_folds[f'{error2}_test'] = Xy_data[f'fold_{error2}_test']
177
+ # df_folds[f'{error3}_test'] = Xy_data[f'fold_{error3}_test']
178
+
179
+ # path_folds = f'{base_csv_path}_CV_folds'
180
+ # _ = df_folds.to_csv(f'{path_folds}.csv', index = None, header=True)
181
+
182
+ # prints
183
+ print_preds = f' o Saving CSV databases with predictions and their SD in:'
184
+ print_preds += f'\n - Predicted results of starting dataset: {base_csv_name}.csv'
185
+
186
+ if self.args.csv_test != '':
187
+ # saves prediction for external test in --csv_test
188
+ Xy_external = pd.DataFrame(Xy_data['names_external'])
189
+
190
+ for col in Xy_data['X_external']:
191
+ Xy_external[col] = Xy_data['X_external'][col].tolist()
192
+
193
+ # Reconvert external set labels if needed (external targets may be legitimately
194
+ # unknown/NaN, e.g. when predicting on new compounds, so those are left as-is)
195
+ if 'y_external' in Xy_data:
196
+ y_external_values = Xy_data['y_external'].tolist()
197
+ if reconvert_labels:
198
+ y_external_values = [class_mapping_reverse[int(y)] if pd.notna(y) else y for y in y_external_values]
199
+ Xy_external[model_data['y']] = y_external_values
200
+
201
+ y_pred_external_values = Xy_data['y_pred_external']
202
+ if reconvert_labels:
203
+ y_pred_external_values = [class_mapping_reverse[int(y)] for y in y_pred_external_values]
204
+
205
+ Xy_external[f"{model_data['y']}_pred"] = y_pred_external_values
206
+ Xy_external[f"{model_data['y']}_pred_sd"] = Xy_data['y_pred_external_sd']
207
+ if include_conformal:
208
+ Xy_external[f"{model_data['y']}_pred_conformal_hw"] = [hw_scalar] * len(Xy_external)
209
+
210
+ path_external = Path(os.getcwd()).joinpath('PREDICT/csv_test/')
211
+ Path(path_external).mkdir(exist_ok=True, parents=True)
212
+ csv_name_external = f'{os.path.basename(self.args.csv_test).split(".csv")[0]}_{model_data["model"]}_{suffix_title}.csv'
213
+ name_external = f"{path_external}/{csv_name_external}"
214
+
215
+ _ = Xy_external.to_csv(name_external, index = None, header=True)
216
+ print_preds += f'\n - External set with predicted results: PREDICT/csv_test/{csv_name_external}'
217
+
218
+ self.args.log.write(print_preds)
219
+
220
+ # store the names of the datapoints
221
+ name_points = {}
222
+ if model_data['names'] != '':
223
+ if model_data['names'].lower() in Xy_train: # accounts for upper/lowercase mismatches
224
+ model_data['names'] = model_data['names'].lower()
225
+ if model_data['names'].upper() in Xy_train:
226
+ model_data['names'] = model_data['names'].upper()
227
+ if model_data['names'] in Xy_train:
228
+ name_points['train'] = df_results[model_data['names']][df_results.Set == 'CV']
229
+ name_points['test'] = df_results[model_data['names']][df_results.Set == 'Test']
230
+
231
+ return path_n_suffix, name_points, Xy_data
232
+
233
+
234
+ def print_predict(self,Xy_data,model_data,suffix_title):
235
+ '''
236
+ Prints results of the predictions for all the sets
237
+ '''
238
+
239
+ print_results = f"\n o Summary of results {model_data['model']}_{suffix_title}:"
240
+ set_print = 'CV (train+valid.):Test'
241
+
242
+ # get number of points and proportions
243
+ n_train = len(Xy_data['y_train'])
244
+ n_test = len(Xy_data['y_test'])
245
+ n_points = f'{n_train}:{n_test}'
246
+ print_results += f"\n - Points {set_print} = {n_points}"
247
+
248
+ total_points = n_train + n_test
249
+ prop_train = round(n_train*100/total_points)
250
+ prop_test = round(n_test*100/total_points)
251
+ prop_print = f'{prop_train}:{prop_test}'
252
+ print_results += f"\n - Proportion {set_print} = {prop_print}"
253
+
254
+ n_descps = len(Xy_data['X_train'].keys())
255
+ print_results += f"\n - Number of descriptors = {n_descps}"
256
+ print_results += f"\n - Proportion (train+valid.) points:descriptors = {n_train}:{n_descps}"
257
+
258
+ # print results and save dat file
259
+ CV_type = f"{model_data['repeat_kfolds']}x {model_data['kfold']}-fold CV"
260
+ if model_data['type'].lower() == 'reg':
261
+ print_results += f"\n - {CV_type} : R2 = {Xy_data['r2_train']:.2}, MAE = {Xy_data['mae_train']:.2}, RMSE = {Xy_data['rmse_train']:.2}"
262
+ print_results += f"\n - Test : R2 = {Xy_data['r2_test']:.2}, MAE = {Xy_data['mae_test']:.2}, RMSE = {Xy_data['rmse_test']:.2}"
263
+ print_results += f"\n - Average SD in test set = {np.mean(Xy_data['y_pred_test_sd']):.2}"
264
+ print_results += f"\n - y range of dataset (CV + test) ={float(Xy_data['pred_min']):.2} to {float(Xy_data['pred_max']):.2}, total {float(Xy_data['pred_range']):.2}"
265
+ if 'r2_train_infold' in Xy_data:
266
+ print_results += f"\n - Train fit (in-fold) : R2 = {Xy_data['r2_train_infold']:.2}, MAE = {Xy_data['mae_train_infold']:.2}, RMSE = {Xy_data['rmse_train_infold']:.2}"
267
+
268
+ # Interpolation item 6, facets (b) and (c), and penalty
269
+ print_results += f"\n - Average SD in train+validation (out-of-fold) = {np.mean(Xy_data['y_pred_train_sd']):.2}"
270
+ if 'rmse_full' in Xy_data:
271
+ print_results += f"\n - Full data {CV_type} : R2 = {Xy_data['r2_full']:.2}, MAE = {Xy_data['mae_full']:.2}, RMSE = {Xy_data['rmse_full']:.2}"
272
+ if 'y_pred_train_all' in Xy_data:
273
+ y_pred_train_all = np.array(Xy_data['y_pred_train_all'])
274
+ if y_pred_train_all.ndim == 1:
275
+ y_pred_train_all = y_pred_train_all[:, None]
276
+ y_train_actual = np.array(Xy_data['y_train'])
277
+
278
+ # Split by actual y, with the extra point (when odd) assigned to the high half.
279
+ # Sort indices only, so y_pred_train_all and its original point ordering stay intact.
280
+ sorted_y_indices = np.argsort(y_train_actual, kind='stable')
281
+ midpoint = len(sorted_y_indices) // 2
282
+ low_50_indices = sorted_y_indices[:midpoint]
283
+ high_50_indices = sorted_y_indices[midpoint:]
284
+ n_repeats = y_pred_train_all.shape[1]
285
+
286
+ # Per half: RMSE (is the error similar in both halves?) and the Spearman rank between
287
+ # observed and predicted values (does the model still rank the points INSIDE each
288
+ # half, or are its predictions flat/unordered there?). R2 is not used here: inside a
289
+ # half the y range is narrow, so R2 mostly reflects how spread that half's y values
290
+ # are, not the model. Spearman uses each point's prediction averaged over the CV
291
+ # repeats (repeating every observed value n_repeats times would only create ties).
292
+ # The observed y range of each half is logged for reference (see
293
+ # half_spearman_penalty() in report_utils.py for the scoring).
294
+ y_pred_mean = y_pred_train_all.mean(axis=1)
295
+
296
+ def get_half_metrics(indices):
297
+ y_actual_half = np.repeat(y_train_actual[indices], n_repeats)
298
+ y_pred_half = y_pred_train_all[indices].reshape(-1)
299
+ _, _, rmse_half = get_prediction_results(model_data, y_actual_half, y_pred_half)
300
+ y_obs, y_pred = y_train_actual[indices], y_pred_mean[indices]
301
+ if len(indices) > 2 and len(np.unique(y_obs)) > 1 and len(np.unique(y_pred)) > 1:
302
+ spearman_half = stats.spearmanr(y_obs, y_pred)[0]
303
+ else:
304
+ spearman_half = 0.0 # flat predictions (or a single value) rank nothing
305
+ return rmse_half, spearman_half, float(np.max(y_obs) - np.min(y_obs))
306
+
307
+ high_50_rmse, high_50_spearman, high_50_range = get_half_metrics(high_50_indices)
308
+ low_50_rmse, low_50_spearman, low_50_range = get_half_metrics(low_50_indices)
309
+ ratio_50_rmse = low_50_rmse / high_50_rmse if high_50_rmse != 0 else 'N/A'
310
+
311
+ print_results += (f"\n - 50% highest data points, RMSE = {high_50_rmse:.2f}, "
312
+ f"Spearman = {high_50_spearman:.2f}, y range = {high_50_range:.3g}")
313
+ print_results += (f"\n - 50% lowest data points, RMSE = {low_50_rmse:.2f}, "
314
+ f"Spearman = {low_50_spearman:.2f}, y range = {low_50_range:.3g}")
315
+ ratio_50_rmse_display = f"{ratio_50_rmse:.2f}" if ratio_50_rmse != 'N/A' else ratio_50_rmse
316
+ print_results += f"\n - Ratio 50% lowest/highest data points, RMSE = {ratio_50_rmse_display}"
317
+
318
+ # Interpolation item 6, facets (b)/(c): stability of the out-of-fold CV predictions
319
+ # themselves (not just the test set - facet (a) above), across the repeated-CV
320
+ # repetitions. (b) average per-point SD of the out-of-fold predictions in
321
+ # train+validation; (c) how much the AGGREGATE RMSE itself varies from repeat to
322
+ # repeat (coefficient of variation = SD/mean of the 10 per-repeat RMSEs) - a
323
+ # complementary, dataset-wide view of the same "how much does this depend on which
324
+ # random split we happened to get" question that (a)/(b) ask per-point
325
+ repeat_rmses = np.sqrt(np.mean((y_train_actual[:,None]-y_pred_train_all)**2,axis=0))
326
+ if len(repeat_rmses) > 1 and np.mean(repeat_rmses) > 0:
327
+ rmse_cv_pct = 100*np.std(repeat_rmses,ddof=1)/np.mean(repeat_rmses)
328
+ else:
329
+ rmse_cv_pct = 0
330
+ print_results += f"\n - RMSE coefficient of variation (10 repeats) = {rmse_cv_pct:.2f}"
331
+
332
+ if 'r2_external' in Xy_data:
333
+ print_results += f"\n - External test : R2 = {Xy_data['r2_external']:.2}, MAE = {Xy_data['mae_external']:.2}, RMSE = {Xy_data['rmse_external']:.2}"
334
+
335
+ elif model_data['type'].lower() == 'clas':
336
+ print_results += f"\n - {CV_type} : Accur. = {Xy_data['acc_train']:.2}, F1 score = {Xy_data['f1_train']:.2}, MCC = {Xy_data['mcc_train']:.2}"
337
+ if 'y_pred_test' in Xy_data and not Xy_data['y_test'].isnull().values.any() and len(Xy_data['y_test']) > 0:
338
+ print_results += f"\n - Test : Accur. = {Xy_data['acc_test']:.2}, F1 score = {Xy_data['f1_test']:.2}, MCC = {Xy_data['mcc_test']:.2}"
339
+ if 'mcc_train_infold' in Xy_data:
340
+ print_results += f"\n - Train fit (in-fold) : Accur. = {Xy_data['acc_train_infold']:.2}, F1 score = {Xy_data['f1_train_infold']:.2}, MCC = {Xy_data['mcc_train_infold']:.2}"
341
+ if 'mcc_full' in Xy_data:
342
+ print_results += f"\n - Full data {CV_type} : Accur. = {Xy_data['acc_full']:.2}, F1 score = {Xy_data['f1_full']:.2}, MCC = {Xy_data['mcc_full']:.2}"
343
+
344
+ # Interpolation item 6 for classification: the same "how much does this depend on
345
+ # the random split" question as the regression facets, adapted for a discrete label.
346
+ # (a)/(b) use the repeat-to-repeat agreement rate with the already-computed
347
+ # majority-voted class instead of a numeric SD; (c) uses the coefficient of
348
+ # variation of the per-repeat MCC instead of the per-repeat RMSE
349
+ if 'y_pred_test_all' in Xy_data and len(Xy_data['y_pred_test_all']) > 0:
350
+ test_agree = [np.mean(np.array(reps) == vote) for reps,vote in zip(Xy_data['y_pred_test_all'],Xy_data['y_pred_test'])]
351
+ print_results += f"\n - Average agreement in test set (10 repeats) = {100*np.mean(test_agree):.1f}"
352
+
353
+ if 'y_pred_train_all' in Xy_data:
354
+ train_agree = [np.mean(np.array(reps) == vote) for reps,vote in zip(Xy_data['y_pred_train_all'],Xy_data['y_pred_train'])]
355
+ print_results += f"\n - Average agreement in train+validation (out-of-fold) (10 repeats) = {100*np.mean(train_agree):.1f}"
356
+
357
+ y_pred_train_all = np.array(Xy_data['y_pred_train_all'])
358
+ y_train_actual = np.array(Xy_data['y_train'])
359
+ if y_pred_train_all.shape[1] > 1:
360
+ repeat_mccs = [mcc_scorer_clf(y_train_actual,y_pred_train_all[:,i]) for i in range(y_pred_train_all.shape[1])]
361
+ if np.mean(repeat_mccs) != 0:
362
+ mcc_cv_pct = 100*np.std(repeat_mccs,ddof=1)/abs(np.mean(repeat_mccs))
363
+ elif np.std(repeat_mccs,ddof=1) == 0:
364
+ mcc_cv_pct = 0
365
+ else:
366
+ # MCCs that vary but average exactly 0 (i.e., positive and negative repeats
367
+ # cancel out) are the least stable case, not the most stable one
368
+ mcc_cv_pct = float('inf')
369
+ print_results += f"\n - MCC coefficient of variation (10 repeats) = {mcc_cv_pct:.1f}"
370
+
371
+ if 'acc_external' in Xy_data:
372
+ print_results += f"\n - External test : Accur. = {Xy_data['acc_external']:.2}, F1 score = {Xy_data['f1_external']:.2}, MCC = {Xy_data['mcc_external']:.2}"
373
+
374
+ self.args.log.write(print_results)
375
+
376
+
377
+ def pearson_map_predict(self,Xy_data,params_dir,suffix_title):
378
+ '''
379
+ Plots the Pearson map and analyzes correlation of descriptors.
380
+ '''
381
+
382
+ X_combined = pd.concat([Xy_data['X_train'], Xy_data['X_test']], axis=0, ignore_index=True)
383
+ corr_matrix = pearson_map(self,X_combined,'predict',params_dir=params_dir,suffix_title=suffix_title)
384
+
385
+ corr_dict = {'descp_1': [],
386
+ 'descp_2': [],
387
+ 'r': []
388
+ }
389
+ for i,descp in enumerate(corr_matrix.columns):
390
+ for j,val in enumerate(corr_matrix[descp]):
391
+ if i < j and np.abs(val) > 0.8:
392
+ corr_dict['descp_1'].append(corr_matrix.columns[i])
393
+ corr_dict['descp_2'].append(corr_matrix.columns[j])
394
+ corr_dict['r'].append(val)
395
+
396
+ print_corr = f' Ideally, variables should show low correlations.' # no initial \n, it's a new log.write
397
+ if len(corr_dict['descp_1']) == 0:
398
+ print_corr += f"\n o Correlations between variables are acceptable"
399
+ else:
400
+ abs_r_list = list(np.abs(corr_dict['r']))
401
+ abs_max_r = max(abs_r_list)
402
+ max_r = corr_dict['r'][abs_r_list.index(abs_max_r)]
403
+ max_descp_1 = corr_dict['descp_1'][abs_r_list.index(abs_max_r)]
404
+ max_descp_2 = corr_dict['descp_2'][abs_r_list.index(abs_max_r)]
405
+ if abs_max_r > 0.84:
406
+ print_corr += f"\n x WARNING! High correlations observed (up to r = {max_r:.2} or R2 = {max_r*max_r:.2}, for {max_descp_1} and {max_descp_2})"
407
+ elif abs_max_r > 0.71:
408
+ print_corr += f"\n x WARNING! Noticeable correlations observed (up to r = {max_r:.2} or R2 = {max_r*max_r:.2}, for {max_descp_1} and {max_descp_2})"
409
+
410
+ self.args.log.write(print_corr)
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,3 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 12 12">
2
+ <path d="M2 6l3 3 5-6" fill="none" stroke="#236c32" stroke-width="1.5"/>
3
+ </svg>
@@ -0,0 +1,3 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 12 12">
2
+ <path d="M6 1L11 10H1z M6 4v3 M6 8v1" fill="none" stroke="#806000" stroke-width="1.5"/>
3
+ </svg>
@@ -0,0 +1,3 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 12 12">
2
+ <path d="M2 2l8 8 M2 10l8-8" fill="none" stroke="#a02828" stroke-width="1.5"/>
3
+ </svg>
Binary file
Binary file
robert/report/pred.png ADDED
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file