Matthew Ford commited on
Commit
c35f284
·
1 Parent(s): 46e1263

character 1.000 diagnosis: artifact — superclass sets identical

Browse files

Diagnose the perfect superclass Jaccard as a collapse/presence artifact: every genre activates every superclass at the 5% threshold, while 26-class distributional cosine remains below 1.0 (0.905 all-labelled, 0.858 for >=3 labels). Add label density, material-level, threshold-sensitivity, and corrected distributional probes. No sourcing, label expansion, dataset assembly, training, or upload.


Former-commit-id: 20258034eadbbd3522dfbbc11014c59ae3297500
Former-commit-id: f12eb2616eabe68b5500d7e8f32d8a0e883c9db1

artifacts/character_grouping_diagnostic_v8.json CHANGED
The diff for this file is too large to render. See raw diff
 
artifacts/character_grouping_diagnostic_v8.md CHANGED
@@ -2,12 +2,65 @@
2
 
3
  Primary snapshot: `v8_2_clause_guard_dominance` (`data/odour_character_labels_v8_2_clause_guard_dominance.jsonl`).
4
 
 
 
 
 
5
  | Axis | classes | mean pairwise Jaccard | delta vs 26 |
6
  | --- | ---: | ---: | ---: |
7
  | 26-class | 26 | 0.793 | baseline |
8
  | six_superclass | 5 | 1.000 | +0.207 |
9
  | eight_superclass | 8 | 1.000 | +0.207 |
10
 
11
- Recommendation: **Do not expand character labels yet. The tested superclass schemes do not materially lower genre overlap versus 26 classes (best 1.000 vs 0.793); character remains non-discriminative on this data.**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- No new sourcing or label expansion was performed.
 
2
 
3
  Primary snapshot: `v8_2_clause_guard_dominance` (`data/odour_character_labels_v8_2_clause_guard_dominance.jsonl`).
4
 
5
+ ## Verdict
6
+
7
+ **Artifact.** The perfect superclass Jaccard is mechanical: after collapse, every genre profile contains every available superclass, so set-presence Jaccard has no room to differ. Distributional class-count metrics are not perfect (26-class all-labelled mean cosine 0.905; 26-class >=3-label mean cosine 0.858), so the prior character-is-non-discriminative verdict is retracted.
8
+
9
  | Axis | classes | mean pairwise Jaccard | delta vs 26 |
10
  | --- | ---: | ---: | ---: |
11
  | 26-class | 26 | 0.793 | baseline |
12
  | six_superclass | 5 | 1.000 | +0.207 |
13
  | eight_superclass | 8 | 1.000 | +0.207 |
14
 
15
+ ## Superclass Sets Compared
16
+
17
+ ### six_superclass
18
+ - `amber_oriental`: animalic_spicy_smoky, balsamic_woody_mossy, edible_gourmand, floral, fresh_citrus_green
19
+ - `citrus_cologne`: animalic_spicy_smoky, balsamic_woody_mossy, edible_gourmand, floral, fresh_citrus_green
20
+ - `floral_woody`: animalic_spicy_smoky, balsamic_woody_mossy, edible_gourmand, floral, fresh_citrus_green
21
+ - `fougere`: animalic_spicy_smoky, balsamic_woody_mossy, edible_gourmand, floral, fresh_citrus_green
22
+ - `wildcard`: animalic_spicy_smoky, balsamic_woody_mossy, edible_gourmand, floral, fresh_citrus_green
23
+
24
+ ### eight_superclass
25
+ - `amber_oriental`: animalic_musk_smoke, aromatic_cool_herbal, balsamic_woody_mossy, floral, fresh_citrus_green_fruit, gourmand_sweet, savory_phenolic, spice
26
+ - `citrus_cologne`: animalic_musk_smoke, aromatic_cool_herbal, balsamic_woody_mossy, floral, fresh_citrus_green_fruit, gourmand_sweet, savory_phenolic, spice
27
+ - `floral_woody`: animalic_musk_smoke, aromatic_cool_herbal, balsamic_woody_mossy, floral, fresh_citrus_green_fruit, gourmand_sweet, savory_phenolic, spice
28
+ - `fougere`: animalic_musk_smoke, aromatic_cool_herbal, balsamic_woody_mossy, floral, fresh_citrus_green_fruit, gourmand_sweet, savory_phenolic, spice
29
+ - `wildcard`: animalic_musk_smoke, aromatic_cool_herbal, balsamic_woody_mossy, floral, fresh_citrus_green_fruit, gourmand_sweet, savory_phenolic, spice
30
+
31
+ ## Label Density
32
+
33
+ | Axis | avg distinct classes / labelled formula | avg labelled materials / labelled formula |
34
+ | --- | ---: | ---: |
35
+ | 26-class | 2.31 | 2.05 |
36
+ | six_superclass | 1.78 | 2.05 |
37
+ | eight_superclass | 1.94 | 2.05 |
38
+
39
+ ## Corrected Distributional Metrics
40
+
41
+ | Axis | mean cosine, all labelled | mean cosine, >=3 classes | material-level mean cosine |
42
+ | --- | ---: | ---: | ---: |
43
+ | 26-class | 0.905 | 0.858 | 0.999 |
44
+ | six_superclass | 0.942 | 0.934 | 1.000 |
45
+ | eight_superclass | 0.926 | 0.900 | 1.000 |
46
+
47
+ Lower cosine means more genre-profile separation. The 26-class axis keeps the strongest separation; collapsing to superclasses weakens it and made presence-Jaccard unusable.
48
+
49
+ ## Threshold Sensitivity
50
+
51
+ | Grouping | activity threshold | mean pairwise Jaccard |
52
+ | --- | ---: | ---: |
53
+ | six_superclass | 5% | 1.000 |
54
+ | six_superclass | 10% | 1.000 |
55
+ | six_superclass | 15% | 0.880 |
56
+ | six_superclass | 20% | 0.900 |
57
+ | eight_superclass | 5% | 1.000 |
58
+ | eight_superclass | 10% | 0.868 |
59
+ | eight_superclass | 15% | 0.886 |
60
+ | eight_superclass | 20% | 0.738 |
61
+
62
+ Recommendation: **Retract the superclass presence-Jaccard conclusion: the 1.000 is a collapse/presence artifact, not proof that character is dead. Keep corrected distributional metrics as the circuit-breaker. Under class-count cosine, 26-class character retains more profile separation than the collapsed schemes (all-labelled mean cosine 0.905; >=3-label mean cosine 0.858; presence-Jaccard baseline 0.793, best collapsed presence-Jaccard 1.000). Recommended direction: character may resume only at 26-class granularity under distributional and well-labelled filters; do not use superclass presence-Jaccard for go/no-go decisions.**
63
+
64
+ Substantivity remains confirmed and publishable independent of this character diagnostic. Next human decision: ship substantivity, resume character only under the corrected 26-class distributional circuit-breaker, or park character for a trajectory-proportion pivot.
65
 
66
+ No new sourcing, label expansion, dataset assembly, training, or upload was performed.
scripts/character_grouping_diagnostic_v8.py CHANGED
@@ -8,6 +8,7 @@ from __future__ import annotations
8
 
9
  from collections import Counter, defaultdict
10
  import json
 
11
  from pathlib import Path
12
  import sys
13
  from typing import Any
@@ -113,6 +114,15 @@ def label_codes(label: dict[str, Any]) -> set[str]:
113
  return {str(code)} if code else set()
114
 
115
 
 
 
 
 
 
 
 
 
 
116
  def transform_labels(labels: dict[str, dict[str, Any]], mapping: dict[str, str]) -> dict[str, dict[str, Any]]:
117
  out = {}
118
  for cas, label in labels.items():
@@ -145,14 +155,212 @@ def formula_character_sets(records: list[dict[str, Any]], labels: dict[str, dict
145
  return by_genre
146
 
147
 
148
- def discrimination_probe(records: list[dict[str, Any]], labels: dict[str, dict[str, Any]], axis_name: str) -> dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  by_genre = formula_character_sets(records, labels)
150
  genre_profiles: dict[str, set[str]] = {}
151
- threshold = 0.05
152
  for genre, sets in sorted(by_genre.items()):
153
  if len(sets) < 10:
154
  continue
155
  counts = Counter(code for s in sets for code in s)
 
156
  genre_profiles[genre] = {code for code, count in counts.items() if count / len(sets) >= threshold}
157
 
158
  pairwise = []
@@ -169,18 +377,40 @@ def discrimination_probe(records: list[dict[str, Any]], labels: dict[str, dict[s
169
  })
170
  mean_jaccard = sum(p["jaccard"] for p in pairwise) / len(pairwise) if pairwise else None
171
  return {
172
- "method": f"per-genre formula-level set Jaccard over {axis_name}; class active if present in >=5% of labelled formulas for genre",
 
 
 
 
173
  "formula_labelled_by_genre": {k: len(v) for k, v in by_genre.items()},
 
174
  "genre_profiles": {k: sorted(v) for k, v in genre_profiles.items()},
175
  "pairwise": pairwise,
176
  "mean_pairwise_jaccard": mean_jaccard,
177
  }
178
 
179
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  def evaluate_snapshot(name: str, path: Path, records: list[dict[str, Any]]) -> dict[str, Any]:
181
  rows = load_jsonl(path)
182
  labels = {row["cas"]: row for row in rows}
183
  base = discrimination_probe(records, labels, "26-class character labels")
 
 
 
 
 
184
  group_results = {}
185
  for grouping_name, spec in GROUPINGS.items():
186
  grouped = transform_labels(labels, spec["mapping"])
@@ -188,7 +418,13 @@ def evaluate_snapshot(name: str, path: Path, records: list[dict[str, Any]]) -> d
188
  "justification": spec["justification"],
189
  "n_superclasses": len({v for v in spec["mapping"].values() if v != "carrier"}),
190
  "class_to_superclass": spec["mapping"],
 
191
  "discrimination_precheck": discrimination_probe(records, grouped, grouping_name),
 
 
 
 
 
192
  }
193
  best_group_name = min(
194
  group_results,
@@ -203,9 +439,15 @@ def evaluate_snapshot(name: str, path: Path, records: list[dict[str, Any]]) -> d
203
  "label_snapshot": name,
204
  "label_path": str(path.relative_to(ROOT)),
205
  "label_count": len(rows),
 
206
  "twenty_six_class": base,
 
 
 
 
207
  "groupings": group_results,
208
- "best_grouping": best_group_name,
 
209
  "best_grouping_mean_pairwise_jaccard": best_j,
210
  "materially_better_than_26_class": material_improvement,
211
  }
@@ -214,15 +456,16 @@ def evaluate_snapshot(name: str, path: Path, records: list[dict[str, Any]]) -> d
214
  def recommendation(primary: dict[str, Any]) -> str:
215
  base_j = primary["twenty_six_class"]["mean_pairwise_jaccard"]
216
  best_j = primary["best_grouping_mean_pairwise_jaccard"]
217
- if primary["materially_better_than_26_class"]:
218
- return (
219
- f"Collapse character target to {primary['best_grouping']} before any label expansion; "
220
- f"mean Jaccard improves from {base_j:.3f} to {best_j:.3f}."
221
- )
222
  return (
223
- "Do not expand character labels yet. The tested superclass schemes do not materially lower "
224
- f"genre overlap versus 26 classes (best {best_j:.3f} vs {base_j:.3f}); character remains "
225
- "non-discriminative on this data."
 
 
 
 
226
  )
227
 
228
 
@@ -230,23 +473,97 @@ def write_markdown(report: dict[str, Any]) -> None:
230
  primary = report["primary_snapshot_result"]
231
  rows = []
232
  base_j = primary["twenty_six_class"]["mean_pairwise_jaccard"]
 
 
233
  rows.append(f"| 26-class | 26 | {base_j:.3f} | baseline |")
234
  for name, result in primary["groupings"].items():
235
  j = result["discrimination_precheck"]["mean_pairwise_jaccard"]
236
  delta = j - base_j
237
  rows.append(f"| {name} | {result['n_superclasses']} | {j:.3f} | {delta:+.3f} |")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  md = [
239
  "# Character grouping diagnostic v8",
240
  "",
241
  f"Primary snapshot: `{primary['label_snapshot']}` (`{primary['label_path']}`).",
242
  "",
 
 
 
 
 
 
 
 
243
  "| Axis | classes | mean pairwise Jaccard | delta vs 26 |",
244
  "| --- | ---: | ---: | ---: |",
245
  *rows,
246
  "",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  f"Recommendation: **{report['recommendation']}**",
248
  "",
249
- "No new sourcing or label expansion was performed.",
 
 
 
 
250
  ]
251
  OUT_MD.write_text("\n".join(md) + "\n", encoding="utf-8")
252
 
 
8
 
9
  from collections import Counter, defaultdict
10
  import json
11
+ import math
12
  from pathlib import Path
13
  import sys
14
  from typing import Any
 
114
  return {str(code)} if code else set()
115
 
116
 
117
+ def label_confidence(label: dict[str, Any]) -> float:
118
+ """Return available label confidence, defaulting to 1 for source-derived labels."""
119
+ for key in ("confidence", "label_confidence", "score"):
120
+ value = label.get(key)
121
+ if isinstance(value, int | float):
122
+ return float(value)
123
+ return 1.0
124
+
125
+
126
  def transform_labels(labels: dict[str, dict[str, Any]], mapping: dict[str, str]) -> dict[str, dict[str, Any]]:
127
  out = {}
128
  for cas, label in labels.items():
 
155
  return by_genre
156
 
157
 
158
+ def formula_character_rows(records: list[dict[str, Any]], labels: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:
159
+ rows = []
160
+ for record in records:
161
+ if record.get("is_control"):
162
+ continue
163
+ genre = record.get("genre") or record.get("metadata", {}).get("generation_strategy") or "unknown"
164
+ formula_id = record.get("formula_id") or record.get("metadata", {}).get("formula_id")
165
+ classes: set[str] = set()
166
+ weighted_classes: Counter[str] = Counter()
167
+ material_classes: Counter[str] = Counter()
168
+ labelled_materials = set()
169
+ for comp in census.formula_components(record):
170
+ cas = str(comp.get("cas"))
171
+ label = labels.get(cas)
172
+ if not label:
173
+ continue
174
+ codes = {code for code in label_codes(label) if code not in {"Z", "carrier"}}
175
+ if not codes:
176
+ continue
177
+ labelled_materials.add(cas)
178
+ confidence = label_confidence(label)
179
+ for code in codes:
180
+ classes.add(code)
181
+ weighted_classes[code] += confidence
182
+ material_classes[code] += 1
183
+ if classes:
184
+ rows.append({
185
+ "genre": genre,
186
+ "formula_id": formula_id,
187
+ "classes": classes,
188
+ "weighted_classes": weighted_classes,
189
+ "material_classes": material_classes,
190
+ "labelled_material_count": len(labelled_materials),
191
+ "label_class_count": len(classes),
192
+ })
193
+ return rows
194
+
195
+
196
+ def label_density(records: list[dict[str, Any]], labels: dict[str, dict[str, Any]], axis_name: str) -> dict[str, Any]:
197
+ rows = formula_character_rows(records, labels)
198
+ by_genre: dict[str, list[dict[str, Any]]] = defaultdict(list)
199
+ for row in rows:
200
+ by_genre[row["genre"]].append(row)
201
+ per_genre = {}
202
+ for genre, genre_rows in sorted(by_genre.items()):
203
+ per_genre[genre] = {
204
+ "labelled_formulas": len(genre_rows),
205
+ "avg_distinct_classes_per_labelled_formula": sum(r["label_class_count"] for r in genre_rows) / len(genre_rows),
206
+ "avg_labelled_materials_per_labelled_formula": sum(r["labelled_material_count"] for r in genre_rows) / len(genre_rows),
207
+ "formulas_with_ge_2_classes": sum(1 for r in genre_rows if r["label_class_count"] >= 2),
208
+ "formulas_with_ge_3_classes": sum(1 for r in genre_rows if r["label_class_count"] >= 3),
209
+ }
210
+ return {
211
+ "axis": axis_name,
212
+ "labelled_formulas": len(rows),
213
+ "avg_distinct_classes_per_labelled_formula": sum(r["label_class_count"] for r in rows) / len(rows) if rows else None,
214
+ "avg_labelled_materials_per_labelled_formula": sum(r["labelled_material_count"] for r in rows) / len(rows) if rows else None,
215
+ "per_genre": per_genre,
216
+ }
217
+
218
+
219
+ def cosine_similarity(left: dict[str, float], right: dict[str, float], codes: list[str]) -> float | None:
220
+ a = [left.get(code, 0.0) for code in codes]
221
+ b = [right.get(code, 0.0) for code in codes]
222
+ left_norm = math.sqrt(sum(v * v for v in a))
223
+ right_norm = math.sqrt(sum(v * v for v in b))
224
+ if not left_norm or not right_norm:
225
+ return None
226
+ return sum(x * y for x, y in zip(a, b)) / (left_norm * right_norm)
227
+
228
+
229
+ def js_divergence(left: dict[str, float], right: dict[str, float], codes: list[str]) -> float | None:
230
+ left_total = sum(left.get(code, 0.0) for code in codes)
231
+ right_total = sum(right.get(code, 0.0) for code in codes)
232
+ if not left_total or not right_total:
233
+ return None
234
+ p = [left.get(code, 0.0) / left_total for code in codes]
235
+ q = [right.get(code, 0.0) / right_total for code in codes]
236
+ m = [(x + y) / 2 for x, y in zip(p, q)]
237
+
238
+ def kl(a: list[float], b: list[float]) -> float:
239
+ return sum(x * math.log2(x / y) for x, y in zip(a, b) if x and y)
240
+
241
+ return 0.5 * kl(p, m) + 0.5 * kl(q, m)
242
+
243
+
244
+ def pairwise_vector_metrics(vectors: dict[str, Counter[str]], codes: list[str]) -> dict[str, Any]:
245
+ pairwise = []
246
+ genres = sorted(vectors)
247
+ for i, left in enumerate(genres):
248
+ for right in genres[i + 1:]:
249
+ cosine = cosine_similarity(vectors[left], vectors[right], codes)
250
+ jsd = js_divergence(vectors[left], vectors[right], codes)
251
+ pairwise.append({
252
+ "left": left,
253
+ "right": right,
254
+ "cosine_similarity": cosine,
255
+ "js_divergence_bits": jsd,
256
+ })
257
+ cosines = [p["cosine_similarity"] for p in pairwise if p["cosine_similarity"] is not None]
258
+ jsds = [p["js_divergence_bits"] for p in pairwise if p["js_divergence_bits"] is not None]
259
+ return {
260
+ "pairwise": pairwise,
261
+ "mean_pairwise_cosine_similarity": sum(cosines) / len(cosines) if cosines else None,
262
+ "min_pairwise_cosine_similarity": min(cosines) if cosines else None,
263
+ "max_pairwise_cosine_similarity": max(cosines) if cosines else None,
264
+ "mean_pairwise_js_divergence_bits": sum(jsds) / len(jsds) if jsds else None,
265
+ "max_pairwise_js_divergence_bits": max(jsds) if jsds else None,
266
+ }
267
+
268
+
269
+ def distributional_probe(
270
+ records: list[dict[str, Any]],
271
+ labels: dict[str, dict[str, Any]],
272
+ axis_name: str,
273
+ min_classes_per_formula: int = 1,
274
+ weighted: bool = False,
275
+ ) -> dict[str, Any]:
276
+ rows = [row for row in formula_character_rows(records, labels) if row["label_class_count"] >= min_classes_per_formula]
277
+ codes = sorted({code for label in labels.values() for code in label_codes(label) if code not in {"Z", "carrier"}})
278
+ vectors: dict[str, Counter[str]] = defaultdict(Counter)
279
+ kept_by_genre = Counter()
280
+ for row in rows:
281
+ kept_by_genre[row["genre"]] += 1
282
+ vectors[row["genre"]].update(row["weighted_classes"] if weighted else row["material_classes"])
283
+ metrics = pairwise_vector_metrics(vectors, codes)
284
+ return {
285
+ "method": (
286
+ f"per-genre class-count vector cosine/JS over {axis_name}; "
287
+ f"formulas require >= {min_classes_per_formula} distinct character classes; "
288
+ f"{'label-confidence weighted' if weighted else 'material occurrence counted'}"
289
+ ),
290
+ "kept_labelled_formulas_by_genre": dict(sorted(kept_by_genre.items())),
291
+ "class_count_vectors_by_genre": {
292
+ genre: {code: vectors[genre].get(code, 0) for code in codes if vectors[genre].get(code, 0)}
293
+ for genre in sorted(vectors)
294
+ },
295
+ **metrics,
296
+ }
297
+
298
+
299
+ def material_level_probe(records: list[dict[str, Any]], labels: dict[str, dict[str, Any]], axis_name: str) -> dict[str, Any]:
300
+ codes = sorted({code for label in labels.values() for code in label_codes(label) if code not in {"Z", "carrier"}})
301
+ material_classes_by_genre: dict[str, dict[str, set[str]]] = defaultdict(dict)
302
+ for record in records:
303
+ if record.get("is_control"):
304
+ continue
305
+ genre = record.get("genre") or record.get("metadata", {}).get("generation_strategy") or "unknown"
306
+ for comp in census.formula_components(record):
307
+ cas = str(comp.get("cas"))
308
+ label = labels.get(cas)
309
+ if not label:
310
+ continue
311
+ classes = {code for code in label_codes(label) if code not in {"Z", "carrier"}}
312
+ if classes:
313
+ material_classes_by_genre[genre][cas] = classes
314
+ presence_profiles = {
315
+ genre: sorted({code for classes in materials.values() for code in classes})
316
+ for genre, materials in material_classes_by_genre.items()
317
+ }
318
+ pairwise_jaccard = []
319
+ genres = sorted(presence_profiles)
320
+ for i, left in enumerate(genres):
321
+ for right in genres[i + 1:]:
322
+ a, b = set(presence_profiles[left]), set(presence_profiles[right])
323
+ pairwise_jaccard.append({
324
+ "left": left,
325
+ "right": right,
326
+ "jaccard": len(a & b) / max(1, len(a | b)),
327
+ "intersection": sorted(a & b),
328
+ "union": sorted(a | b),
329
+ })
330
+ vectors = {}
331
+ for genre, materials in material_classes_by_genre.items():
332
+ vectors[genre] = Counter(code for classes in materials.values() for code in classes)
333
+ metrics = pairwise_vector_metrics(vectors, codes)
334
+ return {
335
+ "method": f"unique-material-level character overlap for {axis_name}, not formula-level aggregation",
336
+ "unique_labelled_materials_by_genre": {genre: len(materials) for genre, materials in sorted(material_classes_by_genre.items())},
337
+ "presence_profiles_by_genre": dict(sorted(presence_profiles.items())),
338
+ "pairwise_presence_jaccard": pairwise_jaccard,
339
+ "mean_pairwise_presence_jaccard": (
340
+ sum(p["jaccard"] for p in pairwise_jaccard) / len(pairwise_jaccard) if pairwise_jaccard else None
341
+ ),
342
+ "class_count_vectors_by_genre": {
343
+ genre: {code: vectors[genre].get(code, 0) for code in codes if vectors[genre].get(code, 0)}
344
+ for genre in sorted(vectors)
345
+ },
346
+ **metrics,
347
+ }
348
+
349
+
350
+ def discrimination_probe(
351
+ records: list[dict[str, Any]],
352
+ labels: dict[str, dict[str, Any]],
353
+ axis_name: str,
354
+ threshold: float = 0.05,
355
+ ) -> dict[str, Any]:
356
  by_genre = formula_character_sets(records, labels)
357
  genre_profiles: dict[str, set[str]] = {}
358
+ prevalence_by_genre = {}
359
  for genre, sets in sorted(by_genre.items()):
360
  if len(sets) < 10:
361
  continue
362
  counts = Counter(code for s in sets for code in s)
363
+ prevalence_by_genre[genre] = {code: count / len(sets) for code, count in sorted(counts.items())}
364
  genre_profiles[genre] = {code for code, count in counts.items() if count / len(sets) >= threshold}
365
 
366
  pairwise = []
 
377
  })
378
  mean_jaccard = sum(p["jaccard"] for p in pairwise) / len(pairwise) if pairwise else None
379
  return {
380
+ "method": (
381
+ f"per-genre formula-level set Jaccard over {axis_name}; "
382
+ f"class active if present in >={threshold:.0%} of labelled formulas for genre"
383
+ ),
384
+ "activity_threshold": threshold,
385
  "formula_labelled_by_genre": {k: len(v) for k, v in by_genre.items()},
386
+ "class_prevalence_by_genre": prevalence_by_genre,
387
  "genre_profiles": {k: sorted(v) for k, v in genre_profiles.items()},
388
  "pairwise": pairwise,
389
  "mean_pairwise_jaccard": mean_jaccard,
390
  }
391
 
392
 
393
+ def threshold_sensitivity_probe(records: list[dict[str, Any]], labels: dict[str, dict[str, Any]], axis_name: str) -> list[dict[str, Any]]:
394
+ rows = []
395
+ for threshold in (0.05, 0.10, 0.15, 0.20):
396
+ probe = discrimination_probe(records, labels, axis_name, threshold=threshold)
397
+ rows.append({
398
+ "threshold": threshold,
399
+ "mean_pairwise_jaccard": probe["mean_pairwise_jaccard"],
400
+ "genre_profiles": probe["genre_profiles"],
401
+ })
402
+ return rows
403
+
404
+
405
  def evaluate_snapshot(name: str, path: Path, records: list[dict[str, Any]]) -> dict[str, Any]:
406
  rows = load_jsonl(path)
407
  labels = {row["cas"]: row for row in rows}
408
  base = discrimination_probe(records, labels, "26-class character labels")
409
+ base_density = label_density(records, labels, "26-class character labels")
410
+ base_distribution = distributional_probe(records, labels, "26-class character labels")
411
+ base_well_labelled_distribution = distributional_probe(records, labels, "26-class character labels", min_classes_per_formula=3)
412
+ base_confidence_distribution = distributional_probe(records, labels, "26-class character labels", min_classes_per_formula=2, weighted=True)
413
+ base_material = material_level_probe(records, labels, "26-class character labels")
414
  group_results = {}
415
  for grouping_name, spec in GROUPINGS.items():
416
  grouped = transform_labels(labels, spec["mapping"])
 
418
  "justification": spec["justification"],
419
  "n_superclasses": len({v for v in spec["mapping"].values() if v != "carrier"}),
420
  "class_to_superclass": spec["mapping"],
421
+ "label_density": label_density(records, grouped, grouping_name),
422
  "discrimination_precheck": discrimination_probe(records, grouped, grouping_name),
423
+ "threshold_sensitivity": threshold_sensitivity_probe(records, grouped, grouping_name),
424
+ "material_level_probe": material_level_probe(records, grouped, grouping_name),
425
+ "distributional_probe": distributional_probe(records, grouped, grouping_name),
426
+ "well_labelled_distributional_probe_ge3": distributional_probe(records, grouped, grouping_name, min_classes_per_formula=3),
427
+ "confidence_weighted_distributional_probe_ge2": distributional_probe(records, grouped, grouping_name, min_classes_per_formula=2, weighted=True),
428
  }
429
  best_group_name = min(
430
  group_results,
 
439
  "label_snapshot": name,
440
  "label_path": str(path.relative_to(ROOT)),
441
  "label_count": len(rows),
442
+ "label_density_26_class": base_density,
443
  "twenty_six_class": base,
444
+ "material_level_probe_26_class": base_material,
445
+ "distributional_probe_26_class": base_distribution,
446
+ "well_labelled_distributional_probe_26_class_ge3": base_well_labelled_distribution,
447
+ "confidence_weighted_distributional_probe_26_class_ge2": base_confidence_distribution,
448
  "groupings": group_results,
449
+ "best_grouping": best_group_name if material_improvement else None,
450
+ "lowest_jaccard_grouping": best_group_name,
451
  "best_grouping_mean_pairwise_jaccard": best_j,
452
  "materially_better_than_26_class": material_improvement,
453
  }
 
456
  def recommendation(primary: dict[str, Any]) -> str:
457
  base_j = primary["twenty_six_class"]["mean_pairwise_jaccard"]
458
  best_j = primary["best_grouping_mean_pairwise_jaccard"]
459
+ base_cos = primary["distributional_probe_26_class"]["mean_pairwise_cosine_similarity"]
460
+ base_ge3_cos = primary["well_labelled_distributional_probe_26_class_ge3"]["mean_pairwise_cosine_similarity"]
 
 
 
461
  return (
462
+ "Retract the superclass presence-Jaccard conclusion: the 1.000 is a collapse/presence artifact, "
463
+ f"not proof that character is dead. Keep corrected distributional metrics as the circuit-breaker. "
464
+ f"Under class-count cosine, 26-class character retains more profile separation than the collapsed "
465
+ f"schemes (all-labelled mean cosine {base_cos:.3f}; >=3-label mean cosine {base_ge3_cos:.3f}; "
466
+ f"presence-Jaccard baseline {base_j:.3f}, best collapsed presence-Jaccard {best_j:.3f}). "
467
+ "Recommended direction: character may resume only at 26-class granularity under distributional "
468
+ "and well-labelled filters; do not use superclass presence-Jaccard for go/no-go decisions."
469
  )
470
 
471
 
 
473
  primary = report["primary_snapshot_result"]
474
  rows = []
475
  base_j = primary["twenty_six_class"]["mean_pairwise_jaccard"]
476
+ base_cos = primary["distributional_probe_26_class"]["mean_pairwise_cosine_similarity"]
477
+ base_ge3_cos = primary["well_labelled_distributional_probe_26_class_ge3"]["mean_pairwise_cosine_similarity"]
478
  rows.append(f"| 26-class | 26 | {base_j:.3f} | baseline |")
479
  for name, result in primary["groupings"].items():
480
  j = result["discrimination_precheck"]["mean_pairwise_jaccard"]
481
  delta = j - base_j
482
  rows.append(f"| {name} | {result['n_superclasses']} | {j:.3f} | {delta:+.3f} |")
483
+ density = primary["label_density_26_class"]
484
+ density_rows = [
485
+ "| 26-class | "
486
+ f"{density['avg_distinct_classes_per_labelled_formula']:.2f} | "
487
+ f"{density['avg_labelled_materials_per_labelled_formula']:.2f} |"
488
+ ]
489
+ for name, result in primary["groupings"].items():
490
+ d = result["label_density"]
491
+ density_rows.append(
492
+ f"| {name} | {d['avg_distinct_classes_per_labelled_formula']:.2f} | "
493
+ f"{d['avg_labelled_materials_per_labelled_formula']:.2f} |"
494
+ )
495
+ superclass_sets = []
496
+ for name, result in primary["groupings"].items():
497
+ profiles = result["discrimination_precheck"]["genre_profiles"]
498
+ superclass_sets.append(f"### {name}")
499
+ for genre, classes in sorted(profiles.items()):
500
+ superclass_sets.append(f"- `{genre}`: {', '.join(classes)}")
501
+ superclass_sets.append("")
502
+ metric_rows = [
503
+ "| 26-class | "
504
+ f"{primary['distributional_probe_26_class']['mean_pairwise_cosine_similarity']:.3f} | "
505
+ f"{primary['well_labelled_distributional_probe_26_class_ge3']['mean_pairwise_cosine_similarity']:.3f} | "
506
+ f"{primary['material_level_probe_26_class']['mean_pairwise_cosine_similarity']:.3f} |",
507
+ ]
508
+ for name, result in primary["groupings"].items():
509
+ metric_rows.append(
510
+ f"| {name} | "
511
+ f"{result['distributional_probe']['mean_pairwise_cosine_similarity']:.3f} | "
512
+ f"{result['well_labelled_distributional_probe_ge3']['mean_pairwise_cosine_similarity']:.3f} | "
513
+ f"{result['material_level_probe']['mean_pairwise_cosine_similarity']:.3f} |"
514
+ )
515
+ threshold_rows = []
516
+ for name, result in primary["groupings"].items():
517
+ for row in result["threshold_sensitivity"]:
518
+ threshold_rows.append(f"| {name} | {row['threshold']:.0%} | {row['mean_pairwise_jaccard']:.3f} |")
519
  md = [
520
  "# Character grouping diagnostic v8",
521
  "",
522
  f"Primary snapshot: `{primary['label_snapshot']}` (`{primary['label_path']}`).",
523
  "",
524
+ "## Verdict",
525
+ "",
526
+ "**Artifact.** The perfect superclass Jaccard is mechanical: after collapse, every genre profile "
527
+ "contains every available superclass, so set-presence Jaccard has no room to differ. Distributional "
528
+ f"class-count metrics are not perfect (26-class all-labelled mean cosine {base_cos:.3f}; "
529
+ f"26-class >=3-label mean cosine {base_ge3_cos:.3f}), so the prior character-is-non-discriminative "
530
+ "verdict is retracted.",
531
+ "",
532
  "| Axis | classes | mean pairwise Jaccard | delta vs 26 |",
533
  "| --- | ---: | ---: | ---: |",
534
  *rows,
535
  "",
536
+ "## Superclass Sets Compared",
537
+ "",
538
+ *superclass_sets,
539
+ "## Label Density",
540
+ "",
541
+ "| Axis | avg distinct classes / labelled formula | avg labelled materials / labelled formula |",
542
+ "| --- | ---: | ---: |",
543
+ *density_rows,
544
+ "",
545
+ "## Corrected Distributional Metrics",
546
+ "",
547
+ "| Axis | mean cosine, all labelled | mean cosine, >=3 classes | material-level mean cosine |",
548
+ "| --- | ---: | ---: | ---: |",
549
+ *metric_rows,
550
+ "",
551
+ "Lower cosine means more genre-profile separation. The 26-class axis keeps the strongest separation; "
552
+ "collapsing to superclasses weakens it and made presence-Jaccard unusable.",
553
+ "",
554
+ "## Threshold Sensitivity",
555
+ "",
556
+ "| Grouping | activity threshold | mean pairwise Jaccard |",
557
+ "| --- | ---: | ---: |",
558
+ *threshold_rows,
559
+ "",
560
  f"Recommendation: **{report['recommendation']}**",
561
  "",
562
+ "Substantivity remains confirmed and publishable independent of this character diagnostic. "
563
+ "Next human decision: ship substantivity, resume character only under the corrected 26-class "
564
+ "distributional circuit-breaker, or park character for a trajectory-proportion pivot.",
565
+ "",
566
+ "No new sourcing, label expansion, dataset assembly, training, or upload was performed.",
567
  ]
568
  OUT_MD.write_text("\n".join(md) + "\n", encoding="utf-8")
569