cs-temporal 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ """cs-temporal: Zero-dependency bitemporal evidence geometry & retraction-aware meta-analysis."""
2
+
3
+ from .engine import (
4
+ DEMO_SERIES,
5
+ Q_CP_ANDREWS_05,
6
+ Q_CP_CHI2_05,
7
+ ReplayResult,
8
+ Study,
9
+ TemporalSnapshot,
10
+ build_replay,
11
+ evaluate_as_of,
12
+ load_csv,
13
+ tie_preserving_permutation_test,
14
+ )
15
+ from .multimodal import (
16
+ analyze_continuous_series,
17
+ analyze_ivw_shape,
18
+ synchronized_panel_permutation,
19
+ )
20
+ from .rdf import RULE_H0F_SPARQL, export_turtle
21
+
22
+ __version__ = "0.2.0"
23
+ __all__ = [
24
+ "__version__",
25
+ "Study",
26
+ "TemporalSnapshot",
27
+ "ReplayResult",
28
+ "DEMO_SERIES",
29
+ "Q_CP_CHI2_05",
30
+ "Q_CP_ANDREWS_05",
31
+ "evaluate_as_of",
32
+ "build_replay",
33
+ "tie_preserving_permutation_test",
34
+ "load_csv",
35
+ "export_turtle",
36
+ "RULE_H0F_SPARQL",
37
+ "analyze_ivw_shape",
38
+ "analyze_continuous_series",
39
+ "synchronized_panel_permutation",
40
+ ]
cs_temporal/cli.py ADDED
@@ -0,0 +1,90 @@
1
+ """Command-line interface for cs-temporal."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .engine import DEMO_SERIES, build_replay, load_csv, tie_preserving_permutation_test
10
+ from .rdf import export_turtle
11
+
12
+
13
+ def _print_summary(result_dict: dict, perm: dict | None = None) -> None:
14
+ cur = result_dict["current"]
15
+ print(f"As of: {result_dict['as_of']} | Status: {cur['status']}")
16
+ print(f"Studies included: {cur['k_admissible']} | Retracted excluded: {cur['k_purged']} | Left out: {cur['k_left_out']} | Later: {len(result_dict['later'])}")
17
+ if cur["mu_re"] is not None:
18
+ print(f"Pooled random-effects estimate: {cur['mu_re']:+.4f} (95% CI {cur['ci95_lo']:+.4f} to {cur['ci95_hi']:+.4f})")
19
+ print(f"Fixed-effect estimate: {cur['mu_fe']:+.4f} | I2: {cur['i2_pct']:.1f}% | Q_tot: {cur['q_tot']:.2f}")
20
+ print(f"Max-Q_cp: {cur['q_cp']:.2f} | R2_time: {cur['r2_time_pct']:.1f}% | Turning point: {cur['t_star'] or 'none'}")
21
+ if perm:
22
+ print(f"Tie-preserving permutation (B={perm['n_perm']}): excess R2_time = {perm['excess_r2_time_pct']:+.2f}%, p = {perm['p_value']:.4f}")
23
+
24
+
25
+ def main(argv: list[str] | None = None) -> int:
26
+ parser = argparse.ArgumentParser(prog="cs-temporal", description="Zero-dependency bitemporal meta-analysis geometry CLI.")
27
+ sub = parser.add_subparsers(dest="cmd", required=True)
28
+
29
+ p_an = sub.add_parser("analyze", help="Analyze a CSV study series as of a date")
30
+ p_an.add_argument("csv_path", help="CSV file with columns: id,day,y,se[,label,retracted_day]")
31
+ p_an.add_argument("--as-of", dest="as_of", default=None, help="ISO date YYYY-MM-DD")
32
+ p_an.add_argument("--without", action="append", default=[], help="Study ID to leave out (repeatable)")
33
+ p_an.add_argument("--perm", type=int, default=0, help="Run tie-preserving permutation test with B permutations")
34
+ p_an.add_argument("--json", action="store_true", dest="as_json", help="Emit JSON output")
35
+
36
+ p_demo = sub.add_parser("demo", help="Run a built-in published clinical example (hcq or icu)")
37
+ p_demo.add_argument("name", choices=sorted(DEMO_SERIES.keys()))
38
+ p_demo.add_argument("--as-of", dest="as_of", default=None)
39
+ p_demo.add_argument("--without", action="append", default=[])
40
+ p_demo.add_argument("--perm", type=int, default=500)
41
+ p_demo.add_argument("--json", action="store_true", dest="as_json")
42
+
43
+ p_rdf = sub.add_parser("export-rdf", help="Export a CSV series to W3C Turtle RDF for SPARQL 1.1 Rule_H0f")
44
+ p_rdf.add_argument("csv_path")
45
+ p_rdf.add_argument("--topic", default="series")
46
+ p_rdf.add_argument("--as-of", dest="as_of", default=None)
47
+ p_rdf.add_argument("--out", default=None, help="Output .ttl path (default stdout)")
48
+
49
+ args = parser.parse_args(argv)
50
+
51
+ if args.cmd == "analyze":
52
+ studies = load_csv(args.csv_path)
53
+ rep = build_replay(studies, as_of=args.as_of, without=args.without)
54
+ perm = tie_preserving_permutation_test(studies, as_of=rep.as_of, without=args.without, n_perm=args.perm) if args.perm > 0 else None
55
+ payload = rep.to_dict()
56
+ if perm:
57
+ payload["permutation"] = perm
58
+ if args.as_json:
59
+ print(json.dumps(payload, indent=2))
60
+ else:
61
+ _print_summary(payload, perm)
62
+ return 0
63
+
64
+ if args.cmd == "demo":
65
+ studies = DEMO_SERIES[args.name]
66
+ rep = build_replay(studies, as_of=args.as_of, without=args.without)
67
+ perm = tie_preserving_permutation_test(studies, as_of=rep.as_of, without=args.without, n_perm=args.perm) if args.perm > 0 else None
68
+ payload = rep.to_dict()
69
+ if perm:
70
+ payload["permutation"] = perm
71
+ if args.as_json:
72
+ print(json.dumps(payload, indent=2))
73
+ else:
74
+ _print_summary(payload, perm)
75
+ return 0
76
+
77
+ if args.cmd == "export-rdf":
78
+ studies = load_csv(args.csv_path)
79
+ ttl = export_turtle(studies, topic_slug=args.topic, topic_label=args.topic, as_of=args.as_of)
80
+ if args.out:
81
+ Path(args.out).write_text(ttl, encoding="utf-8")
82
+ else:
83
+ sys.stdout.write(ttl)
84
+ return 0
85
+
86
+ return 1
87
+
88
+
89
+ if __name__ == "__main__":
90
+ raise SystemExit(main())
cs_temporal/engine.py ADDED
@@ -0,0 +1,327 @@
1
+ """Core zero-dependency bitemporal evidence geometry engine (Rule_H0f v5)."""
2
+ from __future__ import annotations
3
+
4
+ import csv
5
+ import math
6
+ import random
7
+ from dataclasses import asdict, dataclass
8
+ from pathlib import Path
9
+ from typing import Iterable, Sequence
10
+
11
+ Q_CP_CHI2_05 = 3.8416
12
+ Q_CP_ANDREWS_05 = 8.85
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Study:
17
+ """Single dated clinical trial or study effect estimate on a common additive scale."""
18
+
19
+ id: str
20
+ day: str # ISO YYYY-MM-DD (knowledge / public release date)
21
+ y: float # Standardized effect size (e.g., Cohen's h, Hedges' g, -ln HR); >0 favors treatment
22
+ se: float # Standard error (> 0)
23
+ label: str = ""
24
+ retracted_day: str | None = None
25
+ retraction_id: str | None = None
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class TemporalSnapshot:
30
+ """Exact closed-form evidence geometry strictly within the causal cone (day <= as_of)."""
31
+
32
+ day: str
33
+ known: bool
34
+ is_purge_event: bool
35
+ k_admissible: int
36
+ k_purged: int
37
+ k_left_out: int
38
+ mu_fe: float | None
39
+ mu_re: float | None
40
+ se_re: float | None
41
+ ci95_lo: float | None
42
+ ci95_hi: float | None
43
+ j_fe: float
44
+ q_tot: float
45
+ tau2: float
46
+ i2_pct: float
47
+ q_cp: float
48
+ r2_time_pct: float
49
+ t_star: str | None
50
+ mu_pre: float | None
51
+ mu_post: float | None
52
+ status: str # regime_shift | retraction_purged | stable | early
53
+
54
+ def to_dict(self) -> dict:
55
+ return asdict(self)
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class ReplayResult:
60
+ """Complete chronological replay of a study series as of a chosen calendar date."""
61
+
62
+ as_of: str
63
+ without: tuple[str, ...]
64
+ current: TemporalSnapshot
65
+ admissible: tuple[Study, ...]
66
+ purged: tuple[Study, ...]
67
+ left_out: tuple[Study, ...]
68
+ later: tuple[Study, ...]
69
+ event_days: tuple[str, ...]
70
+ trajectory: tuple[TemporalSnapshot, ...]
71
+
72
+ def to_dict(self) -> dict:
73
+ return {
74
+ "as_of": self.as_of,
75
+ "without": list(self.without),
76
+ "current": self.current.to_dict(),
77
+ "admissible": [asdict(s) for s in self.admissible],
78
+ "purged": [asdict(s) for s in self.purged],
79
+ "left_out": [asdict(s) for s in self.left_out],
80
+ "later": [asdict(s) for s in self.later],
81
+ "event_days": list(self.event_days),
82
+ "trajectory": [snap.to_dict() for snap in self.trajectory],
83
+ }
84
+
85
+
86
+ def evaluate_as_of(
87
+ studies: Sequence[Study],
88
+ as_of: str,
89
+ without: Iterable[str] = (),
90
+ *,
91
+ is_purge_event: bool = False,
92
+ ) -> tuple[TemporalSnapshot, list[Study], list[Study], list[Study], list[Study]]:
93
+ """Evaluate exact closed-form Rule_H0f v5 strictly inside the causal cone (day <= as_of)."""
94
+ without_set = set(without)
95
+ admissible: list[Study] = []
96
+ purged: list[Study] = []
97
+ left_out: list[Study] = []
98
+ later: list[Study] = []
99
+
100
+ for s in sorted(studies, key=lambda x: (x.day, x.id)):
101
+ if s.se <= 0 or math.isnan(s.y) or math.isnan(s.se):
102
+ continue
103
+ if s.day > as_of:
104
+ later.append(s)
105
+ continue
106
+ if s.retracted_day and s.retracted_day <= as_of:
107
+ purged.append(s)
108
+ continue
109
+ if s.id in without_set:
110
+ left_out.append(s)
111
+ continue
112
+ admissible.append(s)
113
+
114
+ k = len(admissible)
115
+ if k == 0:
116
+ snap = TemporalSnapshot(
117
+ day=as_of, known=True, is_purge_event=is_purge_event,
118
+ k_admissible=0, k_purged=len(purged), k_left_out=len(left_out),
119
+ mu_fe=None, mu_re=None, se_re=None, ci95_lo=None, ci95_hi=None,
120
+ j_fe=0.0, q_tot=0.0, tau2=0.0, i2_pct=0.0, q_cp=0.0, r2_time_pct=0.0,
121
+ t_star=None, mu_pre=None, mu_post=None, status="early",
122
+ )
123
+ return snap, admissible, purged, left_out, later
124
+
125
+ ws = [1.0 / (s.se * s.se) for s in admissible]
126
+ ys = [s.y for s in admissible]
127
+ days = [s.day for s in admissible]
128
+
129
+ j_fe = sum(ws)
130
+ mu_fe = sum(w * y for w, y in zip(ws, ys)) / j_fe
131
+ q_tot = max(0.0, sum(w * (y - mu_fe) ** 2 for w, y in zip(ws, ys)))
132
+ c_dl = j_fe - (sum(w * w for w in ws) / j_fe)
133
+ tau2 = ((q_tot - (k - 1)) / c_dl) if (k >= 2 and c_dl > 0.0 and q_tot > (k - 1)) else 0.0
134
+ i2_pct = max(0.0, ((q_tot - (k - 1)) / q_tot) * 100.0) if (k >= 2 and q_tot > 0.0) else 0.0
135
+
136
+ w_re = [1.0 / (s.se * s.se + tau2) for s in admissible]
137
+ j_re = sum(w_re)
138
+ mu_re = sum(w * y for w, y in zip(w_re, ys)) / j_re
139
+ se_re = math.sqrt(1.0 / j_re)
140
+ ci_lo = mu_re - 1.959964 * se_re
141
+ ci_hi = mu_re + 1.959964 * se_re
142
+
143
+ # Exact all-cutoff Max-Q_cp with deterministic earliest-t* tie-break (1e-9 tolerance)
144
+ best_q_cp = 0.0
145
+ best_t_star: str | None = None
146
+ best_mu_pre: float | None = None
147
+ best_mu_post: float | None = None
148
+ unique_days = sorted(set(days))
149
+ for cut in unique_days[:-1]:
150
+ w1 = sum(w for w, d in zip(ws, days) if d <= cut)
151
+ wy1 = sum(w * y for w, y, d in zip(ws, ys, days) if d <= cut)
152
+ w2 = sum(w for w, d in zip(ws, days) if d > cut)
153
+ wy2 = sum(w * y for w, y, d in zip(ws, ys, days) if d > cut)
154
+ if w1 <= 0.0 or w2 <= 0.0:
155
+ continue
156
+ m1 = wy1 / w1
157
+ m2 = wy2 / w2
158
+ q_cand = ((m2 - m1) ** 2) / ((1.0 / w1) + (1.0 / w2))
159
+ if q_cand > best_q_cp + 1e-9:
160
+ best_q_cp = q_cand
161
+ best_t_star = cut
162
+ best_mu_pre = m1
163
+ best_mu_post = m2
164
+
165
+ r2_time_pct = min(100.0, (best_q_cp / q_tot) * 100.0) if q_tot > 1e-12 else 0.0
166
+ if k < 2:
167
+ status = "early"
168
+ elif best_q_cp >= Q_CP_CHI2_05:
169
+ status = "regime_shift"
170
+ elif len(purged) > 0:
171
+ status = "retraction_purged"
172
+ else:
173
+ status = "stable"
174
+
175
+ snap = TemporalSnapshot(
176
+ day=as_of, known=True, is_purge_event=is_purge_event,
177
+ k_admissible=k, k_purged=len(purged), k_left_out=len(left_out),
178
+ mu_fe=mu_fe, mu_re=mu_re, se_re=se_re, ci95_lo=ci_lo, ci95_hi=ci_hi,
179
+ j_fe=j_fe, q_tot=q_tot, tau2=tau2, i2_pct=i2_pct,
180
+ q_cp=best_q_cp, r2_time_pct=r2_time_pct, t_star=best_t_star,
181
+ mu_pre=best_mu_pre, mu_post=best_mu_post, status=status,
182
+ )
183
+ return snap, admissible, purged, left_out, later
184
+
185
+
186
+ def build_replay(studies: Sequence[Study], as_of: str | None = None, without: Iterable[str] = ()) -> ReplayResult:
187
+ """Build complete chronological trajectory + snapshot as of `as_of` (defaults to latest event)."""
188
+ event_day_set: set[str] = set()
189
+ purge_days: set[str] = set()
190
+ for s in studies:
191
+ event_day_set.add(s.day)
192
+ if s.retracted_day:
193
+ event_day_set.add(s.retracted_day)
194
+ purge_days.add(s.retracted_day)
195
+ event_days = sorted(event_day_set)
196
+ effective_as_of = as_of or (event_days[-1] if event_days else "2026-01-01")
197
+ without_tup = tuple(sorted(set(without)))
198
+
199
+ current, admissible, purged, left_out, later = evaluate_as_of(
200
+ studies, effective_as_of, without_tup, is_purge_event=(effective_as_of in purge_days)
201
+ )
202
+ traj: list[TemporalSnapshot] = []
203
+ for d in event_days:
204
+ snap, *_ = evaluate_as_of(studies, d, without_tup, is_purge_event=(d in purge_days))
205
+ traj.append(TemporalSnapshot(**{**snap.to_dict(), "known": d <= effective_as_of}))
206
+
207
+ return ReplayResult(
208
+ as_of=effective_as_of,
209
+ without=without_tup,
210
+ current=current,
211
+ admissible=tuple(admissible),
212
+ purged=tuple(purged),
213
+ left_out=tuple(left_out),
214
+ later=tuple(later),
215
+ event_days=tuple(event_days),
216
+ trajectory=tuple(traj),
217
+ )
218
+
219
+
220
+ def tie_preserving_permutation_test(
221
+ studies: Sequence[Study],
222
+ as_of: str | None = None,
223
+ without: Iterable[str] = (),
224
+ *,
225
+ n_perm: int = 1000,
226
+ seed: int = 42,
227
+ ) -> dict:
228
+ """Exact unrounded tie-preserving chronological permutation test holding (y_i, se_i) fixed."""
229
+ effective_as_of = as_of or max((s.day for s in studies), default="2026-01-01")
230
+ snap, admissible, *_ = evaluate_as_of(studies, effective_as_of, without)
231
+ k = len(admissible)
232
+ days = [s.day for s in admissible]
233
+ split_ends = [i for i in range(k - 1) if days[i] != days[i + 1]]
234
+ if k < 4 or not split_ends or snap.q_tot <= 1e-12:
235
+ return {
236
+ "k": k, "n_perm": n_perm, "obs_q_cp": snap.q_cp, "obs_r2_time_pct": snap.r2_time_pct,
237
+ "null_mean_r2_time_pct": None, "excess_r2_time_pct": 0.0, "p_value": 1.0,
238
+ }
239
+
240
+ pairs = [(s.y, 1.0 / (s.se * s.se)) for s in admissible]
241
+ tot_w = sum(w for _, w in pairs)
242
+ tot_wy = sum(y * w for y, w in pairs)
243
+ rng = random.Random(seed)
244
+ ge_cnt = 0
245
+ null_r2_sum = 0.0
246
+
247
+ for _ in range(n_perm):
248
+ perm = pairs[:]
249
+ rng.shuffle(perm)
250
+ cw = 0.0
251
+ cwy = 0.0
252
+ q_max = 0.0
253
+ split_ptr = 0
254
+ next_split = split_ends[0]
255
+ for idx, (y_i, w_i) in enumerate(perm):
256
+ cw += w_i
257
+ cwy += y_i * w_i
258
+ if idx == next_split:
259
+ w2 = tot_w - cw
260
+ if cw > 0.0 and w2 > 0.0:
261
+ m1 = cwy / cw
262
+ m2 = (tot_wy - cwy) / w2
263
+ qc = ((m2 - m1) ** 2) / ((1.0 / cw) + (1.0 / w2))
264
+ if qc > q_max:
265
+ q_max = qc
266
+ split_ptr += 1
267
+ if split_ptr < len(split_ends):
268
+ next_split = split_ends[split_ptr]
269
+ else:
270
+ break
271
+ if q_max >= snap.q_cp - 1e-12:
272
+ ge_cnt += 1
273
+ null_r2_sum += min(100.0, (q_max / snap.q_tot) * 100.0)
274
+
275
+ null_mean_r2 = null_r2_sum / n_perm
276
+ return {
277
+ "k": k,
278
+ "n_perm": n_perm,
279
+ "obs_q_cp": round(snap.q_cp, 4),
280
+ "obs_r2_time_pct": round(snap.r2_time_pct, 2),
281
+ "null_mean_r2_time_pct": round(null_mean_r2, 2),
282
+ "excess_r2_time_pct": round(snap.r2_time_pct - null_mean_r2, 2),
283
+ "p_value": round((ge_cnt + 1.0) / (n_perm + 1.0), 4),
284
+ }
285
+
286
+
287
+ def load_csv(path: str | Path) -> list[Study]:
288
+ """Load studies from a CSV with columns: id, day, y, se [, label, retracted_day, retraction_id]."""
289
+ out: list[Study] = []
290
+ with Path(path).open("r", encoding="utf-8-sig", newline="") as f:
291
+ reader = csv.DictReader(f)
292
+ for row in reader:
293
+ sid = (row.get("id") or "").strip()
294
+ day = (row.get("day") or "").strip()
295
+ if not sid or not day:
296
+ continue
297
+ out.append(
298
+ Study(
299
+ id=sid,
300
+ day=day,
301
+ y=float(row["y"]),
302
+ se=float(row["se"]),
303
+ label=(row.get("label") or sid).strip(),
304
+ retracted_day=(row.get("retracted_day") or "").strip() or None,
305
+ retraction_id=(row.get("retraction_id") or "").strip() or None,
306
+ )
307
+ )
308
+ return out
309
+
310
+
311
+ # Built-in classic published clinical teaching series (exact 5-decimal values matching ontology 0.3.25)
312
+ DEMO_SERIES: dict[str, list[Study]] = {
313
+ "hcq": [
314
+ Study("32205204", "2020-03-25", 1.25958, 0.33541, "Gautret et al. (IJAA, 2020)", retracted_day="2024-12-27", retraction_id="Retraction-2024-12-27"),
315
+ Study("32391667", "2020-05-12", -0.22527, 0.36515, "Chen et al. (J Zhejiang Univ, 2020)"),
316
+ Study("32409561", "2020-05-16", 0.10996, 0.16330, "Tang et al. (BMJ, 2020)"),
317
+ Study("33031652", "2020-10-08", -0.04401, 0.03094, "Horby et al. / RECOVERY (NEJM, 2020)"),
318
+ Study("33165621", "2020-11-09", 0.00717, 0.09158, "Self et al. / ORCHID (JAMA, 2020)"),
319
+ ],
320
+ "icu": [
321
+ Study("11794168", "2002-01-17", 0.14408, 0.05084, "Van den Berghe et al. (NEJM, 2001)"),
322
+ Study("16452557", "2006-02-03", 0.05523, 0.05774, "Van den Berghe et al. (NEJM, 2006)"),
323
+ Study("19318384", "2009-03-26", -0.05930, 0.02577, "Finfer et al. / NICE-SUGAR (NEJM, 2009)"),
324
+ Study("20103758", "2010-01-28", -0.05976, 0.08865, "Annane et al. / COIITSS (JAMA, 2010)"),
325
+ Study("37754283", "2023-09-27", -0.01172, 0.02082, "Gunst et al. / TGC-Fast (NEJM, 2023)"),
326
+ ],
327
+ }
@@ -0,0 +1,402 @@
1
+ """Multi-modal temporal geometry extensions for cs-temporal (v0.2.0, zero external deps).
2
+
3
+ Post-Red-Team hardened primitives validated across 6+ biomedical corpora:
4
+ 1. Complexity-adjusted BIC Step vs. Linear Slope routing (IVW with optional overdispersion scaling
5
+ and SE-free continuous with automatic chronological sorting & length validation).
6
+ 2. Within-era random-effects deflated changepoint contrast (q_cp_re with RE era means).
7
+ 3. Comparator-switch confounding guard for clinical trial series (ignores unknown comparators).
8
+ 4. Automated boilerplate copy-paste control-table detector for preclinical assays.
9
+ 5. Tie-preserving synchronized column-time panel permutation (for stationary / first-differenced
10
+ cross-sectional panels; guards s_tt == 0, n_perm <= 0, and ragged rows).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import datetime as dt
15
+ import math
16
+ import random
17
+ from typing import Any, Sequence
18
+
19
+ from .engine import Study
20
+
21
+ EPS = 1e-12
22
+
23
+
24
+ def _iso_to_year(day: str) -> float:
25
+ s = day.strip()
26
+ if len(s) == 7 and s[4] == "-":
27
+ s = s + "-15"
28
+ elif len(s) == 4 and s.isdigit():
29
+ s = s + "-07-01"
30
+ d = dt.date.fromisoformat(s[:10])
31
+ return d.year + (d.timetuple().tm_yday - 1) / 365.25
32
+
33
+
34
+ def _average_ranks(vals: Sequence[float]) -> list[float]:
35
+ n = len(vals)
36
+ order = sorted(range(n), key=lambda i: vals[i])
37
+ ranks = [0.0] * n
38
+ i = 0
39
+ while i < n:
40
+ j = i
41
+ while j + 1 < n and vals[order[j + 1]] == vals[order[i]]:
42
+ j += 1
43
+ avg_r = 0.5 * (i + j) + 1.0
44
+ for idx in range(i, j + 1):
45
+ ranks[order[idx]] = avg_r
46
+ i = j + 1
47
+ return ranks
48
+
49
+
50
+ def analyze_ivw_shape(
51
+ studies: Sequence[Study],
52
+ as_of: str | None = None,
53
+ comparator_by_id: dict[str, str] | None = None,
54
+ ) -> dict[str, Any]:
55
+ """Compute IVW step (Q_cp), linear slope (Q_slope), within-era RE contrast (Q_cp_re),
56
+ overdispersion-aware BIC shape (step_dominant | slope_dominant | mixed_step_slope | flat),
57
+ and optional comparator-switch guard strictly inside the causal cone (day <= as_of).
58
+ """
59
+ eff_as_of = as_of or max((s.day for s in studies), default="2099-12-31")
60
+ adm = [
61
+ s for s in sorted(studies, key=lambda x: (x.day, x.id))
62
+ if math.isfinite(s.y) and math.isfinite(s.se) and s.se > 0.0
63
+ and s.day <= eff_as_of
64
+ and not (s.retracted_day and s.retracted_day <= eff_as_of)
65
+ ]
66
+ k = len(adm)
67
+ if k < 2:
68
+ return {
69
+ "k": k, "q_tot": 0.0, "q_cp": 0.0, "q_cp_re": 0.0, "q_slope": 0.0,
70
+ "r2_time_pct": 0.0, "r2_slope_pct": 0.0, "t_star": None,
71
+ "mu_pre": None, "mu_post": None, "mu_pre_re": None, "mu_post_re": None,
72
+ "bic_step_minus_slope": 0.0, "shape_bic": "insufficient",
73
+ "comparator_switched": False,
74
+ }
75
+
76
+ ys = [s.y for s in adm]
77
+ v_i = [max(EPS, s.se * s.se) for s in adm]
78
+ ws = [1.0 / v for v in v_i]
79
+ days = [s.day for s in adm]
80
+ yrs = [_iso_to_year(d) for d in days]
81
+
82
+ j_fe = sum(ws)
83
+ mu_fe = sum(w * y for w, y in zip(ws, ys)) / j_fe
84
+ q_tot = max(0.0, sum(w * (y - mu_fe) ** 2 for w, y in zip(ws, ys)))
85
+
86
+ q_cp = 0.0
87
+ t_star: str | None = None
88
+ mu_pre = mu_fe
89
+ mu_post = mu_fe
90
+ best_idx = -1
91
+ tot_wy = sum(w * y for w, y in zip(ws, ys))
92
+ cw = cwy = 0.0
93
+ for i in range(k - 1):
94
+ cw += ws[i]
95
+ cwy += ws[i] * ys[i]
96
+ if days[i] == days[i + 1]:
97
+ continue
98
+ w2 = j_fe - cw
99
+ if cw > EPS and w2 > EPS:
100
+ m1 = cwy / cw
101
+ m2 = (tot_wy - cwy) / w2
102
+ qc = ((m2 - m1) ** 2) / (1.0 / cw + 1.0 / w2)
103
+ if qc > q_cp + 1e-9:
104
+ q_cp = qc
105
+ t_star = days[i]
106
+ mu_pre = m1
107
+ mu_post = m2
108
+ best_idx = i
109
+
110
+ r2_time = min(100.0, (q_cp / q_tot) * 100.0) if q_tot > EPS else 0.0
111
+
112
+ # Within-era RE-deflated contrast Q_cp_re (clamps v_i consistently with ws!)
113
+ q_cp_re = 0.0
114
+ mu_pre_re, mu_post_re = mu_pre, mu_post
115
+ if best_idx >= 0:
116
+ w1, y1, v1 = ws[: best_idx + 1], ys[: best_idx + 1], v_i[: best_idx + 1]
117
+ w2, y2, v2 = ws[best_idx + 1 :], ys[best_idx + 1 :], v_i[best_idx + 1 :]
118
+ q_w = sum(w * (y - mu_pre) ** 2 for w, y in zip(w1, y1)) + sum(w * (y - mu_post) ** 2 for w, y in zip(w2, y2))
119
+ df_w = max(0, k - 2)
120
+ c1 = sum(w1) - sum(w * w for w in w1) / sum(w1) if len(w1) > 1 else 0.0
121
+ c2 = sum(w2) - sum(w * w for w in w2) / sum(w2) if len(w2) > 1 else 0.0
122
+ c_w = c1 + c2
123
+ tau2_w = max(0.0, (q_w - df_w) / c_w) if (df_w > 0 and c_w > EPS and q_w > df_w) else 0.0
124
+ w1_re = [1.0 / (v + tau2_w) for v in v1]
125
+ w2_re = [1.0 / (v + tau2_w) for v in v2]
126
+ j1_re, j2_re = sum(w1_re), sum(w2_re)
127
+ mu_pre_re = sum(w * y for w, y in zip(w1_re, y1)) / j1_re
128
+ mu_post_re = sum(w * y for w, y in zip(w2_re, y2)) / j2_re
129
+ q_cp_re = ((mu_post_re - mu_pre_re) ** 2) / (1.0 / j1_re + 1.0 / j2_re)
130
+
131
+ # Weighted linear time trend Q_slope
132
+ t_bar = sum(w * t for w, t in zip(ws, yrs)) / j_fe
133
+ s_tt = sum(w * (t - t_bar) ** 2 for w, t in zip(ws, yrs))
134
+ s_ty = sum(w * (t - t_bar) * (y - mu_fe) for w, t, y in zip(ws, yrs, ys))
135
+ q_slope = (s_ty * s_ty) / s_tt if s_tt > EPS else 0.0
136
+ slope_per_yr = (s_ty / s_tt) if s_tt > EPS else 0.0
137
+ r2_slope = min(100.0, (q_slope / q_tot) * 100.0) if q_tot > EPS else 0.0
138
+
139
+ # Overdispersion-scaled quasi-likelihood BIC (prevents high-I^2 Q inflation from trivially beating ln(k)):
140
+ # Scale factor phi = max(1.0, min(Q_tot - Q_cp, Q_tot - Q_slope) / max(1, k - 2)) when k > 2.
141
+ q_res_step = max(0.0, q_tot - q_cp)
142
+ q_res_slope = max(0.0, q_tot - q_slope)
143
+ phi = max(1.0, min(q_res_step, q_res_slope) / max(1, k - 2)) if k > 2 else 1.0
144
+ ln_k = math.log(max(2, k))
145
+ bic_null = (q_tot / phi) + ln_k
146
+ bic_slope = (q_res_slope / phi) + 2.0 * ln_k
147
+ bic_step = (q_res_step / phi) + 3.0 * ln_k
148
+ bic_diff = bic_step - bic_slope
149
+ if min(bic_step, bic_slope) >= bic_null - 2.0:
150
+ shape_bic = "flat"
151
+ elif bic_diff <= -2.0:
152
+ shape_bic = "step_dominant"
153
+ elif bic_diff >= 2.0:
154
+ shape_bic = "slope_dominant"
155
+ else:
156
+ shape_bic = "mixed_step_slope"
157
+
158
+ # Optional comparator-switch confounding detector (evaluates ONLY known comparators!)
159
+ comp_switched = False
160
+ if comparator_by_id and t_star is not None:
161
+ pre_c = [comparator_by_id[s.id] for s in adm if s.day <= t_star and s.id in comparator_by_id]
162
+ post_c = [comparator_by_id[s.id] for s in adm if s.day > t_star and s.id in comparator_by_id]
163
+ if pre_c and post_c:
164
+ pre_pbo = sum(1 for c in pre_c if c == "placebo_or_control") / len(pre_c)
165
+ post_pbo = sum(1 for c in post_c if c == "placebo_or_control") / len(post_c)
166
+ comp_switched = abs(pre_pbo - post_pbo) >= 0.50
167
+
168
+ return {
169
+ "k": k,
170
+ "q_tot": q_tot,
171
+ "q_cp": q_cp,
172
+ "q_cp_re": q_cp_re,
173
+ "q_slope": q_slope,
174
+ "slope_per_yr": slope_per_yr,
175
+ "r2_time_pct": r2_time,
176
+ "r2_slope_pct": r2_slope,
177
+ "t_star": t_star,
178
+ "mu_pre": mu_pre,
179
+ "mu_post": mu_post,
180
+ "mu_pre_re": mu_pre_re,
181
+ "mu_post_re": mu_post_re,
182
+ "overdispersion_phi": phi,
183
+ "bic_step_minus_slope": bic_diff,
184
+ "shape_bic": shape_bic,
185
+ "comparator_switched": comp_switched,
186
+ }
187
+
188
+
189
+ def analyze_continuous_series(
190
+ values: Sequence[float],
191
+ times_yr: Sequence[float],
192
+ day_keys: Sequence[Any] | None = None,
193
+ ) -> dict[str, Any]:
194
+ """SE-free continuous temporal geometry with automatic chronological sorting, BIC step-vs-slope
195
+ router, n-normalized Kruskal-Wallis, and automated boilerplate copy-paste detector.
196
+ """
197
+ n = len(values)
198
+ if len(times_yr) != n:
199
+ raise ValueError(f"values (len={n}) and times_yr (len={len(times_yr)}) must have identical length")
200
+ dkeys_raw = list(day_keys) if day_keys is not None else list(times_yr)
201
+ if len(dkeys_raw) != n:
202
+ raise ValueError(f"values (len={n}) and day_keys (len={len(dkeys_raw)}) must have identical length")
203
+
204
+ # Filter non-finite inputs and sort strictly chronologically (preserving relative order on ties)
205
+ valid = [
206
+ (float(t), dkeys_raw[i], i, float(values[i]))
207
+ for i, t in enumerate(times_yr)
208
+ if math.isfinite(values[i]) and math.isfinite(t)
209
+ ]
210
+ valid.sort(key=lambda x: (x[0], x[2]))
211
+ n = len(valid)
212
+ if n < 2:
213
+ return {
214
+ "n": n, "r2_step_pct": 0.0, "r2_slope_pct": 0.0, "kw_z2": 0.0, "kw_norm": 0.0,
215
+ "t_star": None, "mu_pre": valid[0][3] if n else 0.0, "mu_post": valid[0][3] if n else 0.0,
216
+ "slope_per_yr": 0.0, "bic_step_minus_slope": 0.0, "shape_bic": "insufficient",
217
+ "is_boilerplate_copypaste": False,
218
+ }
219
+
220
+ ts = [x[0] for x in valid]
221
+ dkeys = [x[1] for x in valid]
222
+ ys = [x[3] for x in valid]
223
+
224
+ mean_y = sum(ys) / n
225
+ sst = sum((y - mean_y) ** 2 for y in ys)
226
+ tot_y = sum(ys)
227
+ ranks = _average_ranks(ys)
228
+ mean_r = (n + 1.0) / 2.0
229
+ var_r = sum((r - mean_r) ** 2 for r in ranks) / max(1, n - 1)
230
+ tot_r = sum(ranks)
231
+
232
+ best_ssb = best_kw = 0.0
233
+ best_t = None
234
+ mu_pre = mu_post = mean_y
235
+ cy = cr = 0.0
236
+ for i in range(n - 1):
237
+ cy += ys[i]
238
+ cr += ranks[i]
239
+ if dkeys[i] == dkeys[i + 1]:
240
+ continue
241
+ n1, n2 = i + 1, n - (i + 1)
242
+ m1, m2 = cy / n1, (tot_y - cy) / n2
243
+ ssb = (n1 * n2 / n) * ((m2 - m1) ** 2)
244
+ if ssb > best_ssb + 1e-12:
245
+ best_ssb, best_t, mu_pre, mu_post = ssb, dkeys[i], m1, m2
246
+ if var_r > EPS:
247
+ r1, r2 = cr / n1, (tot_r - cr) / n2
248
+ kw = ((n1 * n2) / n) * ((r2 - r1) ** 2) / var_r
249
+ if kw > best_kw + 1e-12:
250
+ best_kw = kw
251
+
252
+ r2_step = min(100.0, (best_ssb / sst) * 100.0) if sst > EPS else 0.0
253
+ # Floor residual variance relative to SST (1e-6 * SST) so exact 0-residual fits don't explode arbitrarily with EPS
254
+ res_floor = max(EPS, 1e-6 * sst)
255
+ ssw_step = max(res_floor, sst - best_ssb)
256
+ kw_norm = best_kw / max(1, n - 1)
257
+
258
+ t_bar = sum(ts) / n
259
+ s_tt = sum((t - t_bar) ** 2 for t in ts)
260
+ s_ty = sum((t - t_bar) * (y - mean_y) for t, y in zip(ts, ys))
261
+ if s_tt > EPS and sst > EPS:
262
+ slope = s_ty / s_tt
263
+ ss_reg = (s_ty * s_ty) / s_tt
264
+ r2_slope = min(100.0, (ss_reg / sst) * 100.0)
265
+ else:
266
+ slope = ss_reg = r2_slope = 0.0
267
+ sse_slope = max(res_floor, sst - ss_reg)
268
+
269
+ if sst > EPS and n >= 4:
270
+ ln_n = math.log(n)
271
+ bic_null = n * math.log(sst / n) + 2.0 * ln_n
272
+ bic_slope = n * math.log(sse_slope / n) + 3.0 * ln_n
273
+ bic_step = n * math.log(ssw_step / n) + 4.0 * ln_n
274
+ bic_diff = bic_step - bic_slope
275
+ if min(bic_step, bic_slope) >= bic_null - 2.0:
276
+ shape_bic = "flat"
277
+ elif bic_diff <= -2.0:
278
+ shape_bic = "step_dominant"
279
+ elif bic_diff >= 2.0:
280
+ shape_bic = "slope_dominant"
281
+ else:
282
+ shape_bic = "mixed_step_slope"
283
+ else:
284
+ bic_diff = 0.0
285
+ shape_bic = "flat"
286
+
287
+ uniq_vals = len({round(y, 6) for y in ys})
288
+ is_boilerplate = (n >= 5 and uniq_vals <= 2) or (n >= 5 and r2_step >= 99.99)
289
+
290
+ return {
291
+ "n": n,
292
+ "r2_step_pct": r2_step,
293
+ "r2_slope_pct": r2_slope,
294
+ "kw_z2": best_kw,
295
+ "kw_norm": kw_norm,
296
+ "t_star": best_t,
297
+ "mu_pre": mu_pre,
298
+ "mu_post": mu_post,
299
+ "slope_per_yr": slope,
300
+ "bic_step_minus_slope": bic_diff,
301
+ "shape_bic": shape_bic,
302
+ "is_boilerplate_copypaste": is_boilerplate,
303
+ }
304
+
305
+
306
+ def synchronized_panel_permutation(
307
+ panel_rows: Sequence[Sequence[float]],
308
+ times_yr: Sequence[float],
309
+ *,
310
+ n_perm: int = 1000,
311
+ seed: int = 42,
312
+ ) -> dict[str, Any]:
313
+ """Exact tie-preserving synchronized column-time permutation across a balanced panel (G units x T times).
314
+
315
+ Applies ONE shared time permutation pi simultaneously across all G cross-sectional units per
316
+ replicate, preserving spatial correlation. Note: for strongly autocorrelated stock series (AR(1)
317
+ rho -> 1), pass first differences (Delta y_t) or log-growth rates (Delta log y_t) rather than raw levels!
318
+ """
319
+ if n_perm <= 0:
320
+ raise ValueError("n_perm must be > 0")
321
+ g_units = len(panel_rows)
322
+ t_len = len(times_yr)
323
+ if g_units == 0 or t_len < 3:
324
+ return {"n_units": g_units, "n_times": t_len, "n_perm": n_perm}
325
+ for idx, row in enumerate(panel_rows):
326
+ if len(row) != t_len:
327
+ raise ValueError(f"panel_rows[{idx}] length {len(row)} != len(times_yr) {t_len}")
328
+
329
+ # Sort columns chronologically and precompute tie-preserving split indices matching analyze_continuous_series
330
+ col_order = sorted(range(t_len), key=lambda i: times_yr[i])
331
+ ts = [float(times_yr[i]) for i in col_order]
332
+ split_indices = [i for i in range(t_len - 1) if ts[i] != ts[i + 1]]
333
+ t_bar = sum(ts) / t_len
334
+ t_dev = [t - t_bar for t in ts]
335
+ s_tt = sum(td * td for td in t_dev)
336
+ if not split_indices or s_tt <= EPS:
337
+ return {
338
+ "n_units": g_units, "n_times": t_len, "n_perm": n_perm,
339
+ "obs_mean_r2_step_pct": 0.0, "null_mean_r2_step_pct": 0.0, "mean_excess_r2_step_pct": 0.0,
340
+ "sync_p_step": 1.0, "obs_mean_r2_slope_pct": 0.0, "null_mean_r2_slope_pct": 0.0,
341
+ "mean_excess_r2_slope_pct": 0.0, "sync_p_slope": 1.0, "mean_bic_step_minus_slope": 0.0,
342
+ }
343
+
344
+ rng = random.Random(seed)
345
+ unit_meta = []
346
+ obs_step = []
347
+ obs_slope = []
348
+ obs_bic = []
349
+ for raw_row in panel_rows:
350
+ row = [float(raw_row[i]) for i in col_order]
351
+ res = analyze_continuous_series(row, ts, ts)
352
+ obs_step.append(res["r2_step_pct"])
353
+ obs_slope.append(res["r2_slope_pct"])
354
+ obs_bic.append(res["bic_step_minus_slope"])
355
+ my = sum(row) / t_len
356
+ sst = sum((y - my) ** 2 for y in row)
357
+ unit_meta.append((row, sum(row), my, sst))
358
+
359
+ obs_step_m = sum(obs_step) / g_units
360
+ obs_slope_m = sum(obs_slope) / g_units
361
+ null_step = []
362
+ null_slope = []
363
+ split_set = set(split_indices)
364
+ for _ in range(n_perm):
365
+ pi = list(range(t_len))
366
+ rng.shuffle(pi)
367
+ ss = sl = 0.0
368
+ for row, tot_y, my, sst in unit_meta:
369
+ if sst <= EPS:
370
+ continue
371
+ cy = sty = best_ssb = 0.0
372
+ for i in range(t_len):
373
+ yv = row[pi[i]]
374
+ cy += yv
375
+ sty += t_dev[i] * (yv - my)
376
+ if i in split_set:
377
+ n1, n2 = i + 1, t_len - (i + 1)
378
+ m1, m2 = cy / n1, (tot_y - cy) / n2
379
+ ssb = (n1 * n2 / t_len) * ((m2 - m1) ** 2)
380
+ if ssb > best_ssb:
381
+ best_ssb = ssb
382
+ ss += min(100.0, (best_ssb / sst) * 100.0)
383
+ sl += min(100.0, ((sty * sty) / (s_tt * sst)) * 100.0)
384
+ null_step.append(ss / g_units)
385
+ null_slope.append(sl / g_units)
386
+
387
+ null_step_m = sum(null_step) / n_perm
388
+ null_slope_m = sum(null_slope) / n_perm
389
+ return {
390
+ "n_units": g_units,
391
+ "n_times": t_len,
392
+ "n_perm": n_perm,
393
+ "obs_mean_r2_step_pct": round(obs_step_m, 3),
394
+ "null_mean_r2_step_pct": round(null_step_m, 3),
395
+ "mean_excess_r2_step_pct": round(obs_step_m - null_step_m, 3),
396
+ "sync_p_step": round((1 + sum(1 for x in null_step if x >= obs_step_m - 1e-12)) / (n_perm + 1), 4),
397
+ "obs_mean_r2_slope_pct": round(obs_slope_m, 3),
398
+ "null_mean_r2_slope_pct": round(null_slope_m, 3),
399
+ "mean_excess_r2_slope_pct": round(obs_slope_m - null_slope_m, 3),
400
+ "sync_p_slope": round((1 + sum(1 for x in null_slope if x >= obs_slope_m - 1e-12)) / (n_perm + 1), 4),
401
+ "mean_bic_step_minus_slope": round(sum(obs_bic) / g_units, 3),
402
+ }
cs_temporal/rdf.py ADDED
@@ -0,0 +1,88 @@
1
+ """Zero-dependency W3C Turtle RDF serializer and portable SPARQL 1.1 Rule_H0f query."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from typing import Sequence
6
+
7
+ from .engine import Study
8
+
9
+ RULE_H0F_SPARQL = """PREFIX asof: <https://conductscience.com/ns/as-of/>
10
+ PREFIX time: <http://www.w3.org/2006/time#>
11
+ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
12
+ # Exact W3C SPARQL 1.1 Rule_H0f v5 (Max-Q_cp autonomous changepoint with live retraction purge)
13
+ SELECT ?topic ?tCut ?qCpRaw ?muPreRaw ?muPostRaw WHERE {
14
+ {
15
+ SELECT ?topic ?tCut
16
+ (SUM(IF(xsd:dateTime(STR(?tIn)) <= xsd:dateTime(STR(?tCut)), 1.0e0 / (xsd:double(?seIn) * xsd:double(?seIn)), 0.0e0)) AS ?w1)
17
+ (SUM(IF(xsd:dateTime(STR(?tIn)) <= xsd:dateTime(STR(?tCut)), xsd:double(?dIn) / (xsd:double(?seIn) * xsd:double(?seIn)), 0.0e0)) AS ?wy1)
18
+ (SUM(IF(xsd:dateTime(STR(?tIn)) > xsd:dateTime(STR(?tCut)), 1.0e0 / (xsd:double(?seIn) * xsd:double(?seIn)), 0.0e0)) AS ?w2)
19
+ (SUM(IF(xsd:dateTime(STR(?tIn)) > xsd:dateTime(STR(?tCut)), xsd:double(?dIn) / (xsd:double(?seIn) * xsd:double(?seIn)), 0.0e0)) AS ?wy2)
20
+ WHERE {
21
+ { SELECT DISTINCT ?topic ?tCut WHERE {
22
+ ?cCut asof:ASOF000341 ?topic ; asof:ASOF000254 ?iCut .
23
+ FILTER NOT EXISTS { ?retC a asof:ASOF000010 ; asof:ASOF000216 ?cCut . }
24
+ ?iCut time:inXSDDateTimeStamp ?tCut .
25
+ } }
26
+ ?cIn asof:ASOF000334 ?dIn ; asof:ASOF000336 ?seIn ; asof:ASOF000341 ?topic ; asof:ASOF000254 ?iIn .
27
+ FILTER NOT EXISTS { ?retI a asof:ASOF000010 ; asof:ASOF000216 ?cIn . }
28
+ ?iIn time:inXSDDateTimeStamp ?tIn .
29
+ } GROUP BY ?topic ?tCut
30
+ }
31
+ FILTER (?w1 > 0.0e0 && ?w2 > 0.0e0)
32
+ BIND(?wy1 / ?w1 AS ?muPreRaw)
33
+ BIND(?wy2 / ?w2 AS ?muPostRaw)
34
+ BIND((((?muPostRaw - ?muPreRaw) * (?muPostRaw - ?muPreRaw)) / ((1.0e0 / ?w1) + (1.0e0 / ?w2))) AS ?qCpRaw)
35
+ } ORDER BY ?topic DESC(?qCpRaw) ASC(?tCut)
36
+ """
37
+
38
+
39
+ def _safe_slug(s: str) -> str:
40
+ return re.sub(r"[^a-zA-Z0-9_-]+", "_", s).strip("_") or "item"
41
+
42
+
43
+ def _esc(s: str) -> str:
44
+ return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ")
45
+
46
+
47
+ def export_turtle(studies: Sequence[Study], topic_slug: str = "series", topic_label: str = "Clinical Evidence Series", as_of: str | None = None) -> str:
48
+ """Serialize a study series into W3C Turtle RDF compatible with SPARQL 1.1 Rule_H0f."""
49
+ t_slug = _safe_slug(topic_slug)
50
+ lines = [
51
+ "@prefix asof: <https://conductscience.com/ns/as-of/> .",
52
+ "@prefix owl: <http://www.w3.org/2002/07/owl#> .",
53
+ "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .",
54
+ "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .",
55
+ "@prefix time: <http://www.w3.org/2006/time#> .",
56
+ "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .",
57
+ "",
58
+ f"asof:topic_{t_slug} a owl:NamedIndividual , asof:ASOF000340 ;",
59
+ f' rdfs:label "{_esc(topic_label)}" .',
60
+ "",
61
+ ]
62
+ for idx, s in enumerate(sorted(studies, key=lambda x: (x.day, x.id))):
63
+ if as_of and s.day > as_of:
64
+ continue
65
+ cid = f"claim_{t_slug}_{_safe_slug(s.id)}_{idx}"
66
+ iid = f"inst_{t_slug}_{_safe_slug(s.id)}_{idx}"
67
+ lines.extend([
68
+ f"asof:{iid} a owl:NamedIndividual , time:Instant ;",
69
+ f' time:inXSDDateTimeStamp "{s.day}T00:00:00Z"^^xsd:dateTimeStamp .',
70
+ f"asof:{cid} a owl:NamedIndividual , asof:ASOF000333 ;",
71
+ f' rdfs:label "{_esc(s.label or s.id)}" ;',
72
+ f" asof:ASOF000341 asof:topic_{t_slug} ;",
73
+ f' asof:ASOF000334 "{s.y}"^^xsd:double ;',
74
+ f' asof:ASOF000336 "{s.se}"^^xsd:double ;',
75
+ f" asof:ASOF000254 asof:{iid} .",
76
+ ])
77
+ if s.retracted_day and (as_of is None or s.retracted_day <= as_of):
78
+ rid = f"retraction_{t_slug}_{_safe_slug(s.id)}_{idx}"
79
+ riid = f"ret_inst_{t_slug}_{_safe_slug(s.id)}_{idx}"
80
+ lines.extend([
81
+ f"asof:{riid} a owl:NamedIndividual , time:Instant ;",
82
+ f' time:inXSDDateTimeStamp "{s.retracted_day}T00:00:00Z"^^xsd:dateTimeStamp .',
83
+ f"asof:{rid} a owl:NamedIndividual , asof:ASOF000010 ;",
84
+ f" asof:ASOF000216 asof:{cid} ;",
85
+ f" asof:ASOF000254 asof:{riid} .",
86
+ ])
87
+ lines.append("")
88
+ return "\n".join(lines)
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: cs-temporal
3
+ Version: 0.2.0
4
+ Summary: Zero-dependency bitemporal meta-analysis geometry, autonomous changepoint detection (Max-Q_cp), live retraction purge, and W3C SPARQL 1.1 Rule_H0f export.
5
+ Author: ConductScience Foundation
6
+ Author-email: Shuhan He <shuhan@conductscience.com>
7
+ License: Apache-2.0
8
+ Project-URL: Homepage, https://conductscience-foundation.github.io/cs-temporal/
9
+ Project-URL: Repository, https://github.com/ConductScience-Foundation/cs-temporal
10
+ Project-URL: ConductScience Time, https://conductscience.org/search?mode=time
11
+ Keywords: meta-analysis,evidence-synthesis,temporal-reasoning,clinical-trials,changepoint,retraction,sparql,rdf
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: Healthcare Industry
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # cs-temporal
27
+
28
+ **Zero-dependency bitemporal evidence geometry, autonomous changepoint detection (`Max-Q_cp`), live retraction purge, and W3C SPARQL 1.1 `Rule_H0f` export.**
29
+
30
+ Part of the [ConductScience Foundation](https://github.com/ConductScience-Foundation) open-source tooling initiative. For live search across clinical trial timelines in medicine, see https://conductscience.org/search?mode=time.
31
+
32
+ ## Why cs-temporal
33
+
34
+ Standard meta-analysis pools trials as if clinical evidence were timeless. When early positive trials are followed by null or negative trials, or when a pivotal trial is later retracted, classical random-effects pooling absorbs the shift into between-study variance (`tau^2`) and obscures when the conclusion changed.
35
+
36
+ `cs-temporal` computes exact closed-form bitemporal evidence geometry with **zero runtime dependencies**:
37
+
38
+ - **Causal-cone `"As Of"` evaluation:** Strictly excludes studies published after `as_of` and excludes retracted studies once `retracted_day <= as_of`.
39
+ - **Exact DerSimonian-Laird random-effects & fixed-effect estimates:** `mu_FE`, `mu_RE`, `se_RE`, 95% CI, Cochran's `Q_tot`, `tau^2`, `I^2`.
40
+ - **Autonomous `Max-Q_cp` changepoint discovery:** Scans all distinct chronological split dates with deterministic earliest-`t*` tie-breaking (`1e-9` tolerance) and computes temporal heterogeneity share `R^2_time = Q_cp / Q_tot`.
41
+ - **Tie-preserving chronological permutation test:** Evaluates unrounded `Q_cp` and excess `R^2_time` above the exact date-block permutation null.
42
+ - **Leave-one-out counterfactual replay:** Recomputes the full timeline with any study excluded (`without=[...]`).
43
+ - **W3C Turtle RDF & SPARQL 1.1 `Rule_H0f` export:** Emit standards-compliant RDF graphs compatible with Oxigraph, Jena, Virtuoso, or RDFLib.
44
+ - **Multi-modal v0.2.0 extensions (`cs_temporal.multimodal`):**
45
+ - `analyze_ivw_shape`: Overdispersion-scaled quasi-likelihood BIC step-vs-slope router (`step_dominant`, `slope_dominant`, `mixed_step_slope`, `flat`), within-era random-effects contrast (`Q_cp_re`), and comparator-switch confounding guard (`comparator_by_id`).
46
+ - `analyze_continuous_series`: SE-free continuous BIC cliff-vs-ramp router with automatic chronological sorting, n-normalized Kruskal-Wallis, and boilerplate copy-paste detection.
47
+ - `synchronized_panel_permutation`: Tie-preserving synchronized column-time permutation across balanced cross-sectional panels (for stationary or first-differenced time series).
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ pip install cs-temporal
53
+ ```
54
+
55
+ ## Quick start (CLI)
56
+
57
+ ```bash
58
+ # Run built-in Hydroxychloroquine COVID-19 timeline before and after the 27 Dec 2024 retraction
59
+ cs-temporal demo hcq --as-of 2024-12-26
60
+ cs-temporal demo hcq --as-of 2024-12-27
61
+
62
+ # Analyze your own CSV (columns: id,day,y,se,label,retracted_day)
63
+ cs-temporal analyze studies.csv --as-of 2025-01-01 --perm 1000 --json
64
+
65
+ # Export W3C Turtle RDF
66
+ cs-temporal export-rdf studies.csv --topic my-drug --out graph.ttl
67
+ ```
68
+
69
+ ## Quick start (Python)
70
+
71
+ ```python
72
+ from cs_temporal import DEMO_SERIES, build_replay, tie_preserving_permutation_test
73
+
74
+ pre = build_replay(DEMO_SERIES["hcq"], as_of="2024-12-26")
75
+ post = build_replay(DEMO_SERIES["hcq"], as_of="2024-12-27")
76
+ print(pre.current.status, pre.current.q_cp, pre.current.t_star)
77
+ print(post.current.status, post.current.q_cp, post.current.k_purged)
78
+ ```
79
+
80
+ ## Zero-install browser app
81
+
82
+ Open `docs/index.html` locally (or via GitHub Pages) to paste any CSV, scrub the `As of` date on a stepped cumulative meta-analysis chart with 95% confidence band, run live leave-one-out sensitivity checks, and export W3C Turtle RDF completely offline in your browser.
83
+
84
+ ## License
85
+
86
+ Apache-2.0.
@@ -0,0 +1,11 @@
1
+ cs_temporal/__init__.py,sha256=Z3YSEce6nRFtlRiBwZ5WuHdgMyVPt3bvcjj3G2aUuj0,897
2
+ cs_temporal/cli.py,sha256=32gX6xtgUJj2PmnE9rijrZt2jBp6MWFxDXa5obhIAS4,4300
3
+ cs_temporal/engine.py,sha256=coBL1Lntg5abfr3V42QwyLCiXL9uGpQqs-vD7m63dLE,12090
4
+ cs_temporal/multimodal.py,sha256=sb_eCIkNrw2ckQ6b58pzwFDOqKw2eOz7bbT8ADYcTvI,15913
5
+ cs_temporal/rdf.py,sha256=EBdb7J1rKtzCIPBvH9N-P7VW_O14rlLncug0S-vBtws,4355
6
+ cs_temporal-0.2.0.dist-info/licenses/LICENSE,sha256=kNxcVPAiRTvA-0LyIgk4SOT8WKcDxOA_eqAsnmTkwRM,10721
7
+ cs_temporal-0.2.0.dist-info/METADATA,sha256=fPzmZdMWL9dW8cAWuRD2wsffgp7vFSh43WE_fVp5v3M,5006
8
+ cs_temporal-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ cs_temporal-0.2.0.dist-info/entry_points.txt,sha256=RRpCwlt7T011EGx7dKAWEVWqae4-F_i0t3iAzteuBDc,53
10
+ cs_temporal-0.2.0.dist-info/top_level.txt,sha256=uuSX_NFkMeUaQFp513grB26nadEhlr_1_JLjVTB_zm0,12
11
+ cs_temporal-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cs-temporal = cs_temporal.cli:main
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE file distributed
112
+ as part of the Derivative Works; within the Derivative Works
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE file from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Work) on an "AS IS" BASIS, WITHOUT
146
+ WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
147
+ INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF
148
+ TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any kind, arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and accept support, warranty, or additional liability obligations
168
+ and/or rights consistent with this License. However, in accepting
169
+ such obligations, You may act only on Your own behalf and on Your
170
+ own sole responsibility, not on behalf of any other Contributor,
171
+ and only if You agree to indemnify, defend, and hold each Contributor
172
+ harmless for any liability incurred by, or claims asserted against,
173
+ any Contributor by reason of your accepting any such warranty or
174
+ additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 ConductScience Foundation
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1 @@
1
+ cs_temporal