Docking_project / libs /adaptive /features.py
QPromaQ's picture
Upload folder using huggingface_hub
c289d87 verified
Raw
History Blame Contribute Delete
19 kB
from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, Iterable, List, Tuple
import numpy as np
import pandas as pd
from rdkit import Chem
from rdkit.Chem import AllChem, Descriptors, Lipinski, MolSurf, rdMolDescriptors
from rdkit.Chem.Scaffolds import MurckoScaffold
from rdkit.DataStructs import TanimotoSimilarity
try:
from rdkit.Chem import rdFreeSASA
except Exception: # pragma: no cover
rdFreeSASA = None # type: ignore[assignment]
@dataclass
class FeatureValue:
value: float | None
available: bool
source: str
feature_type: str
@dataclass
class FeatureBundle:
object_id: str
features: Dict[str, FeatureValue]
def to_records(self, channel: str, round_idx: int | None = None) -> List[dict]:
rows: List[dict] = []
for name, fv in sorted(self.features.items()):
rows.append(
{
"object_id": self.object_id,
"round": round_idx,
"channel": channel,
"feature_name": name,
"value": fv.value,
"available": bool(fv.available),
"source": fv.source,
"feature_type": fv.feature_type,
}
)
return rows
def _fv(value: float | None, available: bool, source: str, feature_type: str) -> FeatureValue:
return FeatureValue(value=value, available=available, source=source, feature_type=feature_type)
def _safe_float(value: float | int | None) -> float | None:
if value is None:
return None
try:
v = float(value)
except Exception:
return None
if not np.isfinite(v):
return None
return v
def _compute_ligand_sasa(mol: Chem.Mol) -> Tuple[float | None, bool]:
if rdFreeSASA is None:
return None, False
try:
if mol.GetNumConformers() == 0:
m = Chem.AddHs(Chem.Mol(mol))
status = AllChem.EmbedMolecule(m, AllChem.ETKDGv3())
if int(status) != 0:
return None, False
else:
m = Chem.Mol(mol)
if m.GetNumConformers() == 0:
return None, False
radii = rdFreeSASA.classifyAtoms(m)
sasa = rdFreeSASA.CalcSASA(m, radii)
return _safe_float(sasa), True
except Exception:
return None, False
def build_ligand_feature_bundle(
ligand_id: str,
smiles: str,
fingerprint: np.ndarray,
reference_mol: Chem.Mol | None = None,
compute_partial_charges: bool = True,
compute_sasa: bool = True,
) -> FeatureBundle:
mol = Chem.MolFromSmiles(smiles)
if mol is None:
raise ValueError(f"Invalid SMILES for ligand {ligand_id}: {smiles}")
m_h = Chem.AddHs(Chem.Mol(mol))
if compute_partial_charges:
try:
AllChem.ComputeGasteigerCharges(m_h)
partial_charges = []
for atom in m_h.GetAtoms():
prop = atom.GetProp("_GasteigerCharge") if atom.HasProp("_GasteigerCharge") else "nan"
try:
q = float(prop)
except Exception:
continue
if np.isfinite(q):
partial_charges.append(q)
if partial_charges:
mean_abs_q = float(np.mean(np.abs(partial_charges)))
total_q = float(np.sum(partial_charges))
has_q = True
else:
mean_abs_q = None
total_q = None
has_q = False
except Exception:
mean_abs_q = None
total_q = None
has_q = False
else:
mean_abs_q = None
total_q = None
has_q = False
aromatic_rings = rdMolDescriptors.CalcNumAromaticRings(mol)
formal_charge = Chem.GetFormalCharge(mol)
heavy_atoms = mol.GetNumHeavyAtoms()
frac_csp3 = rdMolDescriptors.CalcFractionCSP3(mol)
bertz_ct = Descriptors.BertzCT(mol)
balaban_j = Descriptors.BalabanJ(mol)
topological_complexity = rdMolDescriptors.CalcChi0v(mol)
if compute_sasa:
ligand_sasa, has_sasa = _compute_ligand_sasa(m_h)
else:
ligand_sasa, has_sasa = None, False
reference_similarity = None
scaffold_match = None
chemical_distance = None
if reference_mol is not None:
fp_gen = AllChem.GetMorganGenerator(radius=2, fpSize=int(fingerprint.shape[0]))
ref_fp = fp_gen.GetFingerprint(reference_mol)
lig_fp = fp_gen.GetFingerprint(mol)
sim = TanimotoSimilarity(ref_fp, lig_fp)
reference_similarity = float(sim)
chemical_distance = float(1.0 - sim)
ref_scaffold = MurckoScaffold.MurckoScaffoldSmiles(mol=reference_mol)
lig_scaffold = MurckoScaffold.MurckoScaffoldSmiles(mol=mol)
scaffold_match = float(ref_scaffold == lig_scaffold)
features: Dict[str, FeatureValue] = {
"ligand_mw": _fv(_safe_float(Descriptors.MolWt(mol)), True, "rdkit", "exact"),
"ligand_logp": _fv(_safe_float(Descriptors.MolLogP(mol)), True, "rdkit", "exact"),
"ligand_tpsa": _fv(_safe_float(MolSurf.TPSA(mol)), True, "rdkit", "exact"),
"ligand_hbd": _fv(_safe_float(Lipinski.NumHDonors(mol)), True, "rdkit", "exact"),
"ligand_hba": _fv(_safe_float(Lipinski.NumHAcceptors(mol)), True, "rdkit", "exact"),
"ligand_rotatable_bonds": _fv(_safe_float(Lipinski.NumRotatableBonds(mol)), True, "rdkit", "exact"),
"ligand_aromatic_ring_count": _fv(_safe_float(aromatic_rings), True, "rdkit", "exact"),
"ligand_formal_charge": _fv(_safe_float(formal_charge), True, "rdkit", "exact"),
"ligand_partial_charge_abs_mean": _fv(mean_abs_q, has_q, "rdkit", "approximate"),
"ligand_partial_charge_total": _fv(total_q, has_q, "rdkit", "approximate"),
"ligand_topological_bertz": _fv(_safe_float(bertz_ct), True, "rdkit", "exact"),
"ligand_topological_balaban_j": _fv(_safe_float(balaban_j), True, "rdkit", "exact"),
"ligand_topological_chi0v": _fv(_safe_float(topological_complexity), True, "rdkit", "exact"),
"ligand_fraction_csp3": _fv(_safe_float(frac_csp3), True, "rdkit", "exact"),
"ligand_heavy_atom_count": _fv(_safe_float(heavy_atoms), True, "rdkit", "exact"),
"ligand_sasa": _fv(ligand_sasa, has_sasa, "geometric", "approximate"),
"similarity_to_reference": _fv(reference_similarity, reference_similarity is not None, "rdkit", "exact"),
"scaffold_match": _fv(scaffold_match, scaffold_match is not None, "rdkit", "exact"),
"chemical_distance_to_reference": _fv(chemical_distance, chemical_distance is not None, "rdkit", "exact"),
}
for i, bit in enumerate(fingerprint.astype(float).tolist()):
features[f"morgan_fp_{i:04d}"] = _fv(float(bit), True, "rdkit", "exact")
return FeatureBundle(object_id=ligand_id, features=features)
def build_protein_feature_bundle(target_id: str, sequence_features: Dict[str, float], structure_features: Dict[str, float]) -> FeatureBundle:
seq_len = float(sequence_features.get("seq_length", 1.0) or 1.0)
hydrophobic = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["A", "V", "I", "L", "M", "F", "W", "Y"])
charged = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["K", "R", "H", "D", "E"])
polar = sum(sequence_features.get(f"aa_frac_{aa}", 0.0) for aa in ["S", "T", "N", "Q", "C"])
residue_count = float(structure_features.get("residue_count", 0.0))
mean_extent = float(structure_features.get("mean_spatial_extent", 0.0))
pocket_residues = float(structure_features.get("pocket_residue_count", 0.0))
approx_volume = float(max(0.0, mean_extent**3))
pocket_coverage = float(pocket_residues / max(residue_count, 1.0))
features = {
"pocket_hydrophobic_fraction": _fv(hydrophobic, True, "protein", "exact"),
"pocket_charged_fraction": _fv(charged, True, "protein", "exact"),
"pocket_polar_fraction": _fv(polar, True, "protein", "exact"),
"pocket_residue_count": _fv(residue_count, True, "protein", "exact"),
"pocket_volume_approx": _fv(approx_volume, True, "geometric", "approximate"),
"pocket_coverage_fraction": _fv(pocket_coverage, True, "geometric", "approximate"),
"pocket_sequence_length": _fv(seq_len, True, "protein", "exact"),
}
return FeatureBundle(object_id=target_id, features=features)
def build_complex_feature_bundle(
ligand_id: str,
docking_score: float,
interface_features: Dict[str, float],
ligand_bundle: FeatureBundle,
protein_bundle: FeatureBundle,
) -> FeatureBundle:
lig = ligand_bundle.features
prot = protein_bundle.features
logp = lig.get("ligand_logp", _fv(None, False, "rdkit", "exact")).value or 0.0
tpsa = lig.get("ligand_tpsa", _fv(None, False, "rdkit", "exact")).value or 0.0
charge_mag = lig.get("ligand_partial_charge_abs_mean", _fv(None, False, "rdkit", "approximate")).value
heavy_atoms = lig.get("ligand_heavy_atom_count", _fv(None, False, "rdkit", "exact")).value or 1.0
pocket_volume = prot.get("pocket_volume_approx", _fv(None, False, "geometric", "approximate")).value or 1.0
pocket_hydrophobic = prot.get("pocket_hydrophobic_fraction", _fv(None, False, "protein", "exact")).value or 0.0
interface_contact_proxy = float(interface_features.get("interface_contact_proxy", max(0.0, -docking_score / 8.0)))
hbond_proxy = float(interface_features.get("hbond_proxy", max(0.0, tpsa / 100.0)))
shape_proxy = float(interface_features.get("shape_proxy", max(0.0, 1.0 / (1.0 + abs(docking_score)))))
contact_count = max(1.0, heavy_atoms * (0.3 + interface_contact_proxy))
polar_contacts = contact_count * min(1.0, tpsa / 120.0)
hydrophobic_contacts = contact_count * min(1.0, max(0.0, logp) / 6.0) * (0.5 + pocket_hydrophobic)
clash_count = max(0.0, docking_score - 9.0)
min_distance = max(1.5, 6.0 - interface_contact_proxy)
pocket_coverage = min(1.0, contact_count / max(10.0, pocket_volume / 20.0))
interaction_density = contact_count / max(1.0, pocket_volume)
ligand_sasa = lig.get("ligand_sasa", _fv(None, False, "geometric", "approximate")).value
protein_sasa = pocket_volume * 0.75
if ligand_sasa is not None:
complex_sasa = max(1.0, protein_sasa + ligand_sasa - 0.5 * contact_count)
buried_sasa = max(0.0, protein_sasa + ligand_sasa - complex_sasa)
burial_ratio = buried_sasa / max(ligand_sasa, 1e-6)
sasa_available = True
else:
complex_sasa = None
buried_sasa = None
burial_ratio = None
sasa_available = False
if charge_mag is not None:
electrostatic_proxy = -charge_mag * max(0.5, 5.0 - min_distance)
electro_available = True
else:
electrostatic_proxy = None
electro_available = False
contact_energy = -0.15 * contact_count
steric_penalty = 0.6 * clash_count
hydrophobic_proxy = -0.1 * hydrophobic_contacts
interaction_decomp = contact_energy + hydrophobic_proxy + (electrostatic_proxy or 0.0) + steric_penalty
features = {
"complex_contact_count": _fv(float(contact_count), True, "interaction", "proxy"),
"complex_hbond_proxy": _fv(float(hbond_proxy), True, "interaction", "proxy"),
"complex_polar_contact_count": _fv(float(polar_contacts), True, "interaction", "proxy"),
"complex_hydrophobic_contact_proxy": _fv(float(hydrophobic_contacts), True, "interaction", "proxy"),
"complex_clash_count": _fv(float(clash_count), True, "interaction", "proxy"),
"complex_min_distance": _fv(float(min_distance), True, "geometric", "approximate"),
"complex_pocket_coverage": _fv(float(pocket_coverage), True, "interaction", "proxy"),
"complex_interaction_density": _fv(float(interaction_density), True, "interaction", "proxy"),
"complex_ligand_sasa": _fv(_safe_float(ligand_sasa), ligand_sasa is not None, "geometric", "approximate"),
"complex_protein_sasa": _fv(_safe_float(protein_sasa), True, "geometric", "approximate"),
"complex_sasa": _fv(_safe_float(complex_sasa), sasa_available, "geometric", "approximate"),
"complex_buried_sasa": _fv(_safe_float(buried_sasa), sasa_available, "geometric", "approximate"),
"complex_shape_complementarity": _fv(float(shape_proxy), True, "geometric", "proxy"),
"complex_ligand_burial_ratio": _fv(_safe_float(burial_ratio), sasa_available, "geometric", "approximate"),
"energy_contact_proxy": _fv(float(contact_energy), True, "energy_proxy", "proxy"),
"energy_electrostatic_proxy": _fv(_safe_float(electrostatic_proxy), electro_available, "energy_proxy", "proxy"),
"energy_steric_clash_penalty": _fv(float(steric_penalty), True, "energy_proxy", "proxy"),
"energy_hydrophobic_proxy": _fv(float(hydrophobic_proxy), True, "energy_proxy", "proxy"),
"energy_interaction_decomposition": _fv(float(interaction_decomp), True, "energy_proxy", "proxy"),
}
return FeatureBundle(object_id=ligand_id, features=features)
def build_rdock_feature_bundle(
ligand_id: str,
parsed_row: Dict[str, float | int | str | bool | None],
) -> FeatureBundle:
"""Build a feature bundle from rDock-native and rDock-derived per-ligand outputs."""
def _as_feature(
key: str,
source: str,
ftype: str,
) -> FeatureValue:
value = _safe_float(parsed_row.get(key)) # type: ignore[arg-type]
return _fv(value, value is not None, source, ftype if value is not None else "unavailable")
features: Dict[str, FeatureValue] = {
"rdock_total_score": _as_feature("rdock_total_score", "rdock_native", "exact"),
"rdock_pose_rank": _as_feature("rdock_pose_rank", "rdock_native", "exact"),
"n_generated_poses": _as_feature("n_generated_poses", "rdock_native", "exact"),
"best_pose_score": _as_feature("best_pose_score", "rdock_native", "exact"),
"mean_top3_pose_score": _as_feature("mean_top3_pose_score", "rdock_native", "exact"),
"mean_top5_pose_score": _as_feature("mean_top5_pose_score", "rdock_native", "exact"),
"std_top5_pose_score": _as_feature("std_top5_pose_score", "rdock_native", "exact"),
"pose_score_gap_1_2": _as_feature("pose_score_gap_1_2", "rdock_native", "exact"),
"rdock_restraint_term": _as_feature("rdock_restraint_term", "rdock_native", "exact"),
"rdock_internal_ligand_term": _as_feature("rdock_internal_ligand_term", "rdock_native", "exact"),
"rdock_polar_term": _as_feature("rdock_polar_term", "rdock_native", "exact"),
"rdock_vdw_term": _as_feature("rdock_vdw_term", "rdock_native", "exact"),
"top_pose_rmsd_consistency": _as_feature("top_pose_rmsd_consistency", "rdock_derived", "proxy"),
"contact_overlap_consistency": _as_feature("contact_overlap_consistency", "rdock_derived", "proxy"),
"hotspot_contact_frequency": _as_feature("hotspot_contact_frequency", "rdock_derived", "proxy"),
"subpocket_match_score": _as_feature("subpocket_match_score", "rdock_derived", "proxy"),
"replicate_mean_score": _as_feature("replicate_mean_score", "rdock_derived", "proxy"),
"replicate_score_variance": _as_feature("replicate_score_variance", "rdock_derived", "proxy"),
"replicate_consensus_score": _as_feature("replicate_consensus_score", "rdock_derived", "proxy"),
}
return FeatureBundle(object_id=ligand_id, features=features)
def merge_bundles(object_id: str, bundles: Iterable[FeatureBundle]) -> FeatureBundle:
merged: Dict[str, FeatureValue] = {}
for bundle in bundles:
merged.update(bundle.features)
return FeatureBundle(object_id=object_id, features=merged)
def bundles_to_wide_frames(
bundles: List[FeatureBundle],
ordered_feature_names: List[str] | None = None,
) -> Tuple[pd.DataFrame, pd.DataFrame, List[str]]:
if not bundles:
return pd.DataFrame(), pd.DataFrame(), []
if ordered_feature_names is None:
feature_set = set()
for bundle in bundles:
feature_set.update(bundle.features.keys())
ordered_feature_names = sorted(feature_set)
value_rows = []
mask_rows = []
for bundle in bundles:
vrow = {"ligand_id": bundle.object_id}
mrow = {"ligand_id": bundle.object_id}
for name in ordered_feature_names:
fv = bundle.features.get(name)
if fv is None or not fv.available or fv.value is None:
vrow[name] = np.nan
mrow[f"mask_{name}"] = 0
else:
vrow[name] = float(fv.value)
mrow[f"mask_{name}"] = 1
value_rows.append(vrow)
mask_rows.append(mrow)
return pd.DataFrame(value_rows), pd.DataFrame(mask_rows), ordered_feature_names
def compute_feature_diagnostics(values_df: pd.DataFrame, masks_df: pd.DataFrame, target: pd.Series | None = None) -> pd.DataFrame:
if values_df.empty:
return pd.DataFrame(columns=["feature", "missing_frac", "mean", "std", "min", "max", "is_constant", "corr_to_target"])
numeric_cols = [c for c in values_df.columns if c != "ligand_id"]
rows = []
for col in numeric_cols:
vals = pd.to_numeric(values_df[col], errors="coerce")
mask_col = f"mask_{col}"
if mask_col in masks_df.columns:
missing_frac = 1.0 - float(pd.to_numeric(masks_df[mask_col], errors="coerce").mean())
else:
missing_frac = float(vals.isna().mean())
finite_vals = vals[np.isfinite(vals)]
is_constant = finite_vals.nunique(dropna=True) <= 1 if not finite_vals.empty else True
if target is not None and len(target) == len(vals):
target_num = pd.to_numeric(target, errors="coerce")
paired = pd.concat([vals, target_num], axis=1).dropna()
if paired.shape[0] >= 3 and paired.iloc[:, 0].nunique(dropna=True) > 1 and paired.iloc[:, 1].nunique(dropna=True) > 1:
corr = paired.iloc[:, 0].corr(paired.iloc[:, 1])
corr_val = float(corr) if corr is not None and np.isfinite(corr) else np.nan
else:
corr_val = np.nan
else:
corr_val = np.nan
rows.append(
{
"feature": col,
"missing_frac": float(missing_frac),
"mean": float(finite_vals.mean()) if not finite_vals.empty else np.nan,
"std": float(finite_vals.std()) if not finite_vals.empty else np.nan,
"min": float(finite_vals.min()) if not finite_vals.empty else np.nan,
"max": float(finite_vals.max()) if not finite_vals.empty else np.nan,
"is_constant": bool(is_constant),
"corr_to_target": corr_val,
}
)
return pd.DataFrame(rows).sort_values(["missing_frac", "feature"], ascending=[False, True]).reset_index(drop=True)