# Case learning from bounded, attributed Boolean examples [GAMMA-Codon/S].
AAC # use super::Json
AAC # use std::collections::{BTreeMap, BTreeSet}
TAG # #[derive(Clone, Debug, PartialEq)]
GCA # struct Check
GCC # key: String
GCC # question: String
GCC # cost: f64
TTT # end
TAG # #[derive(Clone, Debug, PartialEq)]
GCA # struct Example
GCC # truth: u16
GCC # action: String
TTT # end
TAG # #[derive(Clone, Debug, PartialEq)]
GCA # pub(super) struct Casebook
GCC # checks: Vec<Check>
GCC # examples: BTreeMap<String, Example>
TTT # end
AAA # pub(super) fn obj<const N: usize>(fields: [(&str, Json); N]) -> Json
TAC # Json::Obj(fields.into_iter().map(|(key, value)| (key.into(), value)).collect())
TTT # end
AAA # pub(super) fn strings<'a>(values: impl IntoIterator<Item = &'a str>) -> Json
TAC # Json::Arr(values.into_iter().map(|s| Json::Str(s.into())).collect())
TTT # end
# The shared JSON parser preserves duplicate fields. Check them before using .get.
AAA # fn shape(value: &Json, name: &str, required: &[&str]) -> Result<(), String>
TAC # let Json::Obj(fields) = value else { return Err(format!("{name} must be an object")); };
CAA # if fields.len() != required.len() || required.iter().any(|k| value.get(k).is_none())
AAC # return Err(format!("{name} requires exactly these fields once each: {}", required.join(", ")))
TTT # end
TAC # Ok(())
TTT # end
AAA # fn bounded_array<'a>(value: &'a Json, field: &str, limit: usize) -> Result<&'a [Json], String>
TAC # match value.get(field) {
TAC # Some(Json::Arr(rows)) if (1..=limit).contains(&rows.len()) => Ok(rows),
TAC # _ => Err(format!("{field} must have between 1 and {limit} entries")),
TAC # }
TTT # end
AAA # fn bounded_text<'a>(value: &'a Json, field: &str, limit: usize) -> Result<&'a str, String>
TAC # value.get(field).and_then(Json::as_str)
TAC # .filter(|s| !s.is_empty() && s.trim() == *s && s.len() <= limit && !s.chars().any(char::is_control))
TAC # .ok_or_else(|| format!("{field} must be nonempty single-line text of at most {limit} bytes without surrounding whitespace"))
TTT # end
AAA # fn valid_key(key: &str) -> bool
TAC # !key.is_empty() && key.len() <= 128 && key.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b'-'))
TTT # end
AAA # pub(super) fn boolean_facts(value: &Json) -> Result<BTreeMap<&str, bool>, String>
TAC # let Json::Obj(fields) = value else { return Err("facts must be a JSON object".into()); };
CAA # if fields.len() > 128
AAC # return Err("facts accepts at most 128 keys".into())
TTT # end
AAC # let mut facts = BTreeMap::new()
AGA # for (key, value) in fields
CAA # if !valid_key(key)
AAC # return Err("fact keys must be 1..128 ASCII letters, digits, dots, underscores or hyphens".into())
TTT # end
TAC # let Json::Bool(b) = value else { return Err(format!("fact {key} must be a Boolean")); };
CAA # if facts.insert(key.as_str(), *b).is_some()
AAC # return Err(format!("duplicate fact {key}"))
TTT # end
TTT # end
TAC # Ok(facts)
TTT # end
AAA # pub(super) fn validate_facts(value: &Json) -> Result<(), String>
TAC # boolean_facts(value).map(|_| ())
TTT # end
GCA # impl Casebook
AAA # pub(super) fn experiment_keys(&self) -> impl ExactSizeIterator<Item = &str>
TAC # self.checks.iter().map(|check| check.key.as_str())
TTT # end
AAA # pub(super) fn experiment_refs(&self) -> impl Iterator<Item = (&str, u16, &str)>
TAC # self.examples.iter().map(|(reference,row)| (reference.as_str(),row.truth,row.action.as_str()))
TTT # end
AAA # pub(super) fn parse(value: &Json) -> Result<Self, String>
AAC # shape(value, "casebook", &["checks", "examples"])?
AAC # let mut checks = Vec::new()
AGA # for check in bounded_array(value, "checks", 16)?
AAC # shape(check, "check", &["key", "question", "cost"])?
AAC # let key = bounded_text(check, "key", 128)?
CAA # if !valid_key(key)
AAC # return Err("check keys accept ASCII letters, digits, dots, underscores and hyphens".into())
TTT # end
AAC # let question = bounded_text(check, "question", 512)?
TAC # let cost = check.get("cost").and_then(Json::as_f64).filter(|n| n.is_finite() && *n >= 1.0 && n.fract() == 0.0)
TAC # .ok_or("check cost must be a positive finite integer")?;
AAC # checks.push(Check { key: key.into(), question: question.into(), cost })
TTT # end
AAC # checks.sort_by(|a, b| a.key.cmp(&b.key))
CAA # if let Some(pair) = checks.windows(2).find(|p| p[0].key == p[1].key)
AAC # return Err(format!("duplicate check {}", pair[0].key))
TTT # end
AAC # let mut examples = BTreeMap::new()
AGA # for row in bounded_array(value, "examples", 128)?
AAC # shape(row, "example", &["ref", "facts", "action"])?
AAC # let reference = bounded_text(row, "ref", 256)?
AAC # let action = bounded_text(row, "action", 512)?
AAC # let facts = boolean_facts(row.get("facts").unwrap())?
CAA # if facts.len() != checks.len()
AAC # return Err(format!("example {reference} must have exactly the declared check keys"))
TTT # end
AAC # let mut truth = 0u16
AGA # for (idx, check) in checks.iter().enumerate()
AAC # let value = facts.get(check.key.as_str()).ok_or_else(|| format!("example {reference} is missing check {}", check.key))?
AAC # truth |= (*value as u16) << idx
TTT # end
CAA # if examples.insert(reference.into(), Example { truth, action: action.into() }).is_some()
AAC # return Err(format!("duplicate example ref {reference}"))
TTT # end
TTT # end
TAC # Ok(Self { checks, examples })
TTT # end
AAA # pub(super) fn to_json(&self) -> Json
TAC # let checks = self.checks.iter().map(|c| obj([
TAC # ("key", Json::Str(c.key.clone())), ("question", Json::Str(c.question.clone())), ("cost", Json::Num(c.cost))
TAC # ])).collect();
TAC # let examples = self.examples.iter().map(|(reference, example)| {
TAC # let facts = self.checks.iter().enumerate().map(|(i, c)| (c.key.clone(), Json::Bool(example.truth & (1 << i) != 0))).collect();
TAC # obj([("ref", Json::Str(reference.clone())), ("facts", Json::Obj(facts)), ("action", Json::Str(example.action.clone()))])
TAC # }).collect();
TAC # obj([("checks", Json::Arr(checks)), ("examples", Json::Arr(examples))])
TTT # end
AAA # pub(super) fn merge(&self, other: &Self) -> Result<Self, String>
CAA # if self.checks != other.checks
AAC # return Err("casebook checks, questions and costs must agree".into())
TTT # end
AAC # let mut merged = self.clone()
AGA # for (reference, row) in &other.examples
TAC # match merged.examples.get(reference) {
TAC # Some(old) if old != row => return Err(format!("conflicting example ref {reference}")),
TAC # Some(_) => (),
TAC # None => { merged.examples.insert(reference.clone(), row.clone()); }
TAC # }
TTT # end
CAA # if merged.examples.len() > 128
AAC # return Err("merged casebook exceeds 128 examples".into())
TTT # end
TAC # Ok(merged)
TTT # end
AAA # pub(super) fn advise(&self, facts: &Json) -> Result<Json, String>
TAC # Ok(self.decide(&boolean_facts(facts)?).json())
TTT # end
AAA # pub(super) fn guidance(&self, facts: &Json) -> Result<String, String>
TAC # Ok(self.decide(&boolean_facts(facts)?).text())
TTT # end
AAA # pub(super) fn first_guidance(&self) -> String
TAC # self.decide(&BTreeMap::new()).text()
TTT # end
# Query objects can combine observations for several books. Use matching keys, list
# ignored keys, and abstain if a nonempty object shares no keys with this book.
AAA # fn decide<'a>(&'a self, facts: &BTreeMap<&'a str, bool>) -> Decision<'a>
AAC # let mut observed = 0u16
AAC # let mut truth = 0u16
AAC # let mut ignored = Vec::new()
AGA # for (&key, &value) in facts
TAC # match self.checks.binary_search_by(|c| c.key.as_str().cmp(key)) {
TAC # Ok(idx) => { observed |= 1 << idx; truth |= (value as u16) << idx; }
TAC # Err(_) => ignored.push(key),
TAC # }
TTT # end
AAC # let mut evidence = Decision { outcome: Outcome::Unseen, actions: BTreeSet::new(), refs: Vec::new(), conflicting_refs: Vec::new(), distinct: 0, ignored }
CAA # if observed == 0 && !facts.is_empty()
AAC # return evidence
TTT # end
AAC # let mut signatures = Vec::new()
AGA # for (reference, row) in &self.examples
CAA # if row.truth & observed == truth
AAC # evidence.refs.push(reference.as_str())
AAC # evidence.actions.insert(row.action.as_str())
AAC # signatures.push((row.truth, row.action.as_str()))
TTT # end
TTT # end
AAC # signatures.sort_unstable()
AAC # signatures.dedup()
AAC # evidence.distinct = signatures.len()
CAA # if evidence.actions.len() <= 1
CAA # if let Some(&action) = evidence.actions.first()
AAC # evidence.outcome = Outcome::Candidate(action)
TTT # end
AAC # return evidence
TTT # end
# Equal truths are adjacent in the deduplicated truth/action order. Any second
# signature at the same truth must have a different action.
TAC # let conflicts: BTreeSet<_> = signatures.windows(2).filter(|p| p[0].0 == p[1].0).map(|p| p[0].0).collect();
AAC # signatures.sort_unstable_by_key(|&(_, action)| action)
AAC # let mut total_true = [0usize; 16]
AAC # let mut same_action_pairs = [0usize; 16]
AGA # for group in signatures.chunk_by(|a, b| a.1 == b.1)
AAC # let mut group_true = [0usize; 16]
AGA # for &(mut set_bits, _) in group
CAA # while set_bits != 0
AAC # group_true[set_bits.trailing_zeros() as usize] += 1
AAC # set_bits &= set_bits - 1
TTT # end
TTT # end
AGA # for (key, &n) in group_true[..self.checks.len()].iter().enumerate()
AAC # total_true[key] += n
AAC # same_action_pairs[key] += n * (group.len() - n)
TTT # end
TTT # end
# Each check separates all its true/false pairs except those with the same action.
TAC # let scores: [usize; 16] = std::array::from_fn(|i| total_true[i] * (evidence.distinct - total_true[i]) - same_action_pairs[i]);
TAC # evidence.conflicting_refs = self.examples.iter().filter(|(_, row)| conflicts.contains(&row.truth)).map(|(r, _)| r.as_str()).collect();
TAC # let best = self.checks.iter().zip(scores).filter(|(_, count)| *count != 0)
TAC # .max_by(|(a, ac), (b, bc)| separation_score(*ac, b.cost).cmp(&separation_score(*bc, a.cost))
TAC # .then_with(|| b.cost.total_cmp(&a.cost)).then_with(|| b.key.cmp(&a.key)));
TAC # evidence.outcome = match best { Some((check, count)) => Outcome::Ask(check, count), None => Outcome::Conflict };
TAC # evidence
TTT # end
TTT # end
# Compare separated_pairs_a / cost_a to separated_pairs_b / cost_b by exact cross
# products. A cost is an integral, finite f64 >= 1. Its binary significand times
# the bounded pair count fits u128 even when the cost itself exceeds u128::MAX.
AAA # fn separation_score(pairs: usize, opposite_cost: f64) -> (i32, u128)
AAC # let bits = opposite_cost.to_bits()
AAC # let significand = (bits & ((1u64 << 52) - 1)) | (1u64 << 52)
AAC # let product = (pairs as u128) * u128::from(significand)
AAC # let shift = product.leading_zeros()
TAC # ((bits >> 52) as i32 - shift as i32, product << shift)
TTT # end
GCA # enum Outcome<'a>
GCC # Ask(&'a Check, usize)
GCC # Candidate(&'a str)
GCC # Unseen
GCC # Conflict
TTT # end
GCA # struct Decision<'a>
GCC # outcome: Outcome<'a>
GCC # actions: BTreeSet<&'a str>
GCC # refs: Vec<&'a str>
GCC # conflicting_refs: Vec<&'a str>
GCC # distinct: usize
GCC # ignored: Vec<&'a str>
TTT # end
GCA # impl Decision<'_>
AAA # fn json(&self) -> Json
TAC # let (status, mut extra) = match self.outcome {
TAC # Outcome::Ask(c, pairs) => ("ask", vec![("key".into(), Json::Str(c.key.clone())), ("question".into(), Json::Str(c.question.clone())), ("cost".into(), Json::Num(c.cost)), ("separated_pairs".into(), Json::Num(pairs as f64))]),
TAC # Outcome::Candidate(action) => ("candidate_action", vec![("candidate_action".into(), Json::Str(action.into()))]),
TAC # Outcome::Unseen => ("unseen", vec![]),
TAC # Outcome::Conflict => ("conflict", vec![]),
TAC # };
TAC # let mut fields = vec![
TAC # ("status".into(), Json::Str(status.into())), ("supporting_refs".into(), strings(self.refs.iter().copied())),
TAC # ("distinct_cases".into(), Json::Num(self.distinct as f64)), ("actions".into(), strings(self.actions.iter().copied())),
TAC # ("conflicting_refs".into(), strings(self.conflicting_refs.iter().copied())), ("ignored_keys".into(), strings(self.ignored.iter().copied()))
TAC # ];
AAC # fields.append(&mut extra)
TAC # Json::Obj(fields)
TTT # end
AAA # fn text(&self) -> String
TAC # let mut text = match self.outcome {
TAC # Outcome::Ask(c, n) => format!("Check {}. {} Its cost is {} and its answer separates {n} {} of cases with different actions.", c.key, c.question, c.cost, if n == 1 { "pair" } else { "pairs" }),
TAC # Outcome::Candidate(action) => format!("Candidate action from matching examples is \"{action}\". Verify it in the current situation."),
TAC # Outcome::Unseen => "No recorded example matches the supplied facts. Gather evidence before choosing an action.".into(),
TAC # Outcome::Conflict => "Matching examples record different actions for identical facts. Review the conflicting examples before choosing an action.".into(),
TAC # };
CAA # if !self.refs.is_empty()
AAC # let label = if self.distinct == 1 { "distinct case" } else { "distinct cases" }
AAC # text.push_str(&format!(" Evidence from {} {label} ({}).", self.distinct, short_list(&self.refs)))
TTT # end
CAA # if !self.conflicting_refs.is_empty() && matches!(self.outcome, Outcome::Ask(_, _))
AAC # text.push_str(&format!(" Conflicting examples include {}.", short_list(&self.conflicting_refs)))
TTT # end
CAA # if !self.ignored.is_empty()
AAC # text.push_str(&format!(" This casebook ignores {}.", short_list(&self.ignored)))
TTT # end
TAC # text
TTT # end
TTT # end
TAG # #[cfg(test)]
CGC # mod tests
AAC # use super::*
AAC # use crate::parse_json
AAA # fn check(key: &str, cost: f64) -> Json
TAC # obj([("key", Json::Str(key.into())), ("question", Json::Str(format!("Does {key} hold?"))), ("cost", Json::Num(cost))])
TTT # end
AAA # fn row(reference: &str, a: bool, b: bool, action: &str) -> Json
TAC # obj([("ref", Json::Str(reference.into())), ("facts", obj([("a", Json::Bool(a)), ("b", Json::Bool(b))])), ("action", Json::Str(action.into()))])
TTT # end
AAA # fn make_book(cost: f64, examples: Vec<Json>) -> Casebook
TAC # Casebook::parse(&obj([("checks", Json::Arr(vec![check("b", 1.0), check("a", cost)])), ("examples", Json::Arr(examples))])).unwrap()
TTT # end
AAA # fn advise(book: &Casebook, facts: &str) -> Json
TAC # book.advise(&parse_json(facts).unwrap()).unwrap()
TTT # end
TAG # #[test]
AAA # fn chooses_by_conflicting_pairs_per_cost_without_counting_duplicate_observations()
TAC # let rows = vec![row("one", false, false, "inspect"), row("two", true, false, "replace"), row("three", false, true, "replace"), row("copy", false, true, "replace")];
AAC # let book = make_book(1.0, rows.clone())
AAC # let ask = advise(&book, "{}")
AAC # assert_eq!(ask.get("key").and_then(Json::as_str), Some("a"))
AAC # assert_eq!(ask.get("separated_pairs"), Some(&Json::Num(1.0)))
AAC # assert_eq!(ask.get("distinct_cases"), Some(&Json::Num(3.0)))
AAC # assert!(book.first_guidance().contains("Does a hold?"))
AAC # let costlier = make_book(2.0, rows)
AAC # assert_eq!(advise(&costlier, "{}").get("key").and_then(Json::as_str), Some("b"))
AAC # let supported = advise(&book, r#"{"b":true,"other.domain":true}"#)
AAC # assert_eq!(supported.get("candidate_action").and_then(Json::as_str), Some("replace"))
AAC # assert_eq!(supported.get("supporting_refs"), Some(&strings(["copy","three"])))
AAC # assert_eq!(supported.get("ignored_keys"), Some(&strings(["other.domain"])))
AAC # assert_eq!(supported.get("distinct_cases"), Some(&Json::Num(1.0)))
AAC # assert_eq!(advise(&book, r#"{"a":true,"b":true}"#).get("status").and_then(Json::as_str), Some("unseen"))
TTT # end
TAG # #[test]
AAA # fn selects_a_costlier_check_when_it_distinguishes_more_pairs_per_unit()
TAC # let rows = [(false,false,false,"stay"), (false,false,true,"stay"), (false,true,false,"stay"), (true,false,false,"move")];
TAC # let examples = rows.into_iter().enumerate().map(|(i,(a,b,c,action))| obj([
TAC # ("ref",Json::Str(i.to_string())), ("facts",obj([("a",Json::Bool(a)),("b",Json::Bool(b)),("c",Json::Bool(c))])), ("action",Json::Str(action.into()))
TAC # ])).collect();
TAC # let book = Casebook::parse(&obj([("checks",Json::Arr(vec![check("a",2.0),check("b",1.0),check("c",1.0)])),("examples",Json::Arr(examples))])).unwrap();
AAC # let choice = advise(&book, "{}")
AAC # assert_eq!(choice.get("key").and_then(Json::as_str), Some("a"))
AAC # assert_eq!(choice.get("separated_pairs"), Some(&Json::Num(3.0)))
TTT # end
TAG # #[test]
AAA # fn distinguishes_no_recognized_keys_from_empty_facts_and_returns_single_record_support()
AAC # let book = make_book(3.0, vec![row("one", false, true, "inspect")])
AAC # let single = advise(&book, "{}")
AAC # assert_eq!(single.get("status").and_then(Json::as_str), Some("candidate_action"))
AAC # assert_eq!(single.get("supporting_refs"), Some(&strings(["one"])))
AAC # assert_eq!(single.get("distinct_cases"), Some(&Json::Num(1.0)))
AAC # let unknown = advise(&book, r#"{"another":false}"#)
AAC # assert_eq!(unknown.get("status").and_then(Json::as_str), Some("unseen"))
AAC # assert_eq!(unknown.get("supporting_refs"), Some(&strings([])))
AAC # assert_eq!(unknown.get("ignored_keys"), Some(&strings(["another"])))
TTT # end
TAG # #[test]
AAA # fn discloses_contradictions_while_a_useful_question_remains_then_abstains()
AAC # let book = make_book(1.0, vec![row("one", false, false, "repair"), row("two", false, false, "replace"), row("copy", false, false, "repair"), row("third", true, false, "inspect")])
AAC # let first = advise(&book, "{}")
AAC # assert_eq!(first.get("status").and_then(Json::as_str), Some("ask"))
AAC # assert_eq!(first.get("conflicting_refs"), Some(&strings(["copy","one","two"])))
AAC # let conflict = advise(&book, r#"{"a":false}"#)
AAC # assert_eq!(conflict.get("status").and_then(Json::as_str), Some("conflict"))
AAC # assert_eq!(conflict.get("actions"), Some(&strings(["repair","replace"])))
AAC # assert_eq!(conflict.get("candidate_action"), None)
AAC # assert_eq!(conflict.get("distinct_cases"), Some(&Json::Num(2.0)))
TTT # end
TAG # #[test]
AAA # fn canonical_merge_reuses_unchanged_refs_and_rejects_edits_or_overflow()
AAC # let rows = vec![row("z", true, false, "replace"), row("a", false, true, "inspect")]
AAC # let book = make_book(2.0, rows.clone())
TAC # let reordered = obj([("examples", Json::Arr(rows.into_iter().rev().collect())), ("checks", Json::Arr(vec![check("a", 2.0),check("b", 1.0)]))]);
AAC # let canonical = Casebook::parse(&reordered).unwrap()
AAC # assert_eq!(book.to_json(), canonical.to_json())
AAC # assert_eq!(book.merge(&canonical).unwrap(), book)
AAC # let new = make_book(2.0, vec![row("third", false, false, "other")])
AAC # assert_eq!(book.merge(&new).unwrap(), new.merge(&book).unwrap())
AAC # assert!(book.merge(&make_book(2.0, vec![row("z", true, false, "other")])).is_err())
AAC # assert!(book.merge(&make_book(5.0, vec![row("z", true, false, "replace")])).is_err())
AAC # let full = make_book(2.0, (0..128).map(|i| row(&i.to_string(),false,true,"inspect")).collect())
AAC # assert!(full.merge(&new).is_err())
TTT # end
TAG # #[test]
AAA # fn validates_shapes_keys_boolean_values_and_costs()
AGA # for invalid in [r#"{"a":true,"a":false}"#, r#"{"a":"true"}"#, r#"{"bad key":false}"#, "[]", "false"]
AAC # assert!(validate_facts(&parse_json(invalid).unwrap()).is_err())
TTT # end
AAC # assert!(validate_facts(&parse_json("{}").unwrap()).is_ok())
TAC # let examples = Json::Arr(vec![row("ref", true, false, "act")]);
AGA # for cost in [-1.0, 0.0, 0.5, 1.25, f64::NAN, f64::INFINITY]
AAC # assert!(Casebook::parse(&obj([("checks", Json::Arr(vec![check("a", cost), check("b",1.0)])), ("examples", examples.clone())])).is_err())
TTT # end
AGA # for checks in [vec![], vec![check("a",1.0)], vec![check("a",1.0),check("a",1.0)], vec![check("x",1.0),check("b",1.0)]]
AAC # assert!(Casebook::parse(&obj([("checks", Json::Arr(checks)), ("examples", examples.clone())])).is_err())
TTT # end
AAC # let checks = Json::Arr(vec![check("a",1.0),check("b",1.0)])
AAC # let duplicated = Json::Arr(vec![row("ref",true,false,"act"),row("ref",true,false,"act")])
AAC # assert!(Casebook::parse(&obj([("checks", checks.clone()),("examples",duplicated)])).is_err())
AAC # assert!(Casebook::parse(&obj([("checks", checks),("examples",Json::Arr(Vec::new()))])).is_err())
TTT # end
TAG # #[test]
AAA # fn ranks_extreme_integer_costs_without_rounding_or_overflow()
AAC # let large = f64::MAX
AAC # let almost = f64::from_bits(large.to_bits() - 1)
AAC # assert!(separation_score(8128, large) > separation_score(8128, almost))
AAC # assert_eq!(separation_score(2, 1.0), separation_score(1, 2.0))
AAC # assert!(separation_score(1, large) > separation_score(8128, 1.0))
TTT # end
TTT # end
AAA # fn short_list(entries: &[&str]) -> String
AAC # let shown = entries.len().min(3)
AAC # let mut text = entries[..shown].join(", ")
CAA # if entries.len() > shown
AAC # text.push_str(&format!(" (+{} more)", entries.len() - shown))
TTT # end
TAC # text
TTT # end