aprender-core 0.31.2

Next-generation machine learning library in pure Rust
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
//\! Advanced graph tests: all-pairs shortest paths, A*, DFS, components, label propagation.

use crate::graph::*;

// ========================================================================
// All-Pairs Shortest Paths Tests
// ========================================================================

#[test]
fn test_apsp_linear_chain() {
    // Linear chain: 0 -- 1 -- 2 -- 3
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 3)], false);
    let dist = g.all_pairs_shortest_paths();

    // Check diagonal (distance to self = 0)
    for (i, row) in dist.iter().enumerate().take(4) {
        assert_eq!(row[i], Some(0));
    }

    // Check distances
    assert_eq!(dist[0][1], Some(1));
    assert_eq!(dist[0][2], Some(2));
    assert_eq!(dist[0][3], Some(3));
    assert_eq!(dist[1][2], Some(1));
    assert_eq!(dist[1][3], Some(2));
    assert_eq!(dist[2][3], Some(1));

    // Check symmetry (undirected graph)
    assert_eq!(dist[0][3], dist[3][0]);
    assert_eq!(dist[1][2], dist[2][1]);
}

#[test]
fn test_apsp_complete_graph() {
    // Complete graph K4
    let g = Graph::from_edges(&[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)], false);
    let dist = g.all_pairs_shortest_paths();

    // All pairs should have distance 1 (direct edge) except diagonal
    for (i, row) in dist.iter().enumerate().take(4) {
        for (j, &cell) in row.iter().enumerate().take(4) {
            if i == j {
                assert_eq!(cell, Some(0));
            } else {
                assert_eq!(cell, Some(1));
            }
        }
    }
}

#[test]
fn test_apsp_disconnected() {
    // Two disconnected components: (0, 1) and (2, 3)
    let g = Graph::from_edges(&[(0, 1), (2, 3)], false);
    let dist = g.all_pairs_shortest_paths();

    // Within components
    assert_eq!(dist[0][1], Some(1));
    assert_eq!(dist[1][0], Some(1));
    assert_eq!(dist[2][3], Some(1));
    assert_eq!(dist[3][2], Some(1));

    // Between components (no path)
    assert_eq!(dist[0][2], None);
    assert_eq!(dist[0][3], None);
    assert_eq!(dist[1][2], None);
    assert_eq!(dist[1][3], None);
}

#[test]
fn test_apsp_directed() {
    // Directed graph: 0 -> 1 -> 2
    let g = Graph::from_edges(&[(0, 1), (1, 2)], true);
    let dist = g.all_pairs_shortest_paths();

    // Forward paths
    assert_eq!(dist[0][1], Some(1));
    assert_eq!(dist[0][2], Some(2));
    assert_eq!(dist[1][2], Some(1));

    // Backward paths (no reverse edges)
    assert_eq!(dist[1][0], None);
    assert_eq!(dist[2][0], None);
    assert_eq!(dist[2][1], None);
}

#[test]
fn test_apsp_triangle() {
    // Triangle graph
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 0)], false);
    let dist = g.all_pairs_shortest_paths();

    // All pairs should have distance 1 (triangle) except diagonal
    for (i, row) in dist.iter().enumerate().take(3) {
        for (j, &cell) in row.iter().enumerate().take(3) {
            if i == j {
                assert_eq!(cell, Some(0));
            } else {
                assert_eq!(cell, Some(1));
            }
        }
    }
}

#[test]
fn test_apsp_star_graph() {
    // Star graph: 0 connected to 1, 2, 3
    let g = Graph::from_edges(&[(0, 1), (0, 2), (0, 3)], false);
    let dist = g.all_pairs_shortest_paths();

    // Center to leaves: distance 1
    assert_eq!(dist[0][1], Some(1));
    assert_eq!(dist[0][2], Some(1));
    assert_eq!(dist[0][3], Some(1));

    // Leaf to leaf through center: distance 2
    assert_eq!(dist[1][2], Some(2));
    assert_eq!(dist[1][3], Some(2));
    assert_eq!(dist[2][3], Some(2));
}

#[test]
fn test_apsp_empty_graph() {
    let g = Graph::new(false);
    let dist = g.all_pairs_shortest_paths();
    assert_eq!(dist.len(), 0);
}

#[test]
fn test_apsp_single_node() {
    let g = Graph::from_edges(&[(0, 0)], false);
    let dist = g.all_pairs_shortest_paths();

    assert_eq!(dist.len(), 1);
    assert_eq!(dist[0][0], Some(0));
}

#[test]
fn test_apsp_cycle() {
    // Cycle: 0 -> 1 -> 2 -> 3 -> 0
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 3), (3, 0)], true);
    let dist = g.all_pairs_shortest_paths();

    // Along cycle direction
    assert_eq!(dist[0][1], Some(1));
    assert_eq!(dist[0][2], Some(2));
    assert_eq!(dist[0][3], Some(3));
    assert_eq!(dist[1][3], Some(2));

    // All nodes reachable in directed cycle
    for row in dist.iter().take(4) {
        for &cell in row.iter().take(4) {
            assert!(cell.is_some());
        }
    }
}

#[test]
fn test_apsp_matrix_size() {
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 3)], false);
    let dist = g.all_pairs_shortest_paths();

    // Matrix should be n×n
    assert_eq!(dist.len(), 4);
    for row in &dist {
        assert_eq!(row.len(), 4);
    }
}

// ========================================================================
// A* Search Algorithm Tests
// ========================================================================

#[test]
fn test_astar_linear_chain() {
    // Linear chain: 0 -- 1 -- 2 -- 3
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 3)], false);

    // Simple distance heuristic
    let heuristic = |node: usize| (3 - node) as f64;

    let path = g.a_star(0, 3, heuristic).expect("path should exist");
    assert_eq!(path, vec![0, 1, 2, 3]);
}

#[test]
fn test_astar_same_node() {
    let g = Graph::from_edges(&[(0, 1)], false);
    let heuristic = |_: usize| 0.0;

    let path = g.a_star(0, 0, heuristic).expect("path should exist");
    assert_eq!(path, vec![0]);
}

#[test]
fn test_astar_disconnected() {
    // Two disconnected components
    let g = Graph::from_edges(&[(0, 1), (2, 3)], false);
    let heuristic = |_: usize| 0.0;

    assert!(g.a_star(0, 3, heuristic).is_none());
}

#[test]
fn test_astar_zero_heuristic() {
    // With h(n) = 0, A* behaves like Dijkstra
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 3)], false);
    let heuristic = |_: usize| 0.0;

    let path = g.a_star(0, 3, heuristic).expect("path should exist");
    assert_eq!(path, vec![0, 1, 2, 3]);
}

#[test]
fn test_astar_admissible_heuristic() {
    // Graph with shortcut
    // 0 -- 1 -- 2
    // |         |
    // +----3----+
    let g =
        Graph::from_weighted_edges(&[(0, 1, 1.0), (1, 2, 1.0), (0, 3, 0.5), (3, 2, 0.5)], false);

    // Admissible heuristic (straight-line distance estimate)
    let heuristic = |node: usize| match node {
        0 | 1 => 1.0, // Estimate to reach 2
        3 => 0.5,
        _ => 0.0, // At target (2) or other
    };

    let path = g.a_star(0, 2, heuristic).expect("path should exist");
    // Should find shortest path via 3
    assert!(path.contains(&3)); // Must use the shortcut
}

#[test]
fn test_astar_directed() {
    // Directed graph: 0 -> 1 -> 2
    let g = Graph::from_edges(&[(0, 1), (1, 2)], true);
    let heuristic = |node: usize| (2 - node) as f64;

    let path = g
        .a_star(0, 2, heuristic)
        .expect("forward path should exist");
    assert_eq!(path, vec![0, 1, 2]);

    // Backward path doesn't exist
    assert!(g.a_star(2, 0, |_| 0.0).is_none());
}

#[test]
fn test_astar_triangle() {
    // Triangle graph
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 0)], false);
    let heuristic = |_: usize| 0.0;

    let path = g.a_star(0, 2, heuristic).expect("path should exist");
    assert_eq!(path.len(), 2); // Direct edge 0-2
    assert_eq!(path[0], 0);
    assert_eq!(path[1], 2);
}

#[test]
fn test_astar_weighted_graph() {
    // Weighted graph with better heuristic guidance
    let g = Graph::from_weighted_edges(&[(0, 1, 1.0), (1, 2, 2.0), (0, 2, 5.0)], false);

    // Heuristic guides toward node 2
    let heuristic = |node: usize| match node {
        0 => 3.0,
        1 => 2.0,
        _ => 0.0, // At target (2) or other
    };

    let path = g.a_star(0, 2, heuristic).expect("path should exist");
    // Should find path 0->1->2 (cost 3) instead of 0->2 (cost 5)
    assert_eq!(path, vec![0, 1, 2]);
}

#[test]
fn test_astar_complete_graph() {
    // Complete graph K4
    let g = Graph::from_edges(&[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)], false);
    let heuristic = |_: usize| 0.0;

    // All nodes directly connected
    let path = g.a_star(0, 3, heuristic).expect("path should exist");
    assert_eq!(path.len(), 2); // Direct path
    assert_eq!(path[0], 0);
    assert_eq!(path[1], 3);
}

#[test]
fn test_astar_invalid_nodes() {
    let g = Graph::from_edges(&[(0, 1)], false);
    let heuristic = |_: usize| 0.0;

    assert!(g.a_star(0, 10, heuristic).is_none());
    assert!(g.a_star(10, 0, heuristic).is_none());
}

#[test]
fn test_astar_vs_shortest_path() {
    // On unweighted graph with zero heuristic, A* should match shortest_path
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 3)], false);

    let sp_path = g
        .shortest_path(0, 3)
        .expect("shortest_path should find path");
    let astar_path = g.a_star(0, 3, |_| 0.0).expect("astar should find path");

    assert_eq!(sp_path.len(), astar_path.len());
    assert_eq!(sp_path, astar_path);
}

#[test]
fn test_astar_star_graph() {
    // Star graph: 0 connected to 1, 2, 3
    let g = Graph::from_edges(&[(0, 1), (0, 2), (0, 3)], false);

    // Heuristic that guides toward target 3
    let heuristic = |node: usize| if node == 3 { 0.0 } else { 1.0 };

    let path = g.a_star(1, 3, heuristic).expect("path should exist");
    assert_eq!(path.len(), 3); // Must go through center
    assert_eq!(path[0], 1);
    assert_eq!(path[1], 0);
    assert_eq!(path[2], 3);
}

#[test]
fn test_astar_perfect_heuristic() {
    // Perfect heuristic (exact distance to target)
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 3)], false);

    // Perfect heuristic = exact remaining distance
    let heuristic = |node: usize| (3 - node) as f64;

    let path = g.a_star(0, 3, heuristic).expect("path should exist");
    assert_eq!(path, vec![0, 1, 2, 3]);
}

#[test]
fn test_astar_complex_graph() {
    // More complex graph to test heuristic efficiency
    //     1
    //    / \
    //   0   3 - 4
    //    \ /
    //     2
    let g = Graph::from_weighted_edges(
        &[
            (0, 1, 1.0),
            (0, 2, 1.0),
            (1, 3, 1.0),
            (2, 3, 1.0),
            (3, 4, 1.0),
        ],
        false,
    );

    // Distance-based heuristic
    let heuristic = |node: usize| (4 - node) as f64;

    let path = g.a_star(0, 4, heuristic).expect("path should exist");
    assert_eq!(path.len(), 4); // 0->1->3->4 or 0->2->3->4
    assert_eq!(path[0], 0);
    assert_eq!(path[3], 4);
}

// DFS Tests

#[test]
fn test_dfs_linear_chain() {
    // Linear chain: 0 -- 1 -- 2 -- 3
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 3)], false);
    let visited = g.dfs(0).expect("valid source");

    assert_eq!(visited.len(), 4);
    assert_eq!(visited[0], 0); // Starts at source
    assert!(visited.contains(&1));
    assert!(visited.contains(&2));
    assert!(visited.contains(&3));
}

#[test]
fn test_dfs_tree() {
    // Tree: 0 connected to 1, 2, 3
    let g = Graph::from_edges(&[(0, 1), (0, 2), (0, 3)], false);
    let visited = g.dfs(0).expect("valid source");

    assert_eq!(visited.len(), 4);
    assert_eq!(visited[0], 0); // Root first
                               // Children visited in some order
    assert!(visited.contains(&1));
    assert!(visited.contains(&2));
    assert!(visited.contains(&3));
}

#[test]
fn test_dfs_cycle() {
    // Cycle: 0 -- 1 -- 2 -- 0
    let g = Graph::from_edges(&[(0, 1), (1, 2), (2, 0)], false);
    let visited = g.dfs(0).expect("valid source");

    assert_eq!(visited.len(), 3);
    assert_eq!(visited[0], 0);
    assert!(visited.contains(&1));
    assert!(visited.contains(&2));
}

#[test]
fn test_dfs_disconnected() {
    // Two components: (0, 1) and (2, 3)
    let g = Graph::from_edges(&[(0, 1), (2, 3)], false);

    // DFS from 0 only visits component containing 0
    let visited = g.dfs(0).expect("valid source");
    assert_eq!(visited.len(), 2);
    assert!(visited.contains(&0));
    assert!(visited.contains(&1));
    assert!(!visited.contains(&2));
    assert!(!visited.contains(&3));

    // DFS from 2 only visits component containing 2
    let visited2 = g.dfs(2).expect("valid source");
    assert_eq!(visited2.len(), 2);
    assert!(visited2.contains(&2));
    assert!(visited2.contains(&3));
}

#[test]
fn test_dfs_directed() {
    // Directed: 0 -> 1 -> 2
    let g = Graph::from_edges(&[(0, 1), (1, 2)], true);

    // Forward traversal
    let visited = g.dfs(0).expect("valid source");
    assert_eq!(visited.len(), 3);
    assert_eq!(visited[0], 0);

    // Backward traversal (node 2 has no outgoing edges)
    let visited2 = g.dfs(2).expect("valid source");
    assert_eq!(visited2.len(), 1);
    assert_eq!(visited2[0], 2);
}

include!("advanced_dfs.rs");
include!("advanced_topological.rs");