Spaces:
Sleeping

Mehmet Ali Yücel
fresh upload with LFS tracking
b1dd307
Raw History Blame Contribute Delete
25.4 kB
"""
des_engine.py
-------------
Fitting, scoring, and analysis pipeline for target-family desirability engines.
Logical sections:
1. Preprocessing utilities
2. Engine training (fit_families)
3. Visualisation helpers (KDE, histogram, desirability-curve)
4. Evaluation / discrimination analysis
5. Enrichment analysis
6. Main entry point
"""
#%%
# ---------------------------------------------------------------------------
# Imports – grouped: stdlib → third-party → local
# ---------------------------------------------------------------------------
import logging
import os
import pickle
import sys
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.metrics import cohen_kappa_score, roc_auc_score
sys.path.append(str(Path(__file__).resolve().parent.parent))
from desirability_functions import DesirabilityFunctions
from optimizer import DesirabilityOptimizer
from config import TARGET_FAMILIES as ALL_FAMILIES, MIN_FEATURES
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)
#%%
def fit_families(
df: pd.DataFrame,
features: List[str],
reference_subset: str,
target_col: str = "label",
r2_threshold: float = 0.60,
weight_step: float = 0.25,
weight_objective: str = "entropy",
) -> Tuple[pd.DataFrame, Dict, pd.DataFrame, pd.DataFrame]:
"""
Fit desirability engines on a reference family; score all families.
Steps:
1. Fit distributions on the reference family.
2. Build four engines (best, best_and_good, ADS, Gaussian).
3. Optimise weights for the 'best_and_good' engine.
4. Score every family with all engines and collect per-property components.
Args:
df: Full dataset with a ``target_col`` label column.
features: Feature columns to use.
reference_subset: Label of the family to train on.
target_col: Column name that stores the family label.
r2_threshold: Minimum R² for 'best_and_good' engine.
weight_step: Grid step for weight optimisation.
weight_objective: ``"entropy"`` (unsupervised Shannon entropy on the
reference family) or ``"cohens_d"`` (supervised — maximises the
Cohen's d between the reference family's scores and the rest).
Returns:
summary_df – mean scores per family × engine strategy.
engine_dict – {strategy_name: DesirabilityFunctions}.
report – raw R² fitting report.
components_df – per-property component scores for all families/engines.
"""
logger.info(f"Fitting optimizer on reference subset: '{reference_subset}'")
ref_data = df[df[target_col] == reference_subset][features]
opt = DesirabilityOptimizer()
report = opt.fit_evaluate_all(ref_data, properties=features)
engines: Dict[str, DesirabilityFunctions] = {
"BestFit": opt.create_desirability_function(report, "best"),
"Best_and_good": opt.create_desirability_function(
report, "best_and_good", r2_threshold=r2_threshold
),
"ADS": opt.create_desirability_function(report, "ADS"),
"Gaussian": opt.create_desirability_function(report, "Gaussian"),
}
primary = engines["Best_and_good"]
if weight_objective == "cohens_d":
logger.info("Optimising weights via Cohen's d (supervised) …")
other_data = df[df[target_col] != reference_subset][features]
optimal_weights = DesirabilityFunctions.optimize_weights_cohens_d(
primary, ref_data, other_data, step=weight_step
)
elif weight_objective == "entropy":
logger.info("Optimising weights via Shannon entropy (unsupervised) …")
optimal_weights = DesirabilityFunctions.optimize_weights_shannon_entropy(
primary, ref_data, bins="auto", step=weight_step
)
else:
raise ValueError(
f"Unknown weight_objective={weight_objective!r}; "
"expected 'entropy' or 'cohens_d'."
)
logger.info(f"Optimal weights: {optimal_weights}")
primary.set_weights(optimal_weights)
# Score all families
results, component_parts = [], []
for label in df[target_col].unique():
subset = df[df[target_col] == label]
if subset.empty:
continue
row: Dict = {"Label": label}
for name, engine in engines.items():
scores = engine.predict_dataframe(subset[features])
row[f"Mean_Score_{name}"] = scores.mean()
comps = engine.predict_components(subset[features])
comps["Family"] = label
comps["Engine"] = name
component_parts.append(comps)
results.append(row)
summary_df = pd.DataFrame(results)
components_df = pd.concat(component_parts, ignore_index=True)
return summary_df, engines, report, components_df
# ---------------------------------------------------------------------------
# 3. Visualisation helpers
# ---------------------------------------------------------------------------
def _load_engine(engine_path: Union[str, Path]) -> Optional[Dict]:
"""Load a pickled engine dict, returning None on failure."""
try:
with open(engine_path, "rb") as fh:
return pickle.load(fh)
except Exception as exc:
logger.error(f"Could not load engine from {engine_path}: {exc}")
return None
def _setup_figure(figsize=(10, 6)) -> None:
plt.figure(figsize=figsize)
sns.set_style("white")
def _maybe_save(save_path: Optional[str]) -> None:
if save_path:
os.makedirs(Path(save_path).parent, exist_ok=True)
plt.savefig(save_path, dpi=300, bbox_inches="tight")
def plot_score_comparison(
df: pd.DataFrame,
engine_path: Union[str, Path],
feature_cols: List[str],
family: str,
other: str,
kind: str = "kde",
engine_key: str = "Best_and_good",
save_path: Optional[str] = None,
) -> None:
"""
Overlay score distributions for two families.
Args:
df: Full dataset.
engine_path: Path to pickled engine dict.
feature_cols: Feature columns to pass to the engine.
family: Primary (reference) family label.
other: Comparison family label.
kind: 'kde' or 'hist'.
engine_key: Which engine strategy to use (default 'Best_and_good').
save_path: If set, save the figure here.
"""
engines = _load_engine(engine_path)
if engines is None:
return
engine = engines[engine_key]
family_scores = engine.predict_dataframe(
df[df["label"] == family][feature_cols]
)
other_scores = engine.predict_dataframe(
df[df["label"] == other][feature_cols]
)
_setup_figure()
plot_fn = sns.kdeplot if kind == "kde" else sns.histplot
kw = dict(fill=True, alpha=0.5) if kind == "kde" else dict(kde=True, element="step", alpha=0.5)
plot_fn(family_scores, label=family.capitalize(), color="blue", **kw)
plot_fn(other_scores, label=other.capitalize(), color="orange", **kw)
plt.title(f"Custom {family.capitalize()} QED Score", fontsize=20)
plt.xlabel(f"{family.capitalize()} QED Score", fontsize=16)
plt.ylabel("Density" if kind == "kde" else "Count", fontsize=16)
plt.legend()
_maybe_save(save_path)
plt.show()
def plot_property_desirability(
data: pd.DataFrame,
family: str,
feature: str,
all_features: List[str],
base_path: Union[str, Path] = "des_results/extra",
) -> None:
"""
Dual-axis plot: molecule frequency histogram (left) + desirability curve (right).
"""
base_path = Path(base_path)
engine_path = base_path / f"engines_for_extra{family}.pkl"
report_path = base_path / f"report_for_extra{family}.csv"
engines = _load_engine(engine_path)
if engines is None:
return
engine = engines["Best_and_good"]
# Read R² from the report CSV
r2_text = "N/A"
try:
report = pd.read_csv(report_path, header=None)
row = report[report[0] == feature]
if not row.empty:
r2_text = f"{float(row.iloc[0, 2]):.2f}"
except Exception as exc:
logger.warning(f"Could not read R² for {feature}: {exc}")
# Validate data
if feature not in data.columns:
logger.warning(f"Skipping {feature}: not in dataset columns.")
return
subset = data[data["label"] == family]
if subset.empty:
logger.warning(f"Skipping {family}: no data found.")
return
# Build desirability curve
lo, hi = subset[feature].min(), subset[feature].max()
pad = (hi - lo) * 0.1
x_line = np.linspace(lo - pad, hi + pad, 300)
dummy = pd.DataFrame(0, index=range(300), columns=all_features)
dummy[feature] = x_line
comps = engine.predict_components(dummy)
score_col = f"{feature}_Score"
if score_col not in comps.columns:
logger.warning(f"Skipping {feature} for {family}: {score_col} not in engine output.")
return
y_line = comps[score_col]
# Plot
fig, ax1 = plt.subplots(figsize=(8, 6))
sns.histplot(subset[feature], bins=30, color="#4A90E2", alpha=0.5,
ax=ax1, edgecolor="white")
ax1.set_xlabel(feature, fontsize=12, fontweight="bold")
ax1.set_ylabel("Frequency (Molecule Count)", color="#2C3E50",
fontsize=12, fontweight="bold")
ax1.tick_params(axis="y", labelcolor="#2C3E50")
ax2 = ax1.twinx()
ax2.plot(x_line, y_line, color="#E74C3C", linewidth=3,
label="Desirability Curve")
ax2.set_ylabel("Desirability Score", color="#E74C3C",
fontsize=12, fontweight="bold")
ax2.set_ylim(-0.05, 1.05)
ax2.tick_params(axis="y", labelcolor="#E74C3C")
plt.title(
f"{family.upper()} Family: {feature}\n"
f"Distribution vs. Desirability ($R^2$ = {r2_text})",
fontsize=14,
)
ax1.grid(axis="y", linestyle="--", alpha=0.3)
save_dir = base_path / "curves"
save_dir.mkdir(parents=True, exist_ok=True)
plt.savefig(save_dir / f"{family}_{feature}_curve.svg",
dpi=300, bbox_inches="tight")
plt.close()
logger.info(f"Saved: {family} – {feature}")
# ---------------------------------------------------------------------------
# 4. Discrimination analysis
# ---------------------------------------------------------------------------
def _best_kappa(y_true: np.ndarray, y_scores: np.ndarray,
n_thresholds: int = 100) -> float:
"""Cohen's Kappa maximised over a grid of thresholds."""
thresholds = np.linspace(y_scores.min(), y_scores.max(), n_thresholds)
return max(
cohen_kappa_score(y_true, (y_scores >= t).astype(int))
for t in thresholds
)
def _cohens_d(group1: np.ndarray, group2: np.ndarray) -> float:
"""Effect size: (mean1 − mean2) / pooled SD."""
n1, n2 = len(group1), len(group2)
if n1 < 2 or n2 < 2:
return 0.0
pooled_sd = np.sqrt(
((n1 - 1) * np.var(group1, ddof=1) + (n2 - 1) * np.var(group2, ddof=1))
/ (n1 + n2 - 2)
)
return float((np.mean(group1) - np.mean(group2)) / pooled_sd)
def analyze_family_discrimination(
target_family: str,
data: pd.DataFrame,
feature_cols: List[str],
base_path: Union[str, Path] = "des_results/classy/",
engine_key: str = "Best_and_good",
) -> Optional[pd.DataFrame]:
"""
AUC + best-kappa comparison (custom desirability vs. QED) for one family.
Returns a metrics DataFrame.
"""
logger.info(f"Discrimination analysis: {target_family.upper()}")
base_path = Path(base_path)
engines = _load_engine(base_path / f"engines_for_extra{target_family}.pkl")
if engines is None:
return None
df = data.copy()
df["binary_true"] = (df["label"] == target_family).astype(int)
qed_scores = df["qed"].values
des_scores = engines[engine_key].predict_dataframe(df[feature_cols]).values
y_true = df["binary_true"].values
auc_qed = roc_auc_score(y_true, qed_scores)
auc_des = roc_auc_score(y_true, des_scores)
kappa_qed = _best_kappa(y_true, qed_scores)
kappa_des = _best_kappa(y_true, des_scores)
logger.info(
f" QED → AUC={auc_qed:.3f}, Max-Kappa={kappa_qed:.3f}\n"
f" Des → AUC={auc_des:.3f}, Max-Kappa={kappa_des:.3f}"
)
# Visualisation
target_mask = df["label"] == target_family
other_mask = ~target_mask
fig, axes = plt.subplots(1, 3, figsize=(24, 6))
sns.histplot(df.loc[target_mask, "qed"], label=target_family.title(),
color="blue", kde=True, ax=axes[0], alpha=0.3)
sns.histplot(df.loc[other_mask, "qed"], label="Others",
color="orange", kde=True, ax=axes[0], alpha=0.3)
axes[0].set_title(f"Baseline QED\n(AUC={auc_qed:.2f})")
axes[0].legend()
sns.histplot(des_scores[target_mask], label=target_family.title(),
color="green", kde=True, ax=axes[1], alpha=0.3)
sns.histplot(des_scores[other_mask], label="Others",
color="red", kde=True, ax=axes[1], alpha=0.3)
axes[1].set_title(f"{target_family.title()} Desirability\n(AUC={auc_des:.2f})")
axes[1].legend()
metrics_df = pd.DataFrame({
"Metric": ["Cohen's Kappa", "Cohen's Kappa", "ROC AUC", "ROC AUC"],
"Score Type": ["QED", "Desirability", "QED", "Desirability"],
"Value": [kappa_qed, kappa_des, auc_qed, auc_des],
})
sns.barplot(data=metrics_df, x="Metric", y="Value",
hue="Score Type", ax=axes[2], palette=["gray", "green"])
axes[2].set_title(f"Discriminatory Power\n({target_family.title()} vs Others)")
axes[2].set_ylim(0, 1.05)
for container in axes[2].containers:
axes[2].bar_label(container, fmt="%.2f")
plt.tight_layout()
save_dir = base_path / "figures"
save_dir.mkdir(parents=True, exist_ok=True)
plt.savefig(save_dir / f"{target_family}_metrics_comparison.svg",
dpi=300, bbox_inches="tight")
plt.show()
return metrics_df
def analyze_pairwise_confusion(
target_family: str,
data: pd.DataFrame,
feature_cols: List[str],
base_path: Union[str, Path] = "des_results/classy/",
engine_key: str = "Best_and_good",
min_family_size: int = 5,
) -> Optional[pd.DataFrame]:
"""
One-vs-one ROC-AUC and Cohen's d comparison for the target family against
every other family. Returns a long-format results DataFrame.
"""
logger.info(f"Pairwise confusion analysis: {target_family.upper()}")
base_path = Path(base_path)
engines = _load_engine(base_path / f"engines_for_extra{target_family}.pkl")
if engines is None:
return None
target_subset = data[data["label"] == target_family]
target_qed = target_subset["qed"].values
target_des = engines[engine_key].predict_dataframe(
target_subset[feature_cols]
).values
results = []
for challenger in data["label"].unique():
if challenger == target_family:
continue
chall_data = data[data["label"] == challenger]
if len(chall_data) < min_family_size:
continue
chall_qed = chall_data["qed"].values
chall_des = engines[engine_key].predict_dataframe(
chall_data[feature_cols]
).values
y_true = np.concatenate([np.ones(len(target_des)),
np.zeros(len(chall_des))])
auc_qed = roc_auc_score(y_true, np.concatenate([target_qed, chall_qed]))
auc_des = roc_auc_score(y_true, np.concatenate([target_des, chall_des]))
d_qed = _cohens_d(target_qed, chall_qed)
d_des = _cohens_d(target_des, chall_des)
for metric, qv, dv in [("ROC AUC", auc_qed, auc_des),
("Cohen's d", d_qed, d_des)]:
results.append({
"Challenger": challenger,
"Metric": metric,
"QED": qv,
"Desirability": dv,
"Improvement": dv - qv,
})
res_df = pd.DataFrame(results)
# Visualise Cohen's d
d_data = res_df[res_df["Metric"] == "Cohen's d"].melt(
id_vars=["Challenger"],
value_vars=["QED", "Desirability"],
var_name="Score Type",
value_name="Cohen's d",
)
plt.figure(figsize=(12, 6))
sns.set_style("white")
sns.barplot(data=d_data, x="Challenger", y="Cohen's d",
hue="Score Type", palette=["red", "green"])
plt.title(f"Distinguishing Ability: {target_family.capitalize()} vs Others",
fontsize=20)
plt.ylabel("Effect Size – Cohen's d")
plt.xticks(rotation=30, ha="right")
plt.legend()
plt.tight_layout()
save_dir = base_path / "figures"
save_dir.mkdir(parents=True, exist_ok=True)
plt.savefig(save_dir / f"{target_family}_cohens.svg",
dpi=300, bbox_inches="tight")
plt.show()
return res_df
def plot_all_families_boxplot(
df: pd.DataFrame,
engine_path: Union[str, Path],
feature_cols: List[str],
reference_family: str,
engine_key: str = "Best_and_good",
save_path: Optional[str] = None,
) -> None:
"""
Boxplot showing the distribution of scores for ALL families
based on a single reference engine.
"""
engines = _load_engine(engine_path)
if engines is None:
return
engine = engines[engine_key]
# Calculate scores for the entire dataset
df_plot = df.copy()
df_plot["Custom_Score"] = engine.predict_dataframe(df[feature_cols])
plt.figure(figsize=(14, 6))
sns.set_style("whitegrid")
# Sort families by median score for better visualization
order = df_plot.groupby("label")["Custom_Score"].median().sort_values(ascending=False).index
sns.boxplot(
data=df_plot,
x="label",
y="Custom_Score",
order=order,
palette="viridis",
linewidth=1.5
)
plt.xticks(rotation=45, ha="right")
plt.title(f"Score Distribution Across Families\n(Engine Optimized for: {reference_family.upper()})", fontsize=16)
plt.xlabel("Target Family", fontsize=12)
plt.ylabel(f"Desirability Score ({engine_key})", fontsize=12)
plt.tight_layout()
_maybe_save(save_path)
plt.show()
# ---------------------------------------------------------------------------
# 5. Enrichment analysis
# ---------------------------------------------------------------------------
def enrichment_analysis(
target_fam: str,
data: pd.DataFrame,
feature_cols: List[str],
engine_path: Union[str, Path],
top_percentiles: List[float] = (0.01, 0.05, 0.10),
label_col: str = "label",
qed_col: str = "qed",
engine_key: str = "Best_and_good",
plot: bool = True,
save: bool = True,
) -> Optional[pd.DataFrame]:
"""
Enrichment of target family at various score percentile cut-offs.
Compares desirability-score enrichment vs. QED-score enrichment.
Returns a pivoted summary DataFrame.
"""
required = feature_cols + [label_col, qed_col]
missing = [c for c in required if c not in data.columns]
if missing:
logger.error(f"Missing columns: {missing}")
return None
engines = _load_engine(engine_path)
if engines is None:
return None
try:
des_scores = engines[engine_key].predict_dataframe(data[feature_cols])
except KeyError:
logger.error(f"Engine key '{engine_key}' not found in loaded engine.")
return None
qed_scores = data[qed_col]
overall_prop = (data[label_col] == target_fam).mean()
if overall_prop == 0:
logger.warning(f"Family '{target_fam}' not found in dataset.")
return None
records = []
for perc in top_percentiles:
q = 1.0 - perc
des_thresh = pd.Series(des_scores).quantile(q)
qed_thresh = qed_scores.quantile(q)
ef_des = (data.loc[des_scores >= des_thresh, label_col] == target_fam).mean() / overall_prop
ef_qed = (data.loc[qed_scores >= qed_thresh, label_col] == target_fam).mean() / overall_prop
tag = f"{perc * 100:g}%"
logger.info(f"Top {tag} → {target_fam} Des EF={ef_des:.2f}x | QED EF={ef_qed:.2f}x")
records += [
{"Threshold": tag, "Metric": f"{target_fam.capitalize()} QED",
"Enrichment Factor": ef_des},
{"Threshold": tag, "Metric": "QED",
"Enrichment Factor": ef_qed},
]
plot_df = pd.DataFrame(records)
if plot:
sns.set_theme(style="white")
plt.figure(figsize=(10, 6))
sns.barplot(data=plot_df, x="Threshold", y="Enrichment Factor",
hue="Metric", palette="Set2")
plt.axhline(1.0, color="red", linestyle="--", label="Baseline (1.0×)")
plt.title(f"Enrichment Factors: {target_fam.capitalize()} Family",
pad=15, fontsize=20)
plt.ylabel("Enrichment Factor")
plt.xlabel("Top Percentile Threshold")
plt.tight_layout()
if save:
base = Path(engine_path).parent / "figures"
base.mkdir(parents=True, exist_ok=True)
plt.savefig(base / f"{target_fam}_enrichment_comparison.svg",
dpi=300, bbox_inches="tight")
plt.show()
return (
plot_df
.pivot(index="Threshold", columns="Metric", values="Enrichment Factor")
.reset_index()
.rename_axis(None, axis=1)
)
# ---------------------------------------------------------------------------
# 6. Main entry point
# ---------------------------------------------------------------------------
#%%
if __name__ == "__main__":
MAIN_DIR = Path(__file__).parent.parent
import os
os.chdir(MAIN_DIR)
DATA_PATH = "datasets/short_dataset_filtered_rdkit.csv"
OUTPUT_BASE = Path("des_results/extra")
FIGURE_BASE = OUTPUT_BASE / "figures"
FIGURE_BASE.mkdir(parents=True, exist_ok=True)
# Load & filter
data = pd.read_csv(DATA_PATH)
valid_cols = [f for f in MIN_FEATURES if f in data.columns]
data_clean = data[valid_cols + ["label"]].copy()
final_features = valid_cols
# Train one engine per reference family
for ref in ALL_FAMILIES:
summary, engines, report, components = fit_families(
data_clean,
features=final_features,
reference_subset=ref,
target_col="label",
weight_step=0.25,
weight_objective="cohens_d",
)
engine_file = OUTPUT_BASE / f"engines_for_extra{ref}.pkl"
with open(engine_file, "wb") as fh:
pickle.dump(engines, fh)
report.to_csv(OUTPUT_BASE / f"report_for_extra{ref}.csv", index=False)
summary.to_csv(OUTPUT_BASE / f"summary_for_extra{ref}.csv", index=False)
components.to_csv(OUTPUT_BASE / f"components_for_extra{ref}.csv", index=False)
logger.info(f"\n--- Summary for {ref} ---\n{summary}")
for ref in ALL_FAMILIES:
engine_file = OUTPUT_BASE / f"engines_for_extra{ref}.pkl"
plot_all_families_boxplot(
data_clean,
engine_file,
final_features,
reference_family=ref,
save_path=str(FIGURE_BASE / f"boxplot_all_vs_{ref}_engine.svg")
)
# Score comparison plots (KDE + histogram) for every pair
for ref in ALL_FAMILIES:
engine_file = OUTPUT_BASE / f"engines_for_extra{ref}.pkl"
for other in ALL_FAMILIES:
if other == ref:
continue
plot_score_comparison(
data_clean, engine_file, final_features, ref, other,
kind="kde",
save_path=str(FIGURE_BASE / f"kde_{ref}_vs_{other}.svg"),
)
plot_score_comparison(
data_clean, engine_file, final_features, ref, other,
kind="hist",
save_path=str(FIGURE_BASE / f"hist_{ref}_vs_{other}.svg"),
)
# Discrimination & pairwise confusion
for fam in ALL_FAMILIES:
analyze_family_discrimination(fam, data, final_features,
base_path=OUTPUT_BASE)
analyze_pairwise_confusion(fam, data, final_features,
base_path=OUTPUT_BASE)
# Enrichment analysis
for fam in ALL_FAMILIES:
results_df = enrichment_analysis(
target_fam=fam,
data=data,
feature_cols=final_features,
engine_path=OUTPUT_BASE / f"engines_for_extra{fam}.pkl",
top_percentiles=[0.01, 0.05, 0.10],
)
if results_df is not None:
print(results_df)
# QED distribution boxplot
plt.figure(figsize=(12, 6))
sns.set_style("white")
sns.boxplot(data=data, x="label", y="qed", palette="Set1", linewidth=1.5)
plt.xticks(rotation=45)
plt.xlabel("Target Families")
plt.ylabel("QED Score")
plt.title("QED Score Distribution by Family", fontsize=20)
plt.tight_layout()
plt.savefig(FIGURE_BASE / "qed_boxplot_by_family.svg",
dpi=300, bbox_inches="tight")
plt.show()
# %%
# %%