"""Feature store: single access point for cached tensors + graph batching.""" from __future__ import annotations import json import pickle from pathlib import Path from typing import Dict, List, Sequence import numpy as np import pandas as pd import torch from rdkit import Chem, RDLogger from . import data, featurize, paths RDLogger.DisableLog("rdApp.*") # unified 16-dim physical descriptor layout PHYS_NAMES = [ "logp", "charge", "hbd", "hba", "ccpp", "dccpp", "asphericity", "pmi1", "inertial", "tpsa", "mw", "rot", "nn", "frac_csp3", "tail_carbons", "heavy", ] def _frag_phys16(phys12: np.ndarray) -> np.ndarray: out = np.zeros((len(phys12), 16), dtype=np.float32) out[:, 0] = phys12[:, 1] * 5.0 # logP out[:, 1] = phys12[:, 8] # nitrogen count (charge proxy) out[:, 2] = phys12[:, 3] # HBD out[:, 3] = phys12[:, 4] # HBA out[:, 9] = phys12[:, 2] # TPSA out[:, 10] = phys12[:, 0] # MW out[:, 11] = phys12[:, 5] # rotatable bonds out[:, 12] = phys12[:, 8] # N count out[:, 13] = phys12[:, 10] # fraction sp3 out[:, 15] = phys12[:, 11] # heavy atoms return out class FeatureStore: def __init__(self, cache_dir: Path | None = None): self.cache = Path(cache_dir or paths.CACHE_DIR) self.samples = pd.read_parquet(self.cache / "samples.parquet").reset_index(drop=True) f = np.load(self.cache / "sample_features.npz", allow_pickle=True) self.y = f["y"].astype(np.float32) self.study_id = f["study_id"].astype(np.int64) self.il_id = f["il_id"].astype(np.int64) self.frag_ids = f["frag_ids"].astype(np.int64) self.frag_mask = f["frag_mask"].astype(np.float32) self.helper_ids = f["helper_ids"].astype(np.int64) self.helper_mask = f["helper_mask"].astype(np.float32) self.ratios = f["ratios"].astype(np.float32) self.ctx = f["ctx"].astype(np.float32) self.ctx_dim = int(f["ctx_dim"][0]) self.ctx_vocab = json.loads(str(f["vocab_json"][0])) self.il_fp = np.load(self.cache / "il_fp.npy") self.il_desc = np.clip(np.load(self.cache / "il_desc.npy"), -1e6, 1e6) self.il_cpp = np.load(self.cache / "il_cpp.npy") self.il_desc_names: List[str] = json.load(open(self.cache / "il_desc_names.json")) self.il_smiles: List[str] = json.load(open(self.cache / "il_vocab.json")) with open(self.cache / "il_graphs.pkl", "rb") as fh: self.il_graphs = pickle.load(fh) tok = np.load(self.cache / "il_tokens.npz") self.il_tokens = tok["tokens"] self.il_token_len = tok["lengths"] self.token_vocab: Dict[str, int] = json.load(open(self.cache / "token_vocab.json")) self.frag: Dict[str, dict] = {} for slot in list(data.FRAGMENT_SLOTS) + ["HL", "CHL", "PEG"]: z = np.load(self.cache / f"frag_{slot}.npz", allow_pickle=True) self.frag[slot] = {"fp": z["fp"], "phys": z["phys"], "smiles": z["smiles"].tolist()} self.studies: List[str] = sorted(self.samples["study"].unique().tolist()) self.n_studies = len(self.studies) # optional external multi-task targets (one column per property) aux_path = self.cache / "aux_targets.npz" if aux_path.exists(): z = np.load(aux_path, allow_pickle=True) self.aux = z["aux"].astype(np.float32) self.aux_mask = z["mask"].astype(np.float32) self.aux_names = [str(v) for v in z["names"]] else: self.aux = np.zeros((len(self.samples), 0), dtype=np.float32) self.aux_mask = np.zeros((len(self.samples), 0), dtype=np.float32) self.aux_names = [] md = np.load(self.cache / "md_labels.npz") self.md_rows = md["rows"] self.md_stable = md["stable"] self.md_flag = np.zeros(len(self.samples), dtype=np.float32) self.md_flag[self.md_rows] = 1.0 self._build_unified_physics() # ------------------------------------------------------------------ def _build_unified_physics(self) -> None: path = self.cache / "unified_phys.npz" if path.exists(): z = np.load(path) self.il_phys = z["il_phys"] self.frag_phys = {k: z[f"frag_{k}"] for k in self.frag} return il_phys = np.zeros((len(self.il_smiles), 16), dtype=np.float32) il_phys[:, 0] = self.il_cpp[:, 9] il_phys[:, 1] = self.il_cpp[:, 13] il_phys[:, 4] = self.il_cpp[:, 2] il_phys[:, 5] = self.il_cpp[:, 4] il_phys[:, 6] = self.il_cpp[:, 6] il_phys[:, 7] = np.log1p(np.clip(self.il_cpp[:, 7], 0, None)) il_phys[:, 8] = self.il_cpp[:, 8] il_phys[:, 9] = self.il_cpp[:, 10] il_phys[:, 10] = self.il_cpp[:, 11] il_phys[:, 11] = self.il_cpp[:, 12] il_phys[:, 12] = self.il_cpp[:, 13] il_phys[:, 13] = self.il_cpp[:, 15] il_phys[:, 14] = self.il_cpp[:, 14] for i, smi in enumerate(self.il_smiles): mol = Chem.MolFromSmiles(smi) if mol is None: continue try: from rdkit.Chem import rdMolDescriptors il_phys[i, 2] = rdMolDescriptors.CalcNumHBD(mol) / 5.0 il_phys[i, 3] = rdMolDescriptors.CalcNumHBA(mol) / 10.0 il_phys[i, 15] = mol.GetNumHeavyAtoms() / 100.0 except Exception: pass frag_phys = {k: _frag_phys16(v["phys"]) for k, v in self.frag.items()} np.savez_compressed(path, il_phys=il_phys, **{f"frag_{k}": v for k, v in frag_phys.items()}) self.il_phys = il_phys self.frag_phys = frag_phys # ------------------------------------------------------------------ def __len__(self) -> int: return len(self.samples) def frag_fp32(self, slot: str) -> np.ndarray: """Float32 copy of a fragment fingerprint table, built once per process. Converting the whole table on every mini-batch dominated the runtime of the set-based models (the tables hold up to tens of thousands of rows), so the conversion is memoised on the store instance. """ memo = getattr(self, "_frag_fp32_memo", None) if memo is None: memo = self._frag_fp32_memo = {} if slot not in memo: memo[slot] = np.ascontiguousarray(self.frag[slot]["fp"], dtype=np.float32) return memo[slot] def protonated_fp(self) -> np.ndarray: """Morgan fingerprints of the +1e protonated ionizable lipids (Method B).""" memo = getattr(self, "_fp_prot_memo", None) if memo is not None: return memo path = self.cache / "il_fp_prot.npy" if path.exists(): self._fp_prot_memo = np.load(path) return self._fp_prot_memo rep = self.samples.drop_duplicates("il_smiles").set_index("il_smiles") out = np.zeros_like(self.il_fp) for i, smi in enumerate(self.il_smiles): if smi in rep.index: ps = rep.loc[smi, "il_prot_smiles"] if isinstance(ps, str): out[i] = featurize.morgan_fp(ps) np.save(path, out) self._fp_prot_memo = out return out # ------------------------------------------------------------------ def il_fp_float(self) -> np.ndarray: if not hasattr(self, "_il_fp_float"): self._il_fp_float = self.il_fp.astype(np.float32) return self._il_fp_float # ------------------------------------------------------------------ def collate_graphs(self, il_ids: Sequence[int], device: torch.device) -> dict: xs, eis, eas, batches = [], [], [], [] offset = 0 for b, gid in enumerate(il_ids): g = self.il_graphs[gid] x = g["x"] xs.append(x) ei = g["edge_index"] if ei.shape[1]: eis.append(ei + offset) eas.append(g["edge_attr"]) offset += x.shape[0] batches.append(np.full(x.shape[0], b, dtype=np.int64)) x = torch.from_numpy(np.concatenate(xs, axis=0)).to(device) batch = torch.from_numpy(np.concatenate(batches, axis=0)).to(device) if eis: edge_index = torch.from_numpy(np.concatenate(eis, axis=1)).to(device) edge_attr = torch.from_numpy(np.concatenate(eas, axis=0)).to(device) else: edge_index = torch.zeros((2, 0), dtype=torch.long, device=device) edge_attr = torch.zeros((0, featurize.BOND_DIM), dtype=torch.float32, device=device) return {"x": x, "edge_index": edge_index, "edge_attr": edge_attr, "batch": batch, "n_graphs": len(il_ids)} # ------------------------------------------------------------------ def _md_stable_lookup(self, idx: np.ndarray) -> np.ndarray: mapping = {int(r): float(s) for r, s in zip(self.md_rows, self.md_stable)} return np.asarray([mapping.get(int(i), 0.0) for i in idx], dtype=np.float32) def global_codebook(self) -> np.ndarray: """Label-free archetype coordinates for every row (see global_rep).""" if not hasattr(self, "_glob_cb"): z = np.load(self.cache / "schema_blocks.npz") self._glob_cb = z["cb"].astype(np.float32) return self._glob_cb def subset(self, idx: np.ndarray) -> dict: idx = np.asarray(idx) return { "idx": idx, "y": self.y[idx], "il_id": self.il_id[idx], "frag_ids": self.frag_ids[idx], "helper_ids": self.helper_ids[idx], "ratios": self.ratios[idx], "ctx": self.ctx[idx], "study_id": self.study_id[idx], "md_flag": self.md_flag[idx], "md_stable": np.where(self.md_flag[idx] > 0, self._md_stable_lookup(idx), 0.0), "aux": self.aux[idx], "aux_mask": self.aux_mask[idx], }