nkshirsa commited on
Commit
04f24fb
·
verified ·
1 Parent(s): 0c949ce

Add Epistemic Trigger Words validator (deterministic code-based epistemic classification alongside AI)

Browse files
phd_research_os_v2/layer2/trigger_validator.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Layer 2 + Layer 5: Epistemic Trigger Words Validator
3
+ ======================================================
4
+ Deterministic, code-based epistemic classification using linguistic patterns.
5
+ Runs ALONGSIDE the AI Council as a cross-check.
6
+
7
+ If the AI says "Fact" but trigger words say "Hypothesis" → flag for human review.
8
+
9
+ Adapted from: KGX3/iKuhn's language-game filters (arxiv:2002.03531)
10
+ Addresses blindspots: PA-5, B-4
11
+ Source: SYSTEM_INSPIRATIONS.md AD-3
12
+
13
+ No ML dependencies. Pure Python. Deterministic output.
14
+ """
15
+
16
+ import re
17
+ from typing import Optional
18
+
19
+
20
+ # ══════════════════════════════════════════════════════════════════════
21
+ # TRIGGER WORD DICTIONARIES
22
+ # ══════════════════════════════════════════════════════════════════════
23
+ # Weights: "strong" triggers score 0.30, "moderate" score 0.15, "weak" score 0.08
24
+ # Calibrated to KGX3's activation threshold θ=0.7
25
+
26
+ FACT_TRIGGERS = {
27
+ "strong": [
28
+ "demonstrated", "measured", "observed", "detected", "confirmed",
29
+ "showed that", "resulted in", "was found to be", "achieved",
30
+ "we report", "we found", "was determined to be", "are reported",
31
+ "the data show", "the results show", "statistically significant",
32
+ "p < ", "p = ", "p-value", "with a yield of", "with an efficiency of",
33
+ ],
34
+ "moderate": [
35
+ "correlated with", "associated with", "consistent with the finding",
36
+ "reproduces", "replicated", "validated", "verified",
37
+ "supported by the data", "the analysis revealed",
38
+ ],
39
+ "weak": [
40
+ "found", "obtained", "recorded", "documented", "established",
41
+ ],
42
+ }
43
+
44
+ INTERPRETATION_TRIGGERS = {
45
+ "strong": [
46
+ "suggests that", "indicates that", "implies", "may be attributed to",
47
+ "could be explained by", "appears to", "is likely due to",
48
+ "we interpret", "these findings suggest", "this result suggests",
49
+ "it is likely that", "is indicative of", "we attribute this to",
50
+ "this is consistent with", "supports the notion",
51
+ ],
52
+ "moderate": [
53
+ "consistent with", "in line with", "supports the hypothesis",
54
+ "in agreement with", "pointing to", "reflecting",
55
+ "can be understood as", "we believe", "our interpretation",
56
+ ],
57
+ "weak": [
58
+ "presumably", "apparently", "seems to", "tends to",
59
+ ],
60
+ }
61
+
62
+ HYPOTHESIS_TRIGGERS = {
63
+ "strong": [
64
+ "may", "might", "could potentially", "we hypothesize",
65
+ "it is possible that", "remains to be determined",
66
+ "future work should", "further investigation is needed",
67
+ "we speculate", "one possibility is", "a potential explanation",
68
+ "it is conceivable", "it remains unclear", "requires further study",
69
+ "we cannot rule out",
70
+ ],
71
+ "moderate": [
72
+ "we propose", "we envision", "it is plausible",
73
+ "a promising direction", "warrants further investigation",
74
+ "preliminary evidence suggests", "tentatively",
75
+ ],
76
+ "weak": [
77
+ "possibly", "potentially", "presumably", "perhaps",
78
+ ],
79
+ }
80
+
81
+ CONFLICT_TRIGGERS = {
82
+ "strong": [
83
+ "contradicts", "in contrast to", "unlike previous",
84
+ "contrary to", "inconsistent with", "at odds with",
85
+ "disputes", "challenges the", "refutes",
86
+ "however, our results show", "in disagreement with",
87
+ ],
88
+ "moderate": [
89
+ "differs from", "diverges from", "does not support",
90
+ "failed to reproduce", "we were unable to replicate",
91
+ "the discrepancy", "while others have reported",
92
+ ],
93
+ "weak": [
94
+ "however", "nevertheless", "on the other hand", "conversely",
95
+ ],
96
+ }
97
+
98
+ # ── Section-based priors ──────────────────────────────────────────────
99
+ # These shift the baseline probability before trigger analysis
100
+ SECTION_PRIORS = {
101
+ "abstract": {"Fact": 0.00, "Interpretation": 0.20, "Hypothesis": 0.05, "Conflict_Hypothesis": 0.00},
102
+ "introduction":{"Fact": 0.00, "Interpretation": 0.10, "Hypothesis": 0.05, "Conflict_Hypothesis": 0.00},
103
+ "methods": {"Fact": 0.15, "Interpretation": 0.00, "Hypothesis": 0.00, "Conflict_Hypothesis": 0.00},
104
+ "results": {"Fact": 0.25, "Interpretation": 0.00, "Hypothesis": 0.00, "Conflict_Hypothesis": 0.00},
105
+ "discussion": {"Fact": 0.00, "Interpretation": 0.15, "Hypothesis": 0.10, "Conflict_Hypothesis": 0.00},
106
+ "conclusion": {"Fact": 0.00, "Interpretation": 0.10, "Hypothesis": 0.05, "Conflict_Hypothesis": 0.00},
107
+ "supplement": {"Fact": 0.20, "Interpretation": 0.00, "Hypothesis": 0.00, "Conflict_Hypothesis": 0.00},
108
+ }
109
+
110
+ # Strength weights
111
+ STRENGTH_WEIGHTS = {"strong": 0.30, "moderate": 0.15, "weak": 0.08}
112
+
113
+
114
+ def compute_trigger_scores(claim_text: str, source_section: str = None) -> dict:
115
+ """
116
+ Compute epistemic trigger scores for a claim.
117
+
118
+ Returns:
119
+ {
120
+ "scores": {"Fact": 0.45, "Interpretation": 0.20, ...},
121
+ "predicted_tag": "Fact",
122
+ "confidence": 0.45,
123
+ "matched_triggers": {"Fact": ["measured", "p < 0.01"], ...},
124
+ "section_prior_applied": "results",
125
+ }
126
+ """
127
+ text_lower = claim_text.lower()
128
+
129
+ categories = {
130
+ "Fact": FACT_TRIGGERS,
131
+ "Interpretation": INTERPRETATION_TRIGGERS,
132
+ "Hypothesis": HYPOTHESIS_TRIGGERS,
133
+ "Conflict_Hypothesis": CONFLICT_TRIGGERS,
134
+ }
135
+
136
+ scores = {"Fact": 0.0, "Interpretation": 0.0, "Hypothesis": 0.0, "Conflict_Hypothesis": 0.0}
137
+ matched = {"Fact": [], "Interpretation": [], "Hypothesis": [], "Conflict_Hypothesis": []}
138
+
139
+ # Score trigger matches
140
+ for category, triggers_dict in categories.items():
141
+ for strength, triggers in triggers_dict.items():
142
+ weight = STRENGTH_WEIGHTS[strength]
143
+ for trigger in triggers:
144
+ if trigger in text_lower:
145
+ scores[category] += weight
146
+ matched[category].append(trigger)
147
+
148
+ # Apply section priors
149
+ section_key = (source_section or "").lower().strip()
150
+ priors = SECTION_PRIORS.get(section_key, {})
151
+ for cat, prior in priors.items():
152
+ scores[cat] += prior
153
+
154
+ # Normalize (cap at 1.0)
155
+ for cat in scores:
156
+ scores[cat] = min(1.0, scores[cat])
157
+
158
+ # Determine predicted tag
159
+ predicted_tag = max(scores, key=scores.get)
160
+ confidence = scores[predicted_tag]
161
+
162
+ return {
163
+ "scores": {k: round(v, 3) for k, v in scores.items()},
164
+ "predicted_tag": predicted_tag,
165
+ "confidence": round(confidence, 3),
166
+ "matched_triggers": {k: v for k, v in matched.items() if v},
167
+ "section_prior_applied": section_key or None,
168
+ }
169
+
170
+
171
+ def validate_ai_tag(claim_text: str, ai_tag: str,
172
+ source_section: str = None,
173
+ disagreement_threshold: float = 0.20) -> dict:
174
+ """
175
+ Cross-validate an AI-assigned epistemic tag against trigger analysis.
176
+
177
+ This is the core function — run this AFTER the AI Council assigns a tag,
178
+ and flag disagreements for human review.
179
+
180
+ Args:
181
+ claim_text: The claim text
182
+ ai_tag: Tag assigned by the AI Council (Fact/Interpretation/Hypothesis/Conflict_Hypothesis)
183
+ source_section: Paper section the claim came from
184
+ disagreement_threshold: Minimum score difference to flag disagreement
185
+
186
+ Returns:
187
+ {
188
+ "agreement": True/False,
189
+ "ai_tag": "Fact",
190
+ "trigger_tag": "Interpretation",
191
+ "trigger_scores": {...},
192
+ "disagreement_severity": "none" | "mild" | "strong",
193
+ "recommendation": "accept" | "review" | "override",
194
+ "explanation": "human-readable explanation",
195
+ }
196
+ """
197
+ trigger_result = compute_trigger_scores(claim_text, source_section)
198
+ trigger_tag = trigger_result["predicted_tag"]
199
+ trigger_scores = trigger_result["scores"]
200
+
201
+ agrees = (ai_tag == trigger_tag)
202
+
203
+ if agrees:
204
+ return {
205
+ "agreement": True,
206
+ "ai_tag": ai_tag,
207
+ "trigger_tag": trigger_tag,
208
+ "trigger_scores": trigger_scores,
209
+ "matched_triggers": trigger_result["matched_triggers"],
210
+ "disagreement_severity": "none",
211
+ "recommendation": "accept",
212
+ "explanation": f"AI and trigger analysis agree: {ai_tag}",
213
+ }
214
+
215
+ # Compute disagreement severity
216
+ ai_score = trigger_scores.get(ai_tag, 0.0)
217
+ trigger_score = trigger_scores.get(trigger_tag, 0.0)
218
+ score_diff = trigger_score - ai_score
219
+
220
+ if score_diff < disagreement_threshold:
221
+ severity = "mild"
222
+ recommendation = "accept" # AI tag is close enough
223
+ explanation = (
224
+ f"AI says '{ai_tag}' (trigger score: {ai_score:.2f}), "
225
+ f"triggers lean '{trigger_tag}' (score: {trigger_score:.2f}). "
226
+ f"Difference is small ({score_diff:.2f}). AI tag accepted."
227
+ )
228
+ else:
229
+ severity = "strong"
230
+ recommendation = "review"
231
+
232
+ # Specific explanations for common disagreement patterns
233
+ if ai_tag == "Fact" and trigger_tag in ("Interpretation", "Hypothesis"):
234
+ explanation = (
235
+ f"⚠️ AI tagged as Fact but text contains hedging language: "
236
+ f"{trigger_result['matched_triggers'].get(trigger_tag, [])}. "
237
+ f"Consider downgrading to {trigger_tag}."
238
+ )
239
+ elif ai_tag == "Interpretation" and trigger_tag == "Fact":
240
+ explanation = (
241
+ f"AI tagged as Interpretation but text contains strong evidence language: "
242
+ f"{trigger_result['matched_triggers'].get('Fact', [])}. "
243
+ f"May warrant upgrading to Fact if in Results section."
244
+ )
245
+ elif ai_tag == "Fact" and trigger_tag == "Conflict_Hypothesis":
246
+ explanation = (
247
+ f"⚠️ AI tagged as Fact but text contains contradiction language: "
248
+ f"{trigger_result['matched_triggers'].get('Conflict_Hypothesis', [])}. "
249
+ f"This may be a conflict claim."
250
+ )
251
+ else:
252
+ explanation = (
253
+ f"AI says '{ai_tag}' (score: {ai_score:.2f}), "
254
+ f"triggers say '{trigger_tag}' (score: {trigger_score:.2f}). "
255
+ f"Matched triggers: {trigger_result['matched_triggers']}. "
256
+ f"Human review recommended."
257
+ )
258
+
259
+ return {
260
+ "agreement": False,
261
+ "ai_tag": ai_tag,
262
+ "trigger_tag": trigger_tag,
263
+ "trigger_scores": trigger_scores,
264
+ "matched_triggers": trigger_result["matched_triggers"],
265
+ "disagreement_severity": severity,
266
+ "recommendation": recommendation,
267
+ "explanation": explanation,
268
+ }
269
+
270
+
271
+ def batch_validate(claims: list[dict]) -> dict:
272
+ """
273
+ Validate a batch of claims. Each claim dict must have:
274
+ - "text": str
275
+ - "epistemic_tag": str (AI-assigned tag)
276
+ - "source_section": str (optional)
277
+
278
+ Returns summary statistics and flagged claims.
279
+ """
280
+ results = {
281
+ "total": len(claims),
282
+ "agreements": 0,
283
+ "mild_disagreements": 0,
284
+ "strong_disagreements": 0,
285
+ "flagged_for_review": [],
286
+ }
287
+
288
+ for i, claim in enumerate(claims):
289
+ validation = validate_ai_tag(
290
+ claim_text=claim.get("text", ""),
291
+ ai_tag=claim.get("epistemic_tag", "Interpretation"),
292
+ source_section=claim.get("source_section"),
293
+ )
294
+
295
+ if validation["agreement"]:
296
+ results["agreements"] += 1
297
+ elif validation["disagreement_severity"] == "mild":
298
+ results["mild_disagreements"] += 1
299
+ else:
300
+ results["strong_disagreements"] += 1
301
+ results["flagged_for_review"].append({
302
+ "index": i,
303
+ "claim_text": claim.get("text", "")[:200],
304
+ "validation": validation,
305
+ })
306
+
307
+ results["agreement_rate"] = round(
308
+ results["agreements"] / max(results["total"], 1), 3
309
+ )
310
+
311
+ return results