Spaces:
Sleeping

Mehmet Ali Yücel
fresh upload with LFS tracking
b1dd307
Raw History Blame Contribute Delete
9.52 kB
"""
optimizer.py
------------
Fits statistical distributions to molecular-property histograms and builds
DesirabilityFunctions engines from the best fits.
"""
import math
from typing import Dict, List
import numpy as np
import pandas as pd
from scipy import optimize, stats
from sklearn.metrics import r2_score
from desirability_functions import DesirabilityFunctions
class DesirabilityOptimizer:
"""
Fits multiple statistical distributions to each molecular property and
selects the best-fitting one for use in a DesirabilityFunctions engine.
"""
def __init__(self):
self.report: pd.DataFrame = pd.DataFrame()
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
@staticmethod
def _histogram(data: np.ndarray, bins) -> tuple[np.ndarray, np.ndarray]:
"""Return (bin-centres, density) for a density histogram."""
hist, edges = np.histogram(data, bins=bins, density=True)
centres = (edges[:-1] + edges[1:]) / 2
return centres, hist
@staticmethod
def _safe_r2(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Return R² or –∞ when the calculation fails."""
try:
return float(r2_score(y_true, y_pred))
except Exception:
return float("-inf")
# ------------------------------------------------------------------
# Per-distribution fitting methods
# ------------------------------------------------------------------
def _fit_poisson(self, data: np.ndarray, prop: str) -> dict | None:
"""Fit Poisson to integer data. Returns a result dict or None."""
try:
mu = float(np.mean(data))
possible = np.arange(0, int(data.max()) + 1)
counts = np.array([np.sum(data == v) for v in possible])
y_true = counts / counts.sum()
y_pred = np.array([
(mu ** k * np.exp(-mu)) / math.gamma(k + 1)
for k in possible
])
return {
"Property": prop, "Method": "Poisson",
"R2": self._safe_r2(y_true, y_pred),
"Params": {"function": "poisson", "mu": mu},
}
except Exception:
return None
def _fit_gaussian(self, data: np.ndarray, x: np.ndarray,
y: np.ndarray, prop: str) -> dict | None:
try:
mu, sigma = stats.norm.fit(data)
y_pred = stats.norm.pdf(x, mu, sigma)
return {
"Property": prop, "Method": "Gaussian",
"R2": self._safe_r2(y, y_pred),
"Params": {"function": "gaussian", "mu": mu, "sigma": sigma},
}
except Exception:
return None
def _fit_lognormal(self, data: np.ndarray, x: np.ndarray,
y: np.ndarray, prop: str) -> dict | None:
try:
pos = data[data > 0]
if len(pos) == 0:
return None
shape, loc, scale = stats.lognorm.fit(pos, floc=0)
y_pred = stats.lognorm.pdf(x, shape, loc, scale)
return {
"Property": prop, "Method": "Log-Normal",
"R2": self._safe_r2(y, y_pred),
"Params": {"function": "log_normal",
"mu": float(np.log(scale)), "sigma": float(shape)},
}
except Exception:
return None
def _fit_gamma(self, data: np.ndarray, x: np.ndarray,
y: np.ndarray, prop: str) -> dict | None:
try:
pos = data[data > 0]
if len(pos) == 0:
return None
alpha, loc, beta = stats.gamma.fit(pos, floc=0)
y_pred = stats.gamma.pdf(x, alpha, loc, beta)
return {
"Property": prop, "Method": "Gamma",
"R2": self._safe_r2(y, y_pred),
"Params": {"function": "gamma",
"shape": float(alpha), "scale": float(beta)},
}
except Exception:
return None
def _fit_ads(self, data: np.ndarray, x: np.ndarray,
y: np.ndarray, prop: str) -> dict | None:
"""Fit Asymmetric Double Sigmoid (ADS) to a density histogram."""
try:
def _ads_pdf(xv, c, d, e, f, scale):
a1 = np.clip(-(xv - c + d / 2) / e, -50, 50)
a2 = np.clip((xv - c - d / 2) / f, -50, 50)
return scale / ((1 + np.exp(a1)) * (1 + np.exp(a2)))
mean, std = np.mean(data), np.std(data)
p0 = [mean, std * 1.5, std, std, np.max(y) * 4]
bounds = ([-np.inf, 0.01, 0.01, 0.01, 0],
[np.inf, np.inf, np.inf, np.inf, np.inf])
popt, _ = optimize.curve_fit(
_ads_pdf, x, y, p0=p0, bounds=bounds, maxfev=10_000
)
y_pred = _ads_pdf(x, *popt)
# Normalise b so the peak of the desirability function equals 1.0
c, d, e, f, _ = popt
grid = np.linspace(x.min(), x.max(), 1000)
a1 = np.clip(-(grid - c + d / 2) / e, -50, 50)
a2 = np.clip((grid - c - d / 2) / f, -50, 50)
b_norm = float(np.min((1 + np.exp(a1)) * (1 + np.exp(a2))))
return {
"Property": prop, "Method": "ADS",
"R2": self._safe_r2(y, y_pred),
"Params": {"function": "ads", "a": 0, "b": b_norm,
"c": float(c), "d": float(d),
"e": float(e), "f": float(f)},
}
except Exception:
return None
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def fit_evaluate_all(
self, df: pd.DataFrame, properties: List[str]
) -> pd.DataFrame:
"""
Fit all applicable distributions to each property column.
Returns a DataFrame with columns [Property, Method, R2, Params]
sorted by Property (asc) then R2 (desc).
"""
results = []
for prop in properties:
if prop not in df.columns:
continue
data = df[prop].dropna().values
if len(data) == 0:
continue
# Detect integer (discrete) data
is_integer = np.issubdtype(df[prop].dtype, np.integer) or np.all(
np.mod(data, 1) == 0
)
if is_integer:
data = data.astype(int)
# Build density histogram
if is_integer:
lo, hi = int(data.min()), int(data.max())
edges = np.arange(lo - 0.5, hi + 1.5, 1.0)
x_hist, y_hist = self._histogram(data, bins=edges)
else:
x_hist, y_hist = self._histogram(data, bins="auto")
# Candidate distributions
if is_integer:
r = self._fit_poisson(data, prop)
if r:
results.append(r)
for fitter in (self._fit_gaussian, self._fit_lognormal,
self._fit_gamma, self._fit_ads):
r = fitter(data, x_hist, y_hist, prop)
if r:
results.append(r)
self.report = (
pd.DataFrame(results)
.sort_values(by=["Property", "R2"], ascending=[True, False])
.reset_index(drop=True)
)
return self.report
def create_desirability_function(
self,
method_df: pd.DataFrame,
selection_strategy: str = "best_and_good",
r2_threshold: float = 0.6,
) -> DesirabilityFunctions:
"""
Build a DesirabilityFunctions engine from the fitting report.
Args:
method_df: Output of fit_evaluate_all (sorted by R2 desc per property).
selection_strategy:
- 'best' – always use the top-ranked method.
- 'best_and_good' – use the best method only if R2 ≥ r2_threshold;
skip properties that don't meet the bar.
- '<method_name>' – force a specific method (e.g. 'ADS', 'Gaussian').
r2_threshold: Minimum acceptable R2 (only used with 'best_and_good').
Returns:
A configured DesirabilityFunctions engine.
"""
engine = DesirabilityFunctions()
for prop in method_df["Property"].unique():
rows = method_df[method_df["Property"] == prop]
if selection_strategy == "best":
chosen = rows.iloc[0]
elif selection_strategy == "best_and_good":
best_r2 = rows.iloc[0]["R2"]
print(f" {prop}: best R² = {best_r2:.4f}")
good = rows[rows["R2"] >= r2_threshold]
if good.empty:
print(f" WARNING: No fit for '{prop}' meets R²≥{r2_threshold}. Skipped.")
continue
chosen = good.iloc[0]
else:
# Force a named method; fall back to best if not found
forced = rows[rows["Method"] == selection_strategy]
chosen = forced.iloc[0] if not forced.empty else rows.iloc[0]
engine.add_property(prop, chosen["Params"])
return engine