Download predict.py from RohanSaha2006/kcat-km-model: direct link, hf CLI and curl.
- Browser
- Download file 3.62 kB
-
https://huggingface.co/RohanSaha2006/kcat-km-model/resolve/main/predict.py
- Command line
-
hf download hf://RohanSaha2006/kcat-km-model/predict.py
-
curl -L -o predict.py https://huggingface.co/RohanSaha2006/kcat-km-model/resolve/main/predict.py
3.62 kB
| import numpy as np | |
| import pandas as pd | |
| import joblib, argparse, os, sys | |
| from rdkit import Chem | |
| from rdkit.Chem import AllChem, MACCSkeys | |
| BASE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, BASE) | |
| cache_data = np.load(os.path.join(BASE, "prott5_cache.npz"), allow_pickle=True) | |
| prott5_cache = cache_data["cache"].item() | |
| scaler = joblib.load(os.path.join(BASE, "scaler.pkl")) | |
| smiles_cache = joblib.load(os.path.join(BASE, "smiles_cache.pkl")) | |
| N_FOLDS = 3 | |
| et_kcat_models = [joblib.load(os.path.join(BASE, f"et_kcat_fold{i}.pkl")) for i in range(N_FOLDS)] | |
| et_km_models = [joblib.load(os.path.join(BASE, f"et_km_fold{i}.pkl")) for i in range(N_FOLDS)] | |
| SMILES_DIM = len(next(iter(smiles_cache.values()))) | |
| # SMILES Transformer only for SMILES not in cache; never allowed to crash | |
| try: | |
| import torch | |
| from build_vocab import WordVocab | |
| from pretrain_trfm import TrfmSeq2seq | |
| from utils import split | |
| vocab = WordVocab.load_vocab(os.path.join(BASE, "vocab.pkl")) | |
| trfm = TrfmSeq2seq(len(vocab), 256, len(vocab), 4) | |
| trfm.load_state_dict(torch.load(os.path.join(BASE, "trfm_12_23000.pkl"), map_location="cpu")) | |
| trfm.eval() | |
| SMILES_T_OK = True | |
| except Exception as e: | |
| print(f"WARNING: SMILES Transformer unavailable ({e}); novel SMILES -> zero vector") | |
| SMILES_T_OK = False | |
| def smiles_to_vec(smiles): | |
| if not SMILES_T_OK: | |
| return np.zeros(SMILES_DIM, dtype=np.float32) | |
| try: | |
| tokens = split(smiles) | |
| if len(tokens) > 218: | |
| tokens = tokens[:109] + tokens[-109:] | |
| ids = [3] + [vocab.stoi.get(t, 1) for t in tokens] + [2] | |
| ids += [0] * (220 - len(ids)) | |
| xid = torch.tensor([ids]).T | |
| with torch.no_grad(): | |
| out = trfm.encode(xid) | |
| return np.array(out, dtype=np.float32).squeeze(0) | |
| except Exception: | |
| return np.zeros(SMILES_DIM, dtype=np.float32) | |
| def get_maccs(smiles): | |
| mol = Chem.MolFromSmiles(smiles) | |
| if mol is None: return np.zeros(167, dtype=np.float32) | |
| return np.array(MACCSkeys.GenMACCSKeys(mol), dtype=np.float32) | |
| def get_morgan_fp(smiles, radius=2, nbits=2048): | |
| mol = Chem.MolFromSmiles(smiles) | |
| if mol is None: return np.zeros(nbits, dtype=np.float32) | |
| fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius, nBits=nbits) | |
| return np.array(fp, dtype=np.float32) | |
| def predict(input_path, output_path): | |
| df = pd.read_parquet(input_path) | |
| rows, miss_seq, miss_smi = [], 0, 0 | |
| for _, row in df.iterrows(): | |
| prot = prott5_cache.get(row["sequence"]) | |
| if prot is None: | |
| prot = np.zeros(1024, dtype=np.float32); miss_seq += 1 | |
| smi = smiles_cache.get(row["smiles"]) | |
| if smi is None: | |
| smi = smiles_to_vec(row["smiles"]); miss_smi += 1 | |
| rows.append(np.concatenate([prot, smi, get_maccs(row["smiles"]), | |
| get_morgan_fp(row["smiles"])])) | |
| print(f"Sequences not in cache: {miss_seq} | SMILES not in cache: {miss_smi}") | |
| X = scaler.transform(np.array(rows, dtype=np.float32)) | |
| pred_kcat = np.mean([m.predict(X) for m in et_kcat_models], axis=0) | |
| pred_km = np.mean([m.predict(X) for m in et_km_models], axis=0) | |
| pd.DataFrame({"id": df["id"].values, | |
| "log10_kcat": pred_kcat, | |
| "log10_km": pred_km}).to_csv(output_path, index=False) | |
| print(f"Saved {len(df)} predictions to {output_path}") | |
| if __name__ == "__main__": | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--input", required=True) | |
| p.add_argument("--output", required=True) | |
| a = p.parse_args() | |
| predict(a.input, a.output) | |