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/checkml.py
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Parameters
|
|
3
|
+
----------
|
|
4
|
+
|
|
5
|
+
GENERAL
|
|
6
|
+
+++++++
|
|
7
|
+
|
|
8
|
+
csv_name : str, default=''
|
|
9
|
+
Name of the CSV file containing all the points used in the model (combining train + valid + test).
|
|
10
|
+
A path can be provided (i.e. 'C:/Users/FOLDER/FILE.csv'). By default, CheckML splits the
|
|
11
|
+
data with its standard protocol (EVEN split for regression, STRATIFIED for
|
|
12
|
+
classification, 20% test set). Optionally, include a 'Set' column with the value 'Test'
|
|
13
|
+
on the rows that should be held out as the test set (any other value, e.g. 'Training',
|
|
14
|
+
is used for CV) to analyze your own split. In that case, and also when using a
|
|
15
|
+
non-standard 'split' option, the PDF report contains all the analyses but no CheckML
|
|
16
|
+
score, since the score is calibrated for the standard split.
|
|
17
|
+
y : str, default=''
|
|
18
|
+
Name of the column containing the response variable in the input CSV file (i.e. 'solubility').
|
|
19
|
+
names : str, default=''
|
|
20
|
+
Column of the names for each datapoint. Names are used to print outliers.
|
|
21
|
+
eval_model : str, default='MVL'
|
|
22
|
+
Legacy option, only used as a fallback when none of model_obj/model_file/model_params
|
|
23
|
+
are provided. 'MVL' (Multivariate linear model, LinearRegression() in sklearn) is the
|
|
24
|
+
only value accepted here - use model_obj/model_file/model_params for any other model.
|
|
25
|
+
model_obj : object, default=None
|
|
26
|
+
An already-fitted scikit-learn estimator object (Python API only, e.g. from a Jupyter
|
|
27
|
+
notebook) to evaluate. Only its class and hyperparameters (via get_params()) are used -
|
|
28
|
+
VERIFY/PREDICT's repeated cross-validation always refits fresh copies per fold, so the
|
|
29
|
+
object's already-fitted weights themselves aren't reused.
|
|
30
|
+
model_file : str, default=''
|
|
31
|
+
Path to a fitted scikit-learn estimator saved with joblib/pickle. Same idea as
|
|
32
|
+
model_obj, loaded from disk instead of passed directly.
|
|
33
|
+
model_params : str, default=''
|
|
34
|
+
Path to a CSV with two columns, 'param' and 'value', listing the exact scikit-learn
|
|
35
|
+
class to use (a row with param='model', e.g. value='RandomForestRegressor') and its
|
|
36
|
+
hyperparameters (one row each, e.g. param='n_estimators', value=200). Only scikit-learn's
|
|
37
|
+
own registered estimators are accepted (see sklearn.utils.all_estimators()) - this never
|
|
38
|
+
imports or executes anything outside sklearn.
|
|
39
|
+
type : str, default='reg'
|
|
40
|
+
Type of the pedictions. Options:
|
|
41
|
+
1. 'reg' (Regressor)
|
|
42
|
+
2. 'clas' (Classifier)
|
|
43
|
+
seed : int, default=0
|
|
44
|
+
Random seed used in the ML predictor models and other protocols.
|
|
45
|
+
destination : str, default=None,
|
|
46
|
+
Directory to create the output file(s).
|
|
47
|
+
|
|
48
|
+
Affect VERIFY and PREDICT
|
|
49
|
+
+++++++++++++++++++++++++
|
|
50
|
+
|
|
51
|
+
kfold : int, default=5
|
|
52
|
+
Number of random data splits for the cross-validation of the models.
|
|
53
|
+
repeat_kfolds : int, default=10
|
|
54
|
+
Number of repetitions for the k-fold cross-validation of the models.
|
|
55
|
+
|
|
56
|
+
"""
|
|
57
|
+
#####################################################.
|
|
58
|
+
# This file stores the CHECKML class #
|
|
59
|
+
# used to evaluate existing models #
|
|
60
|
+
#####################################################.
|
|
61
|
+
|
|
62
|
+
import os
|
|
63
|
+
import sys
|
|
64
|
+
import json
|
|
65
|
+
import shutil
|
|
66
|
+
import time
|
|
67
|
+
import pandas as pd
|
|
68
|
+
from pathlib import Path
|
|
69
|
+
from robert.utils import (load_variables, finish_print, load_database, prepare_sets,
|
|
70
|
+
check_clas_problem, resolve_sklearn_estimator, model_adjust_params, _csv_row_numbers_txt,
|
|
71
|
+
serialize_model_params, parse_param_value)
|
|
72
|
+
from robert.generate_utils import set_sets
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _accepts_count_and_fraction(model_cls, param):
|
|
76
|
+
'''
|
|
77
|
+
True when scikit-learn's own parameter constraints of the estimator accept both an integer
|
|
78
|
+
count and a real-valued fraction for this hyperparameter (so 1 and 1.0 mean different things)
|
|
79
|
+
'''
|
|
80
|
+
|
|
81
|
+
import numbers
|
|
82
|
+
try:
|
|
83
|
+
from sklearn.utils._param_validation import Interval
|
|
84
|
+
except ImportError:
|
|
85
|
+
return False
|
|
86
|
+
constraints = getattr(model_cls, '_parameter_constraints', {}).get(param, [])
|
|
87
|
+
has_int, has_fraction = False, False
|
|
88
|
+
for constraint in constraints:
|
|
89
|
+
if not isinstance(constraint, Interval):
|
|
90
|
+
continue
|
|
91
|
+
if constraint.type is numbers.Integral:
|
|
92
|
+
has_int = True
|
|
93
|
+
elif (getattr(constraint.type, '__name__', '') == 'RealNotInt'
|
|
94
|
+
or (constraint.right is not None and constraint.right <= 1)):
|
|
95
|
+
# RealNotInt is how scikit-learn marks "a float, not an int" (the fraction form);
|
|
96
|
+
# its upper bound varies across versions (i.e. max_samples has none in 1.9)
|
|
97
|
+
has_fraction = True
|
|
98
|
+
return has_int and has_fraction
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def smiles_columns(csv_name):
|
|
102
|
+
'''
|
|
103
|
+
Columns named SMILES (any capitalization) of the input CSV. CheckML excludes them from the
|
|
104
|
+
descriptors automatically: they are only used to show molecules in interactive plots
|
|
105
|
+
'''
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
columns = pd.read_csv(csv_name, nrows=0, encoding='utf-8').columns
|
|
109
|
+
except (OSError, ValueError):
|
|
110
|
+
return []
|
|
111
|
+
return [col for col in columns if str(col).strip().lower() == 'smiles']
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class checkml:
|
|
115
|
+
"""
|
|
116
|
+
Class containing all the functions from the CHECKML module.
|
|
117
|
+
|
|
118
|
+
Parameters
|
|
119
|
+
----------
|
|
120
|
+
kwargs : argument class
|
|
121
|
+
Specify any arguments from the CHECKML module (for a complete list of variables, visit the ROBERT documentation)
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def __init__(self, **kwargs):
|
|
125
|
+
|
|
126
|
+
start_time = time.time()
|
|
127
|
+
|
|
128
|
+
# load default and user-specified variables
|
|
129
|
+
self.args = load_variables(kwargs, "checkml")
|
|
130
|
+
|
|
131
|
+
# clean folders from previous runs
|
|
132
|
+
_ = self.clean_eval()
|
|
133
|
+
|
|
134
|
+
# no --ignore/--discard in CHECKML (see the CheckML publication and
|
|
135
|
+
# docs/Report/checkml_database.rst): the CSV must contain ONLY the names, target and
|
|
136
|
+
# descriptors used by the model, so the evaluation (and the CSV shared in the Supporting
|
|
137
|
+
# Information) always matches the model. Only the names column (added by
|
|
138
|
+
# load_variables()), 'Set' and SMILES are excluded, and ROBERT handles them itself
|
|
139
|
+
user_excluded = [
|
|
140
|
+
col for col in self.args.ignore + self.args.discard
|
|
141
|
+
if col != self.args.names and str(col).strip().lower() not in ('set', 'smiles')
|
|
142
|
+
]
|
|
143
|
+
if user_excluded:
|
|
144
|
+
self.args.log.write(f"\nx The --ignore and --discard options are not available in CHECKML (columns requested: {user_excluded}). Remove these columns from the CSV: CheckML accepts ONLY the names, target and descriptors used by the model (plus an optional SMILES column, which is excluded from the descriptors automatically).")
|
|
145
|
+
self.args.log.finalize()
|
|
146
|
+
sys.exit()
|
|
147
|
+
for col in smiles_columns(self.args.csv_name):
|
|
148
|
+
if col not in self.args.ignore:
|
|
149
|
+
self.args.ignore.append(col)
|
|
150
|
+
|
|
151
|
+
# load database, discard user-defined descriptors and perform data checks
|
|
152
|
+
csv_df, csv_X, csv_y = load_database(self,self.args.csv_name,"checkml",print_info=False)
|
|
153
|
+
|
|
154
|
+
# unlike the normal ROBERT pipeline (where CURATE explicitly fills in or removes
|
|
155
|
+
# missing data before GENERATE ever sees it), CHECKML calls load_database() directly,
|
|
156
|
+
# and a descriptor with missing values would otherwise be silently dropped or imputed
|
|
157
|
+
# with zero warning - quietly changing which descriptors the model is evaluated on.
|
|
158
|
+
# Checked on the raw CSV (not csv_X, which load_database() may have already cleaned up
|
|
159
|
+
# by this point) so this always catches it, regardless of --auto_fill
|
|
160
|
+
raw_df = pd.read_csv(self.args.csv_name, encoding='utf-8')
|
|
161
|
+
expected_descriptors = [
|
|
162
|
+
col for col in raw_df.columns
|
|
163
|
+
if col not in self.args.ignore + self.args.discard + [self.args.y, self.args.names, 'Set']
|
|
164
|
+
]
|
|
165
|
+
for column in expected_descriptors:
|
|
166
|
+
rows_missing_x = raw_df[column].isna()
|
|
167
|
+
if rows_missing_x.any():
|
|
168
|
+
self.args.log.write(f"\nx The descriptor column ({column}) has empty values in row(s) {_csv_row_numbers_txt(rows_missing_x)} of {os.path.basename(self.args.csv_name)}! CHECKML does not fill in missing descriptors automatically (unlike CURATE in the full ROBERT workflow), please fill them in (or remove those rows, or remove that column from the CSV if the model doesn't use it) and run ROBERT again.")
|
|
169
|
+
self.args.log.finalize()
|
|
170
|
+
sys.exit()
|
|
171
|
+
|
|
172
|
+
# CHECKML scores the model on the descriptors exactly as they are in the CSV (unlike
|
|
173
|
+
# CURATE, there is no one-hot encoding of categorical variables), so text columns can't
|
|
174
|
+
# be used as descriptors (SMILES was already excluded above)
|
|
175
|
+
text_columns = [col for col in csv_X.columns if not pd.api.types.is_numeric_dtype(csv_X[col])]
|
|
176
|
+
if text_columns:
|
|
177
|
+
self.args.log.write(f"\nx The columns {text_columns} contain text, and CHECKML does not convert categorical variables (no one-hot encoding), so they can't be used as descriptors! Remove them from the CSV (CheckML accepts ONLY the names, target and descriptors used by the model, plus an optional SMILES column) or convert them to numbers.")
|
|
178
|
+
self.args.log.finalize()
|
|
179
|
+
sys.exit()
|
|
180
|
+
|
|
181
|
+
# adjust options of classification problems and detects whether the right type of problem was used
|
|
182
|
+
self = check_clas_problem(self,csv_df)
|
|
183
|
+
# check_clas_problem() converts csv_df's y column to integer class codes in place;
|
|
184
|
+
# csv_y was captured before that conversion, so it needs refreshing to stay in sync
|
|
185
|
+
csv_y = csv_df[self.args.y]
|
|
186
|
+
# class codes the model is trained on (used to translate/check class_weight keys)
|
|
187
|
+
self.class_values = sorted(csv_y.unique().tolist()) if self.args.type.lower() == 'clas' else []
|
|
188
|
+
|
|
189
|
+
# resolve which model to evaluate (an already-fitted object/file, a CSV of
|
|
190
|
+
# hyperparameters, or the legacy 'MVL' default) and validate it against --type
|
|
191
|
+
self.model_params_dict = self.resolve_eval_model()
|
|
192
|
+
|
|
193
|
+
# a user-provided 'Set' column picks the test set directly instead of the usual
|
|
194
|
+
# automatic split (see get_user_defined_test_points()); BO_opt=True re-enables the
|
|
195
|
+
# normal test_select()-based split when no such column/values are present
|
|
196
|
+
test_points = self.get_user_defined_test_points(csv_df)
|
|
197
|
+
Xy_data = prepare_sets(self,csv_df,csv_X,csv_y,test_points,self.args.names,None,None,None,BO_opt=(test_points is None))
|
|
198
|
+
|
|
199
|
+
# saves database and model params in the /GENERATE/Best_model/No_PFI folder
|
|
200
|
+
_ = self.save_generate(csv_df,Xy_data)
|
|
201
|
+
|
|
202
|
+
# finish the printing of the CHECKML info file
|
|
203
|
+
_ = finish_print(self,start_time,'CHECKML')
|
|
204
|
+
|
|
205
|
+
def clean_eval(self):
|
|
206
|
+
'''
|
|
207
|
+
Cleans folders from previous runs
|
|
208
|
+
'''
|
|
209
|
+
|
|
210
|
+
for folder in ['CURATE','GENERATE','VERIFY','PREDICT']:
|
|
211
|
+
eval_folder = f'{Path(os.getcwd()).joinpath(folder)}'
|
|
212
|
+
if os.path.exists(eval_folder):
|
|
213
|
+
shutil.rmtree(eval_folder)
|
|
214
|
+
|
|
215
|
+
def resolve_eval_model(self):
|
|
216
|
+
'''
|
|
217
|
+
Decide which model CHECKML will evaluate, and its hyperparameters. Priority order
|
|
218
|
+
(most specific/explicit first): an already-fitted model object (model_obj, Python API
|
|
219
|
+
only) -> a fitted model saved with joblib/pickle (model_file) -> a CSV naming a
|
|
220
|
+
scikit-learn class and its hyperparameters (model_params) -> the legacy eval_model
|
|
221
|
+
option (default 'MVL').
|
|
222
|
+
|
|
223
|
+
A fitted model's own get_params() is read directly, so the user never has to retype
|
|
224
|
+
hyperparameters by hand - only its class and hyperparameters are kept, since
|
|
225
|
+
repeated_kfold_cv() always refits fresh copies of the model per fold (the object's
|
|
226
|
+
already-fitted weights aren't reused as-is).
|
|
227
|
+
|
|
228
|
+
Sets self.args.eval_model to the resolved class name (used everywhere downstream -
|
|
229
|
+
VERIFY/PREDICT load models the same way regardless of where the name came from) and
|
|
230
|
+
returns the resolved hyperparameters dict.
|
|
231
|
+
'''
|
|
232
|
+
|
|
233
|
+
# deep=False: only the estimator's own constructor arguments - the default deep=True
|
|
234
|
+
# also returns nested keys (i.e. 'kernel__k1' of a GP kernel or 'estimator__max_depth'
|
|
235
|
+
# of a Bagging/AdaBoost base estimator), which the constructor doesn't accept
|
|
236
|
+
if self.args.model_obj is not None:
|
|
237
|
+
model_obj = self.args.model_obj
|
|
238
|
+
model_name = type(model_obj).__name__
|
|
239
|
+
params = model_obj.get_params(deep=False)
|
|
240
|
+
self.args.log.write(f"\no Using the model object passed directly (model_obj): {model_name}")
|
|
241
|
+
|
|
242
|
+
elif self.args.model_file:
|
|
243
|
+
import joblib
|
|
244
|
+
if not os.path.exists(self.args.model_file):
|
|
245
|
+
self.args.log.write(f"\nx WARNING! The model_file specified ({self.args.model_file}) does not exist!")
|
|
246
|
+
sys.exit()
|
|
247
|
+
model_obj = joblib.load(self.args.model_file)
|
|
248
|
+
model_name = type(model_obj).__name__
|
|
249
|
+
params = model_obj.get_params(deep=False)
|
|
250
|
+
self.args.log.write(f"\no Loaded a pre-fitted model from {self.args.model_file}: {model_name}")
|
|
251
|
+
|
|
252
|
+
elif self.args.model_params:
|
|
253
|
+
if not os.path.exists(self.args.model_params):
|
|
254
|
+
self.args.log.write(f"\nx WARNING! The model_params CSV specified ({self.args.model_params}) does not exist!")
|
|
255
|
+
sys.exit()
|
|
256
|
+
params_df = pd.read_csv(self.args.model_params, encoding='utf-8')
|
|
257
|
+
if not {'param','value'}.issubset(params_df.columns):
|
|
258
|
+
self.args.log.write(f"\nx WARNING! The model_params CSV must have 'param' and 'value' columns!")
|
|
259
|
+
sys.exit()
|
|
260
|
+
# stray spaces around names (i.e. " max_depth") would otherwise make the
|
|
261
|
+
# constructor reject the hyperparameter
|
|
262
|
+
rows = {str(param).strip(): value for param, value in zip(params_df['param'], params_df['value'])
|
|
263
|
+
if not pd.isna(param) and str(param).strip() != ''}
|
|
264
|
+
if 'model' not in rows:
|
|
265
|
+
self.args.log.write(f"\nx WARNING! The model_params CSV must include a row with param='model' naming the scikit-learn class to use (e.g. value='RandomForestRegressor')!")
|
|
266
|
+
sys.exit()
|
|
267
|
+
model_name = str(rows.pop('model')).strip()
|
|
268
|
+
# values come from a CSV as plain text - recover their real type (int/float/bool/
|
|
269
|
+
# None/list/dict) where possible, otherwise keep the literal string (e.g. solver
|
|
270
|
+
# names). Empty cells/none/null -> None and TRUE/FALSE (Excel) -> bool
|
|
271
|
+
params = {param: parse_param_value(value) for param, value in rows.items()}
|
|
272
|
+
self.args.log.write(f"\no Using the model and hyperparameters from {self.args.model_params}: {model_name}")
|
|
273
|
+
|
|
274
|
+
else:
|
|
275
|
+
# legacy default - MVL/LinearRegression, unchanged behavior
|
|
276
|
+
model_name = self.args.eval_model
|
|
277
|
+
params = {}
|
|
278
|
+
|
|
279
|
+
# validate the resolved model against --type before committing to it - a dynamic
|
|
280
|
+
# scikit-learn model (anything other than the legacy 'MVL') must exist as a real
|
|
281
|
+
# sklearn estimator of the requested type (see resolve_sklearn_estimator())
|
|
282
|
+
if model_name != 'MVL':
|
|
283
|
+
if resolve_sklearn_estimator(model_name, self.args.type) is None:
|
|
284
|
+
other_type = 'clas' if self.args.type.lower() == 'reg' else 'reg'
|
|
285
|
+
if resolve_sklearn_estimator(model_name, other_type) is not None:
|
|
286
|
+
self.args.log.write(f"\nx WARNING! '{model_name}' is a {other_type} estimator, but type='{self.args.type}' was used. Set type='{other_type}' instead.")
|
|
287
|
+
else:
|
|
288
|
+
self.args.log.write(f"\nx WARNING! '{model_name}' is not a valid scikit-learn {self.args.type} estimator name (or isn't available in this scikit-learn version). Check the exact class name (e.g., 'RandomForestRegressor').")
|
|
289
|
+
sys.exit()
|
|
290
|
+
|
|
291
|
+
self.args.eval_model = model_name
|
|
292
|
+
|
|
293
|
+
# fills in random_state from --seed only if the class accepts one AND the user didn't
|
|
294
|
+
# already set their own - an explicit value is respected as-is (see model_adjust_params())
|
|
295
|
+
params = model_adjust_params(self, model_name, params)
|
|
296
|
+
|
|
297
|
+
if model_name != 'MVL':
|
|
298
|
+
params = self.adjust_class_weight(params)
|
|
299
|
+
self.validate_params(model_name, params)
|
|
300
|
+
|
|
301
|
+
return params
|
|
302
|
+
|
|
303
|
+
def adjust_class_weight(self,params):
|
|
304
|
+
'''
|
|
305
|
+
ROBERT trains classifiers on integer class codes. A class_weight dict typed with the
|
|
306
|
+
original labels (i.e. {'active': 3, 'inactive': 1}, when the y column has text labels
|
|
307
|
+
that check_clas_problem() converted to 0/1) is translated to those codes, and keys that
|
|
308
|
+
match no class stop the run with a clear message instead of scikit-learn's
|
|
309
|
+
"The classes, [0, 1], are not in class_weight" in the middle of VERIFY.
|
|
310
|
+
'''
|
|
311
|
+
|
|
312
|
+
class_weight = params.get('class_weight')
|
|
313
|
+
if self.args.type.lower() != 'clas' or not isinstance(class_weight, dict):
|
|
314
|
+
return params
|
|
315
|
+
|
|
316
|
+
mapping = getattr(self.args, 'class_mapping', None) or {}
|
|
317
|
+
mapping_txt = {str(label): code for label, code in mapping.items()}
|
|
318
|
+
codes_txt = {str(code): code for code in self.class_values}
|
|
319
|
+
translated = {}
|
|
320
|
+
for key, weight in class_weight.items():
|
|
321
|
+
if key in self.class_values:
|
|
322
|
+
translated[key] = weight
|
|
323
|
+
elif key in mapping:
|
|
324
|
+
translated[mapping[key]] = weight
|
|
325
|
+
elif str(key) in mapping_txt:
|
|
326
|
+
translated[mapping_txt[str(key)]] = weight
|
|
327
|
+
elif str(key) in codes_txt:
|
|
328
|
+
translated[codes_txt[str(key)]] = weight
|
|
329
|
+
else:
|
|
330
|
+
valid = list(mapping) if mapping else self.class_values
|
|
331
|
+
self.args.log.write(f"\nx WARNING! The class_weight key {key!r} doesn't match any class of the y column (classes: {valid})! Use the class values of the y column as keys (i.e. class_weight={{{valid[0]!r}: 1, {valid[-1]!r}: 2}}) or class_weight='balanced'.")
|
|
332
|
+
self.args.log.finalize()
|
|
333
|
+
sys.exit()
|
|
334
|
+
if mapping and translated != class_weight:
|
|
335
|
+
self.args.log.write(f"\no class_weight keys converted to the class codes used by ROBERT: {class_weight} -> {translated}")
|
|
336
|
+
params['class_weight'] = translated
|
|
337
|
+
return params
|
|
338
|
+
|
|
339
|
+
def validate_params(self,model_name,params):
|
|
340
|
+
'''
|
|
341
|
+
Check the hyperparameters with scikit-learn's own validation before running anything, so
|
|
342
|
+
a typo (i.e. criterion='ginni' or an unknown parameter name) gives a clear message here
|
|
343
|
+
instead of a traceback in the middle of VERIFY.
|
|
344
|
+
'''
|
|
345
|
+
|
|
346
|
+
model_cls = resolve_sklearn_estimator(model_name, self.args.type)
|
|
347
|
+
try:
|
|
348
|
+
estimator = model_cls(**params)
|
|
349
|
+
# sklearn >= 1.2 (constraint-based validation, otherwise only checked during fit())
|
|
350
|
+
if hasattr(estimator, '_validate_params'):
|
|
351
|
+
estimator._validate_params()
|
|
352
|
+
except (TypeError, ValueError) as error:
|
|
353
|
+
self.args.log.write(f"\nx WARNING! Invalid hyperparameters for {model_name}: {error}")
|
|
354
|
+
self.args.log.finalize()
|
|
355
|
+
sys.exit()
|
|
356
|
+
|
|
357
|
+
# parameters that accept BOTH a count (int) and a fraction (float in (0, 1]) - i.e.
|
|
358
|
+
# max_samples, max_features, min_samples_split - mean very different things for 1 and
|
|
359
|
+
# 1.0: the integer 1 is ONE sample/feature, 1.0 is ALL of them. A CSV edited in Excel
|
|
360
|
+
# saves 1.0 as 1, which silently turns "all" into "one" and makes near-constant
|
|
361
|
+
# predictions. The value is valid, so it's kept as given, but flagged (REPORT reads
|
|
362
|
+
# this line, see get_warning_lines())
|
|
363
|
+
for param, value in params.items():
|
|
364
|
+
if type(value) is int and value == 1 and _accepts_count_and_fraction(model_cls, param):
|
|
365
|
+
self.args.log.write(f"\nx WARNING! Ambiguous hyperparameter: {param} = 1 is an integer, so scikit-learn reads it as ONE (sample/feature), not all of them. If all of them were intended, use the fraction 1.0 (spreadsheet programs like Excel may save 1.0 as 1 in CSV files).")
|
|
366
|
+
|
|
367
|
+
def get_user_defined_test_points(self,csv_df):
|
|
368
|
+
'''
|
|
369
|
+
Detects a user-provided 'Set' column marking which points to hold out as the test set
|
|
370
|
+
(rows with value 'Test', case-insensitive), instead of auto-splitting with
|
|
371
|
+
test_select(). Returns None if no such column/values are present, so the caller falls
|
|
372
|
+
back to the normal automatic split.
|
|
373
|
+
'''
|
|
374
|
+
|
|
375
|
+
if 'Set' not in csv_df.columns:
|
|
376
|
+
return None
|
|
377
|
+
|
|
378
|
+
set_col = csv_df['Set'].astype(str).str.strip().str.lower()
|
|
379
|
+
test_mask = set_col == 'test'
|
|
380
|
+
if not test_mask.any():
|
|
381
|
+
self.args.log.write("\nx WARNING! The input CSV has a 'Set' column but no rows marked 'Test', so the column was ignored and CheckML's standard automatic split was used.")
|
|
382
|
+
return None
|
|
383
|
+
|
|
384
|
+
test_points = csv_df.index[test_mask].tolist()
|
|
385
|
+
# (this sentence is detected by REPORT to hide the score, see print_score() in report.py)
|
|
386
|
+
self.args.log.write(f"\no Using the 'Set' column from the input CSV to select the test set ({len(test_points)} points) instead of an automatic split.")
|
|
387
|
+
self.args.log.write("\nx WARNING! With a user-defined test set, the PDF report includes all the analyses but NOT the CheckML score, which is calibrated for CheckML's standard split. Remove the 'Set' column from the CSV to obtain a score.")
|
|
388
|
+
return test_points
|
|
389
|
+
|
|
390
|
+
def save_generate(self,csv_df,Xy_data):
|
|
391
|
+
'''
|
|
392
|
+
Saves database and model params in the /GENERATE/Best_model/No_PFI folder
|
|
393
|
+
'''
|
|
394
|
+
|
|
395
|
+
# copy database with Set column
|
|
396
|
+
generate_folder = Path('GENERATE/Best_model/No_PFI')
|
|
397
|
+
if os.path.exists(generate_folder):
|
|
398
|
+
shutil.rmtree(generate_folder)
|
|
399
|
+
Path(generate_folder).mkdir(exist_ok=True, parents=True)
|
|
400
|
+
|
|
401
|
+
# include the Set column to differentiate between train and test sets (and external test, if any)
|
|
402
|
+
csv_df = set_sets(csv_df,Xy_data)
|
|
403
|
+
|
|
404
|
+
_ = csv_df.to_csv(f'{generate_folder}/{self.args.eval_model}_db.csv', index = None, header=True)
|
|
405
|
+
|
|
406
|
+
# save all the parameters of the model
|
|
407
|
+
df_params = pd.DataFrame()
|
|
408
|
+
df_params['kfold'] = [self.args.kfold]
|
|
409
|
+
df_params['repeat_kfolds'] = [self.args.repeat_kfolds]
|
|
410
|
+
df_params['model'] = [self.args.eval_model]
|
|
411
|
+
df_params['type'] = [self.args.type]
|
|
412
|
+
df_params['seed'] = [self.args.seed]
|
|
413
|
+
df_params['y'] = [self.args.y]
|
|
414
|
+
df_params['names'] = [self.args.names]
|
|
415
|
+
df_params['error_type'] = [self.args.error_type]
|
|
416
|
+
# serialize_model_params() keeps objects (i.e. GP kernels, base estimators), tuples and
|
|
417
|
+
# dicts with numeric keys (i.e. class_weight) exactly as they are - plain JSON would turn
|
|
418
|
+
# them into text that VERIFY/PREDICT can't use to rebuild the model
|
|
419
|
+
df_params['params'] = serialize_model_params(self.model_params_dict)
|
|
420
|
+
df_params['X_descriptors'] = [list(Xy_data['X_descriptors'])]
|
|
421
|
+
|
|
422
|
+
# class label mapping for text targets (i.e. "active"/"inactive"), saved the same way
|
|
423
|
+
# as in GENERATE so VERIFY/PREDICT restore the original labels in confusion matrices
|
|
424
|
+
# and prediction CSVs instead of showing the 0/1/2... codes
|
|
425
|
+
if hasattr(self.args, 'class_mapping_reverse'):
|
|
426
|
+
df_params['class_mapping_reverse'] = [json.dumps(
|
|
427
|
+
{int(code): str(label) for code, label in self.args.class_mapping_reverse.items()}
|
|
428
|
+
)]
|
|
429
|
+
if hasattr(self.args, 'class_0_label'):
|
|
430
|
+
df_params['class_0_label'] = [self.args.class_0_label]
|
|
431
|
+
df_params['class_1_label'] = [self.args.class_1_label]
|
|
432
|
+
|
|
433
|
+
_ = df_params.to_csv(f'{generate_folder}/{self.args.eval_model}.csv', index = None, header=True)
|
robert/checkml_score.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Shared CheckML score rounding and tier helpers."""
|
|
2
|
+
|
|
3
|
+
from decimal import Decimal, ROUND_HALF_UP
|
|
4
|
+
|
|
5
|
+
_TIER_COLORS = {
|
|
6
|
+
'VERY WEAK': {'rgb': (1.0, 0.42, 0.42), 'text_hex': '#b00020'},
|
|
7
|
+
'WEAK': {'rgb': (1.0, 0.55, 0.29), 'text_hex': '#c85f24'},
|
|
8
|
+
'MODERATE': {'rgb': (1.0, 0.79, 0.38), 'text_hex': '#a77b16'},
|
|
9
|
+
'STRONG': {'rgb': (0.60, 0.78, 0.95), 'text_hex': '#276dd6'},
|
|
10
|
+
'VERY STRONG': {'rgb': (0.38, 0.60, 0.80), 'text_hex': '#1b5e20'},
|
|
11
|
+
'UNKNOWN': {'rgb': (0.4, 0.4, 0.4), 'text_hex': '#666666'},
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def round_checkml_score(score):
|
|
16
|
+
"""Round a 0-10 CheckML score to its displayed integer, using half-up rounding."""
|
|
17
|
+
return int(Decimal(str(score)).quantize(Decimal('1'), rounding=ROUND_HALF_UP))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def checkml_score_tier(score):
|
|
21
|
+
"""Return the five-tier label used by the 0-10 CheckML score bars."""
|
|
22
|
+
score = round_checkml_score(score)
|
|
23
|
+
if score <= 2:
|
|
24
|
+
return 'VERY WEAK'
|
|
25
|
+
if score <= 4:
|
|
26
|
+
return 'WEAK'
|
|
27
|
+
if score <= 6:
|
|
28
|
+
return 'MODERATE'
|
|
29
|
+
if score <= 8:
|
|
30
|
+
return 'STRONG'
|
|
31
|
+
return 'VERY STRONG'
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def checkml_tier_color(tier, output='rgb'):
|
|
35
|
+
"""Return a score tier/status fill RGB, CSS hex equivalent, or darker text hex."""
|
|
36
|
+
if tier not in _TIER_COLORS:
|
|
37
|
+
raise ValueError(f'unknown CheckML score tier: {tier!r}')
|
|
38
|
+
palette = _TIER_COLORS[tier]
|
|
39
|
+
if output == 'rgb':
|
|
40
|
+
return palette['rgb']
|
|
41
|
+
if output == 'text_hex':
|
|
42
|
+
return palette['text_hex']
|
|
43
|
+
if output == 'hex':
|
|
44
|
+
return '#{:02x}{:02x}{:02x}'.format(*(round(channel * 255) for channel in palette['rgb']))
|
|
45
|
+
raise ValueError("output must be 'rgb', 'hex', or 'text_hex'")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def checkml_score_color(score, output='rgb'):
|
|
49
|
+
"""Return the color for a score's rounded tier."""
|
|
50
|
+
return checkml_tier_color(checkml_score_tier(score), output=output)
|