workbench 0.8.198__py3-none-any.whl → 0.8.203__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.
Files changed (53) hide show
  1. workbench/algorithms/dataframe/proximity.py +11 -4
  2. workbench/api/__init__.py +2 -1
  3. workbench/api/df_store.py +17 -108
  4. workbench/api/feature_set.py +48 -11
  5. workbench/api/model.py +1 -1
  6. workbench/api/parameter_store.py +3 -52
  7. workbench/core/artifacts/__init__.py +11 -2
  8. workbench/core/artifacts/artifact.py +5 -5
  9. workbench/core/artifacts/df_store_core.py +114 -0
  10. workbench/core/artifacts/endpoint_core.py +261 -78
  11. workbench/core/artifacts/feature_set_core.py +69 -1
  12. workbench/core/artifacts/model_core.py +48 -14
  13. workbench/core/artifacts/parameter_store_core.py +98 -0
  14. workbench/core/transforms/features_to_model/features_to_model.py +50 -33
  15. workbench/core/transforms/pandas_transforms/pandas_to_features.py +11 -2
  16. workbench/core/views/view.py +2 -2
  17. workbench/model_scripts/chemprop/chemprop.template +933 -0
  18. workbench/model_scripts/chemprop/generated_model_script.py +933 -0
  19. workbench/model_scripts/chemprop/requirements.txt +11 -0
  20. workbench/model_scripts/custom_models/chem_info/fingerprints.py +134 -0
  21. workbench/model_scripts/custom_models/chem_info/morgan_fingerprints.py +1 -1
  22. workbench/model_scripts/custom_models/proximity/proximity.py +11 -4
  23. workbench/model_scripts/custom_models/uq_models/ensemble_xgb.template +11 -5
  24. workbench/model_scripts/custom_models/uq_models/meta_uq.template +11 -5
  25. workbench/model_scripts/custom_models/uq_models/ngboost.template +11 -5
  26. workbench/model_scripts/custom_models/uq_models/proximity.py +11 -4
  27. workbench/model_scripts/ensemble_xgb/ensemble_xgb.template +11 -5
  28. workbench/model_scripts/pytorch_model/generated_model_script.py +365 -173
  29. workbench/model_scripts/pytorch_model/pytorch.template +362 -170
  30. workbench/model_scripts/scikit_learn/generated_model_script.py +302 -0
  31. workbench/model_scripts/script_generation.py +10 -7
  32. workbench/model_scripts/uq_models/generated_model_script.py +43 -27
  33. workbench/model_scripts/uq_models/mapie.template +40 -24
  34. workbench/model_scripts/xgb_model/generated_model_script.py +36 -7
  35. workbench/model_scripts/xgb_model/xgb_model.template +36 -7
  36. workbench/repl/workbench_shell.py +14 -5
  37. workbench/resources/open_source_api.key +1 -1
  38. workbench/scripts/endpoint_test.py +162 -0
  39. workbench/scripts/{lambda_launcher.py → lambda_test.py} +10 -0
  40. workbench/utils/chemprop_utils.py +761 -0
  41. workbench/utils/pytorch_utils.py +527 -0
  42. workbench/utils/xgboost_model_utils.py +10 -5
  43. workbench/web_interface/components/model_plot.py +7 -1
  44. {workbench-0.8.198.dist-info → workbench-0.8.203.dist-info}/METADATA +3 -3
  45. {workbench-0.8.198.dist-info → workbench-0.8.203.dist-info}/RECORD +49 -43
  46. {workbench-0.8.198.dist-info → workbench-0.8.203.dist-info}/entry_points.txt +2 -1
  47. workbench/core/cloud_platform/aws/aws_df_store.py +0 -404
  48. workbench/core/cloud_platform/aws/aws_parameter_store.py +0 -280
  49. workbench/model_scripts/__pycache__/script_generation.cpython-312.pyc +0 -0
  50. workbench/model_scripts/__pycache__/script_generation.cpython-313.pyc +0 -0
  51. {workbench-0.8.198.dist-info → workbench-0.8.203.dist-info}/WHEEL +0 -0
  52. {workbench-0.8.198.dist-info → workbench-0.8.203.dist-info}/licenses/LICENSE +0 -0
  53. {workbench-0.8.198.dist-info → workbench-0.8.203.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,761 @@
1
+ """ChemProp utilities for Workbench models."""
2
+
3
+ # flake8: noqa: E402
4
+ import logging
5
+ import os
6
+ import tempfile
7
+ from typing import Any, Tuple
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ from scipy.stats import spearmanr
12
+ from sklearn.metrics import (
13
+ mean_absolute_error,
14
+ mean_squared_error,
15
+ median_absolute_error,
16
+ precision_recall_fscore_support,
17
+ r2_score,
18
+ roc_auc_score,
19
+ )
20
+ from sklearn.model_selection import KFold, StratifiedKFold
21
+ from sklearn.preprocessing import LabelEncoder
22
+
23
+ from workbench.utils.model_utils import safe_extract_tarfile
24
+ from workbench.utils.pandas_utils import expand_proba_column
25
+ from workbench.utils.aws_utils import pull_s3_data
26
+
27
+ log = logging.getLogger("workbench")
28
+
29
+
30
+ def download_and_extract_model(s3_uri: str, model_dir: str) -> None:
31
+ """Download model artifact from S3 and extract it.
32
+
33
+ Args:
34
+ s3_uri: S3 URI to the model artifact (model.tar.gz)
35
+ model_dir: Directory to extract model artifacts to
36
+ """
37
+ import awswrangler as wr
38
+
39
+ log.info(f"Downloading model from {s3_uri}...")
40
+
41
+ # Download to temp file
42
+ local_tar_path = os.path.join(model_dir, "model.tar.gz")
43
+ wr.s3.download(path=s3_uri, local_file=local_tar_path)
44
+
45
+ # Extract using safe extraction
46
+ log.info(f"Extracting to {model_dir}...")
47
+ safe_extract_tarfile(local_tar_path, model_dir)
48
+
49
+ # Cleanup tar file
50
+ os.unlink(local_tar_path)
51
+
52
+
53
+ def load_chemprop_model_artifacts(model_dir: str) -> Tuple[Any, dict]:
54
+ """Load ChemProp MPNN model and artifacts from an extracted model directory.
55
+
56
+ Args:
57
+ model_dir: Directory containing extracted model artifacts
58
+
59
+ Returns:
60
+ Tuple of (MPNN model, artifacts_dict).
61
+ artifacts_dict contains 'label_encoder' and 'feature_metadata' if present.
62
+ """
63
+ import joblib
64
+ from chemprop import models
65
+
66
+ model_path = os.path.join(model_dir, "chemprop_model.pt")
67
+ if not os.path.exists(model_path):
68
+ raise FileNotFoundError(f"No chemprop_model.pt found in {model_dir}")
69
+
70
+ model = models.MPNN.load_from_file(model_path)
71
+ model.eval()
72
+
73
+ # Load additional artifacts
74
+ artifacts = {}
75
+
76
+ label_encoder_path = os.path.join(model_dir, "label_encoder.joblib")
77
+ if os.path.exists(label_encoder_path):
78
+ artifacts["label_encoder"] = joblib.load(label_encoder_path)
79
+
80
+ feature_metadata_path = os.path.join(model_dir, "feature_metadata.joblib")
81
+ if os.path.exists(feature_metadata_path):
82
+ artifacts["feature_metadata"] = joblib.load(feature_metadata_path)
83
+
84
+ return model, artifacts
85
+
86
+
87
+ def _find_smiles_column(columns: list) -> str:
88
+ """Find the SMILES column name from a list (case-insensitive match for 'smiles')."""
89
+ smiles_column = next((col for col in columns if col.lower() == "smiles"), None)
90
+ if smiles_column is None:
91
+ raise ValueError("Column list must contain a 'smiles' column (case-insensitive)")
92
+ return smiles_column
93
+
94
+
95
+ def _create_molecule_datapoints(
96
+ smiles_list: list,
97
+ targets: list = None,
98
+ extra_descriptors: np.ndarray = None,
99
+ ) -> Tuple[list, list]:
100
+ """Create ChemProp MoleculeDatapoints from SMILES strings.
101
+
102
+ Args:
103
+ smiles_list: List of SMILES strings
104
+ targets: Optional list of target values (for training)
105
+ extra_descriptors: Optional array of extra features (n_samples, n_features)
106
+
107
+ Returns:
108
+ Tuple of (list of MoleculeDatapoint objects, list of valid indices)
109
+ """
110
+ from chemprop import data
111
+ from rdkit import Chem
112
+
113
+ datapoints = []
114
+ valid_indices = []
115
+ invalid_count = 0
116
+
117
+ for i, smi in enumerate(smiles_list):
118
+ # Validate SMILES with RDKit first
119
+ mol = Chem.MolFromSmiles(smi)
120
+ if mol is None:
121
+ invalid_count += 1
122
+ continue
123
+
124
+ # Build datapoint with optional target and extra descriptors
125
+ y = [targets[i]] if targets is not None else None
126
+ x_d = extra_descriptors[i] if extra_descriptors is not None else None
127
+
128
+ dp = data.MoleculeDatapoint.from_smi(smi, y=y, x_d=x_d)
129
+ datapoints.append(dp)
130
+ valid_indices.append(i)
131
+
132
+ if invalid_count > 0:
133
+ print(f"Warning: Skipped {invalid_count} invalid SMILES strings")
134
+
135
+ return datapoints, valid_indices
136
+
137
+
138
+ def _build_mpnn_model(
139
+ hyperparameters: dict,
140
+ task: str = "regression",
141
+ num_classes: int = None,
142
+ n_extra_descriptors: int = 0,
143
+ x_d_transform: Any = None,
144
+ output_transform: Any = None,
145
+ ) -> Any:
146
+ """Build an MPNN model with the specified hyperparameters.
147
+
148
+ Args:
149
+ hyperparameters: Dictionary of model hyperparameters
150
+ task: Either "regression" or "classification"
151
+ num_classes: Number of classes for classification tasks
152
+ n_extra_descriptors: Number of extra descriptor features (for hybrid mode)
153
+ x_d_transform: Optional transform for extra descriptors (scaling)
154
+ output_transform: Optional transform for regression output (unscaling targets)
155
+
156
+ Returns:
157
+ Configured MPNN model
158
+ """
159
+ from chemprop import models, nn
160
+
161
+ # Model hyperparameters with defaults
162
+ hidden_dim = hyperparameters.get("hidden_dim", 300)
163
+ depth = hyperparameters.get("depth", 3)
164
+ dropout = hyperparameters.get("dropout", 0.1)
165
+ ffn_hidden_dim = hyperparameters.get("ffn_hidden_dim", 300)
166
+ ffn_num_layers = hyperparameters.get("ffn_num_layers", 1)
167
+
168
+ # Message passing component
169
+ mp = nn.BondMessagePassing(d_h=hidden_dim, depth=depth, dropout=dropout)
170
+
171
+ # Aggregation - NormAggregation normalizes output, recommended when using extra descriptors
172
+ agg = nn.NormAggregation()
173
+
174
+ # FFN input_dim = message passing output + extra descriptors
175
+ ffn_input_dim = hidden_dim + n_extra_descriptors
176
+
177
+ # Build FFN based on task type
178
+ if task == "classification" and num_classes is not None:
179
+ # Multi-class classification
180
+ ffn = nn.MulticlassClassificationFFN(
181
+ n_classes=num_classes,
182
+ input_dim=ffn_input_dim,
183
+ hidden_dim=ffn_hidden_dim,
184
+ n_layers=ffn_num_layers,
185
+ dropout=dropout,
186
+ )
187
+ else:
188
+ # Regression with optional output transform to unscale predictions
189
+ ffn = nn.RegressionFFN(
190
+ input_dim=ffn_input_dim,
191
+ hidden_dim=ffn_hidden_dim,
192
+ n_layers=ffn_num_layers,
193
+ dropout=dropout,
194
+ output_transform=output_transform,
195
+ )
196
+
197
+ # Create the MPNN model
198
+ mpnn = models.MPNN(
199
+ message_passing=mp,
200
+ agg=agg,
201
+ predictor=ffn,
202
+ batch_norm=True,
203
+ metrics=None,
204
+ X_d_transform=x_d_transform,
205
+ )
206
+
207
+ return mpnn
208
+
209
+
210
+ def _extract_model_hyperparameters(loaded_model: Any) -> dict:
211
+ """Extract hyperparameters from a loaded ChemProp MPNN model.
212
+
213
+ Extracts architecture parameters from the model's components to replicate
214
+ the exact same model configuration during cross-validation.
215
+
216
+ Args:
217
+ loaded_model: Loaded MPNN model instance
218
+
219
+ Returns:
220
+ Dictionary of hyperparameters matching the training template
221
+ """
222
+ hyperparameters = {}
223
+
224
+ # Extract from message passing layer (BondMessagePassing)
225
+ mp = loaded_model.message_passing
226
+ hyperparameters["hidden_dim"] = getattr(mp, "d_h", 300)
227
+ hyperparameters["depth"] = getattr(mp, "depth", 3)
228
+
229
+ # Dropout is stored as a nn.Dropout module, get the p value
230
+ if hasattr(mp, "dropout"):
231
+ dropout_module = mp.dropout
232
+ hyperparameters["dropout"] = getattr(dropout_module, "p", 0.0)
233
+ else:
234
+ hyperparameters["dropout"] = 0.0
235
+
236
+ # Extract from predictor (FFN - either RegressionFFN or MulticlassClassificationFFN)
237
+ ffn = loaded_model.predictor
238
+
239
+ # FFN hidden_dim - try multiple attribute names
240
+ if hasattr(ffn, "hidden_dim"):
241
+ hyperparameters["ffn_hidden_dim"] = ffn.hidden_dim
242
+ elif hasattr(ffn, "d_h"):
243
+ hyperparameters["ffn_hidden_dim"] = ffn.d_h
244
+ else:
245
+ hyperparameters["ffn_hidden_dim"] = 300
246
+
247
+ # FFN num_layers - try multiple attribute names
248
+ if hasattr(ffn, "n_layers"):
249
+ hyperparameters["ffn_num_layers"] = ffn.n_layers
250
+ elif hasattr(ffn, "num_layers"):
251
+ hyperparameters["ffn_num_layers"] = ffn.num_layers
252
+ else:
253
+ hyperparameters["ffn_num_layers"] = 1
254
+
255
+ # Training hyperparameters (use defaults matching the template)
256
+ hyperparameters["max_epochs"] = 50
257
+ hyperparameters["patience"] = 10
258
+
259
+ return hyperparameters
260
+
261
+
262
+ def _get_n_extra_descriptors(loaded_model: Any) -> int:
263
+ """Get the number of extra descriptors from the loaded model.
264
+
265
+ The model's X_d_transform contains the scaler which knows the feature dimension.
266
+
267
+ Args:
268
+ loaded_model: Loaded MPNN model instance
269
+
270
+ Returns:
271
+ Number of extra descriptors (0 if none)
272
+ """
273
+ x_d_transform = loaded_model.X_d_transform
274
+ if x_d_transform is None:
275
+ return 0
276
+
277
+ # ScaleTransform wraps a StandardScaler, check its mean_ attribute
278
+ if hasattr(x_d_transform, "mean"):
279
+ # x_d_transform.mean is a tensor
280
+ return len(x_d_transform.mean)
281
+ elif hasattr(x_d_transform, "scaler") and hasattr(x_d_transform.scaler, "mean_"):
282
+ return len(x_d_transform.scaler.mean_)
283
+
284
+ return 0
285
+
286
+
287
+ def pull_cv_results(workbench_model: Any) -> Tuple[pd.DataFrame, pd.DataFrame]:
288
+ """Pull cross-validation results from AWS training artifacts.
289
+
290
+ This retrieves the validation predictions and training metrics that were
291
+ saved during model training.
292
+
293
+ Args:
294
+ workbench_model: Workbench model object
295
+
296
+ Returns:
297
+ Tuple of:
298
+ - DataFrame with training metrics
299
+ - DataFrame with validation predictions
300
+ """
301
+ # Get the validation predictions from S3
302
+ s3_path = f"{workbench_model.model_training_path}/validation_predictions.csv"
303
+ predictions_df = pull_s3_data(s3_path)
304
+
305
+ if predictions_df is None:
306
+ raise ValueError(f"No validation predictions found at {s3_path}")
307
+
308
+ log.info(f"Pulled {len(predictions_df)} validation predictions from {s3_path}")
309
+
310
+ # Get training metrics from model metadata
311
+ training_metrics = workbench_model.workbench_meta().get("workbench_training_metrics")
312
+
313
+ if training_metrics is None:
314
+ log.warning(f"No training metrics found in model metadata for {workbench_model.model_name}")
315
+ metrics_df = pd.DataFrame({"error": [f"No training metrics found for {workbench_model.model_name}"]})
316
+ else:
317
+ metrics_df = pd.DataFrame.from_dict(training_metrics)
318
+ log.info(f"Metrics summary:\n{metrics_df.to_string(index=False)}")
319
+
320
+ return metrics_df, predictions_df
321
+
322
+
323
+ def cross_fold_inference(
324
+ workbench_model: Any,
325
+ nfolds: int = 5,
326
+ ) -> Tuple[pd.DataFrame, pd.DataFrame]:
327
+ """Performs K-fold cross-validation for ChemProp MPNN models.
328
+
329
+ Replicates the training setup from the original model to ensure
330
+ cross-validation results are comparable to the deployed model.
331
+
332
+ Args:
333
+ workbench_model: Workbench model object
334
+ nfolds: Number of folds for cross-validation (default is 5)
335
+
336
+ Returns:
337
+ Tuple of:
338
+ - DataFrame with per-class metrics (and 'all' row for overall metrics)
339
+ - DataFrame with columns: id, target, prediction, and *_proba columns (for classifiers)
340
+ """
341
+ import shutil
342
+
343
+ import joblib
344
+ import torch
345
+ from chemprop import data, nn
346
+ from lightning import pytorch as pl
347
+
348
+ from workbench.api import FeatureSet
349
+
350
+ # Create a temporary model directory
351
+ model_dir = tempfile.mkdtemp(prefix="chemprop_cv_")
352
+ log.info(f"Using model directory: {model_dir}")
353
+
354
+ try:
355
+ # Download and extract model artifacts to get config and artifacts
356
+ model_artifact_uri = workbench_model.model_data_url()
357
+ download_and_extract_model(model_artifact_uri, model_dir)
358
+
359
+ # Load model and artifacts
360
+ loaded_model, artifacts = load_chemprop_model_artifacts(model_dir)
361
+ feature_metadata = artifacts.get("feature_metadata", {})
362
+
363
+ # Determine if classifier from predictor type
364
+ from chemprop.nn import MulticlassClassificationFFN
365
+
366
+ is_classifier = isinstance(loaded_model.predictor, MulticlassClassificationFFN)
367
+
368
+ # Use saved label encoder if available, otherwise create fresh one
369
+ if is_classifier:
370
+ label_encoder = artifacts.get("label_encoder")
371
+ if label_encoder is None:
372
+ log.warning("No saved label encoder found, creating fresh one")
373
+ label_encoder = LabelEncoder()
374
+ else:
375
+ label_encoder = None
376
+
377
+ # Prepare data
378
+ fs = FeatureSet(workbench_model.get_input())
379
+ df = workbench_model.training_view().pull_dataframe()
380
+
381
+ # Get columns
382
+ id_col = fs.id_column
383
+ target_col = workbench_model.target()
384
+ feature_cols = workbench_model.features()
385
+ print(f"Target column: {target_col}")
386
+ print(f"Feature columns: {len(feature_cols)} features")
387
+
388
+ # Find SMILES column
389
+ smiles_column = _find_smiles_column(feature_cols)
390
+
391
+ # Determine extra feature columns:
392
+ # 1. First try feature_metadata (saved during training)
393
+ # 2. Fall back to inferring from feature_cols (exclude SMILES column)
394
+ # 3. Verify against model's X_d_transform dimension
395
+ if feature_metadata and "extra_feature_cols" in feature_metadata:
396
+ extra_feature_cols = feature_metadata["extra_feature_cols"]
397
+ else:
398
+ # Infer from feature list - everything except SMILES is an extra feature
399
+ extra_feature_cols = [f for f in feature_cols if f.lower() != "smiles"]
400
+
401
+ # Verify against model's actual extra descriptor dimension
402
+ n_extra_from_model = _get_n_extra_descriptors(loaded_model)
403
+ if n_extra_from_model > 0 and len(extra_feature_cols) != n_extra_from_model:
404
+ log.warning(
405
+ f"Inferred {len(extra_feature_cols)} extra features but model expects "
406
+ f"{n_extra_from_model}. Using inferred columns."
407
+ )
408
+
409
+ use_extra_features = len(extra_feature_cols) > 0
410
+
411
+ print(f"SMILES column: {smiles_column}")
412
+ print(f"Extra features: {extra_feature_cols if use_extra_features else 'None (SMILES only)'}")
413
+
414
+ # Drop rows with missing SMILES or target values
415
+ initial_count = len(df)
416
+ df = df.dropna(subset=[smiles_column, target_col])
417
+ dropped = initial_count - len(df)
418
+ if dropped > 0:
419
+ print(f"Dropped {dropped} rows with missing SMILES or target values")
420
+
421
+ # Extract hyperparameters from loaded model
422
+ hyperparameters = _extract_model_hyperparameters(loaded_model)
423
+ print(f"Extracted hyperparameters: {hyperparameters}")
424
+
425
+ # Get number of classes for classifier
426
+ num_classes = None
427
+ if is_classifier:
428
+ # Try to get from loaded model's FFN first (most reliable)
429
+ ffn = loaded_model.predictor
430
+ if hasattr(ffn, "n_classes"):
431
+ num_classes = ffn.n_classes
432
+ elif label_encoder is not None and hasattr(label_encoder, "classes_"):
433
+ num_classes = len(label_encoder.classes_)
434
+ else:
435
+ # Fit label encoder to get classes
436
+ if label_encoder is None:
437
+ label_encoder = LabelEncoder()
438
+ label_encoder.fit(df[target_col])
439
+ num_classes = len(label_encoder.classes_)
440
+ print(f"Classification task with {num_classes} classes")
441
+
442
+ X = df[[smiles_column] + extra_feature_cols]
443
+ y = df[target_col]
444
+ ids = df[id_col]
445
+
446
+ # Encode target if classifier
447
+ if label_encoder is not None:
448
+ if not hasattr(label_encoder, "classes_"):
449
+ label_encoder.fit(y)
450
+ y_encoded = label_encoder.transform(y)
451
+ y_for_cv = pd.Series(y_encoded, index=y.index, name=target_col)
452
+ else:
453
+ y_for_cv = y
454
+
455
+ # Prepare KFold
456
+ kfold = (StratifiedKFold if is_classifier else KFold)(n_splits=nfolds, shuffle=True, random_state=42)
457
+
458
+ # Initialize results collection
459
+ fold_metrics = []
460
+ predictions_df = pd.DataFrame({id_col: ids, target_col: y})
461
+ if is_classifier:
462
+ predictions_df["pred_proba"] = [None] * len(predictions_df)
463
+
464
+ # Perform cross-validation
465
+ for fold_idx, (train_idx, val_idx) in enumerate(kfold.split(X, y_for_cv), 1):
466
+ print(f"\n{'='*50}")
467
+ print(f"Fold {fold_idx}/{nfolds}")
468
+ print(f"{'='*50}")
469
+
470
+ # Split data
471
+ df_train = df.iloc[train_idx].copy()
472
+ df_val = df.iloc[val_idx].copy()
473
+
474
+ # Encode target for this fold
475
+ if is_classifier:
476
+ df_train[target_col] = label_encoder.transform(df_train[target_col])
477
+ df_val[target_col] = label_encoder.transform(df_val[target_col])
478
+
479
+ # Prepare extra features if using hybrid mode
480
+ train_extra_features = None
481
+ val_extra_features = None
482
+ col_means = None
483
+
484
+ if use_extra_features:
485
+ train_extra_features = df_train[extra_feature_cols].values.astype(np.float32)
486
+ val_extra_features = df_val[extra_feature_cols].values.astype(np.float32)
487
+
488
+ # Fill NaN with column means from training data
489
+ col_means = np.nanmean(train_extra_features, axis=0)
490
+ for i in range(train_extra_features.shape[1]):
491
+ train_nan_mask = np.isnan(train_extra_features[:, i])
492
+ val_nan_mask = np.isnan(val_extra_features[:, i])
493
+ train_extra_features[train_nan_mask, i] = col_means[i]
494
+ val_extra_features[val_nan_mask, i] = col_means[i]
495
+
496
+ # Create ChemProp datasets
497
+ train_datapoints, train_valid_idx = _create_molecule_datapoints(
498
+ df_train[smiles_column].tolist(),
499
+ df_train[target_col].tolist(),
500
+ train_extra_features,
501
+ )
502
+ val_datapoints, val_valid_idx = _create_molecule_datapoints(
503
+ df_val[smiles_column].tolist(),
504
+ df_val[target_col].tolist(),
505
+ val_extra_features,
506
+ )
507
+
508
+ # Update dataframes to only include valid molecules
509
+ df_train_valid = df_train.iloc[train_valid_idx].reset_index(drop=True)
510
+ df_val_valid = df_val.iloc[val_valid_idx].reset_index(drop=True)
511
+
512
+ train_dataset = data.MoleculeDataset(train_datapoints)
513
+ val_dataset = data.MoleculeDataset(val_datapoints)
514
+
515
+ # Save raw validation features before scaling
516
+ val_extra_raw = val_extra_features[val_valid_idx] if val_extra_features is not None else None
517
+
518
+ # Scale extra descriptors
519
+ feature_scaler = None
520
+ x_d_transform = None
521
+ if use_extra_features:
522
+ feature_scaler = train_dataset.normalize_inputs("X_d")
523
+ val_dataset.normalize_inputs("X_d", feature_scaler)
524
+ x_d_transform = nn.ScaleTransform.from_standard_scaler(feature_scaler)
525
+
526
+ # Scale targets for regression
527
+ target_scaler = None
528
+ output_transform = None
529
+ if not is_classifier:
530
+ target_scaler = train_dataset.normalize_targets()
531
+ val_dataset.normalize_targets(target_scaler)
532
+ output_transform = nn.UnscaleTransform.from_standard_scaler(target_scaler)
533
+
534
+ # Get batch size
535
+ batch_size = min(64, max(16, len(df_train_valid) // 16))
536
+
537
+ train_loader = data.build_dataloader(train_dataset, batch_size=batch_size, shuffle=True)
538
+ val_loader = data.build_dataloader(val_dataset, batch_size=batch_size, shuffle=False)
539
+
540
+ # Build the model
541
+ n_extra = len(extra_feature_cols) if use_extra_features else 0
542
+ mpnn = _build_mpnn_model(
543
+ hyperparameters,
544
+ task="classification" if is_classifier else "regression",
545
+ num_classes=num_classes,
546
+ n_extra_descriptors=n_extra,
547
+ x_d_transform=x_d_transform,
548
+ output_transform=output_transform,
549
+ )
550
+
551
+ # Training configuration
552
+ max_epochs = hyperparameters.get("max_epochs", 50)
553
+ patience = hyperparameters.get("patience", 10)
554
+
555
+ # Set up trainer
556
+ checkpoint_dir = os.path.join(model_dir, f"fold_{fold_idx}")
557
+ os.makedirs(checkpoint_dir, exist_ok=True)
558
+
559
+ callbacks = [
560
+ pl.callbacks.EarlyStopping(monitor="val_loss", patience=patience, mode="min"),
561
+ pl.callbacks.ModelCheckpoint(
562
+ dirpath=checkpoint_dir,
563
+ filename="best_model",
564
+ monitor="val_loss",
565
+ mode="min",
566
+ save_top_k=1,
567
+ ),
568
+ ]
569
+
570
+ trainer = pl.Trainer(
571
+ accelerator="auto",
572
+ max_epochs=max_epochs,
573
+ callbacks=callbacks,
574
+ logger=False,
575
+ enable_progress_bar=True,
576
+ )
577
+
578
+ # Train the model
579
+ trainer.fit(mpnn, train_loader, val_loader)
580
+
581
+ # Load the best checkpoint
582
+ if trainer.checkpoint_callback and trainer.checkpoint_callback.best_model_path:
583
+ best_ckpt_path = trainer.checkpoint_callback.best_model_path
584
+ checkpoint = torch.load(best_ckpt_path, weights_only=False)
585
+ mpnn.load_state_dict(checkpoint["state_dict"])
586
+
587
+ mpnn.eval()
588
+
589
+ # Make predictions using raw features
590
+ val_datapoints_raw, _ = _create_molecule_datapoints(
591
+ df_val_valid[smiles_column].tolist(),
592
+ df_val_valid[target_col].tolist(),
593
+ val_extra_raw,
594
+ )
595
+ val_dataset_raw = data.MoleculeDataset(val_datapoints_raw)
596
+ val_loader_pred = data.build_dataloader(val_dataset_raw, batch_size=batch_size, shuffle=False)
597
+
598
+ with torch.inference_mode():
599
+ val_predictions = trainer.predict(mpnn, val_loader_pred)
600
+
601
+ preds = np.concatenate([p.numpy() for p in val_predictions], axis=0)
602
+
603
+ # ChemProp may return (n_samples, 1, n_classes) for multiclass - squeeze middle dim
604
+ if preds.ndim == 3 and preds.shape[1] == 1:
605
+ preds = preds.squeeze(axis=1)
606
+
607
+ # Map predictions back to original indices
608
+ original_val_indices = df.iloc[val_idx].index[val_valid_idx]
609
+
610
+ if is_classifier:
611
+ # Get class predictions
612
+ if preds.ndim == 2 and preds.shape[1] > 1:
613
+ class_preds = np.argmax(preds, axis=1)
614
+ else:
615
+ class_preds = (preds.flatten() > 0.5).astype(int)
616
+
617
+ preds_decoded = label_encoder.inverse_transform(class_preds)
618
+ predictions_df.loc[original_val_indices, "prediction"] = preds_decoded
619
+
620
+ # Store probabilities
621
+ if preds.ndim == 2 and preds.shape[1] > 1:
622
+ for i, idx in enumerate(original_val_indices):
623
+ predictions_df.at[idx, "pred_proba"] = preds[i].tolist()
624
+ else:
625
+ predictions_df.loc[original_val_indices, "prediction"] = preds.flatten()
626
+
627
+ # Calculate fold metrics
628
+ y_val = df_val_valid[target_col].values
629
+
630
+ if is_classifier:
631
+ y_val_orig = label_encoder.inverse_transform(y_val.astype(int))
632
+ preds_orig = preds_decoded
633
+
634
+ prec, rec, f1, _ = precision_recall_fscore_support(
635
+ y_val_orig, preds_orig, average="weighted", zero_division=0
636
+ )
637
+
638
+ prec_per_class, rec_per_class, f1_per_class, _ = precision_recall_fscore_support(
639
+ y_val_orig, preds_orig, average=None, zero_division=0, labels=label_encoder.classes_
640
+ )
641
+
642
+ # ROC AUC
643
+ if preds.ndim == 2 and preds.shape[1] > 1:
644
+ roc_auc_overall = roc_auc_score(y_val, preds, multi_class="ovr", average="macro")
645
+ roc_auc_per_class = roc_auc_score(y_val, preds, multi_class="ovr", average=None)
646
+ else:
647
+ roc_auc_overall = roc_auc_score(y_val, preds.flatten())
648
+ roc_auc_per_class = [roc_auc_overall]
649
+
650
+ fold_metrics.append(
651
+ {
652
+ "fold": fold_idx,
653
+ "precision": prec,
654
+ "recall": rec,
655
+ "f1": f1,
656
+ "roc_auc": roc_auc_overall,
657
+ "precision_per_class": prec_per_class,
658
+ "recall_per_class": rec_per_class,
659
+ "f1_per_class": f1_per_class,
660
+ "roc_auc_per_class": roc_auc_per_class,
661
+ }
662
+ )
663
+
664
+ print(f"Fold {fold_idx} - F1: {f1:.4f}, ROC-AUC: {roc_auc_overall:.4f}")
665
+ else:
666
+ spearman_corr, _ = spearmanr(y_val, preds.flatten())
667
+ rmse = np.sqrt(mean_squared_error(y_val, preds.flatten()))
668
+
669
+ fold_metrics.append(
670
+ {
671
+ "fold": fold_idx,
672
+ "rmse": rmse,
673
+ "mae": mean_absolute_error(y_val, preds.flatten()),
674
+ "medae": median_absolute_error(y_val, preds.flatten()),
675
+ "r2": r2_score(y_val, preds.flatten()),
676
+ "spearmanr": spearman_corr,
677
+ }
678
+ )
679
+
680
+ print(f"Fold {fold_idx} - RMSE: {rmse:.4f}, R2: {fold_metrics[-1]['r2']:.4f}")
681
+
682
+ # Calculate summary metrics
683
+ fold_df = pd.DataFrame(fold_metrics)
684
+
685
+ if is_classifier:
686
+ if "pred_proba" in predictions_df.columns:
687
+ predictions_df = expand_proba_column(predictions_df, label_encoder.classes_)
688
+
689
+ metric_rows = []
690
+ for idx, class_name in enumerate(label_encoder.classes_):
691
+ prec_scores = np.array([fold["precision_per_class"][idx] for fold in fold_metrics])
692
+ rec_scores = np.array([fold["recall_per_class"][idx] for fold in fold_metrics])
693
+ f1_scores = np.array([fold["f1_per_class"][idx] for fold in fold_metrics])
694
+ roc_auc_scores = np.array([fold["roc_auc_per_class"][idx] for fold in fold_metrics])
695
+
696
+ y_orig = label_encoder.inverse_transform(y_for_cv)
697
+ support = int((y_orig == class_name).sum())
698
+
699
+ metric_rows.append(
700
+ {
701
+ "class": class_name,
702
+ "precision": prec_scores.mean(),
703
+ "recall": rec_scores.mean(),
704
+ "f1": f1_scores.mean(),
705
+ "roc_auc": roc_auc_scores.mean(),
706
+ "support": support,
707
+ }
708
+ )
709
+
710
+ metric_rows.append(
711
+ {
712
+ "class": "all",
713
+ "precision": fold_df["precision"].mean(),
714
+ "recall": fold_df["recall"].mean(),
715
+ "f1": fold_df["f1"].mean(),
716
+ "roc_auc": fold_df["roc_auc"].mean(),
717
+ "support": len(y_for_cv),
718
+ }
719
+ )
720
+
721
+ metrics_df = pd.DataFrame(metric_rows)
722
+ else:
723
+ metrics_df = pd.DataFrame(
724
+ [
725
+ {
726
+ "rmse": fold_df["rmse"].mean(),
727
+ "mae": fold_df["mae"].mean(),
728
+ "medae": fold_df["medae"].mean(),
729
+ "r2": fold_df["r2"].mean(),
730
+ "spearmanr": fold_df["spearmanr"].mean(),
731
+ "support": len(y_for_cv),
732
+ }
733
+ ]
734
+ )
735
+
736
+ print(f"\n{'='*50}")
737
+ print("Cross-Validation Summary")
738
+ print(f"{'='*50}")
739
+ print(metrics_df.to_string(index=False))
740
+
741
+ return metrics_df, predictions_df
742
+
743
+ finally:
744
+ log.info(f"Cleaning up model directory: {model_dir}")
745
+ shutil.rmtree(model_dir, ignore_errors=True)
746
+
747
+
748
+ if __name__ == "__main__":
749
+
750
+ # Tests for the ChemProp utilities
751
+ from workbench.api import Endpoint, Model
752
+
753
+ # Initialize Workbench model
754
+ model_name = "aqsol-chemprop-reg"
755
+ print(f"Loading Workbench model: {model_name}")
756
+ model = Model(model_name)
757
+ print(f"Model Framework: {model.model_framework}")
758
+
759
+ # Perform cross-fold inference
760
+ end = Endpoint(model.endpoints()[0])
761
+ end.cross_fold_inference()