File size: 8,565 Bytes
242f0b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
256
257
258
259
260
261
262
263
264
265
266
267
"""
Tabular predictor — loads saved artifacts from B13 of the PCOS pipeline
and runs the full inference chain:
  clean → impute → scale → domain severity → base models → ensemble meta
"""

import os
import re
import copy
import numpy as np
import pandas as pd
import joblib

DEPLOY_DIR = os.path.join(os.path.dirname(__file__), "..", "models")

DOMAIN_WEIGHTS = {
    "METABOLIC"      : 0.35,
    "REPRODUCTIVE"   : 0.40,
    "HYPERANDROGENIC": 0.20,
    "GENERAL"        : 0.05,
}

BIOMARKER_DIRECTIONS = {
    "FSH(mIU/mL)"      :  1,
    "LH(mIU/mL)"       : -1,
    "FSH/LH"           :  1,
    "AMH(ng/mL)"       : -1,
    "Follicle No. (L)" : -1,
    "Follicle No. (R)" : -1,
    "Endometrium (mm)" : -1,
    "PRG(ng/mL)"       : -1,
    "Cycle(R/I)"       :  1,
}

BIOMARKER_WEIGHTS = {
    "FSH(mIU/mL)"      : 0.18,
    "LH(mIU/mL)"       : 0.08,
    "FSH/LH"           : 0.15,
    "AMH(ng/mL)"       : 0.22,
    "Follicle No. (L)" : 0.10,
    "Follicle No. (R)" : 0.10,
    "Endometrium (mm)" : 0.08,
    "PRG(ng/mL)"       : 0.05,
    "Cycle(R/I)"       : 0.04,
}

PCOS_RISK_LABELS = {
    "Low"      : "Low PCOS Risk",
    "Moderate" : "Moderate PCOS Risk",
    "High"     : "High PCOS Risk",
}

INFERTILITY_RISK_LABELS = {
    "Low"      : "Low Infertility Risk",
    "Moderate" : "Moderate Infertility Risk",
    "High"     : "High Infertility Risk",
}


def clean_name(name: str) -> str:
    return re.sub(r"[^0-9a-zA-Z_]", "_", name.strip())


def load_tabular_artifacts():
    """Load all pkl artifacts saved by the pipeline's B13."""
    arts = {}
    files = {
        "meta"          : "ensemble_meta.pkl",
        "base_models"   : "base_models.pkl",
        "domain_models" : "domain_models.pkl",
        "mice"          : "mice_imputer.pkl",
        "scaler"        : "scaler.pkl",
        "stats"         : "train_stats.pkl",
        "feat_cols"     : "feature_columns.pkl",
        "threshold"     : "best_threshold.pkl",
    }
    for key, fname in files.items():
        path = os.path.join(DEPLOY_DIR, fname)
        if os.path.exists(path):
            arts[key] = joblib.load(path)
        else:
            arts[key] = None
    return arts


def _apply_severity(domain_models, stats, X_raw_df, X_sc_df):
    """Mirror of apply_severity() from the main pipeline."""
    result = pd.DataFrame(index=X_raw_df.index)
    for d, (model, fc) in domain_models.items():
        available_fc = [c for c in fc if c in X_sc_df.columns]
        if not available_fc:
            result[f"{d}_SEV"] = 0.0
            continue
        p = model.predict_proba(X_sc_df[available_fc])[:, 1]
        mn, mx = stats[d]["min"], stats[d]["max"]
        result[f"{d}_SEV"] = np.clip((p - mn) / (mx - mn + 1e-6), 0, 1)
    result = result.fillna(0)
    result["OVERALL_SEV"] = sum(
        result[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
        for d in DOMAIN_WEIGHTS if f"{d}_SEV" in result
    )
    return result


def predict_tabular(arts: dict, patient_dict: dict) -> dict:
    """
    Run full tabular inference on a single patient.

    patient_dict: {feature_name: value} using original column names
    Returns: pcos_prob, pcos_prediction, severity scores, infertility risk score
    """
    feat_cols = arts["feat_cols"]   # list of cleaned column names

    # Build raw input DataFrame with original names
    raw = pd.DataFrame([patient_dict])

    # Compute FSH/LH ratio if both present
    if "FSH(mIU/mL)" in raw.columns and "LH(mIU/mL)" in raw.columns:
        raw["FSH_LH_Ratio"] = raw["FSH(mIU/mL)"] / (raw["LH(mIU/mL)"] + 1e-6)
    if "Follicle No. (L)" in raw.columns and "Follicle No. (R)" in raw.columns:
        raw["Total_Follicles"] = (raw["Follicle No. (L)"].fillna(0) +
                                   raw["Follicle No. (R)"].fillna(0))
    if "AMH(ng/mL)" in raw.columns and "FSH(mIU/mL)" in raw.columns:
        raw["AMH_FSH_Ratio"] = raw["AMH(ng/mL)"] / (raw["FSH(mIU/mL)"] + 1e-6)
    if "BMI" in raw.columns and "Waist(inch)" in raw.columns:
        raw["BMI_Waist_Ratio"] = raw["BMI"] / (raw["Waist(inch)"] + 1e-6)

    andro_feats = ["hair growth(Y/N)", "Skin darkening (Y/N)",
                   "Hair loss(Y/N)", "Pimples(Y/N)", "PRL(ng/mL)"]
    present_andro = [f for f in andro_feats if f in raw.columns]
    if present_andro:
        raw["Androgenic_Score"] = raw[present_andro].sum(axis=1)

    # Clean column names
    raw_clean = raw.copy()
    raw_clean.columns = [clean_name(c) for c in raw_clean.columns]

    # Align to training columns — fill missing with NaN
    X = pd.DataFrame(columns=feat_cols)
    X = pd.concat([X, raw_clean.reindex(columns=feat_cols)], ignore_index=True)
    X = X.astype(float)
    X_raw_for_severity = X.copy()

    # Impute
    mice   = arts["mice"]
    num_c  = X.select_dtypes(include=np.number).columns
    X_imp  = pd.DataFrame(mice.transform(X), columns=X.columns, index=X.index)

    # Scale
    scaler = arts["scaler"]
    X_sc   = X_imp.copy()
    X_sc[num_c] = scaler.transform(X_imp[num_c])

    # Domain severity
    sev = _apply_severity(arts["domain_models"], arts["stats"],
                           X_raw_for_severity, X_sc)

    # Final feature matrix
    X_final = pd.concat([X_sc, sev], axis=1)

    # Ensure columns match training
    for c in arts["feat_cols"] + list(sev.columns):
        if c not in X_final.columns:
            X_final[c] = 0.0

    # Base model probabilities
    base_probs = {}
    for name, model in arts["base_models"].items():
        try:
            cols_needed = [c for c in X_final.columns if c in
                           (arts["feat_cols"] + list(sev.columns))]
            base_probs[name] = model.predict_proba(X_final)[:, 1][0]
        except Exception:
            base_probs[name] = 0.5

    # Meta-learner
    meta_input = pd.DataFrame([base_probs])
    pcos_prob  = arts["meta"].predict_proba(meta_input)[:, 1][0]
    threshold  = arts["threshold"]
    prediction = "PCOS" if pcos_prob >= threshold else "Not PCOS"

    # PCOS risk tier
    if pcos_prob < 0.33:
        pcos_tier = "Low"
    elif pcos_prob < 0.66:
        pcos_tier = "Moderate"
    else:
        pcos_tier = "High"

    # Severity domain scores
    domain_scores = {
        d: round(float(sev[f"{d}_SEV"].iloc[0]), 4)
        for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev.columns
    }
    overall_sev = round(float(sev["OVERALL_SEV"].iloc[0]), 4)

    # Infertility risk score from biomarkers
    infertility_score, infertility_tier = _compute_infertility_risk(patient_dict)

    return {
        "pcos_prob"        : round(float(pcos_prob), 4),
        "pcos_prediction"  : prediction,
        "pcos_tier"        : pcos_tier,
        "threshold"        : round(float(threshold), 4),
        "base_probs"       : {k: round(v, 4) for k, v in base_probs.items()},
        "domain_scores"    : domain_scores,
        "overall_severity" : overall_sev,
        "infertility_score": round(infertility_score, 4),
        "infertility_tier" : infertility_tier,
    }


def _compute_infertility_risk(patient_dict: dict) -> tuple:
    """
    Compute infertility risk score from raw biomarkers.
    Returns (score 0–1, tier string).
    """
    from sklearn.preprocessing import MinMaxScaler

    # Map patient_dict keys to biomarker keys
    key_map = {
        "AMH(ng/mL)" : "AMH(ng/mL)",
    }

    avail = {f: patient_dict.get(f) for f in BIOMARKER_WEIGHTS
             if patient_dict.get(f) is not None}

    if not avail:
        return 0.5, "Moderate"

    # Simple weighted score — normalise each feature relative to known ranges
    CLINICAL_RANGES = {
        "FSH(mIU/mL)"      : (1.0,  30.0),
        "LH(mIU/mL)"       : (0.5,  40.0),
        "FSH/LH"           : (0.1,   5.0),
        "AMH(ng/mL)"       : (0.1,  15.0),
        "Follicle No. (L)" : (0.0,  25.0),
        "Follicle No. (R)" : (0.0,  25.0),
        "Endometrium (mm)" : (2.0,  16.0),
        "PRG(ng/mL)"       : (0.1,  25.0),
        "Cycle(R/I)"       : (0.0,   1.0),
    }

    score      = 0.0
    total_w    = 0.0
    for feat, val in avail.items():
        lo, hi  = CLINICAL_RANGES.get(feat, (0, 1))
        norm    = np.clip((float(val) - lo) / (hi - lo + 1e-6), 0, 1)
        # Orient
        if BIOMARKER_DIRECTIONS.get(feat, 1) == -1:
            norm = 1 - norm
        w       = BIOMARKER_WEIGHTS.get(feat, 0.1)
        score  += w * norm
        total_w += w

    if total_w > 0:
        score /= total_w

    if score < 0.33:
        tier = "Low"
    elif score < 0.66:
        tier = "Moderate"
    else:
        tier = "High"

    return score, tier