#!/usr/bin/env python3 """Optimize substantivity thresholds against Poucher ground truth, then evaluate dataset coverage and agreement.""" import json import numpy as np from collections import defaultdict # Load true Poucher ground truth (not the merged file) with open("data/poucher_tier_lookup_expanded.json") as f: poucher_data = json.load(f) poucher_tiers = poucher_data["cas_to_tier"] # Load GoodScents substantivity data with open("data/goodscents_substantivity.json") as f: gs_data = json.load(f) cas_to_subst = gs_data["cas_to_substantivity_hours"] # Get overlap: CAS with both Poucher tier and GoodScents substantivity overlap_cas = set(poucher_tiers.keys()).intersection(set(cas_to_subst.keys())) print(f"Overlap (Poucher tier + GS substantivity): {len(overlap_cas)} CAS") # Show the actual substantivity distributions by Poucher tier tier_subst = defaultdict(list) for cas in overlap_cas: tier = poucher_tiers[cas] tier_subst[tier].append(cas_to_subst[cas]) print(f"\nSubstantivity by Poucher tier:") for tier in ["top", "mid", "base"]: vals = np.array(tier_subst[tier]) if len(vals) > 0: print(f" {tier:5s}: n={len(vals):3d}, median={np.median(vals):6.0f}h, " f"P25={np.percentile(vals,25):6.0f}h, P75={np.percentile(vals,75):6.0f}h, " f"min={vals.min():.0f}, max={vals.max():.0f}") # --- Optimize thresholds via grid search --- # We want to find (t1, t2) such that: # subst < t1 → top # t1 <= subst < t2 → mid # subst >= t2 → base # that maximizes Cohen's kappa against Poucher tiers from sklearn.metrics import cohen_kappa_score best_kappa = -2 best_t1 = None best_t2 = None # Use the observed range all_subst = sorted(set(cas_to_subst[c] for c in overlap_cas)) # Grid search over threshold pairs for t1 in np.arange(1, 500, 1): for t2 in np.arange(t1 + 1, 900, 5): pred = [] true = [] for cas in overlap_cas: s = cas_to_subst[cas] if s < t1: pred_tier = "top" elif s < t2: pred_tier = "mid" else: pred_tier = "base" pred.append(pred_tier) true.append(poucher_tiers[cas]) kappa = cohen_kappa_score(true, pred) if kappa > best_kappa: best_kappa = kappa best_t1 = t1 best_t2 = t2 print(f"\n=== Optimal thresholds ===") print(f" Top: < {best_t1:.0f}h") print(f" Mid: {best_t1:.0f}h - {best_t2:.0f}h") print(f" Base: >= {best_t2:.0f}h") print(f" Best kappa: {best_kappa:.3f}") # Show confusion matrix at optimal thresholds tier_to_idx = {"top": 0, "mid": 1, "base": 2} matrix = np.zeros((3, 3), dtype=int) for cas in overlap_cas: s = cas_to_subst[cas] if s < best_t1: pred = "top" elif s < best_t2: pred = "mid" else: pred = "base" true = poucher_tiers[cas] matrix[tier_to_idx[true], tier_to_idx[pred]] += 1 print(f"\nConfusion at optimal thresholds (rows=Poucher, cols=GS, n={len(overlap_cas)}):") print(f" {'':12s} {'GS-top':>10s} {'GS-mid':>10s} {'GS-base':>10s} {'Total':>10s}") for i, tier in enumerate(["top", "mid", "base"]): row = matrix[i] print(f" Poucher-{tier:5s} {row[0]:>10d} {row[1]:>10d} {row[2]:>10d} {sum(row):>10d}") # --- Apply optimal thresholds to full dataset --- cas_to_tier_optimal = {} for cas, subst in cas_to_subst.items(): if subst < best_t1: cas_to_tier_optimal[cas] = "top" elif subst < best_t2: cas_to_tier_optimal[cas] = "mid" else: cas_to_tier_optimal[cas] = "base" # --- Build merged lookup --- # Poucher is ground truth, override GS tiers where both exist merged_tiers = dict(cas_to_tier_optimal) for cas, tier in poucher_tiers.items(): merged_tiers[cas] = tier # Always prefer Poucher # Dataset coverage with open("data/empirical_dataset_v8.jsonl") as f: records = [json.loads(l) for l in f] dataset_cas = set() for r in records: if r.get("is_control"): continue for comp in r.get("formula", []): cas = comp.get("cas", "") if cas: dataset_cas.add(cas) matched = dataset_cas.intersection(set(merged_tiers.keys())) print(f"\n=== Final Coverage ===") print(f"Dataset CAS: {len(dataset_cas)}") print(f"With tier labels: {len(matched)} ({100*len(matched)/len(dataset_cas):.1f}%)") tier_dist = defaultdict(int) for cas in matched: tier_dist[merged_tiers[cas]] += 1 for t in ["top", "mid", "base"]: print(f" {t}: {tier_dist[t]} ({100*tier_dist[t]/len(matched):.1f}%)") # Save the raw substantivity data output = { "cas_to_substantivity_hours": {k: round(v, 2) for k, v in sorted(cas_to_subst.items())}, "total_cas": len(cas_to_subst), } with open("data/goodscents_substantivity.json", "w") as f: json.dump(output, f, indent=2) print(f"\nSaved to data/goodscents_substantivity.json") # Save the optimized tier mapping for use as a fallback source with open("data/goodscents_substantivity_tiers.json", "w") as f: json.dump({ "total_cas": len(cas_to_tier_optimal), "thresholds": {"top_max": float(best_t1), "mid_max": float(best_t2)}, "cas_to_tier": {k: v for k, v in sorted(cas_to_tier_optimal.items())}, }, f, indent=2) print(f"Saved to data/goodscents_substantivity_tiers.json") # Also produce a transient diagnostic tier mapping using Poucher-optimized thresholds # (these are the defaults used before optimization; they are NOT final) cas_to_tier_gs = {} for cas, subst in cas_to_subst.items(): if subst < 15: cas_to_tier_gs[cas] = "top" elif subst < 241: cas_to_tier_gs[cas] = "mid" else: cas_to_tier_gs[cas] = "base" # Merge with Poucher tiers (Poucher is ground truth, takes priority) merged_tiers = dict(cas_to_tier_gs) for cas, tier in poucher_tiers.items(): merged_tiers[cas] = tier with open("data/perfumer_tier_lookup.json", "w") as f: json.dump({k: v for k, v in sorted(merged_tiers.items())}, f, indent=2) print(f"Merged tier lookup: {len(merged_tiers)} CAS")