kotha 0.2.0rc1__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.
kotha/__init__.py ADDED
@@ -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))
kotha/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ import sys
2
+ from .cli import main
3
+ sys.exit(main())
kotha/_build_info.json ADDED
@@ -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
kotha/analysis.py ADDED
@@ -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
kotha/cli.py ADDED
@@ -0,0 +1,130 @@
1
+ """kotha validate | run | report | verify | hash | template-csv"""
2
+ import argparse
3
+ import json
4
+ import sys
5
+
6
+ from . import __version__, export_report, export_result, load_job
7
+ from .analysis import build_info
8
+ from .analysis import run_analysis
9
+ from .contract import ContractError, input_hash
10
+ from .csvio import write_estimates_csv
11
+ from .report import render_html
12
+ from .validate import validate_job
13
+ from .verify import summary_lines, verify_by_recomputation
14
+
15
+
16
+ def _print_items(items, stream):
17
+ for x in items:
18
+ print(f" {x['code']:<26} {x['path']}: {x['message']}", file=stream)
19
+
20
+
21
+ class _InputError(Exception):
22
+ pass
23
+
24
+
25
+ def _load(path, what):
26
+ try:
27
+ return load_job(path)
28
+ except FileNotFoundError:
29
+ raise _InputError(f"{what} file not found: {path}")
30
+ except IsADirectoryError:
31
+ raise _InputError(f"{what} path is a directory, not a file: {path}")
32
+ except PermissionError:
33
+ raise _InputError(f"cannot read {what} file (permission denied): {path}")
34
+ except UnicodeDecodeError:
35
+ raise _InputError(f"{what} file is not UTF-8 text: {path}")
36
+ except json.JSONDecodeError as e:
37
+ raise _InputError(f"{what} file is not valid JSON ({e.msg} at line {e.lineno}, column {e.colno}): {path}")
38
+
39
+
40
+ def _verify(result, job):
41
+ rec = verify_by_recomputation(result, job)
42
+ for line in summary_lines(rec):
43
+ print(line)
44
+ for e in rec["integrity"]["errors"] + rec["original_job"].get("errors", []):
45
+ print(f" {e['code']:<26} {e['path']}: {e['message']}")
46
+ for m in rec["recomputation"]["mismatches"]:
47
+ print(f" {'E_RECOMPUTE':<26} {m['path']}: {m['issue']}" + (f" (file {m.get('file')!r}, recomputed {m.get('recomputed')!r})" if "file" in m else ""))
48
+ return rec
49
+
50
+
51
+ def _safe_console():
52
+ # A console that cannot encode a character (e.g. cp1252 under PowerShell 5.1) must not turn a
53
+ # successful run into an error; files are always written as UTF-8 under their real names.
54
+ for s in (sys.stdout, sys.stderr):
55
+ if hasattr(s, "reconfigure") and (s.errors or "strict") == "strict":
56
+ try:
57
+ s.reconfigure(errors="backslashreplace")
58
+ except (ValueError, OSError):
59
+ pass
60
+
61
+
62
+ def main(argv=None):
63
+ _safe_console()
64
+ argv = sys.argv[1:] if argv is None else list(argv)
65
+ verbose = "--verbose" in argv
66
+ argv = [a for a in argv if a != "--verbose"]
67
+ try:
68
+ return _main(argv)
69
+ except _InputError as e:
70
+ print(f"kotha: error: {e}", file=sys.stderr)
71
+ return 2
72
+ except Exception as e:
73
+ if verbose:
74
+ raise
75
+ print(f"kotha: internal error: {type(e).__name__}: {e} (re-run with --verbose for details)", file=sys.stderr)
76
+ return 1
77
+
78
+
79
+ def _main(argv):
80
+ p = argparse.ArgumentParser(prog="kotha", description="KOTHA aggregate-data conditional borrowing (research use only)")
81
+ p.add_argument("--version", action="version", version=f"kotha {__version__} (source commit {build_info().get('source_commit')})")
82
+ sub = p.add_subparsers(dest="cmd", required=True)
83
+ s = sub.add_parser("validate"); s.add_argument("job")
84
+ s = sub.add_parser("run"); s.add_argument("job"); s.add_argument("--output", "-o", required=True); s.add_argument("--report")
85
+ s = sub.add_parser("report"); s.add_argument("result"); s.add_argument("--output", "-o", required=True)
86
+ s = sub.add_parser("verify"); s.add_argument("result"); s.add_argument("--job")
87
+ s = sub.add_parser("hash"); s.add_argument("job")
88
+ s = sub.add_parser("template-csv"); s.add_argument("--output", "-o", required=True)
89
+ p.add_argument("--verbose", action="store_true", help="show Python tracebacks on internal errors")
90
+ a = p.parse_args(argv)
91
+ if a.cmd == "validate":
92
+ rep = validate_job(_load(a.job, "job"))
93
+ for k in ("errors", "warnings", "flags"):
94
+ print(f"{k}: {len(rep[k])}"); _print_items(rep[k], sys.stdout)
95
+ return 2 if rep["errors"] else 0
96
+ if a.cmd == "run":
97
+ try:
98
+ res = run_analysis(_load(a.job, "job"), access_path="python-cli")
99
+ except ContractError as e:
100
+ print("job invalid:", file=sys.stderr); _print_items(e.errors, sys.stderr)
101
+ return 2
102
+ export_result(res, a.output)
103
+ if a.report:
104
+ export_report(res, a.report)
105
+ rc = res["results"]["rct_only"]
106
+ print(f"analysis {res['analysis_id']} {res['input_hash']}\nRCT-only median ratio {rc['ratio_median']:.3f} "
107
+ f"({rc['ratio_lo']:.3f}-{rc['ratio_hi']:.3f}); borrowing status: {res['results']['borrowing']['status']}\nwrote {a.output}")
108
+ return 0
109
+ if a.cmd == "report":
110
+ res = _load(a.result, "result")
111
+ rec = _verify(res, None)
112
+ if not rec["verified"]:
113
+ print("report not written: verification failed", file=sys.stderr); return 3
114
+ with open(a.output, "w", encoding="utf-8") as fh:
115
+ fh.write(render_html(res, verified=rec))
116
+ return 0
117
+ if a.cmd == "verify":
118
+ rec = _verify(_load(a.result, "result"), _load(a.job, "job") if a.job else None)
119
+ print("VERIFIED (a, b" + (", c" if rec["original_job"]["status"] == "match" else "") + ")" if rec["verified"] else "NOT VERIFIED")
120
+ return 0 if rec["verified"] else 3
121
+ if a.cmd == "hash":
122
+ print(input_hash(_load(a.job, "job"))); return 0
123
+ if a.cmd == "template-csv":
124
+ with open(a.output, "w", encoding="utf-8", newline="") as fh:
125
+ fh.write(write_estimates_csv([]))
126
+ return 0
127
+
128
+
129
+ if __name__ == "__main__":
130
+ sys.exit(main())
kotha/contract.py ADDED
@@ -0,0 +1,113 @@
1
+ """Versioned job/result contract: canonical serialisation, hashes and integrity checks.
2
+
3
+ A matching hash shows that two documents carry the same values. It does not show that the
4
+ causal assumptions hold or that the numbers are correct.
5
+ """
6
+ import copy
7
+ import hashlib
8
+ import json
9
+ import math
10
+
11
+ SCHEMA_VERSION = "1.0"
12
+ JOB_SCHEMA = "kotha-job"
13
+ RESULT_SCHEMA = "kotha-result"
14
+ JOB_HASH_EXCLUDE = ("input_hash", "client")
15
+ NULL_MEANS_ABSENT = ("stage_c",) # "stage_c": null and an omitted stage_c both mean "no judgement recorded"
16
+ RESULT_HASH_EXCLUDE = ("result_hash",)
17
+
18
+
19
+ class ContractError(ValueError):
20
+ def __init__(self, errors):
21
+ self.errors = errors
22
+ super().__init__("; ".join(f"{e['code']}: {e['message']}" for e in errors))
23
+
24
+
25
+ def _norm(x):
26
+ if isinstance(x, bool) or x is None or isinstance(x, str):
27
+ return x
28
+ if isinstance(x, int):
29
+ return x
30
+ if isinstance(x, float):
31
+ if not math.isfinite(x):
32
+ raise ValueError("non-finite number cannot be serialised")
33
+ return int(x) if x.is_integer() and abs(x) < 2 ** 53 else x
34
+ if isinstance(x, dict):
35
+ return {str(k): _norm(v) for k, v in x.items()}
36
+ if isinstance(x, (list, tuple)):
37
+ return [_norm(v) for v in x]
38
+ if hasattr(x, "item"):
39
+ return _norm(x.item())
40
+ raise TypeError(f"unsupported type {type(x).__name__}")
41
+
42
+
43
+ def canonical_json(obj):
44
+ """Sorted keys, no whitespace, UTF-8, integral floats written as integers."""
45
+ return json.dumps(_norm(obj), sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
46
+
47
+
48
+ def _sha(obj):
49
+ return "sha256:" + hashlib.sha256(canonical_json(obj).encode("utf-8")).hexdigest()
50
+
51
+
52
+ def input_hash(job):
53
+ return _sha({k: v for k, v in job.items() if k not in JOB_HASH_EXCLUDE and not (k in NULL_MEANS_ABSENT and v is None)})
54
+
55
+
56
+ def _legacy_input_hash(job):
57
+ # S2 builds hashed an explicit "stage_c": null; such sealed files remain valid.
58
+ return _sha({k: v for k, v in job.items() if k not in JOB_HASH_EXCLUDE})
59
+
60
+
61
+ def input_hash_ok(job, h):
62
+ return h == input_hash(job) or (any(job.get(k, 0) is None for k in NULL_MEANS_ABSENT) and h == _legacy_input_hash(job))
63
+
64
+
65
+ def result_hash(result):
66
+ return _sha({k: v for k, v in result.items() if k not in RESULT_HASH_EXCLUDE})
67
+
68
+
69
+ def seal_job(job):
70
+ job = copy.deepcopy(job)
71
+ job["input_hash"] = input_hash(job)
72
+ return job
73
+
74
+
75
+ def verify_job_hash(job):
76
+ if "input_hash" in job and not input_hash_ok(job, job["input_hash"]):
77
+ return [{"code": "E_INPUT_HASH", "path": "input_hash",
78
+ "message": "input_hash does not match the job content (job was modified after sealing)"}]
79
+ return []
80
+
81
+
82
+ def verify_result(result, job=None):
83
+ """Integrity checks for an imported result. Returns a list of error dicts (empty = pass)."""
84
+ errs = []
85
+ if not isinstance(result, dict):
86
+ return [{"code": "E_RESULT_TYPE", "path": "", "message": "result must be a JSON object"}]
87
+ if result.get("schema") != RESULT_SCHEMA:
88
+ errs.append({"code": "E_SCHEMA", "path": "schema", "message": f"expected '{RESULT_SCHEMA}'"})
89
+ if result.get("schema_version") != SCHEMA_VERSION:
90
+ errs.append({"code": "E_VERSION", "path": "schema_version",
91
+ "message": f"unsupported schema_version {result.get('schema_version')!r}; this build reads {SCHEMA_VERSION}"})
92
+ if errs:
93
+ return errs
94
+ try:
95
+ if result.get("result_hash") != result_hash(result):
96
+ errs.append({"code": "E_RESULT_HASH", "path": "result_hash",
97
+ "message": "result_hash does not match the result content (file altered or corrupted)"})
98
+ emb = result.get("job") or {}
99
+ if not input_hash_ok(emb, result.get("input_hash")):
100
+ errs.append({"code": "E_INPUT_HASH", "path": "input_hash",
101
+ "message": "input_hash does not match the embedded job"})
102
+ except (TypeError, ValueError) as e:
103
+ return [{"code": "E_RESULT_CONTENT", "path": "", "message": str(e)}]
104
+ if result.get("analysis_id") != emb.get("analysis_id"):
105
+ errs.append({"code": "E_ANALYSIS_ID", "path": "analysis_id", "message": "analysis_id differs from embedded job"})
106
+ if job is not None:
107
+ if job.get("analysis_id") != result.get("analysis_id"):
108
+ errs.append({"code": "E_ANALYSIS_ID", "path": "analysis_id",
109
+ "message": "result analysis_id does not match the job in this session"})
110
+ if not (input_hash_ok(job, result.get("input_hash")) or input_hash(job) == input_hash(emb)):
111
+ errs.append({"code": "E_INPUT_HASH", "path": "input_hash",
112
+ "message": "result was computed from different inputs than the job in this session"})
113
+ return errs