kotha 0.2.0rc1__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.
kotha-0.2.0rc1/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tatsuki Onishi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: kotha
3
+ Version: 0.2.0rc1
4
+ Summary: RCT-anchored conditional borrowing of external aggregate evidence with recorded design judgement (research use only)
5
+ Author: Tatsuki Onishi
6
+ License-Expression: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Intended Audience :: Science/Research
9
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy>=1.24
14
+ Requires-Dist: scipy>=1.10
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest>=7; extra == "test"
17
+ Requires-Dist: jsonschema>=4; extra == "test"
18
+ Dynamic: license-file
19
+
20
+ # kotha 0.2.0rc1 (release candidate)
21
+
22
+ **Research use only. Not validated for individual treatment decisions.**
23
+
24
+ `kotha` is a decision/reporting workflow for RCT-anchored, conditional borrowing of
25
+ external *aggregate* evidence (HR, OR or RR on the log scale). It is **not** a novel
26
+ Bayesian estimator: every borrowing computation (fixed-alpha and normalised power
27
+ priors, robust MAP mixture) is established methodology, implemented here by a frozen,
28
+ byte-identical copy of the R1 study engine (`kotha/_engine/kotha_borrow.py`,
29
+ SHA-256 `7b7d07f4bf6e29833ea869e82db5141258a8408682aa2f3ddd1e6059a8a2e7ef`).
30
+ What the workflow adds is structured recording of the target estimand and source
31
+ provenance, a human design-credibility judgement (Stage C) recorded separately from the
32
+ statistical conflict diagnostic, RCT-only results shown first, and machine-readable,
33
+ hash-sealed job/result files.
34
+
35
+ ## Limitations (always shown)
36
+
37
+ - Aggregate data cannot distinguish bias in external evidence from genuine effect modification.
38
+ - Compatibility statistics are not evidence of exchangeability; there is no automatic causal transportability.
39
+ - In the R1 simulations the KOTHA workflow showed **no net decision advantage over robust MAP combined with the same observable screen**.
40
+ - The prespecified Stage C beneficial-borrowing threshold failed in R1 (0.4895 < 0.5).
41
+ - The Stage C judgement is recorded as entered by the named assessor; the software does not verify it.
42
+
43
+ ## Install (from a built wheel)
44
+
45
+ ```
46
+ python -m venv .venv
47
+ # Linux/macOS: source .venv/bin/activate Windows PowerShell: .venv\Scripts\Activate.ps1
48
+ pip install kotha-0.2.0rc1-py3-none-any.whl
49
+ ```
50
+
51
+ Dependencies: Python >= 3.10, NumPy >= 1.24, SciPy >= 1.10.
52
+
53
+ ## Command line
54
+
55
+ ```
56
+ kotha validate JOB.json
57
+ kotha run JOB.json --output RESULT.json --report REPORT.html
58
+ kotha report RESULT.json --output REPORT.html
59
+ kotha verify RESULT.json --job JOB.json
60
+ kotha hash JOB.json
61
+ kotha template-csv --output estimates.csv
62
+ ```
63
+
64
+ `run` refuses to write output when validation fails. `verify` (and `report`, and result
65
+ import in the web app) reports three checks: (a) schema, version, IDs and SHA-256 hashes
66
+ are consistent; (b) re-running the embedded job with this build's engine reproduces the
67
+ result (numbers within 1e-10, all other fields identical, except the self-reported
68
+ runtime/build metadata and timestamp); (c) with `--job`, the inputs equal that job. The
69
+ command exits 0 only if (a) and (b) pass and (c), when given, matches. Without (c) the
70
+ inputs, including the Stage C record, come from the file and may have been edited before
71
+ recomputation. None of the checks shows who produced the file or that the analysis is
72
+ causally valid or transportable. Missing or malformed files give a one-line error and
73
+ exit code 2; add `--verbose` to see a traceback for internal errors.
74
+
75
+ Development: `pip install -e .[test]` (pytest, jsonschema). Building the web app:
76
+ `pip install -r ../webapp/requirements-build.txt`, then `python ../webapp/build.py --fetch-runtime`
77
+ (or `--runtime-dir DIR` with the eight Pyodide files downloaded yourself; every file must match the
78
+ SHA-256 in the acquisition ledger, and TLS verification is never disabled). Windows notes:
79
+ `docs/INSTALL_WINDOWS.md`. Privacy: `docs/PRIVACY.md`. Changes: `CHANGELOG.md`.
80
+
81
+ ## Python API
82
+
83
+ ```python
84
+ import kotha
85
+ job = kotha.load_job("JOB.json")
86
+ report = kotha.validate_job(job) # errors / warnings / flags
87
+ result = kotha.run_analysis(job) # raises ContractError if invalid
88
+ kotha.export_result(result, "RESULT.json")
89
+ kotha.export_report(result, "REPORT.html")
90
+ ```
91
+
92
+ ## Browser bridge
93
+
94
+ The static web app (same engine, run in self-hosted Pyodide) downloads `kotha_job.json`;
95
+ `kotha run` on that file produces a `kotha_result.json` that the web app can import and
96
+ verify. See `docs/LOCAL_RUNNER.md`.
97
+
98
+ ## Licence and citation
99
+
100
+ Original KOTHA code: MIT licence (`LICENSE`). The licence does not cover third-party
101
+ components; notices for the web build (Pyodide MPL-2.0, CPython, Emscripten runtime libraries,
102
+ NumPy, SciPy, OpenBLAS) are in `webapp/third_party/NOTICES.md`. Citation metadata: `CITATION.cff`.
103
+ `kotha --version` prints the version and the source commit recorded at build time.
@@ -0,0 +1,84 @@
1
+ # kotha 0.2.0rc1 (release candidate)
2
+
3
+ **Research use only. Not validated for individual treatment decisions.**
4
+
5
+ `kotha` is a decision/reporting workflow for RCT-anchored, conditional borrowing of
6
+ external *aggregate* evidence (HR, OR or RR on the log scale). It is **not** a novel
7
+ Bayesian estimator: every borrowing computation (fixed-alpha and normalised power
8
+ priors, robust MAP mixture) is established methodology, implemented here by a frozen,
9
+ byte-identical copy of the R1 study engine (`kotha/_engine/kotha_borrow.py`,
10
+ SHA-256 `7b7d07f4bf6e29833ea869e82db5141258a8408682aa2f3ddd1e6059a8a2e7ef`).
11
+ What the workflow adds is structured recording of the target estimand and source
12
+ provenance, a human design-credibility judgement (Stage C) recorded separately from the
13
+ statistical conflict diagnostic, RCT-only results shown first, and machine-readable,
14
+ hash-sealed job/result files.
15
+
16
+ ## Limitations (always shown)
17
+
18
+ - Aggregate data cannot distinguish bias in external evidence from genuine effect modification.
19
+ - Compatibility statistics are not evidence of exchangeability; there is no automatic causal transportability.
20
+ - In the R1 simulations the KOTHA workflow showed **no net decision advantage over robust MAP combined with the same observable screen**.
21
+ - The prespecified Stage C beneficial-borrowing threshold failed in R1 (0.4895 < 0.5).
22
+ - The Stage C judgement is recorded as entered by the named assessor; the software does not verify it.
23
+
24
+ ## Install (from a built wheel)
25
+
26
+ ```
27
+ python -m venv .venv
28
+ # Linux/macOS: source .venv/bin/activate Windows PowerShell: .venv\Scripts\Activate.ps1
29
+ pip install kotha-0.2.0rc1-py3-none-any.whl
30
+ ```
31
+
32
+ Dependencies: Python >= 3.10, NumPy >= 1.24, SciPy >= 1.10.
33
+
34
+ ## Command line
35
+
36
+ ```
37
+ kotha validate JOB.json
38
+ kotha run JOB.json --output RESULT.json --report REPORT.html
39
+ kotha report RESULT.json --output REPORT.html
40
+ kotha verify RESULT.json --job JOB.json
41
+ kotha hash JOB.json
42
+ kotha template-csv --output estimates.csv
43
+ ```
44
+
45
+ `run` refuses to write output when validation fails. `verify` (and `report`, and result
46
+ import in the web app) reports three checks: (a) schema, version, IDs and SHA-256 hashes
47
+ are consistent; (b) re-running the embedded job with this build's engine reproduces the
48
+ result (numbers within 1e-10, all other fields identical, except the self-reported
49
+ runtime/build metadata and timestamp); (c) with `--job`, the inputs equal that job. The
50
+ command exits 0 only if (a) and (b) pass and (c), when given, matches. Without (c) the
51
+ inputs, including the Stage C record, come from the file and may have been edited before
52
+ recomputation. None of the checks shows who produced the file or that the analysis is
53
+ causally valid or transportable. Missing or malformed files give a one-line error and
54
+ exit code 2; add `--verbose` to see a traceback for internal errors.
55
+
56
+ Development: `pip install -e .[test]` (pytest, jsonschema). Building the web app:
57
+ `pip install -r ../webapp/requirements-build.txt`, then `python ../webapp/build.py --fetch-runtime`
58
+ (or `--runtime-dir DIR` with the eight Pyodide files downloaded yourself; every file must match the
59
+ SHA-256 in the acquisition ledger, and TLS verification is never disabled). Windows notes:
60
+ `docs/INSTALL_WINDOWS.md`. Privacy: `docs/PRIVACY.md`. Changes: `CHANGELOG.md`.
61
+
62
+ ## Python API
63
+
64
+ ```python
65
+ import kotha
66
+ job = kotha.load_job("JOB.json")
67
+ report = kotha.validate_job(job) # errors / warnings / flags
68
+ result = kotha.run_analysis(job) # raises ContractError if invalid
69
+ kotha.export_result(result, "RESULT.json")
70
+ kotha.export_report(result, "REPORT.html")
71
+ ```
72
+
73
+ ## Browser bridge
74
+
75
+ The static web app (same engine, run in self-hosted Pyodide) downloads `kotha_job.json`;
76
+ `kotha run` on that file produces a `kotha_result.json` that the web app can import and
77
+ verify. See `docs/LOCAL_RUNNER.md`.
78
+
79
+ ## Licence and citation
80
+
81
+ Original KOTHA code: MIT licence (`LICENSE`). The licence does not cover third-party
82
+ components; notices for the web build (Pyodide MPL-2.0, CPython, Emscripten runtime libraries,
83
+ NumPy, SciPy, OpenBLAS) are in `webapp/third_party/NOTICES.md`. Citation metadata: `CITATION.cff`.
84
+ `kotha --version` prints the version and the source commit recorded at build time.
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kotha"
7
+ version = "0.2.0rc1"
8
+ description = "RCT-anchored conditional borrowing of external aggregate evidence with recorded design judgement (research use only)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "Tatsuki Onishi"}]
14
+ dependencies = ["numpy>=1.24", "scipy>=1.10"]
15
+ classifiers = ["Programming Language :: Python :: 3", "Intended Audience :: Science/Research", "Topic :: Scientific/Engineering :: Medical Science Apps."]
16
+
17
+ [project.optional-dependencies]
18
+ test = ["pytest>=7", "jsonschema>=4"]
19
+
20
+ [project.scripts]
21
+ kotha = "kotha.cli:main"
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
25
+
26
+ [tool.setuptools.package-data]
27
+ kotha = ["_build_info.json", "schemas/*.json", "_engine/*.py"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,24 @@
1
+ """KOTHA: RCT-anchored conditional-borrowing workflow (aggregate data) on the frozen R1 engine."""
2
+ from .analysis import __version__, engine_sha256, run_analysis, rct_only_summary
3
+ from .contract import SCHEMA_VERSION, canonical_json, input_hash, result_hash, seal_job, verify_result, ContractError
4
+ from .csvio import read_estimates_csv, write_estimates_csv, CsvError
5
+ from .report import render_html
6
+ from .validate import validate_job, DEFAULT_SETTINGS
7
+ from .verify import verify_by_recomputation
8
+ import json as _json
9
+
10
+
11
+ def load_job(path):
12
+ # utf-8-sig: accept a leading BOM (Windows Notepad, PowerShell 5.1 Set-Content -Encoding UTF8); content and hashes are unchanged.
13
+ with open(path, encoding="utf-8-sig") as fh:
14
+ return _json.load(fh)
15
+
16
+
17
+ def export_result(result, path):
18
+ with open(path, "w", encoding="utf-8") as fh:
19
+ _json.dump(result, fh, indent=1, ensure_ascii=False)
20
+
21
+
22
+ def export_report(result, path):
23
+ with open(path, "w", encoding="utf-8") as fh:
24
+ fh.write(render_html(result))
@@ -0,0 +1,3 @@
1
+ import sys
2
+ from .cli import main
3
+ sys.exit(main())
@@ -0,0 +1 @@
1
+ {"source_commit": "b1659165b6ba2ecb1dae0fe41c5ddca069724188", "source_dirty": false, "built_at": "1795397355"}
@@ -0,0 +1 @@
1
+ """Frozen KOTHA R1 numerical engine (byte-identical copy of R1/code/kotha_borrow.py)."""
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env python3
2
+ """KOTHA R1 common statistical interface.
3
+
4
+ One engine is used by the empirical analyses and the simulation.
5
+
6
+ Model (normal-normal random effects on log effect estimates y_i with SE s_i):
7
+ y_i | theta_i ~ N(theta_i, s_i^2), theta_i ~ N(mu, tau^2), tau ~ HalfNormal(tau_scale)
8
+ Target parameter: mu (mean log effect in the population represented by the RCTs), with a
9
+ prior on mu that encodes external evidence (or is vague). Conditional on tau the posterior of
10
+ mu is conjugate; tau is integrated by quadrature on a grid. Every prior on mu is a finite
11
+ mixture of normals, so posteriors are exact Gaussian mixtures over (tau grid x components).
12
+
13
+ Borrowing priors on mu (external summary m_E, V_E = Var(mu_E), T2_E = E[tau_E^2]):
14
+ * vague N(0, 10^2) (RCT-only)
15
+ * fixed-alpha power prior N(m_E, V_E / alpha) (summary-level; alpha fixed, so the
16
+ normalising constant does not depend on data and is irrelevant)
17
+ * normalised power prior alpha ~ U(0,1); prior N(m_E, V_E / alpha) normalised for each
18
+ alpha (Duan et al. 2006; Neuenschwander et al. 2009) -> mixture
19
+ * robust MAP (1-w) N(m_E, V_E + T2_E) + w N(m_E, 2^2) (Schmidli et al. 2014)
20
+ * study-level shared-tau power prior (legacy Module T formulation, for validation only)
21
+ """
22
+ import numpy as np
23
+ from scipy import stats
24
+ from scipy.special import ndtr, logsumexp
25
+
26
+ VAGUE_SD = 10.0
27
+ UNIT_INFO_SD = 2.0 # unit-information SD for a log hazard/odds ratio (~one event)
28
+ Z975 = stats.norm.ppf(0.975)
29
+
30
+
31
+ def tau_grid(scale=0.5, n=401, upper=None, kind='halfnormal'):
32
+ upper = upper if upper is not None else (4 * scale if kind == 'halfnormal' else 5.0)
33
+ t = np.linspace(0.0, upper, n)
34
+ if kind == 'halfnormal':
35
+ lp = stats.halfnorm.logpdf(t, scale=scale)
36
+ elif kind == 'halfcauchy':
37
+ lp = stats.halfcauchy.logpdf(t, scale=scale)
38
+ elif kind == 'zero':
39
+ return np.array([0.0]), np.array([0.0])
40
+ else:
41
+ raise ValueError(kind)
42
+ w = np.full(n, t[1] - t[0]); w[0] /= 2; w[-1] /= 2
43
+ return t, lp + np.log(w)
44
+
45
+
46
+ def _rct_terms(y, s, tau):
47
+ """Per tau: precision P, mean ybar and log K with prod N(y_i; mu, v_i) = K * N(mu; ybar, 1/P)."""
48
+ y = np.asarray(y, float)[None, :]; s = np.asarray(s, float)[None, :]
49
+ v = s ** 2 + tau[:, None] ** 2
50
+ P = np.sum(1 / v, axis=1)
51
+ ybar = np.sum(y / v, axis=1) / P
52
+ logK = np.sum(stats.norm.logpdf(y, ybar[:, None], np.sqrt(v)), axis=1) + 0.5 * np.log(2 * np.pi / P)
53
+ return P, ybar, logK
54
+
55
+
56
+ class Mixture:
57
+ def __init__(self, logw, mean, var):
58
+ logw = np.ravel(logw); self.mean = np.ravel(mean); self.var = np.ravel(var)
59
+ self.w = np.exp(logw - logsumexp(logw))
60
+ self.sd = np.sqrt(self.var)
61
+
62
+ def cdf(self, x):
63
+ x = np.atleast_1d(x)
64
+ return np.sum(self.w[None, :] * ndtr((x[:, None] - self.mean[None, :]) / self.sd[None, :]), axis=1)
65
+
66
+ def moments(self):
67
+ m = np.sum(self.w * self.mean)
68
+ v = np.sum(self.w * (self.var + self.mean ** 2)) - m ** 2
69
+ return m, v
70
+
71
+ def quantile(self, q, iters=60):
72
+ q = np.atleast_1d(q).astype(float)
73
+ m, v = self.moments(); sd = np.sqrt(v)
74
+ lo = np.full(q.shape, np.min(self.mean - 12 * self.sd)); hi = np.full(q.shape, np.max(self.mean + 12 * self.sd))
75
+ for _ in range(iters):
76
+ mid = (lo + hi) / 2
77
+ c = self.cdf(mid)
78
+ lo = np.where(c < q, mid, lo); hi = np.where(c >= q, mid, hi)
79
+ return (lo + hi) / 2
80
+
81
+
82
+ def posterior_mu(y, s, prior_components, tau=None, logtau=None, tau_prior=('halfnormal', 0.5)):
83
+ """prior_components: list of (logw, m, V) scalars or arrays over the tau grid."""
84
+ if tau is None:
85
+ tau, logtau = tau_grid(kind=tau_prior[0], scale=tau_prior[1])
86
+ P, ybar, logK = _rct_terms(y, s, tau)
87
+ LW, M, V, TAU = [], [], [], []
88
+ for (lw, m, Vk) in prior_components:
89
+ lw = np.broadcast_to(lw, tau.shape); m = np.broadcast_to(m, tau.shape); Vk = np.broadcast_to(Vk, tau.shape)
90
+ logmarg = logK + stats.norm.logpdf(ybar, m, np.sqrt(1 / P + Vk))
91
+ pv = 1 / (P + 1 / Vk)
92
+ pm = pv * (ybar * P + m / Vk)
93
+ LW.append(logtau + lw + logmarg); M.append(pm); V.append(pv)
94
+ LW = np.stack(LW, 1); M = np.stack(M, 1); V = np.stack(V, 1)
95
+ mix = Mixture(LW, M, V)
96
+ comp_w = np.exp(logsumexp(LW, axis=0) - logsumexp(LW)) # posterior weight per prior component
97
+ tau_w = np.exp(logsumexp(LW, axis=1) - logsumexp(LW))
98
+ return mix, comp_w, tau, tau_w
99
+
100
+
101
+ def summarise(mix, thresholds=(0.0, np.log(0.9), np.log(0.85), np.log(0.8)), level=0.95):
102
+ m, v = mix.moments()
103
+ lo, med, hi = mix.quantile([(1 - level) / 2, 0.5, 1 - (1 - level) / 2])
104
+ out = {'mean': m, 'sd': np.sqrt(v), 'median': med, 'lo': lo, 'hi': hi}
105
+ for t in thresholds:
106
+ out[f'p_lt_{np.exp(t):.2f}'] = float(mix.cdf(t)[0])
107
+ return out
108
+
109
+
110
+ # ---------- external-evidence summary ----------
111
+ def external_summary(yE, sE, tau_prior=('halfnormal', 0.5)):
112
+ mix, _, tau, tau_w = posterior_mu(yE, sE, [(0.0, 0.0, VAGUE_SD ** 2)], tau_prior=tau_prior)
113
+ m, v = mix.moments()
114
+ return {'m_E': m, 'V_E': v, 'T2_E': float(np.sum(tau_w * tau ** 2)), 'k_E': len(yE)}
115
+
116
+
117
+ # ---------- methods ----------
118
+ def rct_only(yR, sR, **kw):
119
+ return posterior_mu(yR, sR, [(0.0, 0.0, VAGUE_SD ** 2)], **kw)
120
+
121
+
122
+ def fixed_power_prior(yR, sR, ext, alpha, **kw):
123
+ if alpha <= 0:
124
+ return rct_only(yR, sR, **kw)
125
+ return posterior_mu(yR, sR, [(0.0, ext['m_E'], ext['V_E'] / alpha)], **kw)
126
+
127
+
128
+ def normalised_power_prior(yR, sR, ext, alphas=None, **kw):
129
+ alphas = np.linspace(0.01, 1.0, 100) if alphas is None else alphas
130
+ lw0 = -np.log(len(alphas))
131
+ comps = [(lw0, ext['m_E'], ext['V_E'] / a) for a in alphas]
132
+ mix, cw, tau, tw = posterior_mu(yR, sR, comps, **kw)
133
+ return mix, cw, alphas
134
+
135
+
136
+ def robust_map(yR, sR, ext, w_vague=0.5, vague_sd=UNIT_INFO_SD, **kw):
137
+ comps = [(np.log(1 - w_vague), ext['m_E'], ext['V_E'] + ext['T2_E']),
138
+ (np.log(w_vague), ext['m_E'], vague_sd ** 2)]
139
+ return posterior_mu(yR, sR, comps, **kw)
140
+
141
+
142
+ def study_level_power_prior(yR, sR, yE, sE, alpha, tau_prior=('halfcauchy', 0.5), mu_prior_sd=VAGUE_SD):
143
+ """Legacy Module T: L_R(mu,tau) * L_E(mu,tau)^alpha * p(mu) p(tau); exact by quadrature."""
144
+ tau, logtau = tau_grid(kind=tau_prior[0], scale=tau_prior[1], n=2001, upper=20.0)
145
+ if alpha <= 0:
146
+ return posterior_mu(yR, sR, [(0.0, 0.0, mu_prior_sd ** 2)], tau=tau, logtau=logtau)
147
+ PE, ybE, logKE = _rct_terms(yE, sE, tau)
148
+ # [K_E N(mu; ybE, 1/PE)]^alpha = exp(c) * N(mu; ybE, 1/(alpha PE))
149
+ c = alpha * logKE + alpha * 0.5 * np.log(PE / (2 * np.pi)) + 0.5 * np.log(2 * np.pi / (alpha * PE))
150
+ # combine with vague N(0, sd^2) prior on mu: product of two normals in mu
151
+ V1 = 1 / (alpha * PE); V0 = mu_prior_sd ** 2
152
+ Vc = 1 / (1 / V1 + 1 / V0); mc = Vc * (ybE / V1)
153
+ c = c + stats.norm.logpdf(ybE, 0.0, np.sqrt(V1 + V0))
154
+ return posterior_mu(yR, sR, [(c, mc, Vc)], tau=tau, logtau=logtau)
155
+
156
+
157
+ # ---------- frequentist ----------
158
+ def fixed_effect(y, s):
159
+ w = 1 / np.asarray(s) ** 2
160
+ est = np.sum(w * y) / np.sum(w); se = 1 / np.sqrt(np.sum(w))
161
+ z = est / se
162
+ return {'est': est, 'se': se, 'lo': est - Z975 * se, 'hi': est + Z975 * se, 'z': z, 'p': 2 * stats.norm.sf(abs(z))}
163
+
164
+
165
+ def dersimonian_laird(y, s):
166
+ y = np.asarray(y, float); s = np.asarray(s, float)
167
+ w = 1 / s ** 2; k = len(y)
168
+ fe = np.sum(w * y) / np.sum(w)
169
+ Q = float(np.sum(w * (y - fe) ** 2))
170
+ C = np.sum(w) - np.sum(w ** 2) / np.sum(w)
171
+ tau2 = max(0.0, (Q - (k - 1)) / C) if k > 1 else 0.0
172
+ wr = 1 / (s ** 2 + tau2)
173
+ est = np.sum(wr * y) / np.sum(wr); se = 1 / np.sqrt(np.sum(wr))
174
+ z = est / se
175
+ I2 = max(0.0, (Q - (k - 1)) / Q) * 100 if Q > 0 else 0.0
176
+ return {'est': est, 'se': se, 'lo': est - Z975 * se, 'hi': est + Z975 * se, 'z': z,
177
+ 'p': 2 * stats.norm.sf(abs(z)), 'tau2': tau2, 'Q': Q, 'Q_p': stats.chi2.sf(Q, k - 1) if k > 1 else np.nan, 'I2': I2, 'k': k}
178
+
179
+
180
+ # ---------- KOTHA workflow components ----------
181
+ def required_information(mcid_ratio, alpha=0.05, power=0.80):
182
+ """Fisher information (1/SE^2 of the log effect) needed to detect log(mcid) with given power."""
183
+ return ((stats.norm.ppf(1 - alpha / 2) + stats.norm.ppf(power)) / abs(np.log(mcid_ratio))) ** 2
184
+
185
+
186
+ def ois_events(mcid_ratio, alpha=0.05, power=0.80, D2=0.0):
187
+ """Events required (Schoenfeld / log-OR rare-event approximation, 1:1), heterogeneity-adjusted by 1/(1-D2)."""
188
+ return 4 * (stats.norm.ppf(1 - alpha / 2) + stats.norm.ppf(power)) ** 2 / np.log(mcid_ratio) ** 2 / (1 - D2)
189
+
190
+
191
+ def compatibility(rct_mean, rct_var, ext):
192
+ """Prior-predictive conflict z for the RCT-population mean vs the MAP predictive of external evidence."""
193
+ z = (rct_mean - ext['m_E']) / np.sqrt(rct_var + ext['V_E'] + ext['T2_E'])
194
+ return {'z': z, 'p': 2 * stats.norm.sf(abs(z))}
195
+
196
+
197
+ def kotha_decision(info_fraction, relevance_adequate, compat_p, conflict_level=0.05):
198
+ """Prespecified KOTHA R1 rule (see simulation_protocol_R1.md / BORROWING_METHOD_SELECTION).
199
+
200
+ Stage B states are diagnostic; borrowing is considered only if the RCT evidence is either
201
+ informationally insufficient or of inadequate relevance, AND no statistical conflict is detected.
202
+ """
203
+ info_ok = info_fraction >= 1.0
204
+ if info_ok and relevance_adequate:
205
+ return 'B1: adequate information and relevance -> RCT-only', False
206
+ if compat_p < conflict_level:
207
+ return ('B2/B3/B4 with prior-data conflict -> RCT-only; external evidence incompatible', False)
208
+ state = {(True, False): 'B2: adequate information, inadequate relevance',
209
+ (False, True): 'B3: inadequate information, adequate relevance',
210
+ (False, False): 'B4: inadequate information and relevance'}[(info_ok, relevance_adequate)]
211
+ return state + ' -> borrow (robust MAP)', True
@@ -0,0 +1,147 @@
1
+ """Adapter from a validated job to the frozen engine. No statistical formulas are defined here
2
+ beyond unit conversion (CI -> log-scale SE) and the R1 tipping-point scan."""
3
+ import copy
4
+ import datetime as _dt
5
+ import hashlib
6
+ import json
7
+ import platform
8
+ import sys
9
+ from importlib import resources
10
+
11
+ import numpy as np
12
+ from scipy import stats
13
+
14
+ from ._engine import kotha_borrow as kb
15
+ from . import texts
16
+ from .contract import RESULT_SCHEMA, SCHEMA_VERSION, ContractError, input_hash, result_hash
17
+ from .validate import DEFAULT_SETTINGS, validate_job
18
+
19
+ __version__ = "0.2.0rc1"
20
+ FROZEN_ENGINE_SHA256 = "7b7d07f4bf6e29833ea869e82db5141258a8408682aa2f3ddd1e6059a8a2e7ef"
21
+
22
+
23
+ def engine_sha256():
24
+ data = resources.files("kotha._engine").joinpath("kotha_borrow.py").read_bytes()
25
+ return hashlib.sha256(data).hexdigest()
26
+
27
+
28
+ def build_info():
29
+ try:
30
+ return json.loads(resources.files("kotha").joinpath("_build_info.json").read_text())
31
+ except (FileNotFoundError, ValueError):
32
+ return {"source_commit": "unrecorded"}
33
+
34
+
35
+ def runtime_info(access_path):
36
+ info = {"access_path": access_path, "python": platform.python_version(), "numpy": np.__version__,
37
+ "scipy": __import__("scipy").__version__, "platform": sys.platform, "pyodide": None}
38
+ if sys.platform == "emscripten":
39
+ try:
40
+ import pyodide
41
+ info["pyodide"] = pyodide.__version__
42
+ except ImportError:
43
+ pass
44
+ return info
45
+
46
+
47
+ def log_effect(e):
48
+ y = float(np.log(e["estimate"]))
49
+ if e.get("se_log") is not None:
50
+ return y, float(e["se_log"])
51
+ z = stats.norm.ppf(1 - (1 - e["ci_level"]) / 2)
52
+ return y, float((np.log(e["ci_upper"]) - np.log(e["ci_lower"])) / (2 * z))
53
+
54
+
55
+ def _row(name, family, mix, strength, parameter=None):
56
+ s = kb.summarise(mix)
57
+ return {"method": name, "family": family, "parameter": parameter,
58
+ "ratio_median": float(np.exp(s["median"])), "ratio_lo": float(np.exp(s["lo"])), "ratio_hi": float(np.exp(s["hi"])),
59
+ "post_mean_log": float(s["mean"]), "post_sd_log": float(s["sd"]),
60
+ "P_lt_1": s["p_lt_1.00"], "P_lt_0.90": s["p_lt_0.90"], "P_lt_0.85": s["p_lt_0.85"], "P_lt_0.80": s["p_lt_0.80"],
61
+ "borrowing_strength": float(strength)}
62
+
63
+
64
+ def tipping_alpha(yR, sR, ext, threshold, tp, step):
65
+ grid = np.round(np.arange(0.0, 1.0 + step / 100, step), 2)
66
+ for a in grid:
67
+ m, *_ = kb.fixed_power_prior(yR, sR, ext, a, tau_prior=tp)
68
+ if m.cdf(0.0)[0] >= threshold:
69
+ return float(a)
70
+ return None
71
+
72
+
73
+ def _split(job):
74
+ yR, sR, yE, sE = [], [], [], []
75
+ for e in job["estimates"]:
76
+ y, s = log_effect(e)
77
+ (yR if e["role"] == "rct" else yE).append(y)
78
+ (sR if e["role"] == "rct" else sE).append(s)
79
+ return np.array(yR), np.array(sR), np.array(yE), np.array(sE)
80
+
81
+
82
+ def rct_only_summary(job):
83
+ yR, sR, _, _ = _split(job)
84
+ tp = (DEFAULT_SETTINGS["tau_prior"]["family"], DEFAULT_SETTINGS["tau_prior"]["scale"])
85
+ m0, *_ = kb.rct_only(yR, sR, tau_prior=tp)
86
+ out = _row("RCT-only (Bayesian RE)", "reference", m0, 0.0)
87
+ dl, fe = kb.dersimonian_laird(yR, sR), kb.fixed_effect(yR, sR)
88
+ req = float(kb.required_information(job["clinically_relevant_ratio"]))
89
+ out.update({"k": int(len(yR)), "dl_tau2": float(dl["tau2"]), "required_information": req,
90
+ "clinically_relevant_ratio": job["clinically_relevant_ratio"],
91
+ "fisher_information_dl": float(1 / dl["se"] ** 2), "fisher_information_fe": float(1 / fe["se"] ** 2)})
92
+ out["info_fraction_dl"] = out["fisher_information_dl"] / req
93
+ out["info_fraction_fe"] = out["fisher_information_fe"] / req
94
+ out["info_fraction"] = out["info_fraction_dl"]
95
+ return out, m0
96
+
97
+
98
+ def run_analysis(job, access_path="python-api", created_at=None):
99
+ rep = validate_job(job)
100
+ if rep["errors"]:
101
+ raise ContractError(rep["errors"])
102
+ job = copy.deepcopy(job)
103
+ job["input_hash"] = input_hash(job)
104
+ S = DEFAULT_SETTINGS
105
+ tp = (S["tau_prior"]["family"], S["tau_prior"]["scale"])
106
+ yR, sR, yE, sE = _split(job)
107
+ rct, m0 = rct_only_summary(job)
108
+ ext = {k: (float(v) if k != "k_E" else int(v)) for k, v in kb.external_summary(yE, sE, tau_prior=tp).items()}
109
+ comp = kb.compatibility(m0.moments()[0], m0.moments()[1], ext)
110
+ rows = []
111
+ for a in S["fixed_alpha_grid"]:
112
+ m, *_ = kb.fixed_power_prior(yR, sR, ext, a, tau_prior=tp)
113
+ rows.append(_row(f"Fixed-alpha power prior (alpha={a})", "fixed-alpha sensitivity", m, a, {"alpha": a}))
114
+ m, cw, al = kb.normalised_power_prior(yR, sR, ext, tau_prior=tp)
115
+ rows.append(_row("Normalised power prior (alpha~U(0,1))", "adaptive comparator", m, float(np.sum(cw * al))))
116
+ for w in S["robust_map_w_vague"]:
117
+ m, cw, *_ = kb.robust_map(yR, sR, ext, w_vague=w, tau_prior=tp)
118
+ rows.append(_row(f"Robust MAP (w_vague={w})", "robust MAP" if w == 0.5 else "robust-weight sensitivity", m, float(cw[0]), {"w_vague": w}))
119
+ tip = {str(t): tipping_alpha(yR, sR, ext, t, tp, S["tipping_alpha_step"]) for t in S["tipping_thresholds"]}
120
+ sc = job.get("stage_c") or {}
121
+ supported = sc.get("judgement") == "credible"
122
+ prov_complete = not any(f["code"] == "F_PROVENANCE_INCOMPLETE" for f in rep["flags"])
123
+ res = {
124
+ "schema": RESULT_SCHEMA, "schema_version": SCHEMA_VERSION,
125
+ "analysis_id": job["analysis_id"], "input_hash": job["input_hash"], "job": job,
126
+ "created_at": created_at or _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0).isoformat(),
127
+ "validation": rep, "provenance_complete": prov_complete,
128
+ "settings": S,
129
+ "results": {
130
+ "primary": "rct_only",
131
+ "rct_only": rct,
132
+ "external_summary": ext,
133
+ "conflict_diagnostics": {"z": float(comp["z"]), "p": float(comp["p"]), "note": texts.CONFLICT_NOTE},
134
+ "borrowing": {"status": "supported_by_recorded_design_judgement" if supported else "exploratory",
135
+ "label": texts.SUPPORTED_LABEL if supported else texts.EXPLORATORY_LABEL,
136
+ "stage_c_judgement": sc.get("judgement"),
137
+ "methods": rows, "tipping_alpha": tip},
138
+ },
139
+ "limitations": texts.LIMITATIONS,
140
+ "software": {"kotha_version": __version__, "schema_version": SCHEMA_VERSION,
141
+ "engine_file": "kotha/_engine/kotha_borrow.py", "engine_sha256": engine_sha256(),
142
+ "engine_matches_frozen_r1": engine_sha256() == FROZEN_ENGINE_SHA256,
143
+ "build": build_info(), "runtime": runtime_info(access_path)},
144
+ }
145
+ res = json.loads(json.dumps(res))
146
+ res["result_hash"] = result_hash(res)
147
+ return res