429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652 | def run_one_model(
model_name: str,
plasmid: str,
data_df: pd.DataFrame,
fitted: dict,
bounds: dict,
sim_func,
obs_y_col="fc.cherry",
time_col="time",
n_sobol_base=ARGS.sobol_base,
n_boot=ARGS.n_boot,
seed=ARGS.seed
):
"""
Run Sobol sensitivity analysis and bootstrap UQ for one model/plasmid.
Args:
model_name (str): Model name ("REV" or "KD").
plasmid (str): Plasmid identifier.
data_df (pd.DataFrame): Observed timecourse data for the plasmid.
fitted (dict): Fitted parameter center values and SEs.
bounds (dict): Parameter bounds for SALib.
sim_func (callable): Function sim(pars_draw)->df(time,R,Y) to simulate the model.
obs_y_col (str): Column name for observed output in data_df.
time_col (str): Column name for time in data_df.
n_sobol_base (int): Base sample size for Sobol analysis.
n_boot (int): Number of bootstrap samples.
seed (int): Random seed for reproducibility.
Returns:
sobol_df (pd.DataFrame): Sobol sensitivity indices per metric.
boot_df (pd.DataFrame): Bootstrap sampled parameters and metrics.
"""
rng = np.random.default_rng(seed)
# ----------------------------------------------------------
# Observed mean trajectory (for predictive band overlay)
# ----------------------------------------------------------
mean_obs = (data_df.groupby(time_col, as_index=False)[obs_y_col].mean()
.sort_values(time_col))
t_obs = mean_obs[time_col].to_numpy(float)
y_obs = mean_obs[obs_y_col].to_numpy(float)
# Standard time grid for predictive bands
t_grid = np.arange(0.0, 150.0 + 0.05 / 2, 0.05)
# ----------------------------------------------------------
# A) SALib Sobol sensitivity on metrics
# ----------------------------------------------------------
param_names = list(bounds.keys())
problem = {
"num_vars": len(param_names),
"names": param_names,
"bounds": [list(bounds[p]) for p in param_names],
}
# Saltelli sampling
X = saltelli.sample(problem, n_sobol_base, calc_second_order=False)
# Evaluate model
metrics_list = []
for row in X:
pars = dict(zip(param_names, row))
# Simulate with these params
with quiet():
sim = sim_func(pars)
if sim is None or sim.empty:
metrics_list.append({k: np.nan for k in ["dynamic_range", "t50", "t10_90", "overshoot", "auc", "y_end"]})
continue
# Interpolate to a consistent grid for stable metrics
tt = sim["time"].to_numpy(float)
yy = sim["Y"].to_numpy(float)
# sanitize
m = np.isfinite(tt) & np.isfinite(yy)
tt, yy = tt[m], yy[m]
if tt.size < 5:
metrics_list.append({k: np.nan for k in ["dynamic_range", "t50", "t10_90", "overshoot", "auc", "y_end"]})
continue
# Compute metrics on (tt,yy)
metrics_list.append(metric_summary(yy, tt))
metrics_df = pd.DataFrame(metrics_list)
metrics_df.insert(0, "plasmid", plasmid)
metrics_df.insert(0, "model", model_name)
metrics_df.to_csv(OUT_PARAM / f"{model_name}_{plasmid}_sobol_samples_metrics.csv", index=False)
# Sobol indices per metric
sobol_rows = []
for metric in ["dynamic_range", "t50", "t10_90", "overshoot", "auc", "y_end"]:
Y = metrics_df[metric].to_numpy(float)
ok = np.isfinite(Y)
if ok.sum() < max(50, 0.3 * len(Y)):
continue
Si = sobol.analyze(problem, Y[ok], calc_second_order=False, print_to_console=False)
for i, p in enumerate(param_names):
sobol_rows.append({
"model": model_name,
"plasmid": plasmid,
"metric": metric,
"param": p,
"S1": float(Si["S1"][i]),
"S1_conf": float(Si["S1_conf"][i]),
"ST": float(Si["ST"][i]),
"ST_conf": float(Si["ST_conf"][i]),
})
sobol_df = pd.DataFrame(sobol_rows)
sobol_df.to_csv(OUT_PARAM / f"{model_name}_{plasmid}_sobol_indices.csv", index=False)
# Plot Sobol ST (total-order) per metric
if not sobol_df.empty:
for metric in sobol_df["metric"].unique():
sub = sobol_df.query("metric == @metric").sort_values("ST", ascending=True)
plt.figure(figsize=(7, 4))
plt.barh(sub["param"], sub["ST"])
plt.xlabel("Sobol ST (total-order)")
plt.title(f"{model_name} {plasmid} – Sensitivity (metric={metric})")
saveplot(OUT_PLOTS / f"{model_name}_{plasmid}_sobol_ST_{metric}.pdf")
# ----------------------------------------------------------
# B) Bootstrap parameter draws + predictive bands
# ----------------------------------------------------------
boot_rows = []
boot_curves = []
# Choose bootstrap scheme:
# - half-times: normal(mean, se) if available
# - K,n: lognormal around fitted with cv=0.20
# - alpha: normal if you have per-plasmid spread; else lognormal cv=0.10
# - delay: normal(mean, 0.5h) clipped [0,25]
for b in range(int(n_boot)):
pars_draw = {}
for p in param_names:
c = fitted[p]
se = fitted.get(p + "_se", None)
if p in ("t_up", "t_down"):
pars_draw[p] = bootstrap_params(rng, c, se=se, kind="normal", clip_lo=1e-6)
elif p in ("K", "n"):
pars_draw[p] = bootstrap_params(rng, c, kind="lognormal", cv=0.20, clip_lo=1e-9)
elif p == "alpha":
# often global; keep conservative
pars_draw[p] = bootstrap_params(rng, c, kind="lognormal", cv=0.10, clip_lo=1e-9)
elif p.startswith("delay"):
pars_draw[p] = float(np.clip(rng.normal(loc=float(c), scale=0.5), 0.0, 25.0))
else:
pars_draw[p] = bootstrap_params(rng, c, kind="lognormal", cv=0.20, clip_lo=1e-9)
with quiet():
sim = sim_func(pars_draw)
if sim is None or sim.empty:
continue
tt = sim["time"].to_numpy(float)
yy = sim["Y"].to_numpy(float)
m = np.isfinite(tt) & np.isfinite(yy)
tt, yy = tt[m], yy[m]
if tt.size < 5:
continue
# Interpolate onto t_grid for band aggregation
y_grid = np.interp(t_grid, tt, yy, left=np.nan, right=np.nan)
boot_curves.append(y_grid)
met = metric_summary(yy, tt)
row = {"model": model_name, "plasmid": plasmid, "boot": b, **pars_draw, **met}
boot_rows.append(row)
boot_df = pd.DataFrame(boot_rows)
boot_df.to_csv(OUT_PARAM / f"{model_name}_{plasmid}_bootstrap_params_and_metrics.csv", index=False)
# Parameter histograms
if not boot_df.empty:
for p in param_names:
plt.figure(figsize=(6, 4))
plt.hist(boot_df[p].dropna().to_numpy(float), bins=40)
plt.xlabel(p)
plt.ylabel("count")
plt.title(f"{model_name} {plasmid} – bootstrap parameter distribution")
saveplot(OUT_PLOTS / f"{model_name}_{plasmid}_boot_param_{p}.pdf")
# Metric histograms
for metric in ["dynamic_range", "t50", "t10_90", "overshoot", "auc", "y_end"]:
if metric not in boot_df.columns:
continue
plt.figure(figsize=(6, 4))
plt.hist(boot_df[metric].dropna().to_numpy(float), bins=40)
plt.xlabel(metric)
plt.ylabel("count")
plt.title(f"{model_name} {plasmid} – bootstrap metric distribution")
saveplot(OUT_PLOTS / f"{model_name}_{plasmid}_boot_metric_{metric}.pdf")
# Predictive bands
if len(boot_curves) > 50:
B = np.vstack(boot_curves) # shape: n_boot x len(t_grid)
qlo = np.nanpercentile(B, 2.5, axis=0)
q50 = np.nanpercentile(B, 50.0, axis=0)
qhi = np.nanpercentile(B, 97.5, axis=0)
band = pd.DataFrame({
"model": model_name,
"plasmid": plasmid,
"time": t_grid,
"Y_q2p5": qlo,
"Y_q50": q50,
"Y_q97p5": qhi,
})
band.to_csv(OUT_PARAM / f"{model_name}_{plasmid}_predictive_band.csv", index=False)
# Plot band + observed mean points
plt.figure(figsize=(7, 4))
plt.fill_between(t_grid, qlo, qhi, alpha=0.3, label="95% predictive band")
plt.plot(t_grid, q50, linewidth=2, label="median prediction")
plt.scatter(t_obs, y_obs, s=18, alpha=0.9, label="observed mean")
plt.xlabel("Time (h)")
plt.ylabel("mCherry (fc.cherry)")
plt.title(f"{model_name} {plasmid} – predictive band vs observed mean")
plt.legend()
saveplot(OUT_PLOTS / f"{model_name}_{plasmid}_predictive_band_overlay.pdf")
return sobol_df, boot_df
|