almos-kit 0.1.0__py2.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 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,418 @@
1
+ """
2
+ Parameters
3
+ ----------
4
+ al : bool
5
+ Indicates whether 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_points : tuple of two int
18
+ Specifies the number of new points for exploration and exploitation in the next batch.
19
+ The first value is for exploration, and the second is for exploitation. (i.e. '--n_points 5:10')
20
+ If not provided or invalid, the program will request the values in the format 'explore:exploit'.
21
+ tolerance : str, default='medium'
22
+ Indicates the tolerance level for the convergence process, defining the percentage change threshold required for convergence. Options:
23
+ 1. 'tight': Strictest level, convergence occurs if the metric improves by ≤1% (threshold = 0.01).
24
+ 2. 'medium': Balanced level, convergence occurs if the metric improves by ≤5% (threshold = 0.05).
25
+ 3. 'wide': Least strict, convergence occurs if the metric improves by ≤10% (threshold = 0.10).
26
+ (i.e. '--tolerance tight')
27
+ robert_keywords : str, default=""
28
+ Additional keywords to be passed to the ROBERT model generation (i.e. --robert_keywords "--model RF --train [70] --seed [0]")
29
+ reverse : bool, default=False
30
+ If set to True, the order of the points in the new batch is reversed, prioritizing in exploitation lower values (i.e. --reverse ).
31
+ intelex : bool, default=False
32
+ If set to True, the program will not need module scikit-learn-intelex to speed up the model update process.
33
+
34
+ """
35
+
36
+ #####################################################
37
+ # This file stores the AL class #
38
+ # used in the active learning process #
39
+ #####################################################
40
+
41
+ import pandas as pd
42
+ import time
43
+ import os , sys
44
+ from pathlib import Path
45
+ import re
46
+ import shutil
47
+ from collections import Counter
48
+
49
+ from almos.utils import (
50
+ load_variables,
51
+ check_dependencies
52
+ )
53
+ from almos.al_utils import (
54
+ generate_quartile_medians_df,
55
+ get_size_counters,
56
+ assign_values,
57
+ get_metrics_from_batches,
58
+ EarlyStopping,
59
+ plot_metrics_subplots
60
+ )
61
+
62
+
63
+ class al:
64
+ """
65
+ Class containing all the functions from the active almos module
66
+
67
+ """
68
+ def __init__(self, **kwargs):
69
+
70
+ # Initialize the timer
71
+ start_time_overall = time.time()
72
+
73
+ # load default and user-specified variables
74
+ self.args = load_variables(kwargs, "al")
75
+
76
+ # Check dependencies such as scikit-learn-intelex
77
+ _ = check_dependencies(self, "al")
78
+
79
+ # run robert model updated and generate predictions
80
+ self.run_robert_process()
81
+
82
+ # run active learning process for select points for new batch
83
+ self.active_learning_process()
84
+
85
+ # Check for convergence in the batches
86
+ # Get metrics from batches
87
+ results_plot_no_PFI, results_plot_PFI = get_metrics_from_batches()
88
+
89
+ # Initialize EarlyStopping to check for convergence
90
+ early_stopping = EarlyStopping(
91
+ logger=self.args.log,
92
+ rmse_min_delta = self.args.levels_tolerance[self.args.tolerance],
93
+ sd_min_delta = self.args.levels_tolerance[self.args.tolerance],
94
+ )
95
+
96
+ results_plot_no_pfi_df, results_plot_pfi_df = early_stopping.check_convergence(
97
+ results_plot_no_PFI, results_plot_PFI
98
+ )
99
+
100
+ # Generate plots
101
+ self.generate_plots(results_plot_no_pfi_df, results_plot_pfi_df)
102
+
103
+ # Log the total time and finalize
104
+ self.finalize_process(start_time_overall)
105
+
106
+ def run_robert_process(self):
107
+ """
108
+ Executes the full ROBERT model update and prediction process.
109
+
110
+ This method performs the following steps:
111
+ - Initializes a logger to record process details and parameters.
112
+ - Filters the input data to create a CSV file for updating the ROBERT model.
113
+ - Creates necessary directories and moves files as required.
114
+ - Runs the ROBERT model update command, logging all output and errors.
115
+ - Checks for successful generation of the model report.
116
+ - Runs the prediction command to generate new predictions with the updated model.
117
+ - Verifies that predictions were successfully created and logs the result.
118
+
119
+ Raises:
120
+ SystemExit: Exits the program if any step fails or if required files are not found.
121
+ """
122
+ # Get the base name of the CSV file without the extension if the csv is introduced as path
123
+ self.args.csv_name = os.path.basename(self.args.csv_name)
124
+ self.args.base_name_raw = os.path.splitext(self.args.csv_name)[0]
125
+
126
+ # Handle cases of different batches (i.e test_b1, test_b2, etc), in order to extract the base name.
127
+ base_name = os.path.splitext(self.args.csv_name)[0]
128
+ match = re.match(r"^(.*)_b\d+$", base_name)
129
+ if match:
130
+ # If the name matches the pattern, extract the base name
131
+ self.args.base_name = match.group(1)
132
+ else:
133
+ # Otherwise, use the entire base name
134
+ self.args.base_name = self.args.base_name_raw
135
+
136
+ # Initialize the logger
137
+ self.args.log.write("\n")
138
+ self.args.log.write("====================================\n")
139
+ self.args.log.write(" Starting Active Learning process\n")
140
+ self.args.log.write("====================================\n")
141
+
142
+ # Log parameters for the process
143
+ self.args.log.write("--- Parameters ---\n")
144
+ self.args.log.write(f"CSV test file : {self.args.csv_name}\n")
145
+ self.args.log.write(f"Name column : {self.args.name}\n")
146
+ self.args.log.write(f"Y column : {self.args.y}\n")
147
+ self.args.log.write(f"Points exploration : {self.args.n_points[0]}\n")
148
+ self.args.log.write(f"Points explotation : {self.args.n_points[1]}\n")
149
+ self.args.log.write(f"Ignore columns : {self.args.ignore}\n")
150
+ self.args.log.write(f"Convergence tolerance : {self.args.tolerance} ({self.args.levels_tolerance[self.args.tolerance] * 100:.2f}%)\n")
151
+ self.args.log.write("-------------------------------\n")
152
+
153
+ # Main directory for the process
154
+ self.main_folder = os.getcwd()
155
+
156
+ # Filter rows where value in the batch_column is not NaN for updating the model
157
+ robert_model_df = self.args.df_raw[self.args.df_raw[self.args.batch_column].notna()]
158
+
159
+ # Ensure the folder for ROBERT model results exists
160
+ self.robert_folder = f'ROBERT_b{self.args.current_number_batch}'
161
+ robert_path = Path(self.main_folder) / self.robert_folder
162
+ robert_path.mkdir(parents=True, exist_ok=True)
163
+
164
+ # Create and save the CSV file inside the folder
165
+ filename_model_csv = robert_path / f"{self.args.base_name}_ROBERT_b{self.args.current_number_batch}.csv"
166
+ try:
167
+ robert_model_df.to_csv(filename_model_csv, index=False)
168
+ print(f"o File successfully saved: {filename_model_csv}")
169
+
170
+ except Exception as e:
171
+ print(f"x WARNING! Could not save the file: {e}")
172
+ sys.exit()
173
+
174
+ # Change to the newly created ROBERT directory
175
+ os.chdir(robert_path)
176
+
177
+ # Trying to avoid error in subprocess with tkinter
178
+ # Use "Agg" backend to prevent matplotlib from using tkinter, avoiding "main thread" errors in headless or multi-threaded environments.
179
+ os.environ["MPLBACKEND"] = "Agg"
180
+
181
+ # Build and run the command for updating the ROBERT model
182
+ command = (
183
+ f'python -m robert --csv_name {filename_model_csv} '
184
+ f'--name {self.args.name} '
185
+ f'--y {self.args.y} '
186
+ f'--ignore "{self.args.ignore}" '
187
+ f'{self.args.robert_keywords}' # Include keywords only if not empty works
188
+ )
189
+
190
+ self.args.log.write("\n")
191
+ self.args.log.write("=======================================\n")
192
+ self.args.log.write(" Generating the ROBERT model updated\n")
193
+ self.args.log.write("=======================================\n")
194
+
195
+ # Run the command and check for errors
196
+ exit_code = os.system(command)
197
+ if exit_code != 0:
198
+ self.args.log.write(f"x WARNING! Command failed with exit code {exit_code}. Exiting.\n")
199
+ sys.exit(exit_code)
200
+
201
+ # Check if the ROBERT model report was generated
202
+ if os.path.exists('ROBERT_report.pdf'):
203
+ self.args.log.write("\no ROBERT model updated and generated successfully!\n")
204
+ else:
205
+ self.args.log.write("\nx WARNING! ROBERT model was not generated\n")
206
+ sys.exit()
207
+
208
+ # Define paths for the source file and destination directory
209
+ source = os.path.join(self.args.path_csv_name)
210
+ destination_dir = Path(Path.cwd().parent, self.robert_folder) # Ensure destination is a directory
211
+ destination_dir.mkdir(parents=True, exist_ok=True) # Create the directory if it doesn't exist
212
+ destination = destination_dir / Path(source).name # Complete path for the destination file
213
+
214
+ # Check if the source file exists before copying
215
+ if os.path.isfile(source):
216
+ # Copy the file from source to destination
217
+ shutil.copy(source, destination)
218
+ else:
219
+ print(f"o File '{self.args.csv_name}' was not found for generate predictions! Exiting.")
220
+
221
+
222
+ # Build and run the command for generating predictions
223
+ command = f'python -m robert --name {self.args.name} --csv_test {self.args.csv_name} --ignore "{self.args.ignore}" --predict'
224
+ self.args.log.write("\n")
225
+ self.args.log.write("==================================================\n")
226
+ self.args.log.write(" Generating predictions with ROBERT model updated\n")
227
+ self.args.log.write("==================================================\n")
228
+
229
+ # Run the command and check for errors
230
+ exit_code = os.system(command)
231
+ if exit_code != 0:
232
+ self.args.log.write(f"x WARNING! Command failed with exit code {exit_code}. Exiting.\n")
233
+ sys.exit(exit_code)
234
+
235
+ # Check if predictions were created correctly
236
+ # Define search path and pattern
237
+ search_path = robert_path / "PREDICT" / "csv_test"
238
+
239
+ # Get all matching files
240
+ matching_files = list(search_path.glob("*_PFI.csv"))
241
+
242
+ # Ensure we exclude "_No_PFI.csv"
243
+ filtered_files = [f for f in matching_files if f.name.endswith("_No_PFI.csv")]
244
+
245
+ # Take the first valid match
246
+ self.path_predictions = filtered_files[0] if filtered_files else None
247
+
248
+ if self.path_predictions.exists():
249
+ # Clean up, remove the test CSV file if it exists in main directory
250
+ os.remove(destination)
251
+ self.args.log.write("o New predictions generated successfully!")
252
+ else:
253
+ self.args.log.write(f"x WARNING! Predictions were not generated in {self.path_predictions}")
254
+ sys.exit()
255
+
256
+ def active_learning_process(self):
257
+ """
258
+ Main function for the active learning process, including:
259
+ - Reading and concatenating predictions with the raw data.
260
+ - Splitting data into experimental and prediction sets.
261
+ - Calculating quartiles and assigning points for exploration and exploitation.
262
+ - Updating the dataset and saving results into organized batch folders.
263
+
264
+ This process manages both exploration and exploitation of data for an active learning cycle.
265
+ """
266
+
267
+ # Read predictions from ROBERT and concatenate with the raw data
268
+ df_predictions = pd.read_csv(self.path_predictions)
269
+
270
+ # Move to the parent directory
271
+ parent_directory = Path.cwd() / '..'
272
+ os.chdir(parent_directory)
273
+
274
+ # Add predictions and prediction SD to the original dataframe
275
+ predictions_column = f'{self.args.y}_pred'
276
+ sd_column = f'{predictions_column}_sd'
277
+ self.args.df_raw[[predictions_column, sd_column]] = df_predictions[[predictions_column, sd_column]]
278
+
279
+ # Filter the DataFrame into experimental and predictions data
280
+ df_raw_copy = self.args.df_raw.copy()
281
+ experimental_df = df_raw_copy[df_raw_copy[self.args.batch_column].notna()]
282
+ predictions_df = df_raw_copy[df_raw_copy[self.args.batch_column].isna()]
283
+
284
+ # Generate lists of target values for experimental and prediction datasets
285
+ list_experimental = experimental_df[self.args.y].tolist()
286
+ list_predictions = predictions_df[predictions_column].tolist()
287
+ values = list_experimental + list_predictions
288
+
289
+ # Create DataFrames with combined values and only experimental values
290
+ total_value_df = pd.DataFrame({self.args.y: values})
291
+ exp_value_df = pd.DataFrame({self.args.y: list_experimental})
292
+
293
+ # Calculate quartiles and their medians for the experimental dataset
294
+ quartile_df_exp, quartile_medians, boundaries = generate_quartile_medians_df(total_value_df, exp_value_df, self.args.y)
295
+
296
+ # Copy predictions DataFrame to avoid modifications
297
+ predictions_copy_df = predictions_df.copy()
298
+
299
+ # Log results and initial data sizes
300
+ self.args.log.write("\n")
301
+ self.args.log.write("================================================\n")
302
+ self.args.log.write(f" Results for Batch {self.args.current_number_batch}\n")
303
+ self.args.log.write("================================================\n")
304
+
305
+ size_counters = get_size_counters(quartile_df_exp)
306
+ # Dataset information
307
+ self.args.log.write("--- Dataset Information ---\n")
308
+ self.args.log.write(f"\nInitial sizes of dataset: {size_counters}\n")
309
+
310
+ # Create variables for exploration vs exploitation using n_points explore:exploit
311
+ explore_points = int(self.args.n_points[0])
312
+ exploit_points = int(self.args.n_points[1])
313
+
314
+ # Exploitation: Select top rows for q4 or q1 based on the predictions and if the process is reverse or not
315
+ if self.args.reverse:
316
+ top_df = predictions_copy_df.nsmallest(exploit_points, predictions_column)
317
+ else:
318
+ top_df = predictions_copy_df.nlargest(exploit_points, predictions_column)
319
+
320
+ predictions_copy_df.loc[top_df.index, self.args.batch_column] = self.args.current_number_batch
321
+
322
+ # Exploration: Assign values to the exploration quartiles based on proximity to quartile medians
323
+ assigned_points, min_size_quartiles = assign_values(
324
+ predictions_copy_df[predictions_copy_df[self.args.batch_column].isna()],
325
+ explore_points,
326
+ quartile_medians,
327
+ size_counters,
328
+ predictions_column,
329
+ self.args.reverse
330
+ )
331
+
332
+ # Count occurrences in exploration assignments
333
+ points_counter = Counter([value for _, points in assigned_points.items() for value in points])
334
+
335
+ # Update the batch column for exploration assignments
336
+ for value, times_value_appears in points_counter.items():
337
+ idx_list = predictions_copy_df[predictions_copy_df[predictions_column] == value].index
338
+ if not idx_list.empty:
339
+ indices_to_update = idx_list[:times_value_appears]
340
+ predictions_copy_df.loc[indices_to_update, self.args.batch_column] = self.args.current_number_batch
341
+
342
+ self.args.log.write(f"Quartile medians of dataset: {quartile_medians}\n")
343
+ self.args.log.write(f"Boundaries range: Min = {min(boundaries)}, Max = {max(boundaries)}\n")
344
+
345
+ # Exploration results
346
+ self.args.log.write("\n--- Exploration ---\n")
347
+ self.args.log.write(f"Ordered assigned points: {min_size_quartiles}\n\n")
348
+ self.args.log.write(f"Number of points assigned for exploration: {explore_points}\n")
349
+ if self.args.reverse:
350
+ for q in ['q2', 'q3', 'q4']:
351
+ self.args.log.write(f" Points assigned to {q}: {assigned_points[q]}\n")
352
+ else:
353
+ for q in ['q1', 'q2', 'q3']:
354
+ self.args.log.write(f" Points assigned to {q}: {assigned_points[q]}\n")
355
+
356
+ # Exploitation results
357
+ self.args.log.write("\n--- Exploitation ---\n")
358
+ self.args.log.write(f"Number of points assigned for exploitation: {exploit_points}\n")
359
+ if self.args.reverse:
360
+ self.args.log.write(f" Points assigned to q1: {top_df[predictions_column].tolist()}\n")
361
+ else:
362
+ self.args.log.write(f" Points assigned to q4: {top_df[predictions_column].tolist()}\n")
363
+
364
+ # Update batch column after exploration and exploitation
365
+ df_raw_copy[self.args.batch_column] = df_raw_copy[self.args.batch_column].combine_first(predictions_copy_df[self.args.batch_column])
366
+ # Drop predictions columns and save updated results
367
+ df_raw_copy.drop([predictions_column, sd_column], axis=1, inplace=True)
368
+
369
+ # Build the filename for the updated dataset and save it
370
+ output_file = f"{self.args.base_name}_b{self.args.current_number_batch}.csv"
371
+ df_raw_copy.to_csv(output_file, index=False)
372
+
373
+ # Create a batch directory and move relevant files
374
+ self.data_path = Path.cwd() / f'batch_{self.args.current_number_batch}'
375
+ self.data_path.mkdir(parents=True, exist_ok=True)
376
+
377
+ # Move the files to the proper batch folder
378
+ shutil.move(self.robert_folder, self.data_path)
379
+ shutil.move(output_file, self.data_path)
380
+
381
+ # Log results
382
+ self.args.log.write(f"\no Results generated successfully in folder 'batch_{self.args.current_number_batch}'\n")
383
+
384
+ def generate_plots(self, results_plot_no_pfi_df, results_plot_pfi_df):
385
+ """
386
+ Generates and saves subplots for each model type (no_PFI and PFI)
387
+ and logs a confirmation message upon successful completion.
388
+
389
+ Parameters
390
+ ----------
391
+ results_plot_no_pfi_df : pd.DataFrame
392
+ DataFrame containing the results for the 'no_PFI' model.
393
+ results_plot_pfi_df : pd.DataFrame
394
+ DataFrame containing the results for the 'PFI' model.
395
+ """
396
+ for model_type, df in [('no_PFI', results_plot_no_pfi_df), ('PFI', results_plot_pfi_df)]:
397
+ plot_metrics_subplots(df, model_type, output_dir="batch_plots", batch_count = self.args.current_number_batch)
398
+
399
+ # Log confirmation after generating both plots
400
+ self.args.log.write("\n==========================================")
401
+ self.args.log.write(" Graph Generation Confirmation Report ")
402
+ self.args.log.write("==========================================\n")
403
+ self.args.log.write("o Subplot figures have been generated and saved successfully!\n")
404
+
405
+ def finalize_process(self, start_time_overall):
406
+ """Stop the timer, calculate the total time taken and move the .dat file to the proper batch folder."""
407
+
408
+ elapsed_time = round(time.time() - start_time_overall, 2)
409
+
410
+ # Log the total time and finalize
411
+ self.args.log.write("==========================================\n")
412
+ self.args.log.write(f"Process Completed! Total time taken for the process: {elapsed_time:.2f} seconds")
413
+ self.args.log.finalize()
414
+
415
+ # Move the .dat file to the proper batch folder
416
+ log_file = Path.cwd() / "AL_data.dat" # Path to the log file in the current directory
417
+ log_destination = os.path.join(self.data_path, "AL_data.dat") # Define the destination path
418
+ shutil.move(log_file, log_destination) # Move the file