coreason_engine/
ontological_solver.rs1use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19
20#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
21pub struct OntologicalConcept {
22 pub id: String,
23 pub name: String,
24 pub category: String,
25}
26
27use petgraph::graph::{DiGraph, NodeIndex};
28use petgraph::visit::Bfs;
29
30pub struct OntologicalVocabularySolver {
32 pub concepts: HashMap<String, OntologicalConcept>,
33 pub graph: DiGraph<String, ()>,
34 pub node_indices: HashMap<String, NodeIndex>,
35}
36
37impl OntologicalVocabularySolver {
38 pub fn new() -> Self {
40 Self {
41 concepts: HashMap::new(),
42 graph: DiGraph::new(),
43 node_indices: HashMap::new(),
44 }
45 }
46
47 pub fn register_concept(&mut self, concept: OntologicalConcept) {
49 self.concepts.insert(concept.id.clone(), concept.clone());
50 if !self.node_indices.contains_key(&concept.id) {
51 let idx = self.graph.add_node(concept.id.clone());
52 self.node_indices.insert(concept.id, idx);
53 }
54 }
55
56 fn get_or_add_node(&mut self, id: &str) -> NodeIndex {
57 if let Some(&idx) = self.node_indices.get(id) {
58 idx
59 } else {
60 let idx = self.graph.add_node(id.to_string());
61 self.node_indices.insert(id.to_string(), idx);
62 idx
63 }
64 }
65
66 pub fn register_relationship(&mut self, parent_id: &str, child_id: &str) {
68 let p_idx = self.get_or_add_node(parent_id);
69 let c_idx = self.get_or_add_node(child_id);
70 self.graph.add_edge(p_idx, c_idx, ());
71 }
72
73 pub fn find_ancestors(&self, concept_id: &str) -> Vec<OntologicalConcept> {
75 let mut ancestors = Vec::new();
76 if let Some(&start_idx) = self.node_indices.get(concept_id) {
77 let mut bfs = Bfs::new(&self.graph, start_idx);
78 let reversed_graph = petgraph::visit::Reversed(&self.graph);
80 while let Some(nx) = bfs.next(reversed_graph) {
81 if nx != start_idx {
82 let id = &self.graph[nx];
83 if let Some(concept) = self.concepts.get(id) {
84 ancestors.push(concept.clone());
85 }
86 }
87 }
88 }
89 ancestors
90 }
91
92 pub fn find_descendants(&self, concept_id: &str) -> Vec<OntologicalConcept> {
94 let mut descendants = Vec::new();
95 if let Some(&start_idx) = self.node_indices.get(concept_id) {
96 let mut bfs = Bfs::new(&self.graph, start_idx);
97 while let Some(nx) = bfs.next(&self.graph) {
98 if nx != start_idx {
99 let id = &self.graph[nx];
100 if let Some(concept) = self.concepts.get(id) {
101 descendants.push(concept.clone());
102 }
103 }
104 }
105 }
106 descendants
107 }
108
109 pub fn compile_cfg_constraint(&self, candidate_ids: &[String]) -> String {
112 if candidate_ids.is_empty() {
113 return "root ::= \"empty\"".to_string();
114 }
115
116 let mut alternatives = Vec::new();
117 for id in candidate_ids {
118 let escaped = id.replace('"', "\\\"");
119 alternatives.push(format!("\"{}\"", escaped));
120 }
121
122 let rule = alternatives.join(" | ");
123 format!("root ::= concept_id\nconcept_id ::= {}", rule)
124 }
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130
131 #[test]
132 fn test_vocabulary_solver_registrations() {
133 let mut solver = OntologicalVocabularySolver::new();
134
135 let c1 = OntologicalConcept {
136 id: "concept_root".to_string(),
137 name: "Root Entity".to_string(),
138 category: "generic".to_string(),
139 };
140 let c2 = OntologicalConcept {
141 id: "concept_child".to_string(),
142 name: "Child Entity".to_string(),
143 category: "generic".to_string(),
144 };
145
146 solver.register_concept(c1.clone());
147 solver.register_concept(c2.clone());
148 solver.register_relationship("concept_root", "concept_child");
149
150 assert_eq!(solver.concepts.len(), 2);
151 assert_eq!(solver.concepts.get("concept_root"), Some(&c1));
152 assert_eq!(solver.concepts.get("concept_child"), Some(&c2));
153 }
154
155 #[test]
156 fn test_hierarchical_concept_traversals() {
157 let mut solver = OntologicalVocabularySolver::new();
158
159 let c1 = OntologicalConcept {
160 id: "urn:coreason:entity:a".to_string(),
161 name: "A".to_string(),
162 category: "tda".to_string(),
163 };
164 let c2 = OntologicalConcept {
165 id: "urn:coreason:entity:b".to_string(),
166 name: "B".to_string(),
167 category: "tda".to_string(),
168 };
169 let c3 = OntologicalConcept {
170 id: "urn:coreason:entity:c".to_string(),
171 name: "C".to_string(),
172 category: "tda".to_string(),
173 };
174
175 solver.register_concept(c1.clone());
176 solver.register_concept(c2.clone());
177 solver.register_concept(c3.clone());
178
179 solver.register_relationship("urn:coreason:entity:a", "urn:coreason:entity:b");
181 solver.register_relationship("urn:coreason:entity:b", "urn:coreason:entity:c");
182
183 let desc = solver.find_descendants("urn:coreason:entity:a");
185 assert_eq!(desc.len(), 2);
186 assert!(desc.contains(&c2));
187 assert!(desc.contains(&c3));
188
189 let anc = solver.find_ancestors("urn:coreason:entity:c");
191 assert_eq!(anc.len(), 2);
192 assert!(anc.contains(&c2));
193 assert!(anc.contains(&c1));
194 }
195
196 #[test]
197 fn test_compile_cfg_constraint() {
198 let solver = OntologicalVocabularySolver::new();
199 let candidates = vec!["urn:coreason:a".to_string(), "urn:coreason:b".to_string()];
200
201 let cfg = solver.compile_cfg_constraint(&candidates);
202 assert_eq!(
203 cfg,
204 "root ::= concept_id\nconcept_id ::= \"urn:coreason:a\" | \"urn:coreason:b\""
205 );
206
207 let empty_cfg = solver.compile_cfg_constraint(&[]);
208 assert_eq!(empty_cfg, "root ::= \"empty\"");
209 }
210}