Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

feat: add Poincaré structural embedding trainer — learns hierarchy layout via Riemannian SGD

FABIOTESSe29c851cbf1d
diff --git a/src/structembed.rs b/src/structembed.rs
new file mode 100644
index 00000000..16e303ba
--- /dev/null
+++ b/src/structembed.rs
@@ -0,0 +1,189 @@
+//! Learn Poincaré embeddings from the ontology class hierarchy.
+//! Uses Riemannian SGD to push parent-child pairs closer and
+//! negative samples apart in the Poincaré ball.
+
+use crate::graph::GraphStore;
+use crate::poincare::{poincare_distance, project_to_ball, rsgd_step};
+use anyhow::Result;
+use std::collections::HashMap;
+use std::collections::HashSet;
+
+pub struct StructuralTrainer {
+ dim: usize,
+ epochs: usize,
+ lr: f32,
+}
+
+impl StructuralTrainer {
+ pub fn new(dim: usize, epochs: usize, lr: f32) -> Self {
+ Self { dim, epochs, lr }
+ }
+
+ /// Extract (parent, child) edges from the graph via SPARQL.
+ fn extract_edges(store: &GraphStore) -> Vec<(String, String)> {
+ let query = r#"
+ SELECT DISTINCT ?child ?parent WHERE {
+ ?child <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?parent .
+ ?child a <http://www.w3.org/2002/07/owl#Class> .
+ ?parent a <http://www.w3.org/2002/07/owl#Class> .
+ FILTER(isIRI(?child) && isIRI(?parent))
+ }
+ "#;
+
+ let result = match store.sparql_select(query) {
+ Ok(r) => r,
+ Err(_) => return Vec::new(),
+ };
+
+ let parsed: serde_json::Value = match serde_json::from_str(&result) {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+
+ parsed["results"]
+ .as_array()
+ .unwrap_or(&Vec::new())
+ .iter()
+ .filter_map(|row| {
+ let child = row["child"].as_str()?.trim_matches(|c| c == '<' || c == '>').to_string();
+ let parent = row["parent"].as_str()?.trim_matches(|c| c == '<' || c == '>').to_string();
+ Some((parent, child))
+ })
+ .collect()
+ }
+
+ /// Extract all class IRIs from the graph.
+ fn extract_all_classes(store: &GraphStore) -> Vec<String> {
+ let query = r#"
+ SELECT DISTINCT ?class WHERE {
+ ?class a <http://www.w3.org/2002/07/owl#Class> .
+ FILTER(isIRI(?class))
+ }
+ "#;
+
+ let result = match store.sparql_select(query) {
+ Ok(r) => r,
+ Err(_) => return Vec::new(),
+ };
+
+ let parsed: serde_json::Value = match serde_json::from_str(&result) {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+
+ parsed["results"]
+ .as_array()
+ .unwrap_or(&Vec::new())
+ .iter()
+ .filter_map(|row| {
+ Some(row["class"].as_str()?.trim_matches(|c| c == '<' || c == '>').to_string())
+ })
+ .collect()
+ }
+
+ /// Train Poincaré embeddings from the ontology hierarchy.
+ pub fn train(&self, store: &GraphStore) -> Result<HashMap<String, Vec<f32>>> {
+ let edges = Self::extract_edges(store);
+ let classes = Self::extract_all_classes(store);
+
+ if classes.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ // Initialize embeddings near origin
+ let mut embeddings: HashMap<String, Vec<f32>> = HashMap::new();
+ for (i, class) in classes.iter().enumerate() {
+ let init: Vec<f32> = (0..self.dim)
+ .map(|j| {
+ let seed = (i * self.dim + j) as f32;
+ ((seed * 2654435761.0) % 1000.0) / 50000.0 - 0.01
+ })
+ .collect();
+ embeddings.insert(class.clone(), project_to_ball(&init, 1e-5));
+ }
+
+ if edges.is_empty() {
+ return Ok(embeddings);
+ }
+
+ // Identify root nodes (parents that are never children)
+ let children: HashSet<&str> = edges.iter().map(|(_, c)| c.as_str()).collect();
+ let roots: Vec<String> = edges.iter()
+ .map(|(p, _)| p.clone())
+ .filter(|p| !children.contains(p.as_str()))
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect();
+
+ let num_classes = classes.len();
+ for epoch in 0..self.epochs {
+ let lr = self.lr * (1.0 - epoch as f32 / self.epochs as f32);
+
+ // Pull parent-child pairs closer
+ for (edge_i, (parent, child)) in edges.iter().enumerate() {
+ let parent_emb = embeddings[parent].clone();
+ let child_emb = embeddings[child].clone();
+
+ let dist = poincare_distance(&parent_emb, &child_emb);
+ if dist > 0.0 {
+ // Gradient to pull them closer
+ let grad_parent: Vec<f32> = parent_emb.iter().zip(child_emb.iter())
+ .map(|(p, c)| p - c)
+ .collect();
+ let grad_child: Vec<f32> = child_emb.iter().zip(parent_emb.iter())
+ .map(|(c, p)| c - p)
+ .collect();
+
+ let new_parent = rsgd_step(&parent_emb, &grad_parent, lr);
+ let new_child = rsgd_step(&child_emb, &grad_child, lr);
+ embeddings.insert(parent.clone(), new_parent);
+ embeddings.insert(child.clone(), new_child);
+ }
+
+ // Push child outward (further from origin than parent)
+ let parent_emb = embeddings[parent].clone();
+ let child_emb = embeddings[child].clone();
+ let parent_norm: f32 = parent_emb.iter().map(|x| x * x).sum::<f32>().sqrt();
+ let child_norm: f32 = child_emb.iter().map(|x| x * x).sum::<f32>().sqrt();
+
+ if child_norm <= parent_norm + 0.01 {
+ // Push child away from origin along its direction
+ let grad_outward: Vec<f32> = child_emb.iter()
+ .map(|c| -c)
+ .collect();
+ let new_child = rsgd_step(&child_emb, &grad_outward, lr * 0.5);
+ embeddings.insert(child.clone(), new_child);
+ }
+
+ // Negative sampling: vary index by both epoch and edge
+ let neg_idx = (epoch * 7 + edge_i * 13 + 3) % num_classes;
+ let neg_iri = &classes[neg_idx];
+ if neg_iri != parent && neg_iri != child {
+ let neg_emb = embeddings[neg_iri].clone();
+ let child_emb = embeddings[child].clone();
+
+ let neg_dist = poincare_distance(&child_emb, &neg_emb);
+ let margin = 1.0;
+ if neg_dist < margin {
+ let grad_neg: Vec<f32> = neg_emb.iter().zip(child_emb.iter())
+ .map(|(n, c)| c - n)
+ .collect();
+ let new_neg = rsgd_step(&neg_emb, &grad_neg, lr);
+ embeddings.insert(neg_iri.clone(), new_neg);
+ }
+ }
+ }
+
+ // Pull root nodes toward origin
+ for root in &roots {
+ let root_emb = embeddings[root].clone();
+ // Gradient: point toward origin (i.e., the embedding itself, pulling it back)
+ let grad_to_origin: Vec<f32> = root_emb.iter().map(|x| *x).collect();
+ let new_root = rsgd_step(&root_emb, &grad_to_origin, lr * 0.5);
+ embeddings.insert(root.clone(), new_root);
+ }
+ }
+
+ Ok(embeddings)
+ }
+}
diff --git a/tests/structembed_test.rs b/tests/structembed_test.rs
new file mode 100644
index 00000000..5ff9fb81
--- /dev/null
+++ b/tests/structembed_test.rs
@@ -0,0 +1,82 @@
+use open_ontologies::structembed::StructuralTrainer;
+use open_ontologies::graph::GraphStore;
+use std::sync::Arc;
+
+#[test]
+fn test_train_simple_hierarchy() {
+ let store = Arc::new(GraphStore::new());
+ store.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://example.org/> .
+
+ ex:Animal a owl:Class ; rdfs:label "Animal" .
+ ex:Mammal a owl:Class ; rdfs:label "Mammal" ; rdfs:subClassOf ex:Animal .
+ ex:Dog a owl:Class ; rdfs:label "Dog" ; rdfs:subClassOf ex:Mammal .
+ ex:Cat a owl:Class ; rdfs:label "Cat" ; rdfs:subClassOf ex:Mammal .
+ ex:Vehicle a owl:Class ; rdfs:label "Vehicle" .
+ ex:Car a owl:Class ; rdfs:label "Car" ; rdfs:subClassOf ex:Vehicle .
+ "#, None).unwrap();
+
+ let trainer = StructuralTrainer::new(10, 500, 0.1);
+ let embeddings = trainer.train(&store).unwrap();
+
+ assert_eq!(embeddings.len(), 6);
+
+ let dog = &embeddings["http://example.org/Dog"];
+ let cat = &embeddings["http://example.org/Cat"];
+ let car = &embeddings["http://example.org/Car"];
+
+ let dog_cat = open_ontologies::poincare::poincare_distance(dog, cat);
+ let dog_car = open_ontologies::poincare::poincare_distance(dog, car);
+ assert!(dog_cat < dog_car, "Dog-Cat ({dog_cat}) should be closer than Dog-Car ({dog_car})");
+}
+
+#[test]
+fn test_train_parent_closer_than_unrelated() {
+ let store = Arc::new(GraphStore::new());
+ store.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://example.org/> .
+
+ ex:Animal a owl:Class .
+ ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal .
+ ex:Vehicle a owl:Class .
+ "#, None).unwrap();
+
+ let trainer = StructuralTrainer::new(10, 500, 0.1);
+ let embeddings = trainer.train(&store).unwrap();
+
+ let dog = &embeddings["http://example.org/Dog"];
+ let animal = &embeddings["http://example.org/Animal"];
+ let vehicle = &embeddings["http://example.org/Vehicle"];
+
+ let dog_animal = open_ontologies::poincare::poincare_distance(dog, animal);
+ let dog_vehicle = open_ontologies::poincare::poincare_distance(dog, vehicle);
+ assert!(dog_animal < dog_vehicle,
+ "Dog-Animal ({dog_animal}) should be closer than Dog-Vehicle ({dog_vehicle})");
+}
+
+#[test]
+fn test_root_near_origin() {
+ let store = Arc::new(GraphStore::new());
+ store.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://example.org/> .
+
+ ex:Thing a owl:Class .
+ ex:Animal a owl:Class ; rdfs:subClassOf ex:Thing .
+ ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal .
+ "#, None).unwrap();
+
+ let trainer = StructuralTrainer::new(10, 500, 0.1);
+ let embeddings = trainer.train(&store).unwrap();
+
+ let thing_norm: f32 = embeddings["http://example.org/Thing"].iter().map(|x| x*x).sum::<f32>().sqrt();
+ let dog_norm: f32 = embeddings["http://example.org/Dog"].iter().map(|x| x*x).sum::<f32>().sqrt();
+
+ assert!(thing_norm < dog_norm,
+ "Root Thing ({thing_norm}) should have smaller norm than leaf Dog ({dog_norm})");
+}