use crate::adjacency::AdjacencyIndex;
use crate::ids::{EdgeId, KindId, NodeId};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
pub const DEFAULT_NODE_WEIGHT: f32 = 1.0;
pub const DEFAULT_EDGE_WEIGHT: f32 = 1.0;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GraphError {
MissingNode(NodeId),
MissingEdge(EdgeId),
MissingKind(KindId),
DuplicateId(u64),
Format(String),
}
impl fmt::Display for GraphError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingNode(id) => write!(f, "missing node {id}"),
Self::MissingEdge(id) => write!(f, "missing edge {id}"),
Self::MissingKind(id) => write!(f, "missing kind {id}"),
Self::DuplicateId(id) => write!(f, "duplicate id {id}"),
Self::Format(m) => write!(f, "invalid document: {m}"),
}
}
}
impl std::error::Error for GraphError {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NodeKind {
pub id: KindId,
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
pub id: NodeId,
pub kind: Option<KindId>,
pub label: String,
pub weight: f32,
pub pinned: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Edge {
pub id: EdgeId,
pub source: NodeId,
pub target: NodeId,
pub weight: f32,
pub label: Option<String>,
}
pub(crate) fn sanitize_weight(w: f32, default: f32) -> f32 {
if w.is_finite() && w >= 0.0 {
w
} else {
default
}
}
#[derive(Serialize, Deserialize)]
struct GraphDoc {
version: u32,
directed: bool,
kinds: Vec<NodeKind>,
nodes: Vec<Node>,
edges: Vec<Edge>,
}
#[derive(Clone, Debug, Default)]
pub struct KnowledgeGraph {
pub directed: bool,
kinds: BTreeMap<KindId, NodeKind>,
nodes: BTreeMap<NodeId, Node>,
edges: BTreeMap<EdgeId, Edge>,
adjacency: AdjacencyIndex,
next_node: u64,
next_edge: u64,
next_kind: u64,
}
impl KnowledgeGraph {
pub fn new() -> Self {
Self {
directed: false,
next_node: 1,
next_edge: 1,
next_kind: 1,
..Default::default()
}
}
pub fn directed(mut self) -> Self {
self.directed = true;
self
}
pub fn alloc_node_id(&mut self) -> NodeId {
let id = NodeId(self.next_node);
self.next_node += 1;
id
}
pub fn alloc_edge_id(&mut self) -> EdgeId {
let id = EdgeId(self.next_edge);
self.next_edge += 1;
id
}
pub fn alloc_kind_id(&mut self) -> KindId {
let id = KindId(self.next_kind);
self.next_kind += 1;
id
}
pub fn add_kind(&mut self, name: impl Into<String>) -> KindId {
let id = self.alloc_kind_id();
self.kinds.insert(
id,
NodeKind {
id,
name: name.into(),
},
);
id
}
pub fn upsert_kind(&mut self, id: KindId, name: impl Into<String>) {
self.kinds
.entry(id)
.or_insert_with(|| NodeKind {
id,
name: String::new(),
})
.name = name.into();
self.next_kind = self.next_kind.max(id.0 + 1);
}
pub fn kind(&self, id: KindId) -> Option<&NodeKind> {
self.kinds.get(&id)
}
pub fn kinds(&self) -> impl Iterator<Item = &NodeKind> {
self.kinds.values()
}
pub fn add_node(&mut self, label: impl Into<String>, kind: Option<KindId>) -> NodeId {
let id = self.alloc_node_id();
self.insert_node(Node {
id,
kind,
label: label.into(),
weight: DEFAULT_NODE_WEIGHT,
pinned: false,
})
.expect("freshly allocated node id must not collide");
id
}
pub fn insert_node(&mut self, node: Node) -> Result<(), GraphError> {
if self.nodes.contains_key(&node.id) {
return Err(GraphError::DuplicateId(node.id.0));
}
if let Some(k) = node.kind
&& !self.kinds.contains_key(&k)
{
return Err(GraphError::MissingKind(k));
}
let n = Node {
weight: sanitize_weight(node.weight, DEFAULT_NODE_WEIGHT),
..node
};
self.next_node = self.next_node.max(n.id.0 + 1);
self.adjacency.add_vertex(n.id);
self.nodes.insert(n.id, n);
Ok(())
}
pub fn update_node(&mut self, node: Node) -> Result<(), GraphError> {
if !self.nodes.contains_key(&node.id) {
return Err(GraphError::MissingNode(node.id));
}
let n = Node {
weight: sanitize_weight(node.weight, DEFAULT_NODE_WEIGHT),
..node
};
self.nodes.insert(n.id, n);
Ok(())
}
pub fn node(&self, id: NodeId) -> Option<&Node> {
self.nodes.get(&id)
}
pub fn remove_node(&mut self, id: NodeId) -> Result<(), GraphError> {
let Some(_node) = self.nodes.remove(&id) else {
return Err(GraphError::MissingNode(id));
};
let incident = self.adjacency.incident_edges(id);
for e in incident {
if let Some(edge) = self.edges.remove(&e) {
self.adjacency
.remove_edge(edge.source, edge.target, e, self.directed);
}
}
self.adjacency.remove_vertex(id);
Ok(())
}
pub fn add_edge(
&mut self,
source: NodeId,
target: NodeId,
weight: f32,
label: Option<String>,
) -> Result<EdgeId, GraphError> {
if !self.nodes.contains_key(&source) {
return Err(GraphError::MissingNode(source));
}
if !self.nodes.contains_key(&target) {
return Err(GraphError::MissingNode(target));
}
let id = self.alloc_edge_id();
self.edges.insert(
id,
Edge {
id,
source,
target,
weight: sanitize_weight(weight, DEFAULT_EDGE_WEIGHT),
label,
},
);
self.adjacency.add_edge(source, target, id, self.directed);
Ok(id)
}
pub fn edge(&self, id: EdgeId) -> Option<&Edge> {
self.edges.get(&id)
}
pub fn remove_edge(&mut self, id: EdgeId) -> Result<(), GraphError> {
let Some(edge) = self.edges.remove(&id) else {
return Err(GraphError::MissingEdge(id));
};
self.adjacency
.remove_edge(edge.source, edge.target, id, self.directed);
Ok(())
}
pub fn node_count(&self) -> usize {
self.nodes.len()
}
pub fn edge_count(&self) -> usize {
self.edges.len()
}
pub fn nodes(&self) -> impl Iterator<Item = &Node> {
self.nodes.values()
}
pub fn edges(&self) -> impl Iterator<Item = &Edge> {
self.edges.values()
}
pub fn adjacency(&self) -> &AdjacencyIndex {
&self.adjacency
}
pub fn to_json(&self) -> String {
let doc = GraphDoc {
version: crate::FORMAT_VERSION,
directed: self.directed,
kinds: self.kinds.values().cloned().collect(),
nodes: self.nodes.values().cloned().collect(),
edges: self.edges.values().cloned().collect(),
};
serde_json::to_string(&doc).unwrap_or_else(|_| "{}".into())
}
pub fn from_json(json: &str) -> Result<Self, GraphError> {
let doc: GraphDoc =
serde_json::from_str(json).map_err(|e| GraphError::Format(e.to_string()))?;
if doc.version != crate::FORMAT_VERSION {
return Err(GraphError::Format(format!(
"unsupported version {}",
doc.version
)));
}
let mut g = Self::new();
g.directed = doc.directed;
for k in doc.kinds {
g.upsert_kind(k.id, k.name);
}
for n in doc.nodes {
g.insert_node(n)?;
}
for e in doc.edges {
if g.edges.contains_key(&e.id) {
return Err(GraphError::DuplicateId(e.id.0));
}
let edge = Edge {
weight: sanitize_weight(e.weight, DEFAULT_EDGE_WEIGHT),
..e
};
if !g.nodes.contains_key(&edge.source) {
return Err(GraphError::MissingNode(edge.source));
}
if !g.nodes.contains_key(&edge.target) {
return Err(GraphError::MissingNode(edge.target));
}
let id = edge.id;
let (source, target) = (edge.source, edge.target);
g.edges.insert(id, edge);
g.adjacency.add_edge(source, target, id, g.directed);
g.next_edge = g.next_edge.max(id.0 + 1);
}
Ok(g)
}
}