Spaces:
Sleeping

FamDLike / main.py
yucelmehmet's picture
Update main.py
ddf37a6 verified
Raw History Blame Contribute Delete
9.92 kB
import os
import sys
import warnings
import argparse
import pickle
import joblib
import numpy as np
import pandas as pd
from sklearn.exceptions import InconsistentVersionWarning
from gam import gam_model
from desirability_functions.optimizer import DesirabilityOptimizer # noqa: F401
from calc_desc import rdkit_desc_parallel
from config import (
MAIN_PATH,
TARGET_FAMILIES,
MIN_FEATURES,
GAM_FEATURES,
load_tree_features,
)
warnings.filterwarnings("ignore", category=InconsistentVersionWarning)
# pickle was saved with the bare module name 'gam_model'; keep that alias.
sys.modules["gam_model"] = gam_model
sys.path.append(os.path.join(MAIN_PATH, "custom_druglikeness"))
LABEL_ENCODER_PATH = os.path.join(MAIN_PATH, "label_encoder.joblib")
TREE_FEATURES = load_tree_features()
try:
label_encoder = joblib.load(LABEL_ENCODER_PATH)
except FileNotFoundError:
label_encoder = None
class PredictDrugLikeness:
def __init__(
self,
df: pd.DataFrame,
calc_desc: bool = True,
tree_models: bool = True,
use_gams: bool = True,
n_cores: int = 1,
):
self.df = df.copy()
self.calc_desc = calc_desc
self.tree_models = tree_models
self.use_gams = use_gams
self.n_cores = n_cores
self.models = []
self.des_engines = {}
self.gam_models = {}
if self.tree_models:
self.load_models()
self.load_desirability_functions()
if self.use_gams:
self.load_gam_models_scalers()
def load_models(self):
model_dir = os.path.join(MAIN_PATH, "treemodels_models")
for model_type in ("RandomForest", "XGBoost"):
path = os.path.join(model_dir, f"{model_type}_final.joblib")
if os.path.exists(path):
self.models.append(joblib.load(path))
else:
print(f" -> Warning: Missing model file: {path}")
def load_desirability_functions(self):
des_dir = os.path.join(MAIN_PATH, "des_results", "extra")
for cls in TARGET_FAMILIES:
path = os.path.join(des_dir, f"engines_for_extra{cls}.pkl")
if os.path.exists(path):
with open(path, "rb") as f:
self.des_engines[cls] = pickle.load(f)
else:
print(f" -> Warning: Missing desirability engine for {cls} at {path}")
def load_gam_models_scalers(self):
"""Load one GAM model + scaler per target family."""
gam_path = os.path.join(MAIN_PATH, "gam_models")
self.gam_models = {}
for cls in TARGET_FAMILIES:
entry = {"model": None, "scaler": None}
path_pkl = os.path.join(gam_path, f"gam_{cls}_final.pkl")
path_scaler = os.path.join(gam_path, f"scaler_{cls}_final.pkl")
if os.path.exists(path_pkl):
with open(path_pkl, "rb") as f:
entry["model"] = pickle.load(f)
if os.path.exists(path_scaler):
with open(path_scaler, "rb") as f:
entry["scaler"] = pickle.load(f)
self.gam_models[cls] = entry
def check_and_prep_df(self):
if self.calc_desc:
smiles_cols = [
c for c in self.df.columns
if c.lower() in ("smiles", "canonical_smiles")
]
if not smiles_cols:
raise ValueError(
"Input DataFrame must contain a 'SMILES' or 'canonical_smiles' "
"column when calc_desc=True."
)
self.df = rdkit_desc_parallel(
self.df, smiles_col=smiles_cols[0], n_cores=self.n_cores
)
self.df = self.df.loc[:, ~self.df.columns.duplicated()]
numeric_cols = self.df.select_dtypes(include=[np.number]).columns
self.df[numeric_cols] = (
self.df[numeric_cols].replace([np.inf, -np.inf], np.nan).fillna(0)
)
if self.tree_models:
missing_cols = [c for c in TREE_FEATURES if c not in self.df.columns]
if missing_cols:
raise ValueError(
f"Missing required columns in DataFrame: {missing_cols}"
)
return self.df
def predict(self):
df_ready = self.check_and_prep_df().copy()
X_tree_models = df_ready[TREE_FEATURES] if self.tree_models else None
X_des = df_ready[MIN_FEATURES]
X_gam = df_ready[GAM_FEATURES] if self.use_gams else None
# --- 1. Tree-model ensemble ---
if self.tree_models:
if not self.models:
raise ValueError("No Tree Models were loaded. Cannot predict.")
avg_probs = np.zeros(
(len(X_tree_models), len(self.models[0].classes_))
)
valid_models_count = 0
for model in self.models:
if hasattr(model, "predict_proba"):
avg_probs += model.predict_proba(X_tree_models)
valid_models_count += 1
else:
print(f" -> Warning: Model {model} does not support predict_proba. Skipping.")
avg_probs /= valid_models_count
if label_encoder is not None:
class_names = label_encoder.inverse_transform(self.models[0].classes_)
for i, class_name in enumerate(class_names):
self.df[f"Ensemble_Prob_{class_name}"] = avg_probs[:, i]
self.df["Predicted_Class"] = class_names[np.argmax(avg_probs, axis=1)]
else:
self.df["Predicted_Class"] = self.models[0].classes_[
np.argmax(avg_probs, axis=1)
]
self.df["Average_Probability"] = np.max(avg_probs, axis=1)
# --- 2. GAM predictions ---
if self.use_gams and self.gam_models:
for family, components in self.gam_models.items():
model = components.get("model")
scaler = components.get("scaler")
if model is None or scaler is None:
print(f" -> Warning: No GAM model/scaler found for {family}.")
continue
if not (hasattr(model, "predict_proba") and hasattr(scaler, "transform")):
print(f" -> Warning: GAM for {family} missing required methods.")
continue
if hasattr(scaler, "feature_names_in_"):
X_gam_reordered = X_gam[scaler.feature_names_in_]
else:
X_gam_reordered = X_gam
X_scaled = scaler.transform(X_gam_reordered)
probs = np.array(model.predict_proba(X_scaled))
# sklearn returns 2-D (n, 2); pygam returns 1-D (n,).
self.df[f"{family}_GAM_Prob"] = (
probs[:, 1] if probs.ndim == 2 else probs
)
# --- 3. Desirability ---
for family, engine_data in self.des_engines.items():
engine = (
engine_data.get("Best_and_good")
if isinstance(engine_data, dict)
else engine_data
)
if hasattr(engine, "predict_dataframe"):
self.df[f"{family}_Desirability"] = engine.predict_dataframe(X_des)
else:
print(f" -> Warning: Engine for {family} is missing 'predict_dataframe'. Skipping.")
# --- 4. Composite drug-likeness score ---
# Equal-weight geometric mean of the available component scores, in [0, 1]:
# S_fam = ( d * g * t ) ** (1 / n_components)
# = exp( mean( log d, log g, log t ) )
# Missing components are simply dropped from the mean.
eps = 1e-3
for fam in TARGET_FAMILIES:
scores = {}
for key, col in (
("Desirability", f"{fam}_Desirability"),
("GAM", f"{fam}_GAM_Prob"),
("Tree_Ensemble", f"Ensemble_Prob_{fam}"),
):
if col in self.df.columns:
scores[key] = self.df[col].values.astype(float)
if not scores:
print(f" -> Warning: No scores available for {fam} to calculate composite score.")
continue
clipped = [np.clip(v, eps, 1 - eps) for v in scores.values()]
log_mean = np.mean([np.log(c) for c in clipped], axis=0)
self.df[f"{fam}_DrugLikeness_Score"] = np.exp(log_mean)
self.df = self.df.copy()
return self.df
# --- CLI ---
def main():
parser = argparse.ArgumentParser(
description="Predict Target Class and Drug Likeness from molecular data."
)
parser.add_argument("-i", "--input", required=True,
help="Path to input CSV file containing molecules.")
parser.add_argument("-o", "--output", required=True,
help="Path to save output CSV file.")
parser.add_argument("-c", "--calc_desc", action="store_true",
help="Flag: Calculate RDKit descriptors.")
parser.add_argument("-n", "--n_cores", type=int, default=1,
help="Number of cores to use for parallel processing.")
args = parser.parse_args()
try:
input_df = pd.read_csv(args.input)
except Exception as e:
print(f"Error reading input file: {e}")
return
try:
predictor = PredictDrugLikeness(
df=input_df,
calc_desc=args.calc_desc,
n_cores=args.n_cores,
)
results_df = predictor.predict()
results_df.to_csv(args.output, index=False)
print(f"Success! Results saved to {args.output}")
except Exception as e:
print(f"\nExecution Failed: {e}")
if __name__ == "__main__":
main()