Upload folder using huggingface_hub
Browse files- src/feature_engineering.py +4 -0
- src/infer_recipe.py +71 -0
- src/train_baseline.py +118 -0
src/feature_engineering.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
def add_derived_features(df):
|
| 3 |
+
# Placeholder for future engineered features (e.g., UV ratios, SDS metrics)
|
| 4 |
+
return df
|
src/infer_recipe.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import argparse, json, numpy as np, joblib
|
| 3 |
+
|
| 4 |
+
PH_GRID = np.linspace(7.0, 7.6, 13)
|
| 5 |
+
IONIC_GRID = np.linspace(100, 170, 15)
|
| 6 |
+
TEMP_GRID = np.array([25.0, 37.0])
|
| 7 |
+
|
| 8 |
+
def load_models():
|
| 9 |
+
clf = joblib.load("models/gel_classifier.joblib")
|
| 10 |
+
try:
|
| 11 |
+
reg = joblib.load("models/thalf_regressor.joblib")
|
| 12 |
+
except Exception:
|
| 13 |
+
reg = None
|
| 14 |
+
return clf, reg
|
| 15 |
+
|
| 16 |
+
def make_candidates(base_features):
|
| 17 |
+
# Build a small grid of candidate recipes
|
| 18 |
+
cands = []
|
| 19 |
+
for pH in PH_GRID:
|
| 20 |
+
for mM in IONIC_GRID:
|
| 21 |
+
for tC in TEMP_GRID:
|
| 22 |
+
x = dict(base_features)
|
| 23 |
+
x["target_pH"] = float(pH)
|
| 24 |
+
x["NaCl_mM_added"] = float(mM)
|
| 25 |
+
x["temp_incubation_C"] = float(tC)
|
| 26 |
+
cands.append(x)
|
| 27 |
+
return cands
|
| 28 |
+
|
| 29 |
+
def score_candidate(clf, reg, x, lam_time=0.25):
|
| 30 |
+
features = clf["features"]
|
| 31 |
+
X = np.array([[x.get(f, np.nan) for f in features]])
|
| 32 |
+
pgel = clf["model"].predict_proba(X)[0,1]
|
| 33 |
+
thalf = 30.0
|
| 34 |
+
if reg is not None:
|
| 35 |
+
Xr = np.array([[x.get(f, np.nan) for f in reg["features"]]])
|
| 36 |
+
try:
|
| 37 |
+
thalf = float(reg["model"].predict(Xr)[0])
|
| 38 |
+
except Exception:
|
| 39 |
+
thalf = 30.0
|
| 40 |
+
util = pgel - lam_time * (thalf/60.0)
|
| 41 |
+
return util, pgel, thalf
|
| 42 |
+
|
| 43 |
+
def main(args):
|
| 44 |
+
clf, reg = load_models()
|
| 45 |
+
base_features = json.load(open(args.json))
|
| 46 |
+
cands = make_candidates(base_features)
|
| 47 |
+
best = None
|
| 48 |
+
for x in cands:
|
| 49 |
+
util, pgel, thalf = score_candidate(clf, reg, x)
|
| 50 |
+
if (best is None) or (util > best[0]):
|
| 51 |
+
best = (util, pgel, thalf, x)
|
| 52 |
+
util, pgel, thalf, x = best
|
| 53 |
+
suggested_pbs_10x = max(0.0, (x["NaCl_mM_added"] - 100) * 0.5) # placeholder mapping
|
| 54 |
+
rec = {
|
| 55 |
+
"recommended": {
|
| 56 |
+
"target_pH": round(x["target_pH"], 2),
|
| 57 |
+
"PBS_10x_uL_per_mL": round(suggested_pbs_10x, 1),
|
| 58 |
+
"temp_incubation_C": x["temp_incubation_C"]
|
| 59 |
+
},
|
| 60 |
+
"predictions": {
|
| 61 |
+
"P_gel": round(pgel, 3),
|
| 62 |
+
"t_half_min": round(thalf, 1),
|
| 63 |
+
"utility": round(util, 3)
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
print(json.dumps(rec, indent=2))
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
ap = argparse.ArgumentParser()
|
| 70 |
+
ap.add_argument("--json", type=str, required=True)
|
| 71 |
+
main(ap.parse_args())
|
src/train_baseline.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import argparse, os, joblib, numpy as np, pandas as pd
|
| 3 |
+
from sklearn.model_selection import train_test_split
|
| 4 |
+
from sklearn.compose import ColumnTransformer
|
| 5 |
+
from sklearn.preprocessing import StandardScaler
|
| 6 |
+
from sklearn.impute import SimpleImputer
|
| 7 |
+
from sklearn.pipeline import Pipeline
|
| 8 |
+
from sklearn.linear_model import LogisticRegression
|
| 9 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 10 |
+
from sklearn.calibration import CalibratedClassifierCV
|
| 11 |
+
from sklearn.metrics import roc_auc_score, average_precision_score, f1_score, r2_score, mean_absolute_error
|
| 12 |
+
|
| 13 |
+
DEFAULT_FEATURES = [
|
| 14 |
+
"ecm_total_protein_mgml","pre_pH","pre_conductivity_mS","temp_incubation_C",
|
| 15 |
+
"uv_ratio_A220_A280","sds_smear_index","sds_alpha_ratio",
|
| 16 |
+
"DMEM_percent","PBS_10x_uL_per_mL","NaCl_mM_added","CaCl2_mM_added",
|
| 17 |
+
"target_pH",
|
| 18 |
+
# Advanced biochemical assays (optional)
|
| 19 |
+
"hydroxyproline_mgml","dmmB_GAG_ugml","viscosity_proxy_sec",
|
| 20 |
+
# Pre-gel viscosity (Scientific Reports 2019) (optional)
|
| 21 |
+
"pre_gel_viscosity_mPas","pre_gel_viscosity_temp_C","shear_rate_s_minus1",
|
| 22 |
+
# Turbidity/gelation kinetics (Scientific Reports 2019, MDPI 2021) (optional)
|
| 23 |
+
"turbidity_lag_time_min","turbidity_t_half_min","turbidity_slope_per_min",
|
| 24 |
+
# Viscoelastic/rheological properties (Saldin et al. 2016, Brazdaru et al. 2015) (optional)
|
| 25 |
+
"storage_modulus_G_prime_Pa","loss_modulus_G_double_prime_Pa","tan_delta",
|
| 26 |
+
# Residual contaminants (cornea ECM study 2019) (optional)
|
| 27 |
+
"sds_residual_ppm","detergent_residual_binary","cytotoxicity_score_0to3",
|
| 28 |
+
# Micro-DSC parameters (optional)
|
| 29 |
+
"dsc_onset_T_C","dsc_peak_T_C","dsc_delta_H_J_g",
|
| 30 |
+
# Circular Dichroism parameters (optional)
|
| 31 |
+
"cd_molar_ellipticity_222nm_mdeg","cd_helix_percent",
|
| 32 |
+
# FTIR parameters (optional)
|
| 33 |
+
"ftir_amide3_1450_ratio",
|
| 34 |
+
# Additional residual contaminants (optional)
|
| 35 |
+
"dna_residual_ng_mg","endotoxin_residual_EU_mg","protease_residual_U_mg",
|
| 36 |
+
# Swelling ratio parameters (optional)
|
| 37 |
+
"swelling_ratio_Q","gel_fresh_weight_mg","gel_swollen_weight_mg","gel_dry_weight_mg",
|
| 38 |
+
# Enzymatic degradation parameters (optional)
|
| 39 |
+
"enzymatic_degradation_t_half_min","collagenase_concentration_U_mL",
|
| 40 |
+
# Diffusion/FRAP parameters (optional)
|
| 41 |
+
"diffusion_coefficient_um2_s","frap_t_half_s","probe_radius_um",
|
| 42 |
+
# Quality control metrics (optional)
|
| 43 |
+
"gel_strength_score_0to3","syneresis_binary"
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
TARGET_CLS = "gel_binary"
|
| 47 |
+
TARGET_REG = "time_to_halfmax_min"
|
| 48 |
+
|
| 49 |
+
def load_dataset(path):
|
| 50 |
+
df = pd.read_csv(path)
|
| 51 |
+
df_cls = df.dropna(subset=[TARGET_CLS]) if TARGET_CLS in df.columns else pd.DataFrame()
|
| 52 |
+
df_reg = df.dropna(subset=[TARGET_REG, TARGET_CLS]) if (TARGET_REG in df.columns and TARGET_CLS in df.columns) else pd.DataFrame()
|
| 53 |
+
return df, df_cls, df_reg
|
| 54 |
+
|
| 55 |
+
def build_classifier(numeric_features):
|
| 56 |
+
pre = ColumnTransformer([("num", Pipeline([("imp", SimpleImputer(strategy="median")),
|
| 57 |
+
("sc", StandardScaler())]), numeric_features)])
|
| 58 |
+
base = LogisticRegression(max_iter=2000, class_weight="balanced", solver="lbfgs")
|
| 59 |
+
pipe = Pipeline([("pre", pre), ("clf", base)])
|
| 60 |
+
clf = CalibratedClassifierCV(pipe, method="isotonic", cv=3)
|
| 61 |
+
return clf
|
| 62 |
+
|
| 63 |
+
def build_regressor(numeric_features):
|
| 64 |
+
pre = ColumnTransformer([("num", Pipeline([("imp", SimpleImputer(strategy="median")),
|
| 65 |
+
("sc", StandardScaler())]), numeric_features)])
|
| 66 |
+
reg = RandomForestRegressor(n_estimators=300, random_state=42, n_jobs=-1)
|
| 67 |
+
pipe = Pipeline([("pre", pre), ("reg", reg)])
|
| 68 |
+
return pipe
|
| 69 |
+
|
| 70 |
+
def main(args):
|
| 71 |
+
os.makedirs("models", exist_ok=True)
|
| 72 |
+
df, df_cls, df_reg = load_dataset(args.csv)
|
| 73 |
+
|
| 74 |
+
features = [c for c in DEFAULT_FEATURES if c in df.columns]
|
| 75 |
+
if not features:
|
| 76 |
+
raise SystemExit("No expected feature columns found. Please include DEFAULT_FEATURES in your CSV.")
|
| 77 |
+
|
| 78 |
+
# Classification
|
| 79 |
+
if len(df_cls) >= 4:
|
| 80 |
+
Xc, yc = df_cls[features], df_cls[TARGET_CLS].astype(int)
|
| 81 |
+
try:
|
| 82 |
+
Xc_tr, Xc_te, yc_tr, yc_te = train_test_split(Xc, yc, test_size=0.25, stratify=yc, random_state=42)
|
| 83 |
+
except ValueError:
|
| 84 |
+
Xc_tr, Xc_te, yc_tr, yc_te = train_test_split(Xc, yc, test_size=0.25, random_state=42)
|
| 85 |
+
clf = build_classifier(features)
|
| 86 |
+
clf.fit(Xc_tr, yc_tr)
|
| 87 |
+
proba = clf.predict_proba(Xc_te)[:,1]
|
| 88 |
+
auc = roc_auc_score(yc_te, proba) if len(np.unique(yc_te))>1 else np.nan
|
| 89 |
+
ap = average_precision_score(yc_te, proba) if len(np.unique(yc_te))>1 else np.nan
|
| 90 |
+
f1 = f1_score(yc_te, (proba>=0.5).astype(int)) if len(np.unique(yc_te))>1 else np.nan
|
| 91 |
+
print(f"[Classifier] ROC-AUC={auc:.3f} AP={ap:.3f} F1@0.5={f1:.3f}")
|
| 92 |
+
joblib.dump({"model": clf, "features": features}, "models/gel_classifier.joblib")
|
| 93 |
+
else:
|
| 94 |
+
print("Not enough rows to train classifier (need >=4). Skipping.")
|
| 95 |
+
|
| 96 |
+
# Regression on positive gels
|
| 97 |
+
if len(df_reg) >= 6:
|
| 98 |
+
df_reg_ok = df_reg[df_reg[TARGET_CLS]==1].copy()
|
| 99 |
+
if len(df_reg_ok) >= 5:
|
| 100 |
+
Xr, yr = df_reg_ok[features], df_reg_ok[TARGET_REG].astype(float)
|
| 101 |
+
Xr_tr, Xr_te, yr_tr, yr_te = train_test_split(Xr, yr, test_size=0.25, random_state=42)
|
| 102 |
+
reg = build_regressor(features)
|
| 103 |
+
reg.fit(Xr_tr, yr_tr)
|
| 104 |
+
pred = reg.predict(Xr_te)
|
| 105 |
+
r2 = r2_score(yr_te, pred)
|
| 106 |
+
mae = mean_absolute_error(yr_te, pred)
|
| 107 |
+
print(f"[Regressor] R2={r2:.3f} MAE={mae:.2f} min")
|
| 108 |
+
joblib.dump({"model": reg, "features": features}, "models/thalf_regressor.joblib")
|
| 109 |
+
else:
|
| 110 |
+
print("Not enough positive gels to train regressor (need >=5). Skipping.")
|
| 111 |
+
else:
|
| 112 |
+
print("Not enough rows to consider regression (need >=6). Skipping.")
|
| 113 |
+
|
| 114 |
+
print("Done.")
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
ap = argparse.ArgumentParser()
|
| 117 |
+
ap.add_argument("--csv", type=str, default="data/ecm_gelation_dataset_template.csv")
|
| 118 |
+
main(ap.parse_args())
|