1use crate::adjacency::AdjacencyIndex;
9use crate::ids::{EdgeId, KindId, NodeId};
10use serde::{Deserialize, Serialize};
11use std::collections::BTreeMap;
12use std::fmt;
13
14pub const DEFAULT_NODE_WEIGHT: f32 = 1.0;
16pub const DEFAULT_EDGE_WEIGHT: f32 = 1.0;
18
19#[derive(Clone, Debug, PartialEq, Eq)]
21pub enum GraphError {
22 MissingNode(NodeId),
23 MissingEdge(EdgeId),
24 MissingKind(KindId),
25 DuplicateId(u64),
26 Format(String),
28}
29
30impl fmt::Display for GraphError {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 match self {
33 Self::MissingNode(id) => write!(f, "missing node {id}"),
34 Self::MissingEdge(id) => write!(f, "missing edge {id}"),
35 Self::MissingKind(id) => write!(f, "missing kind {id}"),
36 Self::DuplicateId(id) => write!(f, "duplicate id {id}"),
37 Self::Format(m) => write!(f, "invalid document: {m}"),
38 }
39 }
40}
41
42impl std::error::Error for GraphError {}
43
44#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
46pub struct NodeKind {
47 pub id: KindId,
48 pub name: String,
49}
50
51#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
53pub struct Node {
54 pub id: NodeId,
55 pub kind: Option<KindId>,
57 pub label: String,
58 pub weight: f32,
60 pub pinned: bool,
62}
63
64#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
66pub struct Edge {
67 pub id: EdgeId,
68 pub source: NodeId,
69 pub target: NodeId,
70 pub weight: f32,
72 pub label: Option<String>,
73}
74
75pub(crate) fn sanitize_weight(w: f32, default: f32) -> f32 {
77 if w.is_finite() && w >= 0.0 {
78 w
79 } else {
80 default
81 }
82}
83
84#[derive(Serialize, Deserialize)]
86struct GraphDoc {
87 version: u32,
88 directed: bool,
89 kinds: Vec<NodeKind>,
90 nodes: Vec<Node>,
91 edges: Vec<Edge>,
92}
93
94#[derive(Clone, Debug, Default)]
96pub struct KnowledgeGraph {
97 pub directed: bool,
99 kinds: BTreeMap<KindId, NodeKind>,
100 nodes: BTreeMap<NodeId, Node>,
101 edges: BTreeMap<EdgeId, Edge>,
102 adjacency: AdjacencyIndex,
103 next_node: u64,
104 next_edge: u64,
105 next_kind: u64,
106}
107
108impl KnowledgeGraph {
109 pub fn new() -> Self {
110 Self {
111 directed: false,
112 next_node: 1,
113 next_edge: 1,
114 next_kind: 1,
115 ..Default::default()
116 }
117 }
118
119 pub fn directed(mut self) -> Self {
121 self.directed = true;
122 self
123 }
124
125 pub fn alloc_node_id(&mut self) -> NodeId {
129 let id = NodeId(self.next_node);
130 self.next_node += 1;
131 id
132 }
133
134 pub fn alloc_edge_id(&mut self) -> EdgeId {
135 let id = EdgeId(self.next_edge);
136 self.next_edge += 1;
137 id
138 }
139
140 pub fn alloc_kind_id(&mut self) -> KindId {
141 let id = KindId(self.next_kind);
142 self.next_kind += 1;
143 id
144 }
145
146 pub fn add_kind(&mut self, name: impl Into<String>) -> KindId {
149 let id = self.alloc_kind_id();
150 self.kinds.insert(
151 id,
152 NodeKind {
153 id,
154 name: name.into(),
155 },
156 );
157 id
158 }
159
160 pub fn upsert_kind(&mut self, id: KindId, name: impl Into<String>) {
162 self.kinds
163 .entry(id)
164 .or_insert_with(|| NodeKind {
165 id,
166 name: String::new(),
167 })
168 .name = name.into();
169 self.next_kind = self.next_kind.max(id.0 + 1);
170 }
171
172 pub fn kind(&self, id: KindId) -> Option<&NodeKind> {
173 self.kinds.get(&id)
174 }
175
176 pub fn kinds(&self) -> impl Iterator<Item = &NodeKind> {
178 self.kinds.values()
179 }
180
181 pub fn add_node(&mut self, label: impl Into<String>, kind: Option<KindId>) -> NodeId {
184 let id = self.alloc_node_id();
185 self.insert_node(Node {
187 id,
188 kind,
189 label: label.into(),
190 weight: DEFAULT_NODE_WEIGHT,
191 pinned: false,
192 })
193 .expect("freshly allocated node id must not collide");
194 id
195 }
196
197 pub fn insert_node(&mut self, node: Node) -> Result<(), GraphError> {
199 if self.nodes.contains_key(&node.id) {
200 return Err(GraphError::DuplicateId(node.id.0));
201 }
202 if let Some(k) = node.kind
203 && !self.kinds.contains_key(&k)
204 {
205 return Err(GraphError::MissingKind(k));
206 }
207 let n = Node {
208 weight: sanitize_weight(node.weight, DEFAULT_NODE_WEIGHT),
209 ..node
210 };
211 self.next_node = self.next_node.max(n.id.0 + 1);
213 self.adjacency.add_vertex(n.id);
214 self.nodes.insert(n.id, n);
215 Ok(())
216 }
217
218 pub fn update_node(&mut self, node: Node) -> Result<(), GraphError> {
220 if !self.nodes.contains_key(&node.id) {
221 return Err(GraphError::MissingNode(node.id));
222 }
223 let n = Node {
224 weight: sanitize_weight(node.weight, DEFAULT_NODE_WEIGHT),
225 ..node
226 };
227 self.nodes.insert(n.id, n);
228 Ok(())
229 }
230
231 pub fn node(&self, id: NodeId) -> Option<&Node> {
232 self.nodes.get(&id)
233 }
234
235 pub fn remove_node(&mut self, id: NodeId) -> Result<(), GraphError> {
237 let Some(_node) = self.nodes.remove(&id) else {
238 return Err(GraphError::MissingNode(id));
239 };
240 let incident = self.adjacency.incident_edges(id);
241 for e in incident {
242 if let Some(edge) = self.edges.remove(&e) {
243 self.adjacency
244 .remove_edge(edge.source, edge.target, e, self.directed);
245 }
246 }
247 self.adjacency.remove_vertex(id);
248 Ok(())
249 }
250
251 pub fn add_edge(
254 &mut self,
255 source: NodeId,
256 target: NodeId,
257 weight: f32,
258 label: Option<String>,
259 ) -> Result<EdgeId, GraphError> {
260 if !self.nodes.contains_key(&source) {
261 return Err(GraphError::MissingNode(source));
262 }
263 if !self.nodes.contains_key(&target) {
264 return Err(GraphError::MissingNode(target));
265 }
266 let id = self.alloc_edge_id();
267 self.edges.insert(
268 id,
269 Edge {
270 id,
271 source,
272 target,
273 weight: sanitize_weight(weight, DEFAULT_EDGE_WEIGHT),
274 label,
275 },
276 );
277 self.adjacency.add_edge(source, target, id, self.directed);
278 Ok(id)
279 }
280
281 pub fn edge(&self, id: EdgeId) -> Option<&Edge> {
282 self.edges.get(&id)
283 }
284
285 pub fn remove_edge(&mut self, id: EdgeId) -> Result<(), GraphError> {
286 let Some(edge) = self.edges.remove(&id) else {
287 return Err(GraphError::MissingEdge(id));
288 };
289 self.adjacency
290 .remove_edge(edge.source, edge.target, id, self.directed);
291 Ok(())
292 }
293
294 pub fn node_count(&self) -> usize {
297 self.nodes.len()
298 }
299
300 pub fn edge_count(&self) -> usize {
301 self.edges.len()
302 }
303
304 pub fn nodes(&self) -> impl Iterator<Item = &Node> {
305 self.nodes.values()
306 }
307
308 pub fn edges(&self) -> impl Iterator<Item = &Edge> {
309 self.edges.values()
310 }
311
312 pub fn adjacency(&self) -> &AdjacencyIndex {
314 &self.adjacency
315 }
316
317 pub fn to_json(&self) -> String {
321 let doc = GraphDoc {
322 version: crate::FORMAT_VERSION,
323 directed: self.directed,
324 kinds: self.kinds.values().cloned().collect(),
325 nodes: self.nodes.values().cloned().collect(),
326 edges: self.edges.values().cloned().collect(),
327 };
328 serde_json::to_string(&doc).unwrap_or_else(|_| "{}".into())
329 }
330
331 pub fn from_json(json: &str) -> Result<Self, GraphError> {
333 let doc: GraphDoc =
334 serde_json::from_str(json).map_err(|e| GraphError::Format(e.to_string()))?;
335 if doc.version != crate::FORMAT_VERSION {
336 return Err(GraphError::Format(format!(
337 "unsupported version {}",
338 doc.version
339 )));
340 }
341 let mut g = Self::new();
342 g.directed = doc.directed;
343 for k in doc.kinds {
344 g.upsert_kind(k.id, k.name);
345 }
346 for n in doc.nodes {
347 g.insert_node(n)?;
348 }
349 for e in doc.edges {
350 if g.edges.contains_key(&e.id) {
351 return Err(GraphError::DuplicateId(e.id.0));
352 }
353 let edge = Edge {
354 weight: sanitize_weight(e.weight, DEFAULT_EDGE_WEIGHT),
355 ..e
356 };
357 if !g.nodes.contains_key(&edge.source) {
358 return Err(GraphError::MissingNode(edge.source));
359 }
360 if !g.nodes.contains_key(&edge.target) {
361 return Err(GraphError::MissingNode(edge.target));
362 }
363 let id = edge.id;
364 let (source, target) = (edge.source, edge.target);
365 g.edges.insert(id, edge);
366 g.adjacency.add_edge(source, target, id, g.directed);
367 g.next_edge = g.next_edge.max(id.0 + 1);
368 }
369 Ok(g)
370 }
371}