anthromesh 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.
- anthromesh/__init__.py +3 -0
- anthromesh/adapters/__init__.py +18 -0
- anthromesh/adapters/base.py +218 -0
- anthromesh/adapters/cloud.py +151 -0
- anthromesh/adapters/factory.py +31 -0
- anthromesh/adapters/heuristic.py +113 -0
- anthromesh/adapters/local.py +91 -0
- anthromesh/benchmarks/__init__.py +3 -0
- anthromesh/benchmarks/datasets.py +207 -0
- anthromesh/benchmarks/empirical.py +176 -0
- anthromesh/benchmarks/panel_cohort.py +67 -0
- anthromesh/benchmarks/public_twin.py +414 -0
- anthromesh/benchmarks/public_validation.py +435 -0
- anthromesh/benchmarks/replay.py +174 -0
- anthromesh/benchmarks/runner.py +140 -0
- anthromesh/benchmarks/study.py +245 -0
- anthromesh/benchmarks/study_report.py +170 -0
- anthromesh/capture/__init__.py +1 -0
- anthromesh/capture/github_webhook.py +51 -0
- anthromesh/capture/graph.py +221 -0
- anthromesh/capture/workflows.py +70 -0
- anthromesh/cli.py +807 -0
- anthromesh/client.py +96 -0
- anthromesh/cohort/__init__.py +3 -0
- anthromesh/cohort/categorical_anchor.py +240 -0
- anthromesh/cohort/clustering.py +93 -0
- anthromesh/cohort/human_anchor.py +92 -0
- anthromesh/cohort/ingest.py +104 -0
- anthromesh/cohort/oracle.py +153 -0
- anthromesh/cohort/twin_priors.py +118 -0
- anthromesh/config.py +48 -0
- anthromesh/gate/__init__.py +15 -0
- anthromesh/gate/calibration.py +95 -0
- anthromesh/gate/conformal.py +73 -0
- anthromesh/gate/engine.py +293 -0
- anthromesh/gate/fast.py +62 -0
- anthromesh/gate/fit.py +56 -0
- anthromesh/judgment/__init__.py +1 -0
- anthromesh/judgment/elicitation.py +206 -0
- anthromesh/judgment/monitor.py +128 -0
- anthromesh/judgment/panel.py +389 -0
- anthromesh/judgment/settings.py +41 -0
- anthromesh/models/__init__.py +39 -0
- anthromesh/models/cohort.py +76 -0
- anthromesh/models/decision.py +81 -0
- anthromesh/models/escalation.py +70 -0
- anthromesh/models/policy.py +41 -0
- anthromesh/models/validity.py +17 -0
- anthromesh/protocols/__init__.py +4 -0
- anthromesh/protocols/a2a_server.py +414 -0
- anthromesh/protocols/capabilities.py +52 -0
- anthromesh/protocols/delegation.py +373 -0
- anthromesh/protocols/mcp_server.py +500 -0
- anthromesh/protocols/oauth.py +177 -0
- anthromesh/ros_gate.py +141 -0
- anthromesh/twin/__init__.py +3 -0
- anthromesh/twin/engine.py +116 -0
- anthromesh/twin/inbox.py +221 -0
- anthromesh/vault/__init__.py +5 -0
- anthromesh/vault/dense.py +171 -0
- anthromesh/vault/encryption.py +50 -0
- anthromesh/vault/policy_engine.py +123 -0
- anthromesh/vault/postgres.py +92 -0
- anthromesh/vault/privacy.py +264 -0
- anthromesh/vault/retrieval.py +135 -0
- anthromesh/vault/storage.py +937 -0
- anthromesh-0.2.0.dist-info/METADATA +493 -0
- anthromesh-0.2.0.dist-info/RECORD +73 -0
- anthromesh-0.2.0.dist-info/WHEEL +5 -0
- anthromesh-0.2.0.dist-info/entry_points.txt +2 -0
- anthromesh-0.2.0.dist-info/licenses/LICENSE +201 -0
- anthromesh-0.2.0.dist-info/licenses/NOTICE +2 -0
- anthromesh-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
"""Development and held-out validation of population-adjusted personal forecasts."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import html
|
|
6
|
+
import json
|
|
7
|
+
import tempfile
|
|
8
|
+
import unicodedata
|
|
9
|
+
from collections import Counter, defaultdict
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from statistics import fmean
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from anthromesh.adapters.heuristic import HeuristicAdapter
|
|
17
|
+
from anthromesh.benchmarks.public_twin import FILE_HASHES, Item, _items, _query, _rank, _reference_rows, _table
|
|
18
|
+
from anthromesh.benchmarks.study_report import _interval
|
|
19
|
+
from anthromesh.cohort.oracle import ResearchCohortOracle
|
|
20
|
+
from anthromesh.gate.calibration import compute_ece, jensen_shannon_divergence
|
|
21
|
+
from anthromesh.models import CohortArchetype, CohortProfile, CohortQuery, DecisionLog
|
|
22
|
+
from anthromesh.vault.retrieval import HybridDecisionRetriever
|
|
23
|
+
from anthromesh.vault.storage import BehavioralVault
|
|
24
|
+
|
|
25
|
+
SEED = "anthromesh-public-validation-v2"
|
|
26
|
+
GRID = ((0, 0.0), *((k, strength) for strength in (0.25, 0.5, 0.75, 1.0) for k in (32, 64, 128, 256)))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class PublicValidation:
|
|
31
|
+
items: dict[str, Item]
|
|
32
|
+
questions: list[str]
|
|
33
|
+
earlier: dict
|
|
34
|
+
later: dict
|
|
35
|
+
exploratory: list[str]
|
|
36
|
+
selection: list[str]
|
|
37
|
+
calibration: list[str]
|
|
38
|
+
sealed: list[str]
|
|
39
|
+
reference: list[str]
|
|
40
|
+
features: list[str]
|
|
41
|
+
fingerprint: str
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def load_public_validation(folder: Path, original_report: Path) -> PublicValidation:
|
|
45
|
+
for filename in ("question_catalog.json", "wave1_3_response.csv", "wave4_response.csv"):
|
|
46
|
+
if hashlib.sha256((folder / filename).read_bytes()).hexdigest() != FILE_HASHES[filename]:
|
|
47
|
+
raise ValueError(f"Unexpected dataset content for {filename}.")
|
|
48
|
+
catalog = json.loads((folder / "question_catalog.json").read_text(encoding="utf-8-sig"))
|
|
49
|
+
report = json.loads(original_report.read_text(encoding="utf-8-sig"))
|
|
50
|
+
if report["seed"] != "anthromesh-public-v1" or report["evaluation_participants"] != 60:
|
|
51
|
+
raise ValueError("Use the original 60-person AnthroMesh report.")
|
|
52
|
+
items = _items(catalog)
|
|
53
|
+
earlier_cols, earlier = _table(folder / "wave1_3_response.csv")
|
|
54
|
+
later_cols, later = _table(folder / "wave4_response.csv")
|
|
55
|
+
paired = sorted(items.keys() & earlier_cols & later_cols,
|
|
56
|
+
key=lambda key: _rank(report["seed"], "question", key))
|
|
57
|
+
questions = paired[len(paired) // 2:]
|
|
58
|
+
if questions != report["evaluation_question_columns"]:
|
|
59
|
+
raise ValueError("The reported question split does not match the pinned catalog.")
|
|
60
|
+
people = sorted(earlier.keys() & later.keys(),
|
|
61
|
+
key=lambda pid: _rank(report["seed"], "participant", pid))
|
|
62
|
+
fresh = sorted(people[92:], key=lambda pid: _rank(SEED, pid))
|
|
63
|
+
if len(fresh) < 500:
|
|
64
|
+
raise ValueError("The full pinned dataset is required.")
|
|
65
|
+
repeated_text = {items[key].text.casefold() for key in paired}
|
|
66
|
+
features = [key for key in sorted((items.keys() & earlier_cols) - later_cols)
|
|
67
|
+
if items[key].text.casefold() not in repeated_text]
|
|
68
|
+
fingerprint = _rank(SEED, repr(questions), repr(features), repr(fresh), repr(GRID), repr(FILE_HASHES))
|
|
69
|
+
return PublicValidation(items, questions, earlier, later, people[:60], fresh[:100], fresh[100:200],
|
|
70
|
+
fresh[200:400], fresh[400:], features, fingerprint)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _choices(data: PublicValidation, people: list[str], columns: list[str], wave: dict) -> np.ndarray:
|
|
74
|
+
values = []
|
|
75
|
+
for column in columns:
|
|
76
|
+
item = data.items[column]
|
|
77
|
+
indexes = {option.option_id: i for i, option in enumerate(item.options)}
|
|
78
|
+
values.append([indexes.get(item.answer(wave[person]), -1) for person in people])
|
|
79
|
+
return np.asarray(values, dtype=np.int16).T
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _similar_history(targets: np.ndarray, reference: np.ndarray) -> np.ndarray:
|
|
83
|
+
order = []
|
|
84
|
+
for target in targets:
|
|
85
|
+
overlap = (reference >= 0) & (target >= 0)
|
|
86
|
+
matched = np.count_nonzero(overlap & (reference == target), axis=1)
|
|
87
|
+
similarity = matched / (np.count_nonzero(overlap, axis=1) + 12)
|
|
88
|
+
order.append(np.argsort(-similarity, kind="stable"))
|
|
89
|
+
return np.asarray(order)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class PopulationAdjustedTwin:
|
|
93
|
+
"""A cross-question survey predictor with opt-in evidence adjustment."""
|
|
94
|
+
|
|
95
|
+
def __init__(self, data: PublicValidation) -> None:
|
|
96
|
+
self.data = data
|
|
97
|
+
self.reference = _choices(data, data.reference, data.features, data.earlier)
|
|
98
|
+
self.early_choices = _choices(data, data.reference, data.questions, data.earlier)
|
|
99
|
+
self.priors = []
|
|
100
|
+
for j, column in enumerate(data.questions):
|
|
101
|
+
observed = self.early_choices[:, j]
|
|
102
|
+
counts = np.bincount(observed[observed >= 0], minlength=len(data.items[column].options))
|
|
103
|
+
self.priors.append((counts + 0.5) / (counts.sum() + 0.5 * len(counts)))
|
|
104
|
+
|
|
105
|
+
def forecast(self, people: list[str], sizes: set[int], *, shuffle: bool = False) -> dict:
|
|
106
|
+
if not sizes:
|
|
107
|
+
return {}
|
|
108
|
+
features = _choices(self.data, people, self.data.features, self.data.earlier)
|
|
109
|
+
if shuffle:
|
|
110
|
+
permutation = sorted(range(len(people)), key=lambda i: _rank(SEED, "shuffle", people[i]))
|
|
111
|
+
features = features[permutation]
|
|
112
|
+
neighbors = _similar_history(features, self.reference)
|
|
113
|
+
forecasts = {k: [] for k in sizes}
|
|
114
|
+
for j, prior in enumerate(self.priors):
|
|
115
|
+
labels = self.early_choices[:, j]
|
|
116
|
+
labels = labels[neighbors]
|
|
117
|
+
for k in sizes:
|
|
118
|
+
votes = np.asarray([
|
|
119
|
+
np.bincount(row[row >= 0][:k], minlength=len(prior))
|
|
120
|
+
for row in labels
|
|
121
|
+
])
|
|
122
|
+
forecasts[k].append((votes + 20 * prior) / (votes.sum(axis=1, keepdims=True) + 20))
|
|
123
|
+
return forecasts
|
|
124
|
+
|
|
125
|
+
def blend(self, forecasts: dict, setting: tuple[int, float], count: int) -> list[np.ndarray]:
|
|
126
|
+
neighbors, strength = setting
|
|
127
|
+
if strength == 0:
|
|
128
|
+
return [np.broadcast_to(prior, (count, len(prior))) for prior in self.priors]
|
|
129
|
+
return [(1 - strength) * prior + strength * votes
|
|
130
|
+
for prior, votes in zip(self.priors, forecasts[neighbors])]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _case_predictions(distributions: list[np.ndarray], truth: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
134
|
+
chosen = np.column_stack([dist.argmax(axis=1) for dist in distributions])
|
|
135
|
+
confidence = np.column_stack([dist.max(axis=1) for dist in distributions])
|
|
136
|
+
return chosen == truth, confidence, chosen
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _means(correct: np.ndarray, present: np.ndarray) -> list[float]:
|
|
140
|
+
return [float(row[mask].mean()) for row, mask in zip(correct, present) if mask.any()]
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _ranking(confidence: np.ndarray, mask: np.ndarray, people: list[str], questions: list[str]):
|
|
144
|
+
return sorted(zip(*np.where(mask)),
|
|
145
|
+
key=lambda ij: (-confidence[ij], _rank(SEED, people[ij[0]], questions[ij[1]])))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _roc_auc(scores: np.ndarray, correct: np.ndarray) -> float | None:
|
|
149
|
+
counts = Counter(zip(scores.tolist(), correct.tolist()))
|
|
150
|
+
ordered = sorted(set(scores.tolist()))
|
|
151
|
+
negatives = concordant = 0
|
|
152
|
+
for score in ordered:
|
|
153
|
+
bad = counts[score, False]
|
|
154
|
+
concordant += counts[score, True] * (negatives + bad / 2)
|
|
155
|
+
negatives += bad
|
|
156
|
+
positives = int(correct.sum())
|
|
157
|
+
return concordant / (positives * negatives) if positives and negatives else None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _fit_confidence(confidence: np.ndarray, correct: np.ndarray, present: np.ndarray) -> list[float]:
|
|
161
|
+
bins = np.minimum(9, (confidence[present] * 10).astype(int))
|
|
162
|
+
correct = correct[present]
|
|
163
|
+
blocks = []
|
|
164
|
+
for bin_id in range(10):
|
|
165
|
+
mask = bins == bin_id
|
|
166
|
+
blocks.append([int(correct[mask].sum()) + 1, int(mask.sum()) + 2, 1])
|
|
167
|
+
while len(blocks) > 1 and blocks[-2][0] / blocks[-2][1] > blocks[-1][0] / blocks[-1][1]:
|
|
168
|
+
right = blocks.pop()
|
|
169
|
+
blocks[-1] = [left + value for left, value in zip(blocks[-1], right)]
|
|
170
|
+
return [correct / total for correct, total, slots in blocks for _ in range(slots)]
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _stage_fit(data: PublicValidation, model: PopulationAdjustedTwin) -> dict:
|
|
174
|
+
people = data.selection
|
|
175
|
+
truth = _choices(data, people, data.questions, data.later)
|
|
176
|
+
present = truth >= 0
|
|
177
|
+
cached = model.forecast(people, {k for k, _ in GRID if k})
|
|
178
|
+
results = []
|
|
179
|
+
for setting in GRID:
|
|
180
|
+
correct, _, _ = _case_predictions(model.blend(cached, setting, len(people)), truth)
|
|
181
|
+
results.append((fmean(_means(correct, present)), setting))
|
|
182
|
+
# GRID starts with the majority and is ordered by increasing blend strength.
|
|
183
|
+
accuracy, selected = max(results, key=lambda row: row[0])
|
|
184
|
+
people = data.calibration
|
|
185
|
+
truth = _choices(data, people, data.questions, data.later)
|
|
186
|
+
cached = model.forecast(people, {selected[0]} - {0})
|
|
187
|
+
correct, confidence, _ = _case_predictions(model.blend(cached, selected, len(people)), truth)
|
|
188
|
+
ranking = _ranking(confidence, truth >= 0, people, data.questions)
|
|
189
|
+
cutoff = ranking[max(0, round(len(ranking) * 0.25) - 1)]
|
|
190
|
+
return {
|
|
191
|
+
"protocol": SEED, "data_fingerprint": data.fingerprint,
|
|
192
|
+
"neighbors": selected[0], "personal_weight": selected[1],
|
|
193
|
+
"selection_accuracy": accuracy, "selection_majority_accuracy": results[0][0],
|
|
194
|
+
"operating_cutoff": [float(confidence[cutoff]), _rank(SEED, people[cutoff[0]], data.questions[cutoff[1]])],
|
|
195
|
+
"calibrated_bins": _fit_confidence(confidence, correct, truth >= 0),
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _bound(data: PublicValidation, correct: np.ndarray, majority: np.ndarray, present: np.ndarray) -> list | None:
|
|
200
|
+
differences = _means(correct.astype(int) - majority.astype(int), present)
|
|
201
|
+
return _interval(differences, draws=5000, seed=int(_rank(SEED, data.fingerprint)[:8], 16), tail=0.025)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _score(data: PublicValidation, model: PopulationAdjustedTwin, fitted: dict) -> tuple[dict, list[np.ndarray], np.ndarray]:
|
|
205
|
+
if fitted["data_fingerprint"] != data.fingerprint or fitted["protocol"] != SEED:
|
|
206
|
+
raise ValueError("Development artifact does not match the held-out protocol.")
|
|
207
|
+
setting = (fitted["neighbors"], fitted["personal_weight"])
|
|
208
|
+
if setting not in GRID:
|
|
209
|
+
raise ValueError("Frozen model is outside the registered grid.")
|
|
210
|
+
people = data.sealed
|
|
211
|
+
early = _choices(data, people, data.questions, data.earlier)
|
|
212
|
+
truth = _choices(data, people, data.questions, data.later)
|
|
213
|
+
present = (truth >= 0) & (early >= 0)
|
|
214
|
+
cached = model.forecast(people, {setting[0]} - {0})
|
|
215
|
+
distributions = model.blend(cached, setting, len(people))
|
|
216
|
+
correct, confidence, _ = _case_predictions(distributions, truth)
|
|
217
|
+
majority, _, _ = _case_predictions(model.blend({}, (0, 0.0), len(people)), truth)
|
|
218
|
+
shuffled = model.forecast(people, {setting[0]} - {0}, shuffle=True)
|
|
219
|
+
shuffled_correct, _, _ = _case_predictions(model.blend(shuffled, setting, len(people)), truth)
|
|
220
|
+
rank = _ranking(confidence, present, people, data.questions)
|
|
221
|
+
numeric_cutoff, tie_cutoff = fitted["operating_cutoff"]
|
|
222
|
+
operating = [ij for ij in rank if confidence[ij] > numeric_cutoff or (
|
|
223
|
+
confidence[ij] == numeric_cutoff and _rank(SEED, people[ij[0]], data.questions[ij[1]]) <= tie_cutoff
|
|
224
|
+
)]
|
|
225
|
+
curve = {}
|
|
226
|
+
for fraction in (0.1, 0.25, 0.5):
|
|
227
|
+
retained = rank[:max(1, round(len(rank) * fraction))]
|
|
228
|
+
curve[str(fraction)] = {"accuracy": fmean(bool(correct[ij]) for ij in retained),
|
|
229
|
+
"majority_accuracy_on_same_cases": fmean(bool(majority[ij]) for ij in retained)}
|
|
230
|
+
interval = _bound(data, correct, majority, present)
|
|
231
|
+
model_score = fmean(_means(correct, present))
|
|
232
|
+
majority_score = fmean(_means(majority, present))
|
|
233
|
+
calibrated = np.asarray(fitted["calibrated_bins"])[np.minimum(9, (confidence[present] * 10).astype(int))]
|
|
234
|
+
oracle_dist = [
|
|
235
|
+
np.eye(len(data.items[column].options))[np.maximum(truth[:, j], 0)]
|
|
236
|
+
for j, column in enumerate(data.questions)
|
|
237
|
+
]
|
|
238
|
+
oracle_correct, _, _ = _case_predictions(oracle_dist, truth)
|
|
239
|
+
return ({
|
|
240
|
+
"participants": len(people), "paired_answers": len(rank),
|
|
241
|
+
"oracle_accuracy": fmean(_means(oracle_correct, present)),
|
|
242
|
+
"copy_earlier_answer_accuracy": fmean(_means(early == truth, present)),
|
|
243
|
+
"majority_accuracy": majority_score, "personal_accuracy": model_score,
|
|
244
|
+
"shuffled_history_accuracy": fmean(_means(shuffled_correct, present)),
|
|
245
|
+
"paired_bootstrap_95pct": interval,
|
|
246
|
+
"clears_predictive_gate": bool(interval and interval[0] > 0 and model_score - majority_score >= 0.03),
|
|
247
|
+
"confidence_roc_auc": _roc_auc(confidence[present], correct[present]),
|
|
248
|
+
"confidence_deciles": np.quantile(confidence[present], np.arange(11) / 10).tolist(),
|
|
249
|
+
"raw_ece": compute_ece(confidence[present].tolist(), correct[present].tolist()),
|
|
250
|
+
"calibrated_ece": compute_ece(calibrated.tolist(), correct[present].tolist()),
|
|
251
|
+
"risk_coverage": curve,
|
|
252
|
+
"by_question_family": {
|
|
253
|
+
family: {"cases": int(mask.sum()), "personal_accuracy": fmean(_means(correct, mask)),
|
|
254
|
+
"majority_accuracy": fmean(_means(majority, mask))}
|
|
255
|
+
for family, columns in (
|
|
256
|
+
("product_pricing", [column.startswith("QID9_") for column in data.questions]),
|
|
257
|
+
("other_single_select", [not column.startswith("QID9_") for column in data.questions]),
|
|
258
|
+
)
|
|
259
|
+
if (mask := present & np.asarray(columns)).any()
|
|
260
|
+
},
|
|
261
|
+
"frozen_gate": {"coverage": len(operating) / len(rank), "accuracy":
|
|
262
|
+
fmean(bool(correct[ij]) for ij in operating) if operating else None},
|
|
263
|
+
}, distributions, present)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _cohort(data: PublicValidation, folder: Path, model: PopulationAdjustedTwin,
|
|
267
|
+
distributions: list[np.ndarray], present: np.ndarray, oracle: ResearchCohortOracle) -> dict:
|
|
268
|
+
people = data.sealed
|
|
269
|
+
early = _choices(data, people, data.questions, data.earlier)
|
|
270
|
+
late = _choices(data, people, data.questions, data.later)
|
|
271
|
+
mapping = {row["catalog_csv_column"]: row["formatted_column"] for row in
|
|
272
|
+
json.loads((folder / "wave4_formatted_to_catalog_mapping.json").read_text(encoding="utf-8-sig"))}
|
|
273
|
+
published = _reference_rows(folder / "responses_llm_imputed_formatted.csv")
|
|
274
|
+
published_human = _reference_rows(folder / "responses_wave4_formatted.csv")
|
|
275
|
+
metrics = {}
|
|
276
|
+
for j, column in enumerate(data.questions):
|
|
277
|
+
item = data.items[column]
|
|
278
|
+
indexes = {option.option_id: i for i, option in enumerate(item.options)}
|
|
279
|
+
selected = [i for i in np.flatnonzero(present[:, j]) if (
|
|
280
|
+
column in mapping and people[i] in published and people[i] in published_human
|
|
281
|
+
and item.answer({column: published_human[people[i]].get(mapping[column], "")})
|
|
282
|
+
== item.options[late[i, j]].option_id
|
|
283
|
+
and item.answer({column: published[people[i]].get(mapping[column], "")}) is not None
|
|
284
|
+
)]
|
|
285
|
+
if len(selected) < 4:
|
|
286
|
+
continue
|
|
287
|
+
formatted = mapping[column]
|
|
288
|
+
published_codes = [indexes[item.answer({column: published[people[i]][formatted]})] for i in selected]
|
|
289
|
+
size = len(item.options)
|
|
290
|
+
def mass(codes) -> np.ndarray:
|
|
291
|
+
return np.bincount(codes, minlength=size) / len(codes)
|
|
292
|
+
|
|
293
|
+
observed = mass(late[selected, j])
|
|
294
|
+
profile = CohortProfile(
|
|
295
|
+
cohort_id=column, name="Earlier-wave reference sample", domain="survey", population_weighted=True,
|
|
296
|
+
archetypes=[
|
|
297
|
+
CohortArchetype(
|
|
298
|
+
archetype_id=f"group-{index}", label="Reference sample", weight=0.5,
|
|
299
|
+
prior_tendencies=dict(zip(indexes, model.priors[j])),
|
|
300
|
+
)
|
|
301
|
+
for index in range(2)
|
|
302
|
+
],
|
|
303
|
+
)
|
|
304
|
+
oracle.register_cohort(profile)
|
|
305
|
+
simulation = oracle.simulate(CohortQuery(
|
|
306
|
+
cohort_id=column, stimulus=item.text, options=list(item.options), sample_size=2000,
|
|
307
|
+
random_seed=int(_rank(SEED, column)[:8], 16), use_twin_priors=False,
|
|
308
|
+
))
|
|
309
|
+
forecasts = {
|
|
310
|
+
"population_prior": model.priors[j],
|
|
311
|
+
"population_adjusted_twin": distributions[j][selected].mean(axis=0),
|
|
312
|
+
"cohort_oracle": np.asarray([simulation.metrics.option_distribution[key] for key in indexes]),
|
|
313
|
+
"uniform": np.full(size, 1 / size),
|
|
314
|
+
"publisher_persona": mass(published_codes),
|
|
315
|
+
"early_vs_late_same_people": mass(early[selected, j]),
|
|
316
|
+
}
|
|
317
|
+
halves = sorted(selected, key=lambda i: _rank(SEED, "noise", column, people[i]))
|
|
318
|
+
noise_left, noise_right = mass(late[halves[::2], j]), mass(late[halves[1::2], j])
|
|
319
|
+
metrics.setdefault("same_wave_split_half", []).append(_cohort_values(noise_left, noise_right))
|
|
320
|
+
for name, predicted in forecasts.items():
|
|
321
|
+
metrics.setdefault(name, []).append(_cohort_values(observed, predicted))
|
|
322
|
+
return {
|
|
323
|
+
name: {"mean_jsd": fmean(row[0] for row in rows),
|
|
324
|
+
"minority_precision": sum(row[1] for row in rows) / sum(row[2] for row in rows)
|
|
325
|
+
if sum(row[2] for row in rows) else None,
|
|
326
|
+
"minority_recall": sum(row[1] for row in rows) / sum(row[3] for row in rows)
|
|
327
|
+
if sum(row[3] for row in rows) else None,
|
|
328
|
+
"questions": len(rows)}
|
|
329
|
+
for name, rows in metrics.items()
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _cohort_values(observed: np.ndarray, predicted: np.ndarray) -> tuple:
|
|
334
|
+
# A 1% floor suppresses numerical dust. A forecast must call an option
|
|
335
|
+
# a minority (1% to <10%) before it earns credit for recovering it.
|
|
336
|
+
truth = (observed >= 0.01) & (observed < 0.10)
|
|
337
|
+
calls = (predicted >= 0.01) & (predicted < 0.10)
|
|
338
|
+
return (jensen_shannon_divergence(dict(enumerate(observed)), dict(enumerate(predicted))),
|
|
339
|
+
int((truth & calls).sum()), int(calls.sum()), int(truth.sum()))
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def run_public_validation(folder: Path, original_report: Path, frozen: Path, *, phase: str) -> dict:
|
|
343
|
+
data = load_public_validation(folder, original_report)
|
|
344
|
+
model = PopulationAdjustedTwin(data)
|
|
345
|
+
if phase == "development":
|
|
346
|
+
outcome = _stage_fit(data, model)
|
|
347
|
+
with frozen.open("x", encoding="utf-8") as file:
|
|
348
|
+
file.write(json.dumps(outcome, indent=2) + "\n")
|
|
349
|
+
return outcome
|
|
350
|
+
if phase != "sealed":
|
|
351
|
+
raise ValueError("Use the development or sealed phase.")
|
|
352
|
+
fitted = json.loads(frozen.read_text(encoding="utf-8"))
|
|
353
|
+
results, distributions, present = _score(data, model, fitted)
|
|
354
|
+
with tempfile.TemporaryDirectory(prefix="anthromesh-cohort-validation-") as temporary:
|
|
355
|
+
oracle = ResearchCohortOracle(BehavioralVault(str(Path(temporary) / "cohort.db")), HeuristicAdapter())
|
|
356
|
+
cohort = _cohort(data, folder, model, distributions, present, oracle)
|
|
357
|
+
return {"protocol": SEED, "development_artifact_sha256": hashlib.sha256(frozen.read_bytes()).hexdigest(),
|
|
358
|
+
"frozen_settings": fitted, "sealed_validation": results,
|
|
359
|
+
"cohort": cohort}
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def audit_original_public_run(folder: Path, original_report: Path) -> dict:
|
|
363
|
+
data = load_public_validation(folder, original_report)
|
|
364
|
+
retriever = HybridDecisionRetriever()
|
|
365
|
+
adapter = HeuristicAdapter()
|
|
366
|
+
people = data.exploratory
|
|
367
|
+
source_people = sorted(people, key=lambda pid: _rank(SEED, "original-shuffle", pid))
|
|
368
|
+
histories = {}
|
|
369
|
+
for pid in people:
|
|
370
|
+
histories[pid] = []
|
|
371
|
+
for column in data.features:
|
|
372
|
+
item = data.items[column]
|
|
373
|
+
choice = item.answer(data.earlier[pid])
|
|
374
|
+
if choice is not None:
|
|
375
|
+
histories[pid].append(DecisionLog(
|
|
376
|
+
decision_id=f"{pid}:{column}", subject_id=pid, domain="survey", context=item.text,
|
|
377
|
+
options_considered=list(item.options), chosen_action=choice,
|
|
378
|
+
rationale=next(option.label for option in item.options if option.option_id == choice),
|
|
379
|
+
created_at="2025-01-01T00:00:00+00:00",
|
|
380
|
+
))
|
|
381
|
+
cases = defaultdict(list)
|
|
382
|
+
mapping = {row["catalog_csv_column"]: row["formatted_column"] for row in
|
|
383
|
+
json.loads((folder / "wave4_formatted_to_catalog_mapping.json").read_text(encoding="utf-8-sig"))}
|
|
384
|
+
formatted = _reference_rows(folder / "responses_wave4_formatted.csv")
|
|
385
|
+
labeled = {}
|
|
386
|
+
for wave, name in (("earlier", "wave1_3_response_label.csv"), ("later", "wave4_response_label.csv")):
|
|
387
|
+
path = folder / name
|
|
388
|
+
if path.is_file():
|
|
389
|
+
labeled[wave] = _table(path)[1]
|
|
390
|
+
verified_labels = Counter()
|
|
391
|
+
for pid, shuffled_pid in zip(people, source_people):
|
|
392
|
+
for column in data.questions:
|
|
393
|
+
item = data.items[column]
|
|
394
|
+
actual = item.answer(data.later[pid])
|
|
395
|
+
early = item.answer(data.earlier[pid])
|
|
396
|
+
if actual is None or early is None:
|
|
397
|
+
continue
|
|
398
|
+
options = [option.option_id for option in item.options]
|
|
399
|
+
reference = item.answer({column: formatted[pid][mapping[column]]})
|
|
400
|
+
if actual != reference:
|
|
401
|
+
raise ValueError(f"Official response alignment failed for {column}.")
|
|
402
|
+
for wave, code in (("earlier", early), ("later", actual)):
|
|
403
|
+
if wave in labeled:
|
|
404
|
+
expected_label = item.options[options.index(code)].label
|
|
405
|
+
if _normalized_label(labeled[wave][pid][column]) != _normalized_label(expected_label):
|
|
406
|
+
raise ValueError(f"Official {wave} text label does not match the code for {column}.")
|
|
407
|
+
verified_labels[wave] += 1
|
|
408
|
+
query = _query(pid, item)
|
|
409
|
+
original = adapter.predict_decision(query, retriever.retrieve(query, histories[pid]))
|
|
410
|
+
shuffled = adapter.predict_decision(query, retriever.retrieve(query, histories[shuffled_pid]))
|
|
411
|
+
cases[pid].append((options.index(actual), original.chosen_option == actual,
|
|
412
|
+
shuffled.chosen_option == actual, early == actual))
|
|
413
|
+
# Feed one-hot ground truth through the same argmax scorer as sealed forecasts.
|
|
414
|
+
oracle_cases = [row[0] for rows in cases.values() for row in rows]
|
|
415
|
+
oracle_truth = np.asarray(oracle_cases).reshape(-1, 1)
|
|
416
|
+
oracle_scored, _, _ = _case_predictions([np.eye(max(oracle_cases) + 1)[oracle_cases]], oracle_truth)
|
|
417
|
+
rows = [row for participant_rows in cases.values() for row in participant_rows]
|
|
418
|
+
expected = json.loads(original_report.read_text(encoding="utf-8-sig"))["paired_evaluation_answers"]
|
|
419
|
+
if len(rows) != expected or not oracle_scored.all():
|
|
420
|
+
raise ValueError("Original case reconstruction or score oracle failed.")
|
|
421
|
+
return {
|
|
422
|
+
"cases": len(rows), "participants": len(cases), "oracle_accuracy": float(oracle_scored.mean()),
|
|
423
|
+
"matched_official_human_codes": len(rows), "question_type": "single_select",
|
|
424
|
+
"verified_text_labels": dict(verified_labels),
|
|
425
|
+
"deterministic_heuristic_replay_accuracy": fmean(row[1] for row in rows),
|
|
426
|
+
"shuffled_history_accuracy": fmean(row[2] for row in rows),
|
|
427
|
+
"copy_earlier_answer_accuracy": fmean(row[3] for row in rows),
|
|
428
|
+
"paired_participant_bootstrap_95pct_linked_minus_shuffled": _interval(
|
|
429
|
+
[fmean(int(row[1]) - int(row[2]) for row in participant_rows)
|
|
430
|
+
for participant_rows in cases.values()], draws=5000, seed=20261123, tail=0.025,
|
|
431
|
+
),
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
def _normalized_label(value: str) -> str:
|
|
435
|
+
return " ".join(unicodedata.normalize("NFKC", html.unescape(value)).split()).casefold()
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import tempfile
|
|
6
|
+
from collections import Counter, defaultdict
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
10
|
+
|
|
11
|
+
from anthromesh.adapters.base import BaseModelAdapter, StructuredPrediction, extract_json_object
|
|
12
|
+
from anthromesh.gate.conformal import CalibrationProfile, ConformalCalibration, normalize_scores
|
|
13
|
+
from anthromesh.gate.engine import ConfidenceGateEngine
|
|
14
|
+
from anthromesh.models import GateAction, QueryContext
|
|
15
|
+
from anthromesh.vault.policy_engine import PolicyEngine
|
|
16
|
+
from anthromesh.vault.storage import BehavioralVault
|
|
17
|
+
|
|
18
|
+
from .study import Registration, StudyCase, StudyDataset, prepare_study
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
SYSTEMS = ("twin", "ungated_rag", "persona", "population_majority")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Forecast(BaseModel):
|
|
25
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
26
|
+
|
|
27
|
+
participant_id: str
|
|
28
|
+
case_id: str
|
|
29
|
+
system: str
|
|
30
|
+
predicted_action: str | None
|
|
31
|
+
confidence: float = Field(ge=0, le=1)
|
|
32
|
+
escalated: bool
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ForecastRun(BaseModel):
|
|
36
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
37
|
+
|
|
38
|
+
plan_hash: str
|
|
39
|
+
dataset_hash: str
|
|
40
|
+
backend: str
|
|
41
|
+
forecasts: list[Forecast]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def load_dataset(path: Path) -> tuple[StudyDataset, str]:
|
|
45
|
+
raw = path.read_bytes()
|
|
46
|
+
return StudyDataset.model_validate_json(raw), hashlib.sha256(raw).hexdigest()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _valid_choice(prediction: StructuredPrediction, case: StudyCase) -> str | None:
|
|
50
|
+
if prediction.chosen_option not in case.option_ids():
|
|
51
|
+
return None
|
|
52
|
+
if prediction.raw_text:
|
|
53
|
+
try:
|
|
54
|
+
original = extract_json_object(prediction.raw_text).get("chosen_option")
|
|
55
|
+
if original not in case.option_ids() or original != prediction.chosen_option:
|
|
56
|
+
return None
|
|
57
|
+
except (TypeError, ValueError, AttributeError):
|
|
58
|
+
return None
|
|
59
|
+
return prediction.chosen_option
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _RecordedPredictor:
|
|
63
|
+
"""Replay one already-recorded prediction through the production gate."""
|
|
64
|
+
def __init__(self, adapter: BaseModelAdapter) -> None:
|
|
65
|
+
self.adapter_name = adapter.adapter_name
|
|
66
|
+
self.model = adapter.model
|
|
67
|
+
self.query_id: str | None = None
|
|
68
|
+
self.prediction: StructuredPrediction | None = None
|
|
69
|
+
|
|
70
|
+
def predict_decision(self, query: QueryContext, evidence):
|
|
71
|
+
if query.query_id != self.query_id or self.prediction is None:
|
|
72
|
+
raise ValueError("Replay prediction does not match the requested case.")
|
|
73
|
+
return self.prediction
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _population_choice(case: StudyCase, items: list[StudyCase]) -> tuple[str | None, float]:
|
|
77
|
+
votes = defaultdict(Counter)
|
|
78
|
+
for item in items:
|
|
79
|
+
if (item.participant_id != case.participant_id and item.recorded_at < case.recorded_at
|
|
80
|
+
and item.option_ids() == case.option_ids()):
|
|
81
|
+
votes[item.participant_id][item.chosen_action] += 1
|
|
82
|
+
if not votes:
|
|
83
|
+
return None, 0
|
|
84
|
+
mass = defaultdict(float)
|
|
85
|
+
for counts in votes.values():
|
|
86
|
+
total = sum(counts.values())
|
|
87
|
+
for option, count in counts.items():
|
|
88
|
+
mass[option] += count / total
|
|
89
|
+
chosen = min(mass, key=lambda option: (-mass[option], option))
|
|
90
|
+
return chosen, mass[chosen] / len(votes)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def forecast_study(
|
|
94
|
+
registration: Registration, dataset_path: Path, adapter: BaseModelAdapter,
|
|
95
|
+
destination: Path, *, allow_remote: bool = False, remote_backend: bool = False,
|
|
96
|
+
vault_key: str | None = None,
|
|
97
|
+
) -> ForecastRun:
|
|
98
|
+
if destination.exists():
|
|
99
|
+
raise FileExistsError(destination)
|
|
100
|
+
plan = registration.plan
|
|
101
|
+
dataset, digest = load_dataset(dataset_path)
|
|
102
|
+
prepared = prepare_study(registration, dataset)
|
|
103
|
+
backend = f"{adapter.adapter_name}:{adapter.model}"
|
|
104
|
+
if backend not in plan.backends:
|
|
105
|
+
raise ValueError("The configured model is absent from the registered plan.")
|
|
106
|
+
if remote_backend and not allow_remote:
|
|
107
|
+
raise ValueError("Enable explicit remote inference for a participant-approved backend.")
|
|
108
|
+
if plan.purpose == "confirmatory":
|
|
109
|
+
if adapter.adapter_name == "heuristic":
|
|
110
|
+
raise ValueError("The deterministic rehearsal adapter does not qualify for confirmatory evaluation.")
|
|
111
|
+
if not vault_key:
|
|
112
|
+
raise ValueError("Confirmatory replay requires ANTHROMESH_VAULT_KEY for the temporary vault.")
|
|
113
|
+
if any(not record.persona.strip() for record in prepared.participants.values()):
|
|
114
|
+
raise ValueError("Every confirmatory participant needs a short contemporaneous persona.")
|
|
115
|
+
forecast_rows = []
|
|
116
|
+
train_by_domain = defaultdict(list)
|
|
117
|
+
trained = defaultdict(list)
|
|
118
|
+
for case in prepared.train:
|
|
119
|
+
train_by_domain[case.domain].append(case)
|
|
120
|
+
trained[(case.participant_id, case.domain)].append(case.as_decision())
|
|
121
|
+
with tempfile.TemporaryDirectory(prefix="anthromesh-study-") as temporary:
|
|
122
|
+
vault = BehavioralVault(str(Path(temporary) / "replay.db"), encryption_key=vault_key)
|
|
123
|
+
for records in trained.values():
|
|
124
|
+
for record in records:
|
|
125
|
+
vault.add_decision(record)
|
|
126
|
+
replay = _RecordedPredictor(adapter)
|
|
127
|
+
gate = ConfidenceGateEngine(vault, PolicyEngine(), replay)
|
|
128
|
+
calibration = defaultdict(list)
|
|
129
|
+
for case in prepared.calibration:
|
|
130
|
+
query = case.query()
|
|
131
|
+
evidence, _ = gate.select_evidence(query, trained[(case.participant_id, case.domain)][-500:])
|
|
132
|
+
model_output = adapter.predict_decision(query, evidence)
|
|
133
|
+
probabilities = normalize_scores(model_output.option_scores, case.option_ids())
|
|
134
|
+
choice = _valid_choice(model_output, case)
|
|
135
|
+
calibration[(case.participant_id, case.domain)].append(
|
|
136
|
+
1 - probabilities.get(case.chosen_action, 0) if choice is not None else 1.0
|
|
137
|
+
)
|
|
138
|
+
gate.conformal = ConformalCalibration(
|
|
139
|
+
CalibrationProfile(subject_id=person, domain=domain, adapter=adapter.adapter_name,
|
|
140
|
+
model=adapter.model, alpha=plan.alpha, scores=scores)
|
|
141
|
+
for (person, domain), scores in calibration.items()
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
for case in prepared.test:
|
|
145
|
+
query = case.query()
|
|
146
|
+
evidence, _ = gate.select_evidence(query, trained[(case.participant_id, case.domain)][-500:])
|
|
147
|
+
rag = adapter.predict_decision(query, evidence)
|
|
148
|
+
raw_choice = _valid_choice(rag, case)
|
|
149
|
+
replay.query_id, replay.prediction = query.query_id, rag
|
|
150
|
+
if raw_choice is not None:
|
|
151
|
+
result = gate.evaluate(query)
|
|
152
|
+
twin_choice, confidence, escalated = raw_choice, result.confidence, result.action != GateAction.APPROVED
|
|
153
|
+
else:
|
|
154
|
+
twin_choice, confidence, escalated = None, 0, True
|
|
155
|
+
persona = adapter.predict_persona(query, prepared.participants[case.participant_id].persona)
|
|
156
|
+
majority, majority_confidence = _population_choice(case, train_by_domain[case.domain])
|
|
157
|
+
if plan.purpose == "confirmatory" and majority is None:
|
|
158
|
+
raise ValueError("A confirmatory test case has no prior cross-participant majority baseline.")
|
|
159
|
+
for system, chosen, certainty, hold in (
|
|
160
|
+
("twin", twin_choice, confidence, escalated),
|
|
161
|
+
("ungated_rag", raw_choice, rag.self_reported_confidence, False),
|
|
162
|
+
("persona", _valid_choice(persona, case), persona.self_reported_confidence, False),
|
|
163
|
+
("population_majority", majority, majority_confidence, False),
|
|
164
|
+
):
|
|
165
|
+
forecast_rows.append(Forecast(
|
|
166
|
+
participant_id=case.participant_id, case_id=case.case_id, system=system,
|
|
167
|
+
predicted_action=chosen, confidence=certainty, escalated=hold,
|
|
168
|
+
))
|
|
169
|
+
|
|
170
|
+
report = ForecastRun(plan_hash=registration.plan_hash, dataset_hash=digest, backend=backend,
|
|
171
|
+
forecasts=forecast_rows)
|
|
172
|
+
with destination.open("x", encoding="utf-8") as output:
|
|
173
|
+
output.write(report.model_dump_json(indent=2) + "\n")
|
|
174
|
+
return report
|