Spaces:
Sleeping

File size: 9,515 Bytes
b1dd307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
"""
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