almos-kit 1.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.
- almos/__init__.py +0 -0
- almos/__main__.py +20 -0
- almos/al.py +522 -0
- almos/al_utils.py +1694 -0
- almos/almos.py +54 -0
- almos/argument_parser.py +258 -0
- almos/cluster.py +4627 -0
- almos/cluster_utils.py +2669 -0
- almos/easyalmos/__init__.py +3 -0
- almos/easyalmos/easyalmos.py +986 -0
- almos/icons/almos_icon.png +0 -0
- almos/icons/almos_logo.png +0 -0
- almos/icons/almos_logo_old.png +0 -0
- almos/icons/old.jpg +0 -0
- almos/icons/overview_almos_2.jpg +0 -0
- almos/package_versions.py +4 -0
- almos/utils.py +456 -0
- almos_kit-1.2.0.dist-info/METADATA +47 -0
- almos_kit-1.2.0.dist-info/RECORD +23 -0
- almos_kit-1.2.0.dist-info/WHEEL +5 -0
- almos_kit-1.2.0.dist-info/entry_points.txt +9 -0
- almos_kit-1.2.0.dist-info/licenses/LICENSE +21 -0
- almos_kit-1.2.0.dist-info/top_level.txt +1 -0
almos/__init__.py
ADDED
|
File without changes
|
almos/__main__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
|
|
3
|
+
###############################################.
|
|
4
|
+
# __main__ file for the code #
|
|
5
|
+
###############################################.
|
|
6
|
+
|
|
7
|
+
from __future__ import absolute_import
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
from almos import almos
|
|
11
|
+
|
|
12
|
+
# If we are running from a wheel, add the wheel to sys.path
|
|
13
|
+
# This allows the usage python pip-*.whl/pip install pip-*.whl
|
|
14
|
+
|
|
15
|
+
if __package__ != 'almos':
|
|
16
|
+
print('ALMOS is not installed! Use: pip install almos (anywhere, using a terminal) or python setup.py install (from the downloaded /almos/almos folder).')
|
|
17
|
+
|
|
18
|
+
if __name__ == '__main__':
|
|
19
|
+
almos.main()
|
|
20
|
+
sys.exit()
|
almos/al.py
ADDED
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Parameters
|
|
3
|
+
----------
|
|
4
|
+
al : bool
|
|
5
|
+
Indicates whether the active learning process is enabled and should be performed. Defaults to "False".
|
|
6
|
+
This parameter is activated in command line (i.e. --al)
|
|
7
|
+
csv_name : str
|
|
8
|
+
Name of the CSV file containing the database. (i.e. 'FILE.csv').
|
|
9
|
+
y : str
|
|
10
|
+
Name of the column containing the response variable in the input CSV file (i.e. 'solubility').
|
|
11
|
+
name : str
|
|
12
|
+
Name of the column containing the molecule names in the input CSV file (i.e. 'names').
|
|
13
|
+
ignore : list, default=[]
|
|
14
|
+
List containing the columns of the input CSV file that will be ignored during the ROBERT process
|
|
15
|
+
(i.e. --ignore "[name,SMILES]"). The descriptors will be included in the final CSV file. The y value, name column and batch column
|
|
16
|
+
are automatically ignored by ROBERT.
|
|
17
|
+
n_exps : int,
|
|
18
|
+
Number of experiments to be selected in the active learning process for the new batch. (i.e. '--n_exps 10')
|
|
19
|
+
If not provided or invalid, the program will request the values in the proper format.
|
|
20
|
+
tolerance : str, default='medium'
|
|
21
|
+
Indicates the tolerance level for the convergence process, defining the percentage change threshold required for convergence. Options:
|
|
22
|
+
1. 'tight': Strictest level, convergence occurs if the metric improves by ≤1% (threshold = 0.01).
|
|
23
|
+
2. 'medium': Balanced level, convergence occurs if the metric improves by ≤5% (threshold = 0.05).
|
|
24
|
+
3. 'wide': Least strict, convergence occurs if the metric improves by ≤10% (threshold = 0.10).
|
|
25
|
+
(i.e. '--tolerance tight')
|
|
26
|
+
robert_keywords : str, default=""
|
|
27
|
+
Additional keywords to be passed to the ROBERT model generation (i.e. --robert_keywords "--model RF --train [70] --seed [0]")
|
|
28
|
+
objective : str
|
|
29
|
+
Optimization direction for hit selection. Always required and must be 'max' or 'min'. (i.e. '--objective max')
|
|
30
|
+
mode : str, optional
|
|
31
|
+
Optional manual override for the acquisition strategy. Use 'model' to rank by uncertainty or 'hit' to rank by
|
|
32
|
+
prediction with uncertainty. If omitted, ALMOS selects the strategy automatically from the model score.
|
|
33
|
+
alpha : float, optional
|
|
34
|
+
Optional acquisition weight used in hit mode. It also overrides the automatic alpha when the strategy is auto
|
|
35
|
+
and the selected score activates hit ranking. (i.e. '--alpha 0.5' or '--alfa 0.5')
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
#####################################################
|
|
39
|
+
# This file stores the AL class #
|
|
40
|
+
# used in the active learning process #
|
|
41
|
+
#####################################################
|
|
42
|
+
|
|
43
|
+
import pandas as pd
|
|
44
|
+
import time
|
|
45
|
+
import os , sys
|
|
46
|
+
from pathlib import Path
|
|
47
|
+
import re
|
|
48
|
+
import shutil
|
|
49
|
+
import matplotlib
|
|
50
|
+
matplotlib.use('Agg') # Use 'Agg' backend for non-interactive plotting
|
|
51
|
+
from almos.utils import (
|
|
52
|
+
load_variables,
|
|
53
|
+
check_dependencies
|
|
54
|
+
)
|
|
55
|
+
from almos.al_utils import (
|
|
56
|
+
get_metrics_from_batches,
|
|
57
|
+
EarlyStopping,
|
|
58
|
+
plot_metrics_subplots,
|
|
59
|
+
get_scores_from_robert_report,
|
|
60
|
+
resolve_active_learning_strategy,
|
|
61
|
+
rank_active_learning_candidates,
|
|
62
|
+
write_log_header,
|
|
63
|
+
write_log_block,
|
|
64
|
+
format_objective_label,
|
|
65
|
+
format_strategy_label,
|
|
66
|
+
format_strategy_reason,
|
|
67
|
+
format_score_regime_label,
|
|
68
|
+
format_score_interpretation,
|
|
69
|
+
format_score_explanation,
|
|
70
|
+
build_selected_candidates_preview,
|
|
71
|
+
format_text_table,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class al:
|
|
76
|
+
"""
|
|
77
|
+
Class containing all the functions from the active almos module
|
|
78
|
+
|
|
79
|
+
"""
|
|
80
|
+
def __init__(self, **kwargs):
|
|
81
|
+
|
|
82
|
+
# Initialize the timer
|
|
83
|
+
start_time_overall = time.time()
|
|
84
|
+
|
|
85
|
+
# load default and user-specified variables
|
|
86
|
+
self.args = load_variables(kwargs, "al")
|
|
87
|
+
|
|
88
|
+
# Check runtime dependencies required by AL
|
|
89
|
+
_ = check_dependencies(self, "al")
|
|
90
|
+
|
|
91
|
+
# run robert model updated and generate predictions
|
|
92
|
+
self.run_robert_process()
|
|
93
|
+
|
|
94
|
+
# run active learning process for selecting points for the new batch
|
|
95
|
+
self.active_learning_process()
|
|
96
|
+
|
|
97
|
+
# Check for convergence in the batches
|
|
98
|
+
# Get metrics from batches
|
|
99
|
+
results_plot_no_PFI, results_plot_PFI = get_metrics_from_batches()
|
|
100
|
+
|
|
101
|
+
# Initialize EarlyStopping to check for convergence
|
|
102
|
+
early_stopping = EarlyStopping(
|
|
103
|
+
logger=self.args.log,
|
|
104
|
+
rmse_min_delta = self.args.levels_tolerance[self.args.tolerance],
|
|
105
|
+
sd_min_delta = self.args.levels_tolerance[self.args.tolerance],
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
results_plot_no_pfi_df, results_plot_pfi_df = early_stopping.check_convergence(
|
|
109
|
+
results_plot_no_PFI, results_plot_PFI
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# Generate plots
|
|
113
|
+
self.generate_plots(results_plot_no_pfi_df, results_plot_pfi_df)
|
|
114
|
+
|
|
115
|
+
# Log the total time and finalize
|
|
116
|
+
self.finalize_process(start_time_overall)
|
|
117
|
+
|
|
118
|
+
def run_robert_process(self):
|
|
119
|
+
"""
|
|
120
|
+
Executes the full ROBERT model update and prediction process.
|
|
121
|
+
|
|
122
|
+
This method performs the following steps:
|
|
123
|
+
- Initializes a logger to record process details and parameters.
|
|
124
|
+
- Filters the input data to create a CSV file for updating the ROBERT model.
|
|
125
|
+
- Creates necessary directories and moves files as required.
|
|
126
|
+
- Runs the ROBERT model update command, including the prediction CSV via ``--csv_test``.
|
|
127
|
+
- Checks for successful generation of the model report.
|
|
128
|
+
- Verifies that predictions were successfully created and logs the result.
|
|
129
|
+
|
|
130
|
+
Raises:
|
|
131
|
+
SystemExit: Exits the program if any step fails or if required files are not found.
|
|
132
|
+
"""
|
|
133
|
+
# Get the base name of the CSV file without the extension if the csv is introduced as path
|
|
134
|
+
self.args.csv_name = os.path.basename(self.args.csv_name)
|
|
135
|
+
self.args.base_name_raw = os.path.splitext(self.args.csv_name)[0]
|
|
136
|
+
|
|
137
|
+
# Handle cases of different batches (i.e test_b1, test_b2, etc), in order to extract the base name.
|
|
138
|
+
base_name = os.path.splitext(self.args.csv_name)[0]
|
|
139
|
+
match = re.match(r"^(.*)_b\d+$", base_name)
|
|
140
|
+
if match:
|
|
141
|
+
# If the name matches the pattern, extract the base name
|
|
142
|
+
self.args.base_name = match.group(1)
|
|
143
|
+
else:
|
|
144
|
+
# Otherwise, use the entire base name
|
|
145
|
+
self.args.base_name = self.args.base_name_raw
|
|
146
|
+
|
|
147
|
+
# Initialize the logger
|
|
148
|
+
write_log_header(self.args.log, "Starting Active Learning Process")
|
|
149
|
+
write_log_block(
|
|
150
|
+
self.args.log,
|
|
151
|
+
"Input summary",
|
|
152
|
+
[
|
|
153
|
+
("Data file", self.args.csv_name),
|
|
154
|
+
("Identifier column", self.args.name),
|
|
155
|
+
("Target column", self.args.y),
|
|
156
|
+
("Experiments requested", self.args.n_exps),
|
|
157
|
+
(
|
|
158
|
+
"Optimization objective",
|
|
159
|
+
format_objective_label(self.args.objective)
|
|
160
|
+
if self.args.al_mode != "model"
|
|
161
|
+
else "not used in model mode",
|
|
162
|
+
),
|
|
163
|
+
("Selection mode request", self.args.al_mode or "auto"),
|
|
164
|
+
(
|
|
165
|
+
"Alpha override",
|
|
166
|
+
"automatic" if self.args.alpha is None else self.args.alpha,
|
|
167
|
+
),
|
|
168
|
+
("Ignored columns", self.args.ignore),
|
|
169
|
+
(
|
|
170
|
+
"Convergence tolerance",
|
|
171
|
+
f"{self.args.tolerance} ({self.args.levels_tolerance[self.args.tolerance] * 100:.2f}%)",
|
|
172
|
+
),
|
|
173
|
+
],
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
# Main directory for the process
|
|
177
|
+
self.main_folder = os.getcwd()
|
|
178
|
+
|
|
179
|
+
# Filter rows where value in the batch_column is not NaN for updating the model
|
|
180
|
+
robert_model_df = self.args.df_raw[self.args.df_raw[self.args.batch_column].notna()]
|
|
181
|
+
|
|
182
|
+
# Ensure the folder for ROBERT model results exists
|
|
183
|
+
self.robert_folder = f'ROBERT_b{self.args.current_number_batch}'
|
|
184
|
+
robert_path = Path(self.main_folder) / self.robert_folder
|
|
185
|
+
robert_path.mkdir(parents=True, exist_ok=True)
|
|
186
|
+
|
|
187
|
+
# Create and save the CSV file inside the folder
|
|
188
|
+
filename_model_csv = robert_path / f"{self.args.base_name}_ROBERT_b{self.args.current_number_batch}.csv"
|
|
189
|
+
try:
|
|
190
|
+
robert_model_df.to_csv(filename_model_csv, index=False)
|
|
191
|
+
print(f"o File successfully saved: {filename_model_csv}")
|
|
192
|
+
|
|
193
|
+
except Exception as e:
|
|
194
|
+
print(f"x WARNING! Could not save the file: {e}")
|
|
195
|
+
sys.exit()
|
|
196
|
+
|
|
197
|
+
# Change to the newly created ROBERT directory
|
|
198
|
+
os.chdir(robert_path)
|
|
199
|
+
|
|
200
|
+
robert_ignore_update = self._sanitize_ignore_columns(robert_model_df.columns)
|
|
201
|
+
robert_ignore_update_cli = self._format_robert_ignore(robert_ignore_update)
|
|
202
|
+
|
|
203
|
+
# Define paths for the source file and destination directory
|
|
204
|
+
source = os.path.join(self.args.path_csv_name)
|
|
205
|
+
destination_dir = Path(Path.cwd().parent, self.robert_folder) # Ensure destination is a directory
|
|
206
|
+
destination_dir.mkdir(parents=True, exist_ok=True) # Create the directory if it doesn't exist
|
|
207
|
+
destination = destination_dir / Path(source).name # Complete path for the destination file
|
|
208
|
+
|
|
209
|
+
# Check if the source file exists before copying
|
|
210
|
+
if os.path.isfile(source):
|
|
211
|
+
# Copy the file from source to destination so ROBERT can train and predict in one run
|
|
212
|
+
shutil.copy(source, destination)
|
|
213
|
+
else:
|
|
214
|
+
print(f"o File '{self.args.csv_name}' was not found for generate predictions! Exiting.")
|
|
215
|
+
|
|
216
|
+
robert_ignore_predict = self._sanitize_ignore_columns(self.args.df_raw.columns)
|
|
217
|
+
robert_ignore_predict_cli = self._format_robert_ignore(robert_ignore_predict)
|
|
218
|
+
|
|
219
|
+
# Build and run the command for updating the ROBERT model
|
|
220
|
+
command = (
|
|
221
|
+
f'python -u -m robert --csv_name "{filename_model_csv}" '
|
|
222
|
+
f'--csv_test "{destination}" '
|
|
223
|
+
f'--name "{self.args.name}" '
|
|
224
|
+
f'--y {self.args.y} '
|
|
225
|
+
f'--ignore "{robert_ignore_predict_cli}" '
|
|
226
|
+
f'{self.args.robert_keywords}'
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
write_log_header(self.args.log, "ROBERT Model Update")
|
|
230
|
+
write_log_block(
|
|
231
|
+
self.args.log,
|
|
232
|
+
"Training data prepared",
|
|
233
|
+
[
|
|
234
|
+
("Rows used for model update", len(robert_model_df)),
|
|
235
|
+
("Working folder", self.robert_folder),
|
|
236
|
+
("Training CSV", filename_model_csv.name),
|
|
237
|
+
("Prediction CSV", destination.name),
|
|
238
|
+
("ROBERT ignore list", robert_ignore_predict_cli),
|
|
239
|
+
],
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
# Run the command and check for errors
|
|
243
|
+
exit_code = os.system(command)
|
|
244
|
+
if exit_code != 0:
|
|
245
|
+
self.args.log.write(f"x WARNING! Command failed with exit code {exit_code}. Exiting.\n")
|
|
246
|
+
sys.exit(exit_code)
|
|
247
|
+
|
|
248
|
+
# Check if the ROBERT model report was generated
|
|
249
|
+
if os.path.exists('ROBERT_report.pdf'):
|
|
250
|
+
write_log_block(
|
|
251
|
+
self.args.log,
|
|
252
|
+
"ROBERT update result",
|
|
253
|
+
[
|
|
254
|
+
("Status", "model generated successfully"),
|
|
255
|
+
("Report file", "ROBERT_report.pdf"),
|
|
256
|
+
],
|
|
257
|
+
)
|
|
258
|
+
else:
|
|
259
|
+
self.args.log.write("\nx WARNING! ROBERT model was not generated\n")
|
|
260
|
+
sys.exit()
|
|
261
|
+
|
|
262
|
+
# Predictions are generated in the same ROBERT run via --csv_test.
|
|
263
|
+
write_log_header(self.args.log, "Prediction Generation")
|
|
264
|
+
write_log_block(
|
|
265
|
+
self.args.log,
|
|
266
|
+
"Prediction request",
|
|
267
|
+
[
|
|
268
|
+
("Prediction CSV", destination.name),
|
|
269
|
+
("ROBERT ignore list", robert_ignore_predict_cli),
|
|
270
|
+
("Execution mode", "generated during model update with --csv_test"),
|
|
271
|
+
],
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
# Get scores from PDF to decide which prediction to use
|
|
275
|
+
pdf_path = robert_path / "ROBERT_report.pdf"
|
|
276
|
+
score_no_PFI, score_PFI = get_scores_from_robert_report(pdf_path)
|
|
277
|
+
use_pfi = False
|
|
278
|
+
if score_PFI is not None and (score_no_PFI is None or score_PFI >= score_no_PFI):
|
|
279
|
+
use_pfi = True
|
|
280
|
+
self.selected_model_type = "PFI" if use_pfi else "No_PFI"
|
|
281
|
+
self.selected_model_score = score_PFI if use_pfi else score_no_PFI
|
|
282
|
+
write_log_block(
|
|
283
|
+
self.args.log,
|
|
284
|
+
"Prediction model comparison",
|
|
285
|
+
[
|
|
286
|
+
("No_PFI score", score_no_PFI),
|
|
287
|
+
("PFI score", score_PFI),
|
|
288
|
+
("Selected prediction model", self.selected_model_type),
|
|
289
|
+
("Selected model score", self.selected_model_score),
|
|
290
|
+
],
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
# Define search path
|
|
294
|
+
search_path = robert_path / "PREDICT" / "csv_test"
|
|
295
|
+
|
|
296
|
+
# Find the correct prediction file
|
|
297
|
+
if use_pfi:
|
|
298
|
+
matching_files = [f for f in search_path.glob("*.csv") if f.name.endswith("_PFI.csv") and "No_PFI" not in f.name]
|
|
299
|
+
else:
|
|
300
|
+
matching_files = [f for f in search_path.glob("*.csv") if f.name.endswith("_No_PFI.csv")]
|
|
301
|
+
|
|
302
|
+
self.path_predictions = matching_files[0] if matching_files else None
|
|
303
|
+
|
|
304
|
+
if self.path_predictions and self.path_predictions.exists():
|
|
305
|
+
if os.path.exists(destination):
|
|
306
|
+
os.remove(destination)
|
|
307
|
+
write_log_block(
|
|
308
|
+
self.args.log,
|
|
309
|
+
"Prediction output",
|
|
310
|
+
[
|
|
311
|
+
("Prediction CSV used", self.path_predictions.name),
|
|
312
|
+
("Prediction source", f"{'PFI' if use_pfi else 'No_PFI'} predictions"),
|
|
313
|
+
("ROBERT ignore list", robert_ignore_predict_cli),
|
|
314
|
+
],
|
|
315
|
+
)
|
|
316
|
+
else:
|
|
317
|
+
self.args.log.write(f"x WARNING! Predictions were not generated in {self.path_predictions}")
|
|
318
|
+
sys.exit()
|
|
319
|
+
|
|
320
|
+
def _sanitize_ignore_columns(self, available_columns):
|
|
321
|
+
"""
|
|
322
|
+
Keep only ignore columns that exist in the CSV passed to ROBERT.
|
|
323
|
+
"""
|
|
324
|
+
available_column_set = set(available_columns)
|
|
325
|
+
robert_ignore = []
|
|
326
|
+
for column in self.args.ignore:
|
|
327
|
+
if column in available_column_set and column not in robert_ignore:
|
|
328
|
+
robert_ignore.append(column)
|
|
329
|
+
return robert_ignore
|
|
330
|
+
|
|
331
|
+
def _format_robert_ignore(self, ignore_columns):
|
|
332
|
+
"""
|
|
333
|
+
Format ignore columns using ROBERT's CLI list style, e.g. [batch,SMILES].
|
|
334
|
+
"""
|
|
335
|
+
return "[" + ",".join(map(str, ignore_columns)) + "]"
|
|
336
|
+
|
|
337
|
+
def active_learning_process(self):
|
|
338
|
+
"""
|
|
339
|
+
Main function for the active learning process, including:
|
|
340
|
+
- Reading and concatenating predictions with the raw data.
|
|
341
|
+
- Splitting data into experimental and prediction sets.
|
|
342
|
+
- Ranking candidates either by uncertainty or by hit acquisition.
|
|
343
|
+
- Updating the dataset and saving results into organized batch folders.
|
|
344
|
+
|
|
345
|
+
This process manages active learning cycles through one acquisition strategy per batch.
|
|
346
|
+
"""
|
|
347
|
+
|
|
348
|
+
# Read predictions from ROBERT and concatenate with the raw data
|
|
349
|
+
df_predictions = pd.read_csv(self.path_predictions)
|
|
350
|
+
|
|
351
|
+
# Move to the parent directory
|
|
352
|
+
parent_directory = Path.cwd() / '..'
|
|
353
|
+
os.chdir(parent_directory)
|
|
354
|
+
|
|
355
|
+
# Add predictions and prediction SD to the original dataframe
|
|
356
|
+
predictions_column = f'{self.args.y}_pred'
|
|
357
|
+
sd_column = f'{predictions_column}_sd'
|
|
358
|
+
self.args.df_raw[[predictions_column, sd_column]] = df_predictions[[predictions_column, sd_column]]
|
|
359
|
+
|
|
360
|
+
# Check if all predictions are equal (firewall)
|
|
361
|
+
if df_predictions[predictions_column].nunique() == 1:
|
|
362
|
+
self.args.log.write(
|
|
363
|
+
"\nx WARNING: All prediction values are identical. Active Learning process will stop.\n"
|
|
364
|
+
f"Predicted value: {df_predictions[predictions_column].iloc[0]}\n"
|
|
365
|
+
"This typically means that the machine learning model cannot find a pattern in the data.\n"
|
|
366
|
+
"Possible reasons:\n"
|
|
367
|
+
"- The molecular descriptors do not capture enough relevant information about the molecules.\n"
|
|
368
|
+
"- The problem is too complex for the current model.\n"
|
|
369
|
+
"- There are not enough data points to train a predictive model.\n"
|
|
370
|
+
"Please review your data and descriptor selection, or try adding more experiments.\n"
|
|
371
|
+
)
|
|
372
|
+
print("\n[ALMOS] Process stopped: all prediction values are identical.")
|
|
373
|
+
sys.exit(0)
|
|
374
|
+
|
|
375
|
+
# Filter the DataFrame into experimental and predictions data
|
|
376
|
+
df_raw_copy = self.args.df_raw.copy()
|
|
377
|
+
predictions_df = df_raw_copy[df_raw_copy[self.args.batch_column].isna()]
|
|
378
|
+
|
|
379
|
+
write_log_header(self.args.log, f"Batch {self.args.current_number_batch} Selection")
|
|
380
|
+
|
|
381
|
+
strategy = resolve_active_learning_strategy(
|
|
382
|
+
score=self.selected_model_score,
|
|
383
|
+
objective=self.args.objective,
|
|
384
|
+
mode=self.args.al_mode,
|
|
385
|
+
alpha_override=self.args.alpha,
|
|
386
|
+
)
|
|
387
|
+
selected_count = min(self.args.n_exps, len(predictions_df))
|
|
388
|
+
ranked_candidates = rank_active_learning_candidates(
|
|
389
|
+
predictions_df,
|
|
390
|
+
strategy,
|
|
391
|
+
predictions_column,
|
|
392
|
+
sd_column,
|
|
393
|
+
selection_size=selected_count,
|
|
394
|
+
)
|
|
395
|
+
selected_candidates = ranked_candidates.head(selected_count).copy()
|
|
396
|
+
|
|
397
|
+
acquisition_rows = [
|
|
398
|
+
("Prediction model used", self.selected_model_type),
|
|
399
|
+
("Model score used", self.selected_model_score),
|
|
400
|
+
("Model score interpretation", format_score_interpretation(self.selected_model_score)),
|
|
401
|
+
("What this means", format_score_explanation(strategy)),
|
|
402
|
+
("Resolved strategy", format_strategy_label(strategy["strategy"])),
|
|
403
|
+
("Why this strategy", format_strategy_reason(strategy)),
|
|
404
|
+
(
|
|
405
|
+
"Objective",
|
|
406
|
+
"not used in model mode"
|
|
407
|
+
if strategy["strategy"] == "model"
|
|
408
|
+
else format_objective_label(strategy["objective"]),
|
|
409
|
+
),
|
|
410
|
+
("Score regime", format_score_regime_label(strategy)),
|
|
411
|
+
(
|
|
412
|
+
"Alpha used",
|
|
413
|
+
"not used" if strategy["strategy"] == "model" else strategy["alpha"],
|
|
414
|
+
),
|
|
415
|
+
(
|
|
416
|
+
"Ranking rule",
|
|
417
|
+
selected_candidates["_acquisition_label"].iloc[0] if selected_count else "n/a",
|
|
418
|
+
),
|
|
419
|
+
("Candidates available", len(ranked_candidates)),
|
|
420
|
+
("Points selected", selected_count),
|
|
421
|
+
]
|
|
422
|
+
|
|
423
|
+
write_log_block(
|
|
424
|
+
self.args.log,
|
|
425
|
+
"Acquisition decision",
|
|
426
|
+
acquisition_rows,
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
if selected_count:
|
|
430
|
+
ranked_preview = build_selected_candidates_preview(
|
|
431
|
+
selected_candidates,
|
|
432
|
+
self.args.name,
|
|
433
|
+
predictions_column,
|
|
434
|
+
sd_column,
|
|
435
|
+
)
|
|
436
|
+
self.args.log.write("\nSelected candidates")
|
|
437
|
+
self.args.log.write(
|
|
438
|
+
format_text_table(
|
|
439
|
+
ranked_preview,
|
|
440
|
+
max_widths={"candidate": 72},
|
|
441
|
+
)
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
predictions_copy_df = predictions_df.copy()
|
|
445
|
+
predictions_copy_df.loc[selected_candidates.index, self.args.batch_column] = self.args.current_number_batch
|
|
446
|
+
|
|
447
|
+
# Update batch column after exploration and exploitation
|
|
448
|
+
df_raw_copy[self.args.batch_column] = df_raw_copy[self.args.batch_column].combine_first(predictions_copy_df[self.args.batch_column])
|
|
449
|
+
# Drop predictions columns and save updated results
|
|
450
|
+
df_raw_copy.drop([predictions_column, sd_column], axis=1, inplace=True)
|
|
451
|
+
|
|
452
|
+
# Build the filename for the updated dataset and save it
|
|
453
|
+
# Sort entire DataFrame by batch descending, keeping NaNs at the end
|
|
454
|
+
df_raw_copy = df_raw_copy.sort_values(by=self.args.batch_column, ascending=False, na_position='last')
|
|
455
|
+
output_file = f"{self.args.base_name}_b{self.args.current_number_batch}.csv"
|
|
456
|
+
df_raw_copy.to_csv(output_file, index=False)
|
|
457
|
+
|
|
458
|
+
# Create a batch directory and move relevant files
|
|
459
|
+
self.data_path = Path.cwd() / f'batch_{self.args.current_number_batch}'
|
|
460
|
+
self.data_path.mkdir(parents=True, exist_ok=True)
|
|
461
|
+
|
|
462
|
+
# Move the files to the proper batch folder
|
|
463
|
+
shutil.move(self.robert_folder, self.data_path)
|
|
464
|
+
shutil.move(output_file, self.data_path)
|
|
465
|
+
|
|
466
|
+
write_log_block(
|
|
467
|
+
self.args.log,
|
|
468
|
+
"Saved outputs",
|
|
469
|
+
[
|
|
470
|
+
("Batch folder", f"batch_{self.args.current_number_batch}"),
|
|
471
|
+
("Updated dataset", output_file),
|
|
472
|
+
("ROBERT folder moved to", str(self.data_path / self.robert_folder)),
|
|
473
|
+
],
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
def generate_plots(self, results_plot_no_pfi_df, results_plot_pfi_df):
|
|
477
|
+
"""
|
|
478
|
+
Generates and saves subplots for each model type (no_PFI and PFI)
|
|
479
|
+
and logs a confirmation message upon successful completion.
|
|
480
|
+
|
|
481
|
+
Parameters
|
|
482
|
+
----------
|
|
483
|
+
results_plot_no_pfi_df : pd.DataFrame
|
|
484
|
+
DataFrame containing the results for the 'no_PFI' model.
|
|
485
|
+
results_plot_pfi_df : pd.DataFrame
|
|
486
|
+
DataFrame containing the results for the 'PFI' model.
|
|
487
|
+
"""
|
|
488
|
+
for model_type, df in [('no_PFI', results_plot_no_pfi_df), ('PFI', results_plot_pfi_df)]:
|
|
489
|
+
plot_metrics_subplots(df, model_type, output_dir="batch_plots", batch_count = self.args.current_number_batch)
|
|
490
|
+
|
|
491
|
+
write_log_header(self.args.log, "Plot Generation Summary")
|
|
492
|
+
write_log_block(
|
|
493
|
+
self.args.log,
|
|
494
|
+
"Generated monitoring plots",
|
|
495
|
+
[
|
|
496
|
+
("No_PFI plot folder", "batch_plots/no_PFI_plots"),
|
|
497
|
+
("PFI plot folder", "batch_plots/PFI_plots"),
|
|
498
|
+
("Status", "subplot figures generated successfully"),
|
|
499
|
+
],
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
def finalize_process(self, start_time_overall):
|
|
503
|
+
"""Stop the timer, calculate the total time taken and move the .dat file to the proper batch folder."""
|
|
504
|
+
|
|
505
|
+
elapsed_time = round(time.time() - start_time_overall, 2)
|
|
506
|
+
|
|
507
|
+
write_log_header(self.args.log, "Active Learning Process Completed")
|
|
508
|
+
write_log_block(
|
|
509
|
+
self.args.log,
|
|
510
|
+
"Run summary",
|
|
511
|
+
[
|
|
512
|
+
("Final batch number", self.args.current_number_batch),
|
|
513
|
+
("Output folder", f"batch_{self.args.current_number_batch}"),
|
|
514
|
+
("Total runtime (s)", f"{elapsed_time:.2f}"),
|
|
515
|
+
],
|
|
516
|
+
)
|
|
517
|
+
self.args.log.finalize()
|
|
518
|
+
|
|
519
|
+
# Move the .dat file to the proper batch folder
|
|
520
|
+
log_file = Path.cwd() / "AL_data.dat" # Path to the log file in the current directory
|
|
521
|
+
log_destination = os.path.join(self.data_path, "AL_data.dat") # Define the destination path
|
|
522
|
+
shutil.move(log_file, log_destination) # Move the file
|