god-graph 0.6.0-alpha

A graph-based LLM white-box optimization toolbox: topology validation, Lie group orthogonalization, tensor ring compression
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! 最短路径算法模块
//!
//! 包含 Dijkstra、Bellman-Ford、Floyd-Warshall、A* 等算法

use crate::errors::{GraphError, GraphResult};
use crate::graph::traits::{GraphBase, GraphQuery};
use crate::graph::Graph;
use crate::node::NodeIndex;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap};

/// Dijkstra 最短路径算法
///
/// 计算从源节点到所有其他节点的最短路径距离
/// 适用于非负权重的图
///
/// # 参数
/// * `graph` - 图
/// * `source` - 源节点
/// * `get_weight` - 获取边权重的闭包
///
/// # 返回
/// HashMap,键为节点索引,值为最短距离
///
/// # 错误
/// * `GraphError::NegativeWeight` - 检测到负权重边,建议使用 Bellman-Ford 算法
///
/// # 注意
/// Dijkstra 算法不适用于负权重图。如果图可能包含负权重,请使用 `bellman_ford` 算法。
pub fn dijkstra<T, E, F>(
    graph: &Graph<T, E>,
    source: NodeIndex,
    mut get_weight: F,
) -> GraphResult<HashMap<NodeIndex, f64>>
where
    F: FnMut(NodeIndex, NodeIndex, &E) -> f64,
{
    // 检测负权重边
    for edge in graph.edges() {
        let u = edge.source();
        let v = edge.target();
        let weight = get_weight(u, v, edge.data());
        if weight < 0.0 {
            return Err(GraphError::NegativeWeight {
                from: u.index(),
                to: v.index(),
                weight,
            });
        }
    }

    // 优先队列项:(节点,距离),使用 Reverse 实现最小堆
    struct State {
        node: NodeIndex,
        distance: f64,
    }

    impl PartialEq for State {
        fn eq(&self, other: &Self) -> bool {
            self.distance == other.distance
        }
    }

    impl Eq for State {}

    impl PartialOrd for State {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }

    impl Ord for State {
        fn cmp(&self, other: &Self) -> Ordering {
            other.distance.total_cmp(&self.distance)
        }
    }

    let mut distances: HashMap<NodeIndex, f64> = HashMap::new();
    let mut heap = BinaryHeap::new();

    distances.insert(source, 0.0);
    heap.push(State {
        node: source,
        distance: 0.0,
    });

    while let Some(State { node, distance }) = heap.pop() {
        // 跳过过期的条目
        if distance > *distances.get(&node).unwrap_or(&f64::INFINITY) {
            continue;
        }

        for neighbor in graph.neighbors(node) {
            let edge_data = graph.get_edge_by_nodes(node, neighbor)?;
            let weight = get_weight(node, neighbor, edge_data);
            let new_distance = distance + weight;

            if new_distance < *distances.get(&neighbor).unwrap_or(&f64::INFINITY) {
                distances.insert(neighbor, new_distance);
                heap.push(State {
                    node: neighbor,
                    distance: new_distance,
                });
            }
        }
    }

    Ok(distances)
}

/// Bellman-Ford 算法
///
/// 计算从源节点到所有其他节点的最短路径
/// 可以处理负权重边,并能检测负权环
///
/// # 返回
/// * `Ok(HashMap)` - 最短距离
/// * `Err(GraphError::NegativeCycle)` - 检测到负权环
pub fn bellman_ford<T, E, F>(
    graph: &Graph<T, E>,
    source: NodeIndex,
    mut get_weight: F,
) -> Result<HashMap<NodeIndex, f64>, GraphError>
where
    F: FnMut(NodeIndex, NodeIndex, &E) -> f64,
{
    let mut distances: HashMap<NodeIndex, f64> = HashMap::new();

    // 初始化距离
    for node in graph.nodes() {
        distances.insert(node.index(), f64::INFINITY);
    }
    distances.insert(source, 0.0);

    let n = graph.node_count();

    // 松弛操作,执行 n-1 轮
    for _ in 0..n - 1 {
        for edge in graph.edges() {
            let u = edge.source();
            let v = edge.target();
            let w = get_weight(u, v, edge.data());

            if distances.get(&u) != Some(&f64::INFINITY) {
                let new_dist = distances[&u] + w;
                if new_dist < *distances.get(&v).unwrap_or(&f64::INFINITY) {
                    distances.insert(v, new_dist);
                }
            }
        }
    }

    // 检测负权环
    for edge in graph.edges() {
        let u = edge.source();
        let v = edge.target();
        let w = get_weight(u, v, edge.data());

        if distances.get(&u) != Some(&f64::INFINITY)
            && distances[&u] + w < *distances.get(&v).unwrap_or(&f64::INFINITY)
        {
            return Err(GraphError::NegativeCycle);
        }
    }

    Ok(distances)
}

/// A* 搜索算法
///
/// 使用启发式函数找到从起点到终点的最短路径
///
/// # 参数
/// * `graph` - 图
/// * `start` - 起始节点
/// * `goal` - 目标节点
/// * `get_weight` - 获取边权重的闭包
/// * `heuristic` - 启发式函数,估计节点到目标的距离
pub fn astar<T, E, F, H>(
    graph: &Graph<T, E>,
    start: NodeIndex,
    goal: NodeIndex,
    mut get_weight: F,
    mut heuristic: H,
) -> GraphResult<(f64, Vec<NodeIndex>)>
where
    F: FnMut(NodeIndex, NodeIndex, &E) -> f64,
    H: FnMut(NodeIndex) -> f64,
{
    #[derive(Debug)]
    struct State {
        node: NodeIndex,
        f_score: f64,
    }

    impl PartialEq for State {
        fn eq(&self, other: &Self) -> bool {
            self.f_score == other.f_score
        }
    }

    impl Eq for State {}

    impl PartialOrd for State {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }

    impl Ord for State {
        fn cmp(&self, other: &Self) -> Ordering {
            other.f_score.total_cmp(&self.f_score)
        }
    }

    let mut g_scores: HashMap<NodeIndex, f64> = HashMap::new();
    let mut came_from: HashMap<NodeIndex, NodeIndex> = HashMap::new();
    let mut heap = BinaryHeap::new();

    g_scores.insert(start, 0.0);
    heap.push(State {
        node: start,
        f_score: heuristic(start),
    });

    while let Some(State { node, .. }) = heap.pop() {
        if node == goal {
            // 重构路径
            let mut path = vec![goal];
            let mut current = goal;
            while let Some(&prev) = came_from.get(&current) {
                path.push(prev);
                current = prev;
            }
            path.reverse();
            return Ok((*g_scores.get(&goal).unwrap_or(&0.0), path));
        }

        let current_g = *g_scores.get(&node).unwrap_or(&f64::INFINITY);

        for neighbor in graph.neighbors(node) {
            let edge_data = graph.get_edge_by_nodes(node, neighbor)?;
            let weight = get_weight(node, neighbor, edge_data);
            let tentative_g = current_g + weight;

            if tentative_g < *g_scores.get(&neighbor).unwrap_or(&f64::INFINITY) {
                came_from.insert(neighbor, node);
                g_scores.insert(neighbor, tentative_g);
                let f_score = tentative_g + heuristic(neighbor);
                heap.push(State {
                    node: neighbor,
                    f_score,
                });
            }
        }
    }

    Err(GraphError::NodeNotFound {
        index: goal.index(),
    })
}

/// Floyd-Warshall 算法
///
/// 计算所有节点对之间的最短路径距离
/// 适用于任意权重的图(可处理负权重)
/// 时间复杂度:O(V³),空间复杂度:O(V²)
///
/// # 参数
/// * `graph` - 图
/// * `get_weight` - 获取边权重的闭包
///
/// # 返回
/// * `Ok(HashMap<(NodeIndex, NodeIndex), f64>)` - 所有节点对的最短距离
/// * `Err(GraphError::NegativeCycle)` - 检测到负权环
///
/// # 示例
/// ```rust
/// use god_gragh::graph::builders::GraphBuilder;
/// use god_gragh::algorithms::shortest_path::floyd_warshall;
///
/// let graph = GraphBuilder::directed()
///     .with_nodes(vec!["A", "B", "C"])
///     .with_edges(vec![(0, 1, 1.0), (1, 2, 2.0), (0, 2, 4.0)])
///     .build()
///     .unwrap();
///
/// let distances = floyd_warshall(&graph, |_, _, w| *w).unwrap();
/// ```
pub fn floyd_warshall<T, E, F>(
    graph: &Graph<T, E>,
    mut get_weight: F,
) -> Result<HashMap<(NodeIndex, NodeIndex), f64>, GraphError>
where
    F: FnMut(NodeIndex, NodeIndex, &E) -> f64,
{
    let node_indices: Vec<NodeIndex> = graph.nodes().map(|n| n.index()).collect();
    let n = node_indices.len();

    if n == 0 {
        return Ok(HashMap::new());
    }

    // 创建索引到 NodeIndex 的映射
    let index_to_node = &node_indices;
    let node_to_index: std::collections::HashMap<usize, usize> = node_indices
        .iter()
        .enumerate()
        .map(|(i, ni)| (ni.index(), i))
        .collect();

    // 初始化距离矩阵
    const INF: f64 = f64::INFINITY;
    let mut dist = vec![vec![INF; n]; n];

    // 设置对角线为 0
    for (i, row) in dist.iter_mut().enumerate().take(n) {
        row[i] = 0.0;
    }

    // 设置直接边的权重
    for edge in graph.edges() {
        let u = edge.source();
        let v = edge.target();
        if let (Some(&i), Some(&j)) = (node_to_index.get(&u.index()), node_to_index.get(&v.index()))
        {
            let weight = get_weight(u, v, edge.data());
            dist[i][j] = dist[i][j].min(weight);
        }
    }

    // Floyd-Warshall 主循环
    for k in 0..n {
        for i in 0..n {
            for j in 0..n {
                if dist[i][k] != INF && dist[k][j] != INF {
                    let new_dist = dist[i][k] + dist[k][j];
                    if new_dist < dist[i][j] {
                        dist[i][j] = new_dist;
                    }
                }
            }
        }
    }

    // 检测负权环:检查对角线是否有负值
    #[allow(clippy::needless_range_loop)]
    for i in 0..n {
        if dist[i][i] < 0.0 {
            return Err(GraphError::NegativeCycle);
        }
    }

    // 构建结果 HashMap
    let mut result = HashMap::with_capacity(n * n);
    for (i, row) in dist.iter().enumerate().take(n) {
        for (j, &value) in row.iter().enumerate().take(n) {
            if value != INF {
                result.insert((index_to_node[i], index_to_node[j]), value);
            }
        }
    }

    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::builders::GraphBuilder;

    #[test]
    fn test_dijkstra_basic() {
        let graph = GraphBuilder::directed()
            .with_nodes(vec!["A", "B", "C", "D"])
            .with_edges(vec![
                (0, 1, 1.0),
                (0, 2, 4.0),
                (1, 2, 2.0),
                (1, 3, 5.0),
                (2, 3, 1.0),
            ])
            .build()
            .unwrap();

        let start = NodeIndex::new(0, 1);
        let distances = dijkstra(&graph, start, |_, _, _| 1.0).unwrap();

        assert!(distances.contains_key(&start));
    }

    #[test]
    fn test_dijkstra_negative_weights() {
        let graph = GraphBuilder::directed()
            .with_nodes(vec!["A", "B", "C"])
            .with_edges(vec![(0, 1, 1.0), (1, 2, -2.0), (0, 2, 3.0)])
            .build()
            .unwrap();

        let start = NodeIndex::new(0, 1);
        let result = dijkstra(&graph, start, |_, _, w| *w);

        assert!(matches!(result, Err(GraphError::NegativeWeight { .. })));
    }

    #[test]
    fn test_bellman_ford_basic() {
        let graph = GraphBuilder::directed()
            .with_nodes(vec!["A", "B", "C", "D"])
            .with_edges(vec![
                (0, 1, 4.0),
                (0, 2, 2.0),
                (1, 2, 1.0),
                (1, 3, 5.0),
                (2, 3, 3.0),
            ])
            .build()
            .unwrap();

        let source = NodeIndex::new(0, 1);
        let distances = bellman_ford(&graph, source, |_, _, w| *w).unwrap();

        assert_eq!(distances.get(&source), Some(&0.0));
        assert!(distances.len() == 4);
    }

    #[test]
    fn test_bellman_ford_negative_weights() {
        let graph = GraphBuilder::directed()
            .with_nodes(vec!["A", "B", "C"])
            .with_edges(vec![(0, 1, 1.0), (1, 2, -2.0), (0, 2, 3.0)])
            .build()
            .unwrap();

        let source = NodeIndex::new(0, 1);
        let distances = bellman_ford(&graph, source, |_, _, w| *w).unwrap();

        // A->B->C = 1 + (-2) = -1, which is shorter than A->C = 3
        assert_eq!(distances.get(&NodeIndex::new(2, 1)), Some(&-1.0));
    }

    #[test]
    fn test_bellman_ford_negative_cycle() {
        let graph = GraphBuilder::directed()
            .with_nodes(vec!["A", "B", "C"])
            .with_edges(vec![(0, 1, 1.0), (1, 2, -2.0), (2, 0, -3.0)])
            .build()
            .unwrap();

        let source = NodeIndex::new(0, 1);
        let result = bellman_ford(&graph, source, |_, _, w| *w);

        assert!(matches!(result, Err(GraphError::NegativeCycle)));
    }

    #[test]
    fn test_astar_basic() {
        let graph = GraphBuilder::directed()
            .with_nodes(vec!["A", "B", "C", "D"])
            .with_edges(vec![
                (0, 1, 1.0),
                (0, 2, 4.0),
                (1, 2, 2.0),
                (1, 3, 5.0),
                (2, 3, 1.0),
            ])
            .build()
            .unwrap();

        let start = NodeIndex::new(0, 1);
        let goal = NodeIndex::new(3, 1);

        // 使用简单的启发式函数(始终返回 0,退化为 Dijkstra)
        let (distance, path) = astar(&graph, start, goal, |_, _, _| 1.0, |_| 0.0).unwrap();

        assert!(distance > 0.0);
        assert!(!path.is_empty());
        assert_eq!(path.first(), Some(&start));
        assert_eq!(path.last(), Some(&goal));
    }

    #[test]
    fn test_floyd_warshall_basic() {
        let graph = GraphBuilder::directed()
            .with_nodes(vec!["A", "B", "C", "D"])
            .with_edges(vec![
                (0, 1, 1.0),
                (0, 2, 4.0),
                (1, 2, 2.0),
                (1, 3, 5.0),
                (2, 3, 1.0),
            ])
            .build()
            .unwrap();

        let distances = floyd_warshall(&graph, |_, _, w| *w).unwrap();

        // 验证节点对之间的距离
        let nodes: Vec<_> = graph.nodes().collect();
        assert_eq!(
            distances.get(&(nodes[0].index(), nodes[3].index())),
            Some(&4.0)
        ); // A->B->C->D = 1+2+1 = 4
    }

    #[test]
    fn test_floyd_warshall_negative_weights() {
        let graph = GraphBuilder::directed()
            .with_nodes(vec!["A", "B", "C"])
            .with_edges(vec![(0, 1, 1.0), (1, 2, -2.0), (0, 2, 3.0)])
            .build()
            .unwrap();

        let distances = floyd_warshall(&graph, |_, _, w| *w).unwrap();

        let nodes: Vec<_> = graph.nodes().collect();
        // A->B->C = 1 + (-2) = -1
        assert_eq!(
            distances.get(&(nodes[0].index(), nodes[2].index())),
            Some(&-1.0)
        );
    }

    #[test]
    fn test_floyd_warshall_negative_cycle() {
        let graph = GraphBuilder::directed()
            .with_nodes(vec!["A", "B", "C"])
            .with_edges(vec![(0, 1, 1.0), (1, 2, -2.0), (2, 0, -3.0)])
            .build()
            .unwrap();

        let result = floyd_warshall(&graph, |_, _, w| *w);
        assert!(matches!(result, Err(GraphError::NegativeCycle)));
    }

    #[test]
    fn test_floyd_warshall_empty_graph() {
        let graph: Graph<i32, f64> = GraphBuilder::directed().build().unwrap();
        let distances = floyd_warshall(&graph, |_, _, _: &f64| 1.0).unwrap();
        assert!(distances.is_empty());
    }
}