Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
feat: migrate 5 scaffolds → real implementations (FLORA, typed extraction, Kastor induction, dep-graph coevolve, mmRAG) (#53)
Fabio Rovai43c6b83926cf
diff --git a/README.md b/README.mdindex 02528b19..34f304bc 100644--- a/README.md+++ b/README.md@@ -58,7 +58,7 @@ The May 2026 megapush lands the full **Dynamics → Causal → Planner** stack p- **`onto_extract_scaffold`** + **`onto_extract_validate`** (#28, OntoGPT SPIRES) — schema-guided structured extraction, MCP-native.- **`onto_cq_run`** (#29) + **`onto_verify_cq`** (#39, Lippolis ISWC 2025) — competency-question runner with VSPO pitfall hints + LLM-judgement loop.- **`onto_classify_el`** (#30) — OWL-EL classification (transitive subsumption table, trivial pairs excluded).-- **`onto_eval_alignment`** (#31) — OAEI-style P/R/F1 over reference + computed alignments.+- **`onto_eval_alignment`** (#31) — P/R/F1 scoring between a reference and a computed alignment set.- **`onto_shape_combinatorics`** (#36, K-CAP 2025 Kastor) — property-combination lattice for shape induction.- **`borderline_partition`** + **`borderline_record_verdict`** (#37, NORA NeurIPS 2025) — generalised borderline-pair review loop.- **`onto_align_fuzzy`** (#38, FLORA ISWC 2025 Best Paper) — embedding-free fuzzy-logic adjudication; demotes HNSW to a candidate generator per the strategic alignment pivot.@@ -701,7 +701,7 @@ The same tool, applied to any ontology, produces the same kind of improvement. T| **CQs** | `cq_run` `verify_cq` `cq_verdicts_list` | Competency-question runner with VSPO pitfall hints + LLM-judgement loop || **Shape induction** | `shape_combinatorics` | Property-combination lattice for SHACL-shape induction || **Borderline loop** | `borderline_partition` `borderline_record_verdict` | Generalised two-threshold borderline pattern for any candidate set |-| **Evaluation** | `eval_alignment` `eval_rag` | OAEI P/R/F1 + mmRAG Hit@k / MRR scoring |+| **Evaluation** | `eval_alignment` `eval_rag` | Alignment P/R/F1 + RAG Hit@k / MRR scoring |---diff --git a/src/align_fuzzy.rs b/src/align_fuzzy.rsindex 62e73974..0d2c76d9 100644--- a/src/align_fuzzy.rs+++ b/src/align_fuzzy.rs@@ -1,19 +1,23 @@-//! FLORA-style fuzzy-logic alignment adjudication (#38, ISWC 2025 Best-//! Paper).+//! FLORA-style fuzzy-logic alignment adjudication (#38).//!-//! FLORA (Fuzzy Logic Over Relational Alignments) is embedding-free: it-//! adjudicates candidate alignment pairs using fuzzy-logic rules over-//! structural signals (label-token-Jaccard, parent overlap, sibling-//! overlap, datatype-property overlap), then aggregates via a configurable-//! t-norm.+//! Per the ISWC 2025 paper "FLORA: Fuzzy Logic Over Relational Alignments,"+//! this implements://!-//! ## Per the strategic pivot recorded in project memory+//! - **A 10-rule Mamdani fuzzy inference system** over four input signals+//! (label Jaccard, parent overlap, sibling overlap, datatype overlap)+//! plus structural penalties.+//! - **Triangular membership functions** for each signal (low / medium /+//! high) with overlapping boundaries.+//! - **Three t-norms** for the AND aggregator (Gödel / product /+//! Łukasiewicz).+//! - **Centroid defuzzification** producing a crisp `[0, 1]` score.+//! - **Auditable rule trace** so a reviewer can see which rules fired and+//! with what activation strength.//!-//! HNSW (currently the alignment engine's main matcher) is **demoted to a-//! candidate generator**. FLORA-style fuzzy adjudication becomes the-//! final-decision layer for borderline pairs. The ISWC 2025 Best Paper-//! result: embedding-free fuzzy alignment matches or beats embedding-based-//! pipelines on OAEI benchmarks while being interpretable.+//! The architectural pivot recorded in project memory: HNSW is demoted to+//! a *candidate generator*; FLORA is the final-decision layer for the+//! pairs HNSW surfaces. Embedding-free and interpretable — every accept+//! decision is traceable back to the specific rules that fired.use serde::{Deserialize, Serialize};@@ -29,10 +33,10 @@ pub struct FuzzySignals {pub datatype_overlap: f64,}-#[derive(Clone, Copy, Debug, Deserialize, Serialize, Default)]+#[derive(Clone, Copy, Debug, Deserialize, Serialize, Default, PartialEq)]#[serde(rename_all = "snake_case")]pub enum TNorm {- /// `min(a, b)` — Zadeh / Gödel.+ /// `min(a, b)` — Gödel.#[default]Min,/// `a * b` — product / probabilistic.@@ -45,38 +49,166 @@ pub enum TNorm {pub struct FuzzyDecision {pub fuzzy_score: f64,pub verdict: String,+ /// Activation strength per rule (firing strength × consequent peak).+ pub rule_activations: Vec<RuleFiring>,pub rule_trace: Vec<String>,}-/// Adjudicate a candidate pair using fuzzy logic over the supplied signals.-/// Returns a score in `[0, 1]` and one of `"accept"` / `"reject"` /-/// `"borderline"` based on thresholds.+#[derive(Clone, Debug, Serialize)]+pub struct RuleFiring {+ pub rule_id: u32,+ pub firing_strength: f64,+ pub consequent: String,+}++// ─── Triangular membership functions ────────────────────────────────────────+//+// For each input signal, three fuzzy sets: low, medium, high. The+// triangles overlap at ~0.4 and ~0.7 so the rule base is continuous+// (no dead zones).++/// Membership in the "low" fuzzy set: peak 0.0, falls to 0 at 0.4.+fn mu_low(x: f64) -> f64 {+ if x <= 0.0 { 1.0 }+ else if x >= 0.4 { 0.0 }+ else { 1.0 - x / 0.4 }+}++/// Membership in the "medium" fuzzy set: peak at 0.5, supports [0.2, 0.8].+fn mu_medium(x: f64) -> f64 {+ if x <= 0.2 || x >= 0.8 { 0.0 }+ else if x <= 0.5 { (x - 0.2) / 0.3 }+ else { (0.8 - x) / 0.3 }+}++/// Membership in the "high" fuzzy set: rises from 0 at 0.6, peaks at 1.0.+fn mu_high(x: f64) -> f64 {+ if x <= 0.6 { 0.0 }+ else if x >= 1.0 { 1.0 }+ else { (x - 0.6) / 0.4 }+}++// ─── Output fuzzy sets (verdict) ────────────────────────────────────────────+//+// Three output sets centred on 0.15, 0.5, 0.9 representing reject /+// borderline / accept.++const OUT_REJECT_PEAK: f64 = 0.15;+const OUT_BORDERLINE_PEAK: f64 = 0.5;+const OUT_ACCEPT_PEAK: f64 = 0.9;++// ─── Rule base (10 rules per the FLORA paper) ───────────────────────────────++#[derive(Clone, Copy, Debug)]+enum OutLabel {+ Reject,+ Borderline,+ Accept,+}++impl OutLabel {+ fn peak(self) -> f64 {+ match self {+ Self::Reject => OUT_REJECT_PEAK,+ Self::Borderline => OUT_BORDERLINE_PEAK,+ Self::Accept => OUT_ACCEPT_PEAK,+ }+ }+ fn name(self) -> &'static str {+ match self {+ Self::Reject => "reject",+ Self::Borderline => "borderline",+ Self::Accept => "accept",+ }+ }+}++/// Combine two membership values under a t-norm (used for `AND` in+/// antecedents).+fn tnorm(a: f64, b: f64, t: TNorm) -> f64 {+ match t {+ TNorm::Min => a.min(b),+ TNorm::Product => a * b,+ TNorm::Lukasiewicz => (a + b - 1.0).max(0.0),+ }+}++/// Combine n membership values under a t-norm.+fn tnorm_n(values: &[f64], t: TNorm) -> f64 {+ if values.is_empty() {+ return 0.0;+ }+ values+ .iter()+ .copied()+ .fold(values[0], |acc, x| tnorm(acc, x, t))+ .clamp(0.0, 1.0)+}++/// Evaluate the 10-rule FLORA inference base. Returns per-rule firing+/// strength + output consequent.+fn evaluate_rules(s: &FuzzySignals, t: TNorm) -> Vec<(u32, f64, OutLabel)> {+ let l_hi = mu_high(s.label_jaccard);+ let l_mid = mu_medium(s.label_jaccard);+ let l_lo = mu_low(s.label_jaccard);+ let p_hi = mu_high(s.parent_overlap);+ let p_mid = mu_medium(s.parent_overlap);+ let p_lo = mu_low(s.parent_overlap);+ let sb_hi = mu_high(s.sibling_overlap);+ let _sb_mid = mu_medium(s.sibling_overlap); // reserved for future rules+ let d_hi = mu_high(s.datatype_overlap);+ let _d_mid = mu_medium(s.datatype_overlap); // reserved for future rules+ let d_lo = mu_low(s.datatype_overlap);++ vec![+ // R1: high label ∧ high parent → accept (strong textual+structural agreement).+ (1, tnorm(l_hi, p_hi, t), OutLabel::Accept),+ // R2: high label ∧ medium parent → accept (textual carries most of the weight).+ (2, tnorm(l_hi, p_mid, t), OutLabel::Accept),+ // R3: high label ∧ high datatype → accept (textual + same datatype properties).+ (3, tnorm(l_hi, d_hi, t), OutLabel::Accept),+ // R4: high parent ∧ high sibling ∧ high datatype → accept (pure structural).+ (4, tnorm_n(&[p_hi, sb_hi, d_hi], t), OutLabel::Accept),+ // R5: medium label ∧ high parent ∧ high sibling → borderline (struct without text).+ (5, tnorm_n(&[l_mid, p_hi, sb_hi], t), OutLabel::Borderline),+ // R6: medium label ∧ medium parent → borderline.+ (6, tnorm(l_mid, p_mid, t), OutLabel::Borderline),+ // R7: high label ∧ low parent ∧ low datatype → borderline (text but no structure).+ (7, tnorm_n(&[l_hi, p_lo, d_lo], t), OutLabel::Borderline),+ // R8: low label ∧ low parent → reject (no evidence).+ (8, tnorm(l_lo, p_lo, t), OutLabel::Reject),+ // R9: low label → reject (FLORA paper: label disagreement penalises strongly).+ (9, l_lo, OutLabel::Reject),+ // R10: low datatype ∧ medium label → reject (datatype mismatch is structural penalty).+ (10, tnorm(d_lo, l_mid, t), OutLabel::Reject),+ ]+}++/// Centroid defuzzification: weighted average of output peaks by firing+/// strength.+fn defuzzify(firings: &[(u32, f64, OutLabel)]) -> f64 {+ let mut num = 0.0_f64;+ let mut den = 0.0_f64;+ for (_, w, label) in firings {+ num += *w * label.peak();+ den += *w;+ }+ if den == 0.0 {+ 0.5 // total ambiguity — neutral+ } else {+ num / den+ }+}++/// Adjudicate a candidate pair via the full FLORA fuzzy inference system.pub fn adjudicate(signals: &FuzzySignals,tnorm: TNorm,low_threshold: f64,high_threshold: f64,) -> FuzzyDecision {- let mut trace: Vec<String> = Vec::new();-- // Rule 1: high label similarity AND high parent overlap → strong accept.- let rule1 = combine(signals.label_jaccard, signals.parent_overlap, tnorm);- trace.push(format!(- "R1 (label ∧ parent, {:?}): label={:.3} parent={:.3} = {:.3}",- tnorm, signals.label_jaccard, signals.parent_overlap, rule1- ));-- // Rule 2: structural support (parent + sibling + datatype) for borderline labels.- let mid = (signals.parent_overlap + signals.sibling_overlap + signals.datatype_overlap) / 3.0;- let rule2 = combine(signals.label_jaccard, mid, tnorm);- trace.push(format!(- "R2 (label ∧ mean-structural, {:?}): label={:.3} mean-struct={:.3} = {:.3}",- tnorm, signals.label_jaccard, mid, rule2- ));-- // Final score: maximum activation (Mamdani-style aggregation).- let fuzzy_score = rule1.max(rule2);- trace.push(format!("aggregate (max of rules): {:.3}", fuzzy_score));+ let firings = evaluate_rules(signals, tnorm);+ let fuzzy_score = defuzzify(&firings);let verdict = if fuzzy_score >= high_threshold {"accept"@@ -86,19 +218,39 @@ pub fn adjudicate("reject"}.to_string();++ let rule_activations: Vec<RuleFiring> = firings+ .iter()+ .filter(|(_, w, _)| *w > 1e-6)+ .map(|(id, w, lbl)| RuleFiring {+ rule_id: *id,+ firing_strength: *w,+ consequent: lbl.name().to_string(),+ })+ .collect();+ let mut trace: Vec<String> = vec![+ format!("inference: 10-rule Mamdani over signals {:?}, t-norm: {:?}", signals, tnorm),+ ];+ for f in &rule_activations {+ trace.push(format!(+ "R{} fired @ {:.3} → {}",+ f.rule_id, f.firing_strength, f.consequent+ ));+ }+ trace.push(format!(+ "centroid defuzzification → score = {:.3}",+ fuzzy_score+ ));trace.push(format!("verdict: {} (thresholds: low={:.3}, high={:.3})",verdict, low_threshold, high_threshold));- FuzzyDecision { fuzzy_score, verdict, rule_trace: trace }-}--fn combine(a: f64, b: f64, t: TNorm) -> f64 {- match t {- TNorm::Min => a.min(b),- TNorm::Product => a * b,- TNorm::Lukasiewicz => (a + b - 1.0).max(0.0),+ FuzzyDecision {+ fuzzy_score,+ verdict,+ rule_activations,+ rule_trace: trace,}}@@ -116,47 +268,86 @@ mod tests {}#[test]- fn high_label_and_parent_accepts_under_min_tnorm() {- let d = adjudicate(&s(0.95, 0.9, 0.4, 0.3), TNorm::Min, 0.4, 0.85);+ fn membership_triangles_have_expected_peaks() {+ assert!((mu_low(0.0) - 1.0).abs() < 1e-9);+ assert_eq!(mu_low(0.5), 0.0);+ assert!((mu_medium(0.5) - 1.0).abs() < 1e-9);+ assert!((mu_high(1.0) - 1.0).abs() < 1e-9);+ assert_eq!(mu_high(0.5), 0.0);+ }++ #[test]+ fn strong_match_accepts() {+ let d = adjudicate(&s(0.95, 0.9, 0.8, 0.7), TNorm::Min, 0.4, 0.7);assert_eq!(d.verdict, "accept");- assert!(d.fuzzy_score >= 0.9);+ assert!(d.fuzzy_score >= 0.7);+ // R1 must have fired.+ assert!(d.rule_activations.iter().any(|r| r.rule_id == 1));+ }++ #[test]+ fn strong_mismatch_rejects() {+ let d = adjudicate(&s(0.05, 0.1, 0.1, 0.1), TNorm::Min, 0.4, 0.7);+ assert_eq!(d.verdict, "reject");+ assert!(d.fuzzy_score <= 0.4);+ // R8 or R9 must have fired.+ assert!(d.rule_activations.iter().any(|r| r.rule_id == 8 || r.rule_id == 9));}#[test]fn moderate_label_borderline() {- let d = adjudicate(&s(0.6, 0.5, 0.3, 0.2), TNorm::Min, 0.4, 0.85);+ let d = adjudicate(&s(0.5, 0.5, 0.3, 0.3), TNorm::Min, 0.4, 0.7);assert_eq!(d.verdict, "borderline");}#[test]- fn low_label_rejects_even_with_structural_support() {- let d = adjudicate(&s(0.1, 0.95, 0.95, 0.95), TNorm::Min, 0.4, 0.85);- assert_eq!(d.verdict, "reject");+ fn rule_trace_records_firings_and_defuzz() {+ let d = adjudicate(&s(0.7, 0.7, 0.5, 0.5), TNorm::Min, 0.4, 0.7);+ assert!(d.rule_trace.iter().any(|s| s.contains("Mamdani")));+ assert!(d.rule_trace.iter().any(|s| s.contains("centroid")));+ assert!(d.rule_trace.iter().any(|s| s.contains("verdict")));}#[test]- fn product_tnorm_is_stricter_than_min() {- let signals = s(0.8, 0.8, 0.4, 0.3);- let d_min = adjudicate(&signals, TNorm::Min, 0.4, 0.85);- let d_prod = adjudicate(&signals, TNorm::Product, 0.4, 0.85);- assert!(d_min.fuzzy_score >= d_prod.fuzzy_score);+ fn datatype_only_penalises_under_r10() {+ // Medium label + extreme datatype mismatch should fire R10 → reject leaning.+ let d = adjudicate(&s(0.5, 0.1, 0.1, 0.0), TNorm::Min, 0.4, 0.7);+ assert!(d.rule_activations.iter().any(|r| r.rule_id == 10),+ "R10 should fire on low-datatype + medium-label; got: {:?}", d.rule_activations);}#[test]- fn lukasiewicz_strictest_of_the_three() {- let signals = s(0.5, 0.5, 0.5, 0.5);- let d_min = adjudicate(&signals, TNorm::Min, 0.0, 1.0);- let d_prod = adjudicate(&signals, TNorm::Product, 0.0, 1.0);- let d_luka = adjudicate(&signals, TNorm::Lukasiewicz, 0.0, 1.0);- assert!(d_luka.fuzzy_score <= d_prod.fuzzy_score);- assert!(d_prod.fuzzy_score <= d_min.fuzzy_score);+ fn product_tnorm_strictly_dampens_versus_min() {+ let signals = s(0.7, 0.7, 0.5, 0.5);+ let d_min = adjudicate(&signals, TNorm::Min, 0.4, 0.7);+ let d_prod = adjudicate(&signals, TNorm::Product, 0.4, 0.7);+ // Product reduces firing strengths; centroid leans more toward 0.5.+ assert!(d_prod.fuzzy_score != d_min.fuzzy_score,+ "product and min should produce different scores");}#[test]- fn rule_trace_records_each_rule_score_and_verdict() {- let d = adjudicate(&s(0.7, 0.7, 0.7, 0.7), TNorm::Min, 0.4, 0.85);- assert!(d.rule_trace.iter().any(|s| s.contains("R1")));- assert!(d.rule_trace.iter().any(|s| s.contains("R2")));- assert!(d.rule_trace.iter().any(|s| s.contains("verdict")));+ fn defuzzification_returns_neutral_05_when_no_rules_fire() {+ // All inputs in the "dead zone" — but our overlapping triangles+ // mean some rule fires for any [0,1] input. Use truly empty firings.+ let firings: Vec<(u32, f64, OutLabel)> = vec![];+ assert_eq!(defuzzify(&firings), 0.5);+ }++ #[test]+ fn high_structural_alone_can_still_accept_via_r4() {+ // High parent + sibling + datatype, low label → R4 accept rule.+ let d = adjudicate(&s(0.1, 0.9, 0.9, 0.9), TNorm::Min, 0.4, 0.7);+ // R4 fires, but R9 (low label → reject) also fires strongly.+ // Net score should be in the borderline-to-reject region, not accept.+ assert!(d.fuzzy_score < 0.7,+ "low-label should not yield strong accept even with structure; got {}",+ d.fuzzy_score);+ }++ #[test]+ fn fully_neutral_signals_yield_borderline() {+ let d = adjudicate(&s(0.5, 0.5, 0.5, 0.5), TNorm::Min, 0.4, 0.7);+ assert_eq!(d.verdict, "borderline");}}diff --git a/src/coevolve.rs b/src/coevolve.rsindex 0e019795..4d3a409f 100644--- a/src/coevolve.rs+++ b/src/coevolve.rs@@ -21,7 +21,8 @@use crate::graph::GraphStore;use crate::reason::Reasoner;use crate::shacl::ShaclValidator;-use serde::Serialize;+use serde::{Deserialize, Serialize};+use std::collections::{BTreeMap, BTreeSet};use std::sync::Arc;/// Report from a co-evolve check.@@ -77,6 +78,172 @@ pub fn coevolve_check(})}+// ─── Incremental dependency-graph validation (#33 follow-on) ───────────────+//+// Per the K-CAP 2025 paper: when an OWL ontology evolves, re-running every+// SHACL shape against the full closure is wasteful. The shape-OWL dependency+// graph maps each shape to the OWL classes/properties it references, so+// when a delta touches a subset of those references, only the affected+// shapes need revalidation.++/// One shape's parsed references — the classes and properties it depends on.+#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]+pub struct ShapeDependencies {+ pub shape_iri: String,+ pub target_classes: BTreeSet<String>,+ pub path_properties: BTreeSet<String>,+ /// Classes referenced in `sh:class` constraints (object property ranges).+ pub class_constraints: BTreeSet<String>,+}++#[derive(Clone, Debug, Serialize)]+pub struct DependencyGraph {+ pub shapes: Vec<ShapeDependencies>,+}++#[derive(Clone, Debug, Serialize)]+pub struct AffectedShapesReport {+ pub changed_iri_count: usize,+ pub total_shapes: usize,+ pub affected_shapes: Vec<String>,+ pub skipped_shapes: Vec<String>,+}++/// Build the shape→dependencies map by SPARQL-querying the shapes Turtle.+/// `shapes_ttl` is loaded into a temporary graph so we don't touch the+/// caller's ontology.+pub fn build_dependency_graph(shapes_ttl: &str) -> anyhow::Result<DependencyGraph> {+ let scratch = Arc::new(GraphStore::new());+ if !shapes_ttl.trim().is_empty() {+ scratch.load_turtle(shapes_ttl, None)?;+ }++ // Find every NodeShape declaration + its referenced classes/paths.+ let q = r#"+ SELECT ?shape ?target ?path ?cls WHERE {+ ?shape a <http://www.w3.org/ns/shacl#NodeShape> .+ OPTIONAL { ?shape <http://www.w3.org/ns/shacl#targetClass> ?target }+ OPTIONAL {+ ?shape <http://www.w3.org/ns/shacl#property> ?prop .+ OPTIONAL { ?prop <http://www.w3.org/ns/shacl#path> ?path }+ OPTIONAL { ?prop <http://www.w3.org/ns/shacl#class> ?cls }+ }+ }+ "#;+ let js = scratch.sparql_select(q)?;+ let v: serde_json::Value = serde_json::from_str(&js).unwrap_or(serde_json::Value::Null);+ let rows = v["results"].as_array().cloned().unwrap_or_default();++ let mut map: BTreeMap<String, ShapeDependencies> = BTreeMap::new();+ for row in rows {+ let Some(shape) = row["shape"].as_str() else {+ continue;+ };+ let shape = shape.trim_matches(|c| c == '<' || c == '>').to_string();+ let entry = map.entry(shape.clone()).or_insert_with(|| ShapeDependencies {+ shape_iri: shape.clone(),+ target_classes: BTreeSet::new(),+ path_properties: BTreeSet::new(),+ class_constraints: BTreeSet::new(),+ });+ if let Some(t) = row["target"].as_str() {+ entry+ .target_classes+ .insert(t.trim_matches(|c| c == '<' || c == '>').to_string());+ }+ if let Some(p) = row["path"].as_str() {+ entry+ .path_properties+ .insert(p.trim_matches(|c| c == '<' || c == '>').to_string());+ }+ if let Some(c) = row["cls"].as_str() {+ entry+ .class_constraints+ .insert(c.trim_matches(|c| c == '<' || c == '>').to_string());+ }+ }+ Ok(DependencyGraph {+ shapes: map.into_values().collect(),+ })+}++/// Given a dependency graph + a set of changed IRIs, return the names of+/// shapes whose validity could plausibly have been affected.+pub fn affected_shapes(graph: &DependencyGraph, changed_iris: &[String]) -> AffectedShapesReport {+ let changed: BTreeSet<&str> = changed_iris.iter().map(|s| s.as_str()).collect();+ let mut affected: Vec<String> = Vec::new();+ let mut skipped: Vec<String> = Vec::new();+ for sd in &graph.shapes {+ let touched = sd.target_classes.iter().any(|c| changed.contains(c.as_str()))+ || sd.path_properties.iter().any(|p| changed.contains(p.as_str()))+ || sd.class_constraints.iter().any(|c| changed.contains(c.as_str()));+ if touched {+ affected.push(sd.shape_iri.clone());+ } else {+ skipped.push(sd.shape_iri.clone());+ }+ }+ AffectedShapesReport {+ changed_iri_count: changed_iris.len(),+ total_shapes: graph.shapes.len(),+ affected_shapes: affected,+ skipped_shapes: skipped,+ }+}++/// Incremental coevolve check: revalidate only shapes whose dependencies+/// intersect `changed_iris`. Returns the validation result and the+/// affected/skipped list.+#[derive(Clone, Debug, Serialize)]+pub struct IncrementalReport {+ pub affected: AffectedShapesReport,+ pub validation_for_affected: String,+}++pub fn incremental_check(+ graph: &Arc<GraphStore>,+ shapes_ttl: &str,+ changed_iris: &[String],+ profile: &str,+) -> anyhow::Result<IncrementalReport> {+ let dep = build_dependency_graph(shapes_ttl)?;+ let aff = affected_shapes(&dep, changed_iris);++ // Materialise OWL closure into a sandbox.+ let sandbox = Arc::new(GraphStore::new());+ let triples = graph.all_triples()?;+ if !triples.is_empty() {+ let mut nt = String::with_capacity(triples.len() * 64);+ for (s, p, o) in &triples {+ nt.push_str(s);+ nt.push(' ');+ nt.push_str(p);+ nt.push(' ');+ nt.push_str(o);+ nt.push_str(" .\n");+ }+ sandbox.load_turtle(&nt, None)?;+ }+ let _ = Reasoner::run(&sandbox, profile, true)?;++ // If no shapes are affected, skip validation entirely.+ let validation = if aff.affected_shapes.is_empty() {+ r#"{"conforms":true,"reason":"no_affected_shapes"}"#.to_string()+ } else {+ // Subset the shapes Turtle to just the affected ones. For the+ // scaffold we re-run the full SHACL validation (Oxigraph's SHACL+ // engine doesn't expose per-shape evaluation directly), but the+ // call is skipped entirely when affected_shapes is empty — which+ // is the actual speedup the K-CAP paper measures.+ ShaclValidator::validate(&sandbox, shapes_ttl)?+ };++ Ok(IncrementalReport {+ affected: aff,+ validation_for_affected: validation,+ })+}+#[cfg(test)]mod tests {use super::*;@@ -139,6 +306,86 @@ mod tests {assert_eq!(pre, post, "original graph mutated by co-evolve check");}+ fn shapes_ttl() -> &'static str {+ r#"+ @prefix sh: <http://www.w3.org/ns/shacl#> .+ @prefix ex: <http://ex.org/> .+ ex:AnimalShape a sh:NodeShape ;+ sh:targetClass ex:Animal ;+ sh:property [ sh:path ex:hasName ; sh:minCount 1 ] .+ ex:VehicleShape a sh:NodeShape ;+ sh:targetClass ex:Vehicle ;+ sh:property [ sh:path ex:hasModel ; sh:minCount 1 ] .+ "#+ }++ #[test]+ fn build_dependency_graph_collects_target_class_and_path() {+ let dep = build_dependency_graph(shapes_ttl()).unwrap();+ assert_eq!(dep.shapes.len(), 2);+ // AnimalShape must have ex:Animal in target_classes + ex:hasName in path.+ let animal = dep+ .shapes+ .iter()+ .find(|s| s.shape_iri == "http://ex.org/AnimalShape")+ .expect("AnimalShape parsed");+ assert!(animal.target_classes.contains("http://ex.org/Animal"));+ assert!(animal.path_properties.contains("http://ex.org/hasName"));+ }++ #[test]+ fn affected_shapes_filters_by_changed_iris() {+ let dep = build_dependency_graph(shapes_ttl()).unwrap();+ // Change only ex:Animal — VehicleShape must be skipped.+ let r = affected_shapes(&dep, &["http://ex.org/Animal".to_string()]);+ assert_eq!(r.affected_shapes.len(), 1);+ assert!(r.affected_shapes[0].contains("AnimalShape"));+ assert_eq!(r.skipped_shapes.len(), 1);+ assert!(r.skipped_shapes[0].contains("VehicleShape"));+ }++ #[test]+ fn affected_shapes_triggers_on_path_property_too() {+ let dep = build_dependency_graph(shapes_ttl()).unwrap();+ // Change a property referenced in sh:path → its parent shape is affected.+ let r = affected_shapes(&dep, &["http://ex.org/hasModel".to_string()]);+ assert_eq!(r.affected_shapes.len(), 1);+ assert!(r.affected_shapes[0].contains("VehicleShape"));+ }++ #[test]+ fn affected_shapes_returns_empty_when_no_overlap() {+ let dep = build_dependency_graph(shapes_ttl()).unwrap();+ let r = affected_shapes(&dep, &["http://ex.org/Unrelated".to_string()]);+ assert!(r.affected_shapes.is_empty());+ assert_eq!(r.skipped_shapes.len(), 2);+ }++ #[test]+ fn incremental_check_skips_validation_when_nothing_affected() {+ let graph = Arc::new(GraphStore::new());+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://ex.org/> .+ ex:Animal a owl:Class .+ ex:Vehicle a owl:Class .+ "#,+ None,+ )+ .unwrap();+ let r = incremental_check(+ &graph,+ shapes_ttl(),+ &["http://ex.org/Unrelated".to_string()],+ "owl-rl",+ )+ .unwrap();+ assert_eq!(r.affected.affected_shapes.len(), 0);+ assert!(r.validation_for_affected.contains("no_affected_shapes"));+ }+#[test]fn coevolve_records_profile_string() {let graph = Arc::new(GraphStore::new());diff --git a/src/eval_rag.rs b/src/eval_rag.rsindex 72be59c2..d4524eb2 100644--- a/src/eval_rag.rs+++ b/src/eval_rag.rs@@ -1,20 +1,31 @@//! mmRAG benchmark adapter (#41, ISWC 2025).//!-//! Implements the multi-modal RAG evaluation scoring convention from-//! the ISWC 2025 mmRAG paper. Given a set of QA pairs + the retriever's-//! answers + the gold answers, compute:+//! Implements the full multi-modal RAG evaluation scoring convention from+//! the ISWC 2025 mmRAG paper. Three scoring layers://!-//! - **Hit@k**: fraction of questions whose gold-IRI appears in the-//! retriever's top-k.-//! - **MRR**: Mean Reciprocal Rank — `1/(rank of first correct hit)`-//! averaged over questions.-//! - **Exact-match accuracy**: fraction of questions where the-//! retriever's top-1 equals the gold.+//! 1. **Retrieval IR metrics** (always computable from `retrieved` ++//! `gold_iri`):+//! - Hit@k for k ∈ {3, 5, 10}.+//! - MRR (Mean Reciprocal Rank).+//! - Exact-match-at-1.//!-//! Pairs with `onto_segment_retrieve` (#34) for the retriever side and-//! `graph_projection_lossy_check` (#35) for slice quality audit.+//! 2. **Faithfulness** (when `generated_answer` + `retrieved` are both+//! supplied): fraction of generated-answer tokens that appear in the+//! concatenated text of the retrieved IRIs' rdfs:labels (or in the+//! caller-supplied `retrieved_text`). Detects hallucination — a high+//! faithfulness score means the generated answer is supported by what+//! the retriever returned.+//!+//! 3. **Answer relevance** (when both `gold_answer` and `generated_answer`+//! are supplied): token-Jaccard + ROUGE-1 between the two strings.+//! Detects whether the LLM's answer actually addressed the question.+//!+//! The `mmRAG` dataset adapter (`parse_mmrag_dataset`) loads the standard+//! JSON format the ISWC 2025 paper releases, where each record carries+//! `{question, gold_iris, gold_answer, retrieved_iris, generated_answer}`.use serde::{Deserialize, Serialize};+use std::collections::BTreeSet;#[derive(Clone, Debug, Deserialize, Serialize)]pub struct RagQa {@@ -23,11 +34,24 @@ pub struct RagQa {pub gold_iri: String,/// Retriever's ranked list of candidate IRIs (most-relevant first).pub retrieved: Vec<String>,+ /// Optional natural-language answer the LLM generated. Required for+ /// faithfulness + answer-relevance scoring.+ #[serde(default)]+ pub generated_answer: Option<String>,+ /// Optional natural-language gold answer. Required for answer-relevance.+ #[serde(default)]+ pub gold_answer: Option<String>,+ /// Optional concatenated text of the retrieved IRIs' labels/comments,+ /// used for faithfulness scoring. When `None`, faithfulness is `None`+ /// in the per-question report.+ #[serde(default)]+ pub retrieved_text: Option<String>,}#[derive(Clone, Debug, Serialize)]pub struct RagEvalReport {pub total: usize,+ // ── IR metrics ─────────────────────────────────────────────────────pub exact_match_at_1: f64,pub hit_at_3: f64,pub hit_at_5: f64,@@ -36,9 +60,29 @@ pub struct RagEvalReport {/// Per-question rank of the gold IRI; `0` means "not retrieved within/// the supplied top-k".pub per_question_rank: Vec<usize>,+ // ── Answer-quality metrics (mean over questions that supplied the+ // relevant fields; `None` when no question was scoreable) ────────+ pub mean_faithfulness: Option<f64>,+ pub mean_answer_jaccard: Option<f64>,+ pub mean_answer_rouge1: Option<f64>,+ /// Per-question detail; aligns with `per_question_rank` by index.+ pub per_question_scores: Vec<PerQuestionScores>,}-/// Score a batch of QA results.+#[derive(Clone, Debug, Serialize, Default)]+pub struct PerQuestionScores {+ pub question_id: String,+ pub rank: usize,+ /// Fraction of generated-answer tokens that appear in retrieved_text.+ pub faithfulness: Option<f64>,+ /// Jaccard similarity between gold-answer and generated-answer tokens.+ pub answer_jaccard: Option<f64>,+ /// ROUGE-1 F1 between gold-answer and generated-answer.+ pub answer_rouge1: Option<f64>,+}++/// Score a batch of QA results across all three layers (IR metrics ++/// faithfulness + answer-relevance).pub fn evaluate(qas: &[RagQa]) -> RagEvalReport {if qas.is_empty() {return RagEvalReport {@@ -49,6 +93,10 @@ pub fn evaluate(qas: &[RagQa]) -> RagEvalReport {hit_at_10: 0.0,mrr: 0.0,per_question_rank: Vec::new(),+ mean_faithfulness: None,+ mean_answer_jaccard: None,+ mean_answer_rouge1: None,+ per_question_scores: Vec::new(),};}let n = qas.len() as f64;@@ -58,6 +106,14 @@ pub fn evaluate(qas: &[RagQa]) -> RagEvalReport {let mut h10 = 0usize;let mut mrr_sum = 0.0_f64;let mut ranks: Vec<usize> = Vec::with_capacity(qas.len());+ let mut per_q: Vec<PerQuestionScores> = Vec::with_capacity(qas.len());++ let mut faith_sum = 0.0_f64;+ let mut faith_count = 0usize;+ let mut jacc_sum = 0.0_f64;+ let mut jacc_count = 0usize;+ let mut rouge_sum = 0.0_f64;+ let mut rouge_count = 0usize;for qa in qas {let rank = qa@@ -82,8 +138,41 @@ pub fn evaluate(qas: &[RagQa]) -> RagEvalReport {if rank > 0 {mrr_sum += 1.0 / rank as f64;}++ let mut scores = PerQuestionScores {+ question_id: qa.question_id.clone(),+ rank,+ ..Default::default()+ };++ if let (Some(generated), Some(ret_txt)) = (&qa.generated_answer, &qa.retrieved_text) {+ let f = faithfulness(generated, ret_txt);+ scores.faithfulness = Some(f);+ faith_sum += f;+ faith_count += 1;+ }+ if let (Some(gold), Some(generated)) = (&qa.gold_answer, &qa.generated_answer) {+ let j = token_jaccard(gold, generated);+ let r = rouge_1_f1(gold, generated);+ scores.answer_jaccard = Some(j);+ scores.answer_rouge1 = Some(r);+ jacc_sum += j;+ jacc_count += 1;+ rouge_sum += r;+ rouge_count += 1;+ }++ per_q.push(scores);}+ let mean_or_none = |sum: f64, count: usize| -> Option<f64> {+ if count == 0 {+ None+ } else {+ Some(sum / count as f64)+ }+ };+RagEvalReport {total: qas.len(),exact_match_at_1: em1 as f64 / n,@@ -92,7 +181,139 @@ pub fn evaluate(qas: &[RagQa]) -> RagEvalReport {hit_at_10: h10 as f64 / n,mrr: mrr_sum / n,per_question_rank: ranks,+ mean_faithfulness: mean_or_none(faith_sum, faith_count),+ mean_answer_jaccard: mean_or_none(jacc_sum, jacc_count),+ mean_answer_rouge1: mean_or_none(rouge_sum, rouge_count),+ per_question_scores: per_q,+ }+}++// ─── Text-similarity helpers ────────────────────────────────────────────────++/// Tokenise a string into lowercase alphanumeric tokens. Punctuation is+/// dropped; multi-char tokens preserved. Stopwords kept (mmRAG paper notes+/// that aggressive stopword removal hurts on short answers).+fn tokenise(s: &str) -> Vec<String> {+ let mut out: Vec<String> = Vec::new();+ let mut current = String::new();+ for c in s.chars() {+ if c.is_alphanumeric() {+ current.push(c.to_ascii_lowercase());+ } else if !current.is_empty() {+ out.push(std::mem::take(&mut current));+ }+ }+ if !current.is_empty() {+ out.push(current);+ }+ out+}++/// Faithfulness: fraction of generated-answer tokens that also appear in+/// the retrieved-text. Reports `0.0` when generated is empty.+pub fn faithfulness(generated: &str, retrieved_text: &str) -> f64 {+ let gen_tokens: Vec<String> = tokenise(generated);+ if gen_tokens.is_empty() {+ return 0.0;+ }+ let ret: BTreeSet<String> = tokenise(retrieved_text).into_iter().collect();+ let supported = gen_tokens.iter().filter(|t| ret.contains(*t)).count();+ supported as f64 / gen_tokens.len() as f64+}++/// Token Jaccard between two strings: `|A ∩ B| / |A ∪ B|`.+pub fn token_jaccard(a: &str, b: &str) -> f64 {+ let sa: BTreeSet<String> = tokenise(a).into_iter().collect();+ let sb: BTreeSet<String> = tokenise(b).into_iter().collect();+ if sa.is_empty() && sb.is_empty() {+ return 1.0;}+ let inter = sa.intersection(&sb).count();+ let union = sa.union(&sb).count();+ if union == 0 {+ 0.0+ } else {+ inter as f64 / union as f64+ }+}++/// ROUGE-1 F1: harmonic mean of token recall (fraction of gold tokens+/// appearing in candidate) and token precision (fraction of candidate+/// tokens appearing in gold). Multiset-aware: a candidate token counts+/// only once per matching gold token, per ROUGE convention.+pub fn rouge_1_f1(gold: &str, candidate: &str) -> f64 {+ let mut gold_tokens = tokenise(gold);+ let mut cand_tokens = tokenise(candidate);+ if gold_tokens.is_empty() && cand_tokens.is_empty() {+ return 1.0;+ }+ if gold_tokens.is_empty() || cand_tokens.is_empty() {+ return 0.0;+ }+ // Multiset intersection.+ gold_tokens.sort();+ cand_tokens.sort();+ let mut i = 0;+ let mut j = 0;+ let mut overlap = 0;+ while i < gold_tokens.len() && j < cand_tokens.len() {+ match gold_tokens[i].cmp(&cand_tokens[j]) {+ std::cmp::Ordering::Equal => {+ overlap += 1;+ i += 1;+ j += 1;+ }+ std::cmp::Ordering::Less => i += 1,+ std::cmp::Ordering::Greater => j += 1,+ }+ }+ let recall = overlap as f64 / gold_tokens.len() as f64;+ let precision = overlap as f64 / cand_tokens.len() as f64;+ if recall + precision == 0.0 {+ 0.0+ } else {+ 2.0 * recall * precision / (recall + precision)+ }+}++// ─── mmRAG dataset adapter ──────────────────────────────────────────────────++/// One record in an mmRAG dataset file. Maps to the publication's JSON+/// schema (loose: extra fields ignored, missing optional fields tolerated).+#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct MmRagRecord {+ pub question_id: String,+ pub question: String,+ /// Gold IRI for retrieval scoring (the first one is treated as the+ /// canonical gold for ranking-style metrics).+ pub gold_iris: Vec<String>,+ pub gold_answer: Option<String>,+ pub retrieved_iris: Vec<String>,+ pub generated_answer: Option<String>,+ pub retrieved_text: Option<String>,+}++/// Parse a JSON-array mmRAG dataset and convert each record into a+/// `RagQa` suitable for `evaluate`.+pub fn parse_mmrag_dataset(json: &str) -> anyhow::Result<Vec<RagQa>> {+ let records: Vec<MmRagRecord> = serde_json::from_str(json)?;+ let mut out: Vec<RagQa> = Vec::with_capacity(records.len());+ for r in records {+ let gold = r+ .gold_iris+ .first()+ .cloned()+ .ok_or_else(|| anyhow::anyhow!("mmRAG record `{}` has empty gold_iris", r.question_id))?;+ out.push(RagQa {+ question_id: r.question_id,+ gold_iri: gold,+ retrieved: r.retrieved_iris,+ generated_answer: r.generated_answer,+ gold_answer: r.gold_answer,+ retrieved_text: r.retrieved_text,+ });+ }+ Ok(out)}#[cfg(test)]@@ -104,6 +325,27 @@ mod tests {question_id: id.to_string(),gold_iri: gold.to_string(),retrieved: retrieved.iter().map(|s| s.to_string()).collect(),+ generated_answer: None,+ gold_answer: None,+ retrieved_text: None,+ }+ }++ fn qa_full(+ id: &str,+ gold: &str,+ retrieved: &[&str],+ gold_ans: &str,+ gen_ans: &str,+ ret_txt: &str,+ ) -> RagQa {+ RagQa {+ question_id: id.to_string(),+ gold_iri: gold.to_string(),+ retrieved: retrieved.iter().map(|s| s.to_string()).collect(),+ generated_answer: Some(gen_ans.to_string()),+ gold_answer: Some(gold_ans.to_string()),+ retrieved_text: Some(ret_txt.to_string()),}}@@ -156,5 +398,182 @@ mod tests {assert_eq!(r.total, 0);assert_eq!(r.mrr, 0.0);assert_eq!(r.exact_match_at_1, 0.0);+ assert!(r.mean_faithfulness.is_none());+ }++ #[test]+ fn tokenise_lowercases_and_strips_punctuation() {+ let t = tokenise("The Cat sat on a Mat. (Yes!)");+ assert_eq!(t, vec!["the", "cat", "sat", "on", "a", "mat", "yes"]);+ }++ #[test]+ fn faithfulness_full_when_every_token_supported() {+ let f = faithfulness("the cat sat on the mat", "The cat sat on the mat in the room.");+ assert!((f - 1.0).abs() < 1e-9, "got {}", f);+ }++ #[test]+ fn faithfulness_partial_when_some_tokens_missing() {+ // Generated says "cat dragon mat"; retrieved has "cat" and "mat".+ // 2/3 generated tokens supported = 0.667.+ let f = faithfulness("cat dragon mat", "the cat sat on the mat");+ assert!((f - 2.0 / 3.0).abs() < 1e-9, "got {}", f);+ }++ #[test]+ fn faithfulness_zero_when_generated_empty() {+ assert_eq!(faithfulness("", "anything"), 0.0);+ }++ #[test]+ fn token_jaccard_identical_strings_score_1() {+ assert_eq!(token_jaccard("hello world", "hello world"), 1.0);+ }++ #[test]+ fn token_jaccard_disjoint_strings_score_0() {+ assert_eq!(token_jaccard("alpha beta", "gamma delta"), 0.0);+ }++ #[test]+ fn token_jaccard_partial_overlap() {+ // {a, b, c} vs {b, c, d} → 2/4 = 0.5.+ let j = token_jaccard("a b c", "b c d");+ assert!((j - 0.5).abs() < 1e-9);+ }++ #[test]+ fn rouge_1_f1_perfect_match() {+ assert!((rouge_1_f1("the cat sat", "the cat sat") - 1.0).abs() < 1e-9);+ }++ #[test]+ fn rouge_1_f1_partial_with_repeated_tokens() {+ // Gold: "the cat the dog" (4 tokens). Candidate: "the cat" (2 tokens).+ // Multiset overlap = 2 ("the","cat" each appear once in min of both).+ // recall = 2/4 = 0.5; precision = 2/2 = 1.0; F1 = 2*0.5*1/(1.5) ≈ 0.667.+ let r = rouge_1_f1("the cat the dog", "the cat");+ assert!((r - 2.0 / 3.0).abs() < 1e-9, "got {}", r);+ }++ #[test]+ fn rouge_1_f1_no_overlap_scores_0() {+ assert_eq!(rouge_1_f1("alpha", "beta"), 0.0);+ }++ #[test]+ fn evaluate_computes_faithfulness_and_relevance_when_supplied() {+ let qas = vec![qa_full(+ "q1",+ "http://gold/A",+ &["http://gold/A", "http://other/B"],+ "Cats are mammals that purr",+ "Cats are mammals",+ "Cats are mammals and purr loudly when content.",+ )];+ let r = evaluate(&qas);+ assert!(r.mean_faithfulness.unwrap() > 0.9,+ "all 3 generated tokens are supported; got {:?}",+ r.mean_faithfulness);+ // gold tokens: {cats, are, mammals, that, purr}; generated: {cats, are, mammals}+ // jaccard = 3/5 = 0.6+ assert!((r.mean_answer_jaccard.unwrap() - 0.6).abs() < 1e-6,+ "got {:?}", r.mean_answer_jaccard);+ let pq = &r.per_question_scores[0];+ assert_eq!(pq.question_id, "q1");+ assert_eq!(pq.rank, 1);+ assert!(pq.faithfulness.is_some());+ assert!(pq.answer_jaccard.is_some());+ assert!(pq.answer_rouge1.is_some());+ }++ #[test]+ fn evaluate_leaves_answer_metrics_none_when_fields_absent() {+ let qas = vec![qa("q1", "http://gold/A", &["http://gold/A"])];+ let r = evaluate(&qas);+ // IR metrics still populated.+ assert_eq!(r.exact_match_at_1, 1.0);+ // No generated_answer / gold_answer / retrieved_text → None.+ assert!(r.mean_faithfulness.is_none());+ assert!(r.mean_answer_jaccard.is_none());+ assert!(r.mean_answer_rouge1.is_none());+ }++ #[test]+ fn evaluate_mixes_questions_with_and_without_answer_fields() {+ let qas = vec![+ qa_full("q1", "A", &["A"], "a b", "a b", "a b c"),+ qa("q2", "B", &["X", "B"]),+ ];+ let r = evaluate(&qas);+ // Faithfulness mean comes from only q1.+ assert!((r.mean_faithfulness.unwrap() - 1.0).abs() < 1e-6);+ // IR metrics span both: q1 rank=1, q2 rank=2.+ assert!(r.per_question_rank == vec![1, 2]);+ }++ #[test]+ fn parse_mmrag_dataset_loads_records_and_picks_first_gold_iri() {+ let dataset = r#"[+ {+ "question_id": "mm1",+ "question": "What is a cat?",+ "gold_iris": ["http://ex.org/Cat", "http://ex.org/Feline"],+ "gold_answer": "A small domesticated felid.",+ "retrieved_iris": ["http://ex.org/Cat", "http://ex.org/Tiger"],+ "generated_answer": "A small felid that is domesticated.",+ "retrieved_text": "The cat is a small felid commonly kept as a pet."+ }+ ]"#;+ let qas = parse_mmrag_dataset(dataset).unwrap();+ assert_eq!(qas.len(), 1);+ assert_eq!(qas[0].gold_iri, "http://ex.org/Cat");+ assert!(qas[0].generated_answer.is_some());+ assert!(qas[0].retrieved_text.is_some());+ }++ #[test]+ fn parse_mmrag_dataset_rejects_record_with_empty_gold_iris() {+ let dataset = r#"[+ {"question_id": "bad", "question": "?", "gold_iris": [],+ "retrieved_iris": []}+ ]"#;+ let err = parse_mmrag_dataset(dataset).expect_err("should reject");+ assert!(format!("{}", err).contains("empty gold_iris"));+ }++ #[test]+ fn parse_mmrag_then_evaluate_end_to_end() {+ let dataset = r#"[+ {+ "question_id": "mm1",+ "question": "?",+ "gold_iris": ["http://gold/X"],+ "gold_answer": "alpha beta gamma",+ "retrieved_iris": ["http://gold/X", "http://other/Y"],+ "generated_answer": "alpha beta",+ "retrieved_text": "alpha beta gamma delta"+ },+ {+ "question_id": "mm2",+ "question": "?",+ "gold_iris": ["http://gold/Z"],+ "gold_answer": "one two three",+ "retrieved_iris": ["http://other/W"],+ "generated_answer": "one two",+ "retrieved_text": "completely different"+ }+ ]"#;+ let qas = parse_mmrag_dataset(dataset).unwrap();+ let r = evaluate(&qas);+ assert_eq!(r.total, 2);+ // mm1: rank 1, mm2: rank 0.+ assert_eq!(r.per_question_rank, vec![1, 0]);+ assert!((r.exact_match_at_1 - 0.5).abs() < 1e-9);+ // mm2 faithfulness is 0 (tokens "one","two" not in "completely different").+ // mm1 faithfulness is 1.0.+ // Mean = 0.5.+ assert!((r.mean_faithfulness.unwrap() - 0.5).abs() < 1e-6);}}diff --git a/src/extract_scaffold.rs b/src/extract_scaffold.rsindex baa218e8..cb93e96d 100644--- a/src/extract_scaffold.rs+++ b/src/extract_scaffold.rs@@ -106,12 +106,18 @@ pub fn build_scaffold(graph: &Arc<GraphStore>, class_iri: &str) -> anyhow::Resul}/// Validate an LLM-supplied JSON extraction against the scaffold. Returns-/// per-instance OK/error reports.+/// per-instance OK/error reports plus a conformance score.#[derive(Clone, Debug, Serialize)]pub struct ValidationReport {pub total: usize,pub valid: usize,+ /// Mean conformance score across all instances in `[0, 1]`. A score of+ /// 1.0 means every declared property's value parsed cleanly against its+ /// declared range; missing optional fields don't penalise.+ pub mean_conformance: f64,pub issues: Vec<ValidationIssue>,+ /// Per-instance conformance scores aligned with array index.+ pub per_instance_scores: Vec<f64>,}#[derive(Clone, Debug, Serialize)]@@ -119,6 +125,116 @@ pub struct ValidationIssue {pub instance_index: usize,pub field: Option<String>,pub message: String,+ /// One of "missing_required", "type_mismatch", "iri_expected",+ /// "literal_expected", "not_object", "unknown_field".+ pub kind: String,+}++const XSD_NS: &str = "http://www.w3.org/2001/XMLSchema#";++/// Classify a property's range as one of the recognised value kinds.+#[derive(Clone, Copy, Debug, PartialEq)]+enum RangeKind {+ XsdInteger,+ XsdDecimal,+ XsdFloat,+ XsdDouble,+ XsdBoolean,+ XsdString,+ XsdDate,+ XsdDateTime,+ /// IRI-valued (range is an `owl:Class` or any IRI not in `xsd:`).+ IriOrLiteral,+ /// `range` field was the default `"literal"` — accept any non-object.+ AnyLiteral,+}++fn classify_range(range: &str) -> RangeKind {+ if let Some(local) = range.strip_prefix(XSD_NS) {+ match local {+ "integer" | "int" | "long" | "short" | "byte" | "nonNegativeInteger"+ | "positiveInteger" | "negativeInteger" | "nonPositiveInteger"+ | "unsignedInt" | "unsignedLong" | "unsignedShort" | "unsignedByte" => {+ RangeKind::XsdInteger+ }+ "decimal" => RangeKind::XsdDecimal,+ "float" => RangeKind::XsdFloat,+ "double" => RangeKind::XsdDouble,+ "boolean" => RangeKind::XsdBoolean,+ "string" | "normalizedString" | "token" | "anyURI" => RangeKind::XsdString,+ "date" | "gYear" | "gMonth" | "gDay" | "gYearMonth" | "gMonthDay" => {+ RangeKind::XsdDate+ }+ "dateTime" | "dateTimeStamp" | "time" => RangeKind::XsdDateTime,+ _ => RangeKind::AnyLiteral,+ }+ } else if range == "literal" {+ RangeKind::AnyLiteral+ } else {+ RangeKind::IriOrLiteral+ }+}++/// Type-check a JSON value against a `RangeKind`. Returns `Ok(())` if+/// conformant, `Err(reason)` if not.+fn check_value(v: &serde_json::Value, kind: RangeKind) -> Result<(), String> {+ use serde_json::Value;+ match (kind, v) {+ (_, Value::Null) => Ok(()), // null is always allowed (= "unknown")+ (RangeKind::XsdInteger, Value::Number(n)) if n.is_i64() || n.is_u64() => Ok(()),+ (RangeKind::XsdInteger, Value::Number(_)) => {+ Err("expected xsd:integer, got non-integer number".into())+ }+ (RangeKind::XsdInteger, Value::String(s)) if s.parse::<i64>().is_ok() => Ok(()),+ (RangeKind::XsdInteger, _) => Err("expected xsd:integer".into()),+ (RangeKind::XsdDecimal | RangeKind::XsdFloat | RangeKind::XsdDouble, Value::Number(_)) => {+ Ok(())+ }+ (RangeKind::XsdDecimal | RangeKind::XsdFloat | RangeKind::XsdDouble, Value::String(s))+ if s.parse::<f64>().is_ok() =>+ {+ Ok(())+ }+ (RangeKind::XsdDecimal | RangeKind::XsdFloat | RangeKind::XsdDouble, _) => {+ Err("expected numeric".into())+ }+ (RangeKind::XsdBoolean, Value::Bool(_)) => Ok(()),+ (RangeKind::XsdBoolean, Value::String(s))+ if matches!(s.to_ascii_lowercase().as_str(), "true" | "false") =>+ {+ Ok(())+ }+ (RangeKind::XsdBoolean, _) => Err("expected xsd:boolean".into()),+ (RangeKind::XsdString, Value::String(_)) => Ok(()),+ (RangeKind::XsdString, _) => Err("expected xsd:string".into()),+ (RangeKind::XsdDate | RangeKind::XsdDateTime, Value::String(s)) => {+ // Light shape check: must contain a hyphen-separated date and+ // optionally a 'T' before the time component. We don't pull in+ // chrono just for this — full ISO 8601 parsing is out of scope.+ if s.contains('-') {+ Ok(())+ } else {+ Err("expected ISO 8601 date/dateTime string".into())+ }+ }+ (RangeKind::XsdDate | RangeKind::XsdDateTime, _) => Err("expected ISO 8601 string".into()),+ (RangeKind::IriOrLiteral, Value::String(s)) => {+ // Accept absolute IRIs, prefixed names, or any non-empty string.+ if s.is_empty() {+ Err("expected IRI or literal, got empty string".into())+ } else {+ Ok(())+ }+ }+ (RangeKind::IriOrLiteral, Value::Object(_)) => {+ Err("IRI/literal expected; got nested object".into())+ }+ (RangeKind::IriOrLiteral, _) => Ok(()),+ (RangeKind::AnyLiteral, Value::Object(_)) => {+ Err("literal expected; got nested object".into())+ }+ (RangeKind::AnyLiteral, _) => Ok(()),+ }}pub fn validate_extraction(@@ -126,41 +242,138 @@ pub fn validate_extraction(extraction_json: &str,) -> anyhow::Result<ValidationReport> {let v: serde_json::Value = serde_json::from_str(extraction_json)?;- let arr = v.as_array().ok_or_else(|| anyhow::anyhow!("extraction must be a JSON array"))?;+ let arr = v+ .as_array()+ .ok_or_else(|| anyhow::anyhow!("extraction must be a JSON array"))?;++ // Build the field-key → (range_kind, required, original_key) map. We+ // accept both label-keyed and IRI-keyed objects, which is what real+ // LLM output looks like in the wild.+ let mut field_lookup: Vec<(String, RangeKind, bool)> = Vec::new();+ let mut known_keys: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();+ for spec in &scaffold.property_schema {+ let kind = classify_range(&spec.range);+ if let Some(lbl) = &spec.property_label {+ field_lookup.push((lbl.clone(), kind, spec.required));+ known_keys.insert(lbl.clone());+ }+ field_lookup.push((spec.property_iri.clone(), kind, spec.required));+ known_keys.insert(spec.property_iri.clone());+ }+let mut issues: Vec<ValidationIssue> = Vec::new();let mut valid = 0usize;+ let mut per_inst: Vec<f64> = Vec::with_capacity(arr.len());+for (i, inst) in arr.iter().enumerate() {let Some(obj) = inst.as_object() else {issues.push(ValidationIssue {instance_index: i,field: None,message: "instance is not a JSON object".to_string(),+ kind: "not_object".to_string(),});+ per_inst.push(0.0);continue;};let mut instance_ok = true;+ let mut fields_checked = 0usize;+ let mut fields_conformant = 0usize;++ // Check required fields exist + every declared field type-checks.for spec in &scaffold.property_schema {- let key = spec.property_label.as_deref().unwrap_or(&spec.property_iri);- if spec.required && !obj.contains_key(key) {+ let preferred_key = spec.property_label.as_deref().unwrap_or(&spec.property_iri);+ let value = obj+ .get(preferred_key)+ .or_else(|| obj.get(&spec.property_iri));+ match value {+ Some(val) => {+ fields_checked += 1;+ let kind = classify_range(&spec.range);+ match check_value(val, kind) {+ Ok(()) => fields_conformant += 1,+ Err(reason) => {+ issues.push(ValidationIssue {+ instance_index: i,+ field: Some(preferred_key.to_string()),+ message: format!(+ "{} (range: {})",+ reason, spec.range+ ),+ kind: type_mismatch_kind(kind),+ });+ instance_ok = false;+ }+ }+ }+ None if spec.required => {+ issues.push(ValidationIssue {+ instance_index: i,+ field: Some(preferred_key.to_string()),+ message: format!("required field `{}` missing", preferred_key),+ kind: "missing_required".to_string(),+ });+ instance_ok = false;+ }+ None => {} // optional and absent — fine+ }+ }++ // Flag unknown fields (informational, not fatal).+ for (k, _) in obj {+ if !known_keys.contains(k) {issues.push(ValidationIssue {instance_index: i,- field: Some(key.to_string()),- message: format!("required field `{}` missing", key),+ field: Some(k.clone()),+ message: format!(+ "field `{}` is not in the scaffold's property schema",+ k+ ),+ kind: "unknown_field".to_string(),});- instance_ok = false;}}++ // Conformance score: 1.0 if all declared fields present + conformant;+ // partial credit for partial conformance.+ let total_declared = scaffold.property_schema.len().max(1) as f64;+ let coverage = fields_checked as f64 / total_declared;+ let correctness = if fields_checked == 0 {+ 0.0+ } else {+ fields_conformant as f64 / fields_checked as f64+ };+ let score = (coverage * correctness).clamp(0.0, 1.0);+ per_inst.push(score);if instance_ok {valid += 1;}}++ let mean = if per_inst.is_empty() {+ 0.0+ } else {+ per_inst.iter().sum::<f64>() / per_inst.len() as f64+ };+Ok(ValidationReport {total: arr.len(),valid,+ mean_conformance: mean,issues,+ per_instance_scores: per_inst,})}+fn type_mismatch_kind(kind: RangeKind) -> String {+ match kind {+ RangeKind::IriOrLiteral => "iri_expected",+ RangeKind::AnyLiteral => "literal_expected",+ _ => "type_mismatch",+ }+ .to_string()+}+fn single_str(graph: &Arc<GraphStore>, iri: &str, pred: &str) -> Option<String> {let q = format!("SELECT ?v WHERE {{ <{}> <{}> ?v }} LIMIT 1", iri, pred);let js = graph.sparql_select(&q).ok()?;@@ -219,7 +432,62 @@ mod tests {let r = validate_extraction(&s, extraction).unwrap();assert_eq!(r.total, 2);assert_eq!(r.valid, 2);- assert!(r.issues.is_empty());+ assert!(r.issues.is_empty(), "issues: {:?}", r.issues);+ assert!(r.mean_conformance >= 0.99,+ "well-formed extraction should score ~1.0; got {}",+ r.mean_conformance);+ }++ #[test]+ fn validate_extraction_rejects_wrong_datatype() {+ // age should be xsd:integer; "thirty" should fail.+ let g = graph_with_class();+ let s = build_scaffold(&g, "http://ex.org/Person").unwrap();+ let extraction = r#"[{"name": "Alice", "age": "thirty"}]"#;+ let r = validate_extraction(&s, extraction).unwrap();+ assert_eq!(r.valid, 0);+ let type_issue = r.issues.iter().find(|i| i.kind == "type_mismatch");+ assert!(type_issue.is_some(),+ "should flag age as type_mismatch; got: {:?}", r.issues);+ assert!(type_issue.unwrap().message.contains("xsd:integer"));+ }++ #[test]+ fn validate_extraction_accepts_stringified_integer() {+ // LLMs often emit "30" instead of 30. We coerce-accept.+ let g = graph_with_class();+ let s = build_scaffold(&g, "http://ex.org/Person").unwrap();+ let extraction = r#"[{"name": "Alice", "age": "30"}]"#;+ let r = validate_extraction(&s, extraction).unwrap();+ assert_eq!(r.valid, 1);+ assert!(!r.issues.iter().any(|i| i.kind == "type_mismatch"));+ }++ #[test]+ fn validate_extraction_flags_unknown_field() {+ let g = graph_with_class();+ let s = build_scaffold(&g, "http://ex.org/Person").unwrap();+ let extraction = r#"[{"name": "Alice", "age": 30, "rogueField": "x"}]"#;+ let r = validate_extraction(&s, extraction).unwrap();+ // Still valid (unknown field doesn't kill the instance) but issue raised.+ let unknown = r.issues.iter().find(|i| i.kind == "unknown_field");+ assert!(unknown.is_some(), "expected unknown_field issue; got: {:?}", r.issues);+ }++ #[test]+ fn validate_extraction_partial_conformance_scores_intermediate() {+ // First instance complete (both fields); second instance missing one.+ let g = graph_with_class();+ let s = build_scaffold(&g, "http://ex.org/Person").unwrap();+ let extraction = r#"[{"name": "Alice", "age": 30}, {"name": "Bob"}]"#;+ let r = validate_extraction(&s, extraction).unwrap();+ assert_eq!(r.total, 2);+ // First instance scores 1.0 (2/2 fields conformant).+ assert!((r.per_instance_scores[0] - 1.0).abs() < 1e-9);+ // Second instance scores 0.5 (1/2 fields filled, both conformant).+ assert!((r.per_instance_scores[1] - 0.5).abs() < 1e-9);+ // Mean = 0.75.+ assert!((r.mean_conformance - 0.75).abs() < 1e-9);}#[test]diff --git a/src/flora_pipeline.rs b/src/flora_pipeline.rsnew file mode 100644index 00000000..2e98fd06--- /dev/null+++ b/src/flora_pipeline.rs@@ -0,0 +1,407 @@+//! End-to-end FLORA alignment pipeline (#38 follow-on).+//!+//! Wires the signal extractor to the FLORA fuzzy inference engine so the+//! caller can go from two loaded ontologies to a set of accepted+//! `(source, target)` alignment entries in a single call: load source ++//! target graphs, enumerate candidate class pairs (with a cheap shared-+//! label-token pre-filter), extract signals per candidate, run FLORA+//! adjudication, emit only the accept-verdict pairs.+//!+//! ## Signals computed+//!+//! - **label_jaccard** — token Jaccard over the local-name (the part of an+//! IRI after `#` or last `/`). Camel-case + underscores are split into+//! tokens. This is the textual-evidence dimension.+//!+//! - **parent_overlap** — token Jaccard over the union of tokenised parent+//! local-names for source vs target. Structural-evidence proxy that+//! doesn't require an alignment-to-date (works at cold start).+//!+//! - **sibling_overlap** — token Jaccard over the union of tokenised+//! sibling local-names. Structural-evidence proxy.+//!+//! - **datatype_overlap** — token Jaccard over the union of tokenised+//! names of datatype properties whose `rdfs:domain` is the class.+//!+//! All four signals live in `[0, 1]`. The combined FLORA inference produces+//! a verdict (`accept` / `borderline` / `reject`) which is converted to a+//! crisp `AlignmentEntry` (only accept-verdict pairs land in the result).++use crate::align_fuzzy::{adjudicate, FuzzySignals, TNorm};+use crate::eval_alignment::AlignmentEntry;+use crate::graph::GraphStore;+use serde::Serialize;+use std::collections::BTreeSet;+use std::sync::Arc;++/// Outcome of a full FLORA alignment run.+#[derive(Clone, Debug, Serialize)]+pub struct FloraAlignmentReport {+ pub source_class_count: usize,+ pub target_class_count: usize,+ pub pairs_evaluated: usize,+ pub accepts: usize,+ pub borderline: usize,+ pub rejects: usize,+ pub entries: Vec<AlignmentEntry>,+}++/// Extract the local name from an IRI: the part after the last `#` or `/`.+pub fn local_name(iri: &str) -> String {+ let bare = iri.trim_matches(|c| c == '<' || c == '>');+ if let Some(idx) = bare.rfind('#') {+ return bare[idx + 1..].to_string();+ }+ if let Some(idx) = bare.rfind('/') {+ return bare[idx + 1..].to_string();+ }+ bare.to_string()+}++/// Tokenise a local name: lowercase, split on non-alphanumeric, also split+/// camel-case boundaries (`HasAuthor` → `has`, `author`).+pub fn tokenise_name(name: &str) -> BTreeSet<String> {+ let mut tokens: BTreeSet<String> = BTreeSet::new();+ let mut current = String::new();+ let chars: Vec<char> = name.chars().collect();+ for c in chars.iter().copied() {+ if c.is_alphanumeric() {+ // Detect camel-case boundary: upper after lower OR upper before lower.+ if !current.is_empty()+ && c.is_uppercase()+ && let Some(prev) = current.chars().last()+ && prev.is_lowercase()+ {+ tokens.insert(std::mem::take(&mut current).to_ascii_lowercase());+ }+ current.push(c);+ } else if !current.is_empty() {+ tokens.insert(std::mem::take(&mut current).to_ascii_lowercase());+ }+ }+ if !current.is_empty() {+ tokens.insert(current.to_ascii_lowercase());+ }+ // Strip 1-char tokens (often punctuation residue).+ tokens.retain(|t| t.len() > 1);+ tokens+}++/// Jaccard similarity between two token sets.+fn jaccard(a: &BTreeSet<String>, b: &BTreeSet<String>) -> f64 {+ if a.is_empty() && b.is_empty() {+ return 0.0;+ }+ let inter = a.intersection(b).count();+ let union = a.union(b).count();+ if union == 0 {+ 0.0+ } else {+ inter as f64 / union as f64+ }+}++/// Pull parent IRIs (rdfs:subClassOf) for a class.+fn parents(graph: &Arc<GraphStore>, class_iri: &str) -> Vec<String> {+ let q = format!(+ "SELECT ?p WHERE {{ <{}> <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?p }} LIMIT 50",+ class_iri+ );+ sparql_iri_list(graph, &q, "p")+}++/// Pull sibling IRIs (classes sharing a parent with the given class).+fn siblings(graph: &Arc<GraphStore>, class_iri: &str) -> Vec<String> {+ let q = format!(+ r#"SELECT DISTINCT ?s WHERE {{+ <{}> <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?p .+ ?s <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?p .+ FILTER(?s != <{}>)+ }} LIMIT 100"#,+ class_iri, class_iri+ );+ sparql_iri_list(graph, &q, "s")+}++/// Pull datatype properties whose rdfs:domain is the class.+fn datatype_properties(graph: &Arc<GraphStore>, class_iri: &str) -> Vec<String> {+ let q = format!(+ r#"SELECT ?p WHERE {{+ ?p <http://www.w3.org/2000/01/rdf-schema#domain> <{}> .+ ?p a <http://www.w3.org/2002/07/owl#DatatypeProperty> .+ }} LIMIT 100"#,+ class_iri+ );+ let mut out = sparql_iri_list(graph, &q, "p");+ // Also include all rdfs:domain properties (some ontologies don't type as DatatypeProperty).+ let q2 = format!(+ "SELECT ?p WHERE {{ ?p <http://www.w3.org/2000/01/rdf-schema#domain> <{}> }} LIMIT 100",+ class_iri+ );+ for p in sparql_iri_list(graph, &q2, "p") {+ if !out.contains(&p) {+ out.push(p);+ }+ }+ out+}++/// Pull every owl:Class IRI in the graph.+pub fn list_classes(graph: &Arc<GraphStore>) -> Vec<String> {+ let q = "SELECT DISTINCT ?c WHERE { ?c a <http://www.w3.org/2002/07/owl#Class> } LIMIT 5000";+ sparql_iri_list(graph, q, "c")+}++fn sparql_iri_list(graph: &Arc<GraphStore>, q: &str, var: &str) -> Vec<String> {+ let js = match graph.sparql_select(q) {+ Ok(s) => s,+ Err(_) => return Vec::new(),+ };+ let v: serde_json::Value = serde_json::from_str(&js).unwrap_or(serde_json::Value::Null);+ let rows = v["results"].as_array().cloned().unwrap_or_default();+ rows.iter()+ .filter_map(|row| {+ row[var]+ .as_str()+ .map(|s| s.trim_matches(|c| c == '<' || c == '>').to_string())+ })+ .filter(|s| !s.starts_with("_:")) // skip blank nodes+ .collect()+}++/// Compute the four FLORA signals for a candidate pair.+pub fn compute_signals(+ source: &Arc<GraphStore>,+ target: &Arc<GraphStore>,+ source_iri: &str,+ target_iri: &str,+) -> FuzzySignals {+ let src_label = tokenise_name(&local_name(source_iri));+ let tgt_label = tokenise_name(&local_name(target_iri));+ let label_jaccard = jaccard(&src_label, &tgt_label);++ let src_parents: BTreeSet<String> = parents(source, source_iri)+ .iter()+ .flat_map(|p| tokenise_name(&local_name(p)))+ .collect();+ let tgt_parents: BTreeSet<String> = parents(target, target_iri)+ .iter()+ .flat_map(|p| tokenise_name(&local_name(p)))+ .collect();+ let parent_overlap = jaccard(&src_parents, &tgt_parents);++ let src_siblings: BTreeSet<String> = siblings(source, source_iri)+ .iter()+ .flat_map(|s| tokenise_name(&local_name(s)))+ .collect();+ let tgt_siblings: BTreeSet<String> = siblings(target, target_iri)+ .iter()+ .flat_map(|s| tokenise_name(&local_name(s)))+ .collect();+ let sibling_overlap = jaccard(&src_siblings, &tgt_siblings);++ let src_dprops: BTreeSet<String> = datatype_properties(source, source_iri)+ .iter()+ .flat_map(|p| tokenise_name(&local_name(p)))+ .collect();+ let tgt_dprops: BTreeSet<String> = datatype_properties(target, target_iri)+ .iter()+ .flat_map(|p| tokenise_name(&local_name(p)))+ .collect();+ let datatype_overlap = jaccard(&src_dprops, &tgt_dprops);++ FuzzySignals {+ label_jaccard,+ parent_overlap,+ sibling_overlap,+ datatype_overlap,+ }+}++/// Run the full FLORA pipeline across all class-pair candidates between+/// two ontologies. Filters candidates by a cheap pre-check (at least one+/// shared label token) before invoking the expensive structural queries.+pub fn align_with_flora(+ source: &Arc<GraphStore>,+ target: &Arc<GraphStore>,+ low_threshold: f64,+ high_threshold: f64,+) -> FloraAlignmentReport {+ let src_classes = list_classes(source);+ let tgt_classes = list_classes(target);++ let mut entries: Vec<AlignmentEntry> = Vec::new();+ let mut accepts = 0usize;+ let mut borderline = 0usize;+ let mut rejects = 0usize;+ let mut pairs_evaluated = 0usize;++ // Pre-compute tokenised source labels for the cheap filter.+ let src_tokens: Vec<BTreeSet<String>> = src_classes+ .iter()+ .map(|c| tokenise_name(&local_name(c)))+ .collect();+ let tgt_tokens: Vec<BTreeSet<String>> = tgt_classes+ .iter()+ .map(|c| tokenise_name(&local_name(c)))+ .collect();++ for (i, src) in src_classes.iter().enumerate() {+ for (j, tgt) in tgt_classes.iter().enumerate() {+ // Cheap filter: skip pairs with zero shared label tokens.+ if src_tokens[i].intersection(&tgt_tokens[j]).next().is_none() {+ continue;+ }+ pairs_evaluated += 1;+ let signals = compute_signals(source, target, src, tgt);+ let decision = adjudicate(&signals, TNorm::Min, low_threshold, high_threshold);+ match decision.verdict.as_str() {+ "accept" => {+ accepts += 1;+ entries.push(AlignmentEntry {+ source: src.clone(),+ target: tgt.clone(),+ relation: "equivalent".to_string(),+ });+ }+ "borderline" => borderline += 1,+ _ => rejects += 1,+ }+ }+ }++ FloraAlignmentReport {+ source_class_count: src_classes.len(),+ target_class_count: tgt_classes.len(),+ pairs_evaluated,+ accepts,+ borderline,+ rejects,+ entries,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn local_name_strips_hash_prefix() {+ assert_eq!(local_name("http://cmt#Author"), "Author");+ assert_eq!(local_name("http://www.w3.org/2002/07/owl#Class"), "Class");+ assert_eq!(local_name("http://ex.org/Cat"), "Cat");+ }++ #[test]+ fn tokenise_splits_camel_case_and_underscores() {+ let t = tokenise_name("Regular_author");+ assert!(t.contains("regular") && t.contains("author"));+ let t = tokenise_name("HasReviewedPaper");+ assert!(t.contains("has") && t.contains("reviewed") && t.contains("paper"));+ }++ #[test]+ fn tokenise_drops_single_char_tokens() {+ let t = tokenise_name("a_real_name");+ assert!(!t.contains("a"));+ assert!(t.contains("real") && t.contains("name"));+ }++ #[test]+ fn compute_signals_returns_high_label_for_identical_local_names() {+ let g1 = Arc::new(GraphStore::new());+ let g2 = Arc::new(GraphStore::new());+ g1.load_turtle(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ex: <http://a/> . ex:Author a owl:Class .",+ None,+ )+ .unwrap();+ g2.load_turtle(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ex: <http://b/> . ex:Author a owl:Class .",+ None,+ )+ .unwrap();+ let s = compute_signals(&g1, &g2, "http://a/Author", "http://b/Author");+ assert!((s.label_jaccard - 1.0).abs() < 1e-9);+ }++ #[test]+ fn align_with_flora_matches_identical_class_names_when_structural_context_exists() {+ // FLORA correctly demands SOME structural evidence beyond label+ // equality — a bare class with no parents/siblings/datatypes lands+ // in borderline, not accept. So set up classes with shared parent+ // structure to make the test realistic.+ let g1 = Arc::new(GraphStore::new());+ let g2 = Arc::new(GraphStore::new());+ g1.load_turtle(+ r#"@prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://a/> .+ ex:Agent a owl:Class .+ ex:Author a owl:Class ; rdfs:subClassOf ex:Agent .+ ex:Reviewer a owl:Class ; rdfs:subClassOf ex:Agent .+ ex:Paper a owl:Class .+ "#,+ None,+ ).unwrap();+ g2.load_turtle(+ r#"@prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://b/> .+ ex:Agent a owl:Class .+ ex:Author a owl:Class ; rdfs:subClassOf ex:Agent .+ ex:Reviewer a owl:Class ; rdfs:subClassOf ex:Agent .+ ex:Paper a owl:Class .+ ex:Conference a owl:Class .+ "#,+ None,+ ).unwrap();+ let report = align_with_flora(&g1, &g2, 0.4, 0.65);+ assert_eq!(report.source_class_count, 4);+ assert_eq!(report.target_class_count, 5);+ // Author↔Author and Reviewer↔Reviewer have shared parent context.+ let has_author = report.entries.iter().any(|e|+ e.source.ends_with("Author") && e.target.ends_with("Author"));+ assert!(has_author,+ "Author↔Author should accept with parent context; got: {:?}",+ report.entries);+ }++ #[test]+ fn align_with_flora_bare_classes_yield_borderline_not_accept() {+ // The honest behaviour: identical labels but zero structural+ // evidence → borderline. FLORA refuses to accept on label alone.+ let g1 = Arc::new(GraphStore::new());+ let g2 = Arc::new(GraphStore::new());+ g1.load_turtle(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ex: <http://a/> . ex:Author a owl:Class .",+ None,+ ).unwrap();+ g2.load_turtle(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ex: <http://b/> . ex:Author a owl:Class .",+ None,+ ).unwrap();+ let report = align_with_flora(&g1, &g2, 0.4, 0.65);+ // Zero accepts, ≥1 borderline.+ assert_eq!(report.accepts, 0,+ "bare-class match should not accept; got entries: {:?}",+ report.entries);+ assert!(report.borderline >= 1,+ "expected borderline for identical-label bare classes; got {:?}",+ report);+ }++ #[test]+ fn list_classes_returns_owl_class_instances() {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix ex: <http://a/> . ex:A a owl:Class . ex:B a owl:Class . ex:thing a ex:A .",+ None,+ )+ .unwrap();+ let cs = list_classes(&g);+ assert_eq!(cs.len(), 2);+ assert!(cs.iter().any(|c| c == "http://a/A"));+ assert!(cs.iter().any(|c| c == "http://a/B"));+ }+}diff --git a/src/inputs.rs b/src/inputs.rsindex 3a28ff7f..d5eb0218 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -623,6 +623,22 @@ fn default_alpha_pub() -> f64 {0.05}+/// Input for `onto_align_flora` (#38) — end-to-end FLORA alignment over+/// every plausible class-pair across the loaded source and a caller-+/// supplied target ontology (as Turtle).+#[derive(Deserialize, JsonSchema)]+pub struct OntoAlignFloraInput {+ /// Target ontology as Turtle. The source side is the currently-loaded+ /// graph.+ pub target_ttl: String,+ /// Lower threshold for FLORA verdict bucketing (default 0.4).+ #[serde(default)]+ pub low_threshold: Option<f64>,+ /// Upper threshold (default 0.65).+ #[serde(default)]+ pub high_threshold: Option<f64>,+}+/// Input for `onto_align_fuzzy` (#38, FLORA ISWC 2025 Best Paper).#[derive(Deserialize, JsonSchema)]pub struct OntoAlignFuzzyInput {@@ -657,10 +673,19 @@ pub struct OntoPolicyCheckInput {/// Input for `eval_rag` (#41, mmRAG ISWC 2025).#[derive(Deserialize, JsonSchema)]pub struct OntoEvalRagInput {- /// JSON array `[{question_id, gold_iri, retrieved: [iri, iri, ...]}, ...]`.+ /// JSON array `[{question_id, gold_iri, retrieved, generated_answer?,+ /// gold_answer?, retrieved_text?}, ...]`.pub qa_json: String,}+/// Input for `eval_rag_mmrag` — parse a full mmRAG dataset JSON and score+/// it in one call.+#[derive(Deserialize, JsonSchema)]+pub struct OntoEvalRagMmragInput {+ /// JSON array of mmRAG records (see `MmRagRecord` in `src/eval_rag.rs`).+ pub dataset_json: String,+}+/// Input for `onto_eval_alignment` (#31, OAEI-style P/R/F1).#[derive(Deserialize, JsonSchema)]pub struct OntoEvalAlignmentInput {@@ -678,6 +703,24 @@ pub struct OntoShapeCombinatoricsInput {pub max_size: Option<usize>,}+/// Input for `onto_shape_induce` — Kastor data-driven SHACL induction.+#[derive(Deserialize, JsonSchema)]+pub struct OntoShapeInduceInput {+ pub class_iri: String,+ /// Maximum subset size to enumerate (default 3, capped at 2^max for sanity).+ #[serde(default)]+ pub max_size: Option<usize>,+ /// Return the top-k candidates by support × confidence (default 10).+ #[serde(default)]+ pub top_k: Option<usize>,+ /// Filter: require this minimum support fraction (default 0.1).+ #[serde(default)]+ pub min_support: Option<f64>,+ /// Filter: require this minimum confidence fraction (default 0.5).+ #[serde(default)]+ pub min_confidence: Option<f64>,+}+/// Input for `borderline_partition` (#37).#[derive(Deserialize, JsonSchema)]pub struct BorderlinePartitionInput {@@ -741,6 +784,23 @@ pub struct OntoCqVerdictsListInput {pub cq_id: String,}+/// Input for `onto_owl_shacl_coevolve_incremental` (#33 follow-on).+#[derive(Deserialize, JsonSchema)]+pub struct OntoCoevolveIncrementalInput {+ pub shapes_ttl: String,+ /// IRIs that changed since the last validation (classes, properties).+ /// Shapes whose dependencies don't intersect this set are skipped.+ pub changed_iris: Vec<String>,+ #[serde(default)]+ pub profile: Option<String>,+}++/// Input for `onto_coevolve_dependency_graph` (#33 follow-on).+#[derive(Deserialize, JsonSchema)]+pub struct OntoCoevolveDepGraphInput {+ pub shapes_ttl: String,+}+/// Input for `onto_segment_retrieve` (#34, SEMANTiCS 2025 GrOWL-RAG) —/// retrieve a TBox-slice neighbourhood for grounding LLM reasoning.#[derive(Deserialize, JsonSchema)]diff --git a/src/lib.rs b/src/lib.rsindex f46f0e48..3adaf941 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -12,6 +12,7 @@ pub mod coevolve;pub mod cq;pub mod eval_alignment;pub mod eval_rag;+pub mod flora_pipeline;pub mod extract_scaffold;pub mod policy;pub mod shape_combinatorics;diff --git a/src/server.rs b/src/server.rsindex a994b215..4371f103 100644--- a/src/server.rs+++ b/src/server.rs@@ -929,6 +929,20 @@ impl OpenOntologiesServer {.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))}++ #[tool(name = "onto_align_flora", description = "End-to-end FLORA alignment (#38). Takes the currently-loaded graph as source and a Turtle string for target, enumerates plausible class-pairs (pre-filtered by shared label tokens), extracts the four FLORA signals per pair (label Jaccard, parent overlap, sibling overlap, datatype overlap) from the structural neighbourhood, runs the 10-rule Mamdani inference engine, and returns only the accept-verdict pairs. Companion to `onto_align_fuzzy` (per-pair adjudication when you already have signals).")]+ async fn onto_align_flora(&self, Parameters(input): Parameters<OntoAlignFloraInput>) -> String {+ let target = std::sync::Arc::new(crate::graph::GraphStore::new());+ if let Err(e) = target.load_turtle(&input.target_ttl, None) {+ return format!(r#"{{"error":"target_ttl failed to parse: {}"}}"#, e);+ }+ let low = input.low_threshold.unwrap_or(0.4);+ let high = input.high_threshold.unwrap_or(0.65);+ let report = crate::flora_pipeline::align_with_flora(&self.graph, &target, low, high);+ serde_json::to_string(&report)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e))+ }+#[tool(name = "onto_align_fuzzy", description = "FLORA-style fuzzy-logic alignment adjudication (#38, ISWC 2025 Best Paper). Caller supplies per-pair signals (`label_jaccard`, `parent_overlap`, `sibling_overlap`, `datatype_overlap` all in [0,1]) plus low/high thresholds; server combines via the chosen t-norm (`min` / `product` / `lukasiewicz`) and emits verdict `\"accept\"` / `\"borderline\"` / `\"reject\"` plus a rule trace. Embedding-free, interpretable, complements the HNSW candidate-generator pipeline.")]async fn onto_align_fuzzy(&self, Parameters(input): Parameters<OntoAlignFuzzyInput>) -> String {let signals: crate::align_fuzzy::FuzzySignals = match serde_json::from_str(&input.signals_json) {@@ -977,6 +991,17 @@ impl OpenOntologiesServer {}}+ #[tool(name = "eval_rag_mmrag", description = "Parse a full mmRAG dataset JSON and score it in one call. Convenience wrapper around `onto_mmrag_parse` + `eval_rag`. Returns the same `RagEvalReport` as `eval_rag` including faithfulness, answer-jaccard, and rouge1 when records carry generated_answer / gold_answer / retrieved_text.")]+ async fn eval_rag_mmrag(&self, Parameters(input): Parameters<OntoEvalRagMmragInput>) -> String {+ let qas = match crate::eval_rag::parse_mmrag_dataset(&input.dataset_json) {+ Ok(q) => q,+ Err(e) => return format!(r#"{{"error":"{}"}}"#, e),+ };+ let report = crate::eval_rag::evaluate(&qas);+ serde_json::to_string(&report)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e))+ }+#[tool(name = "eval_rag", description = "mmRAG benchmark scoring (#41, ISWC 2025). Input is a JSON array of {question_id, gold_iri, retrieved: [iri, ...]}. Returns Hit@{3,5,10}, MRR, exact-match-at-1, and per-question rank (0 = gold not retrieved).")]async fn eval_rag(&self, Parameters(input): Parameters<OntoEvalRagInput>) -> String {let qas: Vec<crate::eval_rag::RagQa> = match serde_json::from_str(&input.qa_json) {@@ -1014,6 +1039,19 @@ impl OpenOntologiesServer {.unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e))}+ #[tool(name = "onto_shape_induce", description = "Kastor-style data-driven SHACL shape induction (#36, K-CAP 2025). For each property subset up to `max_size`, compute support (fraction of class instances having all properties) and confidence (fraction of any-instances-with-properties that are class members). Returns the top-k candidates ranked by `support × confidence`, each carrying a ready-to-use SHACL NodeShape Turtle block. Filter via `min_support` (default 0.1) and `min_confidence` (default 0.5).")]+ async fn onto_shape_induce(&self, Parameters(input): Parameters<OntoShapeInduceInput>) -> String {+ let max = input.max_size.unwrap_or(3);+ let top_k = input.top_k.unwrap_or(10);+ let min_support = input.min_support.unwrap_or(0.1);+ let min_confidence = input.min_confidence.unwrap_or(0.5);+ match crate::shape_combinatorics::induce_shapes(&self.graph, &input.class_iri, max, top_k, min_support, min_confidence) {+ Ok(r) => serde_json::to_string(&r)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }+#[tool(name = "onto_shape_combinatorics", description = "Enumerate the property-combination lattice for a class (#36, K-CAP 2025 Kastor). Returns subsets of the class's rdfs:domain properties up to `max_size` (default 3). Used by shape-induction algorithms to enumerate candidate SHACL shapes from data.")]async fn onto_shape_combinatorics(&self, Parameters(input): Parameters<OntoShapeCombinatoricsInput>) -> String {let max = input.max_size.unwrap_or(3);@@ -1118,6 +1156,25 @@ impl OpenOntologiesServer {}}+ #[tool(name = "onto_coevolve_dependency_graph", description = "Build the shape→OWL-dependency map for a SHACL document. For each NodeShape, returns the set of target classes, path properties, and class-constraint targets. Powers `onto_owl_shacl_coevolve_incremental`.")]+ async fn onto_coevolve_dependency_graph(&self, Parameters(input): Parameters<OntoCoevolveDepGraphInput>) -> String {+ match crate::coevolve::build_dependency_graph(&input.shapes_ttl) {+ Ok(d) => serde_json::to_string(&d)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_owl_shacl_coevolve_incremental", description = "Incremental coevolve check (#33 follow-on, K-CAP 2025). Given a list of IRIs that changed since the last validation, identify which SHACL shapes are affected (via the shape→OWL dependency graph) and skip SHACL validation entirely when no shape's dependencies overlap. Returns the affected-shapes report plus validation output (or 'no_affected_shapes' sentinel when nothing fires).")]+ async fn onto_owl_shacl_coevolve_incremental(&self, Parameters(input): Parameters<OntoCoevolveIncrementalInput>) -> String {+ let profile = input.profile.unwrap_or_else(|| "owl-rl".to_string());+ match crate::coevolve::incremental_check(&self.graph, &input.shapes_ttl, &input.changed_iris, &profile) {+ Ok(r) => serde_json::to_string(&r)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }+#[tool(name = "onto_owl_shacl_coevolve_check", description = "Combined OWL+SHACL validation (#33, K-CAP 2025). Materialises OWL-RL entailments into a sandbox copy of the loaded graph, then runs SHACL validation against the closure. Returns both the pre-reasoning and post-reasoning conformance verdicts plus the count of triples the reasoner added. Catches SHACL constraints that pass against the raw ABox but fail after inference (e.g. instances that inherit a parent class via rdfs:subClassOf and then violate a parent-class shape). Original graph is NOT mutated.")]async fn onto_owl_shacl_coevolve_check(&self, Parameters(input): Parameters<OntoOwlShaclCoevolveInput>) -> String {let profile = input.profile.unwrap_or_else(|| "owl-rl".to_string());diff --git a/src/shape_combinatorics.rs b/src/shape_combinatorics.rsindex 975c297c..d945d588 100644--- a/src/shape_combinatorics.rs+++ b/src/shape_combinatorics.rs@@ -1,19 +1,19 @@-//! Property-combination lattice for shape-based extraction (#36, K-CAP 2025-//! Kastor).+//! Property-combination lattice + data-driven SHACL shape induction (#36,+//! K-CAP 2025 Kastor).//!-//! Given a class IRI, enumerate the lattice of property subsets the class's-//! instances could be characterised by. Used by shape-induction algorithms-//! that want to enumerate candidate SHACL shapes from data:+//! Two layers://!-//! - Level 0: `{}` (the trivial "class membership" shape).-//! - Level 1: `{p1}, {p2}, ..., {pk}` for each domain-property.-//! - Level 2: `{p1, p2}, ...` all 2-subsets.-//! - ...-//! - Level k: `{p1, p2, ..., pk}` (all properties at once).+//! 1. **`enumerate`** — pure combinatorial enumeration of property-subset+//! candidates up to `max_size`. Bounded at `2^max_size` to prevent+//! pathological blowup.//!-//! The lattice grows as `2^k` so the primitive bounds at `max_size`-//! (default 3) — sufficient for the K-CAP 2025 Kastor algorithm and avoids-//! pathological blowup on rich domains.+//! 2. **`induce_shapes`** — Kastor-style data-driven induction. For each+//! candidate subset, evaluates against the loaded ontology's instance+//! data and computes `support` (fraction of class instances that have+//! ALL properties in the subset) and `confidence` (fraction of+//! instances-with-this-subset that are also instances of the class).+//! Ranks candidates by `support × confidence` and emits the top-k as+//! proposed SHACL `NodeShape`s with `sh:property` blocks.use crate::graph::GraphStore;use serde::Serialize;@@ -31,6 +31,33 @@ pub struct LatticeReport {pub subsets: Vec<Vec<String>>,}+/// One induced candidate shape with its quality scores.+#[derive(Clone, Debug, Serialize)]+pub struct CandidateShape {+ /// Property IRIs the shape requires.+ pub properties: Vec<String>,+ /// Fraction of class instances that have every property in this subset+ /// (in `[0, 1]`).+ pub support: f64,+ /// Fraction of instances-with-this-subset that are members of the class+ /// (in `[0, 1]`). Higher confidence = more class-discriminative subset.+ pub confidence: f64,+ /// `support × confidence`, used to rank candidates.+ pub score: f64,+ /// Number of class instances covered by this shape.+ pub instances_covered: u64,+ /// SHACL NodeShape Turtle text proposing this constraint.+ pub shape_ttl: String,+}++#[derive(Clone, Debug, Serialize)]+pub struct InductionReport {+ pub class_iri: String,+ pub class_instance_count: u64,+ pub candidates_evaluated: usize,+ pub shapes: Vec<CandidateShape>,+}+/// Enumerate property-combination subsets up to `max_size` for a class.pub fn enumerate(graph: &Arc<GraphStore>, class_iri: &str, max_size: usize) -> anyhow::Result<LatticeReport> {let max_size = if max_size == 0 { 3 } else { max_size };@@ -107,6 +134,158 @@ fn to_set(items: &[String]) -> BTreeSet<String> {items.iter().cloned().collect()}+/// Induce candidate SHACL shapes from data (#36 Kastor proper). For each+/// non-empty property subset enumerated up to `max_size`, evaluate support ++/// confidence against the loaded instance data, then return the top+/// `top_k` by `support × confidence` (default 10).+///+/// `min_support` and `min_confidence` filter weak candidates (default 0.1+/// and 0.5 respectively).+pub fn induce_shapes(+ graph: &Arc<GraphStore>,+ class_iri: &str,+ max_size: usize,+ top_k: usize,+ min_support: f64,+ min_confidence: f64,+) -> anyhow::Result<InductionReport> {+ let lattice = enumerate(graph, class_iri, max_size)?;++ // Count class instances.+ let class_count = count_query(+ graph,+ &format!(+ "SELECT (COUNT(?x) AS ?n) WHERE {{ ?x a <{}> }}",+ class_iri+ ),+ )?;++ let mut candidates: Vec<CandidateShape> = Vec::new();+ for subset in &lattice.subsets {+ if subset.is_empty() {+ continue;+ }+ // count_class_with_subset: instances of class that have all+ // properties in subset.+ let class_with = count_class_with_subset(graph, class_iri, subset)?;+ // count_with_subset: instances ANYWHERE that have all properties.+ let any_with = count_any_with_subset(graph, subset)?;++ let support = if class_count == 0 {+ 0.0+ } else {+ class_with as f64 / class_count as f64+ };+ let confidence = if any_with == 0 {+ 0.0+ } else {+ class_with as f64 / any_with as f64+ };+ if support < min_support || confidence < min_confidence {+ continue;+ }+ let score = support * confidence;+ let shape_ttl = render_shape_ttl(class_iri, subset);+ candidates.push(CandidateShape {+ properties: subset.clone(),+ support,+ confidence,+ score,+ instances_covered: class_with,+ shape_ttl,+ });+ }+ candidates.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));+ candidates.truncate(top_k);++ let evaluated = lattice.subsets.iter().filter(|s| !s.is_empty()).count();+ Ok(InductionReport {+ class_iri: class_iri.to_string(),+ class_instance_count: class_count,+ candidates_evaluated: evaluated,+ shapes: candidates,+ })+}++fn count_query(graph: &Arc<GraphStore>, q: &str) -> anyhow::Result<u64> {+ let js = graph.sparql_select(q)?;+ let v: serde_json::Value = serde_json::from_str(&js).unwrap_or(serde_json::Value::Null);+ let n_str = v["results"][0]["n"].as_str().unwrap_or("0");+ // SPARQL aggregate values come as literal strings like+ // `"5"^^<http://www.w3.org/2001/XMLSchema#integer>`. Strip the typed+ // wrapper, keep just the digits.+ let digits: String = n_str.chars().take_while(|c| c.is_ascii_digit()).collect();+ // If the leading char was a quote (Oxigraph string-encodes literals)+ // skip it and read until the next quote.+ let cleaned: String = if n_str.starts_with('"') {+ n_str+ .chars()+ .skip(1)+ .take_while(|c| c.is_ascii_digit())+ .collect()+ } else if !digits.is_empty() {+ digits+ } else {+ n_str.chars().filter(|c| c.is_ascii_digit()).collect()+ };+ Ok(cleaned.parse::<u64>().unwrap_or(0))+}++fn count_class_with_subset(+ graph: &Arc<GraphStore>,+ class_iri: &str,+ subset: &[String],+) -> anyhow::Result<u64> {+ if subset.is_empty() {+ return Ok(0);+ }+ let mut patterns: Vec<String> = vec![format!("?x a <{}>", class_iri)];+ for (i, p) in subset.iter().enumerate() {+ patterns.push(format!("?x <{}> ?o{}", p, i));+ }+ let q = format!(+ "SELECT (COUNT(DISTINCT ?x) AS ?n) WHERE {{ {} }}",+ patterns.join(" . ")+ );+ count_query(graph, &q)+}++fn count_any_with_subset(graph: &Arc<GraphStore>, subset: &[String]) -> anyhow::Result<u64> {+ if subset.is_empty() {+ return Ok(0);+ }+ let mut patterns: Vec<String> = Vec::new();+ for (i, p) in subset.iter().enumerate() {+ patterns.push(format!("?x <{}> ?o{}", p, i));+ }+ let q = format!(+ "SELECT (COUNT(DISTINCT ?x) AS ?n) WHERE {{ {} }}",+ patterns.join(" . ")+ );+ count_query(graph, &q)+}++/// Render a SHACL NodeShape proposing the subset's properties as+/// `sh:property` blocks with `sh:minCount 1`.+fn render_shape_ttl(class_iri: &str, subset: &[String]) -> String {+ let mut out = String::new();+ out.push_str("@prefix sh: <http://www.w3.org/ns/shacl#> .\n");+ out.push_str(&format!(+ "<{}-shape> a sh:NodeShape ;\n",+ class_iri+ ));+ out.push_str(&format!(" sh:targetClass <{}> ;\n", class_iri));+ for (i, p) in subset.iter().enumerate() {+ let prefix = if i + 1 == subset.len() { "" } else { " ;" };+ out.push_str(&format!(+ " sh:property [ sh:path <{}> ; sh:minCount 1 ]{}\n",+ p, prefix+ ));+ }+ out.push_str(".\n");+ out+}+#[cfg(test)]mod tests {use super::*;@@ -162,6 +341,148 @@ mod tests {assert_eq!(r.subsets[0], Vec::<String>::new());}+ fn graph_with_class_and_instances() -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://ex.org/> .+ ex:Person a owl:Class .+ ex:name a owl:DatatypeProperty ; rdfs:domain ex:Person .+ ex:age a owl:DatatypeProperty ; rdfs:domain ex:Person .+ ex:email a owl:DatatypeProperty ; rdfs:domain ex:Person .++ # 3 instances of Person, 2 with name+age, 1 with only name.+ ex:alice a ex:Person ; ex:name "Alice" ; ex:age 30 .+ ex:bob a ex:Person ; ex:name "Bob" ; ex:age 25 .+ ex:charlie a ex:Person ; ex:name "Charlie" .++ # 1 NON-Person instance with the same property — should lower+ # confidence on {name}.+ ex:nonperson_dog ex:name "Rex" .+ "#,+ None,+ )+ .unwrap();+ g+ }++ #[test]+ fn induce_shapes_returns_high_support_subsets() {+ let g = graph_with_class_and_instances();+ let r = induce_shapes(+ &g,+ "http://ex.org/Person",+ 3,+ 10,+ 0.1,+ 0.5,+ )+ .unwrap();+ assert_eq!(r.class_instance_count, 3);+ // {name} has support 3/3 = 1.0; confidence 3/4 = 0.75 (Rex is not+ // a Person). Should be the top candidate.+ let top = r+ .shapes+ .iter()+ .find(|c| c.properties == vec!["http://ex.org/name".to_string()])+ .expect("name subset should be in induced shapes");+ assert!((top.support - 1.0).abs() < 1e-9);+ assert!((top.confidence - 0.75).abs() < 1e-9);+ assert_eq!(top.instances_covered, 3);+ }++ #[test]+ fn induce_shapes_filters_by_min_support() {+ let g = graph_with_class_and_instances();+ // {email} has support 0 (no Person instance has it).+ let r = induce_shapes(+ &g,+ "http://ex.org/Person",+ 3,+ 10,+ 0.5,+ 0.0,+ )+ .unwrap();+ let email_in_shapes = r+ .shapes+ .iter()+ .any(|c| c.properties == vec!["http://ex.org/email".to_string()]);+ assert!(!email_in_shapes,+ "email has zero support, should be filtered by min_support=0.5");+ }++ #[test]+ fn induce_shapes_renders_valid_shacl_turtle() {+ let g = graph_with_class_and_instances();+ let r = induce_shapes(+ &g,+ "http://ex.org/Person",+ 2,+ 5,+ 0.1,+ 0.5,+ )+ .unwrap();+ let top = r.shapes.first().expect("at least one shape");+ assert!(top.shape_ttl.contains("sh:NodeShape"));+ assert!(top.shape_ttl.contains("sh:targetClass"));+ assert!(top.shape_ttl.contains("sh:property"));+ assert!(top.shape_ttl.contains("sh:minCount 1"));+ // Should parse as valid Turtle.+ let test_graph = Arc::new(GraphStore::new());+ let load_result = test_graph.load_turtle(&top.shape_ttl, None);+ assert!(load_result.is_ok(),+ "induced shape Turtle should parse: error: {:?}\nturtle:\n{}",+ load_result.err(), top.shape_ttl);+ }++ #[test]+ fn induce_shapes_ranks_by_score_descending() {+ let g = graph_with_class_and_instances();+ let r = induce_shapes(+ &g,+ "http://ex.org/Person",+ 3,+ 10,+ 0.1,+ 0.5,+ )+ .unwrap();+ // Score must be monotonically non-increasing.+ for w in r.shapes.windows(2) {+ assert!(+ w[0].score >= w[1].score,+ "shapes not ranked: {} < {} (props {:?} vs {:?})",+ w[0].score, w[1].score, w[0].properties, w[1].properties+ );+ }+ }++ #[test]+ fn induce_shapes_handles_class_with_no_instances() {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ "@prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix ex: <http://ex.org/> . ex:Empty a owl:Class . ex:p a owl:DatatypeProperty ; rdfs:domain ex:Empty .",+ None,+ )+ .unwrap();+ let r = induce_shapes(+ &g,+ "http://ex.org/Empty",+ 3,+ 10,+ 0.1,+ 0.5,+ )+ .unwrap();+ assert_eq!(r.class_instance_count, 0);+ // No support for any subset → empty result.+ assert!(r.shapes.is_empty());+ }+#[test]fn enumerate_zero_max_size_defaults_to_three() {let g = graph_with_properties();