|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Build the frozen Gate-1 time-series and molecule-feature tables.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import hashlib |
| 7 | +import json |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +import joblib |
| 11 | +import numpy as np |
| 12 | +import pandas as pd |
| 13 | +from rdkit import Chem |
| 14 | + |
| 15 | +from solv_ai.features import descriptor_frame |
| 16 | +from solv_ai.teachers import response_features |
| 17 | + |
| 18 | +ROOT = Path(__file__).resolve().parents[2] |
| 19 | +OUT = ROOT / "active_solvai_v3/data/derived" |
| 20 | +PHASE2 = ROOT / "active_solvai/results/phase2" |
| 21 | +MODEL = ROOT / "models/final" |
| 22 | + |
| 23 | +STRUCTURE_COLUMNS = { |
| 24 | + "structure_molecular_weight": "rdkit__MolWt", |
| 25 | + "structure_heavy_atom_count": "rdkit__HeavyAtomCount", |
| 26 | + "structure_tpsa": "rdkit__TPSA", |
| 27 | + "structure_mol_logp": "rdkit__MolLogP", |
| 28 | + "structure_hbond_donors": "rdkit__NumHDonors", |
| 29 | + "structure_hbond_acceptors": "rdkit__NumHAcceptors", |
| 30 | + "structure_rotatable_bonds": "rdkit__NumRotatableBonds", |
| 31 | + "structure_ring_count": "rdkit__RingCount", |
| 32 | + "structure_fraction_csp3": "rdkit__FractionCSP3", |
| 33 | +} |
| 34 | + |
| 35 | + |
| 36 | +def sha256(path: Path) -> str: |
| 37 | + digest = hashlib.sha256() |
| 38 | + with path.open("rb") as handle: |
| 39 | + for chunk in iter(lambda: handle.read(1024 * 1024), b""): |
| 40 | + digest.update(chunk) |
| 41 | + return digest.hexdigest() |
| 42 | + |
| 43 | + |
| 44 | +def read_energy(path: Path) -> pd.DataFrame: |
| 45 | + frame = pd.read_csv(path, sep="\t") |
| 46 | + frame.columns = [str(column).strip() for column in frame.columns] |
| 47 | + numeric = frame.apply(pd.to_numeric, errors="coerce") |
| 48 | + required = ["Time", "Temp", "Density", "dHdL"] |
| 49 | + missing = [column for column in required if column not in numeric] |
| 50 | + if missing: |
| 51 | + raise AssertionError(f"{path} lacks {missing}") |
| 52 | + if len(numeric) != 51: |
| 53 | + raise AssertionError(f"{path} has {len(numeric)} frames, expected 51") |
| 54 | + post = numeric[numeric["Time"] > 1e-9].copy().reset_index(drop=True) |
| 55 | + if len(post) != 50 or not np.isfinite(post[required]).all().all(): |
| 56 | + raise AssertionError(f"{path} does not contain 50 finite post-initial records") |
| 57 | + post["frame_index"] = np.arange(1, 51) |
| 58 | + post["block_0p5ps"] = (post["frame_index"] - 1) // 5 + 1 |
| 59 | + post["block_1ps"] = (post["frame_index"] - 1) // 10 + 1 |
| 60 | + return post |
| 61 | + |
| 62 | + |
| 63 | +def main() -> None: |
| 64 | + OUT.mkdir(parents=True, exist_ok=True) |
| 65 | + source_paths = [ |
| 66 | + PHASE2 / "dense_responses_calibration.parquet", |
| 67 | + PHASE2 / "dense_responses_prospective.parquet", |
| 68 | + ] |
| 69 | + responses = pd.concat([pd.read_parquet(path) for path in source_paths], ignore_index=True) |
| 70 | + responses = responses.rename(columns={"lambda": "lambda_value"}) |
| 71 | + if len(responses) != 180 or responses.groupby("molecule_id").size().ne(15).any(): |
| 72 | + raise AssertionError("Gate-1 source is not a complete 12 x 15 grid") |
| 73 | + |
| 74 | + time_rows: list[pd.DataFrame] = [] |
| 75 | + raw_hashes: dict[str, str] = {} |
| 76 | + for row in responses.itertuples(index=False): |
| 77 | + path = Path(str(row.energy_file)) |
| 78 | + observed_hash = sha256(path) |
| 79 | + if observed_hash != row.energy_sha256: |
| 80 | + raise AssertionError(f"energy hash mismatch: {path}") |
| 81 | + raw_hashes[str(path)] = observed_hash |
| 82 | + frame = read_energy(path) |
| 83 | + frame = frame.rename( |
| 84 | + columns={ |
| 85 | + "Time": "time_ps", |
| 86 | + "Temp": "temperature_k", |
| 87 | + "Density": "density_g_cm3", |
| 88 | + "dHdL": "dhdl_kcal_mol", |
| 89 | + } |
| 90 | + ) |
| 91 | + frame.insert(0, "lambda", float(row.lambda_value)) |
| 92 | + frame.insert(0, "canonical_smiles", row.canonical_smiles) |
| 93 | + frame.insert(0, "molecule_name", row.molecule_name) |
| 94 | + frame.insert(0, "molecule_id", row.molecule_id) |
| 95 | + frame["energy_file"] = str(path) |
| 96 | + frame["energy_sha256"] = observed_hash |
| 97 | + time_rows.append( |
| 98 | + frame[ |
| 99 | + [ |
| 100 | + "molecule_id", |
| 101 | + "molecule_name", |
| 102 | + "canonical_smiles", |
| 103 | + "lambda", |
| 104 | + "frame_index", |
| 105 | + "block_0p5ps", |
| 106 | + "block_1ps", |
| 107 | + "time_ps", |
| 108 | + "dhdl_kcal_mol", |
| 109 | + "temperature_k", |
| 110 | + "density_g_cm3", |
| 111 | + "energy_file", |
| 112 | + "energy_sha256", |
| 113 | + ] |
| 114 | + ] |
| 115 | + ) |
| 116 | + time_series = pd.concat(time_rows, ignore_index=True).sort_values( |
| 117 | + ["molecule_id", "lambda", "frame_index"] |
| 118 | + ) |
| 119 | + time_path = OUT / "gate1_time_series.parquet" |
| 120 | + time_series.to_parquet(time_path, index=False) |
| 121 | + |
| 122 | + molecules = ( |
| 123 | + responses[["molecule_id", "molecule_name", "canonical_smiles", "functional_group_family"]] |
| 124 | + .drop_duplicates() |
| 125 | + .sort_values("molecule_id") |
| 126 | + .reset_index(drop=True) |
| 127 | + ) |
| 128 | + smiles = molecules.canonical_smiles.tolist() |
| 129 | + descriptors = descriptor_frame(smiles) |
| 130 | + physical = response_features(smiles, descriptors, MODEL) |
| 131 | + head = joblib.load(MODEL / "head.joblib") |
| 132 | + response_columns = [f"response__{name}" for name in head["teacher_columns"]] |
| 133 | + if physical.shape != (len(molecules), 15) or len(response_columns) != 15: |
| 134 | + raise AssertionError("frozen SolvAI response schema is not 15-dimensional") |
| 135 | + features = molecules.copy() |
| 136 | + for output_name, descriptor_name in STRUCTURE_COLUMNS.items(): |
| 137 | + features[output_name] = descriptors[descriptor_name].to_numpy(float) |
| 138 | + features["structure_formal_charge"] = [ |
| 139 | + int(Chem.GetFormalCharge(Chem.MolFromSmiles(value))) for value in smiles |
| 140 | + ] |
| 141 | + for index, name in enumerate(response_columns): |
| 142 | + features[name] = physical[:, index] |
| 143 | + feature_path = OUT / "gate1_molecule_features.parquet" |
| 144 | + features.to_parquet(feature_path, index=False) |
| 145 | + |
| 146 | + manifest = { |
| 147 | + "schema_version": 1, |
| 148 | + "molecules": int(features.molecule_id.nunique()), |
| 149 | + "windows": int(responses.shape[0]), |
| 150 | + "post_initial_frames": int(len(time_series)), |
| 151 | + "lambda_values": sorted(responses["lambda_value"].unique().tolist()), |
| 152 | + "structure_columns": [*STRUCTURE_COLUMNS, "structure_formal_charge"], |
| 153 | + "response_columns": response_columns, |
| 154 | + "source_tables": {str(path): sha256(path) for path in source_paths}, |
| 155 | + "raw_energy_files": raw_hashes, |
| 156 | + "outputs": { |
| 157 | + str(time_path): sha256(time_path), |
| 158 | + str(feature_path): sha256(feature_path), |
| 159 | + }, |
| 160 | + "independence_warning": ( |
| 161 | + "One 5-ps stream per molecule-window; blocks are development diagnostics, not replicas." |
| 162 | + ), |
| 163 | + } |
| 164 | + manifest_path = OUT / "gate1_dataset_manifest.json" |
| 165 | + manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n") |
| 166 | + print(json.dumps({key: value for key, value in manifest.items() if key != "raw_energy_files"}, indent=2)) |
| 167 | + |
| 168 | + |
| 169 | +if __name__ == "__main__": |
| 170 | + main() |
0 commit comments