Spaces:
Sleeping
Sleeping
Update core/evolution/evolution.py
Browse files- core/evolution/evolution.py +238 -233
core/evolution/evolution.py
CHANGED
|
@@ -1,234 +1,239 @@
|
|
| 1 |
-
from .population import Population
|
| 2 |
-
from .molecule import Molecule
|
| 3 |
-
from core.predictors.pure_component.property_predictor import PropertyPredictor
|
| 4 |
-
from core.config import EvolutionConfig
|
| 5 |
-
from crem.crem import mutate_mol
|
| 6 |
-
from rdkit import Chem
|
| 7 |
-
import pandas as pd
|
| 8 |
-
import numpy as np
|
| 9 |
-
import random
|
| 10 |
-
from typing import List, Tuple
|
| 11 |
-
from core.data_prep import df # Initial dataset for sampling
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
|
| 14 |
-
class MolecularEvolution:
|
| 15 |
-
"""Main evolutionary algorithm coordinator."""
|
| 16 |
-
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
| 17 |
-
REP_DB_PATH = BASE_DIR / "data" / "fragments" / "diesel_fragments.db"
|
| 18 |
-
|
| 19 |
-
def __init__(self, config: EvolutionConfig):
|
| 20 |
-
self.config = config
|
| 21 |
-
self.predictor = PropertyPredictor(config)
|
| 22 |
-
self.population = Population(config)
|
| 23 |
-
|
| 24 |
-
def _mutate_molecule(self, mol: Chem.Mol) -> List[str]:
|
| 25 |
-
"""Generate mutations for a molecule using CREM."""
|
| 26 |
-
try:
|
| 27 |
-
mutants = list(mutate_mol(
|
| 28 |
-
mol,
|
| 29 |
-
db_name=str(self.REP_DB_PATH),
|
| 30 |
-
max_size=2,
|
| 31 |
-
return_mol=False
|
| 32 |
-
))
|
| 33 |
-
return [m for m in mutants if m and m not in self.population.seen_smiles]
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
return []
|
| 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 |
-
|
| 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 |
-
|
| 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 |
return self._generate_results()
|
|
|
|
| 1 |
+
from .population import Population
|
| 2 |
+
from .molecule import Molecule
|
| 3 |
+
from core.predictors.pure_component.property_predictor import PropertyPredictor
|
| 4 |
+
from core.config import EvolutionConfig
|
| 5 |
+
from crem.crem import mutate_mol
|
| 6 |
+
from rdkit import Chem
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import numpy as np
|
| 9 |
+
import random
|
| 10 |
+
from typing import List, Tuple
|
| 11 |
+
from core.data_prep import df # Initial dataset for sampling
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
class MolecularEvolution:
|
| 15 |
+
"""Main evolutionary algorithm coordinator."""
|
| 16 |
+
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
| 17 |
+
REP_DB_PATH = BASE_DIR / "data" / "fragments" / "diesel_fragments.db"
|
| 18 |
+
|
| 19 |
+
def __init__(self, config: EvolutionConfig):
|
| 20 |
+
self.config = config
|
| 21 |
+
self.predictor = PropertyPredictor(config)
|
| 22 |
+
self.population = Population(config)
|
| 23 |
+
|
| 24 |
+
def _mutate_molecule(self, mol: Chem.Mol) -> List[str]:
|
| 25 |
+
"""Generate mutations for a molecule using CREM."""
|
| 26 |
+
try:
|
| 27 |
+
mutants = list(mutate_mol(
|
| 28 |
+
mol,
|
| 29 |
+
db_name=str(self.REP_DB_PATH),
|
| 30 |
+
max_size=2,
|
| 31 |
+
return_mol=False
|
| 32 |
+
))
|
| 33 |
+
return [m for m in mutants if m and m not in self.population.seen_smiles]
|
| 34 |
+
|
| 35 |
+
except SystemExit:
|
| 36 |
+
# CREM can call sys.exit(1) internally; this prevents Gunicorn worker crash
|
| 37 |
+
return []
|
| 38 |
+
|
| 39 |
+
except Exception:
|
| 40 |
+
return []
|
| 41 |
+
|
| 42 |
+
def _create_molecules(self, smiles_list: List[str]) -> List[Molecule]:
|
| 43 |
+
"""Create Molecule objects from SMILES with predictions (OPTIMIZED)."""
|
| 44 |
+
if not smiles_list:
|
| 45 |
+
return []
|
| 46 |
+
|
| 47 |
+
# OPTIMIZATION: Single featurization + all predictions
|
| 48 |
+
predictions = self.predictor.predict_all_properties(smiles_list)
|
| 49 |
+
|
| 50 |
+
molecules = []
|
| 51 |
+
for i, smiles in enumerate(smiles_list):
|
| 52 |
+
# Extract predictions for this molecule
|
| 53 |
+
props = {k: v[i] for k, v in predictions.items()}
|
| 54 |
+
|
| 55 |
+
# Validate required properties
|
| 56 |
+
if props.get('cn') is None:
|
| 57 |
+
continue
|
| 58 |
+
if self.config.minimize_ysi and props.get('ysi') is None:
|
| 59 |
+
continue
|
| 60 |
+
|
| 61 |
+
# Validate filtered properties
|
| 62 |
+
if not all(self.predictor.is_valid(k, props.get(k)) for k in ['bp', 'density', 'lhv', 'dynamic_viscosity']):
|
| 63 |
+
continue
|
| 64 |
+
|
| 65 |
+
molecules.append(Molecule(
|
| 66 |
+
smiles=smiles,
|
| 67 |
+
cn=props['cn'],
|
| 68 |
+
cn_error=abs(props['cn'] - self.config.target_cn),
|
| 69 |
+
cn_score=props['cn'], # For maximize mode
|
| 70 |
+
bp=props.get('bp'),
|
| 71 |
+
ysi=props.get('ysi'),
|
| 72 |
+
density=props.get('density'),
|
| 73 |
+
lhv=props.get('lhv'),
|
| 74 |
+
dynamic_viscosity=props.get('dynamic_viscosity')
|
| 75 |
+
))
|
| 76 |
+
|
| 77 |
+
return molecules
|
| 78 |
+
|
| 79 |
+
def initialize_population(self, initial_smiles: List[str]) -> int:
|
| 80 |
+
"""Initialize the population from initial SMILES."""
|
| 81 |
+
print("Predicting properties for initial population...")
|
| 82 |
+
molecules = self._create_molecules(initial_smiles)
|
| 83 |
+
return self.population.add_molecules(molecules)
|
| 84 |
+
|
| 85 |
+
def _log_generation_stats(self, generation: int):
|
| 86 |
+
"""Log statistics for the current generation."""
|
| 87 |
+
mols = self.population.molecules
|
| 88 |
+
|
| 89 |
+
if self.config.maximize_cn:
|
| 90 |
+
best_cn = max(mols, key=lambda m: m.cn)
|
| 91 |
+
avg_cn = np.mean([m.cn for m in mols])
|
| 92 |
+
|
| 93 |
+
print_msg = (f"Gen {generation}/{self.config.generations} | "
|
| 94 |
+
f"Pop {len(mols)} | "
|
| 95 |
+
f"Best CN: {best_cn.cn:.3f} | "
|
| 96 |
+
f"Avg CN: {avg_cn:.3f}")
|
| 97 |
+
else:
|
| 98 |
+
best_cn = min(mols, key=lambda m: m.cn_error)
|
| 99 |
+
avg_cn_err = np.mean([m.cn_error for m in mols])
|
| 100 |
+
|
| 101 |
+
print_msg = (f"Gen {generation}/{self.config.generations} | "
|
| 102 |
+
f"Pop {len(mols)} | "
|
| 103 |
+
f"Best CN err: {best_cn.cn_error:.3f} | "
|
| 104 |
+
f"Avg CN err: {avg_cn_err:.3f}")
|
| 105 |
+
|
| 106 |
+
if self.config.minimize_ysi:
|
| 107 |
+
front = self.population.pareto_front()
|
| 108 |
+
best_ysi = min(mols, key=lambda m: m.ysi)
|
| 109 |
+
avg_ysi = np.mean([m.ysi for m in mols])
|
| 110 |
+
|
| 111 |
+
print_msg += (f" | Best YSI: {best_ysi.ysi:.3f} | "
|
| 112 |
+
f"Avg YSI: {avg_ysi:.3f} | "
|
| 113 |
+
f"Pareto: {len(front)}")
|
| 114 |
+
|
| 115 |
+
print(print_msg)
|
| 116 |
+
|
| 117 |
+
def _generate_offspring(self, survivors: List[Molecule]) -> List[Molecule]:
|
| 118 |
+
"""Generates offspring from survivors."""
|
| 119 |
+
target_count = self.config.population_size - len(survivors)
|
| 120 |
+
max_attempts = target_count * self.config.max_offspring_attempts
|
| 121 |
+
|
| 122 |
+
all_children = []
|
| 123 |
+
new_molecules = []
|
| 124 |
+
|
| 125 |
+
print(f" → Generating offspring (target: {target_count})...")
|
| 126 |
+
|
| 127 |
+
for attempt in range(max_attempts):
|
| 128 |
+
if len(new_molecules) >= target_count:
|
| 129 |
+
break
|
| 130 |
+
|
| 131 |
+
# Generate mutations
|
| 132 |
+
parent = random.choice(survivors)
|
| 133 |
+
mol = Chem.MolFromSmiles(parent.smiles)
|
| 134 |
+
if mol is None:
|
| 135 |
+
continue
|
| 136 |
+
|
| 137 |
+
children = self._mutate_molecule(mol)
|
| 138 |
+
all_children.extend(children[:self.config.mutations_per_parent])
|
| 139 |
+
|
| 140 |
+
# Process in larger batches (single featurization per batch)
|
| 141 |
+
if len(all_children) >= self.config.batch_size:
|
| 142 |
+
print(f" → Evaluating batch of {len(all_children)} (featurizing once)...")
|
| 143 |
+
new_molecules.extend(self._create_molecules(all_children))
|
| 144 |
+
all_children = []
|
| 145 |
+
|
| 146 |
+
# Process remaining children
|
| 147 |
+
if all_children:
|
| 148 |
+
print(f" → Evaluating final batch of {len(all_children)}...")
|
| 149 |
+
new_molecules.extend(self._create_molecules(all_children))
|
| 150 |
+
|
| 151 |
+
print(f" ✓ Generated {len(new_molecules)} valid offspring")
|
| 152 |
+
return new_molecules
|
| 153 |
+
|
| 154 |
+
def _run_evolution_loop(self):
|
| 155 |
+
"""Run the main evolution loop."""
|
| 156 |
+
for gen in range(1, self.config.generations + 1):
|
| 157 |
+
self._log_generation_stats(gen)
|
| 158 |
+
|
| 159 |
+
survivors = self.population.get_survivors()
|
| 160 |
+
offspring = self._generate_offspring(survivors)
|
| 161 |
+
|
| 162 |
+
# Create new population
|
| 163 |
+
new_pop = Population(self.config)
|
| 164 |
+
new_pop.add_molecules(survivors + offspring)
|
| 165 |
+
self.population = new_pop
|
| 166 |
+
|
| 167 |
+
def _generate_results(self) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
| 168 |
+
"""Generate final results DataFrames."""
|
| 169 |
+
final_df = self.population.to_dataframe()
|
| 170 |
+
|
| 171 |
+
# Apply different filtering based on mode
|
| 172 |
+
if self.config.maximize_cn:
|
| 173 |
+
if self.config.minimize_ysi and "ysi" in final_df.columns:
|
| 174 |
+
# Maximize CN + minimize YSI: keep high CN, low YSI
|
| 175 |
+
final_df = final_df[
|
| 176 |
+
(final_df["cn"] > 50) &
|
| 177 |
+
(final_df["ysi"] < 50)
|
| 178 |
+
].sort_values(["cn", "ysi"], ascending=[False, True])
|
| 179 |
+
else:
|
| 180 |
+
# Maximize CN only: just keep high CN
|
| 181 |
+
final_df = final_df[final_df["cn"] > 50].sort_values("cn", ascending=False)
|
| 182 |
+
else:
|
| 183 |
+
if self.config.minimize_ysi and "ysi" in final_df.columns:
|
| 184 |
+
# Target CN + minimize YSI: keep low error, low YSI
|
| 185 |
+
final_df = final_df[
|
| 186 |
+
(final_df["cn_error"] < 5) &
|
| 187 |
+
(final_df["ysi"] < 50)
|
| 188 |
+
].sort_values(["cn_error", "ysi"], ascending=True)
|
| 189 |
+
else:
|
| 190 |
+
# Target CN only: just keep low error
|
| 191 |
+
final_df = final_df[final_df["cn_error"] < 5].sort_values("cn_error", ascending=True)
|
| 192 |
+
|
| 193 |
+
# Overwrite rank safely
|
| 194 |
+
final_df["rank"] = range(1, len(final_df) + 1)
|
| 195 |
+
|
| 196 |
+
if self.config.minimize_ysi:
|
| 197 |
+
pareto_mols = self.population.pareto_front()
|
| 198 |
+
pareto_df = pd.DataFrame([m.to_dict() for m in pareto_mols])
|
| 199 |
+
|
| 200 |
+
if not pareto_df.empty:
|
| 201 |
+
if self.config.maximize_cn:
|
| 202 |
+
pareto_df = pareto_df[
|
| 203 |
+
(pareto_df['cn'] > 50) & (pareto_df['ysi'] < 50)
|
| 204 |
+
].sort_values(["cn", "ysi"], ascending=[False, True])
|
| 205 |
+
else:
|
| 206 |
+
pareto_df = pareto_df[
|
| 207 |
+
(pareto_df['cn_error'] < 5) & (pareto_df['ysi'] < 50)
|
| 208 |
+
].sort_values(["cn_error", "ysi"], ascending=True)
|
| 209 |
+
|
| 210 |
+
pareto_df.insert(0, 'rank', range(1, len(pareto_df) + 1))
|
| 211 |
+
else:
|
| 212 |
+
pareto_df = pd.DataFrame()
|
| 213 |
+
|
| 214 |
+
return final_df, pareto_df
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def evolve(self) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
| 218 |
+
"""Run the evolutionary algorithm."""
|
| 219 |
+
# Initialize
|
| 220 |
+
df_bins = pd.qcut(df["cn"], q=30)
|
| 221 |
+
initial_smiles = (
|
| 222 |
+
df.groupby(df_bins, observed=False)
|
| 223 |
+
.apply(lambda x: x.sample(20, random_state=42))
|
| 224 |
+
.reset_index(drop=True)["SMILES"]
|
| 225 |
+
.tolist()
|
| 226 |
+
)
|
| 227 |
+
init_count = self.initialize_population(initial_smiles)
|
| 228 |
+
|
| 229 |
+
if init_count == 0:
|
| 230 |
+
print("No valid initial molecules")
|
| 231 |
+
return pd.DataFrame(), pd.DataFrame()
|
| 232 |
+
|
| 233 |
+
print(f"✓ Initial population size: {init_count}\n")
|
| 234 |
+
|
| 235 |
+
# Evolution
|
| 236 |
+
self._run_evolution_loop()
|
| 237 |
+
|
| 238 |
+
# Results
|
| 239 |
return self._generate_results()
|