|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Shared, frozen utilities for the SolvAI Phase 1 confirmation package.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +from dataclasses import dataclass |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +import numpy as np |
| 10 | +import pandas as pd |
| 11 | +from sklearn.ensemble import ExtraTreesRegressor |
| 12 | +from sklearn.impute import SimpleImputer |
| 13 | +from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score |
| 14 | +from sklearn.pipeline import make_pipeline |
| 15 | + |
| 16 | + |
| 17 | +MODEL_SEEDS = (11, 29, 47) |
| 18 | +REPEAT_SEEDS = (314159, 271828, 161803, 141421, 173205) |
| 19 | +SHUFFLE_SEEDS = (88001, 88002, 88003, 88004, 88005) |
| 20 | +BOOTSTRAP_SEED = 20260828 |
| 21 | + |
| 22 | + |
| 23 | +@dataclass |
| 24 | +class ConfirmatoryData: |
| 25 | + benchmark: pd.DataFrame |
| 26 | + public: pd.DataFrame |
| 27 | + benchmark_structure: np.ndarray |
| 28 | + public_structure: np.ndarray |
| 29 | + benchmark_responses: dict[str, np.ndarray] |
| 30 | + public_responses: dict[str, np.ndarray] |
| 31 | + feature_sets: dict[str, tuple[np.ndarray, np.ndarray]] |
| 32 | + response_names: list[str] |
| 33 | + |
| 34 | + |
| 35 | +def _align(table: pd.DataFrame, ids: pd.Series, columns: list[str]) -> np.ndarray: |
| 36 | + indexed = table.drop_duplicates("molecule_id").set_index("molecule_id") |
| 37 | + values = indexed.reindex(ids.astype(str))[columns].to_numpy(dtype=np.float32) |
| 38 | + if values.shape != (len(ids), len(columns)) or not np.isfinite(values).all(): |
| 39 | + raise AssertionError(f"Invalid alignment for {columns}") |
| 40 | + return values |
| 41 | + |
| 42 | + |
| 43 | +def load_confirmatory_data(workspace_root: Path) -> ConfirmatoryData: |
| 44 | + processed = workspace_root / "data" / "processed" |
| 45 | + benchmark = pd.read_parquet(processed / "arrow_solvation_master.parquet") |
| 46 | + benchmark = ( |
| 47 | + benchmark.loc[benchmark.solvent.eq("water")] |
| 48 | + .drop_duplicates("molecule_id") |
| 49 | + .reset_index(drop=True) |
| 50 | + ) |
| 51 | + if len(benchmark) != 85: |
| 52 | + raise AssertionError(f"Expected 85 benchmark rows, found {len(benchmark)}") |
| 53 | + |
| 54 | + public_all = pd.read_parquet( |
| 55 | + processed / "expanded_public_hydration_nonbenchmark.parquet" |
| 56 | + ) |
| 57 | + old_public = pd.read_parquet(processed / "public_hydration_nonbenchmark.parquet") |
| 58 | + old_keys = set(old_public.inchi_connectivity_key.astype(str)) |
| 59 | + source_mask = ( |
| 60 | + public_all.inchi_connectivity_key.astype(str).isin(old_keys) |
| 61 | + | public_all.source_measurement_count.fillna(0).ge(2) |
| 62 | + ).to_numpy() |
| 63 | + public = public_all.loc[source_mask].reset_index(drop=True) |
| 64 | + if len(public) != 1280: |
| 65 | + raise AssertionError(f"Expected 1,280 public endpoint rows, found {len(public)}") |
| 66 | + if set(benchmark.inchi_connectivity_key.astype(str)) & set( |
| 67 | + public.inchi_connectivity_key.astype(str) |
| 68 | + ): |
| 69 | + raise AssertionError("Exact benchmark connectivity in endpoint training pool") |
| 70 | + |
| 71 | + benchmark_features = pd.read_parquet(processed / "rdkit_morgan_features.parquet") |
| 72 | + public_features_all = pd.read_parquet( |
| 73 | + processed / "expanded_public_hydration_rdkit_morgan_features.parquet" |
| 74 | + ) |
| 75 | + if not benchmark.molecule_id.equals(benchmark_features.molecule_id): |
| 76 | + raise AssertionError("Benchmark structure-feature order changed") |
| 77 | + if not public_all.molecule_id.equals(public_features_all.molecule_id): |
| 78 | + raise AssertionError("Public structure-feature order changed") |
| 79 | + public_features = public_features_all.loc[source_mask].reset_index(drop=True) |
| 80 | + descriptor_columns = [ |
| 81 | + column |
| 82 | + for column in benchmark_features |
| 83 | + if column.startswith(("rdkit__", "morgan2__")) |
| 84 | + ] |
| 85 | + if len(descriptor_columns) != 2265: |
| 86 | + raise AssertionError( |
| 87 | + f"Expected 2,265 structure columns, found {len(descriptor_columns)}" |
| 88 | + ) |
| 89 | + benchmark_structure = benchmark_features[descriptor_columns].to_numpy( |
| 90 | + dtype=np.float32 |
| 91 | + ) |
| 92 | + public_structure = public_features[descriptor_columns].to_numpy(dtype=np.float32) |
| 93 | + |
| 94 | + qm = pd.read_parquet(processed / "combisolv_qm_teacher_predictions.parquet") |
| 95 | + abraham = pd.read_parquet( |
| 96 | + processed / "soluteml_abraham_teacher_predictions.parquet" |
| 97 | + ) |
| 98 | + openff = pd.read_parquet( |
| 99 | + processed / "openff_alchemical_teacher_predictions.parquet" |
| 100 | + ) |
| 101 | + implicit = pd.read_parquet( |
| 102 | + processed / "implicit_solvent_teacher_predictions.parquet" |
| 103 | + ) |
| 104 | + smd = pd.read_parquet(processed / "molsolv_smd_teacher_predictions.parquet") |
| 105 | + confsolv = pd.read_parquet( |
| 106 | + processed / "confsolv_water_teacher_predictions.parquet" |
| 107 | + ) |
| 108 | + |
| 109 | + qcols = ["combisolv_qm_teacher"] |
| 110 | + acols = [f"abraham_{name}_teacher" for name in "esabl"] |
| 111 | + ocols = ["openff23_dg_teacher", "openff23_exp_residual_teacher"] |
| 112 | + icols = ["gbn2_alchemical_dg_teacher", "gbn2_exp_residual_teacher"] |
| 113 | + scols = ["molsolv_smd_teacher"] |
| 114 | + ccols = [ |
| 115 | + "confsolv_gas_conformer_correction_teacher", |
| 116 | + "confsolv_solution_conformer_correction_teacher", |
| 117 | + "confsolv_hydration_conformer_correction_teacher", |
| 118 | + "confsolv_water_gsolv_std_teacher", |
| 119 | + "confsolv_water_response_mean_teacher", |
| 120 | + "confsolv_water_response_std_teacher", |
| 121 | + ] |
| 122 | + |
| 123 | + def response_parts(ids: pd.Series) -> dict[str, np.ndarray]: |
| 124 | + qm_values = _align(qm, ids, qcols) |
| 125 | + abraham_values = _align(abraham, ids, acols) |
| 126 | + openff_values = _align(openff, ids, ocols) |
| 127 | + implicit_values = _align(implicit, ids, icols) |
| 128 | + smd_values = _align(smd, ids, scols) |
| 129 | + confsolv_values = _align(confsolv, ids, ccols) |
| 130 | + openff_corrected = openff_values.sum(axis=1, keepdims=True) |
| 131 | + gbn2_corrected = implicit_values.sum(axis=1, keepdims=True) |
| 132 | + empirical = np.column_stack( |
| 133 | + [abraham_values, openff_corrected, gbn2_corrected] |
| 134 | + ).astype(np.float32) |
| 135 | + computation_core = np.column_stack( |
| 136 | + [qm_values, openff_values[:, [0]], implicit_values[:, [0]]] |
| 137 | + ).astype(np.float32) |
| 138 | + narrow = np.column_stack( |
| 139 | + [qm_values, abraham_values, openff_corrected, gbn2_corrected] |
| 140 | + ).astype(np.float32) |
| 141 | + full = np.column_stack( |
| 142 | + [narrow, smd_values, confsolv_values] |
| 143 | + ).astype(np.float32) |
| 144 | + return { |
| 145 | + "empirical_residual": empirical, |
| 146 | + "computation_core": computation_core, |
| 147 | + "smd": smd_values, |
| 148 | + "confsolv": confsolv_values, |
| 149 | + "narrow": narrow, |
| 150 | + "narrow_smd": np.column_stack([narrow, smd_values]).astype(np.float32), |
| 151 | + "full": full, |
| 152 | + } |
| 153 | + |
| 154 | + benchmark_responses = response_parts(benchmark.molecule_id) |
| 155 | + public_responses_all = response_parts(public_all.molecule_id) |
| 156 | + public_responses = { |
| 157 | + name: values[source_mask] for name, values in public_responses_all.items() |
| 158 | + } |
| 159 | + |
| 160 | + def add(base: np.ndarray, response: np.ndarray | None) -> np.ndarray: |
| 161 | + return base if response is None else np.column_stack([base, response]) |
| 162 | + |
| 163 | + feature_spec = { |
| 164 | + "A_structure_only": None, |
| 165 | + "B_empirical_residual": "empirical_residual", |
| 166 | + "C_computation_core": "computation_core", |
| 167 | + "D_smd_water": "smd", |
| 168 | + "E_confsolv": "confsolv", |
| 169 | + "F_full_solvai": "full", |
| 170 | + "G_narrow_reference": "narrow", |
| 171 | + "H_narrow_smd_reference": "narrow_smd", |
| 172 | + } |
| 173 | + feature_sets = { |
| 174 | + name: ( |
| 175 | + add(benchmark_structure, benchmark_responses[key] if key else None), |
| 176 | + add(public_structure, public_responses[key] if key else None), |
| 177 | + ) |
| 178 | + for name, key in feature_spec.items() |
| 179 | + } |
| 180 | + response_names = [ |
| 181 | + "combisolv_qm", |
| 182 | + "abraham_e", |
| 183 | + "abraham_s", |
| 184 | + "abraham_a", |
| 185 | + "abraham_b", |
| 186 | + "abraham_l", |
| 187 | + "openff_corrected", |
| 188 | + "gbn2_corrected", |
| 189 | + "smd_water", |
| 190 | + "confsolv_gas_conformer_correction", |
| 191 | + "confsolv_solution_conformer_correction", |
| 192 | + "confsolv_hydration_conformer_correction", |
| 193 | + "confsolv_water_gsolv_std", |
| 194 | + "confsolv_water_response_mean", |
| 195 | + "confsolv_water_response_std", |
| 196 | + ] |
| 197 | + if benchmark_responses["full"].shape[1] != 15: |
| 198 | + raise AssertionError("Full response block does not contain 15 coordinates") |
| 199 | + return ConfirmatoryData( |
| 200 | + benchmark=benchmark, |
| 201 | + public=public, |
| 202 | + benchmark_structure=benchmark_structure, |
| 203 | + public_structure=public_structure, |
| 204 | + benchmark_responses=benchmark_responses, |
| 205 | + public_responses=public_responses, |
| 206 | + feature_sets=feature_sets, |
| 207 | + response_names=response_names, |
| 208 | + ) |
| 209 | + |
| 210 | + |
| 211 | +def endpoint_model(seed: int): |
| 212 | + return make_pipeline( |
| 213 | + SimpleImputer(strategy="median", add_indicator=True), |
| 214 | + ExtraTreesRegressor( |
| 215 | + n_estimators=360, |
| 216 | + max_features=0.7, |
| 217 | + min_samples_leaf=2, |
| 218 | + criterion="squared_error", |
| 219 | + bootstrap=False, |
| 220 | + max_depth=None, |
| 221 | + min_samples_split=2, |
| 222 | + random_state=seed, |
| 223 | + n_jobs=-1, |
| 224 | + ), |
| 225 | + ) |
| 226 | + |
| 227 | + |
| 228 | +def fit_predict( |
| 229 | + public_x: np.ndarray, |
| 230 | + public_y: np.ndarray, |
| 231 | + benchmark_x: np.ndarray, |
| 232 | + benchmark_y: np.ndarray, |
| 233 | + train_indices: np.ndarray, |
| 234 | + test_indices: np.ndarray, |
| 235 | +) -> np.ndarray: |
| 236 | + x_fit = np.vstack([public_x, benchmark_x[train_indices]]) |
| 237 | + y_fit = np.concatenate([public_y, benchmark_y[train_indices]]) |
| 238 | + weights = np.concatenate( |
| 239 | + [np.ones(len(public_y)), np.full(len(train_indices), 3.0)] |
| 240 | + ) |
| 241 | + predictions = [] |
| 242 | + for seed in MODEL_SEEDS: |
| 243 | + model = endpoint_model(seed) |
| 244 | + model.fit(x_fit, y_fit, extratreesregressor__sample_weight=weights) |
| 245 | + predictions.append(model.predict(benchmark_x[test_indices])) |
| 246 | + return np.mean(predictions, axis=0) |
| 247 | + |
| 248 | + |
| 249 | +def metric_record(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]: |
| 250 | + residual = y_true - y_pred |
| 251 | + return { |
| 252 | + "mae": float(mean_absolute_error(y_true, y_pred)), |
| 253 | + "rmse": float(mean_squared_error(y_true, y_pred) ** 0.5), |
| 254 | + "median_absolute_error": float(np.median(np.abs(residual))), |
| 255 | + "r2": float(r2_score(y_true, y_pred)), |
| 256 | + } |
| 257 | + |
| 258 | + |
| 259 | +def bootstrap_difference( |
| 260 | + truth: np.ndarray, |
| 261 | + candidate: np.ndarray, |
| 262 | + baseline: np.ndarray, |
| 263 | + *, |
| 264 | + seed: int = BOOTSTRAP_SEED, |
| 265 | + draws: int = 100_000, |
| 266 | +) -> dict[str, float | str]: |
| 267 | + differences = np.abs(truth - candidate) - np.abs(truth - baseline) |
| 268 | + rng = np.random.default_rng(seed) |
| 269 | + indices = rng.integers(0, len(truth), size=(draws, len(truth))) |
| 270 | + sampled = differences[indices].mean(axis=1) |
| 271 | + low, high = np.quantile(sampled, [0.025, 0.975]) |
| 272 | + mean = float(differences.mean()) |
| 273 | + if high < 0: |
| 274 | + outcome = "positive" |
| 275 | + elif low > 0: |
| 276 | + outcome = "negative" |
| 277 | + else: |
| 278 | + outcome = "neutral" |
| 279 | + return { |
| 280 | + "mae_difference_vs_structure": mean, |
| 281 | + "ci_low_95": float(low), |
| 282 | + "ci_high_95": float(high), |
| 283 | + "probability_lower_error": float(np.mean(sampled < 0)), |
| 284 | + "fraction_molecules_improved": float(np.mean(differences < 0)), |
| 285 | + "material": bool(abs(mean) >= 0.010), |
| 286 | + "outcome": outcome, |
| 287 | + } |
0 commit comments