oxirs 0.2.4

Command-line interface for OxiRS - import, export, migration, and benchmarking tools
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
//! Advanced graph algorithms (coloring, matching, network flow)
//!
//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)

use anyhow::Result;
use colored::Colorize;
use std::collections::{HashMap, HashSet, VecDeque};

use super::types::{AnalyticsConfig, RdfGraph};

/// Execute graph coloring analysis
pub fn execute_graph_coloring(rdf_graph: &RdfGraph, config: &AnalyticsConfig) -> Result<()> {
    println!();
    println!("{}", "Graph Coloring Analysis".cyan().bold());
    println!("{}", "─".repeat(80).cyan());
    println!(
        "{}",
        "Finding chromatic number using greedy coloring algorithm".dimmed()
    );
    println!();

    let node_count = rdf_graph.node_count();
    if node_count == 0 {
        println!("{}", "Empty graph - no coloring needed".yellow());
        return Ok(());
    }

    if config.enable_simd && node_count > 10_000 {
        println!(
            "{}",
            "ℹ SIMD acceleration: Enabled for adjacency checks (>10K nodes)"
                .cyan()
                .dimmed()
        );
    }

    if config.enable_parallel && node_count > 50_000 {
        println!(
            "{}",
            "ℹ Parallel processing: Enabled for coloring phases (>50K nodes)"
                .cyan()
                .dimmed()
        );
    }

    let mut colors: HashMap<usize, usize> = HashMap::new();
    let mut max_color = 0;

    let mut nodes_by_degree: Vec<(usize, usize)> = (0..node_count)
        .map(|node| (node, rdf_graph.out_degree(node) + rdf_graph.in_degree(node)))
        .collect();

    nodes_by_degree.sort_by_key(|item| std::cmp::Reverse(item.1));

    for (node, _degree) in &nodes_by_degree {
        let neighbors = rdf_graph.neighbors(*node);
        let mut used_colors = HashSet::new();

        for &neighbor in neighbors {
            if let Some(&color) = colors.get(&neighbor) {
                used_colors.insert(color);
            }
        }

        let mut assigned_color = 0;
        while used_colors.contains(&assigned_color) {
            assigned_color += 1;
        }

        colors.insert(*node, assigned_color);
        max_color = max_color.max(assigned_color);
    }

    let chromatic_number = max_color + 1;
    let mut color_counts: HashMap<usize, usize> = HashMap::new();

    for &color in colors.values() {
        *color_counts.entry(color).or_insert(0) += 1;
    }

    println!(
        "{}: {}",
        "Chromatic Number (Upper Bound)".green(),
        chromatic_number.to_string().yellow().bold()
    );
    println!(
        "{}: {} nodes colored",
        "Coverage".green(),
        colors.len().to_string().yellow()
    );
    println!();

    println!("{}", "Color Distribution:".green().bold());
    println!("{}", "─".repeat(80).cyan());

    let mut color_vec: Vec<(usize, usize)> = color_counts.iter().map(|(&c, &n)| (c, n)).collect();
    color_vec.sort_by_key(|&(c, _)| c);

    for (color, count) in color_vec.iter().take(config.top_k) {
        let bar = "â–ˆ".repeat((count * 50 / node_count.max(1)).max(1));
        println!(
            "  Color {}: {} nodes {}",
            color.to_string().cyan(),
            count.to_string().yellow(),
            bar.blue()
        );
    }

    if color_vec.len() > config.top_k {
        println!(
            "  {} more colors...",
            (color_vec.len() - config.top_k).to_string().dimmed()
        );
    }

    println!();
    println!(
        "{}",
        "Greedy coloring provides an upper bound on the chromatic number.".dimmed()
    );
    println!(
        "{}",
        "Lower chromatic numbers indicate more efficient graph coloring.".dimmed()
    );

    Ok(())
}

/// Execute maximum matching analysis
pub fn execute_maximum_matching(rdf_graph: &RdfGraph, config: &AnalyticsConfig) -> Result<()> {
    println!();
    println!("{}", "Maximum Matching Analysis".cyan().bold());
    println!("{}", "─".repeat(80).cyan());
    println!(
        "{}",
        "Finding maximum matching using greedy augmenting paths".dimmed()
    );
    println!();

    let node_count = rdf_graph.node_count();
    if node_count == 0 {
        println!("{}", "Empty graph - no matching possible".yellow());
        return Ok(());
    }

    if config.enable_gpu && node_count > 1_000_000 {
        println!(
            "{}",
            "ℹ GPU acceleration: Recommended for matching on very large graphs"
                .cyan()
                .dimmed()
        );
        println!(
            "{}",
            "  Use scirs2_core::gpu::GpuContext for 10-100x speedup on suitable workloads"
                .cyan()
                .dimmed()
        );
    }

    let mut node_colors: HashMap<usize, bool> = HashMap::new();
    let mut is_bipartite = true;
    let mut queue = VecDeque::new();

    for start_node in 0..node_count {
        if node_colors.contains_key(&start_node) {
            continue;
        }

        queue.push_back(start_node);
        node_colors.insert(start_node, false);

        while let Some(node) = queue.pop_front() {
            let current_color = node_colors[&node];
            for &neighbor in rdf_graph.neighbors(node) {
                if let Some(&neighbor_color) = node_colors.get(&neighbor) {
                    if neighbor_color == current_color {
                        is_bipartite = false;
                        break;
                    }
                } else {
                    node_colors.insert(neighbor, !current_color);
                    queue.push_back(neighbor);
                }
            }

            if !is_bipartite {
                break;
            }
        }

        if !is_bipartite {
            break;
        }
    }

    if is_bipartite {
        println!(
            "{}",
            "✓ Graph is bipartite - optimal matching possible".green()
        );
    } else {
        println!(
            "{}",
            "âš  Graph is not bipartite - using general matching algorithm".yellow()
        );
    }

    println!();

    let mut matching: HashMap<usize, usize> = HashMap::new();
    let mut matched_nodes: HashSet<usize> = HashSet::new();

    for node in 0..node_count {
        if matched_nodes.contains(&node) {
            continue;
        }

        for &neighbor in rdf_graph.neighbors(node) {
            if !matched_nodes.contains(&neighbor) {
                matching.insert(node, neighbor);
                matched_nodes.insert(node);
                matched_nodes.insert(neighbor);
                break;
            }
        }
    }

    let matching_size = matching.len();
    let coverage = (matched_nodes.len() as f64 / node_count as f64) * 100.0;

    println!(
        "{}: {} edges",
        "Maximum Matching Size".green(),
        matching_size.to_string().yellow().bold()
    );
    println!(
        "{}: {}/{} nodes ({:.1}%)",
        "Coverage".green(),
        matched_nodes.len().to_string().yellow(),
        node_count,
        coverage
    );
    println!();

    if matching_size > 0 {
        println!("{}", "Sample Matched Pairs:".green().bold());
        println!("{}", "─".repeat(80).cyan());

        for (i, (&src, &dst)) in matching.iter().take(config.top_k).enumerate() {
            let src_name = rdf_graph.get_node_name(src).unwrap_or("Unknown");
            let dst_name = rdf_graph.get_node_name(dst).unwrap_or("Unknown");

            let src_truncated = if src_name.len() > 35 {
                format!("{}...", &src_name[..32])
            } else {
                src_name.to_string()
            };

            let dst_truncated = if dst_name.len() > 35 {
                format!("{}...", &dst_name[..32])
            } else {
                dst_name.to_string()
            };

            println!(
                "  {} {} ↔ {}",
                (i + 1).to_string().cyan(),
                src_truncated,
                dst_truncated
            );
        }

        if matching_size > config.top_k {
            println!(
                "  {} more matches...",
                (matching_size - config.top_k).to_string().dimmed()
            );
        }
    }

    println!();
    println!(
        "{}",
        "Maximum matching identifies the largest set of non-overlapping edges.".dimmed()
    );

    if is_bipartite {
        println!(
            "{}",
            "For bipartite graphs, this can be optimized using Hungarian algorithm.".dimmed()
        );
    }

    Ok(())
}

/// Execute network flow analysis
pub fn execute_network_flow(rdf_graph: &RdfGraph, config: &AnalyticsConfig) -> Result<()> {
    println!();
    println!("{}", "Network Flow Analysis".cyan().bold());
    println!("{}", "─".repeat(80).cyan());
    println!(
        "{}",
        "Computing maximum flow using Ford-Fulkerson algorithm".dimmed()
    );
    println!();

    let node_count = rdf_graph.node_count();
    if node_count < 2 {
        println!("{}", "Need at least 2 nodes for flow analysis".yellow());
        return Ok(());
    }

    if config.enable_parallel && node_count > 100_000 {
        println!(
            "{}",
            "ℹ Parallel processing: Enabled for concurrent flow path search"
                .cyan()
                .dimmed()
        );
        println!(
            "{}",
            "  Use scirs2_core::parallel_ops::par_chunks for multi-core BFS"
                .cyan()
                .dimmed()
        );
    }

    let degrees: Vec<(usize, usize)> = (0..node_count)
        .map(|n| (n, rdf_graph.out_degree(n)))
        .collect();

    let source = degrees
        .iter()
        .max_by_key(|(_, d)| d)
        .map(|(n, _)| *n)
        .unwrap_or(0);

    let sink = degrees
        .iter()
        .filter(|(n, _)| *n != source)
        .min_by_key(|(_, d)| d)
        .map(|(n, _)| *n)
        .unwrap_or(node_count - 1);

    if source == sink {
        println!("{}", "Cannot compute flow: source equals sink".yellow());
        return Ok(());
    }

    println!(
        "Source node: {}",
        rdf_graph
            .get_node_name(source)
            .unwrap_or("Unknown")
            .yellow()
    );
    println!(
        "Sink node: {}",
        rdf_graph.get_node_name(sink).unwrap_or("Unknown").yellow()
    );
    println!();

    let mut capacity: HashMap<(usize, usize), i32> = HashMap::new();
    for node in 0..node_count {
        for &neighbor in rdf_graph.neighbors(node) {
            capacity.insert((node, neighbor), 1);
        }
    }

    let mut flow: HashMap<(usize, usize), i32> = HashMap::new();
    let mut max_flow = 0;
    let mut iteration = 0;
    let max_iterations = config.max_iterations;

    while iteration < max_iterations {
        let mut parent: HashMap<usize, usize> = HashMap::new();
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();

        queue.push_back(source);
        visited.insert(source);
        let mut found_path = false;

        while let Some(node) = queue.pop_front() {
            if node == sink {
                found_path = true;
                break;
            }

            for &neighbor in rdf_graph.neighbors(node) {
                let cap = capacity.get(&(node, neighbor)).copied().unwrap_or(0);
                let curr_flow = flow.get(&(node, neighbor)).copied().unwrap_or(0);
                let residual = cap - curr_flow;

                if residual > 0 && !visited.contains(&neighbor) {
                    parent.insert(neighbor, node);
                    visited.insert(neighbor);
                    queue.push_back(neighbor);
                }
            }
        }

        if !found_path {
            break;
        }

        let mut path_flow = i32::MAX;
        let mut current = sink;

        while current != source {
            if let Some(&prev) = parent.get(&current) {
                let cap = capacity.get(&(prev, current)).copied().unwrap_or(0);
                let curr_flow = flow.get(&(prev, current)).copied().unwrap_or(0);
                path_flow = path_flow.min(cap - curr_flow);
                current = prev;
            } else {
                break;
            }
        }

        current = sink;
        while current != source {
            if let Some(&prev) = parent.get(&current) {
                *flow.entry((prev, current)).or_insert(0) += path_flow;
                *flow.entry((current, prev)).or_insert(0) -= path_flow;
                current = prev;
            } else {
                break;
            }
        }

        max_flow += path_flow;
        iteration += 1;
    }

    let mut visited = HashSet::new();
    let mut queue = VecDeque::new();

    queue.push_back(source);
    visited.insert(source);

    while let Some(node) = queue.pop_front() {
        for &neighbor in rdf_graph.neighbors(node) {
            let cap = capacity.get(&(node, neighbor)).copied().unwrap_or(0);
            let curr_flow = flow.get(&(node, neighbor)).copied().unwrap_or(0);
            let residual = cap - curr_flow;

            if residual > 0 && !visited.contains(&neighbor) {
                visited.insert(neighbor);
                queue.push_back(neighbor);
            }
        }
    }

    let min_cut_size = visited.len();

    println!(
        "{}: {}",
        "Maximum Flow".green(),
        max_flow.to_string().yellow().bold()
    );
    println!(
        "{}: {} iterations",
        "Convergence".green(),
        iteration.to_string().yellow()
    );
    println!(
        "{}: {} nodes (source side)",
        "Min-Cut Size".green(),
        min_cut_size.to_string().yellow()
    );
    println!();

    let non_zero_flows: Vec<((usize, usize), i32)> = flow
        .iter()
        .filter(|(_, &f)| f > 0)
        .map(|((s, d), &f)| ((*s, *d), f))
        .collect();

    if !non_zero_flows.is_empty() {
        println!("{}", "Flow Edges (Sample):".green().bold());
        println!("{}", "─".repeat(80).cyan());

        for (i, ((src, dst), flow_val)) in non_zero_flows.iter().take(config.top_k).enumerate() {
            let src_name = rdf_graph.get_node_name(*src).unwrap_or("Unknown");
            let dst_name = rdf_graph.get_node_name(*dst).unwrap_or("Unknown");

            let src_truncated = if src_name.len() > 32 {
                format!("{}...", &src_name[..29])
            } else {
                src_name.to_string()
            };

            let dst_truncated = if dst_name.len() > 32 {
                format!("{}...", &dst_name[..29])
            } else {
                dst_name.to_string()
            };

            println!(
                "  {} {} → {} (flow: {})",
                (i + 1).to_string().cyan(),
                src_truncated,
                dst_truncated,
                flow_val.to_string().yellow()
            );
        }

        if non_zero_flows.len() > config.top_k {
            println!(
                "  {} more flow edges...",
                (non_zero_flows.len() - config.top_k).to_string().dimmed()
            );
        }
    }

    println!();
    println!(
        "{}",
        "Max flow = min cut (Ford-Fulkerson theorem).".dimmed()
    );
    println!(
        "{}",
        "Identifies bottlenecks and critical edges in the network.".dimmed()
    );

    Ok(())
}