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/report_utils.py
ADDED
|
@@ -0,0 +1,2270 @@
|
|
|
1
|
+
#####################################################.
|
|
2
|
+
# This file stores functions from REPORT #
|
|
3
|
+
#####################################################.
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import re
|
|
8
|
+
import glob
|
|
9
|
+
import pandas as pd
|
|
10
|
+
import numpy as np
|
|
11
|
+
import textwrap
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import ast
|
|
14
|
+
from decimal import Decimal, ROUND_HALF_UP
|
|
15
|
+
from robert.utils import boundary_n_points, deserialize_model_params
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
title_no_pfi = 'No PFI (standard descriptor filter):'
|
|
19
|
+
title_pfi = 'PFI (only important descriptors):'
|
|
20
|
+
|
|
21
|
+
# shared left indent for the Boundary robustness column in Section A, so the caption, the
|
|
22
|
+
# description text (even once it wraps) and the metrics line below all share one left edge
|
|
23
|
+
BOUNDARY_INDENT = '18px'
|
|
24
|
+
|
|
25
|
+
def get_csv_names(self,command_line):
|
|
26
|
+
"""
|
|
27
|
+
Detects the options from a command line or add them from manual inputs
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
csv_name = ''
|
|
31
|
+
if '--csv_name' in command_line:
|
|
32
|
+
csv_name = command_line.split('--csv_name')[1].split()[0]
|
|
33
|
+
csv_name = remove_quot(csv_name)
|
|
34
|
+
|
|
35
|
+
csv_test = ''
|
|
36
|
+
if '--csv_test' in command_line:
|
|
37
|
+
csv_test = command_line.split('--csv_test')[1].split()[0]
|
|
38
|
+
csv_test = remove_quot(csv_test)
|
|
39
|
+
|
|
40
|
+
if self.args.csv_name == '':
|
|
41
|
+
self.args.csv_name = csv_name
|
|
42
|
+
|
|
43
|
+
if self.args.csv_test == '':
|
|
44
|
+
self.args.csv_test = csv_test
|
|
45
|
+
|
|
46
|
+
return self
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def remove_quot(name):
|
|
50
|
+
'''
|
|
51
|
+
Remove initial and final quotations from names
|
|
52
|
+
'''
|
|
53
|
+
|
|
54
|
+
if name[0] in ['"',"'"]:
|
|
55
|
+
name = name[1:]
|
|
56
|
+
if name[-1] in ['"',"'"]:
|
|
57
|
+
name = name[:-1]
|
|
58
|
+
|
|
59
|
+
return name
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def get_outliers(file,suffix,spacing):
|
|
63
|
+
"""
|
|
64
|
+
Retrieve the summary of results from the PREDICT and VERIFY dat files
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
with open(file, 'r', encoding='utf-8') as datfile:
|
|
68
|
+
lines = datfile.readlines()
|
|
69
|
+
train_outliers,test_outliers = [],[]
|
|
70
|
+
for i,line in enumerate(lines):
|
|
71
|
+
if suffix == 'No PFI':
|
|
72
|
+
if 'o Outliers plot saved' in line and 'No_PFI.png' in line:
|
|
73
|
+
train_outliers,test_outliers = locate_outliers(i,lines)
|
|
74
|
+
if suffix == 'PFI':
|
|
75
|
+
if 'o Outliers plot saved' in line and 'No_PFI.png' not in line:
|
|
76
|
+
train_outliers,test_outliers = locate_outliers(i,lines)
|
|
77
|
+
|
|
78
|
+
summary = []
|
|
79
|
+
# add the outlier part
|
|
80
|
+
summary.append(f'\n{spacing*2}<u>Outliers (max. 10 shown)</u>\n')
|
|
81
|
+
summary = summary + train_outliers + test_outliers
|
|
82
|
+
|
|
83
|
+
summary = f'{spacing*2}'.join(summary)
|
|
84
|
+
|
|
85
|
+
# add columns
|
|
86
|
+
if suffix == 'No PFI':
|
|
87
|
+
title_col = title_no_pfi
|
|
88
|
+
elif suffix == 'PFI':
|
|
89
|
+
title_col = title_pfi
|
|
90
|
+
|
|
91
|
+
column = f"""
|
|
92
|
+
<p style='margin-top:-18px'><span style="font-weight:bold;">{spacing*2}{title_col}</span></p>
|
|
93
|
+
<pre style="text-align: justify;">{summary}<br></pre>
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
return column
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def get_metrics(file,suffix,spacing):
|
|
100
|
+
"""
|
|
101
|
+
Retrieve the summary of results from the PREDICT dat files
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
with open(file, 'r', encoding='utf-8') as datfile:
|
|
105
|
+
lines = datfile.readlines()
|
|
106
|
+
start_results,stop_results = 0,0
|
|
107
|
+
for i,line in enumerate(lines):
|
|
108
|
+
if suffix == 'No PFI':
|
|
109
|
+
if 'o Summary of results' in line and 'No_PFI:' in line:
|
|
110
|
+
start_results = i+1
|
|
111
|
+
stop_results = i+6
|
|
112
|
+
if suffix == 'PFI':
|
|
113
|
+
if 'o Summary of results' in line and 'No_PFI:' not in line:
|
|
114
|
+
start_results = i+1
|
|
115
|
+
stop_results = i+6
|
|
116
|
+
|
|
117
|
+
# add the summary of results of PREDICT
|
|
118
|
+
start_results += 4 # skip informaton that aren't metrics
|
|
119
|
+
summary = []
|
|
120
|
+
for line in lines[start_results:stop_results+1]:
|
|
121
|
+
# the R2 of the cross-validated predictions is shown as Q2 (1 - PRESS/SS, see the
|
|
122
|
+
# abbreviations section); the test set keeps R2
|
|
123
|
+
if '-fold CV : R2' in line:
|
|
124
|
+
line = line.replace('R2','Q<sup>2</sup>',1)
|
|
125
|
+
elif 'R2' in line:
|
|
126
|
+
line = line.replace('R2','R<sup>2</sup>')
|
|
127
|
+
|
|
128
|
+
summary.append(f'{spacing}{line[8:]}')
|
|
129
|
+
|
|
130
|
+
summary = ''.join(summary)
|
|
131
|
+
|
|
132
|
+
column = f"""
|
|
133
|
+
<pre style="text-align: justify; margin-top: 10px;">{summary}</pre>
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
return column
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def get_boundary_metrics(data_score,suffix,spacing):
|
|
140
|
+
"""
|
|
141
|
+
Gather the Low/High (sorted CV) boundary robustness metrics for the CheckML score section.
|
|
142
|
+
Regression only - boundary robustness isn't defined for classification (see print_score()
|
|
143
|
+
in report.py)
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
# repeated-CV values from boundary_plot() (same methodology as interpolation)
|
|
147
|
+
low_val = data_score.get(f'scaled_rmse_low_{suffix}')
|
|
148
|
+
high_val = data_score.get(f'scaled_rmse_high_{suffix}')
|
|
149
|
+
if low_val is None or high_val is None:
|
|
150
|
+
return ''
|
|
151
|
+
|
|
152
|
+
metric_line = f'Scaled RMSE (Low, sorted CV) = {low_val}%.'
|
|
153
|
+
metric_line += f'<br>Scaled RMSE (High, sorted CV) = {high_val}%.'
|
|
154
|
+
|
|
155
|
+
indent = f'padding-left: {BOUNDARY_INDENT};' if spacing else ''
|
|
156
|
+
column = f"""
|
|
157
|
+
<pre style="margin-top: 10px; {indent} box-sizing: border-box;">{metric_line}</pre>
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
# architectural limitation of the algorithm itself (tree-based, nearest-neighbour), shown
|
|
161
|
+
# right below the Boundary robustness score: it holds whatever that score is on this split
|
|
162
|
+
limitation = extrapolation_limitation(data_score.get('ML_model',''))
|
|
163
|
+
if limitation:
|
|
164
|
+
column += f"""
|
|
165
|
+
<p style="margin-top: 2px; margin-bottom: 0px; {indent} box-sizing: border-box; font-size: 10.5px; color: #9e3a3a;"><i><b>Note:</b> {limitation[0].lower()} models can't predict values outside the training y range by design.</i></p>
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
return column
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def get_csv_metrics(file,suffix,spacing):
|
|
172
|
+
"""
|
|
173
|
+
Retrieve the csv_test results from the PREDICT dat file
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
results_line = ''
|
|
177
|
+
with open(file, 'r', encoding='utf-8') as datfile:
|
|
178
|
+
lines = datfile.readlines()
|
|
179
|
+
for i,line in enumerate(lines):
|
|
180
|
+
if suffix == 'No PFI':
|
|
181
|
+
if 'o Summary of results' in line and 'No_PFI:' in line:
|
|
182
|
+
for j in range(i,len(lines)):
|
|
183
|
+
if 'o SHAP' in lines[j]:
|
|
184
|
+
break
|
|
185
|
+
elif '- External test : ' in lines[j]:
|
|
186
|
+
results_line = lines[j][25:]
|
|
187
|
+
if suffix == 'PFI':
|
|
188
|
+
if 'o Summary of results' in line and 'No_PFI:' not in line:
|
|
189
|
+
for j in range(i,len(lines)):
|
|
190
|
+
if 'o SHAP' in lines[j]:
|
|
191
|
+
break
|
|
192
|
+
elif '- External test : ' in lines[j]:
|
|
193
|
+
results_line = lines[j][25:]
|
|
194
|
+
|
|
195
|
+
# start the csv_test section
|
|
196
|
+
metrics_dat = f'<p style="text-align: justify; margin-top: -15px; margin-bottom: -3px;">{spacing*2}<u>External test metrics</u></p>'
|
|
197
|
+
# add line with model metrics (if any)
|
|
198
|
+
if results_line != '':
|
|
199
|
+
metrics_dat += f'<p style="text-align: justify; margin-bottom: 35px;">{spacing*2}{results_line}</p>'
|
|
200
|
+
return metrics_dat
|
|
201
|
+
|
|
202
|
+
else:
|
|
203
|
+
return ''
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def get_csv_pred(suffix,path_csv_test,y_value,names,spacing):
|
|
207
|
+
"""
|
|
208
|
+
Retrieve the csv_test results from the PREDICT dat file
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
pred_line = ''
|
|
212
|
+
csv_test_file = None
|
|
213
|
+
# path_csv_test: the predictions files logged in THIS model's PREDICT dat file (see
|
|
214
|
+
# detect_predictions()). Picking from them - instead of listing every CSV in
|
|
215
|
+
# PREDICT/csv_test, which holds the files of every model with --all_models - keeps each
|
|
216
|
+
# report on its own model's predictions (i.e. MVL_PFI never shows RF_PFI's values)
|
|
217
|
+
paths = path_csv_test if isinstance(path_csv_test,(list,tuple)) else [path_csv_test]
|
|
218
|
+
for path in paths:
|
|
219
|
+
file = f'{os.getcwd()}/{path}'
|
|
220
|
+
if not os.path.exists(file):
|
|
221
|
+
continue
|
|
222
|
+
if suffix == 'No PFI' and file.endswith('_No_PFI.csv'):
|
|
223
|
+
csv_test_file = file
|
|
224
|
+
elif suffix == 'PFI' and file.endswith('_PFI.csv') and not file.endswith('_No_PFI.csv'):
|
|
225
|
+
csv_test_file = file
|
|
226
|
+
|
|
227
|
+
# this suffix has no matching csv_test predictions file (e.g. a model with no PFI variant
|
|
228
|
+
# under --all_models), skip the section instead of crashing with a NameError
|
|
229
|
+
if csv_test_file is None:
|
|
230
|
+
return ''
|
|
231
|
+
|
|
232
|
+
csv_test_df = pd.read_csv(csv_test_file, encoding='utf-8')
|
|
233
|
+
|
|
234
|
+
# start the csv_test section
|
|
235
|
+
pred_line = f'<p style="text-align: justify; margin-top: -15px; margin-bottom: -3px;">{spacing*2}<u>External test predictions (sorted, max. 20 shown)</u></p>'
|
|
236
|
+
|
|
237
|
+
# the actual file (this model and PFI variant), so it's clear which predictions are shown
|
|
238
|
+
pred_line += f'<p style="text-align: justify; margin-bottom: 20px;">{spacing*2}From /PREDICT/csv_test/{os.path.basename(csv_test_file)}</p>'
|
|
239
|
+
|
|
240
|
+
pred_line += '''<style>
|
|
241
|
+
th, td {
|
|
242
|
+
border:0.75px solid black;
|
|
243
|
+
border-collapse: collapse;
|
|
244
|
+
padding: 2px;
|
|
245
|
+
text-align: justify;
|
|
246
|
+
}
|
|
247
|
+
</style>
|
|
248
|
+
'''
|
|
249
|
+
|
|
250
|
+
y_val_exist = False
|
|
251
|
+
if f'{y_value}' in csv_test_df.columns:
|
|
252
|
+
y_val_exist = True
|
|
253
|
+
|
|
254
|
+
# adjust format of headers
|
|
255
|
+
names_head = names
|
|
256
|
+
if len(str(names_head)) > 12:
|
|
257
|
+
names_head = f'{str(names_head[:9])}...'
|
|
258
|
+
y_value_head = y_value
|
|
259
|
+
if len(str(y_value_head)) > 12:
|
|
260
|
+
y_value_head = f'{str(y_value_head[:9])}...'
|
|
261
|
+
|
|
262
|
+
margin_left = 0
|
|
263
|
+
|
|
264
|
+
pred_line += f'''
|
|
265
|
+
<table style="width:91%; margin-left: {margin_left}px; margin-top: 20px">
|
|
266
|
+
<tr>
|
|
267
|
+
<td><strong>{names_head}</strong></td>'''
|
|
268
|
+
if y_val_exist:
|
|
269
|
+
pred_line += f'''
|
|
270
|
+
<td><strong>{y_value_head}</strong></td>'''
|
|
271
|
+
if f'{y_value}_pred_sd' in csv_test_df:
|
|
272
|
+
pred_line += f'''
|
|
273
|
+
<td><strong>{y_value_head}_pred ± sd</strong></td>
|
|
274
|
+
</tr>'''
|
|
275
|
+
else:
|
|
276
|
+
pred_line += f'''
|
|
277
|
+
<td><strong>{y_value_head}_pred</strong></td>
|
|
278
|
+
</tr>'''
|
|
279
|
+
|
|
280
|
+
# retrieve and sort the values
|
|
281
|
+
if not y_val_exist:
|
|
282
|
+
csv_test_df[y_value] = csv_test_df[f'{y_value}_pred']
|
|
283
|
+
|
|
284
|
+
# in clas problems, there are no SD in the predictions (we use a list of 0s)
|
|
285
|
+
if f'{y_value}_pred_sd' in csv_test_df:
|
|
286
|
+
sd_list = csv_test_df[f'{y_value}_pred_sd']
|
|
287
|
+
else:
|
|
288
|
+
sd_list = [0] * len(csv_test_df[f'{y_value}_pred'])
|
|
289
|
+
|
|
290
|
+
y_pred_sorted, y_sorted, names_sorted, sd_sorted = (list(t) for t in zip(*sorted(zip(csv_test_df[f'{y_value}_pred'], csv_test_df[y_value], csv_test_df[names], sd_list), reverse=True)))
|
|
291
|
+
|
|
292
|
+
max_table = False
|
|
293
|
+
if len(y_pred_sorted) > 20:
|
|
294
|
+
max_table = True
|
|
295
|
+
|
|
296
|
+
count_entries = 0
|
|
297
|
+
for y_val_pred, y_val, name, sd in zip(y_pred_sorted, y_sorted, names_sorted, sd_sorted):
|
|
298
|
+
# adjust format of entries
|
|
299
|
+
if len(str(name)) > 12:
|
|
300
|
+
name = f'{str(name[:9])}...'
|
|
301
|
+
y_val_pred = round(y_val_pred, 2)
|
|
302
|
+
y_val = round(y_val, 2)
|
|
303
|
+
sd = round(sd, 2)
|
|
304
|
+
if f'{y_value}_pred_sd' in csv_test_df:
|
|
305
|
+
y_val_pred_formatted = f'{y_val_pred} ± {sd}'
|
|
306
|
+
else:
|
|
307
|
+
y_val_pred_formatted = f'{y_val_pred}'
|
|
308
|
+
add_entry = True
|
|
309
|
+
# if there are more than 20 predictions, only 20 values will be shown
|
|
310
|
+
if max_table and count_entries >= 10:
|
|
311
|
+
add_entry = False
|
|
312
|
+
if count_entries == 10:
|
|
313
|
+
pred_line += f'''
|
|
314
|
+
<tr>
|
|
315
|
+
<td>...</td>'''
|
|
316
|
+
if y_val_exist:
|
|
317
|
+
pred_line += f'''
|
|
318
|
+
<td>...</td>'''
|
|
319
|
+
pred_line += f'''
|
|
320
|
+
<td>...</td>
|
|
321
|
+
</tr>'''
|
|
322
|
+
elif count_entries >= (len(y_pred_sorted) - 10):
|
|
323
|
+
add_entry = True
|
|
324
|
+
if add_entry:
|
|
325
|
+
pred_line += f'''
|
|
326
|
+
<tr>
|
|
327
|
+
<td>{name}</td>'''
|
|
328
|
+
if y_val_exist:
|
|
329
|
+
pred_line += f'''
|
|
330
|
+
<td>{y_val}</td>'''
|
|
331
|
+
pred_line += f'''
|
|
332
|
+
<td>{y_val_pred_formatted}</td>
|
|
333
|
+
</tr>'''
|
|
334
|
+
count_entries += 1
|
|
335
|
+
|
|
336
|
+
pred_line += f'''
|
|
337
|
+
</table>
|
|
338
|
+
<p style="margin-bottom: 30px"></p>'''
|
|
339
|
+
|
|
340
|
+
return pred_line
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def detect_predictions(module_file):
|
|
344
|
+
"""
|
|
345
|
+
Check whether there are predictions from an external test set
|
|
346
|
+
"""
|
|
347
|
+
|
|
348
|
+
csv_test_exists = False
|
|
349
|
+
|
|
350
|
+
# summary of the external CSV test set (if any). Every predictions file this model wrote
|
|
351
|
+
# (No_PFI and PFI) is collected: get_csv_pred() picks the one of each report from this
|
|
352
|
+
# list, so a report can never show another model's predictions
|
|
353
|
+
y_value, names, paths_csv_test = '','',[]
|
|
354
|
+
with open(module_file, 'r', encoding= 'utf-8') as datfile:
|
|
355
|
+
lines = datfile.readlines()
|
|
356
|
+
for _,line in enumerate(lines):
|
|
357
|
+
if '- Target value:' in line:
|
|
358
|
+
y_value = ' '.join(line.split(':')[1:]).strip()
|
|
359
|
+
elif '- Names:' in line:
|
|
360
|
+
names = line.split()[-1]
|
|
361
|
+
elif 'External set with predicted results:' in line:
|
|
362
|
+
paths_csv_test.append(line.split('External set with predicted results:')[-1].strip())
|
|
363
|
+
csv_test_exists = True
|
|
364
|
+
|
|
365
|
+
return csv_test_exists, y_value, names, paths_csv_test
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def locate_outliers(i,lines):
|
|
369
|
+
"""
|
|
370
|
+
Returns the start and end of the PREDICT summary in the dat file
|
|
371
|
+
"""
|
|
372
|
+
|
|
373
|
+
train_outliers,test_outliers = [],[]
|
|
374
|
+
len_line = 54
|
|
375
|
+
for j in range(i+1,len(lines)):
|
|
376
|
+
if 'Train:' in lines[j]:
|
|
377
|
+
for k in range(j,len(lines)):
|
|
378
|
+
if 'Test:' in lines[k]:
|
|
379
|
+
break
|
|
380
|
+
elif len(train_outliers) <= 10: # 10 outliers and the line with the % of outliers
|
|
381
|
+
if len(lines[k][6:]) > len_line:
|
|
382
|
+
outlier_line = f'{lines[k][6:len_line+6]}\n{lines[k][len_line+6:]}'
|
|
383
|
+
else:
|
|
384
|
+
outlier_line = lines[k][6:]
|
|
385
|
+
train_outliers.append(outlier_line)
|
|
386
|
+
elif 'Test:' in lines[j]:
|
|
387
|
+
for k in range(j,len(lines)):
|
|
388
|
+
if len(lines[k].split()) == 0:
|
|
389
|
+
break
|
|
390
|
+
elif len(test_outliers) <= 10: # 10 outliers and the line with the % of outliers
|
|
391
|
+
if len(lines[k][6:]) > len_line:
|
|
392
|
+
outlier_line = f'{lines[k][6:len_line+6]}\n{lines[k][len_line+6:]}'
|
|
393
|
+
else:
|
|
394
|
+
outlier_line = lines[k][6:]
|
|
395
|
+
test_outliers.append(outlier_line)
|
|
396
|
+
|
|
397
|
+
if len(lines[j].split()) == 0:
|
|
398
|
+
break
|
|
399
|
+
|
|
400
|
+
return train_outliers,test_outliers
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def combine_cols(columns,align_top=False,right_offset=0,right_rule=None):
|
|
404
|
+
"""
|
|
405
|
+
Makes a string with multi-column lines
|
|
406
|
+
|
|
407
|
+
align_top=True uses align-items:flex-start instead of the flex default (stretch), so a
|
|
408
|
+
short column isn't forced to visually stretch down to match a much taller sibling (e.g.
|
|
409
|
+
Section B's rows, where one side can carry far more content/images than the other) -
|
|
410
|
+
default stays False (unchanged) everywhere else, since other sections haven't been
|
|
411
|
+
re-verified against this behavior change.
|
|
412
|
+
"""
|
|
413
|
+
|
|
414
|
+
column_data = ''
|
|
415
|
+
for index,column in enumerate(columns):
|
|
416
|
+
if len(columns) == 2 and index == 1 and right_offset:
|
|
417
|
+
rule = ''
|
|
418
|
+
relative = ''
|
|
419
|
+
if right_rule is not None:
|
|
420
|
+
rule_top,rule_height = right_rule
|
|
421
|
+
# Decorative overlay, positioned at the same x as Section A's rule. It is
|
|
422
|
+
# out of flow so the established flex widths and pagination stay unchanged.
|
|
423
|
+
relative = 'position:relative; '
|
|
424
|
+
rule = (
|
|
425
|
+
f'<span aria-hidden="true" style="position:absolute; left:{right_offset - 20}px; '
|
|
426
|
+
f'top:{rule_top}px; width:1.5px; height:{rule_height}px; background:#999999; '
|
|
427
|
+
'border-radius:1px; pointer-events:none;"></span>'
|
|
428
|
+
)
|
|
429
|
+
column_data += (
|
|
430
|
+
f'<div style="flex: 1;"><div style="padding-left: {right_offset}px; '
|
|
431
|
+
f'box-sizing: border-box; {relative}">{rule}{column}</div></div>'
|
|
432
|
+
)
|
|
433
|
+
else:
|
|
434
|
+
column_data += f'<div style="flex: 1;">{column}</div>'
|
|
435
|
+
|
|
436
|
+
align_style = 'align-items: flex-start;' if align_top else ''
|
|
437
|
+
combined_data = f"""
|
|
438
|
+
<div style="display: flex; {align_style}">
|
|
439
|
+
{column_data}
|
|
440
|
+
</div>
|
|
441
|
+
"""
|
|
442
|
+
|
|
443
|
+
return combined_data
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
# model families that can't predict outside the range of y values seen in training, by their
|
|
447
|
+
# architecture (not by how well a particular model was fitted): checked by name against
|
|
448
|
+
# ROBERT's own codes and scikit-learn/XGBoost/LightGBM/CatBoost class names (CHECKML)
|
|
449
|
+
EXTRAPOLATION_LIMITED_FAMILIES = [
|
|
450
|
+
# (family label, ROBERT codes, name patterns, why)
|
|
451
|
+
('Tree-based', {'RF','GB','ADAB'},
|
|
452
|
+
('forest','tree','boost','bagging','xgb','lgbm','catboost'),
|
|
453
|
+
'their predictions are piecewise constant and bounded by the y values seen in training'),
|
|
454
|
+
('Nearest-neighbour', set(),
|
|
455
|
+
('neighbor','neighbour','knn'),
|
|
456
|
+
'their predictions are averages of the y values seen in training'),
|
|
457
|
+
]
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def extrapolation_limitation(model_name):
|
|
461
|
+
'''
|
|
462
|
+
Returns (family label, reason) when the model can't extrapolate outside the training y
|
|
463
|
+
range by its architecture, otherwise None
|
|
464
|
+
'''
|
|
465
|
+
|
|
466
|
+
name = str(model_name or '').strip()
|
|
467
|
+
if not name:
|
|
468
|
+
return None
|
|
469
|
+
for family,codes,patterns,reason in EXTRAPOLATION_LIMITED_FAMILIES:
|
|
470
|
+
if name.upper() in codes or any(pattern in name.lower() for pattern in patterns):
|
|
471
|
+
return family,reason
|
|
472
|
+
return None
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def get_col_score(score_info,data_score,suffix,col,spacing):
|
|
476
|
+
"""
|
|
477
|
+
Gather the information regarding the score of the model, for the Interpolation (left)
|
|
478
|
+
or Boundary robustness (right) column
|
|
479
|
+
"""
|
|
480
|
+
|
|
481
|
+
ML_line_format = f'<p style="text-align: justify; margin-top: -10px; margin-bottom: 0px;">{spacing}'
|
|
482
|
+
part_line_format = f'<p style="text-align: justify; margin-top: 1px; margin-bottom: 0px;">{spacing}'
|
|
483
|
+
|
|
484
|
+
score_key = 'interp_score' if col == 'interpolation' else 'extrap_score'
|
|
485
|
+
score_val = data_score.get(f'{score_key}_{suffix}', 0)
|
|
486
|
+
# the number itself is uncalibrated for a non-standard CV/test split (see score_available_
|
|
487
|
+
# {suffix} in calc_score()) just like the bar/tier label below it (see score_gray_N.jpg in
|
|
488
|
+
# print_score()) - shown as N/A instead of a real-looking number that could be misread as a
|
|
489
|
+
# trustworthy score
|
|
490
|
+
score_display = score_val if data_score.get(f'score_available_{suffix}', True) else 'N/A'
|
|
491
|
+
score_title = f''' · Score {score_display}'''
|
|
492
|
+
|
|
493
|
+
if col == 'interpolation':
|
|
494
|
+
caption = f'{spacing}Interpolation{score_title}'
|
|
495
|
+
partitions_ratio = data_score['proportion_ratio_print'].split()[-1]
|
|
496
|
+
|
|
497
|
+
column = f"""<p style="margin-top:-18px;"><span style="font-weight:bold;">{caption}</span></p>
|
|
498
|
+
{ML_line_format}Model = {data_score['ML_model']} · Proportion CV:test = {partitions_ratio}</p>
|
|
499
|
+
{part_line_format}Points = {data_score[f'total_points_{suffix}']} (CV: {data_score[f'cv_points_{suffix}']}, test: {data_score[f'test_points_{suffix}']}) · Descript. = {data_score[f'points_descp_ratio_{suffix}'].split(':')[-1]}</p>
|
|
500
|
+
<p style="margin-top: 4px;">{score_info}
|
|
501
|
+
<p style="margin-bottom: 18px;"></p>
|
|
502
|
+
"""
|
|
503
|
+
|
|
504
|
+
else:
|
|
505
|
+
# single shared padding-left (not leading nbsp) so the caption, the description text
|
|
506
|
+
# (even once it wraps to a 2nd line) and the score bar all start at the same left edge
|
|
507
|
+
indent = f'padding-left: {BOUNDARY_INDENT};' if spacing else ''
|
|
508
|
+
|
|
509
|
+
# 2nd line (mirrors interpolation's "Points(...):descriptors" line so both score bars
|
|
510
|
+
# sit at the same height) - reports how many points fall in the bottom/top 20% (Low/
|
|
511
|
+
# High) folds that the boundary robustness score is actually computed from, out of the
|
|
512
|
+
# total. Uses total_points (train+validation+test), since the Low/High sorted CV is
|
|
513
|
+
# run over the whole dataset (see sort_n_load()), not just the train+validation pool.
|
|
514
|
+
total_points = data_score.get(f'total_points_{suffix}')
|
|
515
|
+
extreme_line = ''
|
|
516
|
+
if total_points:
|
|
517
|
+
# same rule used to build the Low/High partitions (20%, min. 4 points - see
|
|
518
|
+
# boundary_n_points() in utils.py)
|
|
519
|
+
fold_points = boundary_n_points(total_points)
|
|
520
|
+
extreme_line = f'Points in each 20% high/low folds = {fold_points}'
|
|
521
|
+
|
|
522
|
+
# Draw one out-of-flow rule from this heading down through the extrapolation row and
|
|
523
|
+
# callouts. It shares the callout border's x position and cannot change column sizing.
|
|
524
|
+
column = f"""<div style="position:relative; {indent} box-sizing: border-box;">
|
|
525
|
+
<span aria-hidden="true" style="position:absolute; left:-18px; top:0; width:1.5px; height:315px; background:#999999; border-radius:1px; pointer-events:none;"></span>
|
|
526
|
+
<p style="margin-top:-18px;"><span style="font-weight:bold;">Boundary robustness{score_title}</span></p>
|
|
527
|
+
<p style="margin-top: -10px; margin-bottom: 0px;">Full details in Section B</p>
|
|
528
|
+
<p style="margin-top: 1px; margin-bottom: 0px;">{extreme_line}</p>
|
|
529
|
+
<p style="margin-top: 4px;">{score_info}
|
|
530
|
+
<p style="margin-bottom: 18px;"></p>
|
|
531
|
+
</div>
|
|
532
|
+
"""
|
|
533
|
+
|
|
534
|
+
return column
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def score_badge_2(self,data_score,suffix,score_val):
|
|
538
|
+
'''
|
|
539
|
+
Returns (label, icon_path) for a 0-2 Section B sub-metric badge - the real score and its
|
|
540
|
+
colored bar normally, or "N/A" with a grayscale version of that SAME real bar (score_val
|
|
541
|
+
still picks which of the 3 fill patterns - 0, 1 or 2 - score_w_2_gray_N.jpg to use) when this
|
|
542
|
+
run's score isn't calibrated for (non-standard CV/test split - see score_available_{suffix}
|
|
543
|
+
in calc_score()). The underlying metric (Scaled RMSE, R2, etc.) is still real and shown
|
|
544
|
+
either way - only the 0-2 conversion's colored/labeled presentation is grayed out here, since
|
|
545
|
+
its thresholds assume the standard 10x repeated 5-fold CV / ~20% test split
|
|
546
|
+
'''
|
|
547
|
+
|
|
548
|
+
score_val_badge = int(float(Decimal(str(score_val)).quantize(Decimal('1'), rounding=ROUND_HALF_UP)))
|
|
549
|
+
if not data_score.get(f'score_available_{suffix}', True):
|
|
550
|
+
return 'N/A',f'{self._posix_uri(self.args.path_icons)}/score_w_2_gray_{score_val_badge}.jpg'
|
|
551
|
+
return f'{score_val:.1f} / 2',f'{self._posix_uri(self.args.path_icons)}/score_w_2_{score_val_badge}.jpg'
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def score_badge_1(self, data_score, suffix, score_val):
|
|
555
|
+
"""Return a 0-1 badge using the existing 0-2 bar artwork at double scale."""
|
|
556
|
+
score_val = max(0.0, min(1.0, float(score_val or 0)))
|
|
557
|
+
bar_value = score_val * 2
|
|
558
|
+
bar_badge = int(float(Decimal(str(bar_value)).quantize(Decimal('1'), rounding=ROUND_HALF_UP)))
|
|
559
|
+
icon_dir = self._posix_uri(self.args.path_icons)
|
|
560
|
+
if not data_score.get(f'score_available_{suffix}', True):
|
|
561
|
+
return 'N/A', f'{icon_dir}/score_w_2_gray_{bar_badge}.jpg'
|
|
562
|
+
return f'{score_val:.1f} / 1', f'{icon_dir}/score_w_2_{bar_badge}.jpg'
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
SCORE_INFO_SCHEME = 'checkml-info:'
|
|
566
|
+
|
|
567
|
+
# Scoring criteria shown in the "i" icons of Section B. They must match the equations used to
|
|
568
|
+
# calculate the scores (score_rmse_mcc(), calc_penalty_r2(), score_overfit(),
|
|
569
|
+
# score_mcc_difference()...) and the tables of docs/Report/score.rst
|
|
570
|
+
SCALED_RMSE_INFO = 'Scaled RMSE: +2 if ≤ 10%, +1 at 20%, 0 if ≥ 30% (linear).'
|
|
571
|
+
R2_PENALTY_INFO = '{metric} penalty: 0 if ≥ 0.8, -1 at 0.6, -2 if ≤ 0.4 (linear).'
|
|
572
|
+
MCC_INFO = 'MCC: +2 if ≥ 0.6, +1 at 0.3, 0 if ≤ 0 (linear).'
|
|
573
|
+
RATIO_INFO = '+2 if ≤ 1.25, +1 at 1.5, 0 if ≥ 1.75 (linear).'
|
|
574
|
+
DELTA_MCC_INFO = 'ΔMCC: +2 if ≤ 0.15, +1 at 0.30, 0 if ≥ 0.45 (linear).'
|
|
575
|
+
|
|
576
|
+
# CheckML score documentation. Every tab of the page has a direct link (#slug of the tab
|
|
577
|
+
# label, see docs/_static/tab_links.js), used to send each report item to its own tab.
|
|
578
|
+
# If a tab label changes in docs/Report/score.rst, its slug here has to change too.
|
|
579
|
+
SCORE_DOCS_URL = 'https://robert.readthedocs.io/en/latest/Report/score.html'
|
|
580
|
+
SCORE_DOCS_TABS = {
|
|
581
|
+
'warnings': 'list-of-warnings',
|
|
582
|
+
'cv_test_split': 'cv-test-split-diagnostic',
|
|
583
|
+
'calculation': 'how-is-the-score-calculated',
|
|
584
|
+
'interpolation': 'interpolation-0-to-10',
|
|
585
|
+
'flawed': '1-model-vs-flawed-models',
|
|
586
|
+
'cv_test': '2-3-cv-and-test-predictions',
|
|
587
|
+
'gap_diff': '4-5-train-validation-and-cv-test-comparisons',
|
|
588
|
+
'stability': '6-prediction-stability',
|
|
589
|
+
'boundary': 'boundary-robustness-0-to-10-for-regression-only',
|
|
590
|
+
'sorted_cv': '1a-and-2a-sorted-cv-rmse',
|
|
591
|
+
'spearman': '1b-and-2b-spearman-rank',
|
|
592
|
+
'degradation': '1c-and-2c-degradation-ratio',
|
|
593
|
+
'applicability': '3-applicability-domain-leverage',
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def score_docs_url(tab=None):
|
|
598
|
+
"""Link to the CheckML score documentation, opened at a specific tab when given."""
|
|
599
|
+
return f'{SCORE_DOCS_URL}#{SCORE_DOCS_TABS[tab]}' if tab else SCORE_DOCS_URL
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def docs_heading(text, tab):
|
|
603
|
+
"""Section B item heading that links to its own tab of the CheckML score documentation."""
|
|
604
|
+
return (f'<a href="{score_docs_url(tab)}" style="color:#1f4e85; text-decoration:underline;">'
|
|
605
|
+
f'{text}</a>')
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def score_info_icon(criteria_html):
|
|
609
|
+
"""
|
|
610
|
+
Small "i" icon placed next to a Section B score. The scoring criteria aren't printed in
|
|
611
|
+
the PDF: the icon is a link whose URI carries the criteria text, and add_score_info_popups()
|
|
612
|
+
turns each of those links into a PDF note that shows the criteria when hovering the icon.
|
|
613
|
+
"""
|
|
614
|
+
|
|
615
|
+
import html as html_lib
|
|
616
|
+
from urllib.parse import quote
|
|
617
|
+
|
|
618
|
+
text = re.sub(r'<br\s*/?>', '\n', criteria_html)
|
|
619
|
+
text = re.sub(r'<sup>2</sup>', '²', text)
|
|
620
|
+
# strip only real tags: the criteria contain bare "<" / ">" comparisons (e.g. "R2 < 0.5")
|
|
621
|
+
text = html_lib.unescape(re.sub(r'</?(?:i|b|u|span|sup|sub)\b[^>]*>', '', text))
|
|
622
|
+
text = '\n'.join(' '.join(line.split()) for line in text.split('\n') if line.strip())
|
|
623
|
+
icon = ('<span style="display:inline-block; width:11px; height:11px; border-radius:50%; '
|
|
624
|
+
'background-color:#3b6ea5; color:white; font-size:8.5px; font-weight:bold; '
|
|
625
|
+
'font-style:normal; font-family:Georgia, serif; text-align:center; line-height:11px; '
|
|
626
|
+
'vertical-align:1px;">i</span>')
|
|
627
|
+
return f'<a href="{SCORE_INFO_SCHEME}{quote(text)}" style="text-decoration:none;">{icon}</a>'
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def add_score_info_popups(pdf_bytes):
|
|
631
|
+
"""
|
|
632
|
+
Replace the score_info_icon() links with PDF notes (text annotations) covering the icon:
|
|
633
|
+
hovering the icon shows the scoring criteria in PDF viewers that support notes (Acrobat,
|
|
634
|
+
Edge, Firefox). The note has a transparent appearance so the HTML icon stays visible.
|
|
635
|
+
"""
|
|
636
|
+
|
|
637
|
+
from urllib.parse import unquote
|
|
638
|
+
import pymupdf
|
|
639
|
+
|
|
640
|
+
doc = pymupdf.open(stream=pdf_bytes, filetype='pdf')
|
|
641
|
+
for page in doc:
|
|
642
|
+
# WeasyPrint emits one link per box inside the <a> (the <a> and its icon <span>), so
|
|
643
|
+
# overlapping links with the same URI are merged into a single note
|
|
644
|
+
icons = []
|
|
645
|
+
for link in page.get_links():
|
|
646
|
+
uri = link.get('uri') or ''
|
|
647
|
+
if not uri.startswith(SCORE_INFO_SCHEME):
|
|
648
|
+
continue
|
|
649
|
+
page.delete_link(link)
|
|
650
|
+
rect = pymupdf.Rect(link['from'])
|
|
651
|
+
for icon in icons:
|
|
652
|
+
if icon[0] == uri and icon[1].intersects(rect):
|
|
653
|
+
icon[1] |= rect
|
|
654
|
+
break
|
|
655
|
+
else:
|
|
656
|
+
icons.append([uri, rect])
|
|
657
|
+
for uri,rect in icons:
|
|
658
|
+
annot = page.add_text_annot(rect.tl, unquote(uri[len(SCORE_INFO_SCHEME):]), icon='Help')
|
|
659
|
+
annot.set_info(title='Scoring criteria')
|
|
660
|
+
annot.set_rect(rect)
|
|
661
|
+
annot.set_opacity(0)
|
|
662
|
+
annot.update()
|
|
663
|
+
# empty appearance stream: some viewers ignore the opacity and would draw their
|
|
664
|
+
# own note icon over the HTML "i" icon
|
|
665
|
+
annot._setAP(b' ')
|
|
666
|
+
output = doc.tobytes(garbage=3, deflate=True)
|
|
667
|
+
doc.close()
|
|
668
|
+
return output
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def adv_flawed(suffix,data_score,spacing,pred_type):
|
|
672
|
+
"""
|
|
673
|
+
Gather the advanced analysis of flawed models
|
|
674
|
+
"""
|
|
675
|
+
|
|
676
|
+
score_flawed = data_score.get(f'flawed_mod_score_{suffix}', 0)
|
|
677
|
+
|
|
678
|
+
if score_flawed == 0:
|
|
679
|
+
flaw_result = f'The model predicts right for the right reasons.'
|
|
680
|
+
else:
|
|
681
|
+
flaw_result = f'Warning! The model probably has important flaws.'
|
|
682
|
+
|
|
683
|
+
# 4 VERIFY tests for regression (y-mean, y-shuffle, onehot, cluster); classification skips
|
|
684
|
+
# the cluster test (N/A - see cluster_test() in verify.py), so only 3 are actually scored
|
|
685
|
+
min_score = -8 if pred_type == 'reg' else -6
|
|
686
|
+
|
|
687
|
+
# adds a bit more space if there is no test set
|
|
688
|
+
score_adv_flawed = f'<p style="text-align: justify; margin-top: 3px; margin-bottom: 0px;">{spacing}'
|
|
689
|
+
degradation = 'RMSE increase' if pred_type == 'reg' else 'MCC decrease'
|
|
690
|
+
info = score_info_icon(f'Scoring from {min_score} to 0<br>Penalty per applicable test, from the {degradation} vs the original CV:'
|
|
691
|
+
f'<br>0 if ≥ 45%, -1 at 30%, -2 if ≤ 15% (linear).')
|
|
692
|
+
column = f"""
|
|
693
|
+
<p style="text-align: justify; margin-top: 0px; margin-bottom: 0px;">{spacing}<span style="font-weight:bold;">{docs_heading('1. Model vs "flawed" models','flawed')}</span> ({score_flawed:.1f} / 0) {info}</p>
|
|
694
|
+
{score_adv_flawed}{flaw_result}</p>
|
|
695
|
+
"""
|
|
696
|
+
|
|
697
|
+
return column
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
def adv_predict(self,suffix,data_score,spacing,pred_type):
|
|
701
|
+
"""
|
|
702
|
+
Gather the advanced analysis of predictive ability
|
|
703
|
+
|
|
704
|
+
Classification uses the same 0-2 scale as regression (see score_rmse_mcc()):
|
|
705
|
+
2 if MCC >= 0.6, 0 if MCC <= 0, linear in between
|
|
706
|
+
"""
|
|
707
|
+
|
|
708
|
+
score_predict = data_score.get(f'cv_score_combined_{suffix}', 0)
|
|
709
|
+
cv_type = data_score.get(f"cv_type_{suffix}", "10x 5-fold CV")
|
|
710
|
+
|
|
711
|
+
if pred_type == 'reg':
|
|
712
|
+
score_label,predict_image = score_badge_2(self,data_score,suffix,score_predict)
|
|
713
|
+
metric_type = ['Scaled RMSE','Q<sup>2</sup>'] # R2 of the CV predictions (see abbreviations)
|
|
714
|
+
scaled_rmse_cv = data_score.get(f'scaled_rmse_cv_{suffix}', 0)
|
|
715
|
+
r2_cv = data_score.get(f'r2_cv_{suffix}', 0)
|
|
716
|
+
|
|
717
|
+
predict_result = f'{metric_type[0]} ({cv_type}) = {scaled_rmse_cv}%.'
|
|
718
|
+
predict_result += f'<br>{spacing}{metric_type[1]} ({cv_type}) = {r2_cv}.'
|
|
719
|
+
thres_line = f'{SCALED_RMSE_INFO}<br>{R2_PENALTY_INFO.format(metric="Q<sup>2</sup>")}'
|
|
720
|
+
init_sep = f'<p style="text-align: justify; margin-top: 17px; margin-bottom: 0px;">{spacing}'
|
|
721
|
+
score_adv_pred = f'<p style="text-align: justify; margin-top: 3px; margin-bottom: 0px;">{spacing}'
|
|
722
|
+
info = score_info_icon(f'Scoring from 0 to 2<br>{thres_line}')
|
|
723
|
+
column = f"""{init_sep}<span style="font-weight:bold;">{docs_heading('2. CV predictions of the model','cv_test')}</span> ({score_label} <img src="file:///{predict_image}" alt="score" style="width: 13%">) {info}</p>
|
|
724
|
+
{score_adv_pred}{predict_result}</p>
|
|
725
|
+
"""
|
|
726
|
+
return column
|
|
727
|
+
else:
|
|
728
|
+
# Classification: reuse the same thresholds already computed into
|
|
729
|
+
# cv_score_combined_{suffix} via score_rmse_mcc(), instead of a second hand-rolled
|
|
730
|
+
# copy that could silently drift from the score actually feeding interp_score
|
|
731
|
+
mcc_cv = data_score.get(f'r2_cv_{suffix}', 0)
|
|
732
|
+
display_score = score_predict
|
|
733
|
+
|
|
734
|
+
score_label,predict_image = score_badge_2(self,data_score,suffix,display_score)
|
|
735
|
+
metric_type = ['MCC']
|
|
736
|
+
predict_result = f'{metric_type[0]} ({cv_type}) = {mcc_cv}.'
|
|
737
|
+
thres_line = MCC_INFO
|
|
738
|
+
|
|
739
|
+
init_sep = f'<p style="text-align: justify; margin-top: 17px; margin-bottom: 0px;">{spacing}'
|
|
740
|
+
score_adv_pred = f'<p style="text-align: justify; margin-top: 3px; margin-bottom: 0px;">{spacing}'
|
|
741
|
+
info = score_info_icon(f'Scoring from 0 to 2<br>{thres_line}')
|
|
742
|
+
column = f"""{init_sep}<span style="font-weight:bold;">{docs_heading('2. CV predictions of the model','cv_test')}</span> ({score_label} <img src="file:///{predict_image}" alt="score" style="width: 13%">) {info}</p>
|
|
743
|
+
{score_adv_pred}{predict_result}</p>
|
|
744
|
+
"""
|
|
745
|
+
return column
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def adv_test(self,suffix,data_score,spacing,pred_type):
|
|
749
|
+
"""
|
|
750
|
+
Gather the advanced analysis of predictive ability with the test set
|
|
751
|
+
"""
|
|
752
|
+
|
|
753
|
+
score_test = data_score.get(f'test_score_combined_{suffix}', 0)
|
|
754
|
+
|
|
755
|
+
if pred_type == 'reg':
|
|
756
|
+
score_label,test_image = score_badge_2(self,data_score,suffix,score_test)
|
|
757
|
+
metric_type = ['Scaled RMSE','R<sup>2</sup>']
|
|
758
|
+
predict_result = f'{metric_type[0]} (test set) = {data_score.get(f"scaled_rmse_test_{suffix}", 0)}%.'
|
|
759
|
+
predict_result += f'<br>{spacing}{metric_type[1]} (test set) = {data_score.get(f"r2_test_{suffix}", 0)}.'
|
|
760
|
+
thres_line = f'{SCALED_RMSE_INFO}<br>{R2_PENALTY_INFO.format(metric="R<sup>2</sup>")}'
|
|
761
|
+
score_adv_cv = f'<p style="text-align: justify; margin-top: 3px; margin-bottom: 0px;">{spacing}'
|
|
762
|
+
info = score_info_icon(f'Scoring from 0 to 2<br>{thres_line}')
|
|
763
|
+
column = f"""<p style="text-align: justify; margin-top: 17px; margin-bottom: 0px;">{spacing}<span style="font-weight:bold;">{docs_heading('3. Test set predictions','cv_test')}</span> ({score_label} <img src="file:///{test_image}" alt="score" style="width: 13%">) {info}</p>
|
|
764
|
+
{score_adv_cv}{predict_result}</p>
|
|
765
|
+
"""
|
|
766
|
+
return column
|
|
767
|
+
else:
|
|
768
|
+
# Classification: reuse the same thresholds already computed into
|
|
769
|
+
# test_score_combined_{suffix} via score_rmse_mcc(), instead of a second hand-rolled
|
|
770
|
+
# copy that could silently drift from the score actually feeding interp_score
|
|
771
|
+
test_mcc = data_score.get(f"r2_test_{suffix}", 0)
|
|
772
|
+
display_score = score_test
|
|
773
|
+
|
|
774
|
+
score_label,test_image = score_badge_2(self,data_score,suffix,display_score)
|
|
775
|
+
metric_type = ['MCC']
|
|
776
|
+
predict_result = f'{metric_type[0]} (test set) = {test_mcc}.'
|
|
777
|
+
thres_line = MCC_INFO
|
|
778
|
+
|
|
779
|
+
score_adv_cv = f'<p style="text-align: justify; margin-top: 3px; margin-bottom: 0px;">{spacing}'
|
|
780
|
+
info = score_info_icon(f'Scoring from 0 to 2<br>{thres_line}')
|
|
781
|
+
column = f"""<p style="text-align: justify; margin-top: 17px; margin-bottom: 0px;">{spacing}<span style="font-weight:bold;">{docs_heading('3. Test set predictions','cv_test')}</span> ({score_label} <img src="file:///{test_image}" alt="score" style="width: 13%">) {info}</p>
|
|
782
|
+
{score_adv_cv}{predict_result}</p>
|
|
783
|
+
"""
|
|
784
|
+
return column
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def adv_diff_test(self,suffix,data_score,spacing,pred_type):
|
|
788
|
+
"""
|
|
789
|
+
Gather the advanced analysis of difference in model performance between CV and test set.
|
|
790
|
+
For regression, we compare scaled RMSE. For classification, we compare Δ MCC.
|
|
791
|
+
"""
|
|
792
|
+
|
|
793
|
+
if pred_type == 'reg':
|
|
794
|
+
# Regression: use diff_scaled_rmse_score
|
|
795
|
+
score_diff_test = data_score.get(f'diff_scaled_rmse_score_{suffix}', 0)
|
|
796
|
+
score_label,diff_test_image = score_badge_2(self,data_score,suffix,score_diff_test)
|
|
797
|
+
|
|
798
|
+
diff_result = f'RMSE in test is {round(data_score[f"factor_scaled_rmse_{suffix}"],2)}*scaled RMSE (CV).'
|
|
799
|
+
|
|
800
|
+
thres_line = f'Ratio scaled RMSE (test) / scaled RMSE (CV):<br>{RATIO_INFO}'
|
|
801
|
+
else:
|
|
802
|
+
# Classification: use diff_mcc_score instead
|
|
803
|
+
score_diff_test = data_score.get(f'diff_mcc_score_{suffix}', 0)
|
|
804
|
+
score_label,diff_test_image = score_badge_2(self,data_score,suffix,score_diff_test)
|
|
805
|
+
|
|
806
|
+
# Calculate the absolute difference between CV MCC and test MCC
|
|
807
|
+
mcc_cv = data_score.get(f'r2_cv_{suffix}', 0)
|
|
808
|
+
mcc_test = data_score.get(f'r2_test_{suffix}', 0)
|
|
809
|
+
diff_mcc = round(abs(mcc_test - mcc_cv), 2)
|
|
810
|
+
|
|
811
|
+
diff_result = f'The ΔMCC between CV and test is {diff_mcc}.'
|
|
812
|
+
|
|
813
|
+
thres_line = DELTA_MCC_INFO
|
|
814
|
+
|
|
815
|
+
score_adv_diff = f'<p style="text-align: justify; margin-top: 3px; margin-bottom: 0px;">{spacing}'
|
|
816
|
+
info = score_info_icon(f'Scoring from 0 to 2<br>{thres_line}')
|
|
817
|
+
column = f"""<p style="text-align: justify; margin-top: 20px; margin-bottom: 0px;">{spacing}<span style="font-weight:bold;">{docs_heading('5. CV vs test consistency','gap_diff')}</span> ({score_label} <img src="file:///{diff_test_image}" alt="CheckML Score" style="width: 13%">) {info}</p>
|
|
818
|
+
{score_adv_diff}<i>Relative differences in values from sections 2 and 3.</i><br>
|
|
819
|
+
{spacing}{diff_result}</p>
|
|
820
|
+
"""
|
|
821
|
+
|
|
822
|
+
return column
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
def adv_cv_sd(self,suffix,data_score,spacing,pred_type='reg'):
|
|
826
|
+
"""
|
|
827
|
+
Interpolation item 6: prediction stability under resampling, combining three facets - each
|
|
828
|
+
scored 0-2 with its own threshold, final score is their average, rounded.
|
|
829
|
+
|
|
830
|
+
Regression:
|
|
831
|
+
(a) SD of the repeated-CV predictions in the test set (unchanged from before)
|
|
832
|
+
(b) SD of the out-of-fold CV predictions themselves in train+validation (new)
|
|
833
|
+
(c) how much the aggregate RMSE itself varies from repeat to repeat (new) - a
|
|
834
|
+
dataset-wide view of the same "how much does this depend on the random split"
|
|
835
|
+
question (a)/(b) ask per-point
|
|
836
|
+
|
|
837
|
+
Classification: the same three facets, adapted for a discrete label (see the 'clas'
|
|
838
|
+
branch in get_predict_scores() and print_predict() in predict_utils.py):
|
|
839
|
+
(a) disagreement rate between individual CV repeats and the majority-voted class, test set
|
|
840
|
+
(b) same, for the out-of-fold train+validation predictions
|
|
841
|
+
(c) coefficient of variation of the per-repeat MCC (instead of per-repeat RMSE)
|
|
842
|
+
"""
|
|
843
|
+
|
|
844
|
+
# cv_sd_score_{suffix} is only set once the "MCC/RMSE coefficient of variation" line is
|
|
845
|
+
# found in PREDICT's log (see get_predict_scores() above), which itself only prints when
|
|
846
|
+
# there's more than one CV repeat (shape[1] > 1 in predict_utils.py) - a non-standard
|
|
847
|
+
# --repeat_kfolds 1 run (already flagged elsewhere as score_available=False, but Section B
|
|
848
|
+
# still renders the real underlying metrics regardless - see print_score()) would otherwise
|
|
849
|
+
# never populate this key and crash here instead of falling back like every other facet
|
|
850
|
+
# ((a)/(b) below already use .get(...,0))
|
|
851
|
+
score_cv_sd = data_score.get(f'cv_sd_score_{suffix}', 0)
|
|
852
|
+
score_label,cv_r2_image = score_badge_2(self,data_score,suffix,score_cv_sd)
|
|
853
|
+
|
|
854
|
+
if pred_type == 'reg':
|
|
855
|
+
y_range_covered = round(data_score.get(f"cv_range_cov_{suffix}",0)*100)
|
|
856
|
+
cv_4sd = round(data_score.get(f"cv_4sd_{suffix}",0),1)
|
|
857
|
+
y_range_covered_train = round(data_score.get(f"cv_range_cov_train_{suffix}",0)*100)
|
|
858
|
+
cv_4sd_train = round(data_score.get(f"cv_4sd_train_{suffix}",0),1)
|
|
859
|
+
rmse_cv_pct = data_score.get(f'rmse_cv_pct_{suffix}',0)
|
|
860
|
+
|
|
861
|
+
cv_sd_result = (
|
|
862
|
+
f'(a) Test SD, 4*SD = {cv_4sd} ({y_range_covered}% y-range)'
|
|
863
|
+
f'<br>{spacing}(b) CV SD, 4*SD = {cv_4sd_train} ({y_range_covered_train}% y-range)'
|
|
864
|
+
f'<br>{spacing}(c) RMSE coef. of variation = {rmse_cv_pct}%'
|
|
865
|
+
f'<br>{spacing} Symmetric RMSE ratio (50% halves) = {data_score.get(f"absol_rmse_50_ratio_{suffix}", "N/A")}'
|
|
866
|
+
)
|
|
867
|
+
if f'spearman_50_low_{suffix}' in data_score:
|
|
868
|
+
cv_sd_result += (
|
|
869
|
+
f'<br>{spacing} Spearman in 50% halves (low/high) = '
|
|
870
|
+
f'{data_score[f"spearman_50_low_{suffix}"]} / {data_score[f"spearman_50_high_{suffix}"]}'
|
|
871
|
+
)
|
|
872
|
+
|
|
873
|
+
thres_line = (
|
|
874
|
+
'(a)/(b) 4*SD vs y range: +2 if ≤ 25%, +1 at 50%, 0 if ≥ 75% (linear).'
|
|
875
|
+
'<br>(c) RMSE coef. of variation: +2 if ≤ 15%, +1 at 25%, 0 if ≥ 35% (linear).'
|
|
876
|
+
'<br>Score = average of (a), (b) and (c) + the most severe penalty'
|
|
877
|
+
'<br>from the 50% halves of the y range:'
|
|
878
|
+
'<br>Symmetric RMSE ratio: 0 if ≤ 1.25, -1 at 1.5, -2 if ≥ 1.75 (linear).'
|
|
879
|
+
'<br>Spearman in each half: 0 if ≥ 0.3, -1 at 0.05, -2 if ≤ -0.2 (linear).'
|
|
880
|
+
)
|
|
881
|
+
else:
|
|
882
|
+
disagree_a = data_score.get(f'clas_disagree_a_{suffix}',0)
|
|
883
|
+
disagree_b = data_score.get(f'clas_disagree_b_{suffix}',0)
|
|
884
|
+
mcc_cv_pct = data_score.get(f'mcc_cv_pct_{suffix}',0)
|
|
885
|
+
|
|
886
|
+
cv_sd_result = (
|
|
887
|
+
f'(a) Test disagreement (10 repeats) = {disagree_a}%.'
|
|
888
|
+
f'<br>{spacing}(b) CV disagreement (10 repeats) = {disagree_b}%.'
|
|
889
|
+
f'<br>{spacing}(c) MCC coef. of variation = {mcc_cv_pct}%.'
|
|
890
|
+
)
|
|
891
|
+
thres_line = ('(a)/(b) disagreement and (c) MCC coef. of variation:'
|
|
892
|
+
'<br>+2 if ≤ 15%, +1 at 25%, 0 if ≥ 35% (linear).'
|
|
893
|
+
'<br>Score = average of (a), (b) and (c).')
|
|
894
|
+
|
|
895
|
+
score_adv_pred = f'<p style="text-align: justify; margin-top: 3px; margin-bottom: 0px;">{spacing}'
|
|
896
|
+
info = score_info_icon(f'Scoring from 0 to 2<br>{thres_line}')
|
|
897
|
+
column = f"""<p style="text-align: justify; margin-top: 20px; margin-bottom: 0px;">{spacing}<span style="font-weight:bold;">{docs_heading('6. Prediction stability','stability')}</span> ({score_label} <img src="file:///{cv_r2_image}" alt="CheckML Score" style="width: 13%">) {info}</p>
|
|
898
|
+
{score_adv_pred}{cv_sd_result}</p>
|
|
899
|
+
"""
|
|
900
|
+
|
|
901
|
+
return column
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def adv_train_val_gap(self,suffix,data_score,spacing,pred_type='reg'):
|
|
906
|
+
"""
|
|
907
|
+
Interpolation sub-metric 4: gap between the out-of-fold validation error and the in-fold
|
|
908
|
+
training fit, both averaged over all the folds and repeats of the CV (a large gap indicates
|
|
909
|
+
the model memorizes its training splits instead of generalizing to held-out points).
|
|
910
|
+
|
|
911
|
+
Classification uses the same ΔMCC-based comparison as item 5's CV-vs-test consistency
|
|
912
|
+
check (see adv_diff_test()), applied to train-infold vs CV instead of CV vs test.
|
|
913
|
+
"""
|
|
914
|
+
|
|
915
|
+
score_gap = data_score.get(f'train_val_gap_score_{suffix}', 0)
|
|
916
|
+
score_label,gap_image = score_badge_2(self,data_score,suffix,score_gap)
|
|
917
|
+
|
|
918
|
+
if pred_type == 'reg':
|
|
919
|
+
scaled_trainfit = data_score.get(f'scaled_rmse_trainfit_{suffix}')
|
|
920
|
+
factor_trainfit = data_score.get(f'factor_trainfit_{suffix}')
|
|
921
|
+
|
|
922
|
+
if scaled_trainfit is None:
|
|
923
|
+
gap_result = 'Not available.'
|
|
924
|
+
else:
|
|
925
|
+
gap_result = f'Validation is {round(factor_trainfit,2)}*train RMSE.'
|
|
926
|
+
|
|
927
|
+
thres_line = f'Ratio validation RMSE / train RMSE:<br>{RATIO_INFO}'
|
|
928
|
+
else:
|
|
929
|
+
diff_trainfit = data_score.get(f'diff_trainfit_{suffix}')
|
|
930
|
+
|
|
931
|
+
if diff_trainfit is None:
|
|
932
|
+
gap_result = 'Not available.'
|
|
933
|
+
else:
|
|
934
|
+
gap_result = f'The ΔMCC between train and CV is {diff_trainfit}.'
|
|
935
|
+
|
|
936
|
+
thres_line = DELTA_MCC_INFO
|
|
937
|
+
|
|
938
|
+
score_adv_gap = f'<p style="text-align: justify; margin-top: 3px; margin-bottom: 0px;">{spacing}'
|
|
939
|
+
info = score_info_icon(f'Scoring from 0 to 2<br>{thres_line}')
|
|
940
|
+
column = f"""<p style="text-align: justify; margin-top: 20px; margin-bottom: 0px;">{spacing}<span style="font-weight:bold;">{docs_heading('4. Train vs validation gap','gap_diff')}</span> ({score_label} <img src="file:///{gap_image}" alt="CheckML Score" style="width: 13%">) {info}</p>
|
|
941
|
+
{score_adv_gap}{gap_result}</p>
|
|
942
|
+
"""
|
|
943
|
+
|
|
944
|
+
return column
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def adv_sorted_cv_high(self, suffix, data_score, spacing):
|
|
948
|
+
"""Render the High parent section as separate rows for 1a, 1b, and 1c."""
|
|
949
|
+
score = data_score.get(f'sorted_cv_high_score_{suffix}', 0)
|
|
950
|
+
label, image = score_badge_2(self, data_score, suffix, score)
|
|
951
|
+
return _adv_boundary_extreme(
|
|
952
|
+
self, suffix, data_score, spacing, 'high', '1', 'Top 20% (High)',
|
|
953
|
+
label, image, data_score.get(f'scaled_rmse_high_{suffix}', 0),
|
|
954
|
+
data_score.get(f'crossing_high_{suffix}', 0),
|
|
955
|
+
)
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def adv_sorted_cv_low(self, suffix, data_score, spacing):
|
|
959
|
+
"""Render the Low parent section as separate rows for 2a, 2b, and 2c."""
|
|
960
|
+
score = data_score.get(f'sorted_cv_low_score_{suffix}', 0)
|
|
961
|
+
label, image = score_badge_2(self, data_score, suffix, score)
|
|
962
|
+
return _adv_boundary_extreme(
|
|
963
|
+
self, suffix, data_score, spacing, 'low', '2', 'Bottom 20% (Low)',
|
|
964
|
+
label, image, data_score.get(f'scaled_rmse_low_{suffix}', 0),
|
|
965
|
+
data_score.get(f'crossing_low_{suffix}', 0),
|
|
966
|
+
)
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def _adv_boundary_extreme(self, suffix, data_score, spacing, side, section, label,
|
|
970
|
+
sorted_label, sorted_image, scaled_rmse, crossing):
|
|
971
|
+
"""Build a parent heading and three score rows for one target-value boundary."""
|
|
972
|
+
spearman = data_score.get(f'spearman_{side}_{suffix}')
|
|
973
|
+
spearman_score = data_score.get(f'spearman_score_{side}_{suffix}', 0)
|
|
974
|
+
ratio_sd = data_score.get(f'spread_ratio_{side}_{suffix}')
|
|
975
|
+
ratio_range = data_score.get(f'range_ratio_{side}_{suffix}')
|
|
976
|
+
degradation_ratio = data_score.get(f'degradation_ratio_{side}_{suffix}')
|
|
977
|
+
degradation_score = data_score.get(f'degradation_score_{side}_{suffix}', 0)
|
|
978
|
+
rank_label, rank_image = score_badge_1(self, data_score, suffix, spearman_score)
|
|
979
|
+
degradation_label, degradation_image = score_badge_1(self, data_score, suffix, degradation_score)
|
|
980
|
+
|
|
981
|
+
rank_text = 'Not available.' if spearman is None else f'Spearman rank coefficient ({side.title()}) = {spearman}.'
|
|
982
|
+
if ratio_sd is not None and ratio_range is not None:
|
|
983
|
+
rank_text += f'<br>{spacing}Prediction SD ratio = {ratio_sd}; range ratio = {ratio_range}.'
|
|
984
|
+
degradation_text = ('Not available.' if degradation_ratio is None else
|
|
985
|
+
f'Degradation vs 80% RMSE ({side.title()}) = {round(degradation_ratio, 2)}x.')
|
|
986
|
+
|
|
987
|
+
parent = f'<p style="font-weight:bold; font-size:12px; margin-top:0; margin-bottom:5px;">{spacing}{section}. {label}</p>'
|
|
988
|
+
side_name = 'High' if side == 'high' else 'Low'
|
|
989
|
+
detail_spacing = 20 if section == '1' else 10
|
|
990
|
+
sorted_info = score_info_icon(f'Scoring from 0 to 2<br>{SCALED_RMSE_INFO}'
|
|
991
|
+
'<br>Crossing rate penalty: 0 if \u2265 80%, -1 at 50%, -2 if \u2264 20% (linear).')
|
|
992
|
+
rank_info = score_info_icon('Scoring from 0 to 1<br>Spearman rank: +1 if \u2265 0.5, 0 if \u2264 0.2 (linear).'
|
|
993
|
+
'<br>Penalty (lower of the SD and range ratios):'
|
|
994
|
+
'<br>0 if \u2265 0.5, -1 if \u2264 0.2 (linear).')
|
|
995
|
+
degradation_info = score_info_icon('Scoring from 0 to 1<br>Ratio: +1 if \u2264 1.5x, 0 if \u2265 1.75x (linear).')
|
|
996
|
+
sorted_row = f"""<p style="text-align: justify; margin-top: 0; margin-bottom: 0;">{spacing}<u>{docs_heading(f'{section}a. Predictions','sorted_cv')}</u> ({sorted_label} <img src="file:///{sorted_image}" alt="CheckML Score" style="width: 13%">) {sorted_info}</p>
|
|
997
|
+
<p style="text-align: justify; margin-top: 3px; margin-bottom: 0;">{spacing}Scaled RMSE ({side_name}) = {scaled_rmse}%.<br>{spacing}Beyond training range ({side_name}) = {round(crossing*100)}%.</p>"""
|
|
998
|
+
rank_row = f"""<p style="text-align: justify; margin-top: {detail_spacing}px; margin-bottom: 0;">{spacing}<u>{docs_heading(f'{section}b. Spearman rank','spearman')}</u> ({rank_label} <img src="file:///{rank_image}" alt="CheckML Score" style="width: 13%">) {rank_info}</p>
|
|
999
|
+
<p style="text-align: justify; margin-top: 3px; margin-bottom: 0;">{spacing}{rank_text}</p>"""
|
|
1000
|
+
degradation_row = f"""<p style="text-align: justify; margin-top: {detail_spacing}px; margin-bottom: 0;">{spacing}<u>{docs_heading(f'{section}c. Degradation ratio','degradation')}</u> ({degradation_label} <img src="file:///{degradation_image}" alt="CheckML Score" style="width: 13%">) {degradation_info}</p>
|
|
1001
|
+
<p style="text-align: justify; margin-top: 3px; margin-bottom: 0;">{spacing}{degradation_text}</p>"""
|
|
1002
|
+
return [parent + sorted_row, rank_row, degradation_row]
|
|
1003
|
+
|
|
1004
|
+
|
|
1005
|
+
def adv_applicability_domain(self,suffix,data_score,spacing):
|
|
1006
|
+
"""
|
|
1007
|
+
Boundary robustness sub-metric 3: applicability domain (leverage) - boundary robustness in
|
|
1008
|
+
X-descriptor space (train on the 80% "typical" points, test on the 20% highest-leverage,
|
|
1009
|
+
most structurally/descriptor-wise extreme points), complementing sub-metrics 1-2 (all
|
|
1010
|
+
about boundary robustness in y-space)
|
|
1011
|
+
"""
|
|
1012
|
+
|
|
1013
|
+
score_ad = data_score.get(f'applicability_domain_score_{suffix}', 0)
|
|
1014
|
+
score_label,ad_image = score_badge_2(self,data_score,suffix,score_ad)
|
|
1015
|
+
scaled_rmse_ad = data_score.get(f'scaled_rmse_ad_{suffix}')
|
|
1016
|
+
|
|
1017
|
+
if scaled_rmse_ad is None:
|
|
1018
|
+
ad_result = 'Not available.'
|
|
1019
|
+
else:
|
|
1020
|
+
ad_result = f'Scaled RMSE (high-leverage 20%) = {scaled_rmse_ad}%.'
|
|
1021
|
+
|
|
1022
|
+
score_adv_ad = f'<p style="text-align: justify; margin-top: 3px; margin-bottom: 0px;">{spacing}'
|
|
1023
|
+
info = score_info_icon(f'Scoring from 0 to 2<br>{SCALED_RMSE_INFO}')
|
|
1024
|
+
column = f"""<p style="text-align: justify; margin-top: 20px; margin-bottom: 0px;">{spacing}<span style="font-weight:bold;">{docs_heading('3. Applic. domain (leverage)','applicability')}</span> <span style="white-space:nowrap;">({score_label} <img src="file:///{ad_image}" alt="CheckML Score" style="width: 13%">) {info}</span></p>
|
|
1025
|
+
{score_adv_ad}{ad_result}</p>
|
|
1026
|
+
"""
|
|
1027
|
+
|
|
1028
|
+
return column
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
def adv_bound_diagnostic(suffix,data_score,spacing):
|
|
1032
|
+
"""
|
|
1033
|
+
Boundary robustness item 4 (unscored): additional diagnostic kept for context - global Spearman
|
|
1034
|
+
rank correlation over the whole sorted dataset (the local, per-extreme Spearman is already
|
|
1035
|
+
scored in items 1b/2b). Not scored, but still useful signal, so kept visible as its own item
|
|
1036
|
+
instead of dropped, keeping the whole-dataset correlation available beside the boundary plots
|
|
1037
|
+
"""
|
|
1038
|
+
|
|
1039
|
+
spearman_global = data_score.get(f'spearman_global_{suffix}')
|
|
1040
|
+
|
|
1041
|
+
if spearman_global is None:
|
|
1042
|
+
return ''
|
|
1043
|
+
|
|
1044
|
+
result = f'Global Spearman rank coefficient (whole dataset) = {spearman_global}.'
|
|
1045
|
+
|
|
1046
|
+
column = f"""<p style="text-align: justify; margin-top: 20px; margin-bottom: 0px;">{spacing}<span style="font-weight:bold;">4. Additional diagnostics</span> (unscored)</p>
|
|
1047
|
+
<p style="text-align: justify; margin-top: 3px; margin-bottom: 0px;">{spacing}{result}</p>
|
|
1048
|
+
"""
|
|
1049
|
+
|
|
1050
|
+
return column
|
|
1051
|
+
|
|
1052
|
+
|
|
1053
|
+
def get_col_text(type_thres):
|
|
1054
|
+
"""
|
|
1055
|
+
Gather the information regarding the thresholds used in the score and abbreviation sections
|
|
1056
|
+
"""
|
|
1057
|
+
|
|
1058
|
+
reduced_line = '<p style="text-align: justify; margin-top: -8px;">' # reduces line separation separation
|
|
1059
|
+
|
|
1060
|
+
first_line = '<p style="text-align: justify; margin-top: -25px;">'
|
|
1061
|
+
if type_thres == 'abbrev_1':
|
|
1062
|
+
abbrev_list = ['<strong>ACC:</strong> accuracy',
|
|
1063
|
+
'<strong>ADAB:</strong> AdaBoost',
|
|
1064
|
+
'<strong>CSV:</strong> comma separated values',
|
|
1065
|
+
'<strong>CLAS:</strong> classification',
|
|
1066
|
+
'<strong>CV:</strong> cross-validation',
|
|
1067
|
+
'<strong>F1 score:</strong> balanced F-score',
|
|
1068
|
+
'<strong>GB:</strong> gradient boosting',
|
|
1069
|
+
'<strong>GP:</strong> gaussian process'
|
|
1070
|
+
]
|
|
1071
|
+
|
|
1072
|
+
elif type_thres == 'abbrev_2':
|
|
1073
|
+
abbrev_list = ['<strong>KN:</strong> k-nearest neighbors',
|
|
1074
|
+
'<strong>LOGISTIC:</strong> logistic regression',
|
|
1075
|
+
'<strong>MAE:</strong> mean absolute error',
|
|
1076
|
+
"<strong>MCC:</strong> Matthew's correl. coefficient",
|
|
1077
|
+
'<strong>ML:</strong> machine learning',
|
|
1078
|
+
'<strong>MVL:</strong> multivariate linear models',
|
|
1079
|
+
'<strong>NN:</strong> neural network',
|
|
1080
|
+
'<strong>PFI:</strong> permutation feature importance',
|
|
1081
|
+
# what get_prediction_results() computes: sklearn r2_score (y = x reference)
|
|
1082
|
+
'<strong>Q2:</strong> R2 of the cross-validated (out-of-fold) predictions, 1 - PRESS/SS (average of the CV repeats)',
|
|
1083
|
+
'<strong>R2:</strong> coefficient of determination of the predictions, 1 - SSres/SStot (not the squared Pearson correlation)'
|
|
1084
|
+
]
|
|
1085
|
+
elif type_thres == 'abbrev_3':
|
|
1086
|
+
abbrev_list = ['<strong>REG:</strong> Regression',
|
|
1087
|
+
'<strong>RF:</strong> random forest',
|
|
1088
|
+
'<strong>RIDGE:</strong> ridge regression',
|
|
1089
|
+
'<strong>RMSE:</strong> root mean square error',
|
|
1090
|
+
'<strong>RND:</strong> random',
|
|
1091
|
+
'<strong>SD:</strong> standard deviation',
|
|
1092
|
+
'<strong>SHAP:</strong> Shapley additive explanations',
|
|
1093
|
+
]
|
|
1094
|
+
|
|
1095
|
+
column = ''
|
|
1096
|
+
for i,ele in enumerate(abbrev_list):
|
|
1097
|
+
if i == 0:
|
|
1098
|
+
column += f"""{first_line}{ele}</p>
|
|
1099
|
+
"""
|
|
1100
|
+
else:
|
|
1101
|
+
column += f"""{reduced_line}{ele}</p>
|
|
1102
|
+
"""
|
|
1103
|
+
|
|
1104
|
+
return column
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
def get_col_transpa(params_dict,suffix,section,spacing):
|
|
1108
|
+
"""
|
|
1109
|
+
Gather the information regarding the model parameters represented in the Reproducibility section
|
|
1110
|
+
"""
|
|
1111
|
+
|
|
1112
|
+
first_line = f'<p style="text-align: justify; margin-top: -40px;">{spacing*2}' # reduces line separation separation
|
|
1113
|
+
reduced_line = f'<p style="text-align: justify; margin-top: -8px;">{spacing*2}' # reduces line separation separation
|
|
1114
|
+
|
|
1115
|
+
if suffix == 'No PFI':
|
|
1116
|
+
caption = f'{title_no_pfi}'
|
|
1117
|
+
|
|
1118
|
+
elif suffix == 'PFI':
|
|
1119
|
+
caption = f'{title_pfi}'
|
|
1120
|
+
|
|
1121
|
+
excluded_params = [f"combined_{params_dict['error_type']}", 'train', 'X_descriptors', 'y', 'error_train', 'cv_error', 'names']
|
|
1122
|
+
misc_params = ['type','error_type','split','kfold','repeat_kfolds','seed']
|
|
1123
|
+
if params_dict['type'] == 'reg':
|
|
1124
|
+
model_type = 'Regressor'
|
|
1125
|
+
elif params_dict['type'] == 'clas':
|
|
1126
|
+
model_type = 'Classifier'
|
|
1127
|
+
models_dict = {'RF': f'RandomForest{model_type}',
|
|
1128
|
+
'MVL': 'LinearRegression',
|
|
1129
|
+
'GB': f'GradientBoosting{model_type}',
|
|
1130
|
+
'NN': f'MLP{model_type}',
|
|
1131
|
+
'GP': f'GaussianProcess{model_type}',
|
|
1132
|
+
'ADAB': f'AdaBoost{model_type}',
|
|
1133
|
+
'RIDGE': 'Ridge',
|
|
1134
|
+
'LOGISTIC': 'LogisticRegression',
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
col_info,sklearn_model = '',''
|
|
1138
|
+
for _,ele in enumerate(params_dict.keys()):
|
|
1139
|
+
if ele not in excluded_params:
|
|
1140
|
+
if ele == 'model' and section == 'model_section':
|
|
1141
|
+
# ROBERT's own short codes (RF/MVL/...) need translating to their full sklearn
|
|
1142
|
+
# class name; a dynamic scikit-learn model (see CHECKML's --model_params/
|
|
1143
|
+
# --model_file) already stores the exact class name directly, so it's used as-is
|
|
1144
|
+
sklearn_model = models_dict.get(params_dict[ele].upper(), params_dict[ele])
|
|
1145
|
+
sklearn_model = f"""{first_line}sklearn model: {sklearn_model}</p>"""
|
|
1146
|
+
elif section == 'model_section' and ele.lower() not in misc_params:
|
|
1147
|
+
if ele == 'params':
|
|
1148
|
+
# same reader VERIFY/PREDICT use (JSON or the old format, with objects such as
|
|
1149
|
+
# GP kernels decoded back), so the report shows i.e. "kernel: RBF(...)"
|
|
1150
|
+
model_params = deserialize_model_params(params_dict['params'])
|
|
1151
|
+
for param in model_params:
|
|
1152
|
+
col_info += f"""{reduced_line}{param}: {model_params[param]}</p>"""
|
|
1153
|
+
elif section == 'misc_section' and ele.lower() in misc_params:
|
|
1154
|
+
if col_info == '':
|
|
1155
|
+
col_info += f"""{first_line}{ele}: {params_dict[ele]}</p>"""
|
|
1156
|
+
else:
|
|
1157
|
+
col_info += f"""{reduced_line}{ele}: {params_dict[ele]}</p>"""
|
|
1158
|
+
|
|
1159
|
+
column = f"""<p style="margin-top: -30px;"><span style="font-weight:bold;">{spacing*2}{caption}</span></p>
|
|
1160
|
+
{sklearn_model}{col_info}
|
|
1161
|
+
"""
|
|
1162
|
+
|
|
1163
|
+
return column
|
|
1164
|
+
|
|
1165
|
+
def convert_2_decimal(value_score):
|
|
1166
|
+
"""
|
|
1167
|
+
Converts a float value to a decimal with 1 decimal place, rounding half up.
|
|
1168
|
+
"""
|
|
1169
|
+
return float(Decimal(str(value_score)).quantize(Decimal('0.1'), rounding=ROUND_HALF_UP))
|
|
1170
|
+
|
|
1171
|
+
|
|
1172
|
+
def calc_score(dat_files,suffix,pred_type,data_score):
|
|
1173
|
+
'''
|
|
1174
|
+
Calculates the Interpolation and Boundary robustness scores (independent, 0-10 each)
|
|
1175
|
+
'''
|
|
1176
|
+
|
|
1177
|
+
data_score = get_predict_scores(dat_files['PREDICT'],suffix,pred_type,data_score)
|
|
1178
|
+
|
|
1179
|
+
data_score = get_verify_scores(dat_files['VERIFY'],suffix,pred_type,data_score)
|
|
1180
|
+
|
|
1181
|
+
if pred_type == 'reg':
|
|
1182
|
+
# Interpolation: flawed-model gate + CV + test + train-vs-validation gap +
|
|
1183
|
+
# CV-vs-test consistency + avg SD (max 10: 5 sub-points x 0/2, flawed only subtracts)
|
|
1184
|
+
interp_score = data_score.get(f'flawed_mod_score_{suffix}', 0) \
|
|
1185
|
+
+ data_score.get(f'cv_score_combined_{suffix}', 0) + data_score.get(f'test_score_combined_{suffix}', 0) \
|
|
1186
|
+
+ data_score.get(f'train_val_gap_score_{suffix}', 0) + data_score.get(f'diff_scaled_rmse_score_{suffix}', 0) \
|
|
1187
|
+
+ data_score.get(f'cv_sd_score_{suffix}', 0)
|
|
1188
|
+
interp_score = convert_2_decimal(interp_score)
|
|
1189
|
+
if interp_score < 0:
|
|
1190
|
+
interp_score = 0
|
|
1191
|
+
|
|
1192
|
+
# Boundary robustness: 1a/2a sorted CV (0-2 each), 1b/2b Spearman (0-1 each),
|
|
1193
|
+
# 1c/2c degradation (0-1 each), and applicability domain (0-2). Keep this sum as the
|
|
1194
|
+
# same seven component values as before regrouping them by High/Low in the report.
|
|
1195
|
+
extrap_score = data_score.get(f'sorted_cv_high_score_{suffix}', 0) + data_score.get(f'sorted_cv_low_score_{suffix}', 0) \
|
|
1196
|
+
+ data_score.get(f'spearman_score_{suffix}', 0) + data_score.get(f'degradation_score_{suffix}', 0) \
|
|
1197
|
+
+ data_score.get(f'applicability_domain_score_{suffix}', 0)
|
|
1198
|
+
extrap_score = convert_2_decimal(extrap_score)
|
|
1199
|
+
if extrap_score < 0:
|
|
1200
|
+
extrap_score = 0
|
|
1201
|
+
|
|
1202
|
+
data_score[f'interp_score_{suffix}'] = interp_score
|
|
1203
|
+
data_score[f'extrap_score_{suffix}'] = extrap_score
|
|
1204
|
+
|
|
1205
|
+
elif pred_type == 'clas':
|
|
1206
|
+
# Calculate the difference between CV MCC and test MCC
|
|
1207
|
+
mcc_cv = data_score.get(f'r2_cv_{suffix}', 0)
|
|
1208
|
+
mcc_test = data_score.get(f'r2_test_{suffix}', 0)
|
|
1209
|
+
diff_mcc = round(np.abs(mcc_test - mcc_cv), 2)
|
|
1210
|
+
|
|
1211
|
+
# Use the gradual 0-2 score for the MCC gap, matching Section B.3b.
|
|
1212
|
+
data_score[f'diff_mcc_score_{suffix}'] = score_mcc_difference(diff_mcc)
|
|
1213
|
+
|
|
1214
|
+
# Interpolation: flawed-model gate + CV + test + train-vs-validation gap (item 4) +
|
|
1215
|
+
# MCC-diff (item 5) + prediction stability (item 6, see the 'clas' branch in
|
|
1216
|
+
# get_predict_scores()) - same 5-item structure as regression, homogenized to the same
|
|
1217
|
+
# 0-2 scale per item. Max achievable is 10: cv_score_combined(2) + test_score_combined(2)
|
|
1218
|
+
# + flawed_mod_score(0, never positive) + train_val_gap_score(2) + diff_mcc_score(2)
|
|
1219
|
+
# + cv_sd_score(2)
|
|
1220
|
+
interp_score = (
|
|
1221
|
+
data_score.get(f'cv_score_combined_{suffix}', 0)
|
|
1222
|
+
+ data_score.get(f'test_score_combined_{suffix}', 0)
|
|
1223
|
+
+ data_score.get(f'flawed_mod_score_{suffix}', 0)
|
|
1224
|
+
+ data_score.get(f'train_val_gap_score_{suffix}', 0)
|
|
1225
|
+
+ data_score.get(f'diff_mcc_score_{suffix}', 0)
|
|
1226
|
+
+ data_score.get(f'cv_sd_score_{suffix}', 0)
|
|
1227
|
+
)
|
|
1228
|
+
interp_score = convert_2_decimal(interp_score)
|
|
1229
|
+
if interp_score < 0:
|
|
1230
|
+
interp_score = 0
|
|
1231
|
+
|
|
1232
|
+
# Boundary robustness isn't defined for classification (see score.rst) - no sub-metric
|
|
1233
|
+
# is well-defined for a discrete MCC-based score, so this always stays 0/unused
|
|
1234
|
+
extrap_score = 0
|
|
1235
|
+
|
|
1236
|
+
data_score[f'interp_score_{suffix}'] = interp_score
|
|
1237
|
+
data_score[f'extrap_score_{suffix}'] = extrap_score
|
|
1238
|
+
|
|
1239
|
+
return data_score
|
|
1240
|
+
|
|
1241
|
+
|
|
1242
|
+
def calc_degrad_score(degrad_ratio):
|
|
1243
|
+
'''Score +1 at ratios <= 1.5, decreasing linearly to 0 at 1.75.'''
|
|
1244
|
+
return convert_2_decimal(max(0.0, min(1.0, (1.75 - degrad_ratio) / 0.25)))
|
|
1245
|
+
|
|
1246
|
+
|
|
1247
|
+
def calc_spearman_score(spearman_coef):
|
|
1248
|
+
'''Score +1 at coefficients >= 0.5, decreasing linearly to 0 at 0.2.
|
|
1249
|
+
This scale is analogous to MCC, since Spearman coefficients go from +1 to -1'''
|
|
1250
|
+
return convert_2_decimal(max(0.0, min(1.0, (spearman_coef - 0.2) / 0.3)))
|
|
1251
|
+
|
|
1252
|
+
|
|
1253
|
+
def spearman_ratio_penalty(spread_value):
|
|
1254
|
+
'''Score -1 at ratios <= 0.2, increasing linearly to 0 at 0.5.'''
|
|
1255
|
+
return convert_2_decimal(max(-1.0, min(0.0, (spread_value - 0.5) / 0.3)))
|
|
1256
|
+
|
|
1257
|
+
|
|
1258
|
+
def get_verify_scores(dat_verify,suffix,pred_type,data_score):
|
|
1259
|
+
"""
|
|
1260
|
+
Calculates scores that come from the VERIFY module (VERIFY tests)
|
|
1261
|
+
"""
|
|
1262
|
+
|
|
1263
|
+
start_data = False
|
|
1264
|
+
flawed_score = 0
|
|
1265
|
+
failed_tests = 0
|
|
1266
|
+
unclear_tests = 0
|
|
1267
|
+
sorted_cv_score = 0
|
|
1268
|
+
for i,line in enumerate(dat_verify):
|
|
1269
|
+
# set starting points for No PFI and PFI models
|
|
1270
|
+
if suffix == 'No PFI':
|
|
1271
|
+
if '------- ' in line and '(No PFI)' in line:
|
|
1272
|
+
start_data = True
|
|
1273
|
+
elif '------- ' in line and 'with PFI' in line:
|
|
1274
|
+
start_data = False
|
|
1275
|
+
if suffix == 'PFI':
|
|
1276
|
+
if '------- ' in line and 'with PFI' in line:
|
|
1277
|
+
start_data = True
|
|
1278
|
+
|
|
1279
|
+
if start_data:
|
|
1280
|
+
error_keyword = "rmse" if pred_type.lower() == 'reg' else "mcc"
|
|
1281
|
+
if f"Original {error_keyword.upper()} (" in line:
|
|
1282
|
+
failed_threshold = int(line.split('threshold')[0].split()[-3].replace('%',''))
|
|
1283
|
+
unclear_threshold = int(line.split('threshold')[0].split()[-1].replace('%',''))
|
|
1284
|
+
for j in range(i+1,i+5): # y-mean, y-shuffle, onehot and cluster tests
|
|
1285
|
+
# tests that don't apply (onehot with binary descriptors, cluster in
|
|
1286
|
+
# classification) are logged as N/A without a % difference and aren't scored
|
|
1287
|
+
if ': N/A' in dat_verify[j]:
|
|
1288
|
+
continue
|
|
1289
|
+
# A zero CV score makes a relative percentage undefined. VERIFY still
|
|
1290
|
+
# classifies the test from its absolute score and thresholds; preserve
|
|
1291
|
+
# its FAILED count, but there is no percentage to use for this penalty.
|
|
1292
|
+
if 'percentage difference unavailable (CV score is 0)' in dat_verify[j]:
|
|
1293
|
+
if 'FAILED' in dat_verify[j]:
|
|
1294
|
+
failed_tests += 1
|
|
1295
|
+
elif 'UNCLEAR' in dat_verify[j]:
|
|
1296
|
+
unclear_tests += 1
|
|
1297
|
+
continue
|
|
1298
|
+
error_difference = float(dat_verify[j].split(f'% difference.')[0].split()[-1])
|
|
1299
|
+
threshold_gap = unclear_threshold - failed_threshold
|
|
1300
|
+
zero_penalty_threshold = unclear_threshold + threshold_gap
|
|
1301
|
+
# RMSE increases when a VERIFY test degrades, while MCC decreases.
|
|
1302
|
+
# Convert both to a positive degradation direction before scoring.
|
|
1303
|
+
degradation_difference = error_difference if pred_type.lower() == 'reg' else -error_difference
|
|
1304
|
+
flawed_score += max(-2, min(0, (degradation_difference - zero_penalty_threshold)/threshold_gap))
|
|
1305
|
+
flawed_score = convert_2_decimal(flawed_score)
|
|
1306
|
+
if 'FAILED' in dat_verify[j]:
|
|
1307
|
+
failed_tests += 1
|
|
1308
|
+
elif 'UNCLEAR' in dat_verify[j]:
|
|
1309
|
+
unclear_tests += 1
|
|
1310
|
+
if '- Sorted ' in dat_verify[i+5]:
|
|
1311
|
+
sorted_cv_results = dat_verify[i+5].split(f'{error_keyword.upper()} = ')[-1]
|
|
1312
|
+
sorted_cv_results = ast.literal_eval(sorted_cv_results)
|
|
1313
|
+
if pred_type.lower() == 'reg':
|
|
1314
|
+
data_score[f'scaled_{error_keyword}_sorted_{suffix}'] = [round((val/data_score[f'y_range_{suffix}'])*100,2) for val in sorted_cv_results]
|
|
1315
|
+
else:
|
|
1316
|
+
data_score[f'scaled_{error_keyword}_sorted_{suffix}'] = sorted_cv_results # no scaling for MCC
|
|
1317
|
+
|
|
1318
|
+
# define min and max values
|
|
1319
|
+
data_score[f'min_scaled_{error_keyword}_{suffix}'] = min(data_score[f'scaled_{error_keyword}_sorted_{suffix}'])
|
|
1320
|
+
idx_min_scaled_rmse = data_score[f'scaled_{error_keyword}_sorted_{suffix}'].index(data_score[f'min_scaled_{error_keyword}_{suffix}'])
|
|
1321
|
+
data_score[f'max_scaled_{error_keyword}_{suffix}'] = max(data_score[f'scaled_{error_keyword}_sorted_{suffix}'])
|
|
1322
|
+
idx_max_scaled_rmse = data_score[f'scaled_{error_keyword}_sorted_{suffix}'].index(data_score[f'max_scaled_{error_keyword}_{suffix}'])
|
|
1323
|
+
|
|
1324
|
+
data_score[f'scaled_{error_keyword}_results_sorted_{suffix}'] = []
|
|
1325
|
+
for idx,err in enumerate(data_score[f'scaled_{error_keyword}_sorted_{suffix}']):
|
|
1326
|
+
if pred_type.lower() == 'reg':
|
|
1327
|
+
if idx == idx_min_scaled_rmse:
|
|
1328
|
+
data_score[f'scaled_{error_keyword}_results_sorted_{suffix}'].append('min')
|
|
1329
|
+
elif err <= (data_score[f'min_scaled_{error_keyword}_{suffix}']*1.25):
|
|
1330
|
+
data_score[f'scaled_{error_keyword}_results_sorted_{suffix}'].append('pass')
|
|
1331
|
+
else:
|
|
1332
|
+
data_score[f'scaled_{error_keyword}_results_sorted_{suffix}'].append('fail')
|
|
1333
|
+
else:
|
|
1334
|
+
if idx == idx_max_scaled_rmse:
|
|
1335
|
+
data_score[f'scaled_{error_keyword}_results_sorted_{suffix}'].append('max')
|
|
1336
|
+
elif err >= (data_score[f'max_scaled_{error_keyword}_{suffix}']*0.75):
|
|
1337
|
+
data_score[f'scaled_{error_keyword}_results_sorted_{suffix}'].append('pass')
|
|
1338
|
+
else:
|
|
1339
|
+
data_score[f'scaled_{error_keyword}_results_sorted_{suffix}'].append('fail')
|
|
1340
|
+
|
|
1341
|
+
sorted_cv_score = int(data_score[f'scaled_{error_keyword}_results_sorted_{suffix}'].count('pass')/2)
|
|
1342
|
+
|
|
1343
|
+
if pred_type.lower() == 'reg':
|
|
1344
|
+
# boundary robustness sub-metrics: Low (bottom fold) and High (top fold)
|
|
1345
|
+
# scored individually, plus the degradation ratio vs the main CV error.
|
|
1346
|
+
# calc_score() runs get_predict_scores() before get_verify_scores(), so
|
|
1347
|
+
# scaled_rmse_cv_{suffix}/scaled_rmse_low_{suffix}/scaled_rmse_high_{suffix}
|
|
1348
|
+
# are already available here - the latter two come from PREDICT's
|
|
1349
|
+
# boundary_plot() repeated-CV run (same methodology as interpolation),
|
|
1350
|
+
# NOT from VERIFY's old single-pass sorted-CV array
|
|
1351
|
+
# (data_score[f'scaled_{error_keyword}_sorted_{suffix}']), which is kept
|
|
1352
|
+
# around only for classification's adv_sorted_cv() display
|
|
1353
|
+
scaled_low = data_score[f'scaled_rmse_low_{suffix}']
|
|
1354
|
+
scaled_high = data_score[f'scaled_rmse_high_{suffix}']
|
|
1355
|
+
|
|
1356
|
+
# R2 (a variance-ratio) is unstable on a ~7-point, narrow-range fold
|
|
1357
|
+
# and ends up punishing models regardless of actual quality (see
|
|
1358
|
+
# discussion with the user) - replaced with a penalty based on the
|
|
1359
|
+
# "real range extension" crossing rate (does the model actually predict
|
|
1360
|
+
# beyond the training range it saw, or does it clip toward the
|
|
1361
|
+
# boundary?) instead of Spearman, which now gets its own dedicated item
|
|
1362
|
+
# (see adv_spearman()). Parsed in get_predict_scores() since that's
|
|
1363
|
+
# logged by boundary_plot() into PREDICT_data.dat, and available
|
|
1364
|
+
# here because calc_score() runs get_predict_scores() first
|
|
1365
|
+
crossing_low = data_score.get(f'crossing_low_{suffix}', 0)
|
|
1366
|
+
crossing_high = data_score.get(f'crossing_high_{suffix}', 0)
|
|
1367
|
+
|
|
1368
|
+
low_score = score_rmse_mcc(pred_type,scaled_low) + calc_penalty_crossing(crossing_low)
|
|
1369
|
+
high_score = score_rmse_mcc(pred_type,scaled_high) + calc_penalty_crossing(crossing_high)
|
|
1370
|
+
data_score[f'sorted_cv_low_score_{suffix}'] = max(low_score,0)
|
|
1371
|
+
data_score[f'sorted_cv_high_score_{suffix}'] = max(high_score,0)
|
|
1372
|
+
|
|
1373
|
+
# boundary robustness components 1c/2c: degradation ratio - each extreme
|
|
1374
|
+
# fold is compared against the RMSE of its OWN "remaining 80%" from the
|
|
1375
|
+
# same sorted-CV run (not the 10x 5-fold CV RMSE, which is a different
|
|
1376
|
+
# CV procedure over a different dataset scope - see boundary_plot() in
|
|
1377
|
+
# utils.py). Scored independently per side (+1 each), so one
|
|
1378
|
+
# badly-degraded side cannot hide behind a fine one. This has to live
|
|
1379
|
+
# here (not in get_predict_scores(), where every other Low/High
|
|
1380
|
+
# sub-metric is computed) because calc_score() runs get_predict_scores()
|
|
1381
|
+
# BEFORE get_verify_scores() - scaled_rmse_bottom80/top80 only exist
|
|
1382
|
+
# once this function's own loop reaches this point, so computing the
|
|
1383
|
+
# score in get_predict_scores() would always read them as None and
|
|
1384
|
+
# silently score 0/2 regardless of the actual ratios
|
|
1385
|
+
scaled_rmse_bottom80 = data_score.get(f'scaled_rmse_bottom80_{suffix}')
|
|
1386
|
+
scaled_rmse_top80 = data_score.get(f'scaled_rmse_top80_{suffix}')
|
|
1387
|
+
if scaled_rmse_bottom80 is not None and scaled_rmse_top80 is not None:
|
|
1388
|
+
data_score[f'degradation_ratio_high_{suffix}'] = safe_ratio(scaled_high,scaled_rmse_bottom80)
|
|
1389
|
+
data_score[f'degradation_ratio_low_{suffix}'] = safe_ratio(scaled_low,scaled_rmse_top80)
|
|
1390
|
+
degradation_score_low = calc_degrad_score(data_score[f'degradation_ratio_low_{suffix}'])
|
|
1391
|
+
degradation_score_high = calc_degrad_score(data_score[f'degradation_ratio_high_{suffix}'])
|
|
1392
|
+
data_score[f'degradation_score_low_{suffix}'] = degradation_score_low
|
|
1393
|
+
data_score[f'degradation_score_high_{suffix}'] = degradation_score_high
|
|
1394
|
+
data_score[f'degradation_score_{suffix}'] = degradation_score_low + degradation_score_high
|
|
1395
|
+
# stores data
|
|
1396
|
+
data_score[f'flawed_mod_score_{suffix}'] = flawed_score
|
|
1397
|
+
data_score[f'failed_tests_{suffix}'] = failed_tests
|
|
1398
|
+
data_score[f'unclear_tests_{suffix}'] = unclear_tests
|
|
1399
|
+
data_score[f'sorted_cv_score_{suffix}'] = sorted_cv_score
|
|
1400
|
+
|
|
1401
|
+
return data_score
|
|
1402
|
+
|
|
1403
|
+
|
|
1404
|
+
def score_overfit(factor):
|
|
1405
|
+
'''Equation for the score: 0 if factor >= 1.75, +2 if factor <= 1.25, linear in between'''
|
|
1406
|
+
diff_score = max(0, min(2, 4*(1.75 - factor)))
|
|
1407
|
+
return diff_score
|
|
1408
|
+
|
|
1409
|
+
|
|
1410
|
+
def score_mcc_difference(difference):
|
|
1411
|
+
"""Score an MCC gap on a gradual 0-2 scale: 2 at 0.15, 0 at 0.45."""
|
|
1412
|
+
score_diff = max(0, min(2, (0.45 - difference) / 0.15))
|
|
1413
|
+
return convert_2_decimal(score_diff)
|
|
1414
|
+
|
|
1415
|
+
|
|
1416
|
+
def part_50_penalty(factor):
|
|
1417
|
+
'''Equation for the penalty: 0 if factor <= 1.25, -2 if factor >= 1.75, linear in between'''
|
|
1418
|
+
if factor == 'N/A':
|
|
1419
|
+
factor = 999
|
|
1420
|
+
diff_score = max(-2, min(0, 4*(1.25 - factor)))
|
|
1421
|
+
return convert_2_decimal(diff_score)
|
|
1422
|
+
|
|
1423
|
+
|
|
1424
|
+
def half_spearman_penalty(spearman):
|
|
1425
|
+
'''
|
|
1426
|
+
Penalty for flat or unordered predictions inside one 50% half of the y range: 0 if the
|
|
1427
|
+
Spearman rank (observed vs predicted) is >= 0.3, -2 if <= -0.2, linear in between.
|
|
1428
|
+
The thresholds are moderate on purpose: each half only has ~8-25 points in low-data sets,
|
|
1429
|
+
so Spearman values between 0 and 0.3 can't be told apart from noise; the full penalty is
|
|
1430
|
+
kept for halves where the model ranks the points in the wrong order. Calibrated on the 14
|
|
1431
|
+
benchmark datasets with < 50 points: thresholds of 0.5/0 penalized half of all models, while
|
|
1432
|
+
these keep the clear failures (Spearman around 0 or negative) and spare models that rank both
|
|
1433
|
+
halves reasonably. No minimum y range is required: a filter based on the model's own error
|
|
1434
|
+
skipped exactly the worst models, and every half in the benchmark spans >= 10% of the range.
|
|
1435
|
+
'''
|
|
1436
|
+
if spearman is None or not np.isfinite(spearman):
|
|
1437
|
+
spearman = 0
|
|
1438
|
+
return convert_2_decimal(max(-2, min(0, 4*(spearman - 0.3))))
|
|
1439
|
+
|
|
1440
|
+
|
|
1441
|
+
def symmetric_50_ratio_factor(ratio):
|
|
1442
|
+
"""Return the symmetric factor for a low/high half-set metric ratio.
|
|
1443
|
+
|
|
1444
|
+
RMSE ratios are non-negative. For R2, a zero or negative ratio means the
|
|
1445
|
+
halves have a zero or opposite-sign score, so treat it as the maximum factor.
|
|
1446
|
+
"""
|
|
1447
|
+
if ratio == 'N/A':
|
|
1448
|
+
return 'N/A'
|
|
1449
|
+
ratio = float(ratio)
|
|
1450
|
+
if ratio <= 0:
|
|
1451
|
+
return float('inf')
|
|
1452
|
+
return max(ratio, 1 / ratio)
|
|
1453
|
+
|
|
1454
|
+
|
|
1455
|
+
def get_predict_scores(dat_predict,suffix,pred_type,data_score):
|
|
1456
|
+
"""
|
|
1457
|
+
Calculates scores that come from the PREDICT module (R2 or accuracy, datapoints:descriptors ratio, outlier proportion)
|
|
1458
|
+
"""
|
|
1459
|
+
|
|
1460
|
+
start_data = False
|
|
1461
|
+
sd_score_penalty = 0 # half-set penalty of item 6, set when its log line is found
|
|
1462
|
+
data_score[f'rmse_score_{suffix}'] = 0
|
|
1463
|
+
data_score[f'cv_type_{suffix}'] = "10x 5-fold CV"
|
|
1464
|
+
|
|
1465
|
+
for i,line in enumerate(dat_predict):
|
|
1466
|
+
|
|
1467
|
+
# set starting points for No PFI and PFI models
|
|
1468
|
+
if suffix == 'No PFI':
|
|
1469
|
+
if '------- ' in line and '(No PFI)' in line:
|
|
1470
|
+
start_data = True
|
|
1471
|
+
elif '------- ' in line and 'with PFI' in line:
|
|
1472
|
+
start_data = False
|
|
1473
|
+
if suffix == 'PFI':
|
|
1474
|
+
if '------- ' in line and 'with PFI' in line:
|
|
1475
|
+
start_data = True
|
|
1476
|
+
|
|
1477
|
+
if start_data:
|
|
1478
|
+
# model type
|
|
1479
|
+
if line.startswith(' - Model:'):
|
|
1480
|
+
data_score['ML_model'] = line.split()[-1]
|
|
1481
|
+
# R2 and proportion
|
|
1482
|
+
if 'o Summary of results' in line:
|
|
1483
|
+
# Optional diagnostics can grow the summary. Search its own model
|
|
1484
|
+
# block instead of a fixed number of lines (or the next PFI block).
|
|
1485
|
+
summary_end = next(
|
|
1486
|
+
(j for j in range(i+1, len(dat_predict))
|
|
1487
|
+
if '------- ' in dat_predict[j] or 'o Summary of results' in dat_predict[j]),
|
|
1488
|
+
len(dat_predict),
|
|
1489
|
+
)
|
|
1490
|
+
summary_lines = dat_predict[i:summary_end]
|
|
1491
|
+
data_score['proportion_ratio_print'] = dat_predict[i+2]
|
|
1492
|
+
data_score[f'points_descp_ratio_{suffix}'] = dat_predict[i+4].split()[-1]
|
|
1493
|
+
|
|
1494
|
+
# total dataset size (train+validation AND test) - the boundary robustness
|
|
1495
|
+
# Low/High folds are drawn from the whole dataset (see sort_n_load()), not just
|
|
1496
|
+
# the train+validation pool, so the "points in extreme folds" line needs this
|
|
1497
|
+
if 'Points CV (train+valid.):Test' in dat_predict[i+1]:
|
|
1498
|
+
# strip() removes the leading space and trailing newline from the log line,
|
|
1499
|
+
# which otherwise end up in the "Points = X (CV: Y, test: Z)" line of Section A
|
|
1500
|
+
data_score[f'cv_points_{suffix}'],data_score[f'test_points_{suffix}'] = [val.strip() for val in dat_predict[i+1].split('=')[-1].split(':')]
|
|
1501
|
+
data_score[f'total_points_{suffix}'] = int(data_score[f'cv_points_{suffix}']) + int(data_score[f'test_points_{suffix}'])
|
|
1502
|
+
|
|
1503
|
+
# the score's thresholds (test_score, CV-vs-test consistency, etc.) were
|
|
1504
|
+
# calibrated assuming the standard test_set=0.2 split (see the note in
|
|
1505
|
+
# score.rst) - reconstruct what test_select()/prepare_sets() would have
|
|
1506
|
+
# carved out for that split (same round()+4-point-floor formula as
|
|
1507
|
+
# utils.py) and compare against what actually happened. A mismatch means a
|
|
1508
|
+
# non-default --test_set, including 0 (i.e. no internal test set at all) -
|
|
1509
|
+
# in that case the score isn't meaningful, so it's hidden in the PDF instead
|
|
1510
|
+
# of silently showing a misleadingly low value. --csv_test does NOT affect
|
|
1511
|
+
# this check: it no longer forces the internal split to 0 (see
|
|
1512
|
+
# prepare_sets()), so a run using both an internal split and an external
|
|
1513
|
+
# --csv_test file scores normally
|
|
1514
|
+
n_test = int(data_score[f'test_points_{suffix}'])
|
|
1515
|
+
expected_test_pts = max(round(0.2 * data_score[f'total_points_{suffix}']), 4)
|
|
1516
|
+
data_score[f'n_test_{suffix}'] = n_test
|
|
1517
|
+
score_available = (n_test == expected_test_pts)
|
|
1518
|
+
unavailable_reason = None if score_available else 'test_set'
|
|
1519
|
+
|
|
1520
|
+
# same reasoning, for the other half of "standard conditions" the score was
|
|
1521
|
+
# calibrated for: a 10x repeated 5-fold CV (ROBERT's kfold/repeat_kfolds
|
|
1522
|
+
# defaults). A custom --kfold/--repeat_kfolds (common with CHECKML, where a
|
|
1523
|
+
# user brings their own settings) makes the CV estimate noisier or more
|
|
1524
|
+
# optimistic than what the score's thresholds assume, so it's hidden the
|
|
1525
|
+
# same way a non-standard test split is. The "Nx M-fold CV" line has the
|
|
1526
|
+
# same prefix for regression and classification (see predict_utils.py's
|
|
1527
|
+
# shared CV_type string), so this one regex covers both
|
|
1528
|
+
cv_type_match = re.search(r'(\d+)x (\d+)-fold CV', dat_predict[i+5])
|
|
1529
|
+
if cv_type_match:
|
|
1530
|
+
actual_repeat_kfolds, actual_kfold = int(cv_type_match.group(1)), int(cv_type_match.group(2))
|
|
1531
|
+
if actual_repeat_kfolds != 10 or actual_kfold != 5:
|
|
1532
|
+
score_available = False
|
|
1533
|
+
# a bad test split is the more fundamental issue when both happen at
|
|
1534
|
+
# once, so it takes priority in the message
|
|
1535
|
+
unavailable_reason = unavailable_reason or 'cv'
|
|
1536
|
+
|
|
1537
|
+
data_score[f'score_available_{suffix}'] = score_available
|
|
1538
|
+
data_score[f'score_unavailable_reason_{suffix}'] = unavailable_reason
|
|
1539
|
+
|
|
1540
|
+
# scaled RMSE/MCC from test (if any) or validation
|
|
1541
|
+
if pred_type == 'reg':
|
|
1542
|
+
if '-fold CV : R2 =' in dat_predict[i+5]:
|
|
1543
|
+
data_score[f'rmse_cv_{suffix}'] = float(dat_predict[i+5].split()[-1])
|
|
1544
|
+
data_score[f"cv_type_{suffix}"] = ' '.join([ele for ele in dat_predict[i+5].split()[1:4]])
|
|
1545
|
+
data_score[f'r2_cv_{suffix}'] = float(dat_predict[i+5].split(',')[0].split()[-1])
|
|
1546
|
+
if 'Test : R2 =' in dat_predict[i+6]:
|
|
1547
|
+
data_score[f'rmse_test_{suffix}'] = float(dat_predict[i+6].split()[-1])
|
|
1548
|
+
data_score[f'r2_test_{suffix}'] = float(dat_predict[i+6].split(',')[0].split()[-1])
|
|
1549
|
+
if '- y range of dataset' in dat_predict[i+8]:
|
|
1550
|
+
data_score[f'y_range_{suffix}'] = float(dat_predict[i+8].split()[-1])
|
|
1551
|
+
|
|
1552
|
+
data_score[f'scaled_rmse_cv_{suffix}'] = round((data_score[f'rmse_cv_{suffix}']/data_score[f'y_range_{suffix}'])*100,2)
|
|
1553
|
+
data_score[f'scaled_rmse_test_{suffix}'] = round((data_score[f'rmse_test_{suffix}']/data_score[f'y_range_{suffix}'])*100,2)
|
|
1554
|
+
|
|
1555
|
+
for detail_line in summary_lines:
|
|
1556
|
+
if '- Full data ' in detail_line and '-fold CV : R2 =' in detail_line:
|
|
1557
|
+
for metric, label in (('r2', 'R2'), ('mae', 'MAE'), ('rmse', 'RMSE')):
|
|
1558
|
+
data_score[f'{metric}_full_{suffix}'] = float(
|
|
1559
|
+
detail_line.split(f'{label} = ')[-1].split(',')[0].strip()
|
|
1560
|
+
)
|
|
1561
|
+
# Use the same y-range as all four existing report
|
|
1562
|
+
# metrics so their scaled errors remain comparable.
|
|
1563
|
+
data_score[f'scaled_rmse_full_{suffix}'] = (
|
|
1564
|
+
data_score[f'rmse_full_{suffix}']/data_score[f'y_range_{suffix}']*100
|
|
1565
|
+
)
|
|
1566
|
+
break
|
|
1567
|
+
|
|
1568
|
+
data_score[f'cv_score_rmse_{suffix}'] = score_rmse_mcc(pred_type,data_score[f'scaled_rmse_cv_{suffix}'])
|
|
1569
|
+
data_score[f'test_score_rmse_{suffix}'] = score_rmse_mcc(pred_type,data_score[f'scaled_rmse_test_{suffix}'])
|
|
1570
|
+
|
|
1571
|
+
# get penalties for R2
|
|
1572
|
+
data_score[f'cv_penalty_r2_{suffix}'] = calc_penalty_r2(data_score[f'r2_cv_{suffix}'])
|
|
1573
|
+
data_score[f'test_penalty_r2_{suffix}'] = calc_penalty_r2(data_score[f'r2_test_{suffix}'])
|
|
1574
|
+
|
|
1575
|
+
# combined scores RMSE/R2 (min 0)
|
|
1576
|
+
data_score[f'cv_score_combined_{suffix}'] = data_score[f'cv_score_rmse_{suffix}'] + data_score[f'cv_penalty_r2_{suffix}']
|
|
1577
|
+
if data_score[f'cv_score_combined_{suffix}'] < 0:
|
|
1578
|
+
data_score[f'cv_score_combined_{suffix}'] = 0
|
|
1579
|
+
data_score[f'test_score_combined_{suffix}'] = data_score[f'test_score_rmse_{suffix}'] + data_score[f'test_penalty_r2_{suffix}']
|
|
1580
|
+
if data_score[f'test_score_combined_{suffix}'] < 0:
|
|
1581
|
+
data_score[f'test_score_combined_{suffix}'] = 0
|
|
1582
|
+
|
|
1583
|
+
# relative difference between RMSE from test and CV (a near-perfect CV fit can
|
|
1584
|
+
# round its scaled RMSE to 0.00 - see safe_ratio())
|
|
1585
|
+
data_score[f'factor_scaled_rmse_{suffix}'] = safe_ratio(data_score[f'scaled_rmse_test_{suffix}'],data_score[f'scaled_rmse_cv_{suffix}'])
|
|
1586
|
+
diff_score = score_overfit(data_score[f'factor_scaled_rmse_{suffix}'])
|
|
1587
|
+
diff_score = convert_2_decimal(diff_score)
|
|
1588
|
+
data_score[f'diff_scaled_rmse_score_{suffix}'] = diff_score
|
|
1589
|
+
|
|
1590
|
+
# train-vs-validation gap (interpolation): how much worse out-of-fold
|
|
1591
|
+
# validation RMSE is compared to the in-fold training fit (both global, i.e.
|
|
1592
|
+
# over every fold and repeat of the CV, not fold by fold)
|
|
1593
|
+
data_score[f'train_val_gap_score_{suffix}'] = 0
|
|
1594
|
+
for detail_line in summary_lines:
|
|
1595
|
+
if 'Train fit (in-fold)' in detail_line:
|
|
1596
|
+
rmse_trainfit = float(detail_line.split('RMSE = ')[-1].strip())
|
|
1597
|
+
data_score[f'scaled_rmse_trainfit_{suffix}'] = round((rmse_trainfit/data_score[f'y_range_{suffix}'])*100,2)
|
|
1598
|
+
factor_trainfit = safe_ratio(data_score[f'scaled_rmse_cv_{suffix}'],data_score[f'scaled_rmse_trainfit_{suffix}'])
|
|
1599
|
+
data_score[f'factor_trainfit_{suffix}'] = factor_trainfit
|
|
1600
|
+
train_val_gap_score = score_overfit(factor_trainfit)
|
|
1601
|
+
train_val_gap_score = convert_2_decimal(train_val_gap_score)
|
|
1602
|
+
data_score[f'train_val_gap_score_{suffix}'] = train_val_gap_score
|
|
1603
|
+
break
|
|
1604
|
+
|
|
1605
|
+
# boundary robustness: RMSE of the extreme folds themselves (Low/High), from
|
|
1606
|
+
# the repeated-CV predictions computed by boundary_plot() in utils.py - this
|
|
1607
|
+
# is the headline "Scaled RMSE (Low/High, sorted CV)" number shown in the
|
|
1608
|
+
# report, replacing VERIFY's old single-pass sorted-CV RMSE (see get_verify_scores)
|
|
1609
|
+
for detail_line in summary_lines:
|
|
1610
|
+
if 'Sorted CV extremes (repeated)' in detail_line:
|
|
1611
|
+
rmse_low = float(detail_line.split('RMSE Low = ')[-1].split(',')[0].strip())
|
|
1612
|
+
rmse_high = float(detail_line.split('RMSE High = ')[-1].strip())
|
|
1613
|
+
data_score[f'rmse_low_{suffix}'] = rmse_low
|
|
1614
|
+
data_score[f'rmse_high_{suffix}'] = rmse_high
|
|
1615
|
+
data_score[f'scaled_rmse_low_{suffix}'] = round((rmse_low/data_score[f'y_range_{suffix}'])*100,2)
|
|
1616
|
+
data_score[f'scaled_rmse_high_{suffix}'] = round((rmse_high/data_score[f'y_range_{suffix}'])*100,2)
|
|
1617
|
+
break
|
|
1618
|
+
|
|
1619
|
+
# The split-influence diagnostic compares CV with CV. These
|
|
1620
|
+
# pooled OOF errors belong to the remaining 80% of each
|
|
1621
|
+
# boundary partition, not to its held-out extreme test set.
|
|
1622
|
+
for detail_line in summary_lines:
|
|
1623
|
+
if 'Sorted CV training pools (repeated)' in detail_line:
|
|
1624
|
+
# Accept the previous "CV RMSE vs Low/High" labels too.
|
|
1625
|
+
cv_line = detail_line.replace('CV RMSE vs ', 'CV RMSE ')
|
|
1626
|
+
for side in ('Low', 'High'):
|
|
1627
|
+
data_score[f'rmse_{side.lower()}_cv_{suffix}'] = float(
|
|
1628
|
+
cv_line.split(f'CV RMSE {side} = ')[-1].split(',')[0].strip()
|
|
1629
|
+
)
|
|
1630
|
+
break
|
|
1631
|
+
|
|
1632
|
+
# real range extension - does the model actually predict beyond the range
|
|
1633
|
+
# it was trained on (High: prediction > max value seen in training; Low:
|
|
1634
|
+
# prediction < min value seen), rather than clipping toward the training
|
|
1635
|
+
# boundary? No longer its own scored item - now the penalty inside items
|
|
1636
|
+
# 1/2 (Low/High RMSE), replacing Spearman there (see get_verify_scores() and
|
|
1637
|
+
# calc_penalty_crossing()); still logged by boundary_plot() in utils.py
|
|
1638
|
+
for detail_line in summary_lines:
|
|
1639
|
+
if 'Real range extension (Low/High)' in detail_line:
|
|
1640
|
+
range_line = detail_line
|
|
1641
|
+
data_score[f'crossing_low_{suffix}'] = float(range_line.split('Low crossing = ')[-1].split(',')[0].strip())
|
|
1642
|
+
data_score[f'crossing_high_{suffix}'] = float(range_line.split('High crossing = ')[-1].strip())
|
|
1643
|
+
break
|
|
1644
|
+
|
|
1645
|
+
# degradation ratio baseline: RMSE of each extreme fold's own "remaining
|
|
1646
|
+
# 80%" from the same sorted-CV run (see boundary_plot() in utils.py) -
|
|
1647
|
+
# used instead of the 10x 5-fold CV RMSE so the ratio compares within the
|
|
1648
|
+
# same CV procedure/dataset scope rather than across two different ones
|
|
1649
|
+
for detail_line in summary_lines:
|
|
1650
|
+
if 'Degradation baseline (remaining 80%)' in detail_line:
|
|
1651
|
+
rmse_top80 = float(detail_line.split('vs Low (top 80%) RMSE = ')[-1].split(',')[0].strip())
|
|
1652
|
+
rmse_bottom80 = float(detail_line.split('vs High (bottom 80%) RMSE = ')[-1].strip())
|
|
1653
|
+
data_score[f'scaled_rmse_top80_{suffix}'] = round((rmse_top80/data_score[f'y_range_{suffix}'])*100,2)
|
|
1654
|
+
data_score[f'scaled_rmse_bottom80_{suffix}'] = round((rmse_bottom80/data_score[f'y_range_{suffix}'])*100,2)
|
|
1655
|
+
break
|
|
1656
|
+
|
|
1657
|
+
# boundary robustness components 1b/2b: Spearman rank correlation - internal
|
|
1658
|
+
# (within each fold's own points), logged by boundary_plot() in utils.py.
|
|
1659
|
+
# Now its own dedicated item (used to be a penalty inside items 1/2,
|
|
1660
|
+
# replaced there by the range-extension crossing rate - see get_verify_scores())
|
|
1661
|
+
spearman_global = 0
|
|
1662
|
+
for detail_line in summary_lines:
|
|
1663
|
+
# calculate spread and range ratio penalties (these penalties tackle models with flat predictions)
|
|
1664
|
+
if 'y SD at low extreme' in detail_line:
|
|
1665
|
+
spread_ratio_low = float(detail_line.split()[-1])
|
|
1666
|
+
data_score[f'spread_ratio_low_{suffix}'] = spread_ratio_low
|
|
1667
|
+
spread_penalty_low = spearman_ratio_penalty(spread_ratio_low)
|
|
1668
|
+
if 'y SD at high extreme' in detail_line:
|
|
1669
|
+
spread_ratio_high = float(detail_line.split()[-1])
|
|
1670
|
+
data_score[f'spread_ratio_high_{suffix}'] = spread_ratio_high
|
|
1671
|
+
spread_penalty_high = spearman_ratio_penalty(spread_ratio_high)
|
|
1672
|
+
if 'y range at low extreme' in detail_line:
|
|
1673
|
+
range_ratio_low = float(detail_line.split()[-1])
|
|
1674
|
+
data_score[f'range_ratio_low_{suffix}'] = range_ratio_low
|
|
1675
|
+
range_penalty_low = spearman_ratio_penalty(range_ratio_low)
|
|
1676
|
+
if 'y range at high extreme' in detail_line:
|
|
1677
|
+
range_ratio_high = float(detail_line.split()[-1])
|
|
1678
|
+
data_score[f'range_ratio_high_{suffix}'] = range_ratio_high
|
|
1679
|
+
range_penalty_high = spearman_ratio_penalty(range_ratio_high)
|
|
1680
|
+
# calculate Spearman coefficient scores
|
|
1681
|
+
if 'Spearman rank (Low/High)' in detail_line:
|
|
1682
|
+
spearman_low = float(detail_line.split('Low (internal) = ')[-1].split(',')[0].strip())
|
|
1683
|
+
spearman_high = float(detail_line.split('High (internal) = ')[-1].split(',')[0].strip())
|
|
1684
|
+
data_score[f'spearman_low_{suffix}'] = spearman_low
|
|
1685
|
+
data_score[f'spearman_high_{suffix}'] = spearman_high
|
|
1686
|
+
spearman_global = float(detail_line.split('global = ')[-1].strip())
|
|
1687
|
+
data_score[f'spearman_global_{suffix}'] = spearman_global
|
|
1688
|
+
spearman_score_low = calc_spearman_score(spearman_low)
|
|
1689
|
+
spearman_score_high = calc_spearman_score(spearman_high)
|
|
1690
|
+
# get the most negative penalty between SD and range
|
|
1691
|
+
spearman_penalty_low = min(spread_penalty_low, range_penalty_low)
|
|
1692
|
+
spearman_penalty_high = min(spread_penalty_high, range_penalty_high)
|
|
1693
|
+
final_spearman_low = max(0, min(1, (spearman_score_low + spearman_penalty_low)))
|
|
1694
|
+
final_spearman_high = max(0, min(1, (spearman_score_high + spearman_penalty_high)))
|
|
1695
|
+
data_score[f'spearman_score_low_{suffix}'] = final_spearman_low
|
|
1696
|
+
data_score[f'spearman_score_high_{suffix}'] = final_spearman_high
|
|
1697
|
+
data_score[f'spearman_score_{suffix}'] = final_spearman_high + final_spearman_low
|
|
1698
|
+
break
|
|
1699
|
+
|
|
1700
|
+
# boundary robustness components 1c/2c (degradation ratio) are scored in
|
|
1701
|
+
# get_verify_scores() instead of here - degradation_ratio_low/high_{suffix}
|
|
1702
|
+
# are computed from VERIFY's own sorted-CV data, which calc_score() only
|
|
1703
|
+
# parses AFTER this function returns, so they aren't available yet at this
|
|
1704
|
+
# point (see get_verify_scores() for the actual score computation)
|
|
1705
|
+
|
|
1706
|
+
# boundary robustness sub-metric 3: applicability domain (leverage) -
|
|
1707
|
+
# boundary robustness in X-descriptor space rather than y-space, logged by
|
|
1708
|
+
# applicability_domain_plot() in utils.py. RMSE-only scoring (no rank
|
|
1709
|
+
# penalty here, unlike items 1/2/4), since this is a single 80/20 split
|
|
1710
|
+
# rather than a small ~7-point CV fold
|
|
1711
|
+
data_score[f'applicability_domain_score_{suffix}'] = 0
|
|
1712
|
+
for detail_line in summary_lines:
|
|
1713
|
+
if 'Applicability domain (leverage)' in detail_line:
|
|
1714
|
+
ad_line = detail_line
|
|
1715
|
+
# Legacy DATs only contain an unlabelled test RMSE.
|
|
1716
|
+
# Keep that test metric for scoring; never substitute
|
|
1717
|
+
# it for a missing partition CV RMSE in the grey box.
|
|
1718
|
+
test_label = 'Test RMSE = ' if 'Test RMSE = ' in ad_line else 'RMSE = '
|
|
1719
|
+
rmse_ad = float(ad_line.split(test_label)[-1].split(',')[0].strip())
|
|
1720
|
+
data_score[f'rmse_ad_{suffix}'] = rmse_ad
|
|
1721
|
+
if 'CV RMSE = ' in ad_line:
|
|
1722
|
+
data_score[f'rmse_ad_cv_{suffix}'] = float(
|
|
1723
|
+
ad_line.split('CV RMSE = ')[-1].split(',')[0].strip()
|
|
1724
|
+
)
|
|
1725
|
+
scaled_rmse_ad = round((rmse_ad/data_score[f'y_range_{suffix}'])*100,2)
|
|
1726
|
+
data_score[f'scaled_rmse_ad_{suffix}'] = scaled_rmse_ad
|
|
1727
|
+
data_score[f'applicability_domain_score_{suffix}'] = score_rmse_mcc(pred_type,scaled_rmse_ad)
|
|
1728
|
+
break
|
|
1729
|
+
|
|
1730
|
+
elif pred_type == 'clas': # Process classification: using MCC extracted from CV and Test results
|
|
1731
|
+
for detail_line in summary_lines:
|
|
1732
|
+
if '- Full data ' in detail_line and '-fold CV : Accur. =' in detail_line:
|
|
1733
|
+
for metric, label in (('acc', 'Accur.'), ('f1', 'F1 score'), ('mcc', 'MCC')):
|
|
1734
|
+
data_score[f'{metric}_full_{suffix}'] = float(
|
|
1735
|
+
detail_line.split(f'{label} = ')[-1].split(',')[0].strip()
|
|
1736
|
+
)
|
|
1737
|
+
break
|
|
1738
|
+
# Extract MCC from the CV line (generic match, since the fold count is a
|
|
1739
|
+
# user-settable option via --kfold and isn't always 5)
|
|
1740
|
+
if '-fold CV :' in dat_predict[i+5]:
|
|
1741
|
+
# same "10x 5-fold CV" text the regression branch above already
|
|
1742
|
+
# captures (identical line prefix, see predict_utils.py's shared
|
|
1743
|
+
# CV_type string) - without this, the PDF text kept showing the
|
|
1744
|
+
# hardcoded "10x 5-fold CV" default label even when
|
|
1745
|
+
# --kfold/--repeat_kfolds were customized
|
|
1746
|
+
data_score[f"cv_type_{suffix}"] = ' '.join([ele for ele in dat_predict[i+5].split()[1:4]])
|
|
1747
|
+
parts = dat_predict[i+5].split(',')
|
|
1748
|
+
mcc_cv = None
|
|
1749
|
+
for part in parts:
|
|
1750
|
+
if 'MCC' in part:
|
|
1751
|
+
mcc_cv = float(part.split('=')[-1])
|
|
1752
|
+
break
|
|
1753
|
+
if mcc_cv is not None:
|
|
1754
|
+
data_score[f'r2_cv_{suffix}'] = mcc_cv # storing MCC in a key keyed as r2_cv for consistency
|
|
1755
|
+
# Extract MCC from the Test line
|
|
1756
|
+
if '- Test :' in dat_predict[i+6]:
|
|
1757
|
+
parts = dat_predict[i+6].split(',')
|
|
1758
|
+
mcc_test = None
|
|
1759
|
+
for part in parts:
|
|
1760
|
+
if 'MCC' in part:
|
|
1761
|
+
mcc_test = float(part.split('=')[-1])
|
|
1762
|
+
break
|
|
1763
|
+
if mcc_test is not None:
|
|
1764
|
+
data_score[f'r2_test_{suffix}'] = mcc_test
|
|
1765
|
+
# Compute CV and Test scores using the classification thresholds in score_rmse_mcc
|
|
1766
|
+
data_score[f'cv_score_rmse_{suffix}'] = score_rmse_mcc(pred_type, data_score.get(f'r2_cv_{suffix}', 0))
|
|
1767
|
+
data_score[f'test_score_rmse_{suffix}'] = score_rmse_mcc(pred_type, data_score.get(f'r2_test_{suffix}', 0))
|
|
1768
|
+
|
|
1769
|
+
# For classification, the combined score is simply the score from MCC (no additional penalty)
|
|
1770
|
+
data_score[f'cv_score_combined_{suffix}'] = data_score[f'cv_score_rmse_{suffix}']
|
|
1771
|
+
data_score[f'test_score_combined_{suffix}'] = data_score[f'test_score_rmse_{suffix}']
|
|
1772
|
+
|
|
1773
|
+
# train-vs-validation gap (interpolation, item 4 - homogenized with
|
|
1774
|
+
# regression's B.3b): compares the in-fold training MCC against the
|
|
1775
|
+
# out-of-fold CV MCC (r2_cv_{suffix} above), same ΔMCC thresholds as
|
|
1776
|
+
# item 5's CV-vs-test consistency check (see diff_mcc_score below)
|
|
1777
|
+
data_score[f'train_val_gap_score_{suffix}'] = 0
|
|
1778
|
+
for detail_line in summary_lines:
|
|
1779
|
+
if 'Train fit (in-fold)' in detail_line:
|
|
1780
|
+
parts = detail_line.split(',')
|
|
1781
|
+
mcc_trainfit = None
|
|
1782
|
+
for part in parts:
|
|
1783
|
+
if 'MCC' in part:
|
|
1784
|
+
mcc_trainfit = float(part.split('=')[-1])
|
|
1785
|
+
break
|
|
1786
|
+
if mcc_trainfit is not None:
|
|
1787
|
+
data_score[f'mcc_trainfit_{suffix}'] = mcc_trainfit
|
|
1788
|
+
diff_trainfit = round(abs(data_score.get(f'r2_cv_{suffix}', 0) - mcc_trainfit), 2)
|
|
1789
|
+
data_score[f'diff_trainfit_{suffix}'] = diff_trainfit
|
|
1790
|
+
train_val_gap_score = score_mcc_difference(diff_trainfit)
|
|
1791
|
+
data_score[f'train_val_gap_score_{suffix}'] = train_val_gap_score
|
|
1792
|
+
break
|
|
1793
|
+
|
|
1794
|
+
# Interpolation item 6 - three facets of stability under resampling, each scored
|
|
1795
|
+
# 0-2 with its own threshold, then averaged and rounded into the final item score
|
|
1796
|
+
# (facet (a) unchanged from before; (b)/(c) new, logged by print_predict() in
|
|
1797
|
+
# predict_utils.py right after (a))
|
|
1798
|
+
if pred_type == 'reg':
|
|
1799
|
+
# (a) SD of the repeated-CV predictions in the test set
|
|
1800
|
+
if '- Average SD in test set' in line:
|
|
1801
|
+
cv_sd = float(line.split()[-1])
|
|
1802
|
+
|
|
1803
|
+
# with --test_set 0 there's no test set to average over, so this line
|
|
1804
|
+
# prints "nan" (np.std() of an empty array) - without this guard, the NaN
|
|
1805
|
+
# silently flows into cv_range_cov_{suffix}/cv_4sd_{suffix} and later
|
|
1806
|
+
# crashes adv_cv_sd()'s round() call (ValueError: cannot convert float NaN
|
|
1807
|
+
# to integer) instead of just leaving this facet at its "not available" 0,
|
|
1808
|
+
# the same way score_available already handles a non-standard test split
|
|
1809
|
+
if not np.isnan(cv_sd):
|
|
1810
|
+
cv_4sd = 4*cv_sd
|
|
1811
|
+
y_range_covered = cv_4sd/data_score[f'y_range_{suffix}']
|
|
1812
|
+
|
|
1813
|
+
# Score decreases linearly from +2 at 25% coverage to 0 at 75%.
|
|
1814
|
+
cv_sd_score_a = max(0, min(2, 3 - 4*y_range_covered))
|
|
1815
|
+
|
|
1816
|
+
data_score[f"cv_4sd_{suffix}"] = cv_4sd
|
|
1817
|
+
data_score[f"cv_range_cov_{suffix}"] = y_range_covered
|
|
1818
|
+
data_score[f'cv_sd_score_a_{suffix}'] = cv_sd_score_a
|
|
1819
|
+
|
|
1820
|
+
# (b) SD of the out-of-fold CV predictions themselves (train+validation) - same
|
|
1821
|
+
# gradual 25%-75% scoring as (a), since both use the "4*SD as % of y-range"
|
|
1822
|
+
# convention, just on a different set of predictions
|
|
1823
|
+
if '- Average SD in train+validation (out-of-fold)' in line:
|
|
1824
|
+
cv_sd_train = float(line.split()[-1])
|
|
1825
|
+
cv_4sd_train = 4*cv_sd_train
|
|
1826
|
+
y_range_covered_train = cv_4sd_train/data_score[f'y_range_{suffix}']
|
|
1827
|
+
|
|
1828
|
+
cv_sd_score_b = max(0, min(2, 3 - 4*y_range_covered_train))
|
|
1829
|
+
|
|
1830
|
+
data_score[f"cv_4sd_train_{suffix}"] = cv_4sd_train
|
|
1831
|
+
data_score[f"cv_range_cov_train_{suffix}"] = y_range_covered_train
|
|
1832
|
+
data_score[f'cv_sd_score_b_{suffix}'] = cv_sd_score_b
|
|
1833
|
+
|
|
1834
|
+
# (c) how much the AGGREGATE RMSE itself varies from repeat to repeat (a
|
|
1835
|
+
# dataset-wide view of the same "how much does this depend on the random
|
|
1836
|
+
# split" question (a)/(b) ask per-point) - always the last of the three lines
|
|
1837
|
+
# printed, so (a)/(b) are already available here to combine into the final score
|
|
1838
|
+
if '- RMSE coefficient of variation (10 repeats)' in line:
|
|
1839
|
+
rmse_cv_pct = float(line.split()[-1])
|
|
1840
|
+
# equation for the score: 0 if rmse_cv_pct >= 35, +2 if rmse_cv_pct <= 15, linear in between
|
|
1841
|
+
cv_sd_score_c = max(0, min(2, (35 - rmse_cv_pct)/10))
|
|
1842
|
+
|
|
1843
|
+
data_score[f'rmse_cv_pct_{suffix}'] = rmse_cv_pct
|
|
1844
|
+
data_score[f'cv_sd_score_c_{suffix}'] = cv_sd_score_c
|
|
1845
|
+
|
|
1846
|
+
facet_scores = [data_score.get(f'cv_sd_score_a_{suffix}',0),
|
|
1847
|
+
data_score.get(f'cv_sd_score_b_{suffix}',0),
|
|
1848
|
+
cv_sd_score_c]
|
|
1849
|
+
avg_sd_score = sum(facet_scores)/3
|
|
1850
|
+
avg_sd_score = convert_2_decimal(avg_sd_score)
|
|
1851
|
+
# This is a 0-2 sub-score; the extra half-set penalty must not push it
|
|
1852
|
+
# below zero (which would also produce a non-existent score badge image).
|
|
1853
|
+
data_score[f'cv_sd_score_{suffix}'] = max(0, min(2, avg_sd_score + sd_score_penalty))
|
|
1854
|
+
|
|
1855
|
+
# half-set checks: Spearman inside each 50% half (logged right before the ratio)
|
|
1856
|
+
for half, half_label in (('high', '50% highest data points'), ('low', '50% lowest data points')):
|
|
1857
|
+
if f'- {half_label}' in line and 'Spearman = ' in line:
|
|
1858
|
+
data_score[f'spearman_50_{half}_{suffix}'] = float(line.split('Spearman = ')[1].split(',')[0])
|
|
1859
|
+
data_score[f'y_range_50_{half}_{suffix}'] = float(line.split('y range = ')[1].split(',')[0])
|
|
1860
|
+
|
|
1861
|
+
# penalty
|
|
1862
|
+
if f'- Ratio 50% lowest/highest' in line:
|
|
1863
|
+
rmse_50_ratio_text = line.split('RMSE = ')[-1].strip()
|
|
1864
|
+
rmse_50_factor = symmetric_50_ratio_factor(rmse_50_ratio_text)
|
|
1865
|
+
if rmse_50_factor == 'N/A' or not np.isfinite(rmse_50_factor):
|
|
1866
|
+
data_score[f'absol_rmse_50_ratio_{suffix}'] = rmse_50_factor
|
|
1867
|
+
else:
|
|
1868
|
+
data_score[f'absol_rmse_50_ratio_{suffix}'] = float(
|
|
1869
|
+
Decimal(str(rmse_50_factor)).quantize(
|
|
1870
|
+
Decimal('0.01'), rounding=ROUND_HALF_UP
|
|
1871
|
+
)
|
|
1872
|
+
)
|
|
1873
|
+
|
|
1874
|
+
# Apply whichever half-set penalty is more severe: the symmetric RMSE ratio
|
|
1875
|
+
# (is the error similar in both halves?) or the Spearman rank inside each half
|
|
1876
|
+
# (does the model still rank the points there, or are its predictions flat?)
|
|
1877
|
+
half_penalties = [part_50_penalty(rmse_50_factor)]
|
|
1878
|
+
for half in ('low', 'high'):
|
|
1879
|
+
if f'spearman_50_{half}_{suffix}' in data_score:
|
|
1880
|
+
half_penalty = half_spearman_penalty(data_score[f'spearman_50_{half}_{suffix}'])
|
|
1881
|
+
data_score[f'spearman_50_{half}_penalty_{suffix}'] = half_penalty
|
|
1882
|
+
half_penalties.append(half_penalty)
|
|
1883
|
+
sd_score_penalty = min(half_penalties)
|
|
1884
|
+
|
|
1885
|
+
elif pred_type == 'clas':
|
|
1886
|
+
# Interpolation item 6 for classification: same "how much does this depend
|
|
1887
|
+
# on the random split" question as the regression facets (a)/(b)/(c), all
|
|
1888
|
+
# expressed directly as percentages here (no y-range scaling needed for a
|
|
1889
|
+
# discrete label). (a)/(b) use the disagreement rate between individual CV
|
|
1890
|
+
# repeats and the already majority-voted class (logged by print_predict() in
|
|
1891
|
+
# predict_utils.py); (c) uses the coefficient of variation of the per-repeat
|
|
1892
|
+
# MCC instead of the per-repeat RMSE. All three classification facets use the
|
|
1893
|
+
# gradual 15%-35% scale, matching regression facet (c). These are first-pass
|
|
1894
|
+
# choices mirroring the original scale, not independently
|
|
1895
|
+
# benchmarked the way the rest of the score was (see score.rst note)
|
|
1896
|
+
if '- Average agreement in test set' in line:
|
|
1897
|
+
disagreement_a = 100 - float(line.split()[-1])
|
|
1898
|
+
cv_sd_score_a = max(0, min(2, (35 - disagreement_a)/10))
|
|
1899
|
+
data_score[f'clas_disagree_a_{suffix}'] = round(disagreement_a,1)
|
|
1900
|
+
data_score[f'cv_sd_score_a_{suffix}'] = cv_sd_score_a
|
|
1901
|
+
|
|
1902
|
+
if '- Average agreement in train+validation (out-of-fold)' in line:
|
|
1903
|
+
disagreement_b = 100 - float(line.split()[-1])
|
|
1904
|
+
cv_sd_score_b = max(0, min(2, (35 - disagreement_b)/10))
|
|
1905
|
+
data_score[f'clas_disagree_b_{suffix}'] = round(disagreement_b,1)
|
|
1906
|
+
data_score[f'cv_sd_score_b_{suffix}'] = cv_sd_score_b
|
|
1907
|
+
|
|
1908
|
+
if '- MCC coefficient of variation (10 repeats)' in line:
|
|
1909
|
+
mcc_cv_pct = float(line.split()[-1])
|
|
1910
|
+
cv_sd_score_c = max(0, min(2, (35 - mcc_cv_pct)/10))
|
|
1911
|
+
|
|
1912
|
+
data_score[f'mcc_cv_pct_{suffix}'] = mcc_cv_pct
|
|
1913
|
+
data_score[f'cv_sd_score_c_{suffix}'] = cv_sd_score_c
|
|
1914
|
+
|
|
1915
|
+
facet_scores = [data_score.get(f'cv_sd_score_a_{suffix}',0),
|
|
1916
|
+
data_score.get(f'cv_sd_score_b_{suffix}',0),
|
|
1917
|
+
cv_sd_score_c]
|
|
1918
|
+
avg_facet_score = sum(facet_scores)/3
|
|
1919
|
+
avg_facet_score = convert_2_decimal(avg_facet_score)
|
|
1920
|
+
data_score[f'cv_sd_score_{suffix}'] = avg_facet_score
|
|
1921
|
+
|
|
1922
|
+
if pred_type == 'reg':
|
|
1923
|
+
# The common y-range cancels in each ratio. Compute ratios before
|
|
1924
|
+
# rounding scaled errors so small errors do not round to a zero baseline.
|
|
1925
|
+
for metric, rmse_key in (
|
|
1926
|
+
('cv', 'rmse_cv'), ('high', 'rmse_high_cv'),
|
|
1927
|
+
('low', 'rmse_low_cv'), ('ad', 'rmse_ad_cv'),
|
|
1928
|
+
):
|
|
1929
|
+
data_score[f'full_cv_diff_{metric}_{suffix}'] = cv_error_difference(
|
|
1930
|
+
data_score.get(f'{rmse_key}_{suffix}'), data_score.get(f'rmse_full_{suffix}')
|
|
1931
|
+
)
|
|
1932
|
+
elif pred_type == 'clas':
|
|
1933
|
+
# Classification has interpolation only. The existing r2_cv key holds
|
|
1934
|
+
# its pooled out-of-fold MCC, which can legitimately be negative.
|
|
1935
|
+
data_score[f'full_cv_diff_cv_{suffix}'] = cv_error_difference(
|
|
1936
|
+
data_score.get(f'r2_cv_{suffix}'), data_score.get(f'mcc_full_{suffix}'), allow_signed=True
|
|
1937
|
+
)
|
|
1938
|
+
|
|
1939
|
+
return data_score
|
|
1940
|
+
|
|
1941
|
+
|
|
1942
|
+
def cv_error_difference(value, baseline, allow_signed=False):
|
|
1943
|
+
"""Absolute percentage difference, including signed MCC when requested."""
|
|
1944
|
+
|
|
1945
|
+
if value is None or baseline is None:
|
|
1946
|
+
return None
|
|
1947
|
+
if not np.isfinite(value) or not np.isfinite(baseline):
|
|
1948
|
+
return None
|
|
1949
|
+
if not allow_signed and (value < 0 or baseline < 0):
|
|
1950
|
+
return None
|
|
1951
|
+
if baseline == 0:
|
|
1952
|
+
return 0.0 if value == 0 else float('inf')
|
|
1953
|
+
return abs(value/baseline - 1)*100
|
|
1954
|
+
|
|
1955
|
+
|
|
1956
|
+
def score_rmse_mcc(pred_type,scaledrmse_mcc_val):
|
|
1957
|
+
'''
|
|
1958
|
+
Calculate scores for R2 and MCC using predetermined thresholds
|
|
1959
|
+
|
|
1960
|
+
For regression (scaled RMSE): 0-2 points
|
|
1961
|
+
For classification (MCC): 0-2 points, same scale as regression (homogenized so both
|
|
1962
|
+
prediction types share the same 0-2 tiers/max everywhere in Section B)
|
|
1963
|
+
'''
|
|
1964
|
+
|
|
1965
|
+
r2_mcc_score = 0
|
|
1966
|
+
|
|
1967
|
+
if pred_type == 'reg': # scaled RMSE
|
|
1968
|
+
# equation for the score: 0 if scaled RMSE >= 30, +2 if scaled RMSE <= 10, linear in between
|
|
1969
|
+
r2_mcc_score = max(0, min(2, (30 - scaledrmse_mcc_val)/10))
|
|
1970
|
+
r2_mcc_score = convert_2_decimal(r2_mcc_score)
|
|
1971
|
+
|
|
1972
|
+
|
|
1973
|
+
else: # MCC
|
|
1974
|
+
# equation for the score: 0 if MCC <= 0, +2 if MCC >= 0.6, linear in between
|
|
1975
|
+
r2_mcc_score = max(0, min(2, scaledrmse_mcc_val/0.3))
|
|
1976
|
+
r2_mcc_score = convert_2_decimal(r2_mcc_score)
|
|
1977
|
+
|
|
1978
|
+
return r2_mcc_score
|
|
1979
|
+
|
|
1980
|
+
|
|
1981
|
+
def safe_ratio(numerator,denominator):
|
|
1982
|
+
'''
|
|
1983
|
+
Ratio between two errors that can round to exactly 0 (near-perfect fits): 0/0 means no
|
|
1984
|
+
difference between them (0), while a nonzero error over a zero baseline is an unbounded
|
|
1985
|
+
degradation (inf), never the best-case ratio
|
|
1986
|
+
'''
|
|
1987
|
+
|
|
1988
|
+
if denominator > 0:
|
|
1989
|
+
return numerator / denominator
|
|
1990
|
+
return 0 if numerator == 0 else float('inf')
|
|
1991
|
+
|
|
1992
|
+
|
|
1993
|
+
def calc_penalty_r2(r2_val):
|
|
1994
|
+
'''
|
|
1995
|
+
Calculate scores for R2 and MCC using predetermined thresholds
|
|
1996
|
+
'''
|
|
1997
|
+
|
|
1998
|
+
# equation for the penalty: 0 if R2 >= 0.8, -2 if R2 <= 0.4, linear in between. R2 is the
|
|
1999
|
+
# coefficient of determination (Q2 for the CV predictions); a test R2 > 0.6 is "good" in
|
|
2000
|
+
# Alexander, Tropsha and Winkler (J. Chem. Inf. Model. 2015), which here costs 1 point, and
|
|
2001
|
+
# R2 >= 0.8 matches the scaled RMSE that already gets full points (~10% of the y range)
|
|
2002
|
+
penalty_r2 = max(-2, min(0, 5*(r2_val - 0.8)))
|
|
2003
|
+
penalty_r2 = convert_2_decimal(penalty_r2)
|
|
2004
|
+
|
|
2005
|
+
|
|
2006
|
+
return penalty_r2
|
|
2007
|
+
|
|
2008
|
+
|
|
2009
|
+
def calc_penalty_crossing(crossing_rate):
|
|
2010
|
+
'''
|
|
2011
|
+
Penalty for the "real range extension" crossing rate (fraction of Low/High predictions that
|
|
2012
|
+
actually land beyond the training range, rather than clipping toward the training
|
|
2013
|
+
boundary), used for the Low/High sub-metrics - same 0.5/0.2 tier shape as a Spearman-based
|
|
2014
|
+
penalty would use, just swapped to the crossing rate metric (see discussion with the
|
|
2015
|
+
user: Spearman rank gets its own dedicated item instead of penalizing here).
|
|
2016
|
+
'''
|
|
2017
|
+
|
|
2018
|
+
# equation for the penalty: 0 if crossing_rate >= 0.8, -2 if crossing_rate <= 0.2, linear in between
|
|
2019
|
+
penalty_crossing = max(-2, min(0, (crossing_rate - 0.8)/0.3))
|
|
2020
|
+
penalty_crossing = convert_2_decimal(penalty_crossing)
|
|
2021
|
+
|
|
2022
|
+
return penalty_crossing
|
|
2023
|
+
|
|
2024
|
+
|
|
2025
|
+
def repro_info(modules,model_suffix=''):
|
|
2026
|
+
"""
|
|
2027
|
+
Retrieves variables used in the Reproducibility section. model_suffix (e.g. '_RF') reads
|
|
2028
|
+
the per-model log split off by VERIFY/PREDICT under --all_models instead of the normal
|
|
2029
|
+
shared VERIFY_data.dat/PREDICT_data.dat - only applies to those two modules, since
|
|
2030
|
+
CURATE/GENERATE run once for the whole dataset and are never split per model.
|
|
2031
|
+
"""
|
|
2032
|
+
|
|
2033
|
+
version_n_date, citation, command_line = '','',''
|
|
2034
|
+
python_version, total_time = '',0
|
|
2035
|
+
dat_files = {}
|
|
2036
|
+
for module in modules:
|
|
2037
|
+
file_suffix = model_suffix if module in ('VERIFY','PREDICT') else ''
|
|
2038
|
+
path_file = Path(f'{os.getcwd()}/{module}/{module}{file_suffix}_data.dat')
|
|
2039
|
+
if os.path.exists(path_file):
|
|
2040
|
+
txt_file = []
|
|
2041
|
+
with open(path_file, 'r', encoding= 'utf-8', errors="replace") as datfile:
|
|
2042
|
+
for line in datfile:
|
|
2043
|
+
txt_file.append(line)
|
|
2044
|
+
if 'Time' in line and 'seconds' in line:
|
|
2045
|
+
total_time += float(line.split()[2])
|
|
2046
|
+
if 'How to cite: ' in line:
|
|
2047
|
+
citation = line.split('How to cite: ')[1]
|
|
2048
|
+
if 'ROBERT v' == line[:8]:
|
|
2049
|
+
version_n_date = line
|
|
2050
|
+
if 'Command line used in ROBERT: ' in line:
|
|
2051
|
+
if '--csv_name' not in command_line: # ensures that the value for --csv_name is stored
|
|
2052
|
+
command_line = line.split('Command line used in ROBERT: ')[1]
|
|
2053
|
+
total_time = round(total_time,2)
|
|
2054
|
+
dat_files[module] = txt_file
|
|
2055
|
+
|
|
2056
|
+
try:
|
|
2057
|
+
import platform
|
|
2058
|
+
python_version = platform.python_version()
|
|
2059
|
+
except:
|
|
2060
|
+
python_version = '(version could not be determined)'
|
|
2061
|
+
|
|
2062
|
+
# Split after the end marker of the main ROBERT citation (robert_ref in utils.py), leaving
|
|
2063
|
+
# the following low-data-regimes citation for its own row in the report.
|
|
2064
|
+
citation_main, citation_second = citation.strip(), ''
|
|
2065
|
+
lowdata_marker = 'e1733.'
|
|
2066
|
+
if lowdata_marker in citation:
|
|
2067
|
+
split_idx = citation.index(lowdata_marker) + len(lowdata_marker)
|
|
2068
|
+
citation_main = citation[:split_idx].strip()
|
|
2069
|
+
citation_second = citation[split_idx:].strip()
|
|
2070
|
+
|
|
2071
|
+
return version_n_date, citation_main, citation_second, command_line, python_version, total_time, dat_files
|
|
2072
|
+
|
|
2073
|
+
|
|
2074
|
+
def make_report(report_html, HTML, pdf_name='ROBERT_report.pdf'):
|
|
2075
|
+
"""
|
|
2076
|
+
Generate a css file that will be used to make the PDF file
|
|
2077
|
+
"""
|
|
2078
|
+
|
|
2079
|
+
css_files = ["report.css"]
|
|
2080
|
+
outfile = f"{os.getcwd()}/{pdf_name}"
|
|
2081
|
+
if os.path.exists(outfile):
|
|
2082
|
+
try:
|
|
2083
|
+
os.remove(outfile)
|
|
2084
|
+
except PermissionError:
|
|
2085
|
+
print(f'\nx {pdf_name} is open! Please, close the PDF file and run ROBERT again with --report (i.e., "python -m robert --report").')
|
|
2086
|
+
sys.exit()
|
|
2087
|
+
pdf = make_pdf(report_html, HTML, css_files)
|
|
2088
|
+
if SCORE_INFO_SCHEME in report_html:
|
|
2089
|
+
pdf = add_score_info_popups(pdf)
|
|
2090
|
+
_ = Path(outfile).write_bytes(pdf)
|
|
2091
|
+
|
|
2092
|
+
|
|
2093
|
+
def make_pdf(html, HTML, css_files):
|
|
2094
|
+
"""Generate a PDF file from a string of HTML"""
|
|
2095
|
+
htmldoc = HTML(string=html, base_url="")
|
|
2096
|
+
if css_files:
|
|
2097
|
+
htmldoc = htmldoc.write_pdf(stylesheets=css_files)
|
|
2098
|
+
else:
|
|
2099
|
+
htmldoc = htmldoc.write_pdf()
|
|
2100
|
+
return htmldoc
|
|
2101
|
+
|
|
2102
|
+
|
|
2103
|
+
def css_content(csv_name,robert_version,eval_only=False):
|
|
2104
|
+
"""
|
|
2105
|
+
Obtain ROBERT version and CSV name to use it on top of the PDF report. eval_only=True
|
|
2106
|
+
(CHECKML reports, scoring a model the user already chose) shows "CheckML Report" in the
|
|
2107
|
+
top-left running header instead of "ROBERT Report", matching the CheckML logo used in
|
|
2108
|
+
print_header() for the same reports.
|
|
2109
|
+
"""
|
|
2110
|
+
|
|
2111
|
+
report_title = 'CheckML Report' if eval_only else 'ROBERT Report'
|
|
2112
|
+
|
|
2113
|
+
css_content = f"""
|
|
2114
|
+
body {{
|
|
2115
|
+
font-size: 12px;
|
|
2116
|
+
line-height: 1.5;
|
|
2117
|
+
}}
|
|
2118
|
+
@page {{
|
|
2119
|
+
size: A4;
|
|
2120
|
+
margin: 2cm;
|
|
2121
|
+
@bottom-right {{
|
|
2122
|
+
content: "Page "counter(page) " of " counter(pages);
|
|
2123
|
+
font-size: 8pt;
|
|
2124
|
+
position: fixed;
|
|
2125
|
+
right: 0;
|
|
2126
|
+
bottom: 0;
|
|
2127
|
+
transform: translateY(-8pt);
|
|
2128
|
+
white-space: nowrap;
|
|
2129
|
+
}}
|
|
2130
|
+
@bottom-left {{
|
|
2131
|
+
content: "ROBERT v {robert_version}";
|
|
2132
|
+
font-size: 8pt;
|
|
2133
|
+
position: fixed;
|
|
2134
|
+
left: 0;
|
|
2135
|
+
bottom: 0;
|
|
2136
|
+
transform: translateY(-8pt);
|
|
2137
|
+
white-space: nowrap;
|
|
2138
|
+
}}
|
|
2139
|
+
@bottom-center {{
|
|
2140
|
+
content: "";
|
|
2141
|
+
border-top: 3px solid black;
|
|
2142
|
+
width: 100%;
|
|
2143
|
+
position: fixed;
|
|
2144
|
+
left: 0;
|
|
2145
|
+
right: 0;
|
|
2146
|
+
bottom: 0pt;
|
|
2147
|
+
transform: translateY(8pt);
|
|
2148
|
+
}}
|
|
2149
|
+
@top-center {{
|
|
2150
|
+
content: "";
|
|
2151
|
+
border-top: 3px solid black;
|
|
2152
|
+
width: 100%;
|
|
2153
|
+
position: fixed;
|
|
2154
|
+
left: 0;
|
|
2155
|
+
right: 0;
|
|
2156
|
+
bottom: 0pt;
|
|
2157
|
+
transform: translateY(40pt);
|
|
2158
|
+
}}
|
|
2159
|
+
@top-left {{
|
|
2160
|
+
content: "{report_title}";
|
|
2161
|
+
font-size: 8pt;
|
|
2162
|
+
font-weight:bold;
|
|
2163
|
+
position: fixed;
|
|
2164
|
+
position: fixed;
|
|
2165
|
+
left: 0;
|
|
2166
|
+
right: 0;
|
|
2167
|
+
bottom: 0pt;
|
|
2168
|
+
transform: translateY(2pt);
|
|
2169
|
+
white-space: nowrap;
|
|
2170
|
+
}}
|
|
2171
|
+
@top-right {{
|
|
2172
|
+
content: "{csv_name}";
|
|
2173
|
+
font-size: 8pt;
|
|
2174
|
+
font-style: italic;
|
|
2175
|
+
position: fixed;
|
|
2176
|
+
position: fixed;
|
|
2177
|
+
left: 0;
|
|
2178
|
+
right: 0;
|
|
2179
|
+
bottom: 0pt;
|
|
2180
|
+
transform: translateY(2pt);
|
|
2181
|
+
white-space: nowrap;
|
|
2182
|
+
}}
|
|
2183
|
+
}}
|
|
2184
|
+
* {{
|
|
2185
|
+
font-family: "Helvetica", Arial, sans-serif;
|
|
2186
|
+
}}
|
|
2187
|
+
.dat-content {{
|
|
2188
|
+
width: 50%;
|
|
2189
|
+
max-width: 595pt;
|
|
2190
|
+
overflow-x: auto;
|
|
2191
|
+
line-height: 1.2;
|
|
2192
|
+
}}
|
|
2193
|
+
|
|
2194
|
+
img[src="Robert_logo.jpg"] {{
|
|
2195
|
+
float: center;
|
|
2196
|
+
}}
|
|
2197
|
+
img[src*="Pearson"] {{
|
|
2198
|
+
display: inline-block;
|
|
2199
|
+
vertical-align: bottom;
|
|
2200
|
+
max-width: 48%;
|
|
2201
|
+
margin-left: 10px;
|
|
2202
|
+
margin-bottom: -5px;
|
|
2203
|
+
}}
|
|
2204
|
+
img[src*="PFI"] {{
|
|
2205
|
+
display: inline-block;
|
|
2206
|
+
vertical-align: bottom;
|
|
2207
|
+
max-width: 48%;
|
|
2208
|
+
margin-left: 10px;
|
|
2209
|
+
margin-bottom: -5px;
|
|
2210
|
+
}}
|
|
2211
|
+
|
|
2212
|
+
img[src*="PFI"]:first-child {{
|
|
2213
|
+
margin-right: 10%;
|
|
2214
|
+
}}
|
|
2215
|
+
.img-PREDICT {{
|
|
2216
|
+
margin-top: 20px;
|
|
2217
|
+
}}
|
|
2218
|
+
|
|
2219
|
+
hr.black {{
|
|
2220
|
+
border: none;
|
|
2221
|
+
height: 3px;
|
|
2222
|
+
background-color: black;
|
|
2223
|
+
}}
|
|
2224
|
+
|
|
2225
|
+
hr {{
|
|
2226
|
+
border: none;
|
|
2227
|
+
height: 1px;
|
|
2228
|
+
background-color: gray;
|
|
2229
|
+
}}
|
|
2230
|
+
|
|
2231
|
+
body:before {{
|
|
2232
|
+
top: 1.2cm;
|
|
2233
|
+
}}
|
|
2234
|
+
"""
|
|
2235
|
+
return css_content
|
|
2236
|
+
|
|
2237
|
+
|
|
2238
|
+
def format_lines(module_data, max_width=122, cmd_line=False, one_column=False, spacing=''):
|
|
2239
|
+
"""
|
|
2240
|
+
Reads a file and returns a formatted string between two markers
|
|
2241
|
+
"""
|
|
2242
|
+
|
|
2243
|
+
formatted_lines = []
|
|
2244
|
+
lines = module_data.split('\n')
|
|
2245
|
+
for i,line in enumerate(lines):
|
|
2246
|
+
if 'R2' in line:
|
|
2247
|
+
line = line.replace('R2','R<sup>2</sup>')
|
|
2248
|
+
if cmd_line:
|
|
2249
|
+
formatted_line = textwrap.fill(line, width=max_width-5, subsequent_indent='')
|
|
2250
|
+
else:
|
|
2251
|
+
formatted_line = textwrap.fill(line, width=max_width, subsequent_indent='')
|
|
2252
|
+
if i > 0:
|
|
2253
|
+
formatted_lines.append(f'<pre style="text-align: justify;">\n{formatted_line}</pre>')
|
|
2254
|
+
else:
|
|
2255
|
+
formatted_lines.append(f'<pre style="text-align: justify;">{formatted_line}</pre>\n')
|
|
2256
|
+
|
|
2257
|
+
# for two columns
|
|
2258
|
+
if not one_column:
|
|
2259
|
+
return ''.join(formatted_lines)
|
|
2260
|
+
|
|
2261
|
+
# for one column
|
|
2262
|
+
one_col_lines = ''
|
|
2263
|
+
for line in ''.join(formatted_lines).split('\n'):
|
|
2264
|
+
if line.startswith('<pre style="text-align: justify;">') and line != '<pre style="text-align: justify;">':
|
|
2265
|
+
one_col_lines += line.replace('<pre style="text-align: justify;">',f'<pre style="text-align: justify;">{spacing*3}')
|
|
2266
|
+
elif not line.startswith('<'):
|
|
2267
|
+
one_col_lines += f'\n{spacing*3}{line}'
|
|
2268
|
+
else:
|
|
2269
|
+
one_col_lines += f'\n{line}'
|
|
2270
|
+
return one_col_lines
|