manuscript-stats-check 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 QKCLAW Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: manuscript-stats-check
3
+ Version: 0.1.0
4
+ Summary: Zero-dependency deterministic checker for OR/HR/RR, 95% confidence intervals, and P-value consistency in academic manuscripts (Altman-Bland method).
5
+ Author-email: QKCLAW Team <hello@qkclaw.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://qkclaw.com/en/tools/or-ci-checker/
8
+ Project-URL: Documentation, https://qkclaw.com/en/guides/medical-stats-checklist/
9
+ Project-URL: Repository, https://github.com/Louisone1/manuscript-stats-check
10
+ Project-URL: Bug Tracker, https://github.com/Louisone1/manuscript-stats-check/issues
11
+ Keywords: biostatistics,epidemiology,odds-ratio,confidence-interval,p-value,peer-review,academic-publishing,metascience,manuscript-screening
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
22
+ Classifier: Topic :: Text Processing
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Dynamic: license-file
27
+
28
+ # manuscript-stats-check
29
+
30
+ Deterministic, zero-dependency Python library and CLI for verifying reported **OR / HR / RR / IRR / PR / sHR / Exp(B)** effect sizes, **95% confidence intervals**, and **P values** in biomedical and epidemiological manuscripts.
31
+
32
+ > **Prefer a zero-install, zero-upload browser calculator?** Try the free interactive web tool (runs 100% locally in your browser):
33
+ > **[QKCLAW Free OR / 95% CI / P-Value Consistency Checker](https://qkclaw.com/en/tools/or-ci-checker/)**
34
+
35
+ ## Why this exists
36
+
37
+ Tools such as `statcheck` focus on APA-style `t`, `F`, `r`, and `chi-square` statistics in psychology papers, leaving **clinical, biomedical, and public-health regression tables** (Odds Ratios, Hazard Ratios, Risk Ratios) largely unchecked during desk screening and peer review.
38
+
39
+ Copy-paste typos in regression tables frequently produce mathematically impossible entries such as:
40
+
41
+ - `OR = 1.18 (95% CI: 0.86–1.62, P = 0.004)` — 95% CI crosses the null value `1.0`, yet `P < 0.01` (Altman–Bland implied `P ≈ 0.3056`);
42
+ - Point estimate lying outside its own 95% CI or strongly asymmetric on the natural-log scale;
43
+ - Inverted or non-positive confidence interval bounds.
44
+
45
+ `manuscript-stats-check` implements the **log-scale symmetry test** and the **Altman & Bland (BMJ 2011; 343: d2304)** reverse-engineering formula (`SE = (ln U − ln L) / (2 × 1.96)`, `z = |ln(est)| / SE`, `P = erfc(z / √2)`) with zero external dependencies.
46
+
47
+ ## Quick Start
48
+
49
+ ```bash
50
+ pip install manuscript-stats-check
51
+ ```
52
+
53
+ Check a single regression row:
54
+
55
+ ```bash
56
+ manuscript-stats-check --single 1.18 0.86 1.62 --p 0.004
57
+ # [1] ERROR | OR=1.18 (95% CI 0.86-1.62, reported P 0.004) | implied P=0.3056
58
+ # - (ERROR:CI_CROSSES_NULL_BUT_P_SIG) 95% CI [0.86, 1.62] crosses null 1.0 (Altman-Bland implied P=0.3056), contradicting reported P = 0.004.
59
+ ```
60
+
61
+ Scan a manuscript excerpt or table dump (plain text or Markdown, English or Chinese punctuation supported):
62
+
63
+ ```bash
64
+ cat abstract.txt | manuscript-stats-check --json
65
+ ```
66
+
67
+ Use in Python:
68
+
69
+ ```python
70
+ from manuscript_stats_check import check_ratio, scan_text
71
+
72
+ res = check_ratio(1.18, 0.86, 1.62, "0.004", metric="OR")
73
+ print(res.status, res.implied_p, [i.code for i in res.issues])
74
+ # error 0.305561 ['CI_CROSSES_NULL_BUT_P_SIG']
75
+
76
+ for item in scan_text("Adjusted aHR = 1.85 (95% CI: 1.24–2.76, P = 0.003)"):
77
+ print(item.to_dict())
78
+ ```
79
+
80
+ ## Statistical Scope & Caveats
81
+
82
+ - Designed for **Wald-type 95% confidence intervals** on log-transformed ratio scales (standard logistic, Cox proportional hazards, Poisson/log-binomial regression).
83
+ - Exact CIs, profile-likelihood CIs, Firth penalized likelihood, or sparse-cell estimates can legitimately show mild log-scale asymmetry; these are flagged as `warn` rather than `error` unless the reported `P` directly contradicts the null crossing.
84
+ - Always treat flagged entries as **editorial queries for author verification**, never as automatic allegations of misconduct.
85
+
86
+ ## Related Free Editorial Resources
87
+
88
+ - Interactive browser checker (no upload): [OR / 95% CI / P-Value Checker](https://qkclaw.com/en/tools/or-ci-checker/)
89
+ - Editorial screening guide: [Medical Manuscript Stats & Ethics Checklist](https://qkclaw.com/en/guides/medical-stats-checklist/)
90
+ - Reference verification tool: [Free DOI & Retraction Batch Checker](https://qkclaw.com/en/tools/doi-retraction-checker/)
91
+
92
+ ## References
93
+
94
+ - Altman DG, Bland JM. How to obtain the P value from a confidence interval. *BMJ* 2011;343:d2304. https://doi.org/10.1136/bmj.d2304
95
+ - Altman DG, Bland JM. How to obtain the confidence interval from a P value. *BMJ* 2011;343:d2090. https://doi.org/10.1136/bmj.d2090
96
+
97
+ ## License
98
+
99
+ MIT — see [LICENSE](LICENSE). Maintained by the QKCLAW Team.
@@ -0,0 +1,72 @@
1
+ # manuscript-stats-check
2
+
3
+ Deterministic, zero-dependency Python library and CLI for verifying reported **OR / HR / RR / IRR / PR / sHR / Exp(B)** effect sizes, **95% confidence intervals**, and **P values** in biomedical and epidemiological manuscripts.
4
+
5
+ > **Prefer a zero-install, zero-upload browser calculator?** Try the free interactive web tool (runs 100% locally in your browser):
6
+ > **[QKCLAW Free OR / 95% CI / P-Value Consistency Checker](https://qkclaw.com/en/tools/or-ci-checker/)**
7
+
8
+ ## Why this exists
9
+
10
+ Tools such as `statcheck` focus on APA-style `t`, `F`, `r`, and `chi-square` statistics in psychology papers, leaving **clinical, biomedical, and public-health regression tables** (Odds Ratios, Hazard Ratios, Risk Ratios) largely unchecked during desk screening and peer review.
11
+
12
+ Copy-paste typos in regression tables frequently produce mathematically impossible entries such as:
13
+
14
+ - `OR = 1.18 (95% CI: 0.86–1.62, P = 0.004)` — 95% CI crosses the null value `1.0`, yet `P < 0.01` (Altman–Bland implied `P ≈ 0.3056`);
15
+ - Point estimate lying outside its own 95% CI or strongly asymmetric on the natural-log scale;
16
+ - Inverted or non-positive confidence interval bounds.
17
+
18
+ `manuscript-stats-check` implements the **log-scale symmetry test** and the **Altman & Bland (BMJ 2011; 343: d2304)** reverse-engineering formula (`SE = (ln U − ln L) / (2 × 1.96)`, `z = |ln(est)| / SE`, `P = erfc(z / √2)`) with zero external dependencies.
19
+
20
+ ## Quick Start
21
+
22
+ ```bash
23
+ pip install manuscript-stats-check
24
+ ```
25
+
26
+ Check a single regression row:
27
+
28
+ ```bash
29
+ manuscript-stats-check --single 1.18 0.86 1.62 --p 0.004
30
+ # [1] ERROR | OR=1.18 (95% CI 0.86-1.62, reported P 0.004) | implied P=0.3056
31
+ # - (ERROR:CI_CROSSES_NULL_BUT_P_SIG) 95% CI [0.86, 1.62] crosses null 1.0 (Altman-Bland implied P=0.3056), contradicting reported P = 0.004.
32
+ ```
33
+
34
+ Scan a manuscript excerpt or table dump (plain text or Markdown, English or Chinese punctuation supported):
35
+
36
+ ```bash
37
+ cat abstract.txt | manuscript-stats-check --json
38
+ ```
39
+
40
+ Use in Python:
41
+
42
+ ```python
43
+ from manuscript_stats_check import check_ratio, scan_text
44
+
45
+ res = check_ratio(1.18, 0.86, 1.62, "0.004", metric="OR")
46
+ print(res.status, res.implied_p, [i.code for i in res.issues])
47
+ # error 0.305561 ['CI_CROSSES_NULL_BUT_P_SIG']
48
+
49
+ for item in scan_text("Adjusted aHR = 1.85 (95% CI: 1.24–2.76, P = 0.003)"):
50
+ print(item.to_dict())
51
+ ```
52
+
53
+ ## Statistical Scope & Caveats
54
+
55
+ - Designed for **Wald-type 95% confidence intervals** on log-transformed ratio scales (standard logistic, Cox proportional hazards, Poisson/log-binomial regression).
56
+ - Exact CIs, profile-likelihood CIs, Firth penalized likelihood, or sparse-cell estimates can legitimately show mild log-scale asymmetry; these are flagged as `warn` rather than `error` unless the reported `P` directly contradicts the null crossing.
57
+ - Always treat flagged entries as **editorial queries for author verification**, never as automatic allegations of misconduct.
58
+
59
+ ## Related Free Editorial Resources
60
+
61
+ - Interactive browser checker (no upload): [OR / 95% CI / P-Value Checker](https://qkclaw.com/en/tools/or-ci-checker/)
62
+ - Editorial screening guide: [Medical Manuscript Stats & Ethics Checklist](https://qkclaw.com/en/guides/medical-stats-checklist/)
63
+ - Reference verification tool: [Free DOI & Retraction Batch Checker](https://qkclaw.com/en/tools/doi-retraction-checker/)
64
+
65
+ ## References
66
+
67
+ - Altman DG, Bland JM. How to obtain the P value from a confidence interval. *BMJ* 2011;343:d2304. https://doi.org/10.1136/bmj.d2304
68
+ - Altman DG, Bland JM. How to obtain the confidence interval from a P value. *BMJ* 2011;343:d2090. https://doi.org/10.1136/bmj.d2090
69
+
70
+ ## License
71
+
72
+ MIT — see [LICENSE](LICENSE). Maintained by the QKCLAW Team.
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "manuscript-stats-check"
7
+ version = "0.1.0"
8
+ description = "Zero-dependency deterministic checker for OR/HR/RR, 95% confidence intervals, and P-value consistency in academic manuscripts (Altman-Bland method)."
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.9"
12
+ authors = [
13
+ {name = "QKCLAW Team", email = "hello@qkclaw.com"}
14
+ ]
15
+ keywords = [
16
+ "biostatistics",
17
+ "epidemiology",
18
+ "odds-ratio",
19
+ "confidence-interval",
20
+ "p-value",
21
+ "peer-review",
22
+ "academic-publishing",
23
+ "metascience",
24
+ "manuscript-screening",
25
+ ]
26
+ classifiers = [
27
+ "Development Status :: 4 - Beta",
28
+ "Intended Audience :: Science/Research",
29
+ "License :: OSI Approved :: MIT License",
30
+ "Programming Language :: Python :: 3",
31
+ "Programming Language :: Python :: 3.9",
32
+ "Programming Language :: Python :: 3.10",
33
+ "Programming Language :: Python :: 3.11",
34
+ "Programming Language :: Python :: 3.12",
35
+ "Programming Language :: Python :: 3.13",
36
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
37
+ "Topic :: Text Processing",
38
+ ]
39
+
40
+ [project.urls]
41
+ Homepage = "https://qkclaw.com/en/tools/or-ci-checker/"
42
+ Documentation = "https://qkclaw.com/en/guides/medical-stats-checklist/"
43
+ Repository = "https://github.com/Louisone1/manuscript-stats-check"
44
+ "Bug Tracker" = "https://github.com/Louisone1/manuscript-stats-check/issues"
45
+
46
+ [project.scripts]
47
+ manuscript-stats-check = "manuscript_stats_check.cli:main"
48
+
49
+ [tool.setuptools.packages.find]
50
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """Deterministic Altman-Bland checker for OR/HR/RR, 95% CI, and P-value consistency."""
2
+
3
+ from .checker import CheckIssue, CheckResult, check_ratio, scan_text
4
+
5
+ __all__ = ["CheckIssue", "CheckResult", "check_ratio", "scan_text"]
6
+ __version__ = "0.1.0"
@@ -0,0 +1,311 @@
1
+ """Core deterministic engine for checking reported ratio effect sizes (OR/HR/RR/IRR/PR/sHR/Exp(B)),
2
+ 95% confidence intervals, and P values using log-scale symmetry and Altman-Bland (BMJ 2011;343:d2304).
3
+
4
+ Zero third-party dependencies — Python 3.9+ standard library only.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ import re
10
+ from dataclasses import asdict, dataclass
11
+ from typing import Any
12
+
13
+ Z_95 = 1.959963984540054
14
+
15
+ # Full-width / typographic normalization
16
+ _TRANS = str.maketrans({
17
+ "\u3000": " ",
18
+ "\u00a0": " ",
19
+ "\uff08": "(",
20
+ "\uff09": ")",
21
+ "\uff0c": ",",
22
+ "\uff1b": ";",
23
+ "\uff1a": ":",
24
+ "\uff1d": "=",
25
+ "\uff1c": "<",
26
+ "\uff1e": ">",
27
+ "\u2212": "-",
28
+ "\u2013": "-",
29
+ "\u2014": "-",
30
+ "\uff5e": "~",
31
+ "\u2264": "<=",
32
+ "\u2265": ">=",
33
+ "\u00d7": "*",
34
+ "\u2715": "*",
35
+ })
36
+
37
+ _SCI_MULT_RE = re.compile(r"^([+-]?\d+(?:\.\d+)?)\s*\*\s*10\s*\^?\s*([+-]?\d+)$")
38
+ _SUP_MAP = str.maketrans("⁰¹²³⁴⁵⁶⁷⁸⁹⁻⁺", "0123456789-+")
39
+
40
+ # Case-sensitive metric labels (matches tools_widgets.py audited regex to avoid matching prose "or"/"pr")
41
+ _METRIC_PAT = r"(?:a?OR|AOR|cOR|uOR|a?HR|AHR|sHR|SHR|a?RR|ARR|IRR|a?PR|Exp\s*\(\s*B\s*\)|exp\s*\(\s*B\s*\))"
42
+ _NUM_PAT = r"\d+(?:\.\d+)?"
43
+ _PVAL_PAT = r"(?:(?:<=|>=|<|>|=)\s*)?(?:\d+(?:\.\d+)?(?:\s*\*\s*10\s*(?:\^?\s*[+-]?\d+|[⁻⁺⁰¹²³⁴⁵⁶⁷⁸⁹]+)|[eE][+-]?\d+)?|\.\d+)"
44
+
45
+ _SCAN_RE = re.compile(
46
+ rf"(?<![A-Za-z0-9_])(?P<metric>{_METRIC_PAT})\s*(?:=|:)?\s*(?P<est>{_NUM_PAT})\s*"
47
+ rf"(?:\(\s*(?:95\s*%\s*(?:CI|C\.I\.|置信区间)\s*[:=]?\s*)?|,?\s*95\s*%\s*(?:CI|C\.I\.|置信区间)\s*[:=]?\s*)"
48
+ rf"(?P<lo>{_NUM_PAT})\s*(?:-|~|to|,)\s*(?P<hi>{_NUM_PAT})"
49
+ rf"(?:\s*[,;]?\s*[Pp](?:\s*-?\s*value)?\s*(?P<p>{_PVAL_PAT}))?"
50
+ rf"\s*\)?"
51
+ rf"(?:\s*[,;]?\s*[Pp](?:\s*-?\s*value)?\s*(?P<p_after>{_PVAL_PAT}))?"
52
+ )
53
+
54
+
55
+ @dataclass
56
+ class CheckIssue:
57
+ code: str
58
+ severity: str # "error" | "warn"
59
+ message: str
60
+
61
+
62
+ @dataclass
63
+ class CheckResult:
64
+ metric: str
65
+ estimate: float
66
+ ci_low: float
67
+ ci_high: float
68
+ reported_p: str | None
69
+ log_midpoint: float | None
70
+ implied_se: float | None
71
+ implied_z: float | None
72
+ implied_p: float | None
73
+ status: str # "ok" | "warn" | "error"
74
+ issues: list[CheckIssue]
75
+ snippet: str = ""
76
+
77
+ def to_dict(self) -> dict[str, Any]:
78
+ d = asdict(self)
79
+ return d
80
+
81
+
82
+ def normalize_text(text: str) -> str:
83
+ s = text.translate(_TRANS)
84
+ # Convert Unicode superscript exponents after 10 (e.g., 10⁻⁴ -> 10^-4)
85
+ s = re.sub(r"10([⁻⁺⁰¹²³⁴⁵⁶⁷⁸⁹]+)", lambda m: "10^" + m.group(1).translate(_SUP_MAP), s)
86
+ return s
87
+
88
+
89
+ def parse_p_value(raw: str | None) -> tuple[str | None, float | None]:
90
+ """Parse P-value string such as '<0.001', '= 0.042', 'P = 2.3e-4', '1.5×10^-3' -> (op, value)."""
91
+ if raw is None:
92
+ return None, None
93
+ s = normalize_text(str(raw)).strip()
94
+ if not s:
95
+ return None, None
96
+ s = re.sub(r"^[Pp](?:\s*-?\s*value)?\s*", "", s).strip()
97
+ op = "="
98
+ for prefix in ("<=", ">=", "<", ">", "="):
99
+ if s.startswith(prefix):
100
+ op = prefix
101
+ s = s[len(prefix):].strip()
102
+ break
103
+ s = s.rstrip(".,;)")
104
+ if not s:
105
+ return None, None
106
+ m = _SCI_MULT_RE.match(s)
107
+ try:
108
+ val = float(m.group(1)) * (10.0 ** int(m.group(2))) if m else float(s)
109
+ except ValueError:
110
+ return None, None
111
+ if not math.isfinite(val) or val < 0.0 or val > 1.0:
112
+ return None, None
113
+ return op, val
114
+
115
+
116
+ def _altman_bland_p(est: float, lo: float, hi: float) -> tuple[float, float, float, float]:
117
+ """Compute geometric midpoint, SE, z, and two-sided normal P on the natural log scale."""
118
+ ln_est = math.log(est)
119
+ ln_lo = math.log(lo)
120
+ ln_hi = math.log(hi)
121
+ geom_mid = math.exp(0.5 * (ln_lo + ln_hi))
122
+ se = (ln_hi - ln_lo) / (2.0 * Z_95)
123
+ z = abs(ln_est) / se if se > 0 else float("inf")
124
+ p = math.erfc(z / math.sqrt(2.0))
125
+ return geom_mid, se, z, p
126
+
127
+
128
+ def _rounding_tolerance_log(est: float, lo: float, hi: float) -> float:
129
+ """Adaptive tolerance for 2-decimal rounded published tables (lo/hi rounding propagates to ln)."""
130
+ # Half-ULP at 2 decimal places is 0.005; expand slightly for very small values
131
+ step = 0.005
132
+ d_est = step / max(est, 0.02)
133
+ d_lo = step / max(lo, 0.02)
134
+ d_hi = step / max(hi, 0.02)
135
+ return max(0.03, d_est + 0.5 * (d_lo + d_hi) + 0.015)
136
+
137
+
138
+ def check_ratio(
139
+ estimate: float,
140
+ ci_low: float,
141
+ ci_high: float,
142
+ reported_p: str | float | None = None,
143
+ *,
144
+ metric: str = "OR",
145
+ snippet: str = "",
146
+ ) -> CheckResult:
147
+ """Validate one reported ratio effect size (OR/HR/RR/IRR/PR/sHR/Exp(B)) and its 95% CI + optional P."""
148
+ issues: list[CheckIssue] = []
149
+ p_str = None if reported_p is None else str(reported_p).strip() or None
150
+
151
+ if not all(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) for v in (estimate, ci_low, ci_high)):
152
+ issues.append(CheckIssue("NON_FINITE", "error", "Estimate and 95% CI bounds must be finite numbers."))
153
+ return CheckResult(metric, float("nan"), float("nan"), float("nan"), p_str, None, None, None, None, "error", issues, snippet)
154
+
155
+ if estimate <= 0 or ci_low <= 0 or ci_high <= 0:
156
+ issues.append(
157
+ CheckIssue(
158
+ "NON_POSITIVE_RATIO",
159
+ "error",
160
+ f"Ratio metric {metric} and 95% CI bounds must all be strictly positive (got {estimate}, [{ci_low}, {ci_high}]).",
161
+ )
162
+ )
163
+ return CheckResult(metric, estimate, ci_low, ci_high, p_str, None, None, None, None, "error", issues, snippet)
164
+
165
+ if ci_low >= ci_high:
166
+ issues.append(
167
+ CheckIssue(
168
+ "INVERTED_OR_ZERO_WIDTH_CI",
169
+ "error",
170
+ f"95% CI lower bound ({ci_low}) must be strictly less than upper bound ({ci_high}).",
171
+ )
172
+ )
173
+ return CheckResult(metric, estimate, ci_low, ci_high, p_str, None, None, None, None, "error", issues, snippet)
174
+
175
+ if not (ci_low <= estimate <= ci_high):
176
+ issues.append(
177
+ CheckIssue(
178
+ "ESTIMATE_OUTSIDE_CI",
179
+ "error",
180
+ f"Point estimate {metric}={estimate} lies outside its reported 95% CI [{ci_low}, {ci_high}].",
181
+ )
182
+ )
183
+
184
+ geom_mid, se, z, implied_p = _altman_bland_p(estimate, ci_low, ci_high)
185
+
186
+ # Check log-scale symmetry: ln(est) should equal 0.5*(ln(lo)+ln(hi)) within rounding tolerance
187
+ ln_diff = abs(math.log(estimate) - math.log(geom_mid))
188
+ tol = _rounding_tolerance_log(estimate, ci_low, ci_high)
189
+ if ln_diff > max(tol * 2.0, 0.12):
190
+ issues.append(
191
+ CheckIssue(
192
+ "LOG_ASYMMETRY_SEVERE",
193
+ "error",
194
+ f"Reported {metric}={estimate} is strongly asymmetric on the log scale relative to 95% CI [{ci_low}, {ci_high}] (geometric midpoint={geom_mid:.3f}).",
195
+ )
196
+ )
197
+ elif ln_diff > tol:
198
+ issues.append(
199
+ CheckIssue(
200
+ "LOG_ASYMMETRY_MILD",
201
+ "warn",
202
+ f"Reported {metric}={estimate} deviates mildly from 95% CI geometric midpoint ({geom_mid:.3f}); verify rounding or exact-method CI.",
203
+ )
204
+ )
205
+
206
+ # Check P-value consistency if reported
207
+ if p_str is not None:
208
+ op, p_val = parse_p_value(p_str)
209
+ if op is None or p_val is None:
210
+ issues.append(CheckIssue("UNPARSEABLE_P", "warn", f"Could not parse reported P value: {p_str!r}."))
211
+ else:
212
+ crosses_null = ci_low < 1.0 < ci_high
213
+ strictly_away_from_null = ci_high < 1.0 or ci_low > 1.0
214
+ claims_sig_05 = (op in ("<", "<=") and p_val <= 0.05) or (op == "=" and p_val < 0.05)
215
+ claims_nonsig_05 = (op in (">", ">=") and p_val >= 0.05) or (op == "=" and p_val > 0.05)
216
+
217
+ if crosses_null and claims_sig_05 and implied_p >= 0.06:
218
+ issues.append(
219
+ CheckIssue(
220
+ "CI_CROSSES_NULL_BUT_P_SIG",
221
+ "error",
222
+ f"95% CI [{ci_low}, {ci_high}] crosses null 1.0 (Altman-Bland implied P={implied_p:.4f}), contradicting reported P {op} {p_val:g}.",
223
+ )
224
+ )
225
+ elif strictly_away_from_null and claims_nonsig_05 and implied_p <= 0.04:
226
+ issues.append(
227
+ CheckIssue(
228
+ "CI_EXCLUDES_NULL_BUT_P_NONSIG",
229
+ "error",
230
+ f"95% CI [{ci_low}, {ci_high}] excludes null 1.0 (Altman-Bland implied P={implied_p:.4f}), contradicting reported P {op} {p_val:g}.",
231
+ )
232
+ )
233
+ elif op == "=" and p_val > 0 and implied_p > 0:
234
+ abs_diff = abs(implied_p - p_val)
235
+ ratio = max(implied_p, p_val) / max(min(implied_p, p_val), 1e-12)
236
+ if abs_diff >= 0.05 and ratio >= 2.5:
237
+ issues.append(
238
+ CheckIssue(
239
+ "P_MAGNITUDE_MISMATCH",
240
+ "error",
241
+ f"Reported P={p_val:g} diverges substantially from Altman-Bland implied P={implied_p:.4f}.",
242
+ )
243
+ )
244
+ elif abs_diff >= 0.02 and ratio >= 1.8:
245
+ issues.append(
246
+ CheckIssue(
247
+ "P_MAGNITUDE_DRIFT",
248
+ "warn",
249
+ f"Reported P={p_val:g} differs from Altman-Bland implied P={implied_p:.4f} (could reflect likelihood-ratio/exact P or typo).",
250
+ )
251
+ )
252
+ elif op in ("<", "<=") and implied_p > max(p_val * 2.5, p_val + 0.01):
253
+ issues.append(
254
+ CheckIssue(
255
+ "P_BOUND_CONTRADICTION",
256
+ "error",
257
+ f"Altman-Bland implied P={implied_p:.4f} exceeds reported upper bound P {op} {p_val:g}.",
258
+ )
259
+ )
260
+ elif op in (">", ">=") and implied_p < min(p_val * 0.4, p_val - 0.01):
261
+ issues.append(
262
+ CheckIssue(
263
+ "P_LOWER_BOUND_CONTRADICTION",
264
+ "error",
265
+ f"Altman-Bland implied P={implied_p:.4f} is much smaller than reported lower bound P {op} {p_val:g}.",
266
+ )
267
+ )
268
+
269
+ status = "ok"
270
+ if any(i.severity == "error" for i in issues):
271
+ status = "error"
272
+ elif any(i.severity == "warn" for i in issues):
273
+ status = "warn"
274
+
275
+ return CheckResult(
276
+ metric=metric,
277
+ estimate=estimate,
278
+ ci_low=ci_low,
279
+ ci_high=ci_high,
280
+ reported_p=p_str,
281
+ log_midpoint=round(geom_mid, 4),
282
+ implied_se=round(se, 5),
283
+ implied_z=round(z, 4),
284
+ implied_p=round(implied_p, 6),
285
+ status=status,
286
+ issues=issues,
287
+ snippet=snippet,
288
+ )
289
+
290
+
291
+ def scan_text(text: str) -> list[CheckResult]:
292
+ """Extract and validate all reported ratio + 95% CI (+ optional P) triplets from free text or tables."""
293
+ norm = normalize_text(text)
294
+ results: list[CheckResult] = []
295
+ for m in _SCAN_RE.finditer(norm):
296
+ metric = m.group("metric").replace(" ", "")
297
+ est = float(m.group("est"))
298
+ lo = float(m.group("lo"))
299
+ hi = float(m.group("hi"))
300
+ p_raw = m.group("p") or m.group("p_after")
301
+ results.append(
302
+ check_ratio(
303
+ est,
304
+ lo,
305
+ hi,
306
+ p_raw,
307
+ metric=metric,
308
+ snippet=m.group(0).strip(),
309
+ )
310
+ )
311
+ return results
@@ -0,0 +1,69 @@
1
+ """Command-line interface for manuscript-stats-check."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from . import __version__
10
+ from .checker import check_ratio, scan_text
11
+
12
+
13
+ def main(argv: list[str] | None = None) -> int:
14
+ ap = argparse.ArgumentParser(
15
+ prog="manuscript-stats-check",
16
+ description="Deterministic Altman-Bland checker for OR/HR/RR, 95% CI, and P-value consistency in academic manuscripts.",
17
+ )
18
+ ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
19
+ ap.add_argument("--single", nargs=3, metavar=("EST", "CI_LOW", "CI_HIGH"), type=float, help="Check a single ratio triplet.")
20
+ ap.add_argument("--metric", default="OR", help="Metric label for --single (default: OR).")
21
+ ap.add_argument("--p", default=None, help="Optional reported P-value string for --single (e.g. '<0.001' or '0.004').")
22
+ ap.add_argument("--file", default="", help="UTF-8 text/Markdown file to scan (reads stdin if omitted and --single not used).")
23
+ ap.add_argument("--json", dest="as_json", action="store_true", help="Output structured JSON.")
24
+ args = ap.parse_args(argv)
25
+
26
+ if args.single is not None:
27
+ est, lo, hi = args.single
28
+ results = [check_ratio(est, lo, hi, args.p, metric=args.metric)]
29
+ else:
30
+ if args.file:
31
+ text = Path(args.file).read_text(encoding="utf-8")
32
+ else:
33
+ text = sys.stdin.read()
34
+ results = scan_text(text)
35
+
36
+ errors = sum(1 for r in results if r.status == "error")
37
+ warns = sum(1 for r in results if r.status == "warn")
38
+
39
+ if args.as_json:
40
+ print(
41
+ json.dumps(
42
+ {
43
+ "tool": "manuscript-stats-check",
44
+ "version": __version__,
45
+ "checked": len(results),
46
+ "errors": errors,
47
+ "warnings": warns,
48
+ "results": [r.to_dict() for r in results],
49
+ },
50
+ ensure_ascii=False,
51
+ indent=2,
52
+ )
53
+ )
54
+ else:
55
+ if not results:
56
+ print("No ratio + 95% CI triplets detected.")
57
+ for idx, r in enumerate(results, 1):
58
+ p_disp = f", reported P {r.reported_p}" if r.reported_p else ""
59
+ imp_p = f"{r.implied_p:.4f}" if r.implied_p is not None else "n/a"
60
+ print(f"[{idx}] {r.status.upper():5s} | {r.metric}={r.estimate} (95% CI {r.ci_low}-{r.ci_high}{p_disp}) | implied P={imp_p}")
61
+ for iss in r.issues:
62
+ print(f" - ({iss.severity.upper()}:{iss.code}) {iss.message}")
63
+ print(f"Summary: checked={len(results)}, errors={errors}, warnings={warns}")
64
+
65
+ return 1 if errors > 0 else 0
66
+
67
+
68
+ if __name__ == "__main__":
69
+ raise SystemExit(main())
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: manuscript-stats-check
3
+ Version: 0.1.0
4
+ Summary: Zero-dependency deterministic checker for OR/HR/RR, 95% confidence intervals, and P-value consistency in academic manuscripts (Altman-Bland method).
5
+ Author-email: QKCLAW Team <hello@qkclaw.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://qkclaw.com/en/tools/or-ci-checker/
8
+ Project-URL: Documentation, https://qkclaw.com/en/guides/medical-stats-checklist/
9
+ Project-URL: Repository, https://github.com/Louisone1/manuscript-stats-check
10
+ Project-URL: Bug Tracker, https://github.com/Louisone1/manuscript-stats-check/issues
11
+ Keywords: biostatistics,epidemiology,odds-ratio,confidence-interval,p-value,peer-review,academic-publishing,metascience,manuscript-screening
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
22
+ Classifier: Topic :: Text Processing
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Dynamic: license-file
27
+
28
+ # manuscript-stats-check
29
+
30
+ Deterministic, zero-dependency Python library and CLI for verifying reported **OR / HR / RR / IRR / PR / sHR / Exp(B)** effect sizes, **95% confidence intervals**, and **P values** in biomedical and epidemiological manuscripts.
31
+
32
+ > **Prefer a zero-install, zero-upload browser calculator?** Try the free interactive web tool (runs 100% locally in your browser):
33
+ > **[QKCLAW Free OR / 95% CI / P-Value Consistency Checker](https://qkclaw.com/en/tools/or-ci-checker/)**
34
+
35
+ ## Why this exists
36
+
37
+ Tools such as `statcheck` focus on APA-style `t`, `F`, `r`, and `chi-square` statistics in psychology papers, leaving **clinical, biomedical, and public-health regression tables** (Odds Ratios, Hazard Ratios, Risk Ratios) largely unchecked during desk screening and peer review.
38
+
39
+ Copy-paste typos in regression tables frequently produce mathematically impossible entries such as:
40
+
41
+ - `OR = 1.18 (95% CI: 0.86–1.62, P = 0.004)` — 95% CI crosses the null value `1.0`, yet `P < 0.01` (Altman–Bland implied `P ≈ 0.3056`);
42
+ - Point estimate lying outside its own 95% CI or strongly asymmetric on the natural-log scale;
43
+ - Inverted or non-positive confidence interval bounds.
44
+
45
+ `manuscript-stats-check` implements the **log-scale symmetry test** and the **Altman & Bland (BMJ 2011; 343: d2304)** reverse-engineering formula (`SE = (ln U − ln L) / (2 × 1.96)`, `z = |ln(est)| / SE`, `P = erfc(z / √2)`) with zero external dependencies.
46
+
47
+ ## Quick Start
48
+
49
+ ```bash
50
+ pip install manuscript-stats-check
51
+ ```
52
+
53
+ Check a single regression row:
54
+
55
+ ```bash
56
+ manuscript-stats-check --single 1.18 0.86 1.62 --p 0.004
57
+ # [1] ERROR | OR=1.18 (95% CI 0.86-1.62, reported P 0.004) | implied P=0.3056
58
+ # - (ERROR:CI_CROSSES_NULL_BUT_P_SIG) 95% CI [0.86, 1.62] crosses null 1.0 (Altman-Bland implied P=0.3056), contradicting reported P = 0.004.
59
+ ```
60
+
61
+ Scan a manuscript excerpt or table dump (plain text or Markdown, English or Chinese punctuation supported):
62
+
63
+ ```bash
64
+ cat abstract.txt | manuscript-stats-check --json
65
+ ```
66
+
67
+ Use in Python:
68
+
69
+ ```python
70
+ from manuscript_stats_check import check_ratio, scan_text
71
+
72
+ res = check_ratio(1.18, 0.86, 1.62, "0.004", metric="OR")
73
+ print(res.status, res.implied_p, [i.code for i in res.issues])
74
+ # error 0.305561 ['CI_CROSSES_NULL_BUT_P_SIG']
75
+
76
+ for item in scan_text("Adjusted aHR = 1.85 (95% CI: 1.24–2.76, P = 0.003)"):
77
+ print(item.to_dict())
78
+ ```
79
+
80
+ ## Statistical Scope & Caveats
81
+
82
+ - Designed for **Wald-type 95% confidence intervals** on log-transformed ratio scales (standard logistic, Cox proportional hazards, Poisson/log-binomial regression).
83
+ - Exact CIs, profile-likelihood CIs, Firth penalized likelihood, or sparse-cell estimates can legitimately show mild log-scale asymmetry; these are flagged as `warn` rather than `error` unless the reported `P` directly contradicts the null crossing.
84
+ - Always treat flagged entries as **editorial queries for author verification**, never as automatic allegations of misconduct.
85
+
86
+ ## Related Free Editorial Resources
87
+
88
+ - Interactive browser checker (no upload): [OR / 95% CI / P-Value Checker](https://qkclaw.com/en/tools/or-ci-checker/)
89
+ - Editorial screening guide: [Medical Manuscript Stats & Ethics Checklist](https://qkclaw.com/en/guides/medical-stats-checklist/)
90
+ - Reference verification tool: [Free DOI & Retraction Batch Checker](https://qkclaw.com/en/tools/doi-retraction-checker/)
91
+
92
+ ## References
93
+
94
+ - Altman DG, Bland JM. How to obtain the P value from a confidence interval. *BMJ* 2011;343:d2304. https://doi.org/10.1136/bmj.d2304
95
+ - Altman DG, Bland JM. How to obtain the confidence interval from a P value. *BMJ* 2011;343:d2090. https://doi.org/10.1136/bmj.d2090
96
+
97
+ ## License
98
+
99
+ MIT — see [LICENSE](LICENSE). Maintained by the QKCLAW Team.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/manuscript_stats_check/__init__.py
5
+ src/manuscript_stats_check/checker.py
6
+ src/manuscript_stats_check/cli.py
7
+ src/manuscript_stats_check.egg-info/PKG-INFO
8
+ src/manuscript_stats_check.egg-info/SOURCES.txt
9
+ src/manuscript_stats_check.egg-info/dependency_links.txt
10
+ src/manuscript_stats_check.egg-info/entry_points.txt
11
+ src/manuscript_stats_check.egg-info/top_level.txt
12
+ tests/test_checker.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ manuscript-stats-check = manuscript_stats_check.cli:main
@@ -0,0 +1,72 @@
1
+ import math
2
+ import unittest
3
+
4
+ from manuscript_stats_check import check_ratio, scan_text
5
+ from manuscript_stats_check.checker import parse_p_value
6
+ from manuscript_stats_check.cli import main as cli_main
7
+
8
+
9
+ class TestManuscriptStatsCheck(unittest.TestCase):
10
+ def test_valid_or_passes(self):
11
+ r = check_ratio(2.15, 1.42, 3.26, "<0.001", metric="OR")
12
+ self.assertEqual(r.status, "ok")
13
+ self.assertEqual(r.issues, [])
14
+ self.assertIsNotNone(r.implied_p)
15
+ self.assertLess(r.implied_p, 0.001)
16
+
17
+ def test_ci_crosses_null_but_p_significant_caught(self):
18
+ # Exact published example from QKCLAW Medical Stats Guide
19
+ r = check_ratio(1.18, 0.86, 1.62, "0.004", metric="OR")
20
+ self.assertEqual(r.status, "error")
21
+ self.assertTrue(any(i.code == "CI_CROSSES_NULL_BUT_P_SIG" for i in r.issues))
22
+ self.assertAlmostEqual(r.implied_p, 0.3056, places=3)
23
+
24
+ def test_ci_excludes_null_but_p_nonsig_caught(self):
25
+ r = check_ratio(2.40, 1.50, 3.84, "0.18", metric="HR")
26
+ self.assertEqual(r.status, "error")
27
+ self.assertTrue(any(i.code == "CI_EXCLUDES_NULL_BUT_P_NONSIG" for i in r.issues))
28
+
29
+ def test_estimate_outside_ci_and_asymmetry(self):
30
+ r = check_ratio(3.50, 1.20, 2.80, "0.01", metric="aOR")
31
+ self.assertEqual(r.status, "error")
32
+ codes = {i.code for i in r.issues}
33
+ self.assertIn("ESTIMATE_OUTSIDE_CI", codes)
34
+ self.assertIn("LOG_ASYMMETRY_SEVERE", codes)
35
+
36
+ def test_non_positive_and_inverted_bounds(self):
37
+ r1 = check_ratio(-1.2, 0.5, 2.0)
38
+ self.assertEqual(r1.status, "error")
39
+ self.assertEqual(r1.issues[0].code, "NON_POSITIVE_RATIO")
40
+ r2 = check_ratio(1.5, 2.1, 1.2)
41
+ self.assertEqual(r2.status, "error")
42
+ self.assertEqual(r2.issues[0].code, "INVERTED_OR_ZERO_WIDTH_CI")
43
+
44
+ def test_scientific_notation_and_unicode_p_values(self):
45
+ op1, v1 = parse_p_value("P = 2.3×10⁻⁴")
46
+ self.assertEqual(op1, "=")
47
+ self.assertTrue(math.isclose(v1, 2.3e-4, rel_tol=1e-6))
48
+ op2, v2 = parse_p_value("<= 1.5e-3")
49
+ self.assertEqual(op2, "<=")
50
+ self.assertTrue(math.isclose(v2, 1.5e-3, rel_tol=1e-6))
51
+
52
+ def test_scan_text_ignores_english_word_or_and_parses_bilingual(self):
53
+ sample = (
54
+ "Patients received drug A or drug B (95% CI not reported). "
55
+ "Multivariate Cox model: aHR = 1.85 (95% CI: 1.24–2.76, P = 0.003); "
56
+ "Logistic regression showed OR = 1.18 (95% CI: 0.86–1.62, P = 0.004); "
57
+ "中文回归表:OR=2.15(95% CI:1.42~3.26,P<0.001)。"
58
+ )
59
+ res = scan_text(sample)
60
+ self.assertEqual(len(res), 3)
61
+ self.assertEqual([r.metric for r in res], ["aHR", "OR", "OR"])
62
+ self.assertEqual([r.status for r in res], ["ok", "error", "ok"])
63
+
64
+ def test_cli_exit_codes(self):
65
+ rc_ok = cli_main(["--single", "2.15", "1.42", "3.26", "--p", "<0.001", "--json"])
66
+ rc_err = cli_main(["--single", "1.18", "0.86", "1.62", "--p", "0.004", "--json"])
67
+ self.assertEqual(rc_ok, 0)
68
+ self.assertEqual(rc_err, 1)
69
+
70
+
71
+ if __name__ == "__main__":
72
+ unittest.main()