zeechimp's picture
Create example.py
03a6c4c verified
Raw History Blame Contribute Delete
6.71 kB
#!/usr/bin/env python3
"""
example.py β€” Usage demonstrations for hv_chemical_classifier.
NumPy only.
"""
import numpy as np
from hv_chemical_classifier import (
Hypothesis, EvidenceChannel, ChemicalClassifier,
adaptive_tempering, true_voi, correlation_discount,
make_paleo_scenario,
)
def demo_basic():
print("=" * 72)
print("Demo 1 β€” basic classification")
print("=" * 72)
print()
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
# Observe a strong sauropod-like signal
clf.observe('femur_morphology', 2)
clf.observe('tooth_shape', 0)
clf.observe('bone_density', 2)
r = clf.classify()
print(f" Winner: {r['winner']}")
print(f" Posterior: " +
", ".join(f"{h.name}={p:.3f}"
for h, p in zip(clf.hypotheses, r['posterior'])))
print()
def demo_ambivalence():
print("=" * 72)
print("Demo 2 β€” honest refusal via multi-seed bistability")
print("=" * 72)
print()
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
# Weak, ambiguous signal
clf.observe('femur_morphology', 1)
clf.observe('tooth_shape', 1)
r = clf.classify_multiseed(n_seeds=20, n_steps=500)
print(f" Verdict: {r['verdict']}")
print(f" Ambiguous: {r['ambiguous']}")
print(f" Winner counts: {r['winner_counts']}")
print()
def demo_tempering():
print("=" * 72)
print("Demo 3 β€” adaptive tempering")
print("=" * 72)
print()
# Sharp vs weak specimen
for label, obs in [
('sharp', {'femur_morphology': 2, 'tooth_shape': 0,
'bone_density': 2, 'cortical_thickness': 2}),
('weak', {'femur_morphology': 1, 'tooth_shape': 1}),
]:
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
for k, v in obs.items():
clf.observe(k, v)
log_lik = clf.raw_log_likelihoods()
alpha = adaptive_tempering(log_lik)
r = clf.classify(apply_tempering=True)
print(f" {label:<8s} Ξ± = {alpha:.3f} winner = {r['winner']}")
print()
def demo_discount():
print("=" * 72)
print("Demo 4 β€” correlation discount")
print("=" * 72)
print()
for label, group in [('independent', None), ('correlated', 'group')]:
hyp = [Hypothesis('A', prior=0.5), Hypothesis('B', prior=0.5)]
channels = [
EvidenceChannel(f'ch{i}',
np.array([[0.6, 0.4], [0.4, 0.6]]),
cost=1.0, correlation_group=group)
for i in range(5)
]
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in channels:
clf.add_channel(c)
for c in channels:
clf.observe(c.name, 1)
log_lik = clf.raw_log_likelihoods(
apply_discount=(label == 'correlated'))
raw_odds = float(log_lik[1] - log_lik[0])
print(f" {label:<12s} raw log-odds = {raw_odds:+.4f}")
print()
def demo_voi():
print("=" * 72)
print("Demo 5 β€” true VOI (which channel to run next?)")
print("=" * 72)
print()
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
# Partial evidence
clf.observe('femur_morphology', 1)
a = clf.effective_rates()
clf.reset_concentrations()
traj, _ = clf.evolve(a, 300, 0.02)
p = traj[-1] / traj[-1].sum()
candidates = ['tooth_shape', 'bone_density',
'cortical_thickness', 'joint_geometry']
voi = true_voi(clf, p, candidates)
print(f" Current posterior: " +
", ".join(f"{h.name}={p[i]:.3f}"
for i, h in enumerate(clf.hypotheses)))
print()
print(f" {'channel':<22s} {'VOI/cost':>10s}")
print(" " + "-" * 36)
for name, r in sorted(voi.items(), key=lambda x: -x[1]['voi_per_cost']):
print(f" {name:<22s} {r['voi_per_cost']:>10.5f}")
print()
def demo_messenger():
print("=" * 72)
print("Demo 6 β€” pairwise messenger as confidence signal")
print("=" * 72)
print()
# Scenario: clear winner
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
clf.observe('femur_morphology', 2)
clf.observe('tooth_shape', 0)
clf.observe('bone_density', 2)
a = clf.effective_rates()
clf.reset_concentrations()
traj, M = clf.evolve(a, 500, 0.02, track_messenger=True)
print(f" Scenario: clear winner")
print(f" Peak messenger: {M.max():.4f} at step {int(np.argmax(M))}")
print(f" Final messenger: {M[-1]:.6f}")
print()
# Peak occurs during the transition, then decays
peak_idx = int(np.argmax(M))
print(f" Messenger trajectory (every 50 steps):")
for t in range(0, 500, 50):
bar = "β–ˆ" * int(M[t] * 40)
print(f" step {t:>3d} M = {M[t]:.4f} {bar}")
print()
def demo_stopping():
print("=" * 72)
print("Demo 7 β€” entropy stopping vs max-posterior stopping")
print("=" * 72)
print()
hyp, ch = make_paleo_scenario()
clf = ChemicalClassifier(hyp, saturation_mode='per_species')
for c in ch:
clf.add_channel(c)
clf.observe('femur_morphology', 2)
clf.observe('tooth_shape', 0)
clf.observe('bone_density', 2)
clf.observe('cortical_thickness', 2)
a = clf.effective_rates()
clf.reset_concentrations()
traj, _ = clf.evolve(a, 500, 0.02)
threshold = 0.85
stop_step = None
for t in range(len(traj)):
H = traj[t]
p = H / H.sum()
if p.max() > threshold:
stop_step = t
break
print(f" Threshold: max posterior > {threshold}")
print(f" Stopping step: {stop_step}")
print()
print(f" {'step':>5s} {'max p':>8s} {'entropy':>10s} {'stop?':>6s}")
print(" " + "-" * 36)
for t in [0, 50, 100, 150, 200, 300, 499]:
H = traj[t]
p = H / H.sum()
p = np.maximum(p, 1e-12)
ent = -np.sum(p * np.log(p))
stopped = "βœ“" if (stop_step is not None and t >= stop_step) else ""
print(f" {t:>5d} {p.max():>8.4f} {ent:>10.4f} {stopped:>6s}")
print()
def main():
demo_basic()
demo_ambivalence()
demo_tempering()
demo_discount()
demo_voi()
demo_messenger()
demo_stopping()
if __name__ == "__main__":
main()