graziul commited on
Commit
9eb6c74
·
verified ·
1 Parent(s): b6b5a0b

feat: collapsible expansion, canonical formalism pages, citation enrichment

Browse files
Files changed (1) hide show
  1. match.py +1008 -0
match.py ADDED
@@ -0,0 +1,1008 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Compositional matching engine.
3
+
4
+ Takes extraction output (concepts with operational signatures) and matches
5
+ against the formalism knowledge base using three strategies:
6
+
7
+ 1. DIRECT MATCH: signature matches a known formalism exactly → "≡ X"
8
+ 2. COMPOSITIONAL MATCH: signature = compose(f₁, f₂, ...) → "≡ X ∘ Y"
9
+ 3. ANALOGY MATCH: same meso/macro type as known formalism → "≈ X (Δ: ...)"
10
+
11
+ Composition is type-checked: rules specify input/output signatures, and the
12
+ engine verifies that each rule's input constraints are satisfied before
13
+ applying it. The result is a valid composition tree, not just a bag of rules.
14
+
15
+ Returns UNKNOWN when no match found. Returns CONFUSED when the concept's
16
+ own operations are internally contradictory.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import re
23
+ from collections.abc import Sequence
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+ from typing import Any, Optional
27
+
28
+ import yaml
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Type aliases (match the YAML schemas)
32
+ # ---------------------------------------------------------------------------
33
+
34
+ Operation = str # maximize | minimize | transform | project | decompose | sample | aggregate | match | propagate
35
+ DomainType = str # vector | matrix | graph | distribution | sequence | manifold | scalar_field | set | function | latent
36
+ CodomainType = str # vector | matrix | graph | distribution | sequence | scalar | embedding | assignment | latent
37
+ ObjectiveFamily = str # divergence | likelihood | energy | correlation | information | none | adversarial | reconstruction
38
+ MesoType = str # joint_embedding | spectral_method | energy_model | dynamical_system | ...
39
+ MacroType = str # optimization | eigenvalue_problem | stochastic_process | statistical_inference | hamiltonian_system | none
40
+
41
+
42
+ @dataclass
43
+ class Signature:
44
+ """Typed operational signature extracted from a concept or formalism."""
45
+ operation: Operation | None = None
46
+ domain: DomainType | None = None
47
+ codomain: CodomainType | None = None
48
+ objective_family: ObjectiveFamily | None = None
49
+
50
+ @classmethod
51
+ def from_concept(cls, concept: dict) -> "Signature":
52
+ """Infer a typed signature from the LLM's extracted concept fields."""
53
+ sig = cls()
54
+ # Infer operation from the mathematical_operation string
55
+ op_text = (concept.get("mathematical_operation") or "").lower()
56
+ sig.operation = _infer_operation(op_text)
57
+ sig.domain = _normalize_domain(concept.get("domain"))
58
+ sig.codomain = _normalize_domain(concept.get("codomain"))
59
+ sig.objective_family = _infer_objective(concept.get("objective") or "", op_text)
60
+ return sig
61
+
62
+ @classmethod
63
+ def from_formalism(cls, fm: dict) -> "Signature":
64
+ """Extract signature from a formalism YAML entry."""
65
+ sig_raw = fm.get("signature", {})
66
+ return cls(
67
+ operation=sig_raw.get("operation"),
68
+ domain=sig_raw.get("domain"),
69
+ codomain=sig_raw.get("codomain"),
70
+ objective_family=sig_raw.get("objective_family"),
71
+ )
72
+
73
+ def matches(self, other: "Signature", *, strict: bool = True) -> float:
74
+ """Return a match score 0.0–1.0 between this and another signature.
75
+
76
+ strict=True: all non-None fields must match exactly; score = proportion matched.
77
+ strict=False: fuzzy — operation + codomain weighted higher.
78
+ """
79
+ fields = [
80
+ ("operation", 0.35),
81
+ ("domain", 0.15),
82
+ ("codomain", 0.30),
83
+ ("objective_family", 0.20),
84
+ ]
85
+ total = 0.0
86
+ matched = 0.0
87
+ pairs = []
88
+ for attr, weight in fields:
89
+ mine = getattr(self, attr)
90
+ theirs = getattr(other, attr)
91
+ pairs.append((attr, mine, theirs, weight))
92
+
93
+ if strict:
94
+ # Only score on fields where both sides have a value
95
+ scorable = [(a, m, t, w) for a, m, t, w in pairs if m is not None and t is not None]
96
+ if not scorable:
97
+ return 0.0
98
+ total = sum(w for _, _, _, w in scorable)
99
+ matched = sum(w for _, m, t, w in scorable if m == t)
100
+ else:
101
+ total = sum(weight for _, _, _, weight in pairs)
102
+ for _, mine_val, theirs_val, weight in pairs:
103
+ if mine_val is None or theirs_val is None:
104
+ matched += weight * 0.5 # neutral on unknown
105
+ elif mine_val == theirs_val:
106
+ matched += weight
107
+ # else: 0 on mismatch
108
+
109
+ return matched / total if total > 0 else 0.0
110
+
111
+
112
+ @dataclass
113
+ class Formalism:
114
+ """A known formalism from the KB."""
115
+ id: str
116
+ name: str
117
+ year: int | None
118
+ origin: str
119
+ signature: Signature
120
+ meso_type: MesoType | None
121
+ macro_type: MacroType | None
122
+ canonical_reference: str
123
+ status: str
124
+
125
+ @classmethod
126
+ def from_yaml(cls, entry: dict) -> "Formalism":
127
+ return cls(
128
+ id=entry["id"],
129
+ name=entry["name"],
130
+ year=entry.get("year"),
131
+ origin=entry.get("origin", ""),
132
+ signature=Signature.from_formalism(entry),
133
+ meso_type=entry.get("meso_type"),
134
+ macro_type=entry.get("macro_type"),
135
+ canonical_reference=entry.get("canonical_reference", ""),
136
+ status=entry.get("status", "seed"),
137
+ )
138
+
139
+
140
+ @dataclass
141
+ class CompositionRule:
142
+ """A composition rule from the KB."""
143
+ id: str
144
+ name: str
145
+ description: str
146
+ decomposes_to: list[str] # formalism_ids this rule expands to
147
+ input_constraints: dict[str, Any]
148
+ output_signature: dict[str, Any]
149
+ preserves: list[str]
150
+ introduces: list[str]
151
+ examples: list[str]
152
+ status: str
153
+
154
+ @classmethod
155
+ def from_yaml(cls, entry: dict) -> "CompositionRule":
156
+ return cls(
157
+ id=entry["id"],
158
+ name=entry.get("name", entry["id"]),
159
+ description=entry.get("description", ""),
160
+ decomposes_to=entry.get("decomposes_to", []),
161
+ input_constraints=entry.get("input_constraints", {}),
162
+ output_signature=entry.get("output_signature", {}),
163
+ preserves=entry.get("preserves", []),
164
+ introduces=entry.get("introduces", []),
165
+ examples=entry.get("examples", []),
166
+ status=entry.get("status", "seed"),
167
+ )
168
+
169
+ def accepts(self, formalism: Formalism) -> bool:
170
+ """Check whether this rule can be applied to the given formalism."""
171
+ constraints = self.input_constraints
172
+ if not constraints:
173
+ return True # universal rule
174
+
175
+ # Check specific formalism IDs
176
+ req_ids = constraints.get("formalism_ids")
177
+ if req_ids is not None:
178
+ if isinstance(req_ids, list) and req_ids and formalism.id not in req_ids:
179
+ return False
180
+
181
+ # Check meso types
182
+ req_meso = constraints.get("meso_types")
183
+ if req_meso is not None:
184
+ if isinstance(req_meso, list) and req_meso:
185
+ if formalism.meso_type not in req_meso:
186
+ return False
187
+
188
+ # Check macro types
189
+ req_macro = constraints.get("macro_types")
190
+ if req_macro is not None:
191
+ if isinstance(req_macro, list) and req_macro:
192
+ if formalism.macro_type not in req_macro:
193
+ return False
194
+
195
+ return True
196
+
197
+
198
+ @dataclass
199
+ class CompositionNode:
200
+ """A node in a composition tree: formalism + list of applied rules."""
201
+ formalism: Formalism
202
+ rules: list[CompositionRule] = field(default_factory=list)
203
+
204
+ @property
205
+ def name(self) -> str:
206
+ if not self.rules:
207
+ return self.formalism.name
208
+ rule_names = " ∘ ".join(r.name for r in self.rules)
209
+ return f"{self.formalism.name} ∘ {rule_names}"
210
+
211
+ @property
212
+ def is_direct(self) -> bool:
213
+ return len(self.rules) == 0
214
+
215
+
216
+ @dataclass
217
+ class MatchResult:
218
+ """The result of matching a concept against the KB."""
219
+ concept_name: str
220
+ result_type: str # "identity" | "compositional" | "analogy" | "unknown" | "confused"
221
+ reduction: str # e.g., "CCA ∘ neuralize ∘ predict_in_codomain"
222
+ reduction_expanded: str # e.g., "CCA ∘ Gradient Descent ∘ CCA" (rules expanded)
223
+ canonical_analog: str # e.g., "Kernel CCA (Bach & Jordan, 2002)"
224
+ genuine_delta: str # what's actually new, if anything
225
+ micro: str # fine-grained: what operation happens at the lowest level
226
+ meso: str # mid-level: what structural family this belongs to
227
+ macro: str # top-level: what grand tradition this sits in
228
+ confidence: float
229
+ nodes: list[CompositionNode] = field(default_factory=list)
230
+ match_scores: list[float] = field(default_factory=list)
231
+ notes: list[str] = field(default_factory=list)
232
+
233
+ @property
234
+ def display(self) -> str:
235
+ """Sous rature display: ~~AI Term~~ → Mathematical Operation"""
236
+ if self.result_type == "identity":
237
+ return f"~~{self.concept_name}~~ ≡ {self.reduction}"
238
+ elif self.result_type == "compositional":
239
+ base = f"~~{self.concept_name}~~ ≡ {self.reduction}"
240
+ if self.reduction_expanded and self.reduction_expanded != self.reduction:
241
+ base += f"\x00EXPAND\x00{self.reduction_expanded}\x00/EXPAND\x00"
242
+ return base
243
+ elif self.result_type == "analogy":
244
+ return f"~~{self.concept_name}~~ ≈ {self.reduction} (Δ: {self.genuine_delta})"
245
+ elif self.result_type == "confused":
246
+ return f"~~{self.concept_name}~~ → CONFUSED: {self.notes[0] if self.notes else 'terminology overload'}"
247
+ else:
248
+ return f"~~{self.concept_name}~~ → UNKNOWN"
249
+
250
+
251
+ # ---------------------------------------------------------------------------
252
+ # KB loading
253
+ # ---------------------------------------------------------------------------
254
+
255
+ def _kb_dir() -> Path:
256
+ return Path(__file__).resolve().parent / "kb"
257
+
258
+
259
+ def load_formalisms(path: Path | None = None) -> list[Formalism]:
260
+ """Load the formalism KB."""
261
+ if path is None:
262
+ path = _kb_dir() / "formalisms.yaml"
263
+ with open(path) as f:
264
+ data = yaml.safe_load(f)
265
+ return [Formalism.from_yaml(e) for e in data.get("formalisms", [])]
266
+
267
+
268
+ def load_composition_rules(path: Path | None = None) -> list[CompositionRule]:
269
+ """Load the composition rules KB."""
270
+ if path is None:
271
+ path = _kb_dir() / "composition_rules.yaml"
272
+ with open(path) as f:
273
+ data = yaml.safe_load(f)
274
+ return [CompositionRule.from_yaml(e) for e in data.get("composition_rules", [])]
275
+
276
+
277
+ # ---------------------------------------------------------------------------
278
+ # Signature inference helpers (parse LLM output into typed fields)
279
+ # ---------------------------------------------------------------------------
280
+
281
+ _OP_PATTERNS: list[tuple[str, str]] = [
282
+ (r"\b(minimi[zs]e|minimi[zs]ation|minimi[zs]ing)\b", "minimize"),
283
+ (r"\b(maximi[zs]e|maximi[zs]ation|maximi[zs]ing)\b", "maximize"),
284
+ (r"\b(project|projection|projecting)\b", "project"),
285
+ (r"\b(decompose|decomposition|factorize|factorization|eigen)\b", "decompose"),
286
+ (r"\b(sample|sampling|generate|generating|generative)\b", "sample"),
287
+ (r"\b(aggregate|aggregation|weighted\s+sum|pooling)\b", "aggregate"),
288
+ (r"\b(transform|transformations?|map|mapping)\b", "transform"),
289
+ (r"\b(match|matching|align|alignment)\b", "match"),
290
+ (r"\b(propagat|diffuse|random\s+walk)\b", "propagate"),
291
+ ]
292
+
293
+
294
+ def _infer_operation(text: str) -> Operation | None:
295
+ text_lower = text.lower()
296
+ for pattern, op in _OP_PATTERNS:
297
+ if re.search(pattern, text_lower):
298
+ return op
299
+ return None
300
+
301
+
302
+ _DOMAIN_MAP: dict[str, DomainType] = {
303
+ "vector": "vector", "vectors": "vector", "embedding": "vector",
304
+ "matrix": "matrix", "matrices": "matrix",
305
+ "graph": "graph",
306
+ "distribution": "distribution", "probability": "distribution",
307
+ "sequence": "sequence", "token": "sequence", "time series": "sequence",
308
+ "manifold": "manifold",
309
+ "set": "set",
310
+ "function": "function", "scalar field": "scalar_field",
311
+ "latent": "latent", "latent space": "latent",
312
+ }
313
+
314
+
315
+ def _normalize_domain(text: str | None) -> DomainType | None:
316
+ if not text:
317
+ return None
318
+ t = text.strip().lower()
319
+ # Try exact match first
320
+ for key, val in _DOMAIN_MAP.items():
321
+ if key in t:
322
+ return val
323
+ return t # pass through — might be a valid value we just don't have mapped
324
+
325
+
326
+ _OBJ_PATTERNS: list[tuple[str, ObjectiveFamily]] = [
327
+ (r"\b(kl\b|kullback|divergence|kl\s*divergence)\b", "divergence"),
328
+ (r"\b(likelihood|log\s*likelihood|mle|maximum\s*likelihood)\b", "likelihood"),
329
+ (r"\b(energy|free\s*energy|hamiltonian)\b", "energy"),
330
+ (r"\b(correlation|canonical\s*correlation|cca|cross.correlation)\b", "correlation"),
331
+ (r"\b(mutual\s*information|mi\b|infonce|information\s*max)\b", "information"),
332
+ (r"\b(adversarial|minimax|min.max|gan\b|discriminator)\b", "adversarial"),
333
+ (r"\b(reconstruction|autoencod|encode.decode|mse\b|squared\s*error)\b", "reconstruction"),
334
+ ]
335
+
336
+
337
+ def _infer_objective(obj_text: str, op_text: str) -> ObjectiveFamily | None:
338
+ combined = (obj_text + " " + op_text).lower()
339
+ for pattern, obj in _OBJ_PATTERNS:
340
+ if re.search(pattern, combined):
341
+ return obj
342
+ return None
343
+
344
+
345
+ def _infer_meso_type(sig: Signature, concept: dict) -> MesoType | None:
346
+ """Infer meso-type from signature and concept text."""
347
+ text = (
348
+ f"{concept.get('mathematical_operation', '')} "
349
+ f"{concept.get('canonical_analog', '')}"
350
+ ).lower()
351
+
352
+ if any(w in text for w in ("kernel", "rkhs", "nyström", "nystrom")):
353
+ return "kernel_method"
354
+ if any(w in text for w in ("spectral", "eigen", "laplacian", "fourier")):
355
+ return "spectral_method"
356
+ if any(w in text for w in ("energy", "free energy", "boltzmann", "hamiltonian")):
357
+ return "energy_model"
358
+ if any(w in text for w in ("diffusion", "sde", "langevin", "score-based", "ddpm")):
359
+ return "diffusion_process"
360
+ if any(w in text for w in ("variational", "elbo", "vi ")):
361
+ return "variational"
362
+ if any(w in text for w in ("optimal transport", "wasserstein", "sinkhorn")):
363
+ return "optimal_transport"
364
+ if any(w in text for w in ("contrastive", "siamese", "infonce")):
365
+ return "joint_embedding"
366
+ if any(w in text for w in ("gan", "adversarial", "minimax", "generator")):
367
+ return "game_theoretic"
368
+ if any(w in text for w in ("mean field", "mean-field")):
369
+ return "mean_field"
370
+ if any(w in text for w in ("joint embedding", "multi.view", "multiview", "cca")):
371
+ return "joint_embedding"
372
+ if any(w in text for w in ("pca", "projection", "linear", "svd")):
373
+ return "linear_projection"
374
+ if any(w in text for w in ("spin", "ising", "hopfield")):
375
+ return "spin_system"
376
+ return None
377
+
378
+
379
+ # ---------------------------------------------------------------------------
380
+ # Matching engine
381
+ # ---------------------------------------------------------------------------
382
+
383
+ # Keyword → rule triggers for canonical analog path.
384
+ # When the LLM says "this is essentially X," but the concept text
385
+ # describes specific modifications, these keyword sets determine which
386
+ # rules describe the paper's actual delta from the canonical analog.
387
+ _RULE_KEYWORDS: dict[str, list[str]] = {
388
+ "neuralize": [
389
+ "learned", "learnable", "deep", "encoder", "neural", "network",
390
+ "parameterized", "differentiable", "end-to-end", "trained", "φ_θ",
391
+ "f_θ", "g_θ", "dnn", "backprop",
392
+ ],
393
+ "predict_in_codomain": [
394
+ "predict", "predictive", "predicting", "prediction",
395
+ "latent space", "embedding space", "representation space",
396
+ "in latent", "in embedding", "codomain",
397
+ "future embedding", "future representation",
398
+ ],
399
+ "contrastivize": [
400
+ "contrastive", "contrastively", "positive pair", "negative pair",
401
+ "infonce", "noise contrastive", "nce",
402
+ ],
403
+ "diffuse": [
404
+ "diffusion", "denoising", "denoise", "score-based",
405
+ "reverse process", "forward process", "sde", "ddpm",
406
+ ],
407
+ "adversarize": [
408
+ "adversarial", "gan", "discriminator", "generator",
409
+ "minimax", "min-max",
410
+ ],
411
+ "variational_bound": [
412
+ "variational", "elbo", "vae", "auto-encoding", "autoencoding",
413
+ "amortized inference", "inference network",
414
+ ],
415
+ "regularize": [
416
+ "regularize", "regularization", "l1 ", "l2 ", "weight decay",
417
+ "dropout", "sparsity",
418
+ ],
419
+ "attention_wrap": [
420
+ "attention", "self-attention", "transformer", "attend",
421
+ ],
422
+ }
423
+
424
+
425
+ @dataclass
426
+ class MatchEngine:
427
+ """The compositional matching engine."""
428
+
429
+ formalisms: list[Formalism]
430
+ rules: list[CompositionRule]
431
+ config: dict = field(default_factory=dict)
432
+
433
+ # Indexes for fast lookup
434
+ _by_id: dict[str, Formalism] = field(default_factory=dict)
435
+ _by_meso: dict[MesoType, list[Formalism]] = field(default_factory=dict)
436
+ _by_macro: dict[MacroType, list[Formalism]] = field(default_factory=dict)
437
+ _by_name: dict[str, Formalism] = field(default_factory=dict) # fuzzy name index
438
+ _name_tokens: dict[str, list[Formalism]] = field(default_factory=dict)
439
+
440
+ def __post_init__(self):
441
+ self._build_indexes()
442
+
443
+ def _build_indexes(self):
444
+ for fm in self.formalisms:
445
+ self._by_id[fm.id] = fm
446
+ if fm.meso_type:
447
+ self._by_meso.setdefault(fm.meso_type, []).append(fm)
448
+ if fm.macro_type:
449
+ self._by_macro.setdefault(fm.macro_type, []).append(fm)
450
+ # Name index: lowercase the name and each token
451
+ name_lower = fm.name.lower()
452
+ self._by_name[name_lower] = fm
453
+ for token in name_lower.replace("(", "").replace(")", "").replace("/", " ").split():
454
+ token = token.strip().rstrip(".,;:")
455
+ if len(token) >= 3:
456
+ self._name_tokens.setdefault(token, []).append(fm)
457
+
458
+ # ---- Canonical analog resolution ----
459
+
460
+ def _resolve_canonical_analog(self, analog_text: str) -> Formalism | None:
461
+ """Parse the LLM's canonical_analog field and find the matching formalism.
462
+
463
+ Handles formats like:
464
+ - "Kernel CCA (Bach & Jordan, 2002)"
465
+ - "Kernel Canonical Correlation Analysis"
466
+ - "CCA — Bach & Jordan 2002"
467
+ """
468
+ if not analog_text:
469
+ return None
470
+ text_lower = analog_text.lower().strip()
471
+
472
+ # 1. Exact name match
473
+ if text_lower in self._by_name:
474
+ return self._by_name[text_lower]
475
+
476
+ # 2. Try stripping parenthetical citations
477
+ no_parens = re.sub(r"\([^)]*\)", "", text_lower).strip()
478
+ if no_parens in self._by_name:
479
+ return self._by_name[no_parens]
480
+
481
+ # 3. Token intersection scoring
482
+ tokens = set(t.strip().rstrip(".,;:") for t in no_parens.replace("/", " ").split() if len(t.strip()) >= 3)
483
+ if not tokens:
484
+ return None
485
+
486
+ scored: list[tuple[int, Formalism]] = []
487
+ for fm in self.formalisms:
488
+ fm_tokens = set(t.strip().rstrip(".,;:") for t in fm.name.lower().replace("(", "").replace(")", "").replace("/", " ").split() if len(t.strip()) >= 3)
489
+ intersection = tokens & fm_tokens
490
+ if intersection:
491
+ scored.append((len(intersection), fm))
492
+
493
+ if scored:
494
+ scored.sort(key=lambda x: x[0], reverse=True)
495
+ if scored[0][0] >= 2:
496
+ return scored[0][1]
497
+ # Single-token match only if the matched token is distinctive
498
+ top_token = max(tokens, key=len) if tokens else ""
499
+ for score, fm in scored:
500
+ if score >= 1 and len(top_token) >= 4: # e.g., "canonical", "correlation"
501
+ return fm
502
+
503
+ return None
504
+
505
+ # ---- Main entry point ----
506
+
507
+ def match_concept(self, concept: dict) -> MatchResult:
508
+ """Match a single extracted concept against the KB.
509
+
510
+ Returns a MatchResult with the best available decomposition.
511
+ """
512
+ name = concept.get("name", "unknown")
513
+ sig = Signature.from_concept(concept)
514
+ meso = _infer_meso_type(sig, concept)
515
+
516
+ # Route based on concept flags from extraction
517
+ flags = concept.get("flags", []) or []
518
+ if "cannot_determine_from_abstract" in flags:
519
+ return MatchResult(
520
+ concept_name=name,
521
+ result_type="unknown",
522
+ reduction="cannot determine from abstract",
523
+ reduction_expanded="cannot determine from abstract",
524
+ canonical_analog="",
525
+ genuine_delta="",
526
+ micro=concept.get("mathematical_operation", ""),
527
+ meso=meso or "unknown",
528
+ macro="unknown",
529
+ confidence=0.0,
530
+ notes=["LLM extraction flagged: cannot determine from abstract"],
531
+ )
532
+ if "terminology_overload" in flags or "claim_operation_mismatch" in flags:
533
+ pass # Still attempt match but note flags
534
+
535
+ # Strategy 0: Canonical analog from LLM extraction (highest-weight signal)
536
+ canonical_analog_text = concept.get("canonical_analog", "") or ""
537
+ base_fm = self._resolve_canonical_analog(canonical_analog_text)
538
+
539
+ if base_fm is not None:
540
+ # The LLM says this is essentially X. Now find rules that account
541
+ # for what makes it "novel" beyond X.
542
+ rules = self._find_rules_to_match(base_fm, sig, concept)
543
+ if not rules:
544
+ # No rules needed — the LLM-identified analog is the answer
545
+ return MatchResult(
546
+ concept_name=name,
547
+ result_type="identity",
548
+ reduction=base_fm.name,
549
+ reduction_expanded=base_fm.name,
550
+ canonical_analog=f"{base_fm.name} ({base_fm.canonical_reference})",
551
+ genuine_delta="LLM-identified rebranding of known formalism",
552
+ micro=f"{base_fm.signature.operation}({base_fm.signature.domain} → {base_fm.signature.codomain})",
553
+ meso=base_fm.meso_type or "none",
554
+ macro=base_fm.macro_type or "none",
555
+ confidence=0.85, # LLM identification is high-confidence
556
+ nodes=[CompositionNode(formalism=base_fm)],
557
+ match_scores=[0.85],
558
+ notes=["matched via LLM canonical_analog field"],
559
+ )
560
+ else:
561
+ # Rules account for the delta from the canonical analog
562
+ rule_names = " ∘ ".join(r.name for r in rules)
563
+ expanded_fms = self.expand_rules(rules)
564
+ expanded = base_fm.name + " ∘ " + " ∘ ".join(expanded_fms)
565
+ return MatchResult(
566
+ concept_name=name,
567
+ result_type="compositional",
568
+ reduction=f"{base_fm.name} ∘ {rule_names}",
569
+ reduction_expanded=expanded,
570
+ canonical_analog=f"{base_fm.name} ({base_fm.canonical_reference})",
571
+ genuine_delta=" ∘ ".join(r.name for r in rules),
572
+ micro=f"{base_fm.signature.operation}({base_fm.signature.domain} → {base_fm.signature.codomain})",
573
+ meso=base_fm.meso_type or "none",
574
+ macro=base_fm.macro_type or "none",
575
+ confidence=0.80,
576
+ nodes=[CompositionNode(formalism=base_fm, rules=rules)],
577
+ match_scores=[0.80],
578
+ notes=["matched via LLM canonical_analog with rule delta"],
579
+ )
580
+
581
+ # Strategy 1: Direct identity match (signature only)
582
+ direct = self._match_direct(sig)
583
+ if direct and direct[1] >= 0.85:
584
+ fm, score = direct
585
+ return MatchResult(
586
+ concept_name=name,
587
+ result_type="identity",
588
+ reduction=fm.name,
589
+ reduction_expanded=fm.name,
590
+ canonical_analog=f"{fm.name} ({fm.canonical_reference})",
591
+ genuine_delta="none — this is a direct rebranding",
592
+ micro=f"exactly {fm.name}: {fm.signature.operation}({fm.signature.domain} → {fm.signature.codomain})",
593
+ meso=fm.meso_type or "none",
594
+ macro=fm.macro_type or "none",
595
+ confidence=score,
596
+ nodes=[CompositionNode(formalism=fm)],
597
+ match_scores=[score],
598
+ )
599
+
600
+ # Strategy 2: Compositional match
601
+ comp = self._match_compositional(sig, meso)
602
+ if comp and comp.confidence >= 0.5:
603
+ return comp
604
+
605
+ # Strategy 3: Analogy match
606
+ analogy = self._match_analogy(sig, meso)
607
+ if analogy and analogy.confidence >= 0.4:
608
+ return analogy
609
+
610
+ # Give up
611
+ return MatchResult(
612
+ concept_name=name,
613
+ result_type="unknown",
614
+ reduction="no match in KB",
615
+ reduction_expanded="no match in KB",
616
+ canonical_analog="",
617
+ genuine_delta="",
618
+ micro=concept.get("mathematical_operation", ""),
619
+ meso=meso or "unknown",
620
+ macro="unknown",
621
+ confidence=0.0,
622
+ notes=["concept signature does not match any formalism or valid composition"],
623
+ )
624
+
625
+ # ---- Strategy 1: Direct match ----
626
+
627
+ def _match_direct(self, sig: Signature) -> tuple[Formalism, float] | None:
628
+ best: tuple[Formalism, float] | None = None
629
+ best_score = 0.0
630
+ for fm in self.formalisms:
631
+ score = sig.matches(fm.signature, strict=True)
632
+ if score > best_score:
633
+ best_score = score
634
+ best = (fm, score)
635
+ if best and best_score >= 0.5:
636
+ return best
637
+ return None
638
+
639
+ # ---- Rule expansion ----
640
+
641
+ def expand_rules(self, rules: list[CompositionRule]) -> list[str]:
642
+ """Recursively expand composition rules into their constituent formalism names.
643
+
644
+ Each rule's decomposes_to field lists formalism IDs it's composed of.
645
+ This method looks up those formalisms by ID and returns their display names,
646
+ giving the full decomposition chain beneath what appears as a single rule.
647
+ """
648
+ names: list[str] = []
649
+ for rule in rules:
650
+ expanded = False
651
+ for fm_id in rule.decomposes_to:
652
+ fm = self._by_id.get(fm_id)
653
+ if fm:
654
+ names.append(fm.name)
655
+ expanded = True
656
+ if not expanded:
657
+ # Rule has no decomposition — use the rule name itself
658
+ names.append(rule.name)
659
+ return names
660
+
661
+ # ---- Rule-to-target matching (for canonical analog case) ----
662
+
663
+ # _RULE_KEYWORDS is a module-level constant; see below.
664
+ # Keyword → rule triggers for canonical analog path.
665
+
666
+ def _find_rules_to_match(
667
+ self,
668
+ base_fm: Formalism,
669
+ target_sig: Signature,
670
+ concept: dict | None = None,
671
+ ) -> list[CompositionRule]:
672
+ """Find composition rules that describe the paper's delta from the
673
+ canonical analog. Uses two strategies:
674
+
675
+ 1. Signature-distance minimization (greedy, depth ≤ 2)
676
+ 2. Keyword-triggered rules from concept text (when LLM has already
677
+ identified the base formalism — the keywords describe what the
678
+ paper actually changed)
679
+ """
680
+ base_sig = base_fm.signature
681
+ base_dist = 1.0 - base_sig.matches(target_sig, strict=False)
682
+
683
+ # Strategy A: Signature-distance minimization
684
+ best_rules: list[CompositionRule] = []
685
+ best_dist = base_dist
686
+
687
+ for rule in self.rules:
688
+ if not rule.accepts(base_fm):
689
+ continue
690
+ transformed = self._apply_rule_signature(base_sig, rule)
691
+ dist = 1.0 - transformed.matches(target_sig, strict=False)
692
+ if dist < best_dist:
693
+ best_dist = dist
694
+ best_rules = [rule]
695
+
696
+ for rule1 in self.rules:
697
+ if not rule1.accepts(base_fm):
698
+ continue
699
+ inter = self._apply_rule_signature(base_sig, rule1)
700
+ for rule2 in self.rules:
701
+ if rule2 is rule1:
702
+ continue
703
+ if not self._rule_accepts_signature(rule2, inter):
704
+ continue
705
+ transformed = self._apply_rule_signature(inter, rule2)
706
+ dist = 1.0 - transformed.matches(target_sig, strict=False)
707
+ if dist < best_dist:
708
+ best_dist = dist
709
+ best_rules = [rule1, rule2]
710
+
711
+ sig_improved = best_dist < base_dist - 0.05
712
+
713
+ # Strategy B: Keyword-triggered rules from concept text
714
+ if concept is not None:
715
+ text = " ".join([
716
+ concept.get("mathematical_operation") or "",
717
+ concept.get("objective") or "",
718
+ concept.get("claimed_novelty_text") or "",
719
+ concept.get("confidence_rationale") or "",
720
+ ]).lower()
721
+
722
+ keyword_rules: list[CompositionRule] = []
723
+ for rule in self.rules:
724
+ if rule in best_rules:
725
+ continue
726
+ keywords = _RULE_KEYWORDS.get(rule.id, [])
727
+ if any(kw in text for kw in keywords):
728
+ if rule.accepts(base_fm) or not rule.input_constraints:
729
+ keyword_rules.append(rule)
730
+
731
+ # Merge: signature-driven rules first, then keyword rules
732
+ # that don't duplicate. Prefer keyword rules when the LLM
733
+ # has identified the base (they're semantically richer).
734
+ if keyword_rules:
735
+ if sig_improved:
736
+ # Both strategies agree — merge, deduplicate
737
+ merged = list(best_rules)
738
+ for kr in keyword_rules:
739
+ if kr not in merged:
740
+ merged.append(kr)
741
+ return merged
742
+ else:
743
+ # Only keyword strategy fires — use those
744
+ return keyword_rules
745
+
746
+ if sig_improved:
747
+ return best_rules
748
+ return []
749
+
750
+ # ---- Strategy 2: Compositional match ----
751
+
752
+ def _match_compositional(self, sig: Signature, meso: MesoType | None) -> MatchResult | None:
753
+ """Try to decompose the concept as formalism + composition rules.
754
+
755
+ For each formalism whose signature is close, see if applying
756
+ available rules transforms it toward the concept's signature.
757
+ """
758
+ candidates: list[tuple[Formalism, list[CompositionRule], float]] = []
759
+
760
+ # For each formalism that could be a base
761
+ for fm in self.formalisms:
762
+ for rule in self.rules:
763
+ if not rule.accepts(fm):
764
+ continue
765
+ # Apply rule conceptually and score
766
+ composed_sig = self._apply_rule_signature(fm.signature, rule)
767
+ score = sig.matches(composed_sig, strict=True)
768
+ if score >= 0.5:
769
+ candidates.append((fm, [rule], score))
770
+
771
+ # Try two-rule compositions
772
+ for rule2 in self.rules:
773
+ if rule2 is rule:
774
+ continue
775
+ # Check if rule2 accepts the output type of rule1
776
+ intermediate = self._apply_rule_signature(fm.signature, rule)
777
+ if not self._rule_accepts_signature(rule2, intermediate):
778
+ continue
779
+ composed2 = self._apply_rule_signature(intermediate, rule2)
780
+ score2 = sig.matches(composed2, strict=True)
781
+ if score2 >= 0.5:
782
+ candidates.append((fm, [rule, rule2], score2))
783
+
784
+ if not candidates:
785
+ return None
786
+
787
+ # Pick best
788
+ best_fm, best_rules, best_score = max(candidates, key=lambda c: c[2])
789
+ rule_names = " ∘ ".join(r.name for r in best_rules)
790
+ reduction = f"{best_fm.name} ∘ {rule_names}"
791
+ expanded_fms = self.expand_rules(best_rules)
792
+ expanded = best_fm.name + " ∘ " + " ∘ ".join(expanded_fms)
793
+
794
+ return MatchResult(
795
+ concept_name="",
796
+ result_type="compositional",
797
+ reduction=reduction,
798
+ reduction_expanded=expanded,
799
+ canonical_analog=f"{best_fm.name} ({best_fm.canonical_reference})",
800
+ genuine_delta=" ∘ ".join(r.name for r in best_rules),
801
+ micro=f"{best_fm.signature.operation}({best_fm.signature.domain} → {best_fm.signature.codomain})",
802
+ meso=best_fm.meso_type or "none",
803
+ macro=best_fm.macro_type or "none",
804
+ confidence=best_score,
805
+ nodes=[CompositionNode(formalism=best_fm, rules=best_rules)],
806
+ match_scores=[best_score],
807
+ )
808
+
809
+ def _apply_rule_signature(self, sig: Signature, rule: CompositionRule) -> Signature:
810
+ """Compute the approximate output signature after applying a rule.
811
+
812
+ Rules modify operation/codomain/objective_family/meso/macro.
813
+ Fields not mentioned in output_signature pass through unchanged.
814
+ """
815
+ out = rule.output_signature
816
+ return Signature(
817
+ operation=out.get("operation", sig.operation),
818
+ domain=sig.domain, # domain typically preserved
819
+ codomain=out.get("codomain", sig.codomain),
820
+ objective_family=out.get("objective_family", sig.objective_family),
821
+ )
822
+
823
+ def _rule_accepts_signature(self, rule: CompositionRule, sig: Signature) -> bool:
824
+ """Check if a rule can be applied to an intermediate signature.
825
+
826
+ This is a looser check than rule.accepts(formalism) since we
827
+ don't have a Formalism object — we check meso/macro constraints.
828
+ """
829
+ constraints = rule.input_constraints
830
+ if not constraints:
831
+ return True
832
+
833
+ req_ids = constraints.get("formalism_ids")
834
+ if req_ids is not None and isinstance(req_ids, list) and req_ids:
835
+ return False # specific formalism constraint can't be satisfied by signature alone
836
+
837
+ # If rule requires specific meso_types and we can't determine them, be permissive
838
+ req_meso = constraints.get("meso_types")
839
+ if req_meso is not None and isinstance(req_meso, list) and req_meso:
840
+ # Without a formalism we can't enforce meso_type constraints tightly
841
+ # For intermediate nodes, be permissive
842
+ pass
843
+
844
+ req_macro = constraints.get("macro_types")
845
+ if req_macro is not None and isinstance(req_macro, list) and req_macro:
846
+ pass # same reasoning
847
+
848
+ return True
849
+
850
+ # ---- Strategy 3: Analogy match ----
851
+
852
+ def _match_analogy(self, sig: Signature, meso: MesoType | None) -> MatchResult | None:
853
+ """Find formalisms with the same meso/macro type but different specifics."""
854
+ if not meso:
855
+ return None
856
+
857
+ candidates = self._by_meso.get(meso, [])
858
+ if not candidates:
859
+ return None
860
+
861
+ # Find the best signature match among same-meso formalisms
862
+ best_score = 0.0
863
+ best_fm: Formalism | None = None
864
+ for fm in candidates:
865
+ score = sig.matches(fm.signature, strict=False)
866
+ if score > best_score:
867
+ best_score = score
868
+ best_fm = fm
869
+
870
+ if best_fm is None or best_score < 0.3:
871
+ return None
872
+
873
+ # Compute the delta: what's different?
874
+ deltas: list[str] = []
875
+ if sig.operation and sig.operation != best_fm.signature.operation:
876
+ deltas.append(f"operation: {best_fm.signature.operation} → {sig.operation}")
877
+ if sig.codomain and sig.codomain != best_fm.signature.codomain:
878
+ deltas.append(f"codomain: {best_fm.signature.codomain} → {sig.codomain}")
879
+ if sig.objective_family and sig.objective_family != best_fm.signature.objective_family:
880
+ deltas.append(f"objective: {best_fm.signature.objective_family} → {sig.objective_family}")
881
+ delta_str = "; ".join(deltas) if deltas else "minor variation"
882
+
883
+ return MatchResult(
884
+ concept_name="",
885
+ result_type="analogy",
886
+ reduction=f"{best_fm.name}",
887
+ reduction_expanded=f"{best_fm.name}",
888
+ canonical_analog=f"{best_fm.name} ({best_fm.canonical_reference})",
889
+ genuine_delta=delta_str,
890
+ micro=f"Shares meso-type '{meso}' with {best_fm.name}",
891
+ meso=meso,
892
+ macro=best_fm.macro_type or "none",
893
+ confidence=best_score,
894
+ nodes=[CompositionNode(formalism=best_fm)],
895
+ match_scores=[best_score],
896
+ )
897
+
898
+ # ---- Batch matching ----
899
+
900
+ def match_paper(self, extraction: dict) -> dict:
901
+ """Match all concepts extracted from a paper.
902
+
903
+ Returns the extraction dict augmented with match results.
904
+ """
905
+ concepts = extraction.get("concepts", [])
906
+ matched = []
907
+ for concept in concepts:
908
+ result = self.match_concept(concept)
909
+ matched.append(result)
910
+
911
+ extraction["_matches"] = [self._result_to_dict(r) for r in matched]
912
+ extraction["_match_summary"] = self._summarize(matched)
913
+ return extraction
914
+
915
+ def _result_to_dict(self, r: MatchResult) -> dict:
916
+ return {
917
+ "concept_name": r.concept_name,
918
+ "result_type": r.result_type,
919
+ "reduction": r.reduction,
920
+ "reduction_expanded": r.reduction_expanded,
921
+ "canonical_analog": r.canonical_analog,
922
+ "genuine_delta": r.genuine_delta,
923
+ "micro": r.micro,
924
+ "meso": r.meso,
925
+ "macro": r.macro,
926
+ "confidence": r.confidence,
927
+ "display": r.display,
928
+ "notes": r.notes,
929
+ }
930
+
931
+ def _summarize(self, results: list[MatchResult]) -> dict:
932
+ identity = sum(1 for r in results if r.result_type == "identity")
933
+ compositional = sum(1 for r in results if r.result_type == "compositional")
934
+ analogy = sum(1 for r in results if r.result_type == "analogy")
935
+ unknown = sum(1 for r in results if r.result_type == "unknown")
936
+ confused = sum(1 for r in results if r.result_type == "confused")
937
+ total = len(results)
938
+
939
+ return {
940
+ "total_concepts": total,
941
+ "identity_reductions": identity,
942
+ "compositional_reductions": compositional,
943
+ "analogy_matches": analogy,
944
+ "unknown": unknown,
945
+ "confused": confused,
946
+ "reduction_rate": (identity + compositional) / total if total else 0,
947
+ }
948
+
949
+
950
+ # ---------------------------------------------------------------------------
951
+ # Convenience: load engine from defaults
952
+ # ---------------------------------------------------------------------------
953
+
954
+ def load_engine(
955
+ formalism_path: Path | None = None,
956
+ rules_path: Path | None = None,
957
+ ) -> MatchEngine:
958
+ """Load the match engine from the default KB files."""
959
+ formalisms = load_formalisms(formalism_path)
960
+ rules = load_composition_rules(rules_path)
961
+ return MatchEngine(formalisms=formalisms, rules=rules)
962
+
963
+
964
+ # ---------------------------------------------------------------------------
965
+ # Self-test: JEPA canonical decomposition
966
+ # ---------------------------------------------------------------------------
967
+
968
+ def _test_jepa():
969
+ """Verify the canonical JEPA decomposition: CCA ∘ neuralize ∘ predict_in_codomain."""
970
+ engine = load_engine()
971
+
972
+ # Simulate an extraction result for JEPA
973
+ jepa_concept = {
974
+ "name": "Joint Embedding Predictive Architecture",
975
+ "is_claimed_novel": True,
976
+ "claimed_novelty_text": "predicts representations in latent space rather than raw inputs",
977
+ "mathematical_operation": "maximize mutual information between joint embeddings of x and y, then predict future embedding from past embedding in the joint space",
978
+ "domain": "vector",
979
+ "codomain": "vector",
980
+ "objective": "maximize I(Z_x; Z_y) — mutual information between embeddings, plus prediction error in latent space",
981
+ "constraints": [],
982
+ "canonical_analog": "Kernel CCA (Bach & Jordan 2002)",
983
+ "deconstructive_move": "binary_overturn",
984
+ "confidence": "high",
985
+ "confidence_rationale": "abstract explicitly describes joint embedding + prediction in latent space",
986
+ "flags": [],
987
+ }
988
+
989
+ result = engine.match_concept(jepa_concept)
990
+ print("=== JEPA Canonical Decomposition Test ===")
991
+ print(f"Concept: {result.concept_name}")
992
+ print(f"Result type: {result.result_type}")
993
+ print(f"Reduction: {result.reduction}")
994
+ print(f"Display: {result.display}")
995
+ print(f"Micro: {result.micro}")
996
+ print(f"Meso: {result.meso}")
997
+ print(f"Macro: {result.macro}")
998
+ print(f"Confidence: {result.confidence}")
999
+ print(f"Canonical analog: {result.canonical_analog}")
1000
+ print(f"Genuine delta: {result.genuine_delta}")
1001
+ if result.notes:
1002
+ print(f"Notes: {result.notes}")
1003
+ print()
1004
+ return result
1005
+
1006
+
1007
+ if __name__ == "__main__":
1008
+ _test_jepa()