Skip to content

Public functions

Module-level test function

questvar._test.test

test(data, cond_1, cond_2, **kwargs)

Quick one-off equivalence test without instantiating QuestVar.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Input data.

required
cond_1 list of str or list of int

Column names or indices for each condition.

required
cond_2 list of str or list of int

Column names or indices for each condition.

required
**kwargs Any

Passed to TestConfig (cv_thr, p_thr, df_thr, eq_thr, ...).

{}

Returns:

Type Description
TestResults

Raises:

Type Description
ValueError

If cond_1 or cond_2 have fewer than 2 columns, share columns, or reference missing columns.

Examples:

>>> import questvar as qv
>>> import polars as pl
>>> df = pl.read_csv("data.csv")
>>> result = qv.test(df, cond_1=["A1", "A2"], cond_2=["B1", "B2"])
>>> print(result.summary())
Source code in src/questvar/_test.py
def test(
    data: pl.DataFrame | np.ndarray,
    cond_1: list[str] | list[int],
    cond_2: list[str] | list[int],
    **kwargs: Any,
) -> TestResults:
    """Quick one-off equivalence test without instantiating QuestVar.

    Parameters
    ----------
    data : pl.DataFrame or np.ndarray
        Input data.
    cond_1, cond_2 : list of str or list of int
        Column names or indices for each condition.
    **kwargs
        Passed to TestConfig (cv_thr, p_thr, df_thr, eq_thr, ...).

    Returns
    -------
    TestResults

    Raises
    ------
    ValueError
        If cond_1 or cond_2 have fewer than 2 columns, share columns,
        or reference missing columns.

    Examples
    --------
    >>> import questvar as qv
    >>> import polars as pl
    >>> df = pl.read_csv("data.csv")
    >>> result = qv.test(df, cond_1=["A1", "A2"], cond_2=["B1", "B2"])
    >>> print(result.summary())
    """
    return QuestVar(**kwargs).test(data, cond_1, cond_2)

Power analysis

questvar.power.run.run_power_analysis

run_power_analysis(
    target_sei=0.8,
    eq_boundaries=None,
    n_reps_list=None,
    cv_mean_list=None,
    cv_thr_list=None,
    n_prts_list=None,
    random_seed=None,
    n_prts=10000,
    n_iterations=10,
    target_power=0.8,
    p_thr=0.05,
    df_thr=1.0,
    cv_thr=1.0,
    correction="fdr",
    int_mu=18.0,
    int_sd=1.0,
    cv_k=2.0,
    cv_theta=0.5,
    n_jobs=None,
)

Run equivalence-focused power analysis over the requested design grid.

The simulation always uses true log2 fold-change = 0, so every simulated feature is truly equivalent. SEI therefore measures equivalent-feature recovery directly, and diff_rate is interpreted as a false-differential classification rate under that null design.

Parameters:

Name Type Description Default
eq_boundaries ndarray

Equivalence boundaries to sweep. Default [0.1, 0.3, 0.5, 0.7, 0.9].

None
n_reps_list list of int

Replicate counts to sweep. Default [3, 5, 10, 20].

None
cv_mean_list list of float

Mean CV values to sweep. Default [0.10, 0.20, 0.30].

None
cv_thr_list list of float

CV thresholds to sweep.

None
n_prts_list list of int

Feature counts to sweep.

None
random_seed int

Base seed for deterministic simulation.

None
n_prts int

Features per iteration. Default 10000.

10000
n_iterations int

Iterations per design point. Default 10.

10
target_sei float

Target Stable Equivalence Index. Default 0.8.

0.8
target_power float

Target power for design search. Default 0.8.

0.8
p_thr float

Adjusted p-value cutoff. Default 0.05.

0.05
df_thr float

Difference boundary. Default 1.0.

1.0
cv_thr float

CV filter threshold. Default 1.0.

1.0
correction str or None

MTC method. Default "fdr".

'fdr'
int_mu float

Mean log-intensity for simulator. Default 18.0.

18.0
int_sd float

Log-intensity SD. Default 1.0.

1.0
cv_k float

Gamma shape for CV. Default 2.0.

2.0
cv_theta float

Gamma scale for CV. Default 0.5.

0.5
n_jobs int

Parallel workers. Default uses half of CPU cores.

None

Returns:

Type Description
PowerResults

Raises:

Type Description
ValueError

If any parameter is out of range (validated by PowerConfig).

Notes

Seed policy and CRN behavior are documented below.

Seed policy (read carefully, Monte Carlo implications below)

Every Monte Carlo iteration within a design point receives its own numpy.random.default_rng(seed) a fresh local Generator that never touches NumPy's global RNG state. The seed value depends only on the iteration index and random_seed:

  • random_seed=None (default): seed = zero-based run_id (0, 1, 2, …). The analysis is fully deterministic even without an explicit seed.
  • random_seed=<int>: seed = random_seed + run_id. Any fixed integer produces bit-identical results across runs (within the same NumPy major version).

Common Random Numbers (CRN) across design points. The seed derivation does not incorporate the design-point identity. Every design point uses the same sequence of seeds (seed_0, seed_1, …) for its MC iterations. This is intentional: it makes the simulated data identical across design points that share the same n_reps, so differences in outcomes are driven purely by parameter changes rather than random noise (variance reduction). Within-design- point iterations remain independent because each gets a different seed, so per-design-point standard errors are valid.

CRN limitation. CRN only applies when n_reps is the same across the compared design points. When n_reps differs, simulate_data requests a differently-shaped array, and NumPy's Ziggurat algorithm consumes the RNG stream in a shape-dependent way, breaking CRN alignment. This does not affect correctness (each design point's Monte Carlo estimate remains valid), it simply removes the variance-reduction benefit for those cross-point comparisons.

Source code in src/questvar/power/run.py
def run_power_analysis(
    target_sei: float = 0.8,
    eq_boundaries: np.ndarray | None = None,
    n_reps_list: list[int] | None = None,
    cv_mean_list: list[float] | None = None,
    cv_thr_list: list[float] | None = None,
    n_prts_list: list[int] | None = None,
    random_seed: int | None = None,
    n_prts: int = 10000,
    n_iterations: int = 10,
    target_power: float = 0.8,
    p_thr: float = 0.05,
    df_thr: float = 1.0,
    cv_thr: float = 1.0,
    correction: str | None = "fdr",
    int_mu: float = 18.0,
    int_sd: float = 1.0,
    cv_k: float = 2.0,
    cv_theta: float = 0.5,
    n_jobs: int | None = None,
) -> PowerResults:
    """Run equivalence-focused power analysis over the requested design grid.

    The simulation always uses true log2 fold-change = 0, so every simulated
    feature is truly equivalent. SEI therefore measures equivalent-feature
    recovery directly, and ``diff_rate`` is interpreted as a false-differential
    classification rate under that null design.

    Parameters
    ----------
    eq_boundaries : ndarray, optional
        Equivalence boundaries to sweep. Default [0.1, 0.3, 0.5, 0.7, 0.9].
    n_reps_list : list of int, optional
        Replicate counts to sweep. Default [3, 5, 10, 20].
    cv_mean_list : list of float, optional
        Mean CV values to sweep. Default [0.10, 0.20, 0.30].
    cv_thr_list : list of float, optional
        CV thresholds to sweep.
    n_prts_list : list of int, optional
        Feature counts to sweep.
    random_seed : int, optional
        Base seed for deterministic simulation.
    n_prts : int
        Features per iteration. Default 10000.
    n_iterations : int
        Iterations per design point. Default 10.
    target_sei : float
        Target Stable Equivalence Index. Default 0.8.
    target_power : float
        Target power for design search. Default 0.8.
    p_thr : float
        Adjusted p-value cutoff. Default 0.05.
    df_thr : float
        Difference boundary. Default 1.0.
    cv_thr : float
        CV filter threshold. Default 1.0.
    correction : str or None
        MTC method. Default "fdr".
    int_mu : float
        Mean log-intensity for simulator. Default 18.0.
    int_sd : float
        Log-intensity SD. Default 1.0.
    cv_k : float
        Gamma shape for CV. Default 2.0.
    cv_theta : float
        Gamma scale for CV. Default 0.5.
    n_jobs : int, optional
        Parallel workers. Default uses half of CPU cores.

    Returns
    -------
    PowerResults

    Raises
    ------
    ValueError
        If any parameter is out of range (validated by PowerConfig).

    Notes
    -----
    Seed policy and CRN behavior are documented below.

    Seed policy (read carefully, Monte Carlo implications below)
    ---------------------------------------------------------------
    Every Monte Carlo iteration within a design point receives its own
    ``numpy.random.default_rng(seed)`` a fresh local ``Generator`` that
    never touches NumPy's global RNG state.  The seed value depends only on
    the iteration index and ``random_seed``:

    * ``random_seed=None`` (default): seed = zero-based ``run_id``
      (0, 1, 2, …).  **The analysis is fully deterministic even without
      an explicit seed.**
    * ``random_seed=<int>``: seed = ``random_seed + run_id``.
      Any fixed integer produces bit-identical results across runs
      (within the same NumPy major version).

    **Common Random Numbers (CRN) across design points.**
    The seed derivation does **not** incorporate the design-point identity.
    Every design point uses the same sequence of seeds (``seed_0, seed_1,
    …``) for its MC iterations.  This is intentional: it makes the
    simulated data identical across design points that share the same
    ``n_reps``, so differences in outcomes are driven purely by parameter
    changes rather than random noise (variance reduction).  Within-design-
    point iterations remain independent because each gets a different seed,
    so per-design-point standard errors are valid.

    **CRN limitation.**  CRN only applies when ``n_reps`` is the same
    across the compared design points.  When ``n_reps`` differs,
    ``simulate_data`` requests a differently-shaped array, and NumPy's
    Ziggurat algorithm consumes the RNG stream in a shape-dependent way,
    breaking CRN alignment.  This does **not** affect correctness (each
    design point's Monte Carlo estimate remains valid), it simply removes
    the variance-reduction benefit for those cross-point comparisons.
    """
    start = time.perf_counter()
    config = PowerConfig(
        n_prts=n_prts,
        n_reps=n_reps_list[0] if n_reps_list else 5,
        cv_mean=cv_mean_list[0] if cv_mean_list else 0.20,
        eq_thr=float(eq_boundaries[0]) if eq_boundaries is not None else 0.5,
        p_thr=p_thr,
        df_thr=df_thr,
        cv_thr=cv_thr,
        correction=correction,
        n_iterations=n_iterations,
        target_sei=target_sei,
        target_power=target_power,
        eq_boundaries=tuple(eq_boundaries)
        if eq_boundaries is not None
        else (0.1, 0.3, 0.5, 0.7, 0.9),
        n_reps_grid=tuple(n_reps_list) if n_reps_list is not None else (3, 5, 10, 20),
        n_prts_grid=tuple(n_prts_list) if n_prts_list is not None else (),
        cv_mean_grid=tuple(cv_mean_list) if cv_mean_list is not None else (0.10, 0.20, 0.30),
        cv_thr_grid=tuple(cv_thr_list) if cv_thr_list is not None else (cv_thr,),
        random_seed=random_seed,
        int_mu=int_mu,
        int_sd=int_sd,
        cv_k=cv_k,
        cv_theta=cv_theta,
        n_jobs=n_jobs,
    )

    if cv_thr_list is None:
        cv_thr_list = list(config.cv_thr_grid)

    design_points = _build_design_points(config, cv_thr_list)

    # One task per design point; all iterations run inside the worker.
    # This avoids creating QuestVar and deserializing PowerConfig once per iteration.
    tasks = [(point, config.to_dict()) for point in design_points]

    if n_jobs is None or n_jobs < 1:
        n_jobs = max(1, mp.cpu_count() // 2)
    if n_jobs == 1:
        batches = [_simulate_design_point(t) for t in tasks]
    else:
        with mp.Pool(n_jobs) as pool:
            batches = pool.map(_simulate_design_point, tasks)

    run_metrics = [m for batch in batches for m in batch]

    design_grid = _summarize_design_grid(run_metrics, config)
    search_results = _solve_design_targets(design_grid, config)
    monotonicity_checks = _collect_monotonicity_checks(design_grid)
    diagnostics = {
        "used_full_pipeline": True,
        "n_design_points": len(design_points),
        "n_runs": len(run_metrics),
        "worker_count": n_jobs if n_jobs is not None else mp.cpu_count(),
        "seed_policy": (
            "CRN: every design point shares the same seed sequence  "
            f"({'run_id' if config.random_seed is None else f'{config.random_seed}+run_id'})  "
            "within-point iterations are independent"
        ),
        "seed_crn": True,
        "seed_crn_limited_to_fixed_n_reps": True,
        "seed_within_point_independent": True,
        "base_random_seed": config.random_seed,
        "monotonicity_checks": monotonicity_checks,
        "n_converged": sum(1 for r in design_grid if r.get("converged", False)),
        "n_not_converged": sum(1 for r in design_grid if not r.get("converged", False)),
        "runtime_seconds": time.perf_counter() - start,
    }

    from questvar._api import PowerResults

    return PowerResults(
        {
            "config": config.to_dict(),
            "design_grid": design_grid,
            "run_metrics": run_metrics,
            "search_results": search_results,
            "diagnostics": diagnostics,
        }
    )

Plot functions

questvar.plot.antlers.antlers

antlers(
    results,
    *,
    config=None,
    ax=None,
    cond_1_label="Condition 1",
    cond_2_label="Condition 2",
    title_add="",
    figsize=(12, 9),
    feature_ids=None,
    protein_ids=None,
    top_n=None,
    label_col="feature_id",
    rasterize_scatters=True,
    show_legend=True,
    show=False,
    save_path=None,
)

Standalone Antler's plot with optional feature annotations.

Parameters:

Name Type Description Default
results TestResults

Results object returned by QuestVar.test().

required
config PlotConfig

Visual design configuration. Defaults to PlotConfig().

None
cond_1_label str

Display names for the two conditions.

'Condition 1'
cond_2_label str

Display names for the two conditions.

'Condition 1'
title_add str

Optional subtitle appended to the title.

''
figsize tuple

Figure dimensions (width, height) in inches.

(12, 9)
feature_ids list of str

Explicit feature IDs to annotate on the plot.

None
protein_ids list of str

Backward-compatible alias for feature_ids.

None
top_n int

Annotate the top N most significant features per status category. Ignored if feature_ids or protein_ids is given.

None
label_col str

Column in results.data to use as annotation text.

'feature_id'
rasterize_scatters bool

Rasterize scatter layers for smaller file sizes.

True
show bool

Call plt.show() after building.

False
save_path str or Path

Save the figure to this path.

None

Returns:

Type Description
Figure

The matplotlib figure. Attaches fig.ax_main for post-hoc access.

Raises:

Type Description
ImportError

If matplotlib is not installed.

ValueError

If both feature_ids and protein_ids are passed.

Source code in src/questvar/plot/antlers.py
def antlers(
    results: TestResults,
    *,
    config: PlotConfig | None = None,
    ax: Any = None,
    cond_1_label: str = "Condition 1",
    cond_2_label: str = "Condition 2",
    title_add: str = "",
    figsize: tuple[float, float] = (12, 9),
    feature_ids: list[str] | None = None,
    protein_ids: list[str] | None = None,
    top_n: int | None = None,
    label_col: str = "feature_id",
    rasterize_scatters: bool = True,
    show_legend: bool = True,
    show: bool = False,
    save_path: str | Path | None = None,
) -> Figure:
    """Standalone Antler's plot with optional feature annotations.

    Parameters
    ----------
    results : TestResults
        Results object returned by ``QuestVar.test()``.
    config : PlotConfig, optional
        Visual design configuration. Defaults to ``PlotConfig()``.
    cond_1_label, cond_2_label : str
        Display names for the two conditions.
    title_add : str
        Optional subtitle appended to the title.
    figsize : tuple
        Figure dimensions ``(width, height)`` in inches.
    feature_ids : list of str, optional
        Explicit feature IDs to annotate on the plot.
    protein_ids : list of str, optional
        Backward-compatible alias for ``feature_ids``.
    top_n : int, optional
        Annotate the top N most significant features per status category.
        Ignored if ``feature_ids`` or ``protein_ids`` is given.
    label_col : str
        Column in ``results.data`` to use as annotation text.
    rasterize_scatters : bool
        Rasterize scatter layers for smaller file sizes.
    show : bool
        Call ``plt.show()`` after building.
    save_path : str or Path, optional
        Save the figure to this path.

    Returns
    -------
    Figure
        The matplotlib figure. Attaches ``fig.ax_main`` for post-hoc access.

    Raises
    ------
    ImportError
        If matplotlib is not installed.
    ValueError
        If both feature_ids and protein_ids are passed.
    """
    try:
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError(
            "Matplotlib is required for plotting. "
            "Install it with: pip install questvar[plot] or pip install matplotlib"
        ) from None

    if feature_ids is not None and protein_ids is not None:
        raise ValueError("Parameters 'feature_ids' and 'protein_ids' are aliases. Pass only one.")

    selected_feature_ids = feature_ids if feature_ids is not None else protein_ids

    pc = config or PlotConfig()

    cfg = results.config
    p_thr = float(cfg.p_thr)
    eq_thr = float(cfg.eq_thr)
    df_thr = float(cfg.df_thr)

    data = results.data

    log2fc = data["log2fc"].to_numpy().astype(float)
    df_adjp = data["df_adjp"].to_numpy().astype(float)
    eq_adjp_arr = data["eq_adjp"].to_numpy().astype(float)
    status_int = data["status"].to_numpy().astype(int)

    # Build signed log10 y-axis.
    # P-values at exactly zero would produce +inf in -log10 and break
    # downstream sorting.  If the input data is realistic, no p-value
    # should reach true zero, but guard against degenerate input by
    # replacing exactly-zero p-values with the next representable value.
    _safe_p = np.where(df_adjp <= 0, np.nextafter(0, 1, dtype=np.float64), df_adjp)
    _safe_q = np.where(eq_adjp_arr <= 0, np.nextafter(0, 1, dtype=np.float64), eq_adjp_arr)
    _log_eq = np.log10(_safe_q)
    _log_df = -np.log10(_safe_p)
    antler_y = np.where(np.abs(log2fc) < eq_thr, _log_eq, _log_df)

    # String status labels
    status_str = np.where(
        status_int == 1,
        "Equivalent",
        np.where(
            (status_int == -1) & (log2fc > 0),
            "Upregulated",
            np.where((status_int == -1) & (log2fc <= 0), "Downregulated", "Unexplained"),
        ),
    )

    # Annotation labels
    label_arr = data[label_col].to_numpy() if label_col in data.columns else np.full(len(data), "")

    # Figure
    is_external_ax = ax is not None
    if not is_external_ax:
        fig, _ax = plt.subplots(figsize=figsize, facecolor=pc.fig_facecolor)
        fig.ax_main = _ax  # type: ignore[attr-defined]
        ax = _ax
    else:
        fig = ax.figure
    ax.set_facecolor(pc.ax_facecolor)

    # Scatter order from PlotConfig
    scatter_order = [s for s in pc.status_order if s != "Excluded"]

    for st in scatter_order:
        mask = status_str == st
        if mask.sum() > 0:
            ax.scatter(
                log2fc[mask],
                antler_y[mask],
                c=pc.status_colors.get(st, "#cccccc"),
                label=st,
                s=45,
                edgecolor="white",
                linewidth=0.3,
                alpha=0.85,
                rasterized=rasterize_scatters,
                zorder=5,
            )

    # Axis limits with padding
    vx = log2fc[~np.isnan(log2fc)]
    vy = antler_y[~np.isnan(antler_y)]
    if len(vx) > 0:
        xabs = float(np.max(np.abs(vx)))
        xoff = xabs * 0.15 if xabs > 0 else 1.0
        ax.set_xlim(-(xabs + xoff), xabs + xoff)

    # Ensure both threshold lines are visible in the y-direction.
    # The equivalence threshold is at log10(p_thr) (negative y),
    # the difference threshold at -log10(p_thr) (positive y).
    thr_y = max(abs(np.log10(max(p_thr, 1e-300))), 0.5)
    if len(vy) > 0:
        ymin = float(vy.min())
        ymax = float(vy.max())
        yoff = (ymax - ymin) * 0.15 if (ymax - ymin) > 0 else 1.0
        ymin = min(ymin - yoff, -thr_y * 1.4)
        ymax = max(ymax + yoff, thr_y * 1.4)
    else:
        ymin, ymax = -thr_y * 1.4, thr_y * 1.4
    ax.set_ylim(ymin, ymax)

    # Threshold lines with labels
    draw_thresholds(ax, pc, p_thr, eq_thr, df_thr, labels=True)

    # Labels and title
    cond_str = f"{cond_1_label} vs {cond_2_label}" if cond_1_label and cond_2_label else ""
    ax.set_xlabel(
        f"log\u2082 Fold Change ({cond_str})" if cond_str else "log\u2082 Fold Change",
        fontsize=pc.label_fontsize + 4,
        color=pc.label_color,
    )
    ax.set_ylabel(
        "log\u2081\u2080 Adj. p-val (equiv.) | \u2212log\u2081\u2080 Adj. p-val (diff.)",
        fontsize=pc.label_fontsize + 4,
        color=pc.label_color,
    )

    if show_legend:
        title = f"Antler\u2019s Plot: {cond_str}" if cond_str else "Antler\u2019s Plot"
        if title_add:
            title += f"\n{title_add}"
        ax.set_title(
            title,
            fontsize=pc.title_fontsize + 2,
            fontweight=pc.title_fontweight,
            color=pc.title_color,
            loc=pc.title_loc,
            pad=15,
        )

    style_ax(ax, pc)

    # Legend (skipped when embedded in summary plot)
    if show_legend:
        handles, labels = ax.get_legend_handles_labels()
        if handles:
            legend = ax.legend(
                fontsize=pc.legend_fontsize + 2,
                frameon=pc.legend_frameon,
                fancybox=False,
                shadow=False,
                framealpha=0.9,
                loc="upper left",
                bbox_to_anchor=(1.02, 1.02),
                title="Status",
                title_fontsize=pc.legend_fontsize + 3,
            )
            legend.get_title().set_fontweight("bold")

    # Annotations
    if selected_feature_ids is not None or top_n is not None:
        annotate_features(
            ax,
            log2fc,
            antler_y,
            status_int,
            label_arr.tolist(),
            feature_ids=selected_feature_ids,
            top_n=top_n if top_n else (pc.annotate_top_n if selected_feature_ids is None else None),
            pc=pc,
        )

    if not is_external_ax:
        plt.subplots_adjust(right=0.82)
        finalize_plot(fig, save_path=save_path, dpi=pc.dpi, show=show)
    return fig

questvar.plot.power.plot_power

plot_power(
    results,
    *,
    title=None,
    n_reps=None,
    ci=None,
    ci_method="quantile",
    config=None,
    figsize=None,
    save_path=None,
    show=False,
)

Line-plot of power vs equivalence boundary with a CV distribution panel.

Parameters:

Name Type Description Default
results PowerResults

A PowerResults object returned by run_power_analysis.

required
title str | None

Figure title (left-aligned above the main panel). Defaults to "Power Analysis - Equivalence Boundary Sweep".

None
n_reps Sequence[int] | None

Subset of replicate counts to display. None shows all n_reps found in the results.

None
ci float | None

Multiplier for the confidence band: - ci_method="se": half-width as multiple of the standard error of the mean. Overrides PlotConfig.ci_multiplier. - ci_method="quantile": ci=0.90 means 5th-95th percentile band, ci=0.80 means 10th-90th, etc. Default 0.90.

None
ci_method str

"quantile" (default) shades the ci-level percentile range of per-iteration SEI values. "se" shades mean +/- ci * SE.

'quantile'
config PlotConfig | None

Visual design configuration. Defaults to :class:PlotConfig with the built-in transparent settings.

None
save_path str | Path | None

If given, the figure is saved to this path using PlotConfig.dpi.

None

Returns:

Type Description
Figure

The figure. Convenience axes attributes are attached after rendering.

Raises:

Type Description
ImportError

If matplotlib is not installed.

ValueError

If ci_method is not 'quantile' or 'se', or ci is out of range.

Source code in src/questvar/plot/power.py
def plot_power(
    results: PowerResults,
    *,
    title: str | None = None,
    n_reps: Sequence[int] | None = None,
    ci: float | None = None,
    ci_method: str = "quantile",
    config: PlotConfig | None = None,
    figsize: tuple[float, float] | None = None,
    save_path: str | Path | None = None,
    show: bool = False,
) -> Figure:
    """Line-plot of power vs equivalence boundary with a CV distribution panel.

    Parameters
    ----------
    results:
        A ``PowerResults`` object returned by ``run_power_analysis``.
    title:
        Figure title (left-aligned above the main panel). Defaults to
        ``"Power Analysis - Equivalence Boundary Sweep"``.
    n_reps:
        Subset of replicate counts to display. ``None`` shows all n_reps
        found in the results.
    ci:
        Multiplier for the confidence band:
        - ``ci_method="se"``: half-width as multiple of the standard error
          of the mean.  Overrides ``PlotConfig.ci_multiplier``.
        - ``ci_method="quantile"``: ``ci=0.90`` means 5th-95th percentile
          band, ``ci=0.80`` means 10th-90th, etc.  Default 0.90.
    ci_method:
        ``"quantile"`` (default) shades the ``ci``-level percentile range
        of per-iteration SEI values.  ``"se"`` shades ``mean +/- ci * SE``.
    config:
        Visual design configuration. Defaults to :class:`PlotConfig` with
        the built-in transparent settings.
    save_path:
        If given, the figure is saved to this path using ``PlotConfig.dpi``.

    Returns
    -------
    matplotlib.figure.Figure
        The figure. Convenience axes attributes are attached after rendering.

    Raises
    ------
    ImportError
        If matplotlib is not installed.
    ValueError
        If ci_method is not 'quantile' or 'se', or ci is out of range.
    """
    try:
        import matplotlib.pyplot as plt
        from matplotlib.gridspec import GridSpec
        from matplotlib.transforms import blended_transform_factory, offset_copy
    except ImportError:
        raise ImportError(
            "Matplotlib is required for plotting. "
            "Install it with: pip install questvar[plot] or pip install matplotlib"
        ) from None

    pc = config or PlotConfig()

    if ci_method not in ("quantile", "se"):
        raise ValueError(f"Parameter 'ci_method' must be 'quantile' or 'se', got {ci_method!r}.")
    if ci_method == "se":
        ci_mult = ci if ci is not None else pc.ci_multiplier
        if ci_mult < 0:
            raise ValueError(f"Parameter 'ci' must be >= 0, got {ci_mult}")
    else:
        ci_level = ci if ci is not None else 0.90
        if not 0 < ci_level < 1:
            raise ValueError(
                f"Parameter 'ci' must be in (0, 1) for ci_method='quantile', got {ci_level}"
            )

    # ------------------------------------------------------------------
    # Extract lines: n_reps -> [(eq_thr, power, lo, hi), ...]
    # where lo/hi define the shading band.
    # ------------------------------------------------------------------
    joint_rows = [r for r in results.design_grid if r["parameter"] == "eq_thr_n_reps"]
    eq_rows = [r for r in results.design_grid if r["parameter"] == "eq_thr"]

    source_rows = joint_rows if joint_rows else eq_rows
    if not source_rows:
        raise ValueError(
            "PowerResults contains no 'eq_thr' or 'eq_thr_n_reps' rows. "
            "Run power_analysis with at least one eq_thr value."
        )

    available_n_reps = sorted({int(r["n_reps"]) for r in source_rows})
    selected_n_reps = [nr for nr in available_n_reps if n_reps is None or nr in n_reps]

    lines: dict[int, tuple[list[float], list[float], list[float], list[float]]] = {}
    for nr in selected_n_reps:
        pts = []
        for r in source_rows:
            if int(r["n_reps"]) != nr:
                continue
            if ci_method == "quantile":
                target_sei_val = float(r.get("target_sei", 0.80))
                cv_mean_val = float(r.get("cv_mean", 0.20))
                sei_q05 = r.get("sei_q05")
                sei_q95 = r.get("sei_q95")
                if sei_q05 is not None and sei_q95 is not None:
                    lo = _power_from_sei(float(sei_q05), target_sei_val, cv_mean_val)
                    hi = _power_from_sei(float(sei_q95), target_sei_val, cv_mean_val)
                else:
                    lo = hi = r["power"]
            else:
                err = r.get("power_se", 0.0)
                lo = max(0.0, r["power"] - err * ci_mult)
                hi = min(1.0, r["power"] + err * ci_mult)
            pts.append((r["eq_thr"], r["power"], lo, hi))
        pts.sort(key=lambda t: t[0])
        if pts:
            xs, ys, lo_vals, hi_vals = zip(*pts, strict=True)
            lines[nr] = (list(xs), list(ys), list(lo_vals), list(hi_vals))

    if not lines:
        raise ValueError(
            "No power-profile lines remain after applying parameter 'n_reps' filter "
            f"with n_reps={list(n_reps) if n_reps is not None else n_reps}."
        )

    # ------------------------------------------------------------------
    # Pull scalar parameters from config dict
    # ------------------------------------------------------------------
    cfg_dict: dict[str, Any] = results.config if isinstance(results.config, dict) else {}
    cv_mean = float(cfg_dict.get("cv_mean", 0.20))
    cv_k = float(cfg_dict.get("cv_k", 2.0))
    cv_theta = float(cfg_dict.get("cv_theta", 0.5))
    n_prts = cfg_dict.get("n_prts")
    target_power = float(cfg_dict.get("target_power", 0.80))
    target_sei = cfg_dict.get("target_sei")
    correction = cfg_dict.get("correction", "fdr")
    n_iterations = cfg_dict.get("n_iterations")
    p_thr = cfg_dict.get("p_thr")

    # ------------------------------------------------------------------
    # CV distribution sample (gamma, scaled to cv_mean)
    # Fixed seed (0) ensures the visualised CV sample is deterministic
    # across runs.  This is purely a plotting aid, not a statistical
    # computation, so a hardcoded seed is acceptable.
    # ------------------------------------------------------------------
    rng = np.random.default_rng(0)
    cv_raw = rng.gamma(cv_k, cv_theta, pc.cv_sample_size).astype(float)
    cv_sample = cv_raw * cv_mean / cv_raw.mean()

    # ------------------------------------------------------------------
    # Build figure - 1 row x 2 cols; annotation via fig.text
    # ------------------------------------------------------------------
    fig = plt.figure(figsize=figsize or pc.figsize, facecolor=pc.fig_facecolor)
    gs = GridSpec(
        1,
        2,
        figure=fig,
        width_ratios=[pc.main_width_ratio, pc.side_width_ratio],
        wspace=pc.panel_wspace,
    )
    ax_main = fig.add_subplot(gs[0, 0])
    ax_cv = fig.add_subplot(gs[0, 1])

    # Reserve headroom for title + annotation (keeps axes from crowding the top)
    fig.subplots_adjust(top=pc.top_margin)

    # ------------------------------------------------------------------
    # Main panel: one line per n_reps
    # Single replicate: use primary palette colour.
    # Multiple replicates: sample from a sequential cmap so lines form
    # a coherent progression (light-to-dark = fewer-to-more replicates).
    # ------------------------------------------------------------------
    n_lines = len(lines)
    _line_colors: list[Any] = [pc.palette[0]]
    if n_lines > 1:
        _cmap = plt.get_cmap(pc.multi_line_cmap)
        _line_colors = [_cmap(0.35 + 0.55 * i / (n_lines - 1)) for i in range(n_lines)]

    for idx, nr in enumerate(sorted(lines)):
        xvals, yvals, los, his = lines[nr]
        color = _line_colors[idx]

        ax_main.plot(
            xvals,
            yvals,
            color=color,
            linewidth=pc.line_width,
            marker=pc.marker,
            markersize=pc.marker_size,
            label=str(nr),
            zorder=3,
        )
        ax_main.fill_between(xvals, los, his, color=color, alpha=pc.ci_alpha, zorder=2)

    # Ideal reference line at SEI = 1 (power ceiling)
    ax_main.axhline(
        1.0,
        color=pc.ideal_color,
        linewidth=pc.ideal_linewidth,
        linestyle=pc.ideal_linestyle,
        alpha=pc.ideal_alpha,
        label="_nolegend_",
        zorder=4,
    )

    # Target power reference line
    ax_main.axhline(
        target_power,
        color=pc.target_color,
        linewidth=pc.target_linewidth,
        linestyle=pc.target_linestyle,
        alpha=pc.target_alpha,
        label="_nolegend_",
        zorder=4,
    )

    # Inline badge labels for reference lines - blended transform keeps x
    # in axes-fraction space and y in data space so labels track the lines.
    _blend = blended_transform_factory(ax_main.transAxes, ax_main.transData)
    _badge_kw: dict[str, Any] = dict(
        transform=_blend,
        ha="left",
        va="center",
        fontsize=pc.annotation_fontsize,
        zorder=6,
        clip_on=False,
    )
    ax_main.text(
        0.01,
        1.0,
        pc.ideal_label,
        color=pc.ideal_color,
        bbox=dict(
            boxstyle="round,pad=0.28",
            facecolor="white",
            edgecolor=pc.ideal_color,
            linewidth=0.9,
            alpha=0.92,
        ),
        **_badge_kw,
    )
    ax_main.text(
        0.01,
        target_power,
        pc.target_label_template.format(value=target_power),
        color=pc.target_color,
        bbox=dict(
            boxstyle="round,pad=0.28",
            facecolor="white",
            edgecolor=pc.target_color,
            linewidth=0.9,
            alpha=0.92,
        ),
        **_badge_kw,
    )

    _legend_axis_labels = {"n_reps": "# of Rep", "cv_mean": "CV mean"}
    _legend_param = "n_reps" if joint_rows or eq_rows else "n_reps"
    _legend_title = _legend_axis_labels.get(_legend_param, _legend_param)
    ax_main.set_ylim(0, 1.06)
    ax_main.legend(
        fontsize=pc.legend_fontsize,
        frameon=pc.legend_frameon,
        labelcolor=pc.legend_labelcolor,
        loc=pc.legend_loc,
        title=_legend_title,
        title_fontsize=pc.legend_fontsize,
    )
    style_ax(ax_main, pc, xlabel="Equivalence boundary (log\u2082 FC)", ylabel="Power")

    # Title - left-aligned
    ax_main.set_title(
        title or "Power Analysis - Equivalence Boundary Sweep",
        color=pc.title_color,
        fontsize=pc.title_fontsize,
        fontweight=pc.title_fontweight,
        loc=pc.title_loc,
        pad=22,
    )

    # ------------------------------------------------------------------
    # Side panel: CV boxplot
    # ------------------------------------------------------------------
    ax_cv.boxplot(
        cv_sample,
        orientation="vertical",
        patch_artist=True,
        widths=0.5,
        showmeans=True,
        flierprops=dict(
            marker=".",
            markersize=pc.box_fliersize,
            color=pc.box_linecolor,
            alpha=pc.box_flier_alpha,
        ),
        meanprops=dict(
            marker="D",
            markersize=pc.box_meansize,
            markerfacecolor=pc.box_meancolor,
            markeredgecolor=pc.box_linecolor,
            markeredgewidth=0.8,
        ),
        medianprops=dict(
            color=pc.box_mediancolor,
            linewidth=pc.box_median_linewidth,
        ),
        boxprops=dict(
            facecolor=pc.box_color,
            alpha=pc.box_alpha,
            linewidth=0.8,
            edgecolor=pc.box_linecolor,
        ),
        whiskerprops=dict(color=pc.box_linecolor, linewidth=0.8),
        capprops=dict(color=pc.box_linecolor, linewidth=0.8),
    )
    # Move y-axis to the right side
    ax_cv.yaxis.set_label_position("right")
    ax_cv.yaxis.tick_right()
    ax_cv.set_xticks([])

    ax_cv.set_title(
        "CV distribution",
        color=pc.label_color,
        fontsize=pc.label_fontsize - 1,
        loc="center",
        pad=6,
    )
    style_ax(ax_cv, pc, ylabel="CV (ratio)", ylabel_right=True)

    # Stat text centered below the CV panel (outside the axes frame)
    cv_mean_val = float(np.mean(cv_sample))
    cv_median_val = float(np.median(cv_sample))
    _stat_transform = offset_copy(ax_cv.transAxes, fig=fig, x=0, y=-14, units="points")
    ax_cv.text(
        0.5,
        0.0,
        f"mean = {cv_mean_val:.3f}  |  median = {cv_median_val:.3f}",
        transform=_stat_transform,
        ha="center",
        va="top",
        fontsize=pc.box_stat_fontsize,
        color=pc.box_stat_color,
        clip_on=False,
    )

    # ------------------------------------------------------------------
    # Annotation row
    # ------------------------------------------------------------------
    parts: list[str] = [f"cv_mean = {cv_mean:.2f}"]
    if n_prts is not None:
        parts.append(f"n_prts = {n_prts:,}")
    if target_sei is not None:
        parts.append(f"target_sei = {float(target_sei):.2f}")
    if p_thr is not None:
        parts.append(f"p_thr = {float(p_thr):.2f}")
    if correction is not None:
        parts.append(f"correction = {correction}")
    if n_iterations is not None:
        parts.append(f"iterations = {n_iterations}")

    # Annotation - 5 pts above the axes top for breathing room, then title above that
    annot_transform = offset_copy(ax_main.transAxes, fig=fig, x=0, y=5, units="points")
    ax_main.text(
        0.0,
        1.0,
        pc.annotation_sep.join(parts),
        transform=annot_transform,
        color=pc.annotation_color,
        fontsize=pc.annotation_fontsize,
        va="bottom",
        ha="left",
    )

    # ------------------------------------------------------------------
    # Save / show
    # ------------------------------------------------------------------
    finalize_plot(fig, save_path=save_path, dpi=pc.dpi, show=show)

    # Expose axes as named attributes so callers can make post-hoc adjustments
    fig.ax_main = ax_main  # type: ignore[attr-defined]
    fig.ax_cv = ax_cv  # type: ignore[attr-defined]

    return fig

questvar.plot.summary.plot_summary

plot_summary(
    results,
    *,
    config=None,
    cond_1_label="Condition 1",
    cond_2_label="Condition 2",
    title_add="",
    figsize=(20, 15),
    title_fontsize=18,
    legend_fontsize=11,
    rasterize_scatters=True,
    show_excluded=True,
    save_path=None,
    show=False,
)

Comprehensive summary figure for QuEStVar test results.

Parameters:

Name Type Description Default
results TestResults

A TestResults object returned by QuestVar.test().

required
config PlotConfig | None

Visual design configuration. Defaults to :class:PlotConfig.

None
cond_1_label str

Display name for the first condition (used in axis labels and text).

'Condition 1'
cond_2_label str

Display name for the second condition.

'Condition 2'
title_add str

Optional subtitle appended on a second line of the main title.

''
figsize tuple[float, float]

Overall figure size in inches (width, height).

(20, 15)
title_fontsize int

Base font size. Subplot titles and labels are derived from this value.

18
legend_fontsize int

Font size for the legend panel.

11
rasterize_scatters bool

Rasterize scatter layers for smaller file sizes (recommended for large datasets).

True
show_excluded bool

Whether to include the Excluded category in the counts bar chart and the legend.

True
save_path str | Path | None

If given, the figure is saved to this path using PlotConfig.dpi.

None
show bool

Call plt.show() after building the figure.

False

Returns:

Type Description
Figure

The figure. Nine convenience axes attributes are attached.

Raises:

Type Description
ImportError

If matplotlib is not installed.

Source code in src/questvar/plot/summary.py
 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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
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
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
def plot_summary(
    results: TestResults,
    *,
    config: PlotConfig | None = None,
    cond_1_label: str = "Condition 1",
    cond_2_label: str = "Condition 2",
    title_add: str = "",
    figsize: tuple[float, float] = (20, 15),
    title_fontsize: int = 18,
    legend_fontsize: int = 11,
    rasterize_scatters: bool = True,
    show_excluded: bool = True,
    save_path: str | Path | None = None,
    show: bool = False,
) -> Figure:
    """Comprehensive summary figure for QuEStVar test results.

    Parameters
    ----------
    results:
        A ``TestResults`` object returned by ``QuestVar.test()``.
    config:
        Visual design configuration. Defaults to :class:`PlotConfig`.
    cond_1_label:
        Display name for the first condition (used in axis labels and text).
    cond_2_label:
        Display name for the second condition.
    title_add:
        Optional subtitle appended on a second line of the main title.
    figsize:
        Overall figure size in inches ``(width, height)``.
    title_fontsize:
        Base font size. Subplot titles and labels are derived from this value.
    legend_fontsize:
        Font size for the legend panel.
    rasterize_scatters:
        Rasterize scatter layers for smaller file sizes (recommended for large
        datasets).
    show_excluded:
        Whether to include the ``Excluded`` category in the counts bar chart
        and the legend.
    save_path:
        If given, the figure is saved to this path using ``PlotConfig.dpi``.
    show:
        Call ``plt.show()`` after building the figure.

    Returns
    -------
    matplotlib.figure.Figure
        The figure. Nine convenience axes attributes are attached.

    Raises
    ------
    ImportError
        If matplotlib is not installed.
    """
    try:
        import matplotlib.lines as mlines
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError(
            "Matplotlib is required for plotting. "
            "Install it with: pip install questvar[plot] or pip install matplotlib"
        ) from None

    pc = config or PlotConfig()

    # ------------------------------------------------------------------
    # Analysis parameters from results
    # ------------------------------------------------------------------
    cfg = results.config
    p_thr = float(cfg.p_thr)
    eq_thr = float(cfg.eq_thr)
    df_thr = float(cfg.df_thr)
    cv_thr = float(cfg.cv_thr)
    correction = str(cfg.correction or "none")
    c1 = cond_1_label
    c2 = cond_2_label

    # ------------------------------------------------------------------
    # Extract numpy arrays from the Polars DataFrames
    # ------------------------------------------------------------------
    data = results.data
    info = results.info

    log2fc = data["log2fc"].to_numpy().astype(float)
    average = data["average"].to_numpy().astype(float)
    df_p_arr = data["df_p"].to_numpy().astype(float)
    df_adjp = data["df_adjp"].to_numpy().astype(float)
    eq_p_arr = data["eq_p"].to_numpy().astype(float)
    eq_adjp_arr = data["eq_adjp"].to_numpy().astype(float)
    n1_arr = data["n1"].to_numpy().astype(float)
    n2_arr = data["n2"].to_numpy().astype(float)
    status_int = data["status"].to_numpy().astype(int)

    s1_cv = info["s1_cv_status"].to_numpy().astype(int)
    s2_cv = info["s2_cv_status"].to_numpy().astype(int)

    # ------------------------------------------------------------------
    # String status labels for tested features
    # status codes: 1=Equivalent, -1=Differential (up/down by log2fc), 0=Unexplained
    # ------------------------------------------------------------------
    status_str = np.where(
        status_int == 1,
        "Equivalent",
        np.where(
            (status_int == -1) & (log2fc > 0),
            "Upregulated",
            np.where(
                (status_int == -1) & (log2fc <= 0),
                "Downregulated",
                "Unexplained",
            ),
        ),
    )

    # ------------------------------------------------------------------
    # Status counts (tested features + excluded from info)
    # ------------------------------------------------------------------
    n_excluded = int(np.sum((s1_cv == -1) | (s2_cv == -1)))
    # Derive counts directly from integer status codes - single pass per condition
    status_counts: dict[str, int] = {
        "Equivalent": int(np.sum(status_int == 1)),
        "Upregulated": int(np.sum((status_int == -1) & (log2fc > 0))),
        "Downregulated": int(np.sum((status_int == -1) & (log2fc <= 0))),
        "Unexplained": int(np.sum(status_int == 0)),
        "Excluded": n_excluded,
    }
    n_total = len(data)

    status_colors = pc.status_colors

    # ------------------------------------------------------------------
    # Design language constants  (based on title_fontsize for scaling)
    # ------------------------------------------------------------------
    _panel_fs = title_fontsize  # panel letter badge
    _subtitle_fs = title_fontsize - 4  # per-panel subtitle
    _label_fs = title_fontsize - 5  # axis labels
    _tick_fs = pc.tick_fontsize  # tick labels (from PlotConfig)

    _subtitle_kw: dict[str, Any] = dict(
        fontsize=_subtitle_fs,
        fontstyle="italic",
        color=pc.title_color,
        pad=5,
    )
    _legend_kw: dict[str, Any] = dict(
        fontsize=legend_fontsize - 1,
        frameon=pc.legend_frameon,
        handlelength=2.0,
        handletextpad=0.4,
        labelspacing=0.3,
        borderpad=0.5,
    )
    _box_kw: dict[str, Any] = dict(
        boxstyle="round,pad=0.5",
        facecolor=pc.annotation_box_facecolor,
        alpha=0.9,
        edgecolor=pc.annotation_box_edgecolor,
        linewidth=1,
    )

    # Threshold colors from PlotConfig
    _eq_col = pc.eq_threshold_color
    _df_col = pc.df_threshold_color
    _eq_ls = pc.eq_threshold_linestyle
    _df_ls = pc.df_threshold_linestyle
    _thr_lw = pc.threshold_linewidth

    def _letter(ax: Any, label: str) -> None:
        """Draw a panel letter badge above the top-left corner of the axis."""
        ax.annotate(
            label,
            xy=(0, 1),
            xytext=(-10, 8),
            xycoords="axes fraction",
            textcoords="offset points",
            fontsize=_panel_fs,
            fontweight="bold",
            color=pc.label_color,
            ha="right",
            va="bottom",
            bbox=dict(
                boxstyle="round,pad=0.25", facecolor="#fafafa", edgecolor="#cccccc", linewidth=0.8
            ),
        )

    scatter_order = list(pc.status_order)
    if not show_excluded:
        scatter_order = [s for s in scatter_order if s != "Excluded"]

    # ------------------------------------------------------------------
    # Build figure
    # ------------------------------------------------------------------
    fig = plt.figure(figsize=figsize, facecolor=pc.fig_facecolor)
    gs = fig.add_gridspec(
        4,
        5,
        hspace=0.4,
        wspace=0.5,
        height_ratios=[0.65, 0.65, 0.65, 0.65],
        width_ratios=[0.75, 1.0, 1.0, 1.0, 1.0],
        left=0.07,
        right=0.94,
        top=0.89,
        bottom=0.14,
    )

    def _step_hist(
        ax: Any, data: Any, bins: Any, color: Any, label: str, alpha: float = 0.85
    ) -> None:
        """Step-line histogram with thick stroke, for log y-axis."""
        ax.hist(
            data,
            bins=bins,
            histtype="step",
            linewidth=2.0,
            color=color,
            label=label,
            density=True,
            alpha=alpha,
        )

    # ------------------------------------------------------------------
    # Panel A: T-test p-value histogram  (step, density on log scale)
    # ------------------------------------------------------------------
    ax_a = fig.add_subplot(gs[0, 0])
    _letter(ax_a, "A")

    valid_dfp = df_p_arr[~np.isnan(df_p_arr)]
    valid_dfadj = df_adjp[~np.isnan(df_adjp)]

    if len(valid_dfp) > 0 and len(valid_dfadj) > 0:
        _shared = np.histogram_bin_edges(np.concatenate([valid_dfp, valid_dfadj]), bins=30)
        _step_hist(ax_a, valid_dfp, _shared, _df_col, "Raw", alpha=0.35)
        _step_hist(ax_a, valid_dfadj, _shared, _df_col, f"Adj ({correction})")
    elif len(valid_dfp) > 0:
        ax_a.hist(
            valid_dfp,
            bins=30,
            histtype="step",
            linewidth=2.0,
            color=_df_col,
            label="Raw",
            density=True,
            alpha=0.35,
        )
    elif len(valid_dfadj) > 0:
        ax_a.hist(
            valid_dfadj,
            bins=30,
            histtype="step",
            linewidth=2.0,
            color=_df_col,
            label=f"Adj ({correction})",
            density=True,
        )

    ax_a.axvline(
        x=p_thr, color=_df_col, linestyle="--", linewidth=1.5, label="Threshold", alpha=0.8
    )
    ax_a.set_yscale("log")
    style_ax(ax_a, pc, xlabel="P-value", ylabel="Difference Test\nDensity")
    ax_a.xaxis.label.set_fontsize(_label_fs)
    ax_a.yaxis.label.set_fontsize(_label_fs)
    ax_a.legend(**_legend_kw)
    ax_a.set_title("T-test", **_subtitle_kw)

    # ------------------------------------------------------------------
    # Panel B: TOST p-value histogram  (step, density on log scale)
    # ------------------------------------------------------------------
    ax_b = fig.add_subplot(gs[1, 0])
    _letter(ax_b, "B")

    valid_eqp = eq_p_arr[~np.isnan(eq_p_arr)]
    valid_eqadj = eq_adjp_arr[~np.isnan(eq_adjp_arr)]

    if len(valid_eqp) > 0 and len(valid_eqadj) > 0:
        _shared = np.histogram_bin_edges(np.concatenate([valid_eqp, valid_eqadj]), bins=30)
        _step_hist(ax_b, valid_eqp, _shared, _eq_col, "Raw", alpha=0.35)
        _step_hist(ax_b, valid_eqadj, _shared, _eq_col, f"Adj ({correction})")
    elif len(valid_eqp) > 0:
        ax_b.hist(
            valid_eqp,
            bins=30,
            histtype="step",
            linewidth=2.0,
            color=_eq_col,
            label="Raw",
            density=True,
            alpha=0.35,
        )
    elif len(valid_eqadj) > 0:
        ax_b.hist(
            valid_eqadj,
            bins=30,
            histtype="step",
            linewidth=2.0,
            color=_eq_col,
            label=f"Adj ({correction})",
            density=True,
        )

    ax_b.axvline(
        x=p_thr, color=_eq_col, linestyle="--", linewidth=1.5, label="Threshold", alpha=0.8
    )
    ax_b.set_yscale("log")
    style_ax(ax_b, pc, xlabel="P-value", ylabel="Equivalence Test\nDensity")
    ax_b.xaxis.label.set_fontsize(_label_fs)
    ax_b.yaxis.label.set_fontsize(_label_fs)
    ax_b.legend(**_legend_kw)
    ax_b.set_title("TOST", **_subtitle_kw)

    # ------------------------------------------------------------------
    # Panel C: adjusted p-value scatter (df vs eq)
    # ------------------------------------------------------------------
    ax_c = fig.add_subplot(gs[2, 0])
    _letter(ax_c, "C")

    valid_c = ~(np.isnan(df_adjp) | np.isnan(eq_adjp_arr))
    for st in scatter_order:
        if st == "Excluded":
            continue
        mask_c = valid_c & (status_str == st)
        if mask_c.sum() > 0:
            ax_c.scatter(
                df_adjp[mask_c],
                eq_adjp_arr[mask_c],
                c=status_colors.get(st, "#cccccc"),
                s=25,
                alpha=0.7,
                edgecolor="white",
                linewidth=0.3,
                rasterized=rasterize_scatters,
                zorder=5,
            )
    style_ax(
        ax_c, pc, xlabel="Difference Test\nAdj. P-value", ylabel="Equivalence Test\nAdj. P-value"
    )
    ax_c.xaxis.label.set_fontsize(_label_fs)
    ax_c.yaxis.label.set_fontsize(_label_fs)
    ax_c.axhline(y=p_thr, color=_eq_col, linestyle=_eq_ls, linewidth=_thr_lw, alpha=0.8, zorder=6)
    ax_c.axvline(x=p_thr, color=_df_col, linestyle=_df_ls, linewidth=_thr_lw, alpha=0.8, zorder=6)
    ax_c.set_xscale("log")
    ax_c.set_yscale("log")
    ax_c.set_title("P-value Agreement", **_subtitle_kw)

    # ------------------------------------------------------------------
    # Panel D: Antler's plot (delegated to the standalone function)
    # ------------------------------------------------------------------
    ax_d = fig.add_subplot(gs[0:2, 1:3])
    antlers(
        results,
        ax=ax_d,
        config=pc,
        cond_1_label=cond_1_label,
        cond_2_label=cond_2_label,
        title_add=title_add,
        rasterize_scatters=rasterize_scatters,
        show_legend=False,
        show=False,
        save_path=None,
    )
    _letter(ax_d, "D")
    ax_d.set_title("Antler's Plot: Equivalence + Difference Testing", **_subtitle_kw)
    ax_d.xaxis.label.set_fontsize(_label_fs)
    ax_d.yaxis.label.set_fontsize(_label_fs)

    # ------------------------------------------------------------------
    # Panel E: MA plot
    # ------------------------------------------------------------------
    ax_e = fig.add_subplot(gs[0:2, 3:5])
    _letter(ax_e, "E")

    for st in scatter_order:
        if st == "Excluded":
            continue
        mask = status_str == st
        if mask.sum() > 0:
            ax_e.scatter(
                average[mask],
                log2fc[mask],
                c=status_colors.get(st, "#cccccc"),
                label=st,
                s=40,
                edgecolor="white",
                linewidth=0.3,
                alpha=0.8,
                rasterized=rasterize_scatters,
                zorder=5,
            )

    va = average[~np.isnan(average)]
    vf = log2fc[~np.isnan(log2fc)]
    if len(va) > 0:
        xmin_e, xmax_e = float(va.min()), float(va.max())
        xoff_e = (xmax_e - xmin_e) * 0.07 if (xmax_e - xmin_e) > 0 else 1.0
        ax_e.set_xlim(xmin_e - xoff_e, xmax_e + xoff_e)
    if len(vf) > 0:
        yabs = float(np.max(np.abs(vf)))
        yabs = max(yabs, eq_thr, df_thr)
        yoff_e = yabs * 0.07 if yabs > 0 else 1.0
        ax_e.set_ylim(-(yabs + yoff_e), yabs + yoff_e)
    else:
        yabs = max(eq_thr, df_thr, 1.0)
        yoff_e = yabs * 0.07
        ax_e.set_ylim(-(yabs + yoff_e), yabs + yoff_e)

    ax_e.axhline(y=0, color="lightgray", linestyle="-", linewidth=1, alpha=0.6, zorder=1)
    ax_e.axhline(y=df_thr, color=_df_col, linestyle=_df_ls, linewidth=_thr_lw, alpha=0.8, zorder=2)
    ax_e.axhline(y=-df_thr, color=_df_col, linestyle=_df_ls, linewidth=_thr_lw, alpha=0.8, zorder=2)
    ax_e.axhline(y=eq_thr, color=_eq_col, linestyle=_eq_ls, linewidth=_thr_lw, alpha=0.8, zorder=2)
    ax_e.axhline(y=-eq_thr, color=_eq_col, linestyle=_eq_ls, linewidth=_thr_lw, alpha=0.8, zorder=2)

    style_ax(
        ax_e,
        pc,
        xlabel=f"Average Expression ({c1} & {c2})",
        ylabel=f"log\u2082 Fold Change ({c1} vs {c2})",
    )
    ax_e.xaxis.label.set_fontsize(_label_fs)
    ax_e.yaxis.label.set_fontsize(_label_fs)
    ax_e.set_title("MA Plot: Mean Expression vs Fold Change", **_subtitle_kw)

    # ------------------------------------------------------------------
    # Panel F: status counts bar chart
    # ------------------------------------------------------------------
    ax_f = fig.add_subplot(gs[2, 1])
    _letter(ax_f, "F")

    bar_order = ["Downregulated", "Unexplained", "Equivalent", "Upregulated"]
    if show_excluded:
        bar_order.append("Excluded")

    bar_counts = [status_counts.get(s, 0) for s in bar_order]
    bar_colors = [status_colors.get(s, "#cccccc") for s in bar_order]
    y_pos = np.arange(len(bar_order))

    ax_f.barh(
        y_pos,
        bar_counts,
        color=bar_colors,
        alpha=0.9,
        edgecolor=pc.spine_color,
        linewidth=0.8,
        height=0.6,
    )
    ax_f.set_yticks(y_pos)
    ax_f.set_yticklabels(bar_order)
    max_count = max(bar_counts) if bar_counts else 1
    for i, cnt in enumerate(bar_counts):
        if cnt > 0:
            ax_f.text(
                cnt + max_count * 0.02,
                i,
                f"{cnt:,}",
                va="center",
                ha="left",
                fontsize=_tick_fs,
            )
    ax_f.set_xlim(right=max_count * 1.25)
    style_ax(ax_f, pc, xlabel="Count")
    ax_f.xaxis.label.set_fontsize(_label_fs)
    ax_f.set_title("Category Counts", **_subtitle_kw)
    ax_f.invert_yaxis()

    # ------------------------------------------------------------------
    # Panel G: exclusion matrix
    # ------------------------------------------------------------------
    ax_g = fig.add_subplot(gs[2, 2])
    style_ax(ax_g, pc, xlabel=f"{c2} Status", ylabel=f"{c1} Status")
    ax_g.xaxis.label.set_fontsize(_label_fs)
    ax_g.yaxis.label.set_fontsize(_label_fs)
    _letter(ax_g, "G")

    cats = ["Retained", "Missing", "Filtered"]
    s1_idx = np.clip(1 - s1_cv, 0, 2)
    s2_idx = np.clip(1 - s2_cv, 0, 2)
    matrix = np.zeros((3, 3), dtype=int)
    np.add.at(matrix, (s1_idx, s2_idx), 1)

    ax_g.grid(False)
    ax_g.imshow(matrix, cmap=pc.count_cmap, aspect="auto", alpha=0.8, interpolation="nearest")
    max_val = int(matrix.max()) or 1
    for ri in range(3):
        for ci in range(3):
            val = int(matrix[ri, ci])
            txt_col = "white" if val > max_val * 0.4 else "black"
            ax_g.text(
                ci,
                ri,
                f"{val:,}",
                ha="center",
                va="center",
                color=txt_col,
                fontweight="bold",
                fontsize=_tick_fs,
            )
    ax_g.set_xticks(range(3))
    ax_g.set_yticks(range(3))
    ax_g.set_xticklabels(cats)
    ax_g.set_yticklabels(cats)
    ax_g.set_title("Exclusion Matrix", **_subtitle_kw)
    for spine in ax_g.spines.values():
        spine.set_visible(False)

    # ------------------------------------------------------------------
    # Panel H: sample size comparison
    # - allow_missing=True  -> per-feature n1/n2 vary -> hexbin density
    # - allow_missing=False -> all features share the same n1/n2 -> annotated summary
    # ------------------------------------------------------------------
    ax_h = fig.add_subplot(gs[2, 3])
    _letter(ax_h, "H")

    valid_n = ~(np.isnan(n1_arr) | np.isnan(n2_arr))
    n1_v = n1_arr[valid_n]
    n2_v = n2_arr[valid_n]

    if len(n1_v) > 0 and len(n2_v) > 0:
        n1_unique = np.unique(n1_v.astype(int))
        n2_unique = np.unique(n2_v.astype(int))
        if len(n1_unique) > 1 or len(n2_unique) > 1:
            # Variable per-feature sample sizes: hexbin density plot
            max_bins = max(min(20, len(n1_unique), len(n2_unique)), 2)
            hb = ax_h.hexbin(
                n1_v,
                n2_v,
                gridsize=max_bins,
                cmap=pc.count_cmap,
                mincnt=1,
                linewidths=0.3,
                alpha=0.85,
                rasterized=True,
            )
            cb = fig.colorbar(hb, ax=ax_h, shrink=0.7, pad=0.04)
            cb.set_label("Count", fontsize=_tick_fs)
            cb.ax.tick_params(labelsize=_tick_fs)
            ax_h.set_xlim(0, n1_unique.max() + 1)
            ax_h.set_ylim(0, n2_unique.max() + 1)
            style_ax(ax_h, pc, xlabel=f"N\u2081 ({c1} Samples)", ylabel=f"N\u2082 ({c2} Samples)")
            ax_h.xaxis.label.set_fontsize(_label_fs)
            ax_h.yaxis.label.set_fontsize(_label_fs)
        else:
            # Fixed sample sizes: annotated summary avoids a degenerate single-cell hexbin
            n1_val = int(n1_unique[0])
            n2_val = int(n2_unique[0])
            ax_h.text(
                0.5,
                0.62,
                f"{c1}\nN\u2081 = {n1_val}",
                transform=ax_h.transAxes,
                fontsize=title_fontsize - 2,
                ha="center",
                va="center",
                fontweight="bold",
                color=pc.title_color,
            )
            ax_h.text(
                0.5,
                0.30,
                f"{c2}\nN\u2082 = {n2_val}",
                transform=ax_h.transAxes,
                fontsize=title_fontsize - 2,
                ha="center",
                va="center",
                fontweight="bold",
                color=pc.title_color,
            )
            ax_h.axis("off")

    ax_h.set_title("Sample Size Comparison", **_subtitle_kw)

    # ------------------------------------------------------------------
    # Legend panel (column 5, row 2)
    # ------------------------------------------------------------------
    ax_lgd = fig.add_subplot(gs[2, 4])

    legend_bar_order = ["Downregulated", "Unexplained", "Equivalent", "Upregulated"]
    if show_excluded:
        legend_bar_order.append("Excluded")

    legend_handles = [mlines.Line2D([], [], color="none", label="Status Categories:")]
    for st in legend_bar_order:
        legend_handles.append(
            mlines.Line2D(
                [],
                [],
                marker="o",
                color="w",
                markerfacecolor=status_colors.get(st, "#cccccc"),
                markersize=7,
                label=f"  {st}",
                markeredgecolor="white",
                markeredgewidth=0.5,
            )
        )
    legend_handles.append(mlines.Line2D([], [], color="none", label=""))
    legend_handles.append(mlines.Line2D([], [], color="none", label="Equivalence Thresholds:"))
    legend_handles.extend(
        [
            mlines.Line2D(
                [], [], color=_eq_col, linestyle=_eq_ls, linewidth=2.2, label=f"  p-value = {p_thr}"
            ),
            mlines.Line2D(
                [],
                [],
                color=_eq_col,
                linestyle=_eq_ls,
                linewidth=2.2,
                label=f"  |log\u2082FC| = \u00b1{eq_thr}",
            ),
        ]
    )
    legend_handles.append(mlines.Line2D([], [], color="none", label=""))
    legend_handles.append(mlines.Line2D([], [], color="none", label="Difference Thresholds:"))
    legend_handles.extend(
        [
            mlines.Line2D(
                [], [], color=_df_col, linestyle=_df_ls, linewidth=2.2, label=f"  p-value = {p_thr}"
            ),
            mlines.Line2D(
                [],
                [],
                color=_df_col,
                linestyle=_df_ls,
                linewidth=2.2,
                label=f"  |log\u2082FC| = \u00b1{df_thr}",
            ),
        ]
    )

    lgd = ax_lgd.legend(
        handles=legend_handles,
        loc="upper left",
        bbox_to_anchor=(-0.12, 1.02),
        fontsize=_tick_fs,
        frameon=pc.legend_frameon,
        title="Legend",
        title_fontsize=_label_fs,
        handlelength=2.0,
        handletextpad=0.4,
        labelspacing=0.2,
        borderpad=0.1,
        borderaxespad=0.0,
    )
    for text in lgd.get_texts():
        text.set_color(pc.label_color)
    lgd.get_title().set_color(pc.label_color)
    lgd.get_title().set_position((0, 0))
    ax_lgd.axis("off")

    # ------------------------------------------------------------------
    # Bottom row: methodology and panel descriptions
    # ------------------------------------------------------------------
    ax_left = fig.add_subplot(gs[3, :3])
    ax_right = fig.add_subplot(gs[3, 3:])
    ax_left.axis("off")
    ax_right.axis("off")

    n1_nom = len(results.cond_1)
    n2_nom = len(results.cond_2)

    text_left = (
        r"$\mathbf{STATISTICAL\ TESTING\ METHODOLOGY}$"
        + "\n\n"
        + rf"$\mathbf{{Equivalence\ Testing}}$: Two One-Sided Tests (TOST), "
        rf"$|log_2FC| < {eq_thr:.3f}$ as equivalence threshold"
        + "\n"
        + rf"$\mathbf{{Difference\ Testing}}$: Welch's t-test, "
        rf"$|log_2FC| > {df_thr:.3f}$ as significance threshold"
        + "\n"
        + rf"$\mathbf{{CV\ Filtering}}$: Features with CV $> {cv_thr:.2f}$ excluded"
        + "\n"
        + rf"$\mathbf{{Multiple\ Testing}}$: {correction} correction applied"
        + "\n"
        + rf"$\mathbf{{Significance\ Level}}$: $\alpha = {p_thr:.3f}$"
        + "\n\n"
        + rf"$\mathbf{{Data\ Summary}}$: {n_total:,} features analyzed"
        + "\n"
        + rf"{c1}: {n1_nom} samples   {c2}: {n2_nom} samples"
    )
    text_right = (
        r"$\mathbf{FIGURE\ PANEL\ DESCRIPTION}$"
        + "\n\n"
        + rf"$\mathbf{{A)}}$ T-test P-values: Welch's t-test distributions ({c1} vs {c2})"
        + "\n"
        + r"$\mathbf{B)}$ TOST P-values: Two One-Sided Test distributions for equivalence"
        + "\n"
        + r"$\mathbf{C)}$ P-value Comparison: t-test vs TOST adjusted p-values (log scale)"
        + "\n"
        + r"$\mathbf{D)}$ Antler's Plot: Effect size vs significance (TOST + t-test combined)"
        + "\n"
        + r"$\mathbf{E)}$ MA Plot: Mean expression vs log fold change with threshold regions"
        + "\n"
        + r"$\mathbf{F)}$ Category Distribution: Feature counts per testing outcome"
        + "\n"
        + r"$\mathbf{G)}$ Exclusion Matrix: CV filter status cross-tabulation by condition"
        + "\n"
        + r"$\mathbf{H)}$ Sample Size: Per-feature hexbin density (variable N) or fixed N per condition"
    )

    ax_left.text(
        0.02,
        0.98,
        text_left,
        transform=ax_left.transAxes,
        fontsize=10,
        verticalalignment="top",
        horizontalalignment="left",
        bbox=dict(**_box_kw),
    )
    ax_right.text(
        -0.1,
        0.98,
        text_right,
        transform=ax_right.transAxes,
        fontsize=10,
        verticalalignment="top",
        horizontalalignment="left",
        bbox=dict(**_box_kw),
    )

    # ------------------------------------------------------------------
    # Main title
    # ------------------------------------------------------------------
    title_str = f"QuEStVar Summary: {c1} vs {c2}"
    if title_add:
        title_str += f"\n{title_add}"
    fig.suptitle(
        title_str,
        fontsize=title_fontsize,
        fontweight="bold",
        color=pc.title_color,
        y=0.96,
    )

    # ------------------------------------------------------------------
    # Save / show
    # ------------------------------------------------------------------
    finalize_plot(fig, save_path=save_path, dpi=pc.dpi, show=show)

    # Convenience axes attributes
    fig.ax_df_hist = ax_a  # type: ignore[attr-defined]
    fig.ax_eq_hist = ax_b  # type: ignore[attr-defined]
    fig.ax_pval_scatter = ax_c  # type: ignore[attr-defined]
    fig.ax_antlers = ax_d  # type: ignore[attr-defined]
    fig.ax_ma = ax_e  # type: ignore[attr-defined]
    fig.ax_counts = ax_f  # type: ignore[attr-defined]
    fig.ax_matrix = ax_g  # type: ignore[attr-defined]
    fig.ax_hexbin = ax_h  # type: ignore[attr-defined]
    fig.ax_legend = ax_lgd  # type: ignore[attr-defined]

    return fig