#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File: src/scitex_stats/reporting/_full_report.py
"""Six-stat report builder.
Functionalities:
- Bundle the six mandatory fields of a complete statistical report
(n, 95% CI, method, p-value, effect size, test statistic) from a
`run_test()` / `test_*()`-style result dict
- Derive a confidence interval with TEST-APPROPRIATE semantics:
* parametric t-tests -> analytic mean-difference CI (scipy
`ttest_*.confidence_interval`)
* Pearson / Spearman -> Fisher-z CI on the correlation
* Mann-Whitney U -> percentile bootstrap of the
rank-biserial r (1 - 2U/(n1*n2))
* anything else -> NO CI (None). We do not emit a
generic mean/mean-difference CI for a
test whose statistic is not a mean
difference, because that interval is
meaningless for that statistic (e.g. a
Spearman rho=1.0 must not be reported
with a CI spanning negative values).
- Validate the inputs: a NaN/inf statistic, p-value or effect size, or a
NaN / reversed (lower > upper) confidence interval, is treated as
MISSING (and fails loudly under `strict=True`) rather than being
accepted as a complete report.
- Read the method from `test_method` OR `test` (some families, e.g.
repeated-measures ANOVA and Friedman, store it under `test`), and the
sample size from the full set of keys those families emit (incl.
`n_subjects`).
- Raise a clear error (or warn) when a required field cannot be
determined, so partial reports never silently pass as complete.
Dependencies:
- packages: numpy, scipy
IO:
- input: a `run_test()`/`test_*()` result dict, plus optionally the raw
data array(s) or a precomputed CI tuple
- output: a dict bundling all six fields plus a human-readable string
"""
from __future__ import annotations
import os
from typing import Any, Dict, Optional, Sequence, Tuple, Union
import numpy as np
__FILE__ = __file__
__DIR__ = os.path.dirname(__FILE__)
from scitex_stats._logging import getLogger
from scitex_stats._utils._formatters import fmt_sym_md
from scitex_stats.reporting._ci import ( # noqa: E402, F401
_ci_kind,
_ci_method,
_derive_ci,
_is_finite_num,
_method_string,
_valid_ci,
)
logger = getLogger(__name__)
# The six mandatory fields of the operator's six-stat reporting doctrine
# (2026-07-05): n, 95% CI, method, p-value, effect size, test statistic.
SIX_STAT_FIELDS: Tuple[str, ...] = (
"n",
"ci",
"method",
"pvalue",
"effect_size",
"statistic",
)
# Sample-size keys emitted by the various `test_*()` functions, including the
# `n_subjects` / `n_obs` / `n_total` forms used by repeated-measures ANOVA,
# Friedman and other group-based families (which do NOT emit n_x/n_y).
# Collected as-is; this module does not attempt to relabel them to the
# N (subject-level) / n (window-level) convention because a generic
# array-based test function has no way to know which level its input
# represents — that judgement belongs to the caller.
_N_KEY_CANDIDATES: Tuple[str, ...] = (
"n_x",
"n_y",
"n_1",
"n_2",
"n",
"n_pairs",
"n_groups",
"n_samples",
"n_subjects",
"n_obs",
"n_total",
"N",
"N_subjects",
"n_windows",
)
# effect_size_metric string (as emitted by test_* functions) -> plain-text
# symbol used in the formatted six-stat string.
_EFFECT_SYMBOLS: Dict[str, str] = {
"Cohen's d": "d",
"Hedges' g": "g",
"Glass's delta": "Δ",
"Cliff's delta": "δ",
"eta-squared": "η²",
"eta squared": "η²",
"epsilon-squared": "ε²",
"epsilon squared": "ε²",
"partial eta-squared": "η²_p",
"probability of superiority": "P(X>Y)",
"r": "r",
"rho": "ρ",
"tau": "τ",
"kendall_tau": "τ",
"kendall_w": "W",
"rank-biserial correlation": "r_rb",
"Pearson r": "r",
"partial_eta_squared": "η²_p",
}
class IncompleteReportError(ValueError):
"""Raised when a six-stat report cannot be assembled in full.
Encodes "partial reporting is incomplete" as a checked invariant: this
is raised (rather than silently returning a partial dict) whenever one
of the six mandatory fields — n, 95% CI, method, p-value, effect size,
test statistic — cannot be determined from the inputs given.
"""
def _extract_n(result: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Collect every sample-size-like key present in a test result dict."""
found = {k: result[k] for k in _N_KEY_CANDIDATES if k in result and result[k] is not None}
return found or None
def _format_pvalue(pvalue: float, stars: Optional[str]) -> str:
p_str = "p < .001" if pvalue < 0.001 else f"p = {pvalue:.3f}".replace("0.", ".")
if stars and stars != "ns":
p_str += f" {stars}"
return p_str
def _format_six_stat(
*,
method: Optional[str],
stat_symbol: str,
statistic: Optional[float],
df: Optional[Any],
pvalue: Optional[float],
stars: Optional[str],
effect_size_metric: Optional[str],
effect_size: Optional[float],
ci: Optional[Tuple[float, float]],
confidence: float,
n: Optional[Dict[str, Any]],
) -> str:
"""Render the six fields as one human-readable, markdown-italicized line."""
segments = []
sym = stat_symbol or "stat"
sym_md = fmt_sym_md(sym)
if statistic is None:
stat_segment = f"{sym_md} = NA"
elif df is not None:
stat_segment = f"{sym_md}({df}) = {statistic:.2f}"
else:
stat_segment = f"{sym_md} = {statistic:.2f}"
segments.append(stat_segment)
if pvalue is not None:
segments.append(_format_pvalue(pvalue, stars).replace("p ", f"{fmt_sym_md('p')} ", 1))
if effect_size is not None:
es_sym = _EFFECT_SYMBOLS.get(effect_size_metric or "", None)
es_sym_md = fmt_sym_md(es_sym) if es_sym else (effect_size_metric or "effect size")
segments.append(f"{es_sym_md} = {effect_size:.2f}")
if ci is not None:
level_pct = int(round(confidence * 100))
segments.append(f"{level_pct}% CI [{ci[0]:.2f}, {ci[1]:.2f}]")
if n:
n_segments = []
for key, value in n.items():
n_segments.append(f"{fmt_sym_md(key)} = {value}")
segments.append(", ".join(n_segments))
body = ", ".join(segments)
return f"{method}: {body}" if method else body
[docs]
def full_report(
result: Dict[str, Any],
*,
data: Optional[Union[np.ndarray, Sequence[float]]] = None,
data2: Optional[Union[np.ndarray, Sequence[float]]] = None,
ci: Optional[Tuple[float, float]] = None,
confidence: float = 0.95,
n_bootstrap: int = 10_000,
seed: int = 42,
random_state: Optional[int] = None,
strict: bool = True,
) -> Dict[str, Any]:
"""Bundle a `run_test()`/`test_*()` result into a complete six-stat report.
Encodes the operator's six-stat reporting doctrine (2026-07-05): every
reported statistic must carry all of (1) n, (2) 95% CI, (3) method, (4)
p-value, (5) effect size, (6) test statistic. Partial reporting is
treated as incomplete — by default this raises :class:`IncompleteReportError`
rather than silently returning a partial dict.
Parameters
----------
result : dict
A result dict as returned by `scitex_stats.run_test()` or any
`scitex_stats.tests.test_*()` function. Expected to carry the method
(as `test_method` or `test`), `statistic`, `stat_symbol`, `pvalue`,
`effect_size`, `effect_size_metric`, and one or more sample-size keys
(`n_x`/`n_y`, `n`, `n_subjects`, ...).
data, data2 : array-like, optional
Raw sample(s) the test was run on. Used to derive a confidence
interval when *result* and *ci* don't already carry one, with
test-appropriate semantics: an analytic mean-difference CI for
t-tests, a Fisher-z CI for Pearson/Spearman, a rank-biserial
bootstrap CI for Mann-Whitney. Other tests get no derived CI (the
report then marks `ci` missing and fails loudly in strict mode)
rather than a meaningless generic interval.
ci : tuple of (float, float), optional
An already-computed `(lower, upper)` confidence interval. Must be
finite and ordered (lower <= upper); a NaN or reversed interval is
treated as missing. Takes precedence over deriving one from data.
confidence : float, default 0.95
Confidence level for the interval (analytic or bootstrap).
n_bootstrap : int, default 10000
Bootstrap resamples, used only when falling back to a bootstrap CI.
seed : int, default 42
Seed for the bootstrap resampler (``numpy.random.default_rng(seed)``,
freshly created per interval, never global state). Recorded in
``provenance["randomness"]``; the same data and seed give a
bit-identical CI.
random_state : int, optional
Deprecated alias for *seed*; when given it overrides *seed*.
strict : bool, default True
If True (default), raise :class:`IncompleteReportError` when any of
the six mandatory fields cannot be determined (including a NaN or
reversed CI). If False, log a warning instead and return the partial
report with a `missing_fields` list.
Returns
-------
dict
Keys: `method`, `statistic`, `stat_symbol`, `pvalue`, `effect_size`,
`effect_size_metric`, `n`, `ci`, `ci_level`, `ci_method`, `formatted`,
`missing_fields`, `provenance`.
Raises
------
IncompleteReportError
If `strict=True` and one or more of the six mandatory fields
(n, ci, method, pvalue, effect_size, statistic) cannot be
determined from *result* / *data* / *data2* / *ci*.
Examples
--------
>>> import numpy as np
>>> from scitex_stats import run_test, full_report
>>> x = np.random.default_rng(0).normal(0, 1, 50)
>>> y = np.random.default_rng(1).normal(0.5, 1, 50)
>>> result = run_test("ttest_ind", data=x, data2=y)
>>> report = full_report(result, data=x, data2=y)
>>> report["ci"] is not None
True
"""
from scitex_stats import _provenance
if random_state is not None:
import warnings
warnings.warn(
"full_report(random_state=) is deprecated; use seed=",
DeprecationWarning,
stacklevel=2,
)
seed = int(random_state)
raw_inputs = {}
for name, values in (("data", data), ("data2", data2)):
if values is not None:
raw_inputs[name], _, _ = _provenance._to_float_array(name, values)
data, data2 = raw_inputs.get("data"), raw_inputs.get("data2")
missing = []
# (3) method — from test_method or test (some families use `test`).
method = _method_string(result) or None
if not method:
missing.append("method")
# (6) statistic — must be present AND finite (NaN is not a valid stat).
statistic = result.get("statistic")
if not _is_finite_num(statistic):
missing.append("statistic")
stat_symbol = result.get("stat_symbol", "")
# (4) p-value — must be present AND finite.
pvalue = result.get("pvalue")
if not _is_finite_num(pvalue):
missing.append("pvalue")
stars = result.get("stars")
# (5) effect size — must be present AND finite.
effect_size = result.get("effect_size")
if not _is_finite_num(effect_size):
missing.append("effect_size")
effect_size_metric = result.get("effect_size_metric")
# (1) n — any recognised sample-size key (incl. n_subjects/n_obs).
n = _extract_n(result)
if n is None:
missing.append("n")
# (2) CI — test-appropriate semantics; NaN/reversed => missing.
ci_tuple = _derive_ci(result, data, data2, ci, confidence, n_bootstrap, seed)
if ci_tuple is None:
missing.append("ci")
if missing:
message = (
"Incomplete six-stat report — missing required field(s): "
f"{', '.join(missing)}. Under the six-stat reporting doctrine, n, "
"95% CI, method, p-value, effect size, and test statistic are all "
"required; partial reporting is not accepted. A NaN/infinite "
"statistic, p-value, effect size, or a NaN/reversed confidence "
"interval counts as missing. For the CI: pass `data=`/`data2=` "
"(t-tests, Pearson/Spearman, Mann-Whitney) or an explicit "
"`ci=(lower, upper)`; other tests (e.g. Friedman, repeated-"
"measures ANOVA) have no generic mean-difference CI, so pass an "
"explicit `ci` or extend the input result dict."
)
if strict:
raise IncompleteReportError(message)
logger.warning(message)
formatted = _format_six_stat(
method=method,
stat_symbol=stat_symbol,
statistic=statistic,
df=result.get("df"),
pvalue=pvalue,
stars=stars,
effect_size_metric=effect_size_metric,
effect_size=effect_size,
ci=ci_tuple,
confidence=confidence,
n=n,
)
ci_method = _ci_method(result, data, ci, ci_tuple)
report = {
"method": method,
"statistic": statistic,
"stat_symbol": stat_symbol,
"pvalue": pvalue,
"effect_size": effect_size,
"effect_size_metric": effect_size_metric,
"n": n,
"ci": ci_tuple,
"ci_level": confidence if ci_tuple is not None else None,
"ci_method": ci_method,
"formatted": formatted,
"missing_fields": missing,
}
source_receipt = (result.get("provenance") or {}).get("receipt_sha256")
return _provenance.attach(
report,
api="full_report",
test_name="full_report",
function="scitex_stats.reporting.full_report",
parameters={
"ci": ci,
"confidence": confidence,
"n_bootstrap": n_bootstrap,
"seed": seed,
"strict": strict,
},
raw_inputs=raw_inputs,
seed=seed,
stochastic=ci_method == "bootstrap",
extra={
"source_result_sha256": _provenance.hash_result(result),
"source_receipt_sha256": source_receipt,
},
)
# EOF