Skip to content

gp3bayespy.sensitivity

31 public functions in this module.

← API reference hub

Collect supplied evidence components without generating an adequacy verdict.

Source code in src/gp3bayespy/sensitivity.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
def collect_model_evidence(
    fit: Any = None,
    design: Any = None,
    diagnostics: Any = None,
    posterior: Any = None,
    ppc: Any = None,
    estimands: Any = None,
    loo: Any = None,
    kfold: Any = None,
    sensitivity: Any = None,
    manifest: Any = None,
    compute: Sequence[str] = (),
) -> ModelEvidence:
    """Collect supplied evidence components without generating an adequacy verdict."""
    allowed = {"diagnostics", "posterior", "estimands"}
    requested = tuple(dict.fromkeys(str(value) for value in compute))
    if any(value not in allowed for value in requested):
        raise GP3BayesError("`compute` may contain only diagnostics, posterior, estimands.")
    if requested and fit is None:
        raise GP3BayesError("A gp3bayes `fit` is required for requested computed components.")
    if "diagnostics" in requested and diagnostics is None:
        from .unified_workflow_api import diagnose_model_fit

        diagnostics = diagnose_model_fit(fit)
    if "posterior" in requested and posterior is None:
        from .unified_workflow_api import summarise_model_posterior

        posterior = summarise_model_posterior(fit)
    if "estimands" in requested and estimands is None:
        from .unified_workflow_api import estimate_model_estimands

        estimands = estimate_model_estimands(fit)

    components = {
        "design": design,
        "diagnostics": diagnostics,
        "posterior": posterior,
        "ppc": ppc,
        "estimands": estimands,
        "loo": loo,
        "kfold": kfold,
        "sensitivity": sensitivity,
        "manifest": manifest,
    }
    rows = []
    for name, value in components.items():
        status = "not_supplied" if value is None else _status(value)
        if status == "completed":
            status = "available"
        rows.append({"component": name, "available": value is not None, "status": status})
    family = getattr(fit, "family", None)
    if family is None:
        family = getattr(manifest, "family", None) or getattr(estimands, "family", None)
    return ModelEvidence("0.2", family, fit, components, pd.DataFrame(rows))
Source code in src/gp3bayespy/sensitivity.py
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
def create_model_evidence_report(
    evidence: ModelEvidence, file: str | Path, overwrite: bool = False
) -> str:
    if not isinstance(evidence, ModelEvidence):
        raise GP3BayesError("`evidence` must be created by `collect_model_evidence()`.")
    path = Path(file)
    if not str(path):
        raise GP3BayesError("`file` must be one explicit non-empty path.")
    if path.exists() and not _flag(overwrite, "overwrite"):
        raise GP3BayesError("`file` already exists. Set `overwrite=True` to replace it.")
    if not path.parent.exists():
        raise GP3BayesError("The report parent directory does not exist.")
    lines = [
        "# gp3bayes model evidence report",
        "",
        f"Family: {evidence.family}",
        "",
        "## Evidence inventory",
        "",
    ]
    for row in evidence.component_table.itertuples(index=False):
        detail = f"available ({row.status})" if row.available else "not supplied"
        lines.append(f"- {row.component}: {detail}")
    lines += [
        "",
        "## Interpretation boundary",
        "",
        "This report is an evidence inventory. It does not automatically establish "
        "convergence, posterior adequacy, robustness, causal identification, "
        "substantive validity, or a preferred model.",
    ]
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    return str(path.resolve())

Create an inert, declarative sensitivity-suite plan.

Source code in src/gp3bayespy/sensitivity.py
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
def create_sensitivity_suite_plan(
    prior_scale: bool = False,
    powerscale: bool = False,
    psis_loo: bool = False,
    random_slope_plan: Any = None,
    group_deletion_plan: Any = None,
    alternative_estimands: Mapping[str, Any] | None = None,
    duration_unit: Mapping[str, Any] | None = None,
    prior_scale_args: Mapping[str, Any] | None = None,
    powerscale_args: Mapping[str, Any] | None = None,
    psis_args: Mapping[str, Any] | None = None,
    random_slope_args: Mapping[str, Any] | None = None,
    group_deletion_args: Mapping[str, Any] | None = None,
) -> SensitivityPlan:
    """Create an inert, declarative sensitivity-suite plan."""
    return SensitivityPlan(
        prior_scale={
            "run": _flag(prior_scale, "prior_scale"),
            "args": _mapping(prior_scale_args, "prior_scale_args"),
        },
        powerscale={
            "run": _flag(powerscale, "powerscale"),
            "args": _mapping(powerscale_args, "powerscale_args"),
        },
        psis_loo={"run": _flag(psis_loo, "psis_loo"), "args": _mapping(psis_args, "psis_args")},
        random_slope={
            "plan": random_slope_plan,
            "args": _mapping(random_slope_args, "random_slope_args"),
        },
        group_deletion={
            "plan": group_deletion_plan,
            "args": _mapping(group_deletion_args, "group_deletion_args"),
        },
        alternative_estimands=_mapping(alternative_estimands, "alternative_estimands"),
        duration_unit=None if duration_unit is None else _mapping(duration_unit, "duration_unit"),
    )
Source code in src/gp3bayespy/sensitivity.py
496
497
def estimand_sensitivity_table(x: Any) -> pd.DataFrame:
    return _table_field(x, "table")
Source code in src/gp3bayespy/sensitivity.py
500
501
def group_deletion_sensitivity_table(x: Any) -> pd.DataFrame:
    return _table_field(x, "summary")
Source code in src/gp3bayespy/sensitivity.py
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
def plot_estimand_sensitivity_gg(x: Any):
    d = _frame(x, estimand_sensitivity_table)
    required = {
        "alternative",
        "reference_median",
        "alternative_median",
        "alternative_lower",
        "alternative_upper",
    }
    if not required.issubset(d.columns):
        raise GP3BayesError("Estimand sensitivity summaries are incomplete.")
    plt = _mpl()
    fig, ax = plt.subplots()
    y = np.arange(len(d))
    med = d["alternative_median"].to_numpy(float)
    ax.errorbar(
        med,
        y,
        xerr=[
            med - d["alternative_lower"].to_numpy(float),
            d["alternative_upper"].to_numpy(float) - med,
        ],
        fmt="o",
    )
    ax.axvline(float(d["reference_median"].iloc[0]), linestyle="--")
    ax.set_yticks(y, d["alternative"].astype(str))
    ax.set_title("Estimand sensitivity")
    ax.set_xlabel("Posterior estimand")
    return fig
Source code in src/gp3bayespy/sensitivity.py
747
748
749
750
751
752
753
754
755
756
757
758
def plot_group_deletion_sensitivity(x: Any):
    d = _frame(x, group_deletion_sensitivity_table)
    if not {"omitted_unit", "median_shift"}.issubset(d.columns):
        raise GP3BayesError("Group-deletion sensitivity requires omitted_unit and median_shift.")
    fig = _barh(
        d,
        "median_shift",
        "omitted_unit",
        "Declared group-deletion sensitivity",
        "Posterior median shift",
    )
    return fig
Source code in src/gp3bayespy/sensitivity.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
def plot_powerscale_sensitivity_gg(x: Any):
    d = _frame(x, powerscale_sensitivity_table)
    if {"variable", "prior", "likelihood"}.issubset(d.columns):
        labels = d["variable"].astype(str)
        prior = d["prior"].to_numpy(float)
        likelihood = d["likelihood"].to_numpy(float)
    elif {"component", "alpha", "distance"}.issubset(d.columns):
        labels = d["variable"].fillna("all").astype(str) + ":" + d["component"].astype(str)
        prior = np.nan_to_num(d["distance"].to_numpy(float), nan=0.0)
        likelihood = np.zeros(len(d))
    else:
        raise GP3BayesError("Power-scale sensitivity does not contain plottable columns.")
    plt = _mpl()
    fig, ax = plt.subplots()
    y = np.arange(len(d))
    ax.barh(y - 0.2, prior, height=0.4, label="prior")
    ax.barh(y + 0.2, likelihood, height=0.4, label="likelihood")
    ax.set_yticks(y, labels)
    ax.set_title("Prior and likelihood power-scale sensitivity")
    ax.legend()
    return fig
Source code in src/gp3bayespy/sensitivity.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
def plot_prior_sensitivity(x: Any):
    d = _frame(x, prior_sensitivity_table)
    required = {"scenario", "scale_multiplier", "variable", "standardized_shift"}
    if not required.issubset(d.columns):
        raise GP3BayesError(
            "Prior sensitivity requires scenario, scale_multiplier, variable, standardized_shift."
        )
    plt = _mpl()
    fig, ax = plt.subplots()
    for variable, g in d.groupby("variable", sort=False):
        ax.plot(g["scale_multiplier"], g["standardized_shift"], marker="o", label=str(variable))
    ax.set_title("Declared prior-scale sensitivity")
    ax.set_xlabel("Prior scale multiplier")
    ax.set_ylabel("Absolute standardized posterior-median shift")
    ax.legend()
    return fig
Source code in src/gp3bayespy/sensitivity.py
701
702
703
704
705
706
707
708
709
710
711
712
713
def plot_prior_sensitivity_scenarios(x: Any):
    d = _frame(x, prior_sensitivity_scenario_table)
    if not {"scenario", "maximum_standardized_shift"}.issubset(d.columns):
        raise GP3BayesError(
            "Scenario sensitivity requires scenario and maximum_standardized_shift."
        )
    return _barh(
        d,
        "maximum_standardized_shift",
        "scenario",
        "Prior-sensitivity scenario maxima",
        "Maximum standardized shift",
    )
Source code in src/gp3bayespy/sensitivity.py
761
762
763
764
765
def plot_random_slope_sensitivity(x: Any):
    d = random_slope_sensitivity_table(x) if not isinstance(x, pd.DataFrame) else x
    fig = plot_estimand_sensitivity_gg(d)
    fig.axes[0].set_title("Random-intercept versus random-slope sensitivity")
    return fig
Source code in src/gp3bayespy/sensitivity.py
622
623
624
625
626
def plot_recovery_bias(x: Any):
    d = _frame(x, recovery_parameter_table)
    if not {"variable", "standardized_bias"}.issubset(d.columns):
        raise GP3BayesError("Recovery summaries require variable and standardized_bias.")
    return _barh(d, "standardized_bias", "variable", "Parameter recovery bias", "Standardized bias")
Source code in src/gp3bayespy/sensitivity.py
629
630
631
632
633
def plot_recovery_coverage(x: Any):
    d = _frame(x, recovery_parameter_table)
    if not {"variable", "coverage"}.issubset(d.columns):
        raise GP3BayesError("Recovery summaries require variable and coverage.")
    return _barh(d, "coverage", "variable", "Parameter recovery coverage", "Coverage")
Source code in src/gp3bayespy/sensitivity.py
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
def plot_recovery_estimates(x: Any, variables: Sequence[str] | None = None):
    d = _frame(x, recovery_estimate_table)
    required = {"variable", "truth", "median", "lower", "upper", "repetition"}
    if not required.issubset(d.columns):
        raise GP3BayesError("Recovery estimates do not contain the required columns.")
    if variables is not None:
        d = d[d["variable"].astype(str).isin([str(v) for v in variables])]
    if d.empty:
        raise GP3BayesError("No recovery rows remain after filtering.")
    plt = _mpl()
    fig, ax = plt.subplots()
    for variable, g in d.groupby("variable", sort=False):
        ax.errorbar(
            g["repetition"],
            g["median"],
            yerr=[g["median"] - g["lower"], g["upper"] - g["median"]],
            fmt="o",
            label=str(variable),
        )
        ax.plot(g["repetition"], g["truth"], linestyle="--")
    ax.set_title("Repetition-level parameter recovery")
    ax.set_xlabel("Recovery repetition")
    ax.set_ylabel("Posterior estimate")
    ax.legend()
    return fig
Source code in src/gp3bayespy/sensitivity.py
670
671
672
673
674
675
676
677
678
679
680
def plot_recovery_fit_status(x: Any):
    d = _frame(x, recovery_fit_status_table)
    if not {"diagnostic_status", "completed"}.issubset(d.columns):
        raise GP3BayesError("Recovery fit statuses require diagnostic_status and completed.")
    tab = d.groupby(["diagnostic_status", "completed"], dropna=False).size().unstack(fill_value=0)
    plt = _mpl()
    fig, ax = plt.subplots()
    tab.plot(kind="bar", ax=ax)
    ax.set_title("Recovery-fit completion and diagnostics")
    ax.set_ylabel("Repetitions")
    return fig
Source code in src/gp3bayespy/sensitivity.py
636
637
638
639
640
def plot_recovery_rmse(x: Any):
    d = _frame(x, recovery_parameter_table)
    if not {"variable", "rmse"}.issubset(d.columns):
        raise GP3BayesError("Recovery summaries require variable and rmse.")
    return _barh(d, "rmse", "variable", "Parameter recovery RMSE", "RMSE")
Source code in src/gp3bayespy/sensitivity.py
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
def plot_sbc_coverage_gg(x: Any, variables: Sequence[str] | None = None):
    d = _sbc_plot_data(x, variables)
    if "coverage" in d.columns:
        labels = d.get("parameter", d.get("variable", pd.Series(range(len(d))))).astype(str)
        values = d["coverage"].to_numpy(float)
    else:
        # Rank fractions within central 90% are a descriptive coverage proxy when
        # the Python SBC result records ranks but not interval coverage.
        max_rank = "draws" if "draws" in d.columns else "max_rank"
        scale = (
            d[max_rank].to_numpy(float) if max_rank in d.columns else np.maximum(d["rank"].max(), 1)
        )
        u = d["rank"].to_numpy(float) / np.maximum(scale, 1)
        labels = pd.Series(["central 90%"])
        values = np.array([np.mean((u >= 0.05) & (u <= 0.95))])
    plt = _mpl()
    fig, ax = plt.subplots()
    ax.bar(labels, values)
    ax.set_ylim(0, 1)
    ax.set_title("SBC empirical coverage")
    return fig
Source code in src/gp3bayespy/sensitivity.py
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
def plot_sbc_ecdf_gg(x: Any, variables: Sequence[str] | None = None):
    d = _sbc_plot_data(x, variables)
    rank = "rank"
    max_rank = "draws" if "draws" in d.columns else "max_rank"
    if rank not in d.columns:
        raise GP3BayesError("SBC rank statistics are unavailable.")
    scale = d[max_rank].to_numpy(float) if max_rank in d.columns else np.maximum(d[rank].max(), 1)
    u = np.sort(d[rank].to_numpy(float) / np.maximum(scale, 1))
    ecdf = np.arange(1, len(u) + 1) / len(u)
    plt = _mpl()
    fig, ax = plt.subplots()
    ax.plot(u, ecdf)
    ax.plot([0, 1], [0, 1], linestyle="--")
    ax.set_title("SBC ECDF diagnostic")
    return fig
Source code in src/gp3bayespy/sensitivity.py
803
804
805
806
807
808
809
810
811
812
813
814
815
816
def plot_sbc_rank_gg(x: Any, variables: Sequence[str] | None = None):
    d = _sbc_plot_data(x, variables)
    rank = "rank"
    max_rank = "draws" if "draws" in d.columns else "max_rank"
    if rank not in d.columns:
        raise GP3BayesError("SBC rank statistics are unavailable.")
    scale = d[max_rank].to_numpy(float) if max_rank in d.columns else np.maximum(d[rank].max(), 1)
    u = d[rank].to_numpy(float) / np.maximum(scale, 1)
    plt = _mpl()
    fig, ax = plt.subplots()
    ax.hist(u, bins=min(10, max(3, len(u) // 2)))
    ax.set_title("SBC rank fractions")
    ax.set_xlabel("Rank fraction")
    return fig
Source code in src/gp3bayespy/sensitivity.py
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
def plot_sbc_simulated_vs_estimated_gg(x: Any, variables: Sequence[str] | None = None):
    d = _sbc_plot_data(x, variables)
    pairs = next(
        (
            (a, b)
            for a, b in (("simulated", "estimated"), ("truth", "median"), ("value", "estimate"))
            if a in d.columns and b in d.columns
        ),
        None,
    )
    plt = _mpl()
    fig, ax = plt.subplots()
    if pairs is None:
        if "rank" not in d.columns:
            raise GP3BayesError("SBC simulated-versus-estimated statistics are unavailable.")
        xvals = np.arange(1, len(d) + 1)
        yvals = d["rank"].to_numpy(float)
        ax.scatter(xvals, yvals)
        ax.set_xlabel("SBC record")
        ax.set_ylabel("Rank")
    else:
        ax.scatter(d[pairs[0]], d[pairs[1]])
        lo = min(float(d[pairs[0]].min()), float(d[pairs[1]].min()))
        hi = max(float(d[pairs[0]].max()), float(d[pairs[1]].max()))
        ax.plot([lo, hi], [lo, hi], linestyle="--")
        ax.set_xlabel("Simulated")
        ax.set_ylabel("Estimated")
    ax.set_title("SBC simulated versus estimated")
    return fig
Source code in src/gp3bayespy/sensitivity.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
def powerscale_sensitivity_table(x: Any) -> pd.DataFrame:
    if isinstance(x, pd.DataFrame):
        return x.copy()
    raw = getattr(x, "raw", None)
    if raw is None and isinstance(x, Mapping):
        raw = x.get("raw")
    if raw is None:
        # The Python priorsense adaptation returns a DataFrame directly.
        try:
            return pd.DataFrame(x).copy()
        except Exception as exc:
            raise GP3BayesError("Could not convert the power-scale sensitivity result.") from exc
    try:
        return pd.DataFrame(raw).copy()
    except Exception as exc:
        raise GP3BayesError("Could not convert the power-scale sensitivity result.") from exc
Source code in src/gp3bayespy/sensitivity.py
492
493
def prior_sensitivity_scenario_table(x: Any) -> pd.DataFrame:
    return _table_field(x, "scenario_status")
Source code in src/gp3bayespy/sensitivity.py
488
489
def prior_sensitivity_table(x: Any) -> pd.DataFrame:
    return _table_field(x, "comparison")
Source code in src/gp3bayespy/sensitivity.py
504
505
506
507
508
509
510
def random_slope_sensitivity_table(x: Any) -> pd.DataFrame:
    comparison = getattr(x, "comparison", None)
    if comparison is None and isinstance(x, Mapping):
        comparison = x.get("comparison")
    if comparison is None:
        raise GP3BayesError("The random-slope object has no valid estimand comparison.")
    return estimand_sensitivity_table(comparison)
Source code in src/gp3bayespy/sensitivity.py
480
481
def recovery_estimate_table(x: Any) -> pd.DataFrame:
    return _table_field(x, "estimates")
Source code in src/gp3bayespy/sensitivity.py
484
485
def recovery_fit_status_table(x: Any) -> pd.DataFrame:
    return _table_field(x, "fit_status")
Source code in src/gp3bayespy/sensitivity.py
476
477
def recovery_parameter_table(x: Any) -> pd.DataFrame:
    return _table_field(x, "parameter_summary")

Run only sensitivity components explicitly enabled in plan.

Source code in src/gp3bayespy/sensitivity.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def run_sensitivity_suite(
    fit: Any,
    plan: SensitivityPlan | None = None,
    reference_estimand: Any = None,
    stop_on_error: bool = False,
) -> SensitivitySuite:
    """Run only sensitivity components explicitly enabled in ``plan``."""
    family = _family(fit)
    if plan is None:
        plan = create_sensitivity_suite_plan()
    if not isinstance(plan, SensitivityPlan):
        raise GP3BayesError("`plan` must be created by `create_sensitivity_suite_plan()`.")
    stop = _flag(stop_on_error, "stop_on_error")
    results: dict[str, Any] = {}

    if bool(plan.prior_scale["run"]):
        function: Any
        if family == "binary":
            from .binary import assess_binary_prior_sensitivity as function
        else:
            from .duration import (
                assess_duration_prior_sensitivity as function,  # type: ignore[assignment]
            )
        results["prior_scale"] = _safe_call(
            function, {"fit": fit, **dict(plan.prior_scale["args"])}, stop
        )

    if bool(plan.powerscale["run"]):
        from .advanced_optional_workflows import assess_powerscaled_sensitivity

        results["powerscale"] = _safe_call(
            assess_powerscaled_sensitivity,
            {"fit": fit, **dict(plan.powerscale["args"])},
            stop,
        )

    if bool(plan.psis_loo["run"]):
        from .advanced_optional_workflows import compute_psis_loo

        results["psis_loo"] = _safe_call(
            compute_psis_loo, {"fit": fit, **dict(plan.psis_loo["args"])}, stop
        )

    if plan.random_slope["plan"] is not None:
        from .specification_closure import run_random_slope_sensitivity

        results["random_slope"] = _safe_call(
            run_random_slope_sensitivity,
            {"plan": plan.random_slope["plan"], **dict(plan.random_slope["args"])},
            stop,
        )

    if plan.group_deletion["plan"] is not None:
        from .specification_closure import run_group_deletion_sensitivity

        results["group_deletion"] = _safe_call(
            run_group_deletion_sensitivity,
            {"plan": plan.group_deletion["plan"], **dict(plan.group_deletion["args"])},
            stop,
        )

    if plan.alternative_estimands:
        from .specification_closure import compare_estimand_sensitivity

        if reference_estimand is None:
            from .unified_workflow_api import estimate_model_estimands

            try:
                reference_estimand = estimate_model_estimands(fit)
            except Exception as exc:
                if stop:
                    raise
                reference_estimand = SuiteError("error", str(exc))
        if not isinstance(reference_estimand, SuiteError):
            results["estimand_alternatives"] = _safe_call(
                compare_estimand_sensitivity,
                {"reference": reference_estimand, "alternatives": plan.alternative_estimands},
                stop,
            )

    if plan.duration_unit is not None:
        required = {"estimand", "multiplier"}
        if not required.issubset(plan.duration_unit):
            raise GP3BayesError("`duration_unit` must contain `estimand` and `multiplier`.")
        if reference_estimand is None:
            from .unified_workflow_api import estimate_model_estimands

            reference_estimand = _safe_call(estimate_model_estimands, {"fit": fit}, stop)
        from .specification_closure import audit_duration_unit_invariance

        if not isinstance(reference_estimand, SuiteError):
            results["duration_unit"] = _safe_call(
                audit_duration_unit_invariance,
                {
                    "reference": reference_estimand,
                    "converted": plan.duration_unit["estimand"],
                    "multiplier": plan.duration_unit["multiplier"],
                    "tolerance": plan.duration_unit.get("tolerance", 0.02),
                },
                stop,
            )

    statuses = {name: _status(value) for name, value in results.items()}
    if any(value in {"error", "fail"} for value in statuses.values()) or any(
        value in {"review", "warn", "not_assessed"} for value in statuses.values()
    ):
        overall = "review"
    elif statuses:
        overall = "completed"
    else:
        overall = "not_run"
    table = pd.DataFrame(
        [{"component": name, "status": value} for name, value in statuses.items()],
        columns=["component", "status"],
    )
    return SensitivitySuite("0.2", family, overall, fit, plan, reference_estimand, results, table)
Source code in src/gp3bayespy/sensitivity.py
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
def sbc_overview_table(x: Any) -> pd.DataFrame:
    from .advanced_optional_workflows import SBCResult

    stats = sbc_stats_table(x)
    if isinstance(x, SBCResult):
        plan = x.plan
        variable_col = (
            "parameter"
            if "parameter" in stats.columns
            else "variable"
            if "variable" in stats.columns
            else None
        )
        n_variables = stats[variable_col].astype(str).nunique() if variable_col else np.nan
        return pd.DataFrame(
            [
                {
                    "status": "completed" if not x.simulations.empty else "not_run",
                    "family": getattr(plan.specification, "family", None),
                    "backend": plan.backend,
                    "simulations": plan.n_sims,
                    "variables_recorded": n_variables,
                    "diagnostics_inspected": not x.ranks.empty,
                    "calibration_established": False,
                }
            ]
        )
    plan = getattr(x, "plan", None)  # type: ignore[assignment]
    if plan is None and isinstance(x, Mapping):
        plan = x.get("plan", {})

    def take(name: str, default: Any = None) -> Any:
        return (
            plan.get(name, default) if isinstance(plan, Mapping) else getattr(plan, name, default)
        )

    variable_col = next((name for name in ("variable", "parameter") if name in stats.columns), None)
    n_variables = stats[variable_col].astype(str).nunique() if variable_col else np.nan
    status = getattr(x, "status", None) if not isinstance(x, Mapping) else x.get("status")
    inspected = (
        getattr(x, "diagnostics_inspected", None)
        if not isinstance(x, Mapping)
        else x.get("diagnostics_inspected")
    )
    return pd.DataFrame(
        [
            {
                "status": status,
                "family": take("family"),
                "backend": take("backend"),
                "simulations": take("n_sims"),
                "variables_recorded": n_variables,
                "diagnostics_inspected": inspected,
                "calibration_established": False,
            }
        ]
    )
Source code in src/gp3bayespy/sensitivity.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def sbc_stats_table(x: Any) -> pd.DataFrame:
    from .advanced_optional_workflows import SBCResult

    if isinstance(x, SBCResult):
        if not x.ranks.empty:
            return x.ranks.copy()
        return x.simulations.copy()
    raw = getattr(x, "raw", None)
    if raw is None and isinstance(x, Mapping):
        raw = x.get("raw")
    stats = raw.get("stats") if isinstance(raw, Mapping) else None
    if stats is None:
        raise GP3BayesError("The SBC result does not expose tabular statistics.")
    return pd.DataFrame(stats).copy()
Source code in src/gp3bayespy/sensitivity.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def summarise_sensitivity_suite(x: SensitivitySuite) -> pd.DataFrame:
    if not isinstance(x, SensitivitySuite):
        raise GP3BayesError("`x` must be a gp3bayes sensitivity suite.")
    if x.component_status.empty:
        return pd.DataFrame(columns=["component", "status", "detail"])
    rows = []
    for row in x.component_status.itertuples(index=False):
        result = x.results[str(row.component)]
        if isinstance(result, SuiteError):
            detail = result.message
        else:
            detail = getattr(result, "interpretation", type(result).__name__)
        rows.append({"component": row.component, "status": row.status, "detail": str(detail)})
    return pd.DataFrame(rows)