Update evaluate_molecular_model.py
Browse files- evaluate_molecular_model.py +425 -338
evaluate_molecular_model.py
CHANGED
|
@@ -1,339 +1,426 @@
|
|
| 1 |
-
# evaluate_molecular_model.py
|
| 2 |
-
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
from rdkit
|
| 13 |
-
from rdkit import
|
| 14 |
-
|
| 15 |
-
import
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
from
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
#
|
| 28 |
-
#
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
#
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
)
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
for
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
print(f"
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
#
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
"
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
#
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
)
|
|
|
|
| 1 |
+
# evaluate_molecular_model.py
|
| 2 |
+
# evaluate_molecular_model.py
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import json
|
| 6 |
+
import argparse
|
| 7 |
+
import random
|
| 8 |
+
from typing import List, Optional
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from rdkit import Chem
|
| 13 |
+
from rdkit.Chem import AllChem
|
| 14 |
+
from rdkit import RDLogger
|
| 15 |
+
import selfies as sf
|
| 16 |
+
import pandas as pd
|
| 17 |
+
|
| 18 |
+
# Suppress RDKit warnings
|
| 19 |
+
RDLogger.DisableLog('rdApp.*')
|
| 20 |
+
|
| 21 |
+
# Add local path
|
| 22 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 23 |
+
|
| 24 |
+
from FastChemTokenizerHF import FastChemTokenizerSelfies
|
| 25 |
+
from ChemQ3MTP import ChemQ3MTPForCausalLM
|
| 26 |
+
|
| 27 |
+
# ----------------------------
|
| 28 |
+
# Robust Conversion & Validation (as per your spec)
|
| 29 |
+
# ----------------------------
|
| 30 |
+
|
| 31 |
+
def selfies_to_smiles(selfies_str: str) -> Optional[str]:
|
| 32 |
+
"""Convert SELFIES string to SMILES, handling tokenizer artifacts."""
|
| 33 |
+
try:
|
| 34 |
+
clean_selfies = selfies_str.replace(" ", "")
|
| 35 |
+
return sf.decoder(clean_selfies)
|
| 36 |
+
except Exception:
|
| 37 |
+
return None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def is_valid_smiles(smiles: str) -> bool:
|
| 41 |
+
"""
|
| 42 |
+
Check if a SMILES string represents a valid molecule.
|
| 43 |
+
FIXED: Now properly checks for heavy atoms (non-hydrogens) >= 3
|
| 44 |
+
and rejects disconnected/separated molecules
|
| 45 |
+
"""
|
| 46 |
+
if not isinstance(smiles, str) or len(smiles.strip()) == 0:
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
smiles = smiles.strip()
|
| 50 |
+
|
| 51 |
+
# FAST CHECK: Reject separated molecules (contains dots)
|
| 52 |
+
if '.' in smiles:
|
| 53 |
+
return False # Disconnected components indicated by dots
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 57 |
+
if mol is None:
|
| 58 |
+
return False
|
| 59 |
+
|
| 60 |
+
# CRITICAL FIX: Check heavy atoms (non-hydrogens), not total atoms
|
| 61 |
+
heavy_atoms = mol.GetNumHeavyAtoms() # This excludes hydrogens
|
| 62 |
+
if heavy_atoms < 3:
|
| 63 |
+
return False
|
| 64 |
+
|
| 65 |
+
return True
|
| 66 |
+
except Exception:
|
| 67 |
+
return False
|
| 68 |
+
|
| 69 |
+
def passes_durrant_lab_filter(smiles: str) -> bool:
|
| 70 |
+
"""
|
| 71 |
+
Apply Durrant's lab filter to remove improbable substructures.
|
| 72 |
+
FIXED: More robust error handling, pattern checking, and disconnected molecule rejection.
|
| 73 |
+
Returns True if molecule passes the filter (is acceptable), False otherwise.
|
| 74 |
+
"""
|
| 75 |
+
if not smiles or not isinstance(smiles, str) or len(smiles.strip()) == 0:
|
| 76 |
+
return False
|
| 77 |
+
|
| 78 |
+
try:
|
| 79 |
+
mol = Chem.MolFromSmiles(smiles.strip())
|
| 80 |
+
if mol is None:
|
| 81 |
+
return False
|
| 82 |
+
|
| 83 |
+
# Check heavy atoms again (belt and suspenders approach)
|
| 84 |
+
if mol.GetNumHeavyAtoms() < 3:
|
| 85 |
+
return False
|
| 86 |
+
|
| 87 |
+
# REJECT SEPARATED/DISCONNECTED MOLECULES (double check here too)
|
| 88 |
+
fragments = Chem.rdmolops.GetMolFrags(mol, asMols=False)
|
| 89 |
+
if len(fragments) > 1:
|
| 90 |
+
return False # Reject molecules with multiple disconnected parts
|
| 91 |
+
|
| 92 |
+
# Define SMARTS patterns for problematic substructures
|
| 93 |
+
problematic_patterns = [
|
| 94 |
+
"C=[N-]", # Carbon double bonded to negative nitrogen
|
| 95 |
+
"[N-]C=[N+]", # Nitrogen anion bonded to nitrogen cation
|
| 96 |
+
"[nH+]c[n-]", # Aromatic nitrogen cation adjacent to nitrogen anion
|
| 97 |
+
"[#7+]~[#7+]", # Positive nitrogen connected to positive nitrogen
|
| 98 |
+
"[#7-]~[#7-]", # Negative nitrogen connected to negative nitrogen
|
| 99 |
+
"[!#7]~[#7+]~[#7-]~[!#7]", # Bridge: non-nitrogen - pos nitrogen - neg nitrogen - non-nitrogen
|
| 100 |
+
"[#5]", # Boron atoms
|
| 101 |
+
"O=[PH](=O)([#8])([#8])", # Phosphoryl with hydroxyls
|
| 102 |
+
"N=c1cc[#7]c[#7]1", # Nitrogen in aromatic ring with another nitrogen
|
| 103 |
+
"[$([NX2H1]),$([NX3H2])]=C[$([OH]),$([O-])]", # N=CH-OH or N=CH-O-
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
# Check for metals (excluding common biologically relevant ions)
|
| 107 |
+
metal_exclusions = {11, 12, 19, 20} # Na, Mg, K, Ca
|
| 108 |
+
for atom in mol.GetAtoms():
|
| 109 |
+
atomic_num = atom.GetAtomicNum()
|
| 110 |
+
# More precise metal detection
|
| 111 |
+
if atomic_num > 20 and atomic_num not in metal_exclusions:
|
| 112 |
+
return False
|
| 113 |
+
|
| 114 |
+
# Check for each problematic pattern
|
| 115 |
+
for pattern in problematic_patterns:
|
| 116 |
+
try:
|
| 117 |
+
patt_mol = Chem.MolFromSmarts(pattern)
|
| 118 |
+
if patt_mol is not None:
|
| 119 |
+
matches = mol.GetSubstructMatches(patt_mol)
|
| 120 |
+
if matches:
|
| 121 |
+
return False # Found problematic substructure
|
| 122 |
+
except Exception:
|
| 123 |
+
# If SMARTS parsing fails, continue to next pattern
|
| 124 |
+
continue
|
| 125 |
+
|
| 126 |
+
return True # Passed all checks
|
| 127 |
+
|
| 128 |
+
except Exception:
|
| 129 |
+
return False
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def get_sa_label_and_confidence(selfies_str: str) -> tuple[str, float]:
|
| 133 |
+
"""Get SA label (Easy/Hard) and confidence from the model's SA classifier."""
|
| 134 |
+
try:
|
| 135 |
+
from ChemQ3MTP.rl_utils import get_sa_classifier
|
| 136 |
+
classifier = get_sa_classifier()
|
| 137 |
+
if classifier is None:
|
| 138 |
+
return "Unknown", 0.0
|
| 139 |
+
|
| 140 |
+
# Get raw classifier output: [{'label': 'Easy', 'score': 0.9187200665473938}]
|
| 141 |
+
result = classifier(selfies_str, truncation=True, max_length=128)[0]
|
| 142 |
+
return result["label"], result["score"]
|
| 143 |
+
except Exception as e:
|
| 144 |
+
return "Unknown", 0.0
|
| 145 |
+
|
| 146 |
+
def get_morgan_fingerprint_from_smiles(smiles: str, radius=2, n_bits=2048):
|
| 147 |
+
mol = Chem.MolFromSmiles(smiles)
|
| 148 |
+
if mol is None:
|
| 149 |
+
return None
|
| 150 |
+
return AllChem.GetMorganFingerprintAsBitVect(mol, radius, nBits=n_bits)
|
| 151 |
+
|
| 152 |
+
def tanimoto_sim(fp1, fp2):
|
| 153 |
+
from rdkit.DataStructs import TanimotoSimilarity
|
| 154 |
+
return TanimotoSimilarity(fp1, fp2)
|
| 155 |
+
|
| 156 |
+
# ----------------------------
|
| 157 |
+
# Main Evaluation Function
|
| 158 |
+
# ----------------------------
|
| 159 |
+
|
| 160 |
+
def evaluate_model(
|
| 161 |
+
model_path: str,
|
| 162 |
+
train_data_path: str = "../data/chunk_5.csv",
|
| 163 |
+
n_samples: int = 1000,
|
| 164 |
+
seed: int = 42,
|
| 165 |
+
max_gen_len: int = 32
|
| 166 |
+
):
|
| 167 |
+
torch.manual_seed(seed)
|
| 168 |
+
random.seed(seed)
|
| 169 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 170 |
+
print(f"🚀 Evaluating model at: {model_path}")
|
| 171 |
+
print(f" Device: {device} | Samples: {n_samples} | Seed: {seed}\n")
|
| 172 |
+
|
| 173 |
+
# Load tokenizer and model
|
| 174 |
+
tokenizer = FastChemTokenizerSelfies.from_pretrained("../selftok_core")
|
| 175 |
+
model = ChemQ3MTPForCausalLM.from_pretrained(model_path)
|
| 176 |
+
model.to(device)
|
| 177 |
+
model.eval()
|
| 178 |
+
|
| 179 |
+
# Load training set and normalize SELFIES (remove spaces)
|
| 180 |
+
print("📂 Loading and normalizing training set for novelty...")
|
| 181 |
+
train_df = pd.read_csv(train_data_path)
|
| 182 |
+
train_selfies_clean = set()
|
| 183 |
+
for s in train_df["SELFIES"].dropna().astype(str):
|
| 184 |
+
clean_s = s.replace(" ", "")
|
| 185 |
+
train_selfies_clean.add(clean_s)
|
| 186 |
+
print(f" Training set size: {len(train_selfies_clean)} unique (space-free) SELFIES\n")
|
| 187 |
+
|
| 188 |
+
# === MTP-AWARE GENERATION ===
|
| 189 |
+
print("GenerationStrategy: Using MTP-aware generation...")
|
| 190 |
+
all_selfies_raw = []
|
| 191 |
+
batch_size = 32
|
| 192 |
+
num_batches = (n_samples + batch_size - 1) // batch_size
|
| 193 |
+
|
| 194 |
+
with torch.no_grad():
|
| 195 |
+
for _ in tqdm(range(num_batches), desc="Generating"):
|
| 196 |
+
current_batch_size = min(batch_size, n_samples - len(all_selfies_raw))
|
| 197 |
+
if current_batch_size <= 0:
|
| 198 |
+
break
|
| 199 |
+
|
| 200 |
+
input_ids = torch.full(
|
| 201 |
+
(current_batch_size, 1),
|
| 202 |
+
tokenizer.bos_token_id,
|
| 203 |
+
dtype=torch.long,
|
| 204 |
+
device=device
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
if hasattr(model, 'generate_with_logprobs'):
|
| 208 |
+
try:
|
| 209 |
+
outputs = model.generate_with_logprobs(
|
| 210 |
+
input_ids=input_ids,
|
| 211 |
+
max_new_tokens=25,
|
| 212 |
+
temperature=1.0,
|
| 213 |
+
top_k=50,
|
| 214 |
+
top_p=0.95,
|
| 215 |
+
do_sample=True,
|
| 216 |
+
return_probs=True,
|
| 217 |
+
tokenizer=tokenizer
|
| 218 |
+
)
|
| 219 |
+
batch_selfies = outputs[0] # list of raw SELFIES (may have spaces)
|
| 220 |
+
except Exception as e:
|
| 221 |
+
print(f"⚠️ MTP generation failed: {e}. Falling back.")
|
| 222 |
+
gen_tokens = model.generate(
|
| 223 |
+
input_ids,
|
| 224 |
+
max_length=max_gen_len,
|
| 225 |
+
do_sample=True,
|
| 226 |
+
top_k=50,
|
| 227 |
+
top_p=0.95,
|
| 228 |
+
temperature=1.0,
|
| 229 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 230 |
+
eos_token_id=tokenizer.eos_token_id
|
| 231 |
+
)
|
| 232 |
+
batch_selfies = [
|
| 233 |
+
tokenizer.decode(seq, skip_special_tokens=True)
|
| 234 |
+
for seq in gen_tokens
|
| 235 |
+
]
|
| 236 |
+
else:
|
| 237 |
+
gen_tokens = model.generate(
|
| 238 |
+
input_ids,
|
| 239 |
+
max_length=max_gen_len,
|
| 240 |
+
do_sample=True,
|
| 241 |
+
top_k=50,
|
| 242 |
+
top_p=0.95,
|
| 243 |
+
temperature=1.0,
|
| 244 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 245 |
+
eos_token_id=tokenizer.eos_token_id
|
| 246 |
+
)
|
| 247 |
+
batch_selfies = [
|
| 248 |
+
tokenizer.decode(seq, skip_special_tokens=True)
|
| 249 |
+
for seq in gen_tokens
|
| 250 |
+
]
|
| 251 |
+
|
| 252 |
+
all_selfies_raw.extend(batch_selfies)
|
| 253 |
+
if len(all_selfies_raw) >= n_samples:
|
| 254 |
+
break
|
| 255 |
+
|
| 256 |
+
all_selfies_raw = all_selfies_raw[:n_samples]
|
| 257 |
+
print(f"\n✅ Generated {len(all_selfies_raw)} raw SELFIES strings.\n")
|
| 258 |
+
|
| 259 |
+
# Process: SELFIES → clean SELFIES → SMILES → valid molecules
|
| 260 |
+
valid_records = []
|
| 261 |
+
print("🧪 Processing SELFIES and converting to SMILES...")
|
| 262 |
+
for i, raw_selfies in enumerate(tqdm(all_selfies_raw, desc="Converting")):
|
| 263 |
+
# Clean the SELFIES (remove spaces as tokenizer uses whitespace)
|
| 264 |
+
clean_selfies = raw_selfies.replace(" ", "")
|
| 265 |
+
|
| 266 |
+
# Convert to SMILES
|
| 267 |
+
smiles = selfies_to_smiles(clean_selfies)
|
| 268 |
+
|
| 269 |
+
if smiles is not None and is_valid_smiles(smiles) and passes_durrant_lab_filter(smiles):
|
| 270 |
+
valid_records.append({
|
| 271 |
+
"raw_selfies": raw_selfies,
|
| 272 |
+
"selfies_clean": clean_selfies,
|
| 273 |
+
"selfies": clean_selfies, # canonical version
|
| 274 |
+
"smiles": smiles.strip()
|
| 275 |
+
})
|
| 276 |
+
|
| 277 |
+
# >>> DEBUG: Print multiple examples and SA label analysis <<<
|
| 278 |
+
if valid_records:
|
| 279 |
+
print("\n🔍 DEBUG: Sample generated molecules")
|
| 280 |
+
print("-" * 70)
|
| 281 |
+
for i in range(min(5, len(valid_records))):
|
| 282 |
+
example = valid_records[i]
|
| 283 |
+
print(f"Example {i+1}:")
|
| 284 |
+
print(f" Raw SELFIES : {example['raw_selfies'][:80]}{'...' if len(example['raw_selfies']) > 80 else ''}")
|
| 285 |
+
print(f" SMILES : {example['smiles']}")
|
| 286 |
+
|
| 287 |
+
# Get SA label and confidence
|
| 288 |
+
label, confidence = get_sa_label_and_confidence(example['raw_selfies'])
|
| 289 |
+
print(f" SA Label : {label} (confidence: {confidence:.3f})")
|
| 290 |
+
|
| 291 |
+
if i == 0:
|
| 292 |
+
# Test SA classifier with simple molecules
|
| 293 |
+
simple_label, simple_conf = get_sa_label_and_confidence('[C]')
|
| 294 |
+
benzene_label, benzene_conf = get_sa_label_and_confidence('[c] [c] [c] [c] [c] [c] [Ring1] [=Branch1]')
|
| 295 |
+
print(f" 🧪 SA Test - Simple molecule: {simple_label} ({simple_conf:.3f})")
|
| 296 |
+
print(f" 🧪 SA Test - Benzene: {benzene_label} ({benzene_conf:.3f})")
|
| 297 |
+
|
| 298 |
+
# Check molecule properties
|
| 299 |
+
mol = Chem.MolFromSmiles(example['smiles'])
|
| 300 |
+
if mol:
|
| 301 |
+
print(f" Atoms : {mol.GetNumAtoms()}")
|
| 302 |
+
print(f" Bonds : {mol.GetNumBonds()}")
|
| 303 |
+
print()
|
| 304 |
+
print("-" * 70)
|
| 305 |
+
|
| 306 |
+
# SA Label distribution analysis
|
| 307 |
+
sa_labels = []
|
| 308 |
+
for r in valid_records[:100]:
|
| 309 |
+
label, _ = get_sa_label_and_confidence(r["raw_selfies"])
|
| 310 |
+
sa_labels.append(label)
|
| 311 |
+
|
| 312 |
+
easy_count = sa_labels.count("Easy")
|
| 313 |
+
hard_count = sa_labels.count("Hard")
|
| 314 |
+
unknown_count = sa_labels.count("Unknown")
|
| 315 |
+
|
| 316 |
+
print(f"🔍 SA Label Analysis (first 100 molecules):")
|
| 317 |
+
print(f" Easy to synthesize: {easy_count}/100 ({easy_count}%)")
|
| 318 |
+
print(f" Hard to synthesize: {hard_count}/100 ({hard_count}%)")
|
| 319 |
+
if unknown_count > 0:
|
| 320 |
+
print(f" Unknown/Failed: {unknown_count}/100 ({unknown_count}%)")
|
| 321 |
+
else:
|
| 322 |
+
print("\n⚠️ WARNING: No valid molecules generated in sample!")
|
| 323 |
+
# <<< END DEBUG >>>
|
| 324 |
+
|
| 325 |
+
# Now compute metrics...
|
| 326 |
+
validity = len(valid_records) / n_samples
|
| 327 |
+
|
| 328 |
+
unique_valid = list({r["selfies_clean"]: r for r in valid_records}.values())
|
| 329 |
+
uniqueness = len(unique_valid) / len(valid_records) if valid_records else 0.0
|
| 330 |
+
|
| 331 |
+
novel_count = sum(1 for r in unique_valid if r["selfies_clean"] not in train_selfies_clean)
|
| 332 |
+
novelty = novel_count / len(unique_valid) if unique_valid else 0.0
|
| 333 |
+
|
| 334 |
+
# SA Label Counts (using model's SA classifier)
|
| 335 |
+
sa_labels_all = []
|
| 336 |
+
for r in unique_valid:
|
| 337 |
+
label, _ = get_sa_label_and_confidence(r["raw_selfies"])
|
| 338 |
+
sa_labels_all.append(label)
|
| 339 |
+
|
| 340 |
+
easy_total = sa_labels_all.count("Easy")
|
| 341 |
+
hard_total = sa_labels_all.count("Hard")
|
| 342 |
+
unknown_total = sa_labels_all.count("Unknown")
|
| 343 |
+
total_labeled = len(sa_labels_all)
|
| 344 |
+
|
| 345 |
+
# Internal Diversity (on SMILES)
|
| 346 |
+
if len(unique_valid) >= 2:
|
| 347 |
+
fps = []
|
| 348 |
+
for r in unique_valid:
|
| 349 |
+
fp = get_morgan_fingerprint_from_smiles(r["smiles"])
|
| 350 |
+
if fp is not None:
|
| 351 |
+
fps.append(fp)
|
| 352 |
+
if len(fps) >= 2:
|
| 353 |
+
total_sim, count = 0.0, 0
|
| 354 |
+
for i in range(len(fps)):
|
| 355 |
+
for j in range(i + 1, len(fps)):
|
| 356 |
+
total_sim += tanimoto_sim(fps[i], fps[j])
|
| 357 |
+
count += 1
|
| 358 |
+
internal_diversity = 1.0 - (total_sim / count)
|
| 359 |
+
else:
|
| 360 |
+
internal_diversity = 0.0
|
| 361 |
+
else:
|
| 362 |
+
internal_diversity = 0.0
|
| 363 |
+
|
| 364 |
+
# ----------------------------
|
| 365 |
+
# Final Summary
|
| 366 |
+
# ----------------------------
|
| 367 |
+
print("\n" + "="*55)
|
| 368 |
+
print("📊 MOLECULAR GENERATION EVALUATION SUMMARY")
|
| 369 |
+
print("="*55)
|
| 370 |
+
print(f"Model Path : {model_path}")
|
| 371 |
+
print(f"Generation Mode : {'MTP-aware' if hasattr(model, 'generate_with_logprobs') else 'Standard'}")
|
| 372 |
+
print(f"Samples Generated: {n_samples}")
|
| 373 |
+
print("-"*55)
|
| 374 |
+
print(f"Validity : {validity:.4f} ({len(valid_records)}/{n_samples})")
|
| 375 |
+
print(f"Uniqueness : {uniqueness:.4f} (unique valid)")
|
| 376 |
+
print(f"Novelty (vs train): {novelty:.4f} (space-free SELFIES)")
|
| 377 |
+
print(f"Synthesis Labels : Easy: {easy_total}/{total_labeled} ({easy_total/max(1,total_labeled)*100:.1f}%) | Hard: {hard_total}/{total_labeled} ({hard_total/max(1,total_labeled)*100:.1f}%)")
|
| 378 |
+
if unknown_total > 0:
|
| 379 |
+
print(f" Unknown: {unknown_total}/{total_labeled} ({unknown_total/max(1,total_labeled)*100:.1f}%)")
|
| 380 |
+
print(f"Internal Diversity: {internal_diversity:.4f} (1 - avg Tanimoto)")
|
| 381 |
+
print("="*55)
|
| 382 |
+
|
| 383 |
+
results = {
|
| 384 |
+
"model_path": model_path,
|
| 385 |
+
"generation_mode": "MTP-aware" if hasattr(model, 'generate_with_logprobs') else "standard",
|
| 386 |
+
"n_samples": n_samples,
|
| 387 |
+
"validity": validity,
|
| 388 |
+
"uniqueness": uniqueness,
|
| 389 |
+
"novelty": novelty,
|
| 390 |
+
"sa_easy_count": easy_total,
|
| 391 |
+
"sa_hard_count": hard_total,
|
| 392 |
+
"sa_easy_percentage": easy_total/max(1,total_labeled)*100,
|
| 393 |
+
"sa_hard_percentage": hard_total/max(1,total_labeled)*100,
|
| 394 |
+
"internal_diversity": internal_diversity,
|
| 395 |
+
"valid_molecules_count": len(valid_records)
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
if unknown_total > 0:
|
| 399 |
+
results["sa_unknown_count"] = unknown_total
|
| 400 |
+
results["sa_unknown_percentage"] = unknown_total/max(1,total_labeled)*100
|
| 401 |
+
|
| 402 |
+
output_json = os.path.join(model_path, "evaluation_summary.json")
|
| 403 |
+
with open(output_json, "w") as f:
|
| 404 |
+
json.dump(results, f, indent=2)
|
| 405 |
+
print(f"\n💾 Results saved to: {output_json}")
|
| 406 |
+
|
| 407 |
+
return results
|
| 408 |
+
|
| 409 |
+
# ----------------------------
|
| 410 |
+
# CLI
|
| 411 |
+
# ----------------------------
|
| 412 |
+
|
| 413 |
+
if __name__ == "__main__":
|
| 414 |
+
parser = argparse.ArgumentParser(description="Evaluate molecular generative model with MTP-aware generation")
|
| 415 |
+
parser.add_argument("--model_path", type=str, required=True, help="Path to model checkpoint")
|
| 416 |
+
parser.add_argument("--n_samples", type=int, default=1000, help="Number of molecules to generate")
|
| 417 |
+
parser.add_argument("--seed", type=int, default=42, help="Random seed")
|
| 418 |
+
parser.add_argument("--train_data", type=str, default="../data/chunk_5.csv", help="Training data CSV")
|
| 419 |
+
|
| 420 |
+
args = parser.parse_args()
|
| 421 |
+
evaluate_model(
|
| 422 |
+
model_path=args.model_path,
|
| 423 |
+
train_data_path=args.train_data,
|
| 424 |
+
n_samples=args.n_samples,
|
| 425 |
+
seed=args.seed
|
| 426 |
)
|