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.
Files changed (73) hide show
  1. anthromesh/__init__.py +3 -0
  2. anthromesh/adapters/__init__.py +18 -0
  3. anthromesh/adapters/base.py +218 -0
  4. anthromesh/adapters/cloud.py +151 -0
  5. anthromesh/adapters/factory.py +31 -0
  6. anthromesh/adapters/heuristic.py +113 -0
  7. anthromesh/adapters/local.py +91 -0
  8. anthromesh/benchmarks/__init__.py +3 -0
  9. anthromesh/benchmarks/datasets.py +207 -0
  10. anthromesh/benchmarks/empirical.py +176 -0
  11. anthromesh/benchmarks/panel_cohort.py +67 -0
  12. anthromesh/benchmarks/public_twin.py +414 -0
  13. anthromesh/benchmarks/public_validation.py +435 -0
  14. anthromesh/benchmarks/replay.py +174 -0
  15. anthromesh/benchmarks/runner.py +140 -0
  16. anthromesh/benchmarks/study.py +245 -0
  17. anthromesh/benchmarks/study_report.py +170 -0
  18. anthromesh/capture/__init__.py +1 -0
  19. anthromesh/capture/github_webhook.py +51 -0
  20. anthromesh/capture/graph.py +221 -0
  21. anthromesh/capture/workflows.py +70 -0
  22. anthromesh/cli.py +807 -0
  23. anthromesh/client.py +96 -0
  24. anthromesh/cohort/__init__.py +3 -0
  25. anthromesh/cohort/categorical_anchor.py +240 -0
  26. anthromesh/cohort/clustering.py +93 -0
  27. anthromesh/cohort/human_anchor.py +92 -0
  28. anthromesh/cohort/ingest.py +104 -0
  29. anthromesh/cohort/oracle.py +153 -0
  30. anthromesh/cohort/twin_priors.py +118 -0
  31. anthromesh/config.py +48 -0
  32. anthromesh/gate/__init__.py +15 -0
  33. anthromesh/gate/calibration.py +95 -0
  34. anthromesh/gate/conformal.py +73 -0
  35. anthromesh/gate/engine.py +293 -0
  36. anthromesh/gate/fast.py +62 -0
  37. anthromesh/gate/fit.py +56 -0
  38. anthromesh/judgment/__init__.py +1 -0
  39. anthromesh/judgment/elicitation.py +206 -0
  40. anthromesh/judgment/monitor.py +128 -0
  41. anthromesh/judgment/panel.py +389 -0
  42. anthromesh/judgment/settings.py +41 -0
  43. anthromesh/models/__init__.py +39 -0
  44. anthromesh/models/cohort.py +76 -0
  45. anthromesh/models/decision.py +81 -0
  46. anthromesh/models/escalation.py +70 -0
  47. anthromesh/models/policy.py +41 -0
  48. anthromesh/models/validity.py +17 -0
  49. anthromesh/protocols/__init__.py +4 -0
  50. anthromesh/protocols/a2a_server.py +414 -0
  51. anthromesh/protocols/capabilities.py +52 -0
  52. anthromesh/protocols/delegation.py +373 -0
  53. anthromesh/protocols/mcp_server.py +500 -0
  54. anthromesh/protocols/oauth.py +177 -0
  55. anthromesh/ros_gate.py +141 -0
  56. anthromesh/twin/__init__.py +3 -0
  57. anthromesh/twin/engine.py +116 -0
  58. anthromesh/twin/inbox.py +221 -0
  59. anthromesh/vault/__init__.py +5 -0
  60. anthromesh/vault/dense.py +171 -0
  61. anthromesh/vault/encryption.py +50 -0
  62. anthromesh/vault/policy_engine.py +123 -0
  63. anthromesh/vault/postgres.py +92 -0
  64. anthromesh/vault/privacy.py +264 -0
  65. anthromesh/vault/retrieval.py +135 -0
  66. anthromesh/vault/storage.py +937 -0
  67. anthromesh-0.2.0.dist-info/METADATA +493 -0
  68. anthromesh-0.2.0.dist-info/RECORD +73 -0
  69. anthromesh-0.2.0.dist-info/WHEEL +5 -0
  70. anthromesh-0.2.0.dist-info/entry_points.txt +2 -0
  71. anthromesh-0.2.0.dist-info/licenses/LICENSE +201 -0
  72. anthromesh-0.2.0.dist-info/licenses/NOTICE +2 -0
  73. anthromesh-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,207 @@
1
+ from __future__ import annotations
2
+
3
+ from anthromesh.models import (
4
+ CandidateOption,
5
+ CohortArchetype,
6
+ CohortProfile,
7
+ DecisionLog,
8
+ QueryContext,
9
+ RiskTier,
10
+ )
11
+
12
+
13
+ def build_twin_benchmark_suite() -> tuple[list[DecisionLog], list[tuple[QueryContext, str, bool]]]:
14
+ opts_pr = [
15
+ CandidateOption(option_id="request_changes", label="Request Changes", description="Block merge until tests and verification pass"),
16
+ CandidateOption(option_id="approve_with_nits", label="Approve with Nits", description="Approve PR with minor follow-up comments"),
17
+ CandidateOption(option_id="merge_immediately", label="Merge Immediately", description="Fast-track merge without extra checks"),
18
+ ]
19
+ opts_cal = [
20
+ CandidateOption(option_id="decline_async", label="Decline & Go Async", description="Convert status meeting into a written update"),
21
+ CandidateOption(option_id="accept_meeting", label="Accept Meeting", description="Attend live synchronous call"),
22
+ CandidateOption(option_id="propose_15min", label="Propose 15-Min Huddle", description="Shorten meeting to focused 15 minutes"),
23
+ ]
24
+ opts_contract = [
25
+ CandidateOption(option_id="sign_standard", label="Sign Standard Terms", description="Accept vendor agreement as written"),
26
+ CandidateOption(option_id="redline_ip", label="Redline IP Clause", description="Negotiate intellectual property ownership"),
27
+ CandidateOption(option_id="reject_vendor", label="Reject Vendor", description="Walk away from vendor"),
28
+ ]
29
+
30
+ history = [
31
+ DecisionLog(
32
+ decision_id="hist_pr_01",
33
+ subject_id="user_alex",
34
+ domain="code_review",
35
+ context="PR modifies numerical solver convergence loop without unit tests or regression benchmarks.",
36
+ options_considered=opts_pr,
37
+ chosen_action="request_changes",
38
+ rationale="Never merge numerical or core logic changes without deterministic regression tests.",
39
+ risk_tier=RiskTier.MEDIUM,
40
+ tags=["verification", "testing"],
41
+ ),
42
+ DecisionLog(
43
+ decision_id="hist_pr_02",
44
+ subject_id="user_alex",
45
+ domain="code_review",
46
+ context="PR updates physics kernel boundary condition and skips integration test suite.",
47
+ options_considered=opts_pr,
48
+ chosen_action="request_changes",
49
+ rationale="Missing integration tests on boundary conditions is a hard blocker.",
50
+ risk_tier=RiskTier.MEDIUM,
51
+ tags=["verification", "testing"],
52
+ ),
53
+ DecisionLog(
54
+ decision_id="hist_pr_03",
55
+ subject_id="user_alex",
56
+ domain="code_review",
57
+ context="PR fixes typo in README documentation and updates badge URL, all CI checks green.",
58
+ options_considered=opts_pr,
59
+ chosen_action="approve_with_nits",
60
+ rationale="Low-risk doc fix with passing CI does not need blocking.",
61
+ risk_tier=RiskTier.LOW,
62
+ tags=["docs", "low_risk"],
63
+ ),
64
+ DecisionLog(
65
+ decision_id="hist_cal_01",
66
+ subject_id="user_alex",
67
+ domain="calendar",
68
+ context="Recurring 60-minute weekly status sync with no agenda during deep-work morning block.",
69
+ options_considered=opts_cal,
70
+ chosen_action="decline_async",
71
+ rationale="Protect deep-work mornings; status updates belong in async docs.",
72
+ risk_tier=RiskTier.LOW,
73
+ tags=["deep_work", "async"],
74
+ ),
75
+ DecisionLog(
76
+ decision_id="hist_cal_02",
77
+ subject_id="user_alex",
78
+ domain="calendar",
79
+ context="One-hour project status check-in during morning focus hours with no decision items.",
80
+ options_considered=opts_cal,
81
+ chosen_action="decline_async",
82
+ rationale="No agenda and no decisions required; request written summary instead.",
83
+ risk_tier=RiskTier.LOW,
84
+ tags=["deep_work", "async"],
85
+ ),
86
+ ]
87
+
88
+ eval_cases: list[tuple[QueryContext, str, bool]] = [
89
+ (
90
+ QueryContext(
91
+ subject_id="user_alex",
92
+ caller_agent="pr_bot",
93
+ domain="code_review",
94
+ context="PR refactors solver convergence loop and removes unit tests for speed.",
95
+ candidate_options=opts_pr,
96
+ risk_tier=RiskTier.LOW,
97
+ ),
98
+ "request_changes",
99
+ False,
100
+ ),
101
+ (
102
+ QueryContext(
103
+ subject_id="user_alex",
104
+ caller_agent="cal_bot",
105
+ domain="calendar",
106
+ context="60-minute weekly status sync with no agenda scheduled during morning deep-work block.",
107
+ candidate_options=opts_cal,
108
+ risk_tier=RiskTier.LOW,
109
+ ),
110
+ "decline_async",
111
+ False,
112
+ ),
113
+ (
114
+ QueryContext(
115
+ subject_id="user_alex",
116
+ caller_agent="legal_bot",
117
+ domain="legal_contracts",
118
+ context="Vendor MSA includes perpetual derivative IP license on fine-tuned weights.",
119
+ candidate_options=opts_contract,
120
+ risk_tier=RiskTier.HIGH,
121
+ ),
122
+ "redline_ip",
123
+ True,
124
+ ),
125
+ (
126
+ QueryContext(
127
+ subject_id="user_alex",
128
+ caller_agent="ops_bot",
129
+ domain="production_ops",
130
+ context="Database schema migration requires 15-minute downtime during peak customer traffic.",
131
+ candidate_options=[
132
+ CandidateOption(option_id="run_now", label="Run Now"),
133
+ CandidateOption(option_id="schedule_weekend", label="Schedule Weekend"),
134
+ ],
135
+ risk_tier=RiskTier.HIGH,
136
+ ),
137
+ "schedule_weekend",
138
+ True,
139
+ ),
140
+ ]
141
+ return history, eval_cases
142
+
143
+
144
+ def build_cohort_benchmark_suite() -> tuple[CohortProfile, list[CandidateOption], str, dict[str, float]]:
145
+ options = [
146
+ CandidateOption(option_id="adopt_now", label="Adopt Immediately", description="Deploy AI assistant broadly"),
147
+ CandidateOption(option_id="pilot_guarded", label="Guarded Pilot", description="Run limited sandbox with audit logs"),
148
+ CandidateOption(option_id="local_only", label="Local-Only Self-Hosted", description="Require air-gapped local models"),
149
+ CandidateOption(option_id="reject_ai", label="Reject Outright", description="Refuse AI integration due to trust/IP"),
150
+ ]
151
+
152
+ profile = CohortProfile(
153
+ cohort_id="enterprise_eng_leaders_v1",
154
+ name="Enterprise Engineering & Research Leaders",
155
+ description="Empirical cohort modeling technology adoption across mainstream and long-tail security-first archetypes.",
156
+ domain="ai_adoption",
157
+ archetypes=[
158
+ CohortArchetype(
159
+ archetype_id="pragmatic_evaluators",
160
+ label="Pragmatic Evaluators",
161
+ weight=0.45,
162
+ is_long_tail=False,
163
+ traits={"risk_appetite": "moderate", "priority": "ROI and auditability"},
164
+ prior_tendencies={"pilot_guarded": 0.68, "adopt_now": 0.18, "local_only": 0.12, "reject_ai": 0.02},
165
+ sample_rationales=["We need a bounded pilot with measurable accuracy before rolling out."],
166
+ ),
167
+ CohortArchetype(
168
+ archetype_id="velocity_optimists",
169
+ label="Velocity-First Builders",
170
+ weight=0.25,
171
+ is_long_tail=False,
172
+ traits={"risk_appetite": "high", "priority": "shipping speed"},
173
+ prior_tendencies={"adopt_now": 0.66, "pilot_guarded": 0.28, "local_only": 0.04, "reject_ai": 0.02},
174
+ sample_rationales=["Speed wins; adopt now and iterate on guardrails in production."],
175
+ ),
176
+ CohortArchetype(
177
+ archetype_id="sovereign_infra",
178
+ label="Local-First / Air-Gapped Architects",
179
+ weight=0.20,
180
+ is_long_tail=True,
181
+ traits={"risk_appetite": "low", "priority": "data sovereignty and local control"},
182
+ prior_tendencies={"local_only": 0.74, "pilot_guarded": 0.16, "reject_ai": 0.08, "adopt_now": 0.02},
183
+ sample_rationales=["Proprietary data cannot leave our perimeter; self-hosted local inference only."],
184
+ ),
185
+ CohortArchetype(
186
+ archetype_id="compliance_skeptics",
187
+ label="Strict Regulatory Skeptics",
188
+ weight=0.10,
189
+ is_long_tail=True,
190
+ traits={"risk_appetite": "minimal", "priority": "zero liability and IP protection"},
191
+ prior_tendencies={"reject_ai": 0.65, "local_only": 0.25, "pilot_guarded": 0.08, "adopt_now": 0.02},
192
+ sample_rationales=["Unproven behavioral liability outweighs productivity gains right now."],
193
+ ),
194
+ ],
195
+ )
196
+
197
+ ground_truth = {
198
+ "pilot_guarded": 0.416,
199
+ "adopt_now": 0.252,
200
+ "local_only": 0.237,
201
+ "reject_ai": 0.095,
202
+ }
203
+ stimulus = (
204
+ "Your organization is considering deploying an autonomous AI agent middleware that accesses "
205
+ "internal engineering decision logs to assist with code reviews and vendor evaluations."
206
+ )
207
+ return profile, options, stimulus, ground_truth
@@ -0,0 +1,176 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import random
6
+ from collections import defaultdict
7
+ from pathlib import Path
8
+ from statistics import fmean
9
+ from typing import Any
10
+
11
+ from pydantic import BaseModel, Field
12
+
13
+ from anthromesh.gate.calibration import compute_ece, jensen_shannon_divergence
14
+
15
+
16
+ class PersonalObservation(BaseModel):
17
+ backend: str
18
+ system: str
19
+ participant_id: str
20
+ case_id: str
21
+ expected_action: str
22
+ predicted_action: str
23
+ confidence: float = Field(ge=0, le=1)
24
+ escalated: bool
25
+ out_of_distribution: bool
26
+
27
+
28
+ class SurveyObservation(BaseModel):
29
+ backend: str
30
+ system: str
31
+ question_id: str
32
+ observed: dict[str, float]
33
+ predicted: dict[str, float]
34
+ ordered_options: list[str] | None = None
35
+
36
+
37
+ def _ratio(numerator: int, denominator: int) -> float | None:
38
+ return numerator / denominator if denominator else None
39
+
40
+
41
+ def _distribution(values: dict[str, float]) -> dict[str, float]:
42
+ total = sum(values.values())
43
+ if not math.isfinite(total) or total <= 0 or any(value < 0 for value in values.values()):
44
+ raise ValueError("Survey distributions require finite nonnegative mass and a positive total.")
45
+ return {key: value / total for key, value in values.items()}
46
+
47
+
48
+ def _personal(rows: list[PersonalObservation]) -> dict[str, Any]:
49
+ correct = [row.predicted_action == row.expected_action for row in rows]
50
+ accepted = sum(not row.escalated for row in rows)
51
+ escalated = len(rows) - accepted
52
+ tp = sum(row.escalated and row.out_of_distribution for row in rows)
53
+ false_positive = sum(row.escalated and not row.out_of_distribution for row in rows)
54
+ false_negative = sum(not row.escalated and row.out_of_distribution for row in rows)
55
+ return {
56
+ "observations": len(rows),
57
+ "participants": len({row.participant_id for row in rows}),
58
+ "selective_accuracy": _ratio(
59
+ sum(not row.escalated and ok for row, ok in zip(rows, correct)), accepted,
60
+ ),
61
+ "ood_escalation_f1": _ratio(2 * tp, 2 * tp + false_positive + false_negative),
62
+ "ece": compute_ece([row.confidence for row in rows], correct),
63
+ "escalation_rate": escalated / len(rows),
64
+ "avoided_errors": sum(row.escalated and not ok for row, ok in zip(rows, correct)),
65
+ }
66
+
67
+
68
+ def _survey(rows: list[SurveyObservation]) -> dict[str, Any]:
69
+ jsd = []
70
+ distances = []
71
+ entropy = []
72
+ recalled = total_tail = 0
73
+ for row in rows:
74
+ if set(row.observed) != set(row.predicted) or len(row.observed) < 2:
75
+ raise ValueError("Survey predictions and observations must declare the same options.")
76
+ observed, predicted = _distribution(row.observed), _distribution(row.predicted)
77
+ jsd.append(jensen_shannon_divergence(observed, predicted))
78
+ entropy.append(-sum(p * math.log2(p) for p in predicted.values() if p > 0)
79
+ / math.log2(len(predicted)))
80
+ tail = [key for key, p in observed.items() if 0 < p < 0.10]
81
+ total_tail += len(tail)
82
+ recalled += sum(predicted[key] >= 0.5 * observed[key] for key in tail)
83
+ if row.ordered_options is not None:
84
+ if set(row.ordered_options) != set(observed) or len(row.ordered_options) != len(observed):
85
+ raise ValueError("Ordered options must list every response exactly once.")
86
+ gap = distance = 0.0
87
+ for option in row.ordered_options[:-1]:
88
+ gap += observed[option] - predicted[option]
89
+ distance += abs(gap)
90
+ distances.append(distance)
91
+ return {
92
+ "questions": len(rows),
93
+ "mean_jsd": fmean(jsd),
94
+ "mean_ordinal_wasserstein": fmean(distances) if distances else None,
95
+ "ordinal_questions": len(distances),
96
+ "mean_normalized_entropy": fmean(entropy),
97
+ "long_tail_recall_at_half_observed_mass": _ratio(recalled, total_tail),
98
+ }
99
+
100
+
101
+ def _paired_improvement(
102
+ baseline: list[PersonalObservation | SurveyObservation],
103
+ candidate: list[PersonalObservation | SurveyObservation],
104
+ mode: str,
105
+ ) -> dict[str, Any]:
106
+ def key(row):
107
+ return ((row.participant_id, row.case_id) if mode == "personal" else (row.question_id,))
108
+
109
+ by_key = {key(row): row for row in baseline}
110
+ if set(by_key) != {key(row) for row in candidate}:
111
+ raise ValueError("Baseline and candidate must cover the same evaluation observations.")
112
+ clusters = defaultdict(list)
113
+ for row in candidate:
114
+ other = by_key[key(row)]
115
+ if mode == "personal":
116
+ if (row.expected_action, row.out_of_distribution) != (
117
+ other.expected_action, other.out_of_distribution,
118
+ ):
119
+ raise ValueError("Paired personal outcomes must use the same ground truth.")
120
+ elif row.observed != other.observed or row.ordered_options != other.ordered_options:
121
+ raise ValueError("Paired survey outcomes must use the same ground truth and ordering.")
122
+ clusters[key(row)[0]].append((other, row))
123
+
124
+ def reduction(pairs) -> float:
125
+ reference, evaluated = zip(*pairs)
126
+ if mode == "personal":
127
+ return _personal(reference)["ece"] - _personal(evaluated)["ece"]
128
+ return _survey(reference)["mean_jsd"] - _survey(evaluated)["mean_jsd"]
129
+
130
+ groups = list(clusters.values())
131
+ result = {
132
+ "metric": "ece" if mode == "personal" else "mean_jsd",
133
+ "baseline_minus_candidate": reduction([pair for group in groups for pair in group]),
134
+ "cluster_count": len(groups),
135
+ "confidence_interval_95": None,
136
+ }
137
+ if len(groups) >= 2:
138
+ rng = random.Random(42)
139
+ draws = sorted(
140
+ reduction([pair for group in rng.choices(groups, k=len(groups)) for pair in group])
141
+ for _ in range(1000)
142
+ )
143
+ result["confidence_interval_95"] = [draws[24], draws[974]]
144
+ return result
145
+
146
+
147
+ def score_study(path: Path, mode: str, baseline: str | None = None) -> list[dict[str, Any]]:
148
+ """Score independently collected observations without loading a model or uploading records."""
149
+ subjects = mode == "personal"
150
+ model = PersonalObservation if subjects else SurveyObservation
151
+ groups = defaultdict(list)
152
+ seen = set()
153
+ with path.open(encoding="utf-8") as stream:
154
+ for line in stream:
155
+ if not line.strip():
156
+ continue
157
+ row = model.model_validate(json.loads(line))
158
+ group = (row.backend, row.system)
159
+ observation = (row.participant_id, row.case_id) if subjects else (row.question_id,)
160
+ if (group, observation) in seen:
161
+ raise ValueError("Duplicate study prediction within a system and backend.")
162
+ seen.add((group, observation))
163
+ groups[group].append(row)
164
+ if not groups:
165
+ raise ValueError("Provide at least one study observation.")
166
+ summarize = _personal if subjects else _survey
167
+ result = []
168
+ for (backend, system), rows in sorted(groups.items()):
169
+ summary = {"backend": backend, "system": system, **summarize(rows)}
170
+ if baseline and system != baseline:
171
+ reference = groups.get((backend, baseline))
172
+ if not reference:
173
+ raise ValueError(f"Missing baseline {baseline!r} for backend {backend!r}.")
174
+ summary["paired_improvement"] = _paired_improvement(reference, rows, mode)
175
+ result.append(summary)
176
+ return result
@@ -0,0 +1,67 @@
1
+ from __future__ import annotations
2
+
3
+ from collections import defaultdict
4
+
5
+ from anthromesh.cohort.oracle import ResearchCohortOracle
6
+ from anthromesh.judgment.panel import HumanPanel
7
+ from anthromesh.models import CohortArchetype, CohortQuery
8
+
9
+ from .empirical import SurveyObservation, _paired_improvement, _survey
10
+
11
+
12
+ def evaluate_against_panel(
13
+ oracle: ResearchCohortOracle, cohort_id: str, question_ids: list[str], *, sample_size: int = 500,
14
+ ) -> dict:
15
+ if len(set(question_ids)) != len(question_ids) or not question_ids:
16
+ raise ValueError("Provide distinct, held-out panel question IDs.")
17
+ cohort = oracle.vault.get_cohort(cohort_id)
18
+ if cohort is None:
19
+ raise KeyError(cohort_id)
20
+ panel = HumanPanel(oracle.vault)
21
+ prepared = []
22
+ for identifier in question_ids:
23
+ question = panel.question(identifier)
24
+ if question.topic != cohort.domain or question.repeat_of:
25
+ raise ValueError("Use held-out non-repeated questions from the cohort's domain.")
26
+ observed = panel.report(identifier)
27
+ if observed["option_counts"] is None or observed["quality_reviewed_answers"] < question.answer_count:
28
+ raise ValueError("All requested panel responses must be reviewed before evaluation.")
29
+ prepared.append((question, observed["option_counts"]))
30
+
31
+ grouped = defaultdict(list)
32
+ twin_priors_used = []
33
+ backend = f"{oracle.adapter.adapter_name}:{oracle.adapter.model}"
34
+ for question, counts in prepared:
35
+ query = CohortQuery(
36
+ cohort_id=cohort_id, stimulus=question.stimulus, options=question.options,
37
+ sample_size=sample_size, caller_agent="panel_cohort_evaluation",
38
+ )
39
+ survey_only = oracle.simulate(query.model_copy(update={"use_twin_priors": False, "simulation_id": f"base-{query.simulation_id}"}))
40
+ integrated = oracle.simulate(query)
41
+ generic = oracle.adapter.simulate_cohort_archetype(
42
+ question.stimulus, question.options,
43
+ CohortArchetype(archetype_id="general", label="Typical respondent", weight=1),
44
+ )
45
+ if "consented_twin_aggregates" in integrated.prior_sources:
46
+ twin_priors_used.append(question.question_id)
47
+ persona = {option.option_id: generic.option_scores.get(option.option_id, 0.0)
48
+ for option in question.options}
49
+ for name, prediction in (
50
+ ("persona", persona),
51
+ ("survey_prior", survey_only.metrics.option_distribution),
52
+ ("consented_twin_prior", integrated.metrics.option_distribution),
53
+ ):
54
+ grouped[name].append(SurveyObservation(
55
+ backend=backend, system=name, question_id=question.question_id,
56
+ observed=counts, predicted=prediction,
57
+ ))
58
+ evaluations = {name: _survey(rows) for name, rows in grouped.items()}
59
+ for name in ("survey_prior", "consented_twin_prior"):
60
+ evaluations[name]["paired_improvement_over_persona"] = _paired_improvement(
61
+ grouped["persona"], grouped[name], "survey",
62
+ )
63
+ return {
64
+ "cohort_id": cohort_id, "backend": backend, "ground_truth_source": "human_panel",
65
+ "questions_using_consented_twin_priors": twin_priors_used,
66
+ "simulations": evaluations,
67
+ }