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/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ __all__ = ("RobertModel",)
2
+
3
+
4
+ def __getattr__(name: str):
5
+ if name == "RobertModel":
6
+ from robert.api import RobertModel
7
+
8
+ return RobertModel
9
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
robert/__main__.py ADDED
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env python
2
+
3
+ ###############################################.
4
+ # __main__ file for the code #
5
+ ###############################################.
6
+
7
+ from __future__ import absolute_import
8
+
9
+ import sys
10
+ from robert import robert
11
+
12
+ # If we are running from a wheel, add the wheel to sys.path
13
+ # This allows the usage python pip-*.whl/pip install pip-*.whl
14
+
15
+ if __package__ != 'robert':
16
+ print('ROBERT is not installed! Use: pip install robert or conda install -y -c conda-forge robert.')
17
+
18
+ if __name__ == '__main__':
19
+ robert.main()
20
+ sys.exit()
robert/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Single release version shared by ROBERT and easyROB."""
2
+
3
+ ROBERT_VERSION = "2.2.0"
robert/api.py ADDED
@@ -0,0 +1,646 @@
1
+ """
2
+ Sklearn-style facade over the ROBERT CLI pipeline.
3
+
4
+ ``RobertModel`` runs CURATE through PREDICT (optional REPORT). Point
5
+ predictions, uncertainty columns, and matplotlib handling are documented in
6
+ ``docs/API/robert.api.rst``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import glob
12
+ import os
13
+ import tempfile
14
+ import uuid
15
+ import warnings
16
+ from contextlib import contextmanager
17
+ from pathlib import Path
18
+ from typing import Any, Literal, Optional, Tuple, Union
19
+
20
+ import matplotlib
21
+ import matplotlib.pyplot as plt
22
+ import numpy as np
23
+ import pandas as pd
24
+ from sklearn.base import BaseEstimator
25
+ from sklearn.metrics import accuracy_score, r2_score
26
+
27
+ from robert.argument_parser import options_add, var_dict
28
+ from robert.curate import curate
29
+ from robert.generate import generate
30
+ from robert.predict import predict as predict_module
31
+ from robert.report import report as report_module
32
+ from robert.utils import load_params
33
+ from robert.verify import verify
34
+
35
+ _NAME_COL = "__robert_name__"
36
+ _DEFAULT_Y = "__robert_y__"
37
+
38
+
39
+ def _filter_robert_kwargs(kwargs: dict) -> dict:
40
+ """Keep only keys accepted by ``set_options`` / ``load_variables``."""
41
+ return {k: v for k, v in kwargs.items() if k in var_dict}
42
+
43
+
44
+ @contextmanager
45
+ def _chdir(path: Path):
46
+ prev = os.getcwd()
47
+ os.chdir(path)
48
+ try:
49
+ yield
50
+ finally:
51
+ os.chdir(prev)
52
+
53
+
54
+ @contextmanager
55
+ def _noninteractive_mpl():
56
+ """Use Agg during ROBERT steps; restore the previous backend afterward."""
57
+ prev = matplotlib.get_backend()
58
+ was_interactive = matplotlib.is_interactive()
59
+ matplotlib.use("Agg", force=True)
60
+ plt.ioff()
61
+ try:
62
+ yield
63
+ finally:
64
+ matplotlib.use(prev, force=True)
65
+ if was_interactive:
66
+ plt.ion()
67
+
68
+
69
+ class _ParamsAdapter:
70
+ """Minimal ``self`` for :func:`robert.utils.load_params` / ``model_adjust_params``."""
71
+
72
+ __slots__ = ("args",)
73
+
74
+ def __init__(self, seed: int, type_: str):
75
+ self.args = options_add()
76
+ self.args.seed = seed
77
+ self.args.type = type_
78
+
79
+
80
+ def _suffix_title(filter_mode: str) -> str:
81
+ if filter_mode == "pfi":
82
+ return "PFI"
83
+ if filter_mode == "no_pfi":
84
+ return "No_PFI"
85
+ raise ValueError("filter_mode must be 'pfi' or 'no_pfi'")
86
+
87
+
88
+ def _find_params_csv(best_subdir: Path) -> Path:
89
+ if not best_subdir.is_dir():
90
+ raise FileNotFoundError(str(best_subdir))
91
+ csvs = sorted(p for p in best_subdir.glob("*.csv") if not p.name.endswith("_db.csv"))
92
+ if len(csvs) != 1:
93
+ raise RuntimeError(
94
+ "Expected exactly one parameter CSV in "
95
+ f"{best_subdir}, found: {[p.name for p in csvs]}"
96
+ )
97
+ return csvs[0]
98
+
99
+
100
+ def _resolve_prediction_id_column(
101
+ result_df: pd.DataFrame, names_key: str, model_names: str
102
+ ) -> str:
103
+ """
104
+ Column in the PREDICT external CSV used to align rows to the API input order.
105
+
106
+ Prefer the API names column, then the name stored in GENERATE params, then a
107
+ single case-insensitive match. Avoid assuming ``result_df.columns[0]`` is the id
108
+ column (column order may change).
109
+ """
110
+ cols = list(result_df.columns)
111
+ if names_key in result_df.columns:
112
+ return names_key
113
+ if model_names and model_names in result_df.columns:
114
+ return model_names
115
+ candidates = [c for c in (names_key, model_names) if c]
116
+ for cand in candidates:
117
+ cf = cand.casefold()
118
+ matches = [c for c in cols if str(c).casefold() == cf]
119
+ if len(matches) == 1:
120
+ return str(matches[0])
121
+ if len(matches) > 1:
122
+ raise RuntimeError(
123
+ f"Ambiguous id column for predictions: {matches!r} all match {cand!r} "
124
+ f"(case-insensitive). Columns in CSV: {cols!r}"
125
+ )
126
+ raise RuntimeError(
127
+ f"Could not find row id column for predictions (tried {names_key!r} and "
128
+ f"{model_names!r}). Columns in CSV: {cols!r}"
129
+ )
130
+
131
+
132
+ def _resolve_predict_csv(workdir: Path, pred_stem: str, model_code: str, suffix: str) -> str:
133
+ """Path to PREDICT output CSV for the external set (exact file, else sorted glob)."""
134
+ csv_dir = workdir / "PREDICT" / "csv_test"
135
+ exact = csv_dir / f"{pred_stem}_{model_code}_{suffix}.csv"
136
+ if exact.is_file():
137
+ return str(exact)
138
+ # exact match failed - fall back to a glob that still requires model_code, so a workdir
139
+ # holding CSVs from more than one model can't silently return another model's predictions
140
+ pattern = str(csv_dir / f"{pred_stem}_{model_code}*{suffix}*.csv")
141
+ matches = sorted(glob.glob(pattern))
142
+ if not matches:
143
+ raise RuntimeError(f"No prediction CSV found matching {pattern!r}")
144
+ if len(matches) > 1:
145
+ warnings.warn(
146
+ "Multiple prediction CSVs matched; using the first after lexicographic sort: "
147
+ f"{matches[0]!r}",
148
+ UserWarning,
149
+ stacklevel=3,
150
+ )
151
+ return matches[0]
152
+
153
+
154
+ class RobertModel(BaseEstimator):
155
+ """
156
+ High-level ROBERT workflow with ``fit``, ``predict``, and ``score``.
157
+
158
+ Subclasses :class:`~sklearn.base.BaseEstimator` for ``get_params`` and
159
+ ``set_params``. Preprocessing (CURATE encoding, ROBERT-internal
160
+ ``StandardScaler`` on the design matrix) runs inside ROBERT; do not stack a
161
+ separate ``StandardScaler`` on the same raw descriptors. Refitting with the same
162
+ ``workdir`` leaves prior outputs on disk. ``fit`` and ``predict`` change the
163
+ process working directory and are not safe to run concurrently on multiple
164
+ instances in one process.
165
+
166
+ :param problem_type: ``"reg"`` or ``"clas"``.
167
+ :param filter_mode: ``"pfi"`` or ``"no_pfi"``; which ``GENERATE/Best_model``
168
+ variant ``predict`` loads.
169
+ :param workdir: Directory for ROBERT outputs, or ``None`` for a managed temp dir.
170
+ :param names: Column in ``X`` used as row identifiers (CURATE ``names``), or ``None``.
171
+ :param report: If ``True``, run REPORT after PREDICT during ``fit``.
172
+ :param seed: Random seed forwarded to ROBERT, or ``None`` for package default.
173
+ :param y_column: If ``fit(X)`` is called with ``y is None``, name of the target column
174
+ in ``X`` (DataFrame only).
175
+ :param kwargs: Additional ROBERT options (keys in ``robert.argument_parser.var_dict``),
176
+ e.g. ``model``, ``n_iter``. Regression uncertainty tuning includes
177
+ ``conformal_enable``, ``conformal_calib_frac``, and ``conformal_coverage``.
178
+ """
179
+
180
+ def __init__(
181
+ self,
182
+ problem_type: Literal["reg", "clas"] = "reg",
183
+ filter_mode: Literal["pfi", "no_pfi"] = "pfi",
184
+ workdir: Optional[Union[str, Path]] = None,
185
+ names: Optional[str] = None,
186
+ report: bool = False,
187
+ seed: Optional[int] = None,
188
+ y_column: Optional[str] = None,
189
+ **kwargs: Any,
190
+ ) -> None:
191
+ super().__init__()
192
+ kwargs = dict(kwargs)
193
+ if "type" in kwargs:
194
+ warnings.warn(
195
+ "Passing 'type' to RobertModel is deprecated; use 'problem_type' instead.",
196
+ DeprecationWarning,
197
+ stacklevel=2,
198
+ )
199
+ if problem_type != "reg":
200
+ raise ValueError("Pass only one of 'problem_type' or deprecated 'type'.")
201
+ problem_type = kwargs.pop("type") # type: ignore[assignment]
202
+ if "filter" in kwargs:
203
+ warnings.warn(
204
+ "Passing 'filter' to RobertModel is deprecated; use 'filter_mode' instead.",
205
+ DeprecationWarning,
206
+ stacklevel=2,
207
+ )
208
+ if filter_mode != "pfi":
209
+ raise ValueError("Pass only one of 'filter_mode' or deprecated 'filter'.")
210
+ filter_mode = kwargs.pop("filter") # type: ignore[assignment]
211
+
212
+ self.problem_type = problem_type
213
+ self.filter_mode = filter_mode
214
+ self._user_names_col = names
215
+ self.run_report = report
216
+ self.y_column_init = y_column
217
+ self._workdir_raw: Optional[Union[str, Path]] = workdir
218
+ self._seed_explicit = seed
219
+
220
+ raw_kw = _filter_robert_kwargs(kwargs)
221
+ if seed is not None:
222
+ raw_kw["seed"] = seed
223
+ raw_kw["type"] = problem_type
224
+ self._rob_kwargs = raw_kw
225
+
226
+ self._managed_temp = workdir is None
227
+ self.workdir_: Optional[Path] = (
228
+ Path(workdir).resolve() if workdir is not None else None
229
+ )
230
+ self._tempdir_obj: Optional[tempfile.TemporaryDirectory[str]] = None
231
+
232
+ self.is_fitted_ = False
233
+ self.y_col_: str = ""
234
+ self.X_columns_: list[str] = []
235
+ self.model_data_: dict[str, Any] = {}
236
+ self.names_col_: str = ""
237
+ self.n_features_in_: int = 0
238
+ self.feature_names_in_: Optional[np.ndarray] = None
239
+ self._fit_input_was_dataframe = False
240
+
241
+ def get_params(self, deep: bool = True) -> dict[str, Any]:
242
+ """Estimator and ROBERT option names from ``__init__`` (no nested estimators)."""
243
+ _ = deep
244
+ out: dict[str, Any] = {
245
+ "problem_type": self.problem_type,
246
+ "filter_mode": self.filter_mode,
247
+ "workdir": self._workdir_raw,
248
+ "names": self._user_names_col,
249
+ "report": self.run_report,
250
+ "seed": self._seed_explicit,
251
+ "y_column": self.y_column_init,
252
+ }
253
+ for k, v in self._rob_kwargs.items():
254
+ if k == "type":
255
+ continue
256
+ out[k] = v
257
+ return out
258
+
259
+ def set_params(self, **params: Any) -> "RobertModel":
260
+ """Update ``RobertModel`` fields and ROBERT keys accepted by ``var_dict``."""
261
+ if not params:
262
+ return self
263
+ special = {
264
+ "problem_type",
265
+ "filter_mode",
266
+ "workdir",
267
+ "names",
268
+ "report",
269
+ "seed",
270
+ "y_column",
271
+ }
272
+ for key in list(params):
273
+ if key not in special and key not in var_dict:
274
+ raise ValueError(
275
+ f"RobertModel got invalid parameter {key!r}. "
276
+ "Use problem_type, filter_mode, workdir, names, report, seed, y_column, "
277
+ "or a key from robert.argument_parser.var_dict."
278
+ )
279
+ for key in list(params):
280
+ if key not in special:
281
+ continue
282
+ val = params.pop(key)
283
+ if key == "problem_type":
284
+ self.problem_type = val
285
+ self._rob_kwargs["type"] = val
286
+ elif key == "filter_mode":
287
+ self.filter_mode = val
288
+ elif key == "workdir":
289
+ self._workdir_raw = val
290
+ self.workdir_ = Path(val).resolve() if val is not None else None
291
+ self._managed_temp = val is None
292
+ self._tempdir_obj = None
293
+ elif key == "names":
294
+ self._user_names_col = val
295
+ elif key == "report":
296
+ self.run_report = val
297
+ elif key == "seed":
298
+ self._seed_explicit = val
299
+ if val is not None:
300
+ self._rob_kwargs["seed"] = val
301
+ else:
302
+ self._rob_kwargs.pop("seed", None)
303
+ elif key == "y_column":
304
+ self.y_column_init = val
305
+ for k, v in params.items():
306
+ self._rob_kwargs[k] = v
307
+ if k == "type":
308
+ self.problem_type = v # noqa: PLW2901
309
+ return self
310
+
311
+ def __enter__(self) -> "RobertModel":
312
+ self._ensure_workdir()
313
+ return self
314
+
315
+ def __exit__(self, *exc: Any) -> Literal[False]:
316
+ self.cleanup()
317
+ return False
318
+
319
+ def cleanup(self) -> None:
320
+ """Remove managed temporary workdir, if any. Safe to call multiple times."""
321
+ if self._tempdir_obj is not None:
322
+ self._tempdir_obj.cleanup()
323
+ self._tempdir_obj = None
324
+ self.workdir_ = None
325
+ self._managed_temp = self._workdir_raw is None
326
+
327
+ def _ensure_workdir(self) -> Path:
328
+ if self.workdir_ is not None:
329
+ self.workdir_.mkdir(parents=True, exist_ok=True)
330
+ return self.workdir_
331
+ if self._tempdir_obj is None:
332
+ self._tempdir_obj = tempfile.TemporaryDirectory(prefix="robert_api_")
333
+ self.workdir_ = Path(self._tempdir_obj.name).resolve()
334
+ self._managed_temp = True
335
+ assert self.workdir_ is not None
336
+ self.workdir_.mkdir(parents=True, exist_ok=True)
337
+ return self.workdir_
338
+
339
+ def _coerce_xy(
340
+ self,
341
+ X: Union[pd.DataFrame, np.ndarray],
342
+ y: Optional[Union[pd.Series, np.ndarray, list]],
343
+ names: Optional[str],
344
+ ) -> Tuple[pd.DataFrame, pd.Series, str]:
345
+ if isinstance(X, np.ndarray):
346
+ if X.ndim != 2:
347
+ raise ValueError("X must be 2-D")
348
+ X_df = pd.DataFrame(X, columns=[f"x{i}" for i in range(X.shape[1])])
349
+ elif isinstance(X, pd.DataFrame):
350
+ X_df = X.copy()
351
+ else:
352
+ raise TypeError("X must be a pandas DataFrame or numpy.ndarray")
353
+
354
+ names_col = names or self._user_names_col
355
+ if names_col is not None and names_col not in X_df.columns:
356
+ raise ValueError(f"names column {names_col!r} not found in X")
357
+
358
+ if y is None:
359
+ ykey = self.y_column_init
360
+ if ykey is None or ykey not in X_df.columns:
361
+ raise ValueError(
362
+ "y is None but no valid y_column in X; pass y or set y_column="
363
+ )
364
+ y_series = X_df[ykey].copy()
365
+ X_df = X_df.drop(columns=[ykey])
366
+ else:
367
+ y_series = pd.Series(np.asarray(y).ravel(), index=X_df.index)
368
+ if isinstance(y, pd.Series) and y.name is not None and str(y.name).strip():
369
+ y_col_guess = str(y.name)
370
+ else:
371
+ y_col_guess = self.y_column_init or _DEFAULT_Y
372
+ y_series.name = y_col_guess
373
+
374
+ if names_col is None:
375
+ X_df = X_df.copy()
376
+ X_df.insert(0, _NAME_COL, X_df.index.astype(str))
377
+ names_col = _NAME_COL
378
+
379
+ y_col = str(y_series.name) if y_series.name is not None else _DEFAULT_Y
380
+ y_series.name = y_col
381
+ return X_df, y_series, names_col
382
+
383
+ def _build_train_frame(self, X_df: pd.DataFrame, y_series: pd.Series) -> pd.DataFrame:
384
+ out = X_df.copy()
385
+ out[y_series.name] = y_series.values
386
+ return out
387
+
388
+ def _read_model_snapshot(self, workdir: Path) -> dict[str, Any]:
389
+ sub = "PFI" if self.filter_mode == "pfi" else "No_PFI"
390
+ folder = workdir / "GENERATE" / "Best_model" / sub
391
+ params_path = _find_params_csv(folder)
392
+ seed = int(self._rob_kwargs.get("seed", var_dict["seed"]))
393
+ adapter = _ParamsAdapter(seed, self.problem_type)
394
+ return load_params(adapter, str(params_path))
395
+
396
+ def fit(
397
+ self,
398
+ X: Union[pd.DataFrame, np.ndarray],
399
+ y: Optional[Union[pd.Series, np.ndarray, list]] = None,
400
+ names: Optional[str] = None,
401
+ **fit_params: Any,
402
+ ) -> "RobertModel":
403
+ _ = fit_params
404
+ self._fit_input_was_dataframe = isinstance(X, pd.DataFrame)
405
+ workdir = self._ensure_workdir()
406
+ X_df, y_series, names_col = self._coerce_xy(X, y, names)
407
+ train_csv = workdir / "_robert_train.csv"
408
+ train_rel = train_csv.name
409
+ y_col = str(y_series.name)
410
+
411
+ train_frame = self._build_train_frame(X_df, y_series)
412
+ train_frame.to_csv(train_csv, index=False)
413
+
414
+ base = dict(self._rob_kwargs)
415
+ base["command_line"] = False
416
+ base["csv_test"] = ""
417
+
418
+ with _noninteractive_mpl(), _chdir(workdir):
419
+ curate(
420
+ csv_name=train_rel,
421
+ y=y_col,
422
+ names=names_col,
423
+ **base,
424
+ )
425
+ generate(
426
+ csv_name="",
427
+ y="",
428
+ discard=[],
429
+ **base,
430
+ )
431
+ verify(**base)
432
+ predict_module(**base)
433
+ if self.run_report:
434
+ report_module(**base)
435
+
436
+ best_sub = workdir / "GENERATE" / "Best_model" / (
437
+ "PFI" if self.filter_mode == "pfi" else "No_PFI"
438
+ )
439
+ if self.filter_mode == "pfi" and not best_sub.is_dir():
440
+ raise RuntimeError(
441
+ "PFI model folder missing after fit. "
442
+ "Try filter_mode='no_pfi' or enable pfi_filter in ROBERT options."
443
+ )
444
+ if self.filter_mode == "no_pfi" and not best_sub.is_dir():
445
+ raise RuntimeError("No_PFI model folder missing after fit.")
446
+
447
+ model_data = self._read_model_snapshot(workdir)
448
+ self.model_data_ = model_data
449
+ self.y_col_ = str(model_data["y"])
450
+ descs = list(model_data["X_descriptors"])
451
+ self.X_columns_ = descs
452
+ self.n_features_in_ = len(descs)
453
+ if self._fit_input_was_dataframe:
454
+ self.feature_names_in_ = np.asarray(descs, dtype=object)
455
+ else:
456
+ self.feature_names_in_ = None
457
+ model_names = str(model_data.get("names") or "")
458
+ if model_names != names_col:
459
+ if model_names and names_col and model_names.casefold() == names_col.casefold():
460
+ warnings.warn(
461
+ f"Names column casing normalized to saved model column {model_names!r} "
462
+ f"(was {names_col!r}).",
463
+ UserWarning,
464
+ stacklevel=2,
465
+ )
466
+ names_col = model_names
467
+ else:
468
+ raise RuntimeError(
469
+ "Names column mismatch between training data "
470
+ f"({names_col!r}) and GENERATE params ({model_names!r}). "
471
+ "Refit with a clean workdir or align the names column with the model."
472
+ )
473
+ self.names_col_ = names_col
474
+ self.is_fitted_ = True
475
+ return self
476
+
477
+ def best_model_info(self) -> dict[str, Any]:
478
+ if not self.is_fitted_:
479
+ raise RuntimeError("Call fit before best_model_info.")
480
+ md = self.model_data_
481
+ return {
482
+ "model": md["model"],
483
+ "params": md["params"],
484
+ "descriptors": md["X_descriptors"],
485
+ "filter_mode": self.filter_mode,
486
+ "y": md["y"],
487
+ }
488
+
489
+ def predict(
490
+ self,
491
+ X: Union[pd.DataFrame, np.ndarray],
492
+ return_std: bool = False,
493
+ return_uncertainty: Literal[False, "cv_sd", "conformal", "both"] = False,
494
+ ) -> Union[
495
+ np.ndarray,
496
+ Tuple[np.ndarray, np.ndarray],
497
+ Tuple[np.ndarray, np.ndarray, np.ndarray],
498
+ ]:
499
+ if not self.is_fitted_:
500
+ raise RuntimeError("Call fit before predict.")
501
+ workdir = self.workdir_
502
+ assert workdir is not None
503
+
504
+ if return_uncertainty is not False:
505
+ umode: Literal[False, "cv_sd", "conformal", "both"] = return_uncertainty
506
+ if return_std:
507
+ warnings.warn(
508
+ "return_uncertainty is set; return_std is ignored.",
509
+ UserWarning,
510
+ stacklevel=2,
511
+ )
512
+ elif return_std:
513
+ umode = "cv_sd"
514
+ else:
515
+ umode = False
516
+ if umode in ("conformal", "both") and self.problem_type != "reg":
517
+ raise ValueError(
518
+ "return_uncertainty='conformal' or 'both' is only supported "
519
+ "for problem_type='reg'."
520
+ )
521
+
522
+ descriptors = list(self.model_data_["X_descriptors"])
523
+ y_target = str(self.model_data_["y"])
524
+ names_key = self.names_col_
525
+
526
+ if isinstance(X, np.ndarray):
527
+ if X.ndim != 2:
528
+ raise ValueError("X must be 2-D")
529
+ if X.shape[1] != len(descriptors):
530
+ raise ValueError(
531
+ f"X has {X.shape[1]} columns but model expects "
532
+ f"{len(descriptors)} descriptors"
533
+ )
534
+ X_df = pd.DataFrame(X, columns=descriptors, copy=False)
535
+ else:
536
+ X_df = X.copy()
537
+ missing = [c for c in descriptors if c not in X_df.columns]
538
+ if missing:
539
+ tail = "..." if len(missing) > 10 else ""
540
+ raise ValueError(
541
+ f"Missing descriptor columns: {missing[:10]!r}{tail}"
542
+ )
543
+
544
+ pred_id = uuid.uuid4().hex[:12]
545
+ pred_name = f"_robert_predict_{pred_id}.csv"
546
+ pred_path = workdir / pred_name
547
+
548
+ if names_key and names_key in X_df.columns:
549
+ X_out = X_df[[names_key] + descriptors].copy()
550
+ else:
551
+ X_out = X_df[descriptors].copy()
552
+ X_out.insert(0, names_key or _NAME_COL, X_out.index.astype(str))
553
+
554
+ order_keys = X_out.iloc[:, 0].astype(str)
555
+ if order_keys.duplicated().any():
556
+ raise ValueError(
557
+ "Duplicate values in the names column; cannot align predictions to rows."
558
+ )
559
+ X_out.to_csv(pred_path, index=False)
560
+
561
+ base = dict(self._rob_kwargs)
562
+ base["command_line"] = False
563
+ base["csv_test"] = pred_name
564
+ base["params_dir"] = "GENERATE/Best_model"
565
+ base["names"] = self.names_col_
566
+ base["_api_predict"] = True
567
+
568
+ with _noninteractive_mpl(), _chdir(workdir):
569
+ predict_module(**base)
570
+
571
+ suffix = _suffix_title(self.filter_mode)
572
+ model_code = str(self.model_data_["model"])
573
+ pred_stem = Path(pred_name).stem
574
+ csv_path = _resolve_predict_csv(workdir, pred_stem, model_code, suffix)
575
+
576
+ result_df = pd.read_csv(csv_path, encoding="utf-8")
577
+ pred_col = f"{y_target}_pred"
578
+ sd_col = f"{y_target}_pred_sd"
579
+ hw_col = f"{y_target}_pred_conformal_hw"
580
+ if pred_col not in result_df.columns:
581
+ raise RuntimeError(f"Column {pred_col!r} missing in {csv_path}")
582
+
583
+ model_names = str(self.model_data_.get("names") or "")
584
+ name_col_result = _resolve_prediction_id_column(
585
+ result_df, names_key, model_names
586
+ )
587
+ aligned = result_df.set_index(
588
+ result_df[name_col_result].astype(str), drop=False
589
+ )
590
+ try:
591
+ ordered = aligned.reindex(order_keys.values)
592
+ except ValueError as err:
593
+ raise RuntimeError(
594
+ "Could not align predictions to input row names; duplicate names?"
595
+ ) from err
596
+ if ordered[pred_col].isna().any():
597
+ missing_n = int(ordered[pred_col].isna().sum())
598
+ raise RuntimeError(
599
+ f"Prediction CSV row count or names mismatch ({missing_n} missing rows)."
600
+ )
601
+
602
+ y_pred = ordered[pred_col].to_numpy()
603
+ try:
604
+ os.remove(pred_path)
605
+ except OSError:
606
+ pass
607
+
608
+ if umode is False:
609
+ return y_pred
610
+
611
+ if umode in ("cv_sd", "both"):
612
+ if sd_col not in result_df.columns:
613
+ raise RuntimeError(f"Column {sd_col!r} missing in {csv_path}")
614
+ y_sd = ordered[sd_col].to_numpy(dtype=float)
615
+ if umode in ("conformal", "both"):
616
+ if hw_col not in result_df.columns:
617
+ raise RuntimeError(f"Column {hw_col!r} missing in {csv_path}")
618
+ y_hw = ordered[hw_col].to_numpy(dtype=float)
619
+ if np.all(np.isnan(y_hw)):
620
+ raise RuntimeError(
621
+ f"Column {hw_col!r} has no finite values; disable conformal "
622
+ "or use a larger training set."
623
+ )
624
+
625
+ if umode == "cv_sd":
626
+ return y_pred, y_sd
627
+ if umode == "conformal":
628
+ return y_pred, y_hw
629
+ return y_pred, y_sd, y_hw
630
+
631
+ def score(
632
+ self,
633
+ X: Union[pd.DataFrame, np.ndarray],
634
+ y: Union[pd.Series, np.ndarray, list],
635
+ ) -> float:
636
+ y_true = np.asarray(y).ravel()
637
+ y_hat = np.asarray(self.predict(X, return_std=False)).ravel()
638
+ if self.problem_type == "reg":
639
+ return float(r2_score(y_true, y_hat))
640
+ try:
641
+ y_true_score = np.round(y_true).astype(int)
642
+ y_hat_score = np.round(y_hat).astype(int)
643
+ except (TypeError, ValueError):
644
+ y_true_score = y_true.astype(str)
645
+ y_hat_score = y_hat.astype(str)
646
+ return float(accuracy_score(y_true_score, y_hat_score))