statscrutiny 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- statscrutiny/__init__.py +40 -0
- statscrutiny/__main__.py +5 -0
- statscrutiny/ci.py +188 -0
- statscrutiny/cli.py +119 -0
- statscrutiny/counts.py +134 -0
- statscrutiny/extract.py +133 -0
- statscrutiny/grim.py +68 -0
- statscrutiny/grimmer.py +91 -0
- statscrutiny/pvalues.py +303 -0
- statscrutiny/result.py +45 -0
- statscrutiny/rounding.py +123 -0
- statscrutiny/samplesize.py +105 -0
- statscrutiny/tables.py +195 -0
- statscrutiny-0.1.0.dist-info/METADATA +170 -0
- statscrutiny-0.1.0.dist-info/RECORD +18 -0
- statscrutiny-0.1.0.dist-info/WHEEL +4 -0
- statscrutiny-0.1.0.dist-info/entry_points.txt +2 -0
- statscrutiny-0.1.0.dist-info/licenses/LICENSE +21 -0
statscrutiny/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""statscrutiny: conservative consistency checks for reported statistics.
|
|
2
|
+
|
|
3
|
+
Every check takes the numbers as printed (strings, so that trailing zeros keep
|
|
4
|
+
their meaning) and returns a CheckResult with one of four statuses:
|
|
5
|
+
CONSISTENT, INCONSISTENT, UNRESOLVED or UNASSESSABLE. Printed numbers are
|
|
6
|
+
treated as intervals (rounding or truncation), and a result is INCONSISTENT only
|
|
7
|
+
if it disagrees under every reasonable convention and supported interpretation.
|
|
8
|
+
|
|
9
|
+
Check families:
|
|
10
|
+
p-values from t, F, chi2, r, z check_pvalue, check_pvalue_both
|
|
11
|
+
means and SDs of integer data check_grim, check_grimmer
|
|
12
|
+
counts and percentages check_percentage, check_percentage_granularity,
|
|
13
|
+
check_count_sum, check_percentage_sum
|
|
14
|
+
sample sizes compare_sample_sizes, check_arm_total
|
|
15
|
+
confidence intervals check_ci_pvalue
|
|
16
|
+
2 x 2 tables (OR, RR, RD) check_2x2
|
|
17
|
+
APA-style text extract_results, check_text
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from .ci import check_ci_pvalue
|
|
21
|
+
from .counts import check_count_sum, check_percentage, check_percentage_granularity, check_percentage_sum
|
|
22
|
+
from .extract import ReportedResult, check_text, extract_results
|
|
23
|
+
from .grim import check_grim
|
|
24
|
+
from .grimmer import check_grimmer
|
|
25
|
+
from .pvalues import check_pvalue, check_pvalue_both
|
|
26
|
+
from .result import CheckResult, Status
|
|
27
|
+
from .samplesize import SampleSizeReport, check_arm_total, compare_sample_sizes
|
|
28
|
+
from .tables import check_2x2
|
|
29
|
+
|
|
30
|
+
__version__ = "0.1.0"
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"CheckResult", "Status", "__version__",
|
|
34
|
+
"check_pvalue", "check_pvalue_both",
|
|
35
|
+
"check_grim", "check_grimmer",
|
|
36
|
+
"check_percentage", "check_percentage_granularity", "check_count_sum", "check_percentage_sum",
|
|
37
|
+
"SampleSizeReport", "compare_sample_sizes", "check_arm_total",
|
|
38
|
+
"check_ci_pvalue", "check_2x2",
|
|
39
|
+
"ReportedResult", "extract_results", "check_text",
|
|
40
|
+
]
|
statscrutiny/__main__.py
ADDED
statscrutiny/ci.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Confidence interval, point estimate and p-value consistency.
|
|
2
|
+
|
|
3
|
+
For an estimate reported with a (1 - a) confidence interval [L, U] and a p-value:
|
|
4
|
+
|
|
5
|
+
1. Order (any CI method): L <= estimate <= U must be possible for some compatible
|
|
6
|
+
values of the printed numbers. Otherwise INCONSISTENT.
|
|
7
|
+
2. Significance direction (Wald-type duality): a (1 - a) CI that excludes the null
|
|
8
|
+
value implies p < a; a CI that contains it implies p >= a. A mismatch is
|
|
9
|
+
INCONSISTENT only when the caller declares that the CI and the p-value come from
|
|
10
|
+
the same Wald-type test (`same_test=True`); otherwise it is UNRESOLVED, because
|
|
11
|
+
articles often pair a Wald CI with a p-value from another test (likelihood
|
|
12
|
+
ratio, exact, permutation, mixed model, ...).
|
|
13
|
+
3. Recomputed p (only with `same_test=True` and a declared reference
|
|
14
|
+
distribution, 'z' or 't' with df): the CI must be symmetric on the working
|
|
15
|
+
scale (difference scale, or log scale for ratio measures). Then
|
|
16
|
+
SE = (U - L) / (2 q), with q the 1 - a/2 quantile, and the test statistic is
|
|
17
|
+
(estimate - null) / SE. The p range over all compatible printed values is
|
|
18
|
+
compared with the reported p, as in pvalues.py. When the CI is not symmetric
|
|
19
|
+
within rounding, this part is skipped (the CI is not a Wald interval on this
|
|
20
|
+
scale) and reported in the details.
|
|
21
|
+
|
|
22
|
+
Ratio measures (odds ratio, risk ratio, hazard ratio) use `scale='ratio'`: all
|
|
23
|
+
printed numbers must be positive and the checks run on the log scale; the null
|
|
24
|
+
value is then 1 by default. Printed numbers are intervals (rounding or
|
|
25
|
+
truncation; rounding.py) and the transformation is monotone, so the bounds carry
|
|
26
|
+
over exactly.
|
|
27
|
+
|
|
28
|
+
References: Altman DG, Bland JM. How to obtain the P value from a confidence
|
|
29
|
+
interval. BMJ 2011;343:d2304. Altman DG, Bland JM. How to obtain the confidence
|
|
30
|
+
interval from a P value. BMJ 2011;343:d2090.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import math
|
|
36
|
+
|
|
37
|
+
from scipy import stats
|
|
38
|
+
|
|
39
|
+
from .pvalues import _COMP, _reported_set
|
|
40
|
+
from .result import CheckResult, Status, unassessable
|
|
41
|
+
from .rounding import parse_printed, printed_interval
|
|
42
|
+
|
|
43
|
+
CHECK = "ci"
|
|
44
|
+
_ORDER = {Status.INCONSISTENT: 3, Status.UNRESOLVED: 2, Status.CONSISTENT: 1, Status.UNASSESSABLE: 0}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _iv(text: str, ratio: bool) -> tuple[float, float]:
|
|
48
|
+
iv = printed_interval(text)
|
|
49
|
+
lo, hi = float(iv.lo), float(iv.hi)
|
|
50
|
+
if not ratio:
|
|
51
|
+
return lo, hi
|
|
52
|
+
if hi <= 0:
|
|
53
|
+
raise ValueError(f"ratio measure must be positive: {text!r}")
|
|
54
|
+
return math.log(max(lo, 1e-300)), math.log(hi)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _combine(parts: dict[str, CheckResult]) -> Status:
|
|
58
|
+
worst = max((r.status for r in parts.values()), key=_ORDER.get)
|
|
59
|
+
return worst
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def check_ci_pvalue(estimate: str, lower: str, upper: str, p: str | None = None, comparator: str = "=",
|
|
63
|
+
level: str = "95", scale: str = "difference", null: str | None = None,
|
|
64
|
+
same_test: bool = False, distribution: str | None = None, df=None) -> CheckResult:
|
|
65
|
+
"""Check a reported estimate, its confidence interval and (optionally) its p-value.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
estimate, lower, upper: printed point estimate and CI limits, as strings.
|
|
69
|
+
p: printed p-value or bound (None: only the order check runs; with
|
|
70
|
+
comparator 'ns' no number is needed).
|
|
71
|
+
comparator: '=', '<', '>', '<=', '>=' or 'ns'.
|
|
72
|
+
level: confidence level in percent, e.g. '95' or '90'.
|
|
73
|
+
scale: 'difference' (mean difference, regression coefficient, risk
|
|
74
|
+
difference, ...) or 'ratio' (OR, RR, HR; checked on the log scale).
|
|
75
|
+
null: null value on the reported scale; default 0 (difference) or 1 (ratio).
|
|
76
|
+
same_test: the article establishes that the CI and the p-value come from
|
|
77
|
+
the same Wald-type test. Without it, a direction mismatch is UNRESOLVED
|
|
78
|
+
and p is not recomputed.
|
|
79
|
+
distribution: 'z' or 't' (with df) to recompute p from the CI.
|
|
80
|
+
df: degrees of freedom for distribution 't'.
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
CheckResult; `details["parts"]` holds the outcome of each sub-check
|
|
84
|
+
('order', 'direction', 'recomputed_p').
|
|
85
|
+
"""
|
|
86
|
+
if scale not in ("difference", "ratio"):
|
|
87
|
+
return unassessable(CHECK, f"unknown scale {scale!r}")
|
|
88
|
+
ratio = scale == "ratio"
|
|
89
|
+
comp = _COMP.get(str(comparator).strip().lower() if comparator else "=")
|
|
90
|
+
if comp is None:
|
|
91
|
+
return unassessable(CHECK, f"unknown comparator {comparator!r}")
|
|
92
|
+
try:
|
|
93
|
+
lv = float(parse_printed(level).value)
|
|
94
|
+
if not 0 < lv < 100:
|
|
95
|
+
raise ValueError("level must be between 0 and 100")
|
|
96
|
+
a = 1 - lv / 100
|
|
97
|
+
e_lo, e_hi = _iv(estimate, ratio)
|
|
98
|
+
l_lo, l_hi = _iv(lower, ratio)
|
|
99
|
+
u_lo, u_hi = _iv(upper, ratio)
|
|
100
|
+
null_v = float(parse_printed(null).value) if null is not None else (1.0 if ratio else 0.0)
|
|
101
|
+
if ratio:
|
|
102
|
+
if null_v <= 0:
|
|
103
|
+
raise ValueError("null of a ratio measure must be positive")
|
|
104
|
+
null_v = math.log(null_v)
|
|
105
|
+
reported = _reported_set(p, comp, a) if (p is not None or comp == "ns") else None
|
|
106
|
+
except (ValueError, TypeError) as e:
|
|
107
|
+
return unassessable(CHECK, f"invalid input: {e}")
|
|
108
|
+
|
|
109
|
+
details = {"scale": scale, "level": lv, "null": null if null is not None else ("1" if ratio else "0"),
|
|
110
|
+
"same_test": same_test}
|
|
111
|
+
parts: dict[str, CheckResult] = {}
|
|
112
|
+
|
|
113
|
+
# 1. order
|
|
114
|
+
if l_lo > u_hi:
|
|
115
|
+
parts["order"] = CheckResult(CHECK, Status.INCONSISTENT, "lower limit exceeds upper limit")
|
|
116
|
+
elif e_hi < l_lo or e_lo > u_hi:
|
|
117
|
+
parts["order"] = CheckResult(CHECK, Status.INCONSISTENT, "estimate lies outside its confidence interval")
|
|
118
|
+
else:
|
|
119
|
+
parts["order"] = CheckResult(CHECK, Status.CONSISTENT, "estimate can lie inside its confidence interval")
|
|
120
|
+
|
|
121
|
+
# 2. direction
|
|
122
|
+
if reported is None:
|
|
123
|
+
parts["direction"] = unassessable(CHECK, "no p-value reported")
|
|
124
|
+
else:
|
|
125
|
+
excludes = l_lo > null_v or u_hi < null_v # every compatible CI excludes the null
|
|
126
|
+
includes = l_hi <= null_v <= u_lo # every compatible CI contains the null
|
|
127
|
+
p_lo, p_hi = float(reported.lo), float(reported.hi)
|
|
128
|
+
conflict = None
|
|
129
|
+
if excludes and p_lo >= a:
|
|
130
|
+
conflict = f"CI excludes the null but p >= {a:g} is reported"
|
|
131
|
+
elif includes and p_hi < a:
|
|
132
|
+
conflict = f"CI contains the null but p < {a:g} is reported"
|
|
133
|
+
if conflict is None:
|
|
134
|
+
parts["direction"] = CheckResult(CHECK, Status.CONSISTENT, "CI and p agree on significance")
|
|
135
|
+
elif same_test:
|
|
136
|
+
parts["direction"] = CheckResult(CHECK, Status.INCONSISTENT, conflict)
|
|
137
|
+
else:
|
|
138
|
+
parts["direction"] = CheckResult(CHECK, Status.UNRESOLVED,
|
|
139
|
+
conflict + " (CI and p may come from different methods)")
|
|
140
|
+
|
|
141
|
+
# 3. recomputed p
|
|
142
|
+
parts["recomputed_p"] = _recompute(e_lo, e_hi, l_lo, l_hi, u_lo, u_hi, null_v, a, reported, same_test,
|
|
143
|
+
distribution, df, details)
|
|
144
|
+
|
|
145
|
+
status = _combine(parts)
|
|
146
|
+
details["parts"] = {k: {"status": r.status.value, "reason": r.reason} for k, r in parts.items()}
|
|
147
|
+
reasons = [f"{k}: {r.reason}" for k, r in parts.items() if r.status is status]
|
|
148
|
+
return CheckResult(CHECK, status, "; ".join(reasons), details)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _recompute(e_lo, e_hi, l_lo, l_hi, u_lo, u_hi, null_v, a, reported, same_test, distribution, df,
|
|
152
|
+
details) -> CheckResult:
|
|
153
|
+
if reported is None:
|
|
154
|
+
return unassessable(CHECK, "no p-value reported")
|
|
155
|
+
if not same_test:
|
|
156
|
+
return unassessable(CHECK, "CI and p not declared to come from the same Wald-type test")
|
|
157
|
+
if distribution not in ("z", "t"):
|
|
158
|
+
return unassessable(CHECK, "reference distribution not declared ('z' or 't')")
|
|
159
|
+
if distribution == "t":
|
|
160
|
+
try:
|
|
161
|
+
dfv = float(parse_printed(str(df)).value)
|
|
162
|
+
if dfv <= 0:
|
|
163
|
+
raise ValueError
|
|
164
|
+
except (ValueError, TypeError):
|
|
165
|
+
return unassessable(CHECK, "distribution 't' needs a positive df")
|
|
166
|
+
q = float(stats.t.ppf(1 - a / 2, dfv))
|
|
167
|
+
sf = lambda x: float(2 * stats.t.sf(x, dfv)) # noqa: E731
|
|
168
|
+
else:
|
|
169
|
+
q = float(stats.norm.ppf(1 - a / 2))
|
|
170
|
+
sf = lambda x: float(2 * stats.norm.sf(x)) # noqa: E731
|
|
171
|
+
|
|
172
|
+
m_lo, m_hi = (l_lo + u_lo) / 2, (l_hi + u_hi) / 2
|
|
173
|
+
if m_hi < e_lo or m_lo > e_hi:
|
|
174
|
+
return unassessable(CHECK, "CI not symmetric around the estimate on this scale; p not recomputed")
|
|
175
|
+
c_lo, c_hi = max(e_lo, m_lo), min(e_hi, m_hi) # centre compatible with estimate and CI
|
|
176
|
+
h_lo, h_hi = max((u_lo - l_hi) / 2, 0.0), (u_hi - l_lo) / 2
|
|
177
|
+
if h_hi <= 0:
|
|
178
|
+
return unassessable(CHECK, "CI has zero width")
|
|
179
|
+
d_lo = 0.0 if c_lo <= null_v <= c_hi else min(abs(c_lo - null_v), abs(c_hi - null_v))
|
|
180
|
+
d_hi = max(abs(c_lo - null_v), abs(c_hi - null_v))
|
|
181
|
+
s_lo = q * d_lo / h_hi
|
|
182
|
+
s_hi = math.inf if h_lo == 0 else q * d_hi / h_lo
|
|
183
|
+
p_lo, p_hi = (0.0 if math.isinf(s_hi) else sf(s_hi)), sf(s_lo)
|
|
184
|
+
details["recomputed_p"] = [p_lo, p_hi]
|
|
185
|
+
if p_lo <= float(reported.hi) and float(reported.lo) <= p_hi:
|
|
186
|
+
return CheckResult(CHECK, Status.CONSISTENT, "p recomputed from the CI matches the reported p")
|
|
187
|
+
return CheckResult(CHECK, Status.INCONSISTENT,
|
|
188
|
+
f"p recomputed from the CI ({p_lo:.4g} to {p_hi:.4g}) does not match the reported p")
|
statscrutiny/cli.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Command line interface.
|
|
2
|
+
|
|
3
|
+
statscrutiny text article.txt [more.txt ...] find APA-style results in text and check them
|
|
4
|
+
statscrutiny csv results.csv check one result per CSV row
|
|
5
|
+
|
|
6
|
+
CSV columns (header required; only `test`, `stat` and `p` or comparator `ns` are
|
|
7
|
+
mandatory): test, stat, p, comparator, df1, df2, n, tails, adjusted, df_method.
|
|
8
|
+
Use '-' to read from standard input. Output: a table (default), CSV or JSON.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import csv
|
|
15
|
+
import json
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from . import __version__
|
|
20
|
+
from .extract import check_text
|
|
21
|
+
from .pvalues import check_pvalue
|
|
22
|
+
from .result import CheckResult
|
|
23
|
+
|
|
24
|
+
FIELDS = ["source", "location", "result", "status", "crosses_alpha", "reason"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _read(path: str) -> str:
|
|
28
|
+
if path == "-":
|
|
29
|
+
return sys.stdin.read()
|
|
30
|
+
return Path(path).read_text(encoding="utf-8", errors="replace")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _row(source: str, location: str, result: str, res: CheckResult) -> dict:
|
|
34
|
+
return {"source": source, "location": location, "result": result, "status": res.status.value,
|
|
35
|
+
"crosses_alpha": res.details.get("crosses_alpha", ""), "reason": res.reason}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _truthy(v: str | None) -> bool:
|
|
39
|
+
return str(v or "").strip().lower() in {"1", "true", "yes", "y"}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _rows_text(args) -> list[dict]:
|
|
43
|
+
rows = []
|
|
44
|
+
for path in args.files:
|
|
45
|
+
for rep, res in check_text(_read(path), alpha=args.alpha, mode=args.mode, tails=args.tails):
|
|
46
|
+
rows.append(_row(path, f"char {rep.start}", rep.text, res))
|
|
47
|
+
return rows
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _rows_csv(args) -> list[dict]:
|
|
51
|
+
rows = []
|
|
52
|
+
for path in args.files:
|
|
53
|
+
reader = csv.DictReader(_read(path).splitlines())
|
|
54
|
+
for i, rec in enumerate(reader, start=2):
|
|
55
|
+
g = {k.strip().lower(): (v.strip() if isinstance(v, str) else v) for k, v in rec.items() if k}
|
|
56
|
+
empty = lambda k: g.get(k) or None # noqa: E731
|
|
57
|
+
res = check_pvalue(g.get("test", ""), g.get("stat", ""), empty("p"), g.get("comparator") or "=",
|
|
58
|
+
empty("df1"), empty("df2"), empty("n"),
|
|
59
|
+
tails=args.tails or empty("tails"), adjusted=_truthy(g.get("adjusted")),
|
|
60
|
+
alpha=args.alpha, mode=args.mode, df_method=empty("df_method"))
|
|
61
|
+
label = f"{g.get('test', '')}({','.join(x for x in (g.get('df1'), g.get('df2')) if x)}) = " \
|
|
62
|
+
f"{g.get('stat', '')}, p {g.get('comparator') or '='} {g.get('p') or ''}".strip()
|
|
63
|
+
rows.append(_row(path, f"line {i}", label, res))
|
|
64
|
+
return rows
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _print(rows: list[dict], fmt: str, out) -> None:
|
|
68
|
+
if fmt == "json":
|
|
69
|
+
json.dump(rows, out, indent=1, ensure_ascii=False)
|
|
70
|
+
out.write("\n")
|
|
71
|
+
elif fmt == "csv":
|
|
72
|
+
w = csv.DictWriter(out, fieldnames=FIELDS, lineterminator="\n")
|
|
73
|
+
w.writeheader()
|
|
74
|
+
w.writerows(rows)
|
|
75
|
+
else:
|
|
76
|
+
if not rows:
|
|
77
|
+
out.write("no results found\n")
|
|
78
|
+
return
|
|
79
|
+
width = min(max(len(r["result"]) for r in rows), 48)
|
|
80
|
+
for r in rows:
|
|
81
|
+
mark = "!!" if r["status"] == "inconsistent" else " "
|
|
82
|
+
out.write(f"{mark} {r['result'][:width]:<{width}} {r['status']:<12} {r['reason']}\n")
|
|
83
|
+
counts: dict[str, int] = {}
|
|
84
|
+
for r in rows:
|
|
85
|
+
counts[r["status"]] = counts.get(r["status"], 0) + 1
|
|
86
|
+
out.write("\n" + ", ".join(f"{k}: {v}" for k, v in sorted(counts.items())) + "\n")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def main(argv: list[str] | None = None) -> int:
|
|
90
|
+
ap = argparse.ArgumentParser(prog="statscrutiny", description="Conservative consistency checks for reported "
|
|
91
|
+
"statistics.")
|
|
92
|
+
ap.add_argument("--version", action="version", version=f"statscrutiny {__version__}")
|
|
93
|
+
sub = ap.add_subparsers(dest="command", required=True)
|
|
94
|
+
for name, help_ in (("text", "find APA-style results in plain-text files and check them"),
|
|
95
|
+
("csv", "check one result per row of CSV files")):
|
|
96
|
+
p = sub.add_parser(name, help=help_)
|
|
97
|
+
p.add_argument("files", nargs="+", help="input files ('-' for standard input)")
|
|
98
|
+
p.add_argument("--format", choices=["table", "csv", "json"], default="table")
|
|
99
|
+
p.add_argument("--mode", choices=["lenient", "strict"], default="lenient",
|
|
100
|
+
help="lenient: rounding or truncation (default); strict: round-to-nearest only")
|
|
101
|
+
p.add_argument("--tails", choices=["one", "two"], default=None,
|
|
102
|
+
help="number of tails for t, z, r (default: as stated, else both accepted)")
|
|
103
|
+
p.add_argument("--alpha", type=float, default=0.05)
|
|
104
|
+
p.add_argument("--only-flags", action="store_true", help="print inconsistent results only")
|
|
105
|
+
p.add_argument("--fail-on-flag", action="store_true", help="exit with status 1 if anything is inconsistent")
|
|
106
|
+
args = ap.parse_args(argv)
|
|
107
|
+
rows = _rows_text(args) if args.command == "text" else _rows_csv(args)
|
|
108
|
+
if args.only_flags:
|
|
109
|
+
rows = [r for r in rows if r["status"] == "inconsistent"]
|
|
110
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
111
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
112
|
+
_print(rows, args.format, sys.stdout)
|
|
113
|
+
if args.fail_on_flag and any(r["status"] == "inconsistent" for r in rows):
|
|
114
|
+
return 1
|
|
115
|
+
return 0
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
if __name__ == "__main__": # pragma: no cover
|
|
119
|
+
sys.exit(main())
|
statscrutiny/counts.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Counts, percentages and totals.
|
|
2
|
+
|
|
3
|
+
Checks (interval logic as in rounding.py; counts and denominators are exact):
|
|
4
|
+
|
|
5
|
+
1. check_percentage(count, denominator, percent): is 100*count/denominator inside
|
|
6
|
+
the printed percentage interval? If not, but an alternative denominator the
|
|
7
|
+
article reports (e.g. randomised vs analysed) fits, the result is UNRESOLVED.
|
|
8
|
+
2. check_percentage_granularity(percent, n): with no count printed, is there any
|
|
9
|
+
integer count c in [0, n] with 100*c/n inside the printed interval? (The GRIM
|
|
10
|
+
idea applied to proportions; Brown & Heathers 2017.)
|
|
11
|
+
3. check_count_sum(parts, total, ...): category counts against the reported total.
|
|
12
|
+
4. check_percentage_sum(parts, ...): printed percentages of one variable against 100
|
|
13
|
+
(each one is an interval).
|
|
14
|
+
Sums are checked ONLY when the caller asserts that the categories are mutually
|
|
15
|
+
exclusive (no multi-select item); otherwise UNASSESSABLE. Only over-summing is an
|
|
16
|
+
error: parts that add up to MORE than the total (or percentages that must exceed
|
|
17
|
+
100) are INCONSISTENT. Under-summing is UNRESOLVED, because an unreported
|
|
18
|
+
category ("missing", "other", "declined") can explain it even when the article
|
|
19
|
+
presents the list as complete.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import math
|
|
25
|
+
from fractions import Fraction
|
|
26
|
+
|
|
27
|
+
from .result import CheckResult, Status, unassessable
|
|
28
|
+
from .rounding import exact_int, printed_interval
|
|
29
|
+
|
|
30
|
+
CHECK_PCT = "percentage"
|
|
31
|
+
CHECK_SUM = "sum"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _pct_fits(count: int, denom: int, percent: str) -> bool:
|
|
35
|
+
return printed_interval(percent).contains(Fraction(100 * count, denom))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def check_percentage(count, denominator, percent: str, alt_denominators=()) -> CheckResult:
|
|
39
|
+
"""Check a printed 'count (percent%)' against its denominator."""
|
|
40
|
+
try:
|
|
41
|
+
c, d = exact_int(count), exact_int(denominator)
|
|
42
|
+
alts = [exact_int(a) for a in alt_denominators]
|
|
43
|
+
printed_interval(percent)
|
|
44
|
+
except (ValueError, TypeError) as e:
|
|
45
|
+
return unassessable(CHECK_PCT, f"invalid input: {e}")
|
|
46
|
+
if d == 0:
|
|
47
|
+
return unassessable(CHECK_PCT, "denominator is zero")
|
|
48
|
+
details = {"count": c, "denominator": d, "percent": percent, "exact": float(Fraction(100 * c, d))}
|
|
49
|
+
if c > d:
|
|
50
|
+
return CheckResult(CHECK_PCT, Status.INCONSISTENT, "count exceeds denominator", details)
|
|
51
|
+
if _pct_fits(c, d, percent):
|
|
52
|
+
return CheckResult(CHECK_PCT, Status.CONSISTENT, "percentage matches count/denominator", details)
|
|
53
|
+
fitting = [a for a in alts if a > 0 and c <= a and _pct_fits(c, a, percent)]
|
|
54
|
+
if fitting:
|
|
55
|
+
return CheckResult(CHECK_PCT, Status.UNRESOLVED,
|
|
56
|
+
"percentage matches only an alternative denominator", details | {"fits": fitting})
|
|
57
|
+
return CheckResult(CHECK_PCT, Status.INCONSISTENT,
|
|
58
|
+
"percentage does not match count/denominator under any rounding convention", details)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def check_percentage_granularity(percent: str, n) -> CheckResult:
|
|
62
|
+
"""Is a printed percentage achievable as c/n for an integer count c?"""
|
|
63
|
+
try:
|
|
64
|
+
n = exact_int(n)
|
|
65
|
+
iv = printed_interval(percent)
|
|
66
|
+
except (ValueError, TypeError) as e:
|
|
67
|
+
return unassessable(CHECK_PCT, f"invalid input: {e}")
|
|
68
|
+
if n == 0:
|
|
69
|
+
return unassessable(CHECK_PCT, "n is zero")
|
|
70
|
+
lo = max(math.ceil(iv.lo * n / 100), 0)
|
|
71
|
+
hi = min(math.floor(iv.hi * n / 100), n)
|
|
72
|
+
details = {"percent": percent, "n": n}
|
|
73
|
+
if lo <= hi:
|
|
74
|
+
return CheckResult(CHECK_PCT, Status.CONSISTENT, "some integer count gives this percentage",
|
|
75
|
+
details | {"counts": list(range(lo, min(hi, lo + 5) + 1))})
|
|
76
|
+
return CheckResult(CHECK_PCT, Status.INCONSISTENT, "no integer count out of n gives this percentage", details)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def check_count_sum(parts, total, exhaustive: bool = False, mutually_exclusive: bool = False) -> CheckResult:
|
|
80
|
+
"""Category counts of one variable against the reported total.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
parts: printed counts of the categories (int or digit strings).
|
|
84
|
+
total: printed total.
|
|
85
|
+
exhaustive: the article presents the categories as complete. Recorded in
|
|
86
|
+
details; under-summing stays UNRESOLVED either way.
|
|
87
|
+
mutually_exclusive: required. Each participant is in at most one category.
|
|
88
|
+
|
|
89
|
+
Returns CONSISTENT if the parts add up to the total, INCONSISTENT if they add
|
|
90
|
+
up to more, UNRESOLVED if they add up to less.
|
|
91
|
+
"""
|
|
92
|
+
if not mutually_exclusive:
|
|
93
|
+
return unassessable(CHECK_SUM, "categories not established as mutually exclusive")
|
|
94
|
+
try:
|
|
95
|
+
ps = [exact_int(p) for p in parts]
|
|
96
|
+
t = exact_int(total)
|
|
97
|
+
except (ValueError, TypeError) as e:
|
|
98
|
+
return unassessable(CHECK_SUM, f"invalid input: {e}")
|
|
99
|
+
s = sum(ps)
|
|
100
|
+
details = {"parts": ps, "sum": s, "total": t, "exhaustive": exhaustive}
|
|
101
|
+
if s == t:
|
|
102
|
+
return CheckResult(CHECK_SUM, Status.CONSISTENT, "counts sum to total", details)
|
|
103
|
+
if s > t:
|
|
104
|
+
return CheckResult(CHECK_SUM, Status.INCONSISTENT,
|
|
105
|
+
f"counts sum to {s}, more than the reported total {t}", details)
|
|
106
|
+
return CheckResult(CHECK_SUM, Status.UNRESOLVED,
|
|
107
|
+
f"counts sum to {s}, less than the reported total {t} (an unreported category could explain it)",
|
|
108
|
+
details)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def check_percentage_sum(parts, exhaustive: bool = False, mutually_exclusive: bool = False,
|
|
112
|
+
target: str = "100") -> CheckResult:
|
|
113
|
+
"""Printed percentages of mutually exclusive categories of one variable against 100.
|
|
114
|
+
|
|
115
|
+
Each printed percentage is an interval (rounding or truncation). INCONSISTENT
|
|
116
|
+
only if even the smallest compatible values add up to more than 100;
|
|
117
|
+
UNRESOLVED if even the largest add up to less than 100.
|
|
118
|
+
"""
|
|
119
|
+
if not mutually_exclusive:
|
|
120
|
+
return unassessable(CHECK_SUM, "categories not established as mutually exclusive")
|
|
121
|
+
try:
|
|
122
|
+
ivs = [printed_interval(p) for p in parts]
|
|
123
|
+
except (ValueError, TypeError) as e:
|
|
124
|
+
return unassessable(CHECK_SUM, f"invalid input: {e}")
|
|
125
|
+
lo, hi = sum(i.lo for i in ivs), sum(i.hi for i in ivs)
|
|
126
|
+
tgt = Fraction(int(target))
|
|
127
|
+
details = {"parts": list(parts), "min_sum": float(lo), "max_sum": float(hi), "exhaustive": exhaustive}
|
|
128
|
+
if lo <= tgt <= hi:
|
|
129
|
+
return CheckResult(CHECK_SUM, Status.CONSISTENT, "percentages can sum to 100", details)
|
|
130
|
+
if lo > tgt:
|
|
131
|
+
return CheckResult(CHECK_SUM, Status.INCONSISTENT,
|
|
132
|
+
"percentages exceed 100 under every rounding convention", details)
|
|
133
|
+
return CheckResult(CHECK_SUM, Status.UNRESOLVED,
|
|
134
|
+
"percentages sum to less than 100 (an unreported category could explain it)", details)
|
statscrutiny/extract.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Find APA-style test results in plain text and check them.
|
|
2
|
+
|
|
3
|
+
Recognised forms (as in statcheck; Nuijten et al., 2016), with optional spaces,
|
|
4
|
+
any minus sign (-, unicode minus, en dash) and any comparator (=, <, >, <=, >=,
|
|
5
|
+
unicode signs):
|
|
6
|
+
|
|
7
|
+
t(28) = 2.20, p = .036 t(45.3) = -2.01, p < .05
|
|
8
|
+
F(2, 57) = 3.41, p = .040 F(1,30)=4.17; p=.05
|
|
9
|
+
r(48) = .35, p = .013
|
|
10
|
+
chi2(1, N = 120) = 4.20, p = .040 (also chi-square, X2, and the chi letter with 2 or a superscript 2)
|
|
11
|
+
z = 2.45, p = .014 t(28) = 1.20, ns
|
|
12
|
+
|
|
13
|
+
The p-value must follow the statistic directly, separated only by a comma or
|
|
14
|
+
semicolon. Only the number of tails and p-value adjustment are read from the
|
|
15
|
+
surrounding sentence: "one-tailed" / "one-sided" sets tails='one';
|
|
16
|
+
"two-tailed" / "two-sided" sets tails='two'; "Bonferroni", "Holm", "corrected",
|
|
17
|
+
"adjusted", "FDR", "Tukey", "Sidak" mark the p-value as adjusted (UNASSESSABLE).
|
|
18
|
+
Results that do not fit these forms are not extracted: statscrutiny does not
|
|
19
|
+
guess.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import re
|
|
25
|
+
from dataclasses import asdict, dataclass
|
|
26
|
+
|
|
27
|
+
from .pvalues import check_pvalue
|
|
28
|
+
from .result import CheckResult
|
|
29
|
+
|
|
30
|
+
_MINUS = str.maketrans({"−": "-", "–": "-", "—": "-", "‐": "-", "‑": "-"})
|
|
31
|
+
_NUM = r"-?\s?(?:\d+(?:\.\d+)?|\.\d+)"
|
|
32
|
+
_DF = r"\d+(?:\.\d+)?"
|
|
33
|
+
_HEAD = {
|
|
34
|
+
"t": rf"(?<![A-Za-z])t\s*\(\s*(?P<df1>{_DF})\s*\)",
|
|
35
|
+
"F": rf"(?<![A-Za-z])F\s*\(\s*(?P<df1>{_DF})\s*,\s*(?P<df2>{_DF})\s*\)",
|
|
36
|
+
"r": rf"(?<![A-Za-z])r\s*\(\s*(?P<df1>\d+)\s*\)",
|
|
37
|
+
"chi2": rf"(?:χ|Χ|[Cc]hi|X)\s*-?\s*(?:2|²|\^2|square[d]?)\s*"
|
|
38
|
+
rf"\(\s*(?P<df1>{_DF})\s*(?:,\s*[Nn]\s*=\s*(?P<n>\d[\d,]*)\s*)?\)",
|
|
39
|
+
"z": r"(?<![A-Za-z])[zZ]",
|
|
40
|
+
}
|
|
41
|
+
_STAT = rf"\s*=\s*(?P<stat>{_NUM})"
|
|
42
|
+
_P = (r"\s*[,;]?\s*(?:(?:[pP]\s*(?P<comp><=|>=|=|<|>|≤|≥)\s*(?P<p>\d*\.\d+|[01](?![\d.])))"
|
|
43
|
+
r"|(?P<ns>n\.\s?s\.|ns\b))")
|
|
44
|
+
_PATTERNS = {k: re.compile(h + _STAT + _P) for k, h in _HEAD.items()}
|
|
45
|
+
_ONE = re.compile(r"one[- ]?(?:tailed|sided)|directional", re.I)
|
|
46
|
+
_TWO = re.compile(r"two[- ]?(?:tailed|sided)", re.I)
|
|
47
|
+
_ADJ = re.compile(r"bonferroni|holm|corrected|adjusted|\bfdr\b|false discovery|tukey|[sš]id[aá]k|scheff", re.I)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class ReportedResult:
|
|
52
|
+
"""One test result found in text. Numbers are kept as printed strings."""
|
|
53
|
+
test: str
|
|
54
|
+
stat: str
|
|
55
|
+
p: str | None
|
|
56
|
+
comparator: str
|
|
57
|
+
df1: str | None = None
|
|
58
|
+
df2: str | None = None
|
|
59
|
+
n: str | None = None
|
|
60
|
+
tails: str | None = None
|
|
61
|
+
adjusted: bool = False
|
|
62
|
+
text: str = ""
|
|
63
|
+
start: int = 0
|
|
64
|
+
end: int = 0
|
|
65
|
+
|
|
66
|
+
def as_dict(self) -> dict:
|
|
67
|
+
return asdict(self)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
_BOUNDARY = re.compile(r"[.!?](?=\s)|\n")
|
|
71
|
+
_ABBREV = {"e.g", "i.e", "al", "vs", "cf", "approx", "fig", "figs", "no", "eq", "ref", "resp", "n.s", "dr", "etc"}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _boundaries(text: str) -> list[int]:
|
|
75
|
+
"""Positions just after each sentence end (period, ! or ? before whitespace, or newline)."""
|
|
76
|
+
out = []
|
|
77
|
+
for m in _BOUNDARY.finditer(text):
|
|
78
|
+
if m.group() == ".":
|
|
79
|
+
word = re.search(r"([A-Za-z.]+)$", text[max(0, m.start() - 10):m.start()])
|
|
80
|
+
if word and word.group(1).lower().strip(".") in _ABBREV:
|
|
81
|
+
continue
|
|
82
|
+
out.append(m.end())
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _sentence(text: str, start: int, end: int, bounds: list[int]) -> str:
|
|
87
|
+
left = max((b for b in bounds if b <= start), default=0)
|
|
88
|
+
right = min((b for b in bounds if b > end), default=len(text))
|
|
89
|
+
return text[left:right]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def extract_results(text: str) -> list[ReportedResult]:
|
|
93
|
+
"""Return every recognised test result in `text`, in order of appearance."""
|
|
94
|
+
norm = text.translate(_MINUS) # one-to-one replacement: offsets stay valid
|
|
95
|
+
bounds = _boundaries(norm)
|
|
96
|
+
found: list[ReportedResult] = []
|
|
97
|
+
for test, pat in _PATTERNS.items():
|
|
98
|
+
for m in pat.finditer(norm):
|
|
99
|
+
g = m.groupdict()
|
|
100
|
+
sent = _sentence(norm, m.start(), m.end(), bounds)
|
|
101
|
+
tails = "one" if _ONE.search(sent) else ("two" if _TWO.search(sent) else None)
|
|
102
|
+
if g.get("ns"):
|
|
103
|
+
comp, p = "ns", None
|
|
104
|
+
else:
|
|
105
|
+
comp, p = g["comp"], g["p"]
|
|
106
|
+
found.append(ReportedResult(
|
|
107
|
+
test=test, stat=g["stat"].replace(" ", ""), p=p, comparator=comp,
|
|
108
|
+
df1=g.get("df1"), df2=g.get("df2"), n=(g.get("n") or None) and g["n"].replace(",", ""),
|
|
109
|
+
tails=tails if test in ("t", "z", "r") else None, adjusted=bool(_ADJ.search(sent)),
|
|
110
|
+
text=text[m.start():m.end()], start=m.start(), end=m.end()))
|
|
111
|
+
found.sort(key=lambda r: r.start)
|
|
112
|
+
return found
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def check_text(text: str, alpha: float = 0.05, mode: str = "lenient",
|
|
116
|
+
tails: str | None = None) -> list[tuple[ReportedResult, CheckResult]]:
|
|
117
|
+
"""Extract every APA-style result from `text` and check its p-value.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
text: plain text (e.g. an article converted from PDF or HTML).
|
|
121
|
+
alpha: significance level for the `crosses_alpha` flag.
|
|
122
|
+
mode: 'lenient' (rounding or truncation) or 'strict' (round-to-nearest).
|
|
123
|
+
tails: override the number of tails for every t, z and r result
|
|
124
|
+
('one' or 'two'); None keeps what the sentence says (unstated: both
|
|
125
|
+
accepted).
|
|
126
|
+
"""
|
|
127
|
+
out = []
|
|
128
|
+
for r in extract_results(text):
|
|
129
|
+
t = tails if (tails is not None and r.test in ("t", "z", "r")) else r.tails
|
|
130
|
+
res = check_pvalue(r.test, r.stat, r.p, r.comparator, r.df1, r.df2, r.n, tails=t,
|
|
131
|
+
adjusted=r.adjusted, alpha=alpha, mode=mode)
|
|
132
|
+
out.append((r, res))
|
|
133
|
+
return out
|