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.
- robert/__init__.py +9 -0
- robert/__main__.py +20 -0
- robert/_version.py +3 -0
- robert/api.py +646 -0
- robert/aqme.py +280 -0
- robert/argument_parser.py +98 -0
- robert/checkml.py +433 -0
- robert/checkml_score.py +50 -0
- robert/curate.py +217 -0
- robert/evaluate_bot_retrieval.py +125 -0
- robert/evaluate_bot_support.py +102 -0
- robert/evaluate_workflow_summaries.py +87 -0
- robert/export_bot_docs_knowledge.py +1632 -0
- robert/generate.py +249 -0
- robert/generate_utils.py +311 -0
- robert/gui_easyrob/__init__.py +0 -0
- robert/gui_easyrob/assets/gif_easyrob.gif +0 -0
- robert/gui_easyrob/bot/__init__.py +47 -0
- robert/gui_easyrob/bot/answer_metadata.py +198 -0
- robert/gui_easyrob/bot/bot_context.py +679 -0
- robert/gui_easyrob/bot/bot_engine.py +1100 -0
- robert/gui_easyrob/bot/bot_panel.py +1231 -0
- robert/gui_easyrob/bot/bot_rag.py +1178 -0
- robert/gui_easyrob/bot/bot_window.py +39 -0
- robert/gui_easyrob/bot/bot_worker.py +149 -0
- robert/gui_easyrob/bot/credential_store.py +143 -0
- robert/gui_easyrob/bot/error_parser.py +105 -0
- robert/gui_easyrob/bot/evidence_policy.py +164 -0
- robert/gui_easyrob/bot/heuristics.py +859 -0
- robert/gui_easyrob/bot/icons.py +56 -0
- robert/gui_easyrob/bot/input_csv_audit.py +212 -0
- robert/gui_easyrob/bot/knowledge/aqme_context.json +5907 -0
- robert/gui_easyrob/bot/knowledge/robert_context.json +4817 -0
- robert/gui_easyrob/bot/knowledge/ui_context.json +8293 -0
- robert/gui_easyrob/bot/knowledge_schema.py +1252 -0
- robert/gui_easyrob/bot/knowledge_sources/aqme_user_guidance.json +442 -0
- robert/gui_easyrob/bot/knowledge_sources/coverage_manifest.json +95 -0
- robert/gui_easyrob/bot/knowledge_sources/robert_user_guidance.json +471 -0
- robert/gui_easyrob/bot/knowledge_sources/ui_user_guidance.json +1312 -0
- robert/gui_easyrob/bot/llm_providers.py +1573 -0
- robert/gui_easyrob/bot/online_docs.py +105 -0
- robert/gui_easyrob/bot/prompt_policy.py +575 -0
- robert/gui_easyrob/bot/question_intent.py +562 -0
- robert/gui_easyrob/bot/response_quality.py +104 -0
- robert/gui_easyrob/bot/result_insights.py +225 -0
- robert/gui_easyrob/bot/token_usage.py +75 -0
- robert/gui_easyrob/bot/workflow_results.py +1396 -0
- robert/gui_easyrob/checkml_launcher.py +15 -0
- robert/gui_easyrob/easyrob.py +29 -0
- robert/gui_easyrob/easyrob_launcher.py +113 -0
- robert/gui_easyrob/main/__init__.py +9 -0
- robert/gui_easyrob/main/window.py +5152 -0
- robert/gui_easyrob/result_navigation.py +14 -0
- robert/gui_easyrob/tabs/__init__.py +23 -0
- robert/gui_easyrob/tabs/advanced_options.py +370 -0
- robert/gui_easyrob/tabs/aqme.py +1234 -0
- robert/gui_easyrob/tabs/checkml.py +898 -0
- robert/gui_easyrob/tabs/images.py +427 -0
- robert/gui_easyrob/tabs/interactive_predictions.py +555 -0
- robert/gui_easyrob/tabs/molssi.py +447 -0
- robert/gui_easyrob/tabs/predictions.py +484 -0
- robert/gui_easyrob/tabs/result_catalog.py +170 -0
- robert/gui_easyrob/tabs/results.py +490 -0
- robert/gui_easyrob/tabs/results_workspace.py +120 -0
- robert/gui_easyrob/test_bot_input_csv_audit.py +152 -0
- robert/gui_easyrob/test_bot_question_routing.py +383 -0
- robert/gui_easyrob/test_bot_result_analysis.py +356 -0
- robert/gui_easyrob/test_bot_retrieval_evaluation.py +110 -0
- robert/gui_easyrob/test_bot_ui_integration.py +278 -0
- robert/gui_easyrob/test_checkml_app_mode.py +124 -0
- robert/gui_easyrob/test_checkml_completion.py +57 -0
- robert/gui_easyrob/test_checkml_defaults.py +37 -0
- robert/gui_easyrob/test_checkml_result_summary.py +113 -0
- robert/gui_easyrob/test_checkml_web_mode.py +57 -0
- robert/gui_easyrob/test_dialog_layout.py +33 -0
- robert/gui_easyrob/test_gui_bot_regressions.py +320 -0
- robert/gui_easyrob/test_molssi_auto.py +569 -0
- robert/gui_easyrob/test_tutorial_view.py +215 -0
- robert/gui_easyrob/tutorials/check_model.md +25 -0
- robert/gui_easyrob/tutorials/chemdraw.md +49 -0
- robert/gui_easyrob/tutorials/csv.md +53 -0
- robert/gui_easyrob/tutorials/descriptors.md +21 -0
- robert/gui_easyrob/tutorials/overview.md +65 -0
- robert/gui_easyrob/tutorials/predictions.md +25 -0
- robert/gui_easyrob/tutorials/robbot.md +29 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/check_model/check_model_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_10.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_11.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_12.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_13.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_8.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/chemdraw/chemdraw_9.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_1_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_8.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/csv/csv_9.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/descriptors/descriptors_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_1_8.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_5_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/overview/overview_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_1_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/predictions/predictions_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_1.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_2.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_3.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_4.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_5.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_6.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_7.png +0 -0
- robert/gui_easyrob/tutorials/tutorial_images/robbot/robbot_8.png +0 -0
- robert/gui_easyrob/utils/__init__.py +0 -0
- robert/gui_easyrob/utils/aqme_utils.py +238 -0
- robert/gui_easyrob/utils/molssi_utils.py +584 -0
- robert/gui_easyrob/utils/predictions_utils.py +985 -0
- robert/gui_easyrob/utils/utils_gui.py +738 -0
- robert/gui_easyrob/version.py +68 -0
- robert/gui_easyrob/web/app.css +484 -0
- robert/gui_easyrob/web/app.html +134 -0
- robert/gui_easyrob/web/app.js +764 -0
- robert/gui_easyrob/web/checkml_brand.png +0 -0
- robert/gui_easyrob/web/easyrob_background.gif +0 -0
- robert/gui_easyrob/web/easyrob_background.png +0 -0
- robert/gui_easyrob/web/images.css +89 -0
- robert/gui_easyrob/web/images.html +39 -0
- robert/gui_easyrob/web/images.js +101 -0
- robert/gui_easyrob/web/results.js +499 -0
- robert/gui_easyrob/web/robert_brand.png +0 -0
- robert/gui_easyrob/web_dialogs.py +64 -0
- robert/gui_easyrob/web_results.py +253 -0
- robert/gui_easyrob/web_shell.py +684 -0
- robert/gui_easyrob/workflow_progress.py +89 -0
- robert/gui_easyrob/workflow_run_lock.py +27 -0
- robert/icons/CheckML_icon.png +0 -0
- robert/icons/Robert_icon.png +0 -0
- robert/icons/Robert_logo.jpg +0 -0
- robert/icons/Robert_logo_transparent.png +0 -0
- robert/icons/documentation_icon.png +0 -0
- robert/icons/info_icon.png +0 -0
- robert/icons/pdf_icon.png +0 -0
- robert/icons/play_icon.png +0 -0
- robert/icons/stop_icon.png +0 -0
- robert/icons/youtube_icon.ico +0 -0
- robert/predict.py +193 -0
- robert/predict_utils.py +410 -0
- robert/report/CheckML_logo.jpg +0 -0
- robert/report/GENERATE.png +0 -0
- robert/report/Robert_icon.ico +0 -0
- robert/report/Robert_logo.jpg +0 -0
- robert/report/Robert_logo1.jpg +0 -0
- robert/report/abbrev.png +0 -0
- robert/report/adv_anal.png +0 -0
- robert/report/checkml_pass.svg +3 -0
- robert/report/checkml_unclear.svg +3 -0
- robert/report/checkml_warning.svg +3 -0
- robert/report/features.png +0 -0
- robert/report/outliers.png +0 -0
- robert/report/pred.png +0 -0
- robert/report/repro.png +0 -0
- robert/report/robust_x.png +0 -0
- robert/report/robust_y_high.png +0 -0
- robert/report/robust_y_low.png +0 -0
- robert/report/score.png +0 -0
- robert/report/score_0.jpg +0 -0
- robert/report/score_1.jpg +0 -0
- robert/report/score_10.jpg +0 -0
- robert/report/score_2.jpg +0 -0
- robert/report/score_3.jpg +0 -0
- robert/report/score_4.jpg +0 -0
- robert/report/score_5.jpg +0 -0
- robert/report/score_6.jpg +0 -0
- robert/report/score_7.jpg +0 -0
- robert/report/score_8.jpg +0 -0
- robert/report/score_9.jpg +0 -0
- robert/report/score_gray_0.jpg +0 -0
- robert/report/score_gray_1.jpg +0 -0
- robert/report/score_gray_10.jpg +0 -0
- robert/report/score_gray_2.jpg +0 -0
- robert/report/score_gray_3.jpg +0 -0
- robert/report/score_gray_4.jpg +0 -0
- robert/report/score_gray_5.jpg +0 -0
- robert/report/score_gray_6.jpg +0 -0
- robert/report/score_gray_7.jpg +0 -0
- robert/report/score_gray_8.jpg +0 -0
- robert/report/score_gray_9.jpg +0 -0
- robert/report/score_w_1_0.jpg +0 -0
- robert/report/score_w_1_1.jpg +0 -0
- robert/report/score_w_2_0.jpg +0 -0
- robert/report/score_w_2_1.jpg +0 -0
- robert/report/score_w_2_2.jpg +0 -0
- robert/report/score_w_2_gray_0.jpg +0 -0
- robert/report/score_w_2_gray_1.jpg +0 -0
- robert/report/score_w_2_gray_2.jpg +0 -0
- robert/report/score_w_3_0.jpg +0 -0
- robert/report/score_w_3_1.jpg +0 -0
- robert/report/score_w_3_2.jpg +0 -0
- robert/report/score_w_3_3.jpg +0 -0
- robert/report/score_w_4_0.jpg +0 -0
- robert/report/score_w_4_1.JPG +0 -0
- robert/report/score_w_4_2.jpg +0 -0
- robert/report/score_w_4_3.jpg +0 -0
- robert/report/score_w_4_4.jpg +0 -0
- robert/report/transpa.png +0 -0
- robert/report/y_distrib.png +0 -0
- robert/report.py +2880 -0
- robert/report_utils.py +2270 -0
- robert/robert.py +181 -0
- robert/utils.py +4763 -0
- robert/verify.py +606 -0
- robert-2.2.0.dist-info/METADATA +55 -0
- robert-2.2.0.dist-info/RECORD +261 -0
- robert-2.2.0.dist-info/WHEEL +5 -0
- robert-2.2.0.dist-info/entry_points.txt +3 -0
- robert-2.2.0.dist-info/licenses/LICENSE +21 -0
- robert-2.2.0.dist-info/top_level.txt +1 -0
robert/generate.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Parameters
|
|
3
|
+
----------
|
|
4
|
+
|
|
5
|
+
csv_name : str, default=''
|
|
6
|
+
Name of the CSV file containing the database. A path can be provided (i.e. 'C:/Users/FOLDER/FILE.csv').
|
|
7
|
+
y : str, default=''
|
|
8
|
+
Name of the column containing the response variable in the input CSV file (i.e. 'solubility').
|
|
9
|
+
discard : list, default=[]
|
|
10
|
+
List containing the columns of the input CSV file that will not be included as descriptors
|
|
11
|
+
in the curated CSV file (i.e. ['name','SMILES']).
|
|
12
|
+
ignore : list, default=[]
|
|
13
|
+
List containing the columns of the input CSV file that will be ignored during the curation process
|
|
14
|
+
(i.e. ['name','SMILES']). The descriptors will be included in the curated CSV file. The y value
|
|
15
|
+
is automatically ignored.
|
|
16
|
+
destination : str, default=None
|
|
17
|
+
Directory to create the output file(s).
|
|
18
|
+
varfile : str, default=None
|
|
19
|
+
Option to parse the variables using a yaml file (specify the filename, i.e. varfile=FILE.yaml).
|
|
20
|
+
auto_type : bool, default=True
|
|
21
|
+
If there are only two y values, the program automatically changes the type of problem to classification.
|
|
22
|
+
model : list, default=['RF','GB','NN','MVL'] (regression) and default=['RF','GB','NN','LOGISTIC'] (classification, MVL is replaced by its linear counterpart LOGISTIC)
|
|
23
|
+
ML models available:
|
|
24
|
+
1. 'RF' (Random forest)
|
|
25
|
+
2. 'MVL' (Multivariate lineal models)
|
|
26
|
+
3. 'GB' (Gradient boosting)
|
|
27
|
+
4. 'NN' (MLP neural network)
|
|
28
|
+
5. 'GP' (Gaussian Process)
|
|
29
|
+
6. 'AdaB' (AdaBoost)
|
|
30
|
+
7. 'RIDGE' (Ridge regression, regression only)
|
|
31
|
+
8. 'LOGISTIC' (Logistic regression, classification only)
|
|
32
|
+
type : str, default='reg'
|
|
33
|
+
Type of the pedictions. Options:
|
|
34
|
+
1. 'reg' (Regressor)
|
|
35
|
+
2. 'clas' (Classifier)
|
|
36
|
+
all_models : bool, default=True
|
|
37
|
+
Runs the full VERIFY/PREDICT/REPORT pipeline for every screened model (from the 'model'
|
|
38
|
+
option), each producing its own PDF report - instead of only the single best one. All
|
|
39
|
+
the PDFs are moved into a REPORT_models folder, keeping one overall-best model and
|
|
40
|
+
variant report in the working directory. Set to False to run only the
|
|
41
|
+
GENERATE-selected model; REPORT can still create both No PFI and PFI PDFs
|
|
42
|
+
for that model when PFI filtering is enabled (faster).
|
|
43
|
+
seed : int, default=0
|
|
44
|
+
Random seed used in the ML predictor models and other protocols.
|
|
45
|
+
error_type : str, default: rmse (regression), mcc (classification)
|
|
46
|
+
Target value used during the hyperopt optimization. Options:
|
|
47
|
+
Regression:
|
|
48
|
+
1. rmse (root-mean-square error)
|
|
49
|
+
2. mae (mean absolute error)
|
|
50
|
+
3. r2 (R-squared, not recommended since R2 might be good even with high errors in small datasets)
|
|
51
|
+
Classification:
|
|
52
|
+
1. mcc (Matthew's correlation coefficient)
|
|
53
|
+
2. f1 (F1 score)
|
|
54
|
+
3. acc (accuracy, fraction of correct predictions)
|
|
55
|
+
init_points : int, default=10
|
|
56
|
+
Number of initial points for Bayesian optimization (exploration)
|
|
57
|
+
n_iter : int, default=10
|
|
58
|
+
Number of iterations for Bayesian optimization (exploitation)
|
|
59
|
+
expect_improv : int, default=0.05
|
|
60
|
+
Expected improvement for Bayesian optimization
|
|
61
|
+
pfi_filter : bool, default=True
|
|
62
|
+
Activate the PFI filter of descriptors.
|
|
63
|
+
pfi_epochs : int, default=5
|
|
64
|
+
Sets the number of times a feature is randomly shuffled during the PFI analysis
|
|
65
|
+
(standard from sklearn webpage: 5).
|
|
66
|
+
pfi_threshold : float, default=0.2
|
|
67
|
+
The PFI filter is X% of the model's score (% adjusted, 0.2 = 20% of the total score during PFI).
|
|
68
|
+
pfi_max : int, default=0
|
|
69
|
+
Number of features to keep after the PFI filter. If pfi_max is 0, all the features that pass the PFI
|
|
70
|
+
filter are used.
|
|
71
|
+
auto_test : bool, default=True
|
|
72
|
+
Raises % of test points to 20% if test_set is lower than that.
|
|
73
|
+
test_set : float, default=0.2
|
|
74
|
+
Amount of datapoints to separate as external test set (0.2 = 20%). These points will not be used during the
|
|
75
|
+
hyperoptimization, and PREDICT will use the points as test set during ROBERT workflows. Select
|
|
76
|
+
--test_set 0 to use only training and validation.
|
|
77
|
+
kfold : int, default=5
|
|
78
|
+
Number of random data splits for the cross-validation of the models.
|
|
79
|
+
repeat_kfolds : int, default=10
|
|
80
|
+
Number of repetitions for the k-fold cross-validation of the models.
|
|
81
|
+
split : str, default='auto' (resolves to 'even' for regression, 'stratified' for classification)
|
|
82
|
+
Specifies how the data is split into training and test sets. Options:
|
|
83
|
+
1. 'auto': resolves to 'even' (regression) or 'stratified' (classification).
|
|
84
|
+
2. 'even': splits the data evenly into training and test sets.
|
|
85
|
+
3. 'RND': randomly splits the data.
|
|
86
|
+
4. 'stratified': splits the data while preserving the distribution of the target variable.
|
|
87
|
+
5. 'KN': uses a k-means approach to select representative samples for training (good for intrapolation, bad for boundary robustness).
|
|
88
|
+
6. 'extra_q1': selects the 20% lowest values.
|
|
89
|
+
7. 'extra_q5': selects the 20% highest values.
|
|
90
|
+
|
|
91
|
+
"""
|
|
92
|
+
#####################################################.
|
|
93
|
+
# This file stores the GENERATE class #
|
|
94
|
+
# used in model generation #
|
|
95
|
+
#####################################################.
|
|
96
|
+
|
|
97
|
+
import os
|
|
98
|
+
import time
|
|
99
|
+
from robert.utils import (
|
|
100
|
+
load_variables,
|
|
101
|
+
finish_print,
|
|
102
|
+
load_database,
|
|
103
|
+
check_clas_problem,
|
|
104
|
+
prepare_sets
|
|
105
|
+
)
|
|
106
|
+
from robert.generate_utils import (
|
|
107
|
+
BO_workflow,
|
|
108
|
+
PFI_workflow,
|
|
109
|
+
heatmap_workflow,
|
|
110
|
+
detect_best,
|
|
111
|
+
stage_all_models,
|
|
112
|
+
normalize_model_name
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class generate:
|
|
117
|
+
"""
|
|
118
|
+
Class containing all the functions from the GENERATE module.
|
|
119
|
+
|
|
120
|
+
Parameters
|
|
121
|
+
----------
|
|
122
|
+
kwargs : argument class
|
|
123
|
+
Specify any arguments from the GENERATE module (for a complete list of variables, visit the ROBERT documentation)
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
def __init__(self, **kwargs):
|
|
127
|
+
|
|
128
|
+
start_time = time.time()
|
|
129
|
+
|
|
130
|
+
# load default and user-specified variables
|
|
131
|
+
self.args = load_variables(kwargs, "generate")
|
|
132
|
+
|
|
133
|
+
# load database, discard user-defined descriptors and perform data checks
|
|
134
|
+
csv_df, _, _ = load_database(self,self.args.csv_name,"generate")
|
|
135
|
+
|
|
136
|
+
# adjust classification labels and auto-detect binary classification
|
|
137
|
+
if self.args.type.lower() == 'clas' or (self.args.type.lower() == 'reg' and self.args.auto_type):
|
|
138
|
+
self = check_clas_problem(self,csv_df)
|
|
139
|
+
|
|
140
|
+
# scan different ML models
|
|
141
|
+
txt_heatmap = f"\no Starting heatmap scan with {len(self.args.model)} ML models ({self.args.model})."
|
|
142
|
+
|
|
143
|
+
cycle = 1
|
|
144
|
+
txt_heatmap += f'\n Heatmap generation:'
|
|
145
|
+
self.args.log.write(txt_heatmap)
|
|
146
|
+
|
|
147
|
+
# scan different ML models
|
|
148
|
+
self.args.log.write(f''' o Starting BO-based hyperoptimization using the combined target:
|
|
149
|
+
\n 1. 50% = {self.args.error_type.upper()} from a {self.args.repeat_kfolds}x repeated {self.args.kfold}-fold CV (interpolation)
|
|
150
|
+
\n 2. 50% = {self.args.error_type.upper()} from the bottom or top (worst performing) fold in a sorted {self.args.kfold}-fold CV (boundary robustness)
|
|
151
|
+
\n''')
|
|
152
|
+
|
|
153
|
+
# BO_workflow and PFI_workflow (right below) load the exact same csv_to_load within one
|
|
154
|
+
# model's iteration, and different models often share the same general fallback CSV too -
|
|
155
|
+
# cache load_database()'s (expensive: disk read + missing-data imputation + column sort)
|
|
156
|
+
# result per path and hand out fresh copies instead of redoing that work every time
|
|
157
|
+
_loaded_csvs = {}
|
|
158
|
+
def _load_database_cached(csv_path):
|
|
159
|
+
csv_path = str(csv_path)
|
|
160
|
+
if csv_path not in _loaded_csvs:
|
|
161
|
+
_loaded_csvs[csv_path] = load_database(self,csv_path,"generate",print_info=False)
|
|
162
|
+
csv_df_cached, csv_X_cached, csv_y_cached = _loaded_csvs[csv_path]
|
|
163
|
+
return csv_df_cached.copy(), csv_X_cached.copy(), csv_y_cached.copy()
|
|
164
|
+
|
|
165
|
+
for ML_model in self.args.model:
|
|
166
|
+
|
|
167
|
+
# normalize once, upfront, so every downstream step in this iteration (BO_workflow,
|
|
168
|
+
# PFI_workflow, the log line below) agrees on the same name - BO_workflow() already
|
|
169
|
+
# normalized internally for its own No_PFI save, but PFI_workflow()/save_pfi_csv()
|
|
170
|
+
# used the raw, unnormalized ML_model for the PFI CSV's filename instead, which
|
|
171
|
+
# broke heatmap_workflow()'s No_PFI/PFI name matching whenever a model was given in
|
|
172
|
+
# lowercase/mixed case (e.g. --model "['ridge']")
|
|
173
|
+
ML_model = normalize_model_name(ML_model)
|
|
174
|
+
|
|
175
|
+
self.args.log.write(f' - {cycle}/{len(self.args.model)} - ML model: {ML_model} ')
|
|
176
|
+
|
|
177
|
+
# Try to load model-specific curated CSV first, fall back to general CSV
|
|
178
|
+
# Get the base name from the original csv_name (remove path if any)
|
|
179
|
+
csv_name_base = os.path.basename(f'{self.args.csv_name}')
|
|
180
|
+
if csv_name_base.endswith('_CURATE.csv'):
|
|
181
|
+
# If csv_name is already a CURATE file, extract the original base name
|
|
182
|
+
csv_basename = csv_name_base[:-len('_CURATE.csv')]
|
|
183
|
+
else:
|
|
184
|
+
csv_basename = csv_name_base.split('.')[0]
|
|
185
|
+
|
|
186
|
+
curate_folder = self.args.initial_dir.joinpath('CURATE')
|
|
187
|
+
csv_model_specific = curate_folder.joinpath(f'{csv_basename}_CURATE_{ML_model}.csv')
|
|
188
|
+
|
|
189
|
+
# Store the original csv_name temporarily
|
|
190
|
+
original_csv_name = self.args.csv_name
|
|
191
|
+
|
|
192
|
+
if os.path.exists(csv_model_specific):
|
|
193
|
+
csv_to_load = csv_model_specific
|
|
194
|
+
# Temporarily update csv_name to the model-specific CSV
|
|
195
|
+
self.args.csv_name = str(csv_model_specific)
|
|
196
|
+
self.args.log.write(f' o Using model-specific curated database: {os.path.basename(csv_model_specific)}')
|
|
197
|
+
else:
|
|
198
|
+
csv_to_load = self.args.csv_name
|
|
199
|
+
self.args.log.write(f' x Using general database (model-specific not found): {os.path.basename(self.args.csv_name)}')
|
|
200
|
+
|
|
201
|
+
# load database, discard user-defined descriptors and perform data checks
|
|
202
|
+
csv_df, csv_X, csv_y = _load_database_cached(csv_to_load)
|
|
203
|
+
if self.args.type.lower() == 'clas':
|
|
204
|
+
self = check_clas_problem(self,csv_df)
|
|
205
|
+
csv_y = csv_df[self.args.y]
|
|
206
|
+
|
|
207
|
+
# standardizes and separates an external test set
|
|
208
|
+
Xy_data = prepare_sets(self,csv_df,csv_X,csv_y,None,self.args.names,None,None,None,BO_opt=True)
|
|
209
|
+
|
|
210
|
+
# hyperopt process for ML models
|
|
211
|
+
_ = BO_workflow(self, Xy_data, csv_df, ML_model)
|
|
212
|
+
|
|
213
|
+
# apply the PFI descriptor filter if it's activated
|
|
214
|
+
if self.args.pfi_filter:
|
|
215
|
+
# load database, discard user-defined descriptors and perform data checks
|
|
216
|
+
csv_df, csv_X, csv_y = _load_database_cached(csv_to_load)
|
|
217
|
+
if self.args.type.lower() == 'clas':
|
|
218
|
+
self = check_clas_problem(self,csv_df)
|
|
219
|
+
csv_y = csv_df[self.args.y]
|
|
220
|
+
|
|
221
|
+
# standardizes and separates an external test set
|
|
222
|
+
Xy_data = prepare_sets(self,csv_df,csv_X,csv_y,None,self.args.names,None,None,None,BO_opt=True)
|
|
223
|
+
|
|
224
|
+
_ = PFI_workflow(self, csv_df, ML_model, Xy_data)
|
|
225
|
+
|
|
226
|
+
# Restore the original csv_name
|
|
227
|
+
self.args.csv_name = original_csv_name
|
|
228
|
+
|
|
229
|
+
cycle += 1
|
|
230
|
+
|
|
231
|
+
# detects best combinations
|
|
232
|
+
dir_csv = self.args.destination.joinpath(f"Raw_data")
|
|
233
|
+
_ = detect_best(f'{dir_csv}/No_PFI')
|
|
234
|
+
if self.args.all_models:
|
|
235
|
+
_ = stage_all_models(f'{dir_csv}/No_PFI')
|
|
236
|
+
|
|
237
|
+
# create heatmap plot(s)
|
|
238
|
+
_ = heatmap_workflow(self,"No_PFI")
|
|
239
|
+
|
|
240
|
+
# detect best and create heatmap for PFI models
|
|
241
|
+
if self.args.pfi_filter:
|
|
242
|
+
# detect_best() already returns gracefully (no exception) when no model produced
|
|
243
|
+
# a result in this folder, matching the unguarded No_PFI call above
|
|
244
|
+
_ = detect_best(f'{dir_csv}/PFI')
|
|
245
|
+
if self.args.all_models:
|
|
246
|
+
_ = stage_all_models(f'{dir_csv}/PFI')
|
|
247
|
+
_ = heatmap_workflow(self,"PFI")
|
|
248
|
+
|
|
249
|
+
_ = finish_print(self,start_time,'GENERATE')
|
robert/generate_utils.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
#####################################################.
|
|
2
|
+
# This file stores functions from GENERATE #
|
|
3
|
+
#####################################################.
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import numpy as np
|
|
9
|
+
import glob
|
|
10
|
+
import json
|
|
11
|
+
from robert.utils import (
|
|
12
|
+
load_params,
|
|
13
|
+
PFI_filter,
|
|
14
|
+
create_heatmap,
|
|
15
|
+
BO_optimizer,
|
|
16
|
+
BO_metrics,
|
|
17
|
+
model_adjust_params
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
# ROBERT's own short codes for the models GENERATE can use, case-insensitive (normalized to
|
|
21
|
+
# upper, e.g. 'rf' -> 'RF')
|
|
22
|
+
KNOWN_MODEL_CODES = ['RF','MVL','GB','GP','ADAB','NN','RIDGE','LOGISTIC']
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def normalize_model_name(model_name):
|
|
26
|
+
'''
|
|
27
|
+
Normalizes one of ROBERT's own short model codes to uppercase (case-insensitive).
|
|
28
|
+
'''
|
|
29
|
+
|
|
30
|
+
return model_name.upper() if model_name.upper() in KNOWN_MODEL_CODES else model_name
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# hyperopt workflow
|
|
34
|
+
def BO_workflow(self, Xy_data, csv_df, ML_model):
|
|
35
|
+
'''
|
|
36
|
+
Load hyperparameter space and perform a Bayesian optimization
|
|
37
|
+
'''
|
|
38
|
+
|
|
39
|
+
model_key = normalize_model_name(ML_model)
|
|
40
|
+
|
|
41
|
+
bo_data = {'model': model_key,
|
|
42
|
+
'type': self.args.type.lower(),
|
|
43
|
+
'kfold': self.args.kfold,
|
|
44
|
+
'repeat_kfolds': self.args.repeat_kfolds,
|
|
45
|
+
'seed': self.args.seed,
|
|
46
|
+
'error_type': self.args.error_type.lower(),
|
|
47
|
+
'y': self.args.y,
|
|
48
|
+
'names': self.args.names,
|
|
49
|
+
'X_descriptors': Xy_data['X_descriptors']}
|
|
50
|
+
|
|
51
|
+
if ML_model.upper() != 'MVL':
|
|
52
|
+
bo_data['params'], bo_data[f"combined_{bo_data['error_type']}"] = BO_optimizer(self,bo_data,Xy_data)
|
|
53
|
+
bo_data['params'] = model_adjust_params(self, bo_data['model'], bo_data['params'])
|
|
54
|
+
|
|
55
|
+
else:
|
|
56
|
+
bo_data['params'] = {}
|
|
57
|
+
bo_data = BO_metrics(self, bo_data, Xy_data)
|
|
58
|
+
metric_combined = bo_data[f"combined_{bo_data['error_type']}"]
|
|
59
|
+
self.args.log.write(f" o Combined {bo_data['error_type'].upper()} for {bo_data['model']} (no BO needed) (no PFI filter): {metric_combined:.2}")
|
|
60
|
+
|
|
61
|
+
# include the Set column to differentiate between train and test sets (and external test, if any)
|
|
62
|
+
csv_df = set_sets(csv_df,Xy_data)
|
|
63
|
+
|
|
64
|
+
# save csv files with model params and with Xy datapoints - both filenames must use the
|
|
65
|
+
# same case (model_key) or PFI_workflow() can't find the params file it just wrote back
|
|
66
|
+
db_name = self.args.destination.joinpath(f"Raw_data/No_PFI/{model_key}_db")
|
|
67
|
+
params_name = self.args.destination.joinpath(f"Raw_data/No_PFI/{model_key}")
|
|
68
|
+
_ = csv_df.to_csv(f'{db_name}.csv', index = None, header=True)
|
|
69
|
+
|
|
70
|
+
# Convert params dict to string to avoid serialization issues
|
|
71
|
+
bo_data_to_save = bo_data.copy()
|
|
72
|
+
if 'params' in bo_data_to_save:
|
|
73
|
+
bo_data_to_save['params'] = json.dumps(bo_data_to_save['params'])
|
|
74
|
+
if 'X_descriptors' in bo_data_to_save:
|
|
75
|
+
bo_data_to_save['X_descriptors'] = json.dumps(bo_data_to_save['X_descriptors'])
|
|
76
|
+
|
|
77
|
+
# Save class label mapping if it exists (for classification with string labels)
|
|
78
|
+
if hasattr(self.args, 'class_mapping_reverse'):
|
|
79
|
+
bo_data_to_save['class_mapping_reverse'] = json.dumps(self.args.class_mapping_reverse)
|
|
80
|
+
if hasattr(self.args, 'class_0_label'):
|
|
81
|
+
bo_data_to_save['class_0_label'] = self.args.class_0_label
|
|
82
|
+
bo_data_to_save['class_1_label'] = self.args.class_1_label
|
|
83
|
+
|
|
84
|
+
# Save split type
|
|
85
|
+
bo_data_to_save['split'] = self.args.split
|
|
86
|
+
|
|
87
|
+
bo_data_df = pd.DataFrame([bo_data_to_save])
|
|
88
|
+
_ = bo_data_df.to_csv(f'{params_name}.csv', index = None, header=True)
|
|
89
|
+
|
|
90
|
+
return bo_data
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def PFI_workflow(self, csv_df, ML_model, Xy_data):
|
|
94
|
+
'''
|
|
95
|
+
Filter off parameters with low PFI (not relevant in the model)
|
|
96
|
+
'''
|
|
97
|
+
|
|
98
|
+
# convert df to dict, then adjust params to a valid format
|
|
99
|
+
name_csv_hyperopt = f"Raw_data/No_PFI/{ML_model}"
|
|
100
|
+
path_csv = self.args.destination.joinpath(f'{name_csv_hyperopt}.csv')
|
|
101
|
+
PFI_dict = load_params(self,path_csv)
|
|
102
|
+
|
|
103
|
+
PFI_discard_cols,descp_cols_pfi = PFI_filter(self, Xy_data, PFI_dict)
|
|
104
|
+
|
|
105
|
+
desc_keep = calc_desc_keep(self,Xy_data,PFI_discard_cols)
|
|
106
|
+
|
|
107
|
+
discard_idx, descriptors_PFI = [],[]
|
|
108
|
+
# if no descriptors pass the filter, just choose them based on importance until having the number of descps from desc_keep
|
|
109
|
+
if len(PFI_discard_cols) == len(descp_cols_pfi):
|
|
110
|
+
PFI_discard_cols = []
|
|
111
|
+
|
|
112
|
+
for _,column in enumerate(descp_cols_pfi):
|
|
113
|
+
if column not in PFI_discard_cols and len(descriptors_PFI) < desc_keep:
|
|
114
|
+
descriptors_PFI.append(column)
|
|
115
|
+
else:
|
|
116
|
+
discard_idx.append(column)
|
|
117
|
+
|
|
118
|
+
# only use the descriptors that passed the PFI filter
|
|
119
|
+
Xy_data_PFI = Xy_data.copy()
|
|
120
|
+
Xy_data_PFI['X_train_scaled'] = Xy_data['X_train_scaled'].drop(discard_idx, axis=1)
|
|
121
|
+
|
|
122
|
+
PFI_dict['X_descriptors'] = descriptors_PFI
|
|
123
|
+
|
|
124
|
+
# updates the model's error and descriptors used from the corresponding No_PFI CSV file
|
|
125
|
+
# (the other parameters remain the same)
|
|
126
|
+
PFI_dict = BO_metrics(self, PFI_dict, Xy_data_PFI)
|
|
127
|
+
metric_combined = PFI_dict[f"combined_{PFI_dict['error_type']}"]
|
|
128
|
+
self.args.log.write(f" o Combined {PFI_dict['error_type'].upper()} for {PFI_dict['model']} (with PFI filter): {metric_combined:.2}")
|
|
129
|
+
|
|
130
|
+
# save CSV file
|
|
131
|
+
_ = save_pfi_csv(self,csv_df,name_csv_hyperopt,PFI_dict,Xy_data_PFI,ML_model)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def calc_desc_keep(self,Xy_data,PFI_discard_cols):
|
|
135
|
+
'''
|
|
136
|
+
Calculate number of descriptors to keep in the PFI model
|
|
137
|
+
'''
|
|
138
|
+
|
|
139
|
+
# generate new X datasets and store the descriptors used for the PFI-filtered model
|
|
140
|
+
desc_keep = len(Xy_data['X_train_scaled'].columns)
|
|
141
|
+
|
|
142
|
+
# if the filter does not remove any descriptors based on the PFI threshold, or the
|
|
143
|
+
# proportion of descriptors:total datapoints is higher than 1:3, then the filter takes
|
|
144
|
+
# the minimum value of 1 and 2:
|
|
145
|
+
# 1. 25% less descriptors than the No PFI original model
|
|
146
|
+
# 2. Proportion of 1:3 of descriptors:total datapoints (training + validation)
|
|
147
|
+
total_points = len(Xy_data['y_train'])
|
|
148
|
+
n_descp_PFI = desc_keep-len(PFI_discard_cols)
|
|
149
|
+
|
|
150
|
+
# determine how many points will be kept
|
|
151
|
+
if desc_keep > 1:
|
|
152
|
+
if self.args.pfi_max > 0:
|
|
153
|
+
desc_keep = self.args.pfi_max
|
|
154
|
+
elif n_descp_PFI > 0.2*total_points or n_descp_PFI >= (0.75*desc_keep) or n_descp_PFI == 0:
|
|
155
|
+
option_one = round(0.75*len(Xy_data['X_train_scaled'].columns))
|
|
156
|
+
option_two = round(0.2*total_points)
|
|
157
|
+
option_three = round(len(Xy_data['X_train_scaled'].columns)-1) # for databases with two or three descriptors
|
|
158
|
+
desc_keep = min(option_one,option_two,option_three)
|
|
159
|
+
|
|
160
|
+
return desc_keep
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def save_pfi_csv(self,csv_df,name_csv_hyperopt,PFI_dict,Xy_data_PFI,ML_model):
|
|
164
|
+
'''
|
|
165
|
+
Saves CSV files with PFI models and information
|
|
166
|
+
'''
|
|
167
|
+
|
|
168
|
+
name_csv_hyperopt_PFI = name_csv_hyperopt.replace('No_PFI','PFI')
|
|
169
|
+
path_csv_PFI = self.args.destination.joinpath(f'{name_csv_hyperopt_PFI}_PFI')
|
|
170
|
+
|
|
171
|
+
# Save class label mapping if it exists (for classification with string labels)
|
|
172
|
+
if hasattr(self.args, 'class_mapping_reverse'):
|
|
173
|
+
PFI_dict['class_mapping_reverse'] = json.dumps(self.args.class_mapping_reverse)
|
|
174
|
+
if hasattr(self.args, 'class_0_label'):
|
|
175
|
+
PFI_dict['class_0_label'] = self.args.class_0_label
|
|
176
|
+
PFI_dict['class_1_label'] = self.args.class_1_label
|
|
177
|
+
|
|
178
|
+
csv_PFI_df = pd.DataFrame([PFI_dict])
|
|
179
|
+
_ = csv_PFI_df.to_csv(f'{path_csv_PFI}.csv', index = None, header=True)
|
|
180
|
+
|
|
181
|
+
# include the Set column to differentiate between train and test sets (and external test, if any)
|
|
182
|
+
csv_df = set_sets(csv_df,Xy_data_PFI)
|
|
183
|
+
|
|
184
|
+
# save the csv file
|
|
185
|
+
if os.path.exists(self.args.destination.joinpath(f"Raw_data/PFI/{ML_model}_PFI.csv")):
|
|
186
|
+
db_name = self.args.destination.joinpath(f"Raw_data/PFI/{ML_model}_PFI_db")
|
|
187
|
+
_ = csv_df.to_csv(f'{db_name}.csv', index = None, header=True)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def set_sets(csv_df,Xy_data):
|
|
191
|
+
"""
|
|
192
|
+
Set a new column for the sets, including test set (if any)
|
|
193
|
+
"""
|
|
194
|
+
|
|
195
|
+
set_column = []
|
|
196
|
+
n_points = len(csv_df[csv_df.columns[0]])
|
|
197
|
+
for i in range(0,n_points):
|
|
198
|
+
if i in Xy_data['test_points']:
|
|
199
|
+
set_column.append('Test')
|
|
200
|
+
else:
|
|
201
|
+
set_column.append('Training')
|
|
202
|
+
|
|
203
|
+
csv_df['Set'] = set_column
|
|
204
|
+
|
|
205
|
+
return csv_df
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def detect_best(folder):
|
|
209
|
+
'''
|
|
210
|
+
Check which combination led to the best results
|
|
211
|
+
'''
|
|
212
|
+
|
|
213
|
+
# detect files
|
|
214
|
+
file_list = glob.glob(f'{folder}/*.csv')
|
|
215
|
+
errors = []
|
|
216
|
+
results_model = None
|
|
217
|
+
for file in file_list:
|
|
218
|
+
if '_db' not in file:
|
|
219
|
+
results_model = pd.read_csv(f'{file}', encoding='utf-8')
|
|
220
|
+
training_error = results_model[f"combined_{results_model['error_type'][0]}"][0]
|
|
221
|
+
errors.append(training_error)
|
|
222
|
+
else:
|
|
223
|
+
errors.append(np.nan)
|
|
224
|
+
|
|
225
|
+
# no valid model results in this folder (e.g. every model's BO search failed), nothing to select
|
|
226
|
+
if results_model is None or all(pd.isna(e) for e in errors):
|
|
227
|
+
return
|
|
228
|
+
|
|
229
|
+
# detect best result and copy files to the Best_model folder
|
|
230
|
+
if results_model['error_type'][0].lower() in ['mae','rmse']:
|
|
231
|
+
min_idx = errors.index(np.nanmin(errors))
|
|
232
|
+
else:
|
|
233
|
+
min_idx = errors.index(np.nanmax(errors))
|
|
234
|
+
best_name = file_list[min_idx]
|
|
235
|
+
best_db = f'{os.path.dirname(file_list[min_idx])}/{os.path.basename(file_list[min_idx]).split(".csv")[0]}_db.csv'
|
|
236
|
+
|
|
237
|
+
shutil.copyfile(f'{best_name}', f'{best_name}'.replace('Raw_data','Best_model'))
|
|
238
|
+
shutil.copyfile(f'{best_db}', f'{best_db}'.replace('Raw_data','Best_model'))
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def stage_all_models(folder):
|
|
242
|
+
'''
|
|
243
|
+
Copies every model's parameter+database CSV pair from Raw_data into its own per-model
|
|
244
|
+
subfolder under All_models/ (same idea as detect_best()'s Best_model/ folder, but keeping
|
|
245
|
+
every model instead of just the best one). Each model needs its own dedicated folder since
|
|
246
|
+
load_dfs() scans a folder for exactly one non-"_db" CSV (the params) plus its "_db" pair
|
|
247
|
+
(the database) - a folder with several models' files mixed together would be ambiguous.
|
|
248
|
+
Used when --all_models is active, so VERIFY/PREDICT/REPORT can loop over every model.
|
|
249
|
+
'''
|
|
250
|
+
|
|
251
|
+
file_list = glob.glob(f'{folder}/*.csv')
|
|
252
|
+
for file in file_list:
|
|
253
|
+
if '_db' not in file:
|
|
254
|
+
file_stem = os.path.basename(file).split('.csv')[0]
|
|
255
|
+
db_file = f'{os.path.dirname(file)}/{file_stem}_db.csv'
|
|
256
|
+
# PFI params files are already named e.g. "RF_PFI" (see save_pfi_csv()) - strip
|
|
257
|
+
# that suffix for the destination folder name, so it stays just the model name
|
|
258
|
+
# ("RF") regardless of PFI/No_PFI, matching build_params_dirs()'s own "_PFI"
|
|
259
|
+
# suffix it appends when building suffix_titles (avoids a doubled "_PFI_PFI")
|
|
260
|
+
model_name = file_stem[:-len('_PFI')] if file_stem.endswith('_PFI') else file_stem
|
|
261
|
+
dest_dir = f'{folder}/{model_name}'.replace('Raw_data','All_models')
|
|
262
|
+
os.makedirs(dest_dir, exist_ok=True)
|
|
263
|
+
shutil.copyfile(file, f'{dest_dir}/{os.path.basename(file)}')
|
|
264
|
+
shutil.copyfile(db_file, f'{dest_dir}/{os.path.basename(db_file)}')
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def heatmap_workflow(self,folder_hm):
|
|
268
|
+
"""
|
|
269
|
+
Create matrix of ML models, training sizes and errors/precision
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
path_raw = self.args.destination.joinpath(f"Raw_data")
|
|
273
|
+
csv_data, model_list = {},[]
|
|
274
|
+
for csv_file in glob.glob(path_raw.joinpath(f"{folder_hm}/*.csv").as_posix()):
|
|
275
|
+
if '_db' not in csv_file:
|
|
276
|
+
basename = os.path.basename(csv_file)
|
|
277
|
+
csv_model = basename.replace('.','_').split('_')[0]
|
|
278
|
+
if csv_model not in model_list:
|
|
279
|
+
csv_value = pd.read_csv(csv_file, encoding='utf-8')
|
|
280
|
+
csv_data[csv_model] = csv_value[f"combined_{self.args.error_type}"][0]
|
|
281
|
+
|
|
282
|
+
# pass dictionary into a dataframe, and sort the models alphabetically
|
|
283
|
+
csv_df = pd.DataFrame([csv_data])
|
|
284
|
+
|
|
285
|
+
# sort columns in the same order as the optimization
|
|
286
|
+
df_cols = []
|
|
287
|
+
for model in self.args.model:
|
|
288
|
+
df_cols.append(normalize_model_name(model))
|
|
289
|
+
|
|
290
|
+
# a model missing from csv_data means its CSV wasn't found under Raw_data/{folder_hm} (BO/PFI
|
|
291
|
+
# step failed to produce one, or a partial run was resumed) - reindexing on the full model
|
|
292
|
+
# list would otherwise raise a bare KeyError instead of pointing at the actual missing model
|
|
293
|
+
missing_models = [model for model in df_cols if model not in csv_data]
|
|
294
|
+
if missing_models:
|
|
295
|
+
self.args.log.write(f"\nx WARNING! No results were found for these models, they will be skipped in the heatmap: {missing_models}")
|
|
296
|
+
df_cols = [model for model in df_cols if model not in missing_models]
|
|
297
|
+
|
|
298
|
+
# nothing to plot if every model failed (seaborn can't draw an empty matrix)
|
|
299
|
+
if not df_cols:
|
|
300
|
+
self.args.log.write(f"\nx WARNING! No model produced results, so the heatmap was not generated.")
|
|
301
|
+
return
|
|
302
|
+
|
|
303
|
+
csv_df = csv_df[df_cols]
|
|
304
|
+
|
|
305
|
+
# plot heatmap
|
|
306
|
+
if folder_hm == "No_PFI":
|
|
307
|
+
suffix = 'No PFI'
|
|
308
|
+
elif folder_hm == "PFI":
|
|
309
|
+
suffix = 'PFI'
|
|
310
|
+
_ = create_heatmap(self,csv_df,suffix,path_raw)
|
|
311
|
+
|
|
File without changes
|
|
Binary file
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Lazy bot package exports used while the scaffold is still incomplete."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib import import_module
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
__all__ = ["BotEngine", "BotPanel", "BotWindow"]
|
|
9
|
+
|
|
10
|
+
_EXPORTS = {
|
|
11
|
+
"BotEngine": "bot_engine",
|
|
12
|
+
"BotPanel": "bot_panel",
|
|
13
|
+
"BotWindow": "bot_window",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from .bot_engine import BotEngine
|
|
19
|
+
from .bot_panel import BotPanel
|
|
20
|
+
from .bot_window import BotWindow
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _load_export(name: str) -> Any:
|
|
24
|
+
module_name = _EXPORTS[name]
|
|
25
|
+
try:
|
|
26
|
+
module = import_module(f".{module_name}", __name__)
|
|
27
|
+
except ModuleNotFoundError as exc:
|
|
28
|
+
if exc.name == f"{__name__}.{module_name}":
|
|
29
|
+
raise ImportError(
|
|
30
|
+
f"{name} is not available yet; {__name__}.{module_name} has not been added."
|
|
31
|
+
) from exc
|
|
32
|
+
raise
|
|
33
|
+
|
|
34
|
+
return getattr(module, name)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def __getattr__(name: str) -> Any:
|
|
38
|
+
if name not in _EXPORTS:
|
|
39
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
40
|
+
|
|
41
|
+
value = _load_export(name)
|
|
42
|
+
globals()[name] = value
|
|
43
|
+
return value
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def __dir__() -> list[str]:
|
|
47
|
+
return sorted(set(globals()) | set(__all__))
|