Skip to main content

arc_graph_core/
model.rs

1//! 知识图谱数据模型:节点 / 关系 / 类型 / 权重 + 变更 API。
2//!
3//! 设计要点(方案 `docs/graph/knowledge-graph-plan.md` §2):
4//! - 纯数据,不依赖 gpui;颜色等外观一律留在视图层(arc-tokens),核心层只存类型名。
5//! - 权重在输入边界净化(NaN / 负数归默认值),布局引擎(G2)可以直接信任。
6//! - 邻接索引增量维护(见 [`AdjacencyIndex`]),读路径 O(1),写路径摊还 O(degree)。
7
8use crate::adjacency::AdjacencyIndex;
9use crate::ids::{EdgeId, KindId, NodeId};
10use serde::{Deserialize, Serialize};
11use std::collections::BTreeMap;
12use std::fmt;
13
14/// 节点默认质量(力导向里的质量 / 惯性)。
15pub const DEFAULT_NODE_WEIGHT: f32 = 1.0;
16/// 边默认引力强度。
17pub const DEFAULT_EDGE_WEIGHT: f32 = 1.0;
18
19/// 顶层错误。`Display` 与 arc-flow-core 的 `GraphError` 风格一致。
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub enum GraphError {
22    MissingNode(NodeId),
23    MissingEdge(EdgeId),
24    MissingKind(KindId),
25    DuplicateId(u64),
26    /// 导入文档结构不合法(坏 JSON / 表头缺失等)。解析层保证不 panic。
27    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/// 节点类型(如「人物」「机构」「概念」)。只存名称;颜色映射在视图层按类型序号取 arc-tokens 调色板。
45#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
46pub struct NodeKind {
47    pub id: KindId,
48    pub name: String,
49}
50
51/// 图节点。`weight` 是力导向质量,`pinned` 表示布局中固定不动。
52#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
53pub struct Node {
54    pub id: NodeId,
55    /// 类型;`None` 表示未分类。
56    pub kind: Option<KindId>,
57    pub label: String,
58    /// 布局质量,恒 ≥ 0 且非 NaN(输入边界已净化)。
59    pub weight: f32,
60    /// 固定节点:布局迭代中位置不动,可被拖动 / 搜索定位。
61    pub pinned: bool,
62}
63
64/// 关系边。知识图谱常为有向(A → B),也支持无向整体开关。
65#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
66pub struct Edge {
67    pub id: EdgeId,
68    pub source: NodeId,
69    pub target: NodeId,
70    /// 引力强度,恒 ≥ 0 且非 NaN。
71    pub weight: f32,
72    pub label: Option<String>,
73}
74
75/// 权重净化:NaN / 负数 / 非有限值归默认,防止布局发散(方案 §7「大图不溢出」)。
76pub(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/// 持久化文档格式(JSON)。
85#[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/// 知识图谱。有向 / 无向在图级别声明(布局与邻接口径一致)。
95#[derive(Clone, Debug, Default)]
96pub struct KnowledgeGraph {
97    /// 是否有向;无向图的邻接查询双向对称。
98    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    /// 有向图构造器(导入与测试用)。
120    pub fn directed(mut self) -> Self {
121        self.directed = true;
122        self
123    }
124
125    // ---------- ID ----------
126
127    /// 分配并占用一个新节点 ID(导入预扫用,避免逐条 add 的开销)。
128    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    // ---------- 类型 ----------
147
148    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    /// 插入指定 ID 的类型;已存在时只更新名称(CSV 按名引用的场景)。
161    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    /// 类型列表,按 ID 有序(保证遍历与序列化可复现)。
177    pub fn kinds(&self) -> impl Iterator<Item = &NodeKind> {
178        self.kinds.values()
179    }
180
181    // ---------- 节点 ----------
182
183    pub fn add_node(&mut self, label: impl Into<String>, kind: Option<KindId>) -> NodeId {
184        let id = self.alloc_node_id();
185        // 新分配的 ID 不可能与现有节点冲突,插入必成功。
186        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    /// 插入完整节点(导入路径)。ID 已存在返回错误且不产生半写入。
198    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        // 外部指定的 ID 也要推进计数器,避免后续 add_node 分配出重复 ID。
212        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    /// 直接更新节点(保留原位置语义在布局层,这里只是存储替换)。
219    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    /// 删除节点,级联删除全部关联边。
236    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    // ---------- 边 ----------
252
253    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    // ---------- 查询 ----------
295
296    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    /// 邻接索引(一度邻居 / 入射边 / 度数)。
313    pub fn adjacency(&self) -> &AdjacencyIndex {
314        &self.adjacency
315    }
316
317    // ---------- 序列化 ----------
318
319    /// 导出为 JSON 文档字符串。
320    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    /// 从 JSON 文档导入。坏 JSON 返回 `GraphError::Format`,不 panic。
332    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}