Merge commit 'd803bfe2b1fe7f5e219e50ac20d6801a0a58ac75' as 'vendor/ruvector'
This commit is contained in:
649
vendor/ruvector/crates/ruvector-mincut/docs/guide/01-getting-started.md
vendored
Normal file
649
vendor/ruvector/crates/ruvector-mincut/docs/guide/01-getting-started.md
vendored
Normal file
@@ -0,0 +1,649 @@
|
||||
# Getting Started with RuVector MinCut
|
||||
|
||||
Welcome to RuVector MinCut! This guide will help you understand minimum cuts and start using the library in your Rust projects.
|
||||
|
||||
---
|
||||
|
||||
## 1. What is Minimum Cut?
|
||||
|
||||
### The Simple Explanation
|
||||
|
||||
Imagine you have a network of roads connecting different cities. The **minimum cut** answers this question:
|
||||
|
||||
> **"What's the smallest number of roads I need to close to completely separate the network into two parts?"**
|
||||
|
||||
Think of it like finding the **weakest links in a chain** — the places where your network is most vulnerable to breaking apart.
|
||||
|
||||
### Real-World Analogies
|
||||
|
||||
| Scenario | What You Have | What Min-Cut Finds |
|
||||
|----------|---------------|-------------------|
|
||||
| **Road Network** | Cities connected by roads | Fewest roads to block to isolate a city |
|
||||
| **Social Network** | People connected by friendships | Weakest link between two communities |
|
||||
| **Computer Network** | Servers connected by cables | Most vulnerable connections if attacked |
|
||||
| **Water Pipes** | Houses connected by pipes | Minimum pipes to shut off to stop water flow |
|
||||
| **Supply Chain** | Factories connected by routes | Critical dependencies that could break the chain |
|
||||
|
||||
### Visual Example
|
||||
|
||||
Here's what a minimum cut looks like in a simple graph:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "Original Graph"
|
||||
A((A)) ---|1| B((B))
|
||||
B ---|1| C((C))
|
||||
C ---|1| D((D))
|
||||
A ---|1| D((D))
|
||||
B ---|1| D((D))
|
||||
end
|
||||
|
||||
subgraph "After Minimum Cut (value = 2)"
|
||||
A1((A)) -.x.- B1((B))
|
||||
B1((B)) ---|1| C1((C))
|
||||
C1((C)) ---|1| D1((D))
|
||||
A1((A)) -.x.- D1((D))
|
||||
B1 ---|1| D1
|
||||
end
|
||||
|
||||
style A1 fill:#ffcccc
|
||||
style A fill:#ffcccc
|
||||
style B fill:#ccccff
|
||||
style C fill:#ccccff
|
||||
style D fill:#ccccff
|
||||
style B1 fill:#ccccff
|
||||
style C1 fill:#ccccff
|
||||
style D1 fill:#ccccff
|
||||
```
|
||||
|
||||
**Legend:**
|
||||
- **Solid lines** (—): Edges that remain
|
||||
- **Crossed lines** (-.x.-): Edges in the minimum cut (removed)
|
||||
- **Red nodes**: One side of the partition (set S)
|
||||
- **Blue nodes**: Other side of the partition (set T)
|
||||
|
||||
The minimum cut value is **2** because we need to remove 2 edges to disconnect node A from the rest.
|
||||
|
||||
### Key Terminology for Beginners
|
||||
|
||||
| Term | Simple Explanation | Example |
|
||||
|------|-------------------|---------|
|
||||
| **Vertex** (or Node) | A point in the network | A city, a person, a server |
|
||||
| **Edge** | A connection between two vertices | A road, a friendship, a cable |
|
||||
| **Weight** | The "strength" or "capacity" of an edge | Road width, friendship closeness |
|
||||
| **Cut** | A set of edges that, when removed, splits the graph | Roads to close to isolate a city |
|
||||
| **Partition** | The two groups created after a cut | Cities on each side of the divide |
|
||||
| **Cut Value** | Sum of weights of edges in the cut | Total capacity of removed edges |
|
||||
|
||||
### Why Is This Useful?
|
||||
|
||||
- **Find Vulnerabilities**: Identify critical infrastructure that could fail
|
||||
- **Optimize Networks**: Understand where to strengthen connections
|
||||
- **Detect Communities**: Find natural groupings in social networks
|
||||
- **Image Segmentation**: Separate objects from backgrounds in photos
|
||||
- **Load Balancing**: Divide work efficiently across systems
|
||||
|
||||
---
|
||||
|
||||
## 2. Installation
|
||||
|
||||
### Adding to Your Project
|
||||
|
||||
The easiest way to add RuVector MinCut to your project:
|
||||
|
||||
```bash
|
||||
cargo add ruvector-mincut
|
||||
```
|
||||
|
||||
Or manually add to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ruvector-mincut = "0.2"
|
||||
```
|
||||
|
||||
### Understanding Feature Flags
|
||||
|
||||
RuVector MinCut has several optional features you can enable based on your needs:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ruvector-mincut = { version = "0.2", features = ["monitoring", "simd"] }
|
||||
```
|
||||
|
||||
#### Available Features
|
||||
|
||||
| Feature | Default | What It Does | When to Use |
|
||||
|---------|---------|--------------|-------------|
|
||||
| **`exact`** | ✅ Yes | Exact minimum cut algorithm | When you need guaranteed correct results |
|
||||
| **`approximate`** | ✅ Yes | Fast (1+ε)-approximate algorithm | When speed matters more than perfect accuracy |
|
||||
| **`monitoring`** | ❌ No | Real-time event notifications | When you need alerts for cut changes |
|
||||
| **`integration`** | ❌ No | GraphDB integration with ruvector-graph | When working with vector databases |
|
||||
| **`simd`** | ❌ No | SIMD vector optimizations | For faster processing on modern CPUs |
|
||||
| **`wasm`** | ❌ No | WebAssembly compatibility | For browser or edge deployment |
|
||||
| **`agentic`** | ❌ No | 256-core parallel execution | For agentic chip deployment |
|
||||
|
||||
#### Common Configurations
|
||||
|
||||
```toml
|
||||
# Default: exact + approximate algorithms
|
||||
[dependencies]
|
||||
ruvector-mincut = "0.2"
|
||||
|
||||
# With real-time monitoring
|
||||
[dependencies]
|
||||
ruvector-mincut = { version = "0.2", features = ["monitoring"] }
|
||||
|
||||
# Maximum performance
|
||||
[dependencies]
|
||||
ruvector-mincut = { version = "0.2", features = ["simd"] }
|
||||
|
||||
# Everything enabled
|
||||
[dependencies]
|
||||
ruvector-mincut = { version = "0.2", features = ["full"] }
|
||||
```
|
||||
|
||||
### Quick Feature Decision Guide
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start[Which features do I need?] --> NeedAlerts{Need real-time<br/>alerts?}
|
||||
NeedAlerts -->|Yes| AddMonitoring[Add 'monitoring']
|
||||
NeedAlerts -->|No| CheckSpeed{Need maximum<br/>speed?}
|
||||
|
||||
AddMonitoring --> CheckSpeed
|
||||
|
||||
CheckSpeed -->|Yes| AddSIMD[Add 'simd']
|
||||
CheckSpeed -->|No| CheckWasm{Deploying to<br/>browser/edge?}
|
||||
|
||||
AddSIMD --> CheckWasm
|
||||
|
||||
CheckWasm -->|Yes| AddWasm[Add 'wasm']
|
||||
CheckWasm -->|No| Done[Use default features]
|
||||
|
||||
AddWasm --> Done
|
||||
|
||||
style Start fill:#e1f5ff
|
||||
style Done fill:#c8e6c9
|
||||
style AddMonitoring fill:#fff9c4
|
||||
style AddSIMD fill:#fff9c4
|
||||
style AddWasm fill:#fff9c4
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Your First Min-Cut
|
||||
|
||||
Let's create a simple program that finds the minimum cut in a triangle graph.
|
||||
|
||||
### Complete Working Example
|
||||
|
||||
Create a new file `examples/my_first_mincut.rs`:
|
||||
|
||||
```rust
|
||||
use ruvector_mincut::{MinCutBuilder, DynamicMinCut};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("🔷 Finding Minimum Cut in a Triangle\n");
|
||||
|
||||
// Step 1: Create a triangle graph
|
||||
// 1 ------- 2
|
||||
// \ /
|
||||
// \ /
|
||||
// \ /
|
||||
// 3
|
||||
//
|
||||
// Each edge has weight 1.0
|
||||
let mut mincut = MinCutBuilder::new()
|
||||
.exact() // Use exact algorithm for guaranteed correct results
|
||||
.with_edges(vec![
|
||||
(1, 2, 1.0), // Edge from vertex 1 to vertex 2, weight 1.0
|
||||
(2, 3, 1.0), // Edge from vertex 2 to vertex 3, weight 1.0
|
||||
(3, 1, 1.0), // Edge from vertex 3 to vertex 1, weight 1.0
|
||||
])
|
||||
.build()?;
|
||||
|
||||
// Step 2: Query the minimum cut value
|
||||
let cut_value = mincut.min_cut_value();
|
||||
println!("Minimum cut value: {}", cut_value);
|
||||
println!("→ We need to remove {} edge(s) to disconnect the graph\n", cut_value);
|
||||
|
||||
// Step 3: Get the partition (which vertices are on each side?)
|
||||
let (side_s, side_t) = mincut.partition();
|
||||
println!("Partition:");
|
||||
println!(" Side S (red): {:?}", side_s);
|
||||
println!(" Side T (blue): {:?}", side_t);
|
||||
println!("→ These two groups are separated by the cut\n");
|
||||
|
||||
// Step 4: Get the actual edges in the cut
|
||||
let cut_edges = mincut.cut_edges();
|
||||
println!("Edges in the minimum cut:");
|
||||
for (u, v, weight) in &cut_edges {
|
||||
println!(" {} ←→ {} (weight: {})", u, v, weight);
|
||||
}
|
||||
println!("→ These edges must be removed to separate the graph\n");
|
||||
|
||||
// Step 5: Make the graph dynamic - add a new edge
|
||||
println!("📍 Adding edge 3 → 4 (weight 2.0)...");
|
||||
let new_cut = mincut.insert_edge(3, 4, 2.0)?;
|
||||
println!("New minimum cut value: {}", new_cut);
|
||||
println!("→ Adding a leaf node increased connectivity\n");
|
||||
|
||||
// Step 6: Delete an edge
|
||||
println!("📍 Deleting edge 2 → 3...");
|
||||
let final_cut = mincut.delete_edge(2, 3)?;
|
||||
println!("Final minimum cut value: {}", final_cut);
|
||||
println!("→ The graph is now a chain: 1-2, 3-4, 1-3\n");
|
||||
|
||||
println!("✅ Success! You've computed your first dynamic minimum cut.");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
### Running the Example
|
||||
|
||||
```bash
|
||||
cargo run --example my_first_mincut
|
||||
```
|
||||
|
||||
**Expected Output:**
|
||||
|
||||
```
|
||||
🔷 Finding Minimum Cut in a Triangle
|
||||
|
||||
Minimum cut value: 2.0
|
||||
→ We need to remove 2 edge(s) to disconnect the graph
|
||||
|
||||
Partition:
|
||||
Side S (red): [1]
|
||||
Side T (blue): [2, 3]
|
||||
→ These two groups are separated by the cut
|
||||
|
||||
Edges in the minimum cut:
|
||||
1 ←→ 2 (weight: 1.0)
|
||||
1 ←→ 3 (weight: 1.0)
|
||||
→ These edges must be removed to separate the graph
|
||||
|
||||
📍 Adding edge 3 → 4 (weight 2.0)...
|
||||
New minimum cut value: 2.0
|
||||
→ Adding a leaf node increased connectivity
|
||||
|
||||
📍 Deleting edge 2 → 3...
|
||||
Final minimum cut value: 1.0
|
||||
→ The graph is now a chain: 1-2, 3-4, 1-3
|
||||
|
||||
✅ Success! You've computed your first dynamic minimum cut.
|
||||
```
|
||||
|
||||
### Breaking Down the Code
|
||||
|
||||
Let's understand each part:
|
||||
|
||||
#### 1. Building the Graph
|
||||
|
||||
```rust
|
||||
let mut mincut = MinCutBuilder::new()
|
||||
.exact()
|
||||
.with_edges(vec![
|
||||
(1, 2, 1.0),
|
||||
(2, 3, 1.0),
|
||||
(3, 1, 1.0),
|
||||
])
|
||||
.build()?;
|
||||
```
|
||||
|
||||
- **`MinCutBuilder::new()`**: Creates a new builder
|
||||
- **`.exact()`**: Use exact algorithm (guaranteed correct)
|
||||
- **`.with_edges(vec![...])`**: Add edges as `(source, target, weight)` tuples
|
||||
- **`.build()?`**: Construct the data structure
|
||||
|
||||
#### 2. Querying the Cut
|
||||
|
||||
```rust
|
||||
let cut_value = mincut.min_cut_value();
|
||||
```
|
||||
|
||||
This is **O(1)** — instant! The value is already computed.
|
||||
|
||||
#### 3. Getting the Partition
|
||||
|
||||
```rust
|
||||
let (side_s, side_t) = mincut.partition();
|
||||
```
|
||||
|
||||
Returns two vectors of vertex IDs showing which vertices are on each side of the cut.
|
||||
|
||||
#### 4. Dynamic Updates
|
||||
|
||||
```rust
|
||||
mincut.insert_edge(3, 4, 2.0)?; // Add edge
|
||||
mincut.delete_edge(2, 3)?; // Remove edge
|
||||
```
|
||||
|
||||
These operations update the minimum cut in **O(n^{o(1)})** amortized time — much faster than recomputing from scratch!
|
||||
|
||||
---
|
||||
|
||||
## 4. Understanding the Output
|
||||
|
||||
### What Do the Numbers Mean?
|
||||
|
||||
#### Minimum Cut Value
|
||||
|
||||
```rust
|
||||
let cut_value = mincut.min_cut_value(); // Example: 2.0
|
||||
```
|
||||
|
||||
**Interpretation:**
|
||||
- This is the **sum of weights** of edges you need to remove
|
||||
- For unweighted graphs (all edges weight 1.0), it's the **count of edges**
|
||||
- **Lower values** = weaker connectivity, easier to disconnect
|
||||
- **Higher values** = stronger connectivity, harder to disconnect
|
||||
|
||||
#### Partition
|
||||
|
||||
```rust
|
||||
let (side_s, side_t) = mincut.partition();
|
||||
// Example: ([1], [2, 3])
|
||||
```
|
||||
|
||||
**Interpretation:**
|
||||
- `side_s`: Vertex IDs on one side of the cut (arbitrarily chosen)
|
||||
- `side_t`: Vertex IDs on the other side
|
||||
- All edges connecting S to T are in the minimum cut
|
||||
- Vertices within S or T remain connected
|
||||
|
||||
#### Cut Edges
|
||||
|
||||
```rust
|
||||
let cut_edges = mincut.cut_edges();
|
||||
// Example: [(1, 2, 1.0), (1, 3, 1.0)]
|
||||
```
|
||||
|
||||
**Interpretation:**
|
||||
- These are the **specific edges** that form the minimum cut
|
||||
- Format: `(source_vertex, target_vertex, weight)`
|
||||
- Removing these edges disconnects the graph
|
||||
- The sum of weights equals the cut value
|
||||
|
||||
### Exact vs Approximate Results
|
||||
|
||||
```rust
|
||||
let result = mincut.min_cut();
|
||||
|
||||
if result.is_exact {
|
||||
println!("Guaranteed minimum: {}", result.value);
|
||||
} else {
|
||||
println!("Approximate: {} (±{}%)",
|
||||
result.value,
|
||||
(result.approximation_ratio - 1.0) * 100.0
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Exact Mode
|
||||
- **`is_exact = true`**
|
||||
- Guaranteed to find the true minimum cut
|
||||
- Slower for very large graphs
|
||||
- Use when correctness is critical
|
||||
|
||||
#### Approximate Mode
|
||||
- **`is_exact = false`**
|
||||
- Returns a cut within `(1+ε)` of the minimum
|
||||
- Much faster for large graphs
|
||||
- Use when speed matters more than perfect accuracy
|
||||
|
||||
**Example:** With `ε = 0.1`:
|
||||
- If true minimum = 10, approximate returns between 10 and 11
|
||||
- Approximation ratio = 1.1 (10% tolerance)
|
||||
|
||||
### Performance Characteristics
|
||||
|
||||
```rust
|
||||
// Query: O(1) - instant!
|
||||
let value = mincut.min_cut_value();
|
||||
|
||||
// Insert edge: O(n^{o(1)}) - subpolynomial!
|
||||
mincut.insert_edge(u, v, weight)?;
|
||||
|
||||
// Delete edge: O(n^{o(1)}) - subpolynomial!
|
||||
mincut.delete_edge(u, v)?;
|
||||
```
|
||||
|
||||
**What is O(n^{o(1)})?**
|
||||
- Slower than O(1) but faster than O(n), O(log n), etc.
|
||||
- Example: O(n^{0.01}) or O(n^{1/log log n})
|
||||
- Much better than traditional O(m·n) algorithms
|
||||
- Enables real-time updates even for large graphs
|
||||
|
||||
---
|
||||
|
||||
## 5. Choosing Between Exact and Approximate
|
||||
|
||||
Use this flowchart to decide which mode to use:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start{What's your<br/>graph size?} --> Small{Less than<br/>10,000 nodes?}
|
||||
|
||||
Small -->|Yes| UseExact[Use EXACT mode]
|
||||
Small -->|No| Large{More than<br/>1 million nodes?}
|
||||
|
||||
Large -->|Yes| UseApprox[Use APPROXIMATE mode]
|
||||
Large -->|No| CheckAccuracy{Need guaranteed<br/>correctness?}
|
||||
|
||||
CheckAccuracy -->|Yes| UseExact2[Use EXACT mode]
|
||||
CheckAccuracy -->|No| CheckSpeed{Speed is<br/>critical?}
|
||||
|
||||
CheckSpeed -->|Yes| UseApprox2[Use APPROXIMATE mode]
|
||||
CheckSpeed -->|No| UseExact3[Use EXACT mode<br/>as default]
|
||||
|
||||
UseExact --> ExactCode["mincut = MinCutBuilder::new()
|
||||
.exact()
|
||||
.build()?"]
|
||||
|
||||
UseExact2 --> ExactCode
|
||||
UseExact3 --> ExactCode
|
||||
|
||||
UseApprox --> ApproxCode["mincut = MinCutBuilder::new()
|
||||
.approximate(0.1)
|
||||
.build()?"]
|
||||
|
||||
UseApprox2 --> ApproxCode
|
||||
|
||||
style Start fill:#e1f5ff
|
||||
style UseExact fill:#c8e6c9
|
||||
style UseExact2 fill:#c8e6c9
|
||||
style UseExact3 fill:#c8e6c9
|
||||
style UseApprox fill:#fff9c4
|
||||
style UseApprox2 fill:#fff9c4
|
||||
style ExactCode fill:#f0f0f0
|
||||
style ApproxCode fill:#f0f0f0
|
||||
```
|
||||
|
||||
### Quick Comparison
|
||||
|
||||
| Aspect | Exact Mode | Approximate Mode |
|
||||
|--------|-----------|------------------|
|
||||
| **Accuracy** | 100% correct | (1+ε) of optimal |
|
||||
| **Speed** | Moderate | Very fast |
|
||||
| **Memory** | O(n log n + m) | O(n log n / ε²) |
|
||||
| **Best For** | Small-medium graphs | Large graphs |
|
||||
| **Update Time** | O(n^{o(1)}) | O(n^{o(1)}) |
|
||||
|
||||
### Code Examples
|
||||
|
||||
**Exact Mode** (guaranteed correct):
|
||||
```rust
|
||||
let mut mincut = MinCutBuilder::new()
|
||||
.exact()
|
||||
.with_edges(edges)
|
||||
.build()?;
|
||||
|
||||
assert!(mincut.min_cut().is_exact);
|
||||
```
|
||||
|
||||
**Approximate Mode** (10% tolerance):
|
||||
```rust
|
||||
let mut mincut = MinCutBuilder::new()
|
||||
.approximate(0.1) // ε = 0.1
|
||||
.with_edges(edges)
|
||||
.build()?;
|
||||
|
||||
let result = mincut.min_cut();
|
||||
assert!(!result.is_exact);
|
||||
assert_eq!(result.approximation_ratio, 1.1);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Next Steps
|
||||
|
||||
Congratulations! You now understand the basics of minimum cuts and how to use RuVector MinCut. Here's where to go next:
|
||||
|
||||
### Learn More
|
||||
|
||||
| Topic | Link | What You'll Learn |
|
||||
|-------|------|------------------|
|
||||
| **Advanced API** | [02-advanced-api.md](02-advanced-api.md) | Batch operations, custom graphs, thread safety |
|
||||
| **Real-Time Monitoring** | [03-monitoring.md](03-monitoring.md) | Event notifications, thresholds, callbacks |
|
||||
| **Performance Tuning** | [04-performance.md](04-performance.md) | Benchmarking, optimization, scaling |
|
||||
| **Use Cases** | [05-use-cases.md](05-use-cases.md) | Network analysis, community detection, partitioning |
|
||||
| **Algorithm Details** | [../ALGORITHMS.md](../ALGORITHMS.md) | Mathematical foundations, proofs, complexity |
|
||||
| **Architecture** | [../ARCHITECTURE.md](../ARCHITECTURE.md) | Internal design, data structures, implementation |
|
||||
|
||||
### Try These Examples
|
||||
|
||||
RuVector MinCut comes with several examples you can run:
|
||||
|
||||
```bash
|
||||
# Basic minimum cut operations
|
||||
cargo run --example basic
|
||||
|
||||
# Graph sparsification
|
||||
cargo run --example sparsify_demo
|
||||
|
||||
# Local k-cut algorithm
|
||||
cargo run --example localkcut_demo
|
||||
|
||||
# Real-time monitoring (requires 'monitoring' feature)
|
||||
cargo run --example monitoring --features monitoring
|
||||
|
||||
# Performance benchmarking
|
||||
cargo run --example benchmark --release
|
||||
```
|
||||
|
||||
### Common Tasks
|
||||
|
||||
#### Task 1: Analyze Your Own Graph
|
||||
|
||||
```rust
|
||||
use ruvector_mincut::{MinCutBuilder, DynamicMinCut};
|
||||
|
||||
fn analyze_network(edges: Vec<(u32, u32, f64)>) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut mincut = MinCutBuilder::new()
|
||||
.exact()
|
||||
.with_edges(edges)
|
||||
.build()?;
|
||||
|
||||
println!("Network vulnerability: {}", mincut.min_cut_value());
|
||||
println!("Critical edges: {:?}", mincut.cut_edges());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
#### Task 2: Monitor Real-Time Changes
|
||||
|
||||
```rust
|
||||
#[cfg(feature = "monitoring")]
|
||||
use ruvector_mincut::{MonitorBuilder, EventType};
|
||||
|
||||
fn setup_monitoring() {
|
||||
let monitor = MonitorBuilder::new()
|
||||
.threshold_below(5.0, "critical")
|
||||
.on_event_type(EventType::CutDecreased, "alert", |event| {
|
||||
eprintln!("⚠️ WARNING: Cut decreased to {}", event.new_value);
|
||||
})
|
||||
.build();
|
||||
|
||||
// Attach to your mincut structure...
|
||||
}
|
||||
```
|
||||
|
||||
#### Task 3: Batch Process Updates
|
||||
|
||||
```rust
|
||||
fn batch_updates(mincut: &mut impl DynamicMinCut,
|
||||
new_edges: &[(u32, u32, f64)]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Insert many edges at once
|
||||
for (u, v, w) in new_edges {
|
||||
mincut.insert_edge(*u, *v, *w)?;
|
||||
}
|
||||
|
||||
// Query triggers lazy evaluation
|
||||
let current_cut = mincut.min_cut_value();
|
||||
println!("Updated minimum cut: {}", current_cut);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
### Get Help
|
||||
|
||||
- **📖 Documentation**: [docs.rs/ruvector-mincut](https://docs.rs/ruvector-mincut)
|
||||
- **🐙 GitHub Issues**: [Report bugs or ask questions](https://github.com/ruvnet/ruvector/issues)
|
||||
- **💬 Discussions**: [Community forum](https://github.com/ruvnet/ruvector/discussions)
|
||||
- **🌐 Website**: [ruv.io](https://ruv.io)
|
||||
|
||||
### Keep Learning
|
||||
|
||||
The minimum cut problem connects to many fascinating areas of computer science:
|
||||
|
||||
- **Network Flow**: Max-flow/min-cut theorem
|
||||
- **Graph Theory**: Connectivity, separators, spanning trees
|
||||
- **Optimization**: Linear programming, approximation algorithms
|
||||
- **Distributed Systems**: Partition tolerance, consensus
|
||||
- **Machine Learning**: Graph neural networks, clustering
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Builder Pattern
|
||||
|
||||
```rust
|
||||
MinCutBuilder::new()
|
||||
.exact() // or .approximate(0.1)
|
||||
.with_edges(edges) // Initial edges
|
||||
.with_capacity(10000) // Preallocate capacity
|
||||
.build()? // Construct
|
||||
```
|
||||
|
||||
### Core Operations
|
||||
|
||||
```rust
|
||||
mincut.min_cut_value() // Get cut value (O(1))
|
||||
mincut.partition() // Get partition (O(n))
|
||||
mincut.cut_edges() // Get cut edges (O(m))
|
||||
mincut.insert_edge(u, v, w)? // Add edge (O(n^{o(1)}))
|
||||
mincut.delete_edge(u, v)? // Remove edge (O(n^{o(1)}))
|
||||
```
|
||||
|
||||
### Result Inspection
|
||||
|
||||
```rust
|
||||
let result = mincut.min_cut();
|
||||
result.value // Cut value
|
||||
result.is_exact // true if exact mode
|
||||
result.approximation_ratio // 1.0 if exact, >1.0 if approximate
|
||||
result.edges // Edges in the cut
|
||||
result.partition // (S, T) vertex sets
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Happy computing! 🚀**
|
||||
|
||||
> **Pro Tip**: Start simple with exact mode on small graphs, then switch to approximate mode as your graphs grow. The API is identical!
|
||||
655
vendor/ruvector/crates/ruvector-mincut/docs/guide/02-core-concepts.md
vendored
Normal file
655
vendor/ruvector/crates/ruvector-mincut/docs/guide/02-core-concepts.md
vendored
Normal file
@@ -0,0 +1,655 @@
|
||||
# Core Concepts
|
||||
|
||||
This guide explains the fundamental concepts behind minimum cut algorithms in accessible language. Whether you're new to graph theory or experienced with algorithms, this guide will help you understand what makes RuVector's minimum cut implementation special.
|
||||
|
||||
---
|
||||
|
||||
## 1. Graph Basics
|
||||
|
||||
### What is a Graph?
|
||||
|
||||
Think of a graph like a social network or a map:
|
||||
|
||||
- **Vertices (Nodes)**: These are the "things" in your system
|
||||
- Cities on a map
|
||||
- People in a social network
|
||||
- Computers in a network
|
||||
- Pixels in an image
|
||||
|
||||
- **Edges (Links)**: These are the connections between things
|
||||
- Roads between cities
|
||||
- Friendships between people
|
||||
- Network cables between computers
|
||||
- Similarity between adjacent pixels
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Alice] ---|Friend| B[Bob]
|
||||
B ---|Friend| C[Carol]
|
||||
A ---|Friend| C
|
||||
C ---|Friend| D[Dave]
|
||||
B ---|Friend| D
|
||||
|
||||
style A fill:#e1f5ff
|
||||
style B fill:#e1f5ff
|
||||
style C fill:#e1f5ff
|
||||
style D fill:#e1f5ff
|
||||
```
|
||||
|
||||
### Weighted vs Unweighted Graphs
|
||||
|
||||
**Unweighted Graph**: All connections are equal
|
||||
- Example: "Is there a friendship?" (yes/no)
|
||||
|
||||
**Weighted Graph**: Connections have different strengths or capacities
|
||||
- Example: "How strong is the friendship?" (1-10 scale)
|
||||
- Example: "What's the bandwidth of this network cable?" (100 Mbps, 1 Gbps, etc.)
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "Unweighted Graph"
|
||||
A1[City A] --- B1[City B]
|
||||
B1 --- C1[City C]
|
||||
A1 --- C1
|
||||
end
|
||||
|
||||
subgraph "Weighted Graph"
|
||||
A2[City A] ---|50 km| B2[City B]
|
||||
B2 ---|30 km| C2[City C]
|
||||
A2 ---|80 km| C2
|
||||
end
|
||||
|
||||
style A1 fill:#ffe1e1
|
||||
style B1 fill:#ffe1e1
|
||||
style C1 fill:#ffe1e1
|
||||
style A2 fill:#e1ffe1
|
||||
style B2 fill:#e1ffe1
|
||||
style C2 fill:#e1ffe1
|
||||
```
|
||||
|
||||
### Directed vs Undirected Graphs
|
||||
|
||||
**Undirected**: Connections work both ways
|
||||
- Example: Roads (usually bidirectional)
|
||||
- Example: Mutual friendships
|
||||
|
||||
**Undirected**: Connections have a direction
|
||||
- Example: One-way streets
|
||||
- Example: Twitter follows (Alice follows Bob doesn't mean Bob follows Alice)
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "Undirected (Bidirectional)"
|
||||
A1[A] --- B1[B]
|
||||
B1 --- C1[C]
|
||||
end
|
||||
|
||||
subgraph "Directed (One-way)"
|
||||
A2[A] --> B2[B]
|
||||
B2 --> C2[C]
|
||||
C2 --> A2
|
||||
end
|
||||
```
|
||||
|
||||
**RuVector focuses on undirected, weighted graphs** for minimum cut problems.
|
||||
|
||||
---
|
||||
|
||||
## 2. What is Minimum Cut?
|
||||
|
||||
### Definition
|
||||
|
||||
A **cut** in a graph divides vertices into two groups. The **minimum cut** is the division that requires removing the fewest (or lowest-weight) edges.
|
||||
|
||||
Think of it like this:
|
||||
- Imagine a network of pipes carrying water
|
||||
- A cut is choosing which pipes to block to split the network in two
|
||||
- The minimum cut finds the weakest point - the smallest set of pipes that, if blocked, would separate the network
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "Original Graph"
|
||||
A[A] ---|2| B[B]
|
||||
A ---|3| C[C]
|
||||
B ---|1| D[D]
|
||||
C ---|1| D
|
||||
B ---|4| C
|
||||
end
|
||||
|
||||
subgraph "Minimum Cut (weight = 2)"
|
||||
A1[A] ---|2| B1[B]
|
||||
A1 ---|3| C1[C]
|
||||
B1 -.X.-|1| D1[D]
|
||||
C1 -.X.-|1| D1
|
||||
B1 ---|4| C1
|
||||
|
||||
style A1 fill:#ffcccc
|
||||
style B1 fill:#ffcccc
|
||||
style C1 fill:#ffcccc
|
||||
style D1 fill:#ccffcc
|
||||
end
|
||||
```
|
||||
|
||||
In the example above:
|
||||
- Cutting edges B-D and C-D (total weight = 1 + 1 = 2) separates the graph
|
||||
- This is the minimum cut because no smaller cut exists
|
||||
- The red group {A, B, C} is separated from the green group {D}
|
||||
|
||||
### Why Minimum Cut Matters
|
||||
|
||||
Minimum cut algorithms solve real-world problems:
|
||||
|
||||
#### 1. **Network Reliability**
|
||||
Find the weakest point in your infrastructure:
|
||||
- Which network links, if they fail, would split your system?
|
||||
- What's the minimum bandwidth bottleneck?
|
||||
- Where should you add redundancy?
|
||||
|
||||
#### 2. **Image Segmentation**
|
||||
Separate objects from backgrounds:
|
||||
- Each pixel is a vertex
|
||||
- Similar adjacent pixels have high-weight edges
|
||||
- Minimum cut finds natural object boundaries
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "Image Pixels"
|
||||
P1[Sky] ---|9| P2[Sky]
|
||||
P2 ---|9| P3[Sky]
|
||||
P3 ---|2| P4[Tree]
|
||||
P4 ---|8| P5[Tree]
|
||||
P5 ---|8| P6[Tree]
|
||||
end
|
||||
|
||||
style P1 fill:#87ceeb
|
||||
style P2 fill:#87ceeb
|
||||
style P3 fill:#87ceeb
|
||||
style P4 fill:#228b22
|
||||
style P5 fill:#228b22
|
||||
style P6 fill:#228b22
|
||||
```
|
||||
|
||||
#### 3. **Community Detection**
|
||||
Find natural groupings in social networks:
|
||||
- Strong connections within communities
|
||||
- Weak connections between communities
|
||||
- Minimum cut reveals community boundaries
|
||||
|
||||
#### 4. **VLSI Design**
|
||||
Partition circuits to minimize connections between chips:
|
||||
- Reduces manufacturing complexity
|
||||
- Minimizes communication overhead
|
||||
- Optimizes physical layout
|
||||
|
||||
### Global Minimum Cut vs S-T Minimum Cut
|
||||
|
||||
There are two types of minimum cut problems:
|
||||
|
||||
#### **S-T Minimum Cut (Terminal Cut)**
|
||||
- You specify two vertices: source (s) and sink (t)
|
||||
- Find the minimum cut that separates s from t
|
||||
- Common in flow networks and image segmentation
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
S[Source S] ---|5| A[A]
|
||||
S ---|3| B[B]
|
||||
A ---|2| T[Sink T]
|
||||
B ---|4| T
|
||||
A ---|1| B
|
||||
|
||||
style S fill:#ffcccc
|
||||
style A fill:#ffcccc
|
||||
style B fill:#ccffcc
|
||||
style T fill:#ccffcc
|
||||
```
|
||||
|
||||
#### **Global Minimum Cut (All-Pairs)**
|
||||
- No specific source/sink specified
|
||||
- Find the absolute minimum cut across the entire graph
|
||||
- Harder problem, but more general
|
||||
|
||||
**RuVector implements global minimum cut algorithms** - the most general and challenging variant.
|
||||
|
||||
---
|
||||
|
||||
## 3. Dynamic vs Static Algorithms
|
||||
|
||||
### The Static Approach
|
||||
|
||||
Traditional algorithms start from scratch every time:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant Algorithm
|
||||
participant Graph
|
||||
|
||||
User->>Graph: Initial graph with 1000 edges
|
||||
User->>Algorithm: Compute minimum cut
|
||||
Algorithm->>Algorithm: Process all 1000 edges
|
||||
Algorithm->>User: Result (takes 10 seconds)
|
||||
|
||||
User->>Graph: Add 1 edge
|
||||
User->>Algorithm: Compute minimum cut again
|
||||
Algorithm->>Algorithm: Reprocess all 1001 edges from scratch
|
||||
Algorithm->>User: Result (takes 10 seconds again!)
|
||||
|
||||
Note over User,Algorithm: Inefficient: Full recomputation every time
|
||||
```
|
||||
|
||||
**Problem**: If you add/remove just one edge, static algorithms recompute everything!
|
||||
|
||||
### The Dynamic Approach (Revolutionary!)
|
||||
|
||||
Dynamic algorithms maintain the solution incrementally:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant DynAlg as Dynamic Algorithm
|
||||
participant Graph
|
||||
|
||||
User->>Graph: Initial graph with 1000 edges
|
||||
User->>DynAlg: Compute minimum cut
|
||||
DynAlg->>DynAlg: Process all 1000 edges, build data structures
|
||||
DynAlg->>User: Result (takes 10 seconds)
|
||||
|
||||
User->>Graph: Add 1 edge
|
||||
User->>DynAlg: Update minimum cut
|
||||
DynAlg->>DynAlg: Update only affected parts
|
||||
DynAlg->>User: Result (takes 0.1 seconds!)
|
||||
|
||||
Note over User,DynAlg: Efficient: Incremental updates only
|
||||
```
|
||||
|
||||
**Advantage**: Updates are typically much faster than full recomputation!
|
||||
|
||||
### Why Dynamic is Revolutionary
|
||||
|
||||
Consider a practical scenario:
|
||||
|
||||
| Operation | Static Algorithm | Dynamic Algorithm |
|
||||
|-----------|------------------|-------------------|
|
||||
| Initial computation (10,000 edges) | 100 seconds | 100 seconds |
|
||||
| Add 1 edge | 100 seconds | 0.5 seconds |
|
||||
| Add 100 edges (one at a time) | 10,000 seconds (2.7 hours!) | 50 seconds |
|
||||
| **Speed improvement** | — | **200× faster** |
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Change in Graph] --> B{Use Dynamic Algorithm?}
|
||||
B -->|Yes| C[Update incrementally]
|
||||
B -->|No| D[Recompute from scratch]
|
||||
C --> E[Fast Update 0.5s]
|
||||
D --> F[Slow Recompute 100s]
|
||||
|
||||
style C fill:#90EE90
|
||||
style D fill:#FFB6C6
|
||||
style E fill:#90EE90
|
||||
style F fill:#FFB6C6
|
||||
```
|
||||
|
||||
### Amortized vs Worst-Case Complexity
|
||||
|
||||
Dynamic algorithms have two complexity measures:
|
||||
|
||||
#### **Amortized Complexity**
|
||||
- Average time per operation over many operations
|
||||
- Usually much better than worst-case
|
||||
- Example: O(log² n) per edge insertion
|
||||
|
||||
#### **Worst-Case Complexity**
|
||||
- Maximum time for a single operation
|
||||
- Guarantees for real-time systems
|
||||
- Example: O(log⁴ n) per edge insertion
|
||||
|
||||
**RuVector provides both**:
|
||||
- **Standard algorithm**: Best amortized complexity O(n^{o(1)})
|
||||
- **PolylogConnectivity**: Deterministic worst-case O(log⁴ n)
|
||||
|
||||
---
|
||||
|
||||
## 4. Algorithm Choices
|
||||
|
||||
RuVector provides three cutting-edge algorithms from recent research papers (2024-2025). Here's when to use each:
|
||||
|
||||
### 4.1 Exact Algorithm (Default)
|
||||
|
||||
**Based on**: "A Õ(n^{o(1)})-Approximation Algorithm for Minimum Cut" (Chen et al., 2024)
|
||||
|
||||
**Complexity**: O(n^{o(1)}) amortized per operation
|
||||
|
||||
**When to use**:
|
||||
- ✅ You need the exact minimum cut value
|
||||
- ✅ Your graph changes frequently (dynamic updates)
|
||||
- ✅ You want the best average-case performance
|
||||
- ✅ General-purpose applications
|
||||
|
||||
**Trade-offs**:
|
||||
- Slower worst-case than approximate algorithm
|
||||
- Best for most applications
|
||||
|
||||
```rust
|
||||
use ruvector_mincut::{MinCutWrapper, MinCutAlgorithm};
|
||||
|
||||
let mut wrapper = MinCutWrapper::new(
|
||||
num_vertices,
|
||||
MinCutAlgorithm::Exact
|
||||
);
|
||||
```
|
||||
|
||||
### 4.2 Approximate Algorithm ((1+ε)-approximation)
|
||||
|
||||
**Based on**: "Dynamic (1+ε)-Approximate Minimum Cut in Subpolynomial Time per Operation" (Cen et al., 2025)
|
||||
|
||||
**Complexity**: Õ(1/ε²) amortized per operation (subpolynomial in n!)
|
||||
|
||||
**When to use**:
|
||||
- ✅ You can tolerate small approximation error
|
||||
- ✅ You need extremely fast updates
|
||||
- ✅ Your graph is very large (millions of vertices)
|
||||
- ✅ You want cutting-edge performance
|
||||
|
||||
**Trade-offs**:
|
||||
- Result is within (1+ε) of optimal (e.g., ε=0.1 → 10% error bound)
|
||||
- **Fastest algorithm** for large graphs
|
||||
|
||||
```rust
|
||||
let mut wrapper = MinCutWrapper::new_approx(
|
||||
num_vertices,
|
||||
0.1 // ε = 10% approximation
|
||||
);
|
||||
```
|
||||
|
||||
**Example**: If true minimum cut is 100, approximate algorithm returns 100-110.
|
||||
|
||||
### 4.3 PolylogConnectivity (Deterministic Worst-Case)
|
||||
|
||||
**Based on**: "Incremental (1+ε)-Approximate Dynamic Connectivity with polylog Worst-Case Time per Update" (Cen et al., 2025)
|
||||
|
||||
**Complexity**: O(log⁴ n / ε²) worst-case per operation
|
||||
|
||||
**When to use**:
|
||||
- ✅ You need **guaranteed** worst-case performance
|
||||
- ✅ Real-time systems with strict latency requirements
|
||||
- ✅ Safety-critical applications
|
||||
- ✅ You need predictable performance (no spikes)
|
||||
|
||||
**Trade-offs**:
|
||||
- Slightly slower than amortized algorithms on average
|
||||
- Provides deterministic guarantees
|
||||
|
||||
```rust
|
||||
let mut wrapper = MinCutWrapper::new_polylog_connectivity(
|
||||
num_vertices,
|
||||
0.1 // ε = 10% approximation
|
||||
);
|
||||
```
|
||||
|
||||
### Performance Comparison
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph "Performance Characteristics"
|
||||
A[Exact Algorithm] --> A1["Amortized: O(n^o1)"]
|
||||
A --> A2[Exact results]
|
||||
A --> A3[Best general-purpose]
|
||||
|
||||
B[Approximate] --> B1["Amortized: Õ(1/ε²)"]
|
||||
B --> B2[±ε error]
|
||||
B --> B3[Fastest updates]
|
||||
|
||||
C[PolylogConnectivity] --> C1["Worst-case: O(log⁴ n / ε²)"]
|
||||
C --> C2[±ε error]
|
||||
C --> C3[Predictable latency]
|
||||
end
|
||||
|
||||
style A fill:#e1f5ff
|
||||
style B fill:#ffe1e1
|
||||
style C fill:#e1ffe1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Key Data Structures
|
||||
|
||||
Dynamic minimum cut algorithms rely on sophisticated data structures. You don't need to understand these deeply to use RuVector, but knowing they exist helps appreciate the complexity.
|
||||
|
||||
### 5.1 Link-Cut Trees
|
||||
|
||||
**Purpose**: Maintain connectivity in forests with dynamic edge insertions/deletions
|
||||
|
||||
**Operations**:
|
||||
- `link(u, v)`: Connect two trees
|
||||
- `cut(u, v)`: Disconnect an edge
|
||||
- `find_root(v)`: Find root of v's tree
|
||||
- `path_aggregate(u, v)`: Aggregate values on path from u to v
|
||||
|
||||
**Time Complexity**: O(log n) per operation (amortized)
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "Link-Cut Tree Structure"
|
||||
R1[Root] --> C1[Child 1]
|
||||
R1 --> C2[Child 2]
|
||||
C1 --> G1[Grandchild 1]
|
||||
C1 --> G2[Grandchild 2]
|
||||
C2 --> G3[Grandchild 3]
|
||||
end
|
||||
|
||||
subgraph "Operations"
|
||||
O1[link: Add edge]
|
||||
O2[cut: Remove edge]
|
||||
O3[find_root: Query root]
|
||||
O4[path_aggregate: Sum on path]
|
||||
end
|
||||
|
||||
style R1 fill:#ffcccc
|
||||
style C1 fill:#ccffcc
|
||||
style C2 fill:#ccffcc
|
||||
style G1 fill:#ccccff
|
||||
style G2 fill:#ccccff
|
||||
style G3 fill:#ccccff
|
||||
```
|
||||
|
||||
**Used in**: All three algorithms for maintaining spanning forests
|
||||
|
||||
### 5.2 Euler Tour Trees
|
||||
|
||||
**Purpose**: Alternative dynamic connectivity structure with different trade-offs
|
||||
|
||||
**Key Idea**: Represent tree as a cyclic sequence (Euler tour)
|
||||
|
||||
**Advantages**:
|
||||
- Efficient subtree operations
|
||||
- Good for maintaining subtree properties
|
||||
- Deterministic performance
|
||||
|
||||
**Time Complexity**: O(log n) per operation
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[A] --> B[B]
|
||||
A --> C[C]
|
||||
B --> D[D]
|
||||
B --> E[E]
|
||||
|
||||
subgraph "Euler Tour Sequence"
|
||||
direction LR
|
||||
ET[A → B → D → B → E → B → A → C → A]
|
||||
end
|
||||
|
||||
style A fill:#ffcccc
|
||||
style B fill:#ccffcc
|
||||
style C fill:#ccccff
|
||||
style D fill:#ffffcc
|
||||
style E fill:#ffccff
|
||||
```
|
||||
|
||||
**Used in**: PolylogConnectivity algorithm for deterministic guarantees
|
||||
|
||||
### 5.3 Hierarchical Decomposition
|
||||
|
||||
**Purpose**: Partition graph into levels with decreasing density
|
||||
|
||||
**Key Idea**:
|
||||
- Level 0: Original graph
|
||||
- Level i: Graph with edges of weight ≥ 2^i
|
||||
- Higher levels are sparser
|
||||
|
||||
**Advantages**:
|
||||
- Focus computation on relevant parts
|
||||
- Skip unnecessary levels
|
||||
- Efficient updates
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "Level 0 (All edges)"
|
||||
L0A[A] ---|1| L0B[B]
|
||||
L0A ---|2| L0C[C]
|
||||
L0A ---|4| L0D[D]
|
||||
L0B ---|8| L0C
|
||||
end
|
||||
|
||||
subgraph "Level 1 (Weight ≥ 2)"
|
||||
L1A[A] ---|2| L1C[C]
|
||||
L1A ---|4| L1D[D]
|
||||
L1B[B] ---|8| L1C
|
||||
end
|
||||
|
||||
subgraph "Level 2 (Weight ≥ 4)"
|
||||
L2A[A] ---|4| L2D[D]
|
||||
L2B[B] ---|8| L2C[C]
|
||||
end
|
||||
|
||||
subgraph "Level 3 (Weight ≥ 8)"
|
||||
L3B[B] ---|8| L3C[C]
|
||||
end
|
||||
|
||||
style L0A fill:#ffcccc
|
||||
style L1A fill:#ccffcc
|
||||
style L2A fill:#ccccff
|
||||
style L3B fill:#ffffcc
|
||||
```
|
||||
|
||||
**Used in**: Approximate and PolylogConnectivity algorithms for hierarchical graph processing
|
||||
|
||||
### 5.4 Local k-Cut Hierarchy
|
||||
|
||||
**Purpose**: Maintain minimum cuts of varying connectivity
|
||||
|
||||
**Key Idea**:
|
||||
- Store cuts of different sizes (1-cut, 2-cut, ..., k-cut)
|
||||
- Update only affected levels
|
||||
- Query appropriate level for minimum cut
|
||||
|
||||
**Advantages**:
|
||||
- Efficient querying of different cut sizes
|
||||
- Incremental updates
|
||||
- Supports connectivity curve analysis
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
H1[1-Cut: λ=2] --> H2[2-Cut: λ=5]
|
||||
H2 --> H3[3-Cut: λ=7]
|
||||
H3 --> H4[4-Cut: λ=9]
|
||||
|
||||
style H1 fill:#ffcccc
|
||||
style H2 fill:#ccffcc
|
||||
style H3 fill:#ccccff
|
||||
style H4 fill:#ffffcc
|
||||
```
|
||||
|
||||
**Used in**: All algorithms for maintaining cut hierarchies
|
||||
|
||||
---
|
||||
|
||||
## 6. Which Algorithm Should I Use?
|
||||
|
||||
Use this decision flowchart to choose the right algorithm:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
Start[Which algorithm?] --> Q1{Need exact result?}
|
||||
|
||||
Q1 -->|Yes| Exact[Use Exact Algorithm]
|
||||
Q1 -->|No, approximation OK| Q2{Need worst-case guarantees?}
|
||||
|
||||
Q2 -->|Yes, real-time/safety-critical| Polylog[Use PolylogConnectivity]
|
||||
Q2 -->|No, average case is fine| Q3{Graph size?}
|
||||
|
||||
Q3 -->|Small < 10K vertices| Exact2[Use Exact Algorithm]
|
||||
Q3 -->|Large > 10K vertices| Approx[Use Approximate Algorithm]
|
||||
|
||||
Exact --> E1["MinCutAlgorithm::Exact<br/>Best general-purpose"]
|
||||
Exact2 --> E1
|
||||
Approx --> A1["new_approx(n, 0.1)<br/>10% error, fastest"]
|
||||
Polylog --> P1["new_polylog_connectivity(n, 0.1)<br/>Predictable latency"]
|
||||
|
||||
style Exact fill:#90EE90
|
||||
style Exact2 fill:#90EE90
|
||||
style Approx fill:#FFD700
|
||||
style Polylog fill:#87CEEB
|
||||
style E1 fill:#90EE90
|
||||
style A1 fill:#FFD700
|
||||
style P1 fill:#87CEEB
|
||||
```
|
||||
|
||||
### Quick Reference Table
|
||||
|
||||
| Your Needs | Recommended Algorithm | Configuration |
|
||||
|------------|----------------------|---------------|
|
||||
| General-purpose, need exact results | **Exact** | `MinCutAlgorithm::Exact` |
|
||||
| Large graph (>10K vertices), can tolerate 5-10% error | **Approximate** | `new_approx(n, 0.1)` |
|
||||
| Real-time system, need guaranteed latency | **PolylogConnectivity** | `new_polylog_connectivity(n, 0.1)` |
|
||||
| Interactive application with frequent updates | **Approximate** | `new_approx(n, 0.05)` |
|
||||
| Scientific computing, need precision | **Exact** | `MinCutAlgorithm::Exact` |
|
||||
| Image segmentation (can accept small errors) | **Approximate** | `new_approx(n, 0.1)` |
|
||||
| Network monitoring (need alerts) | **PolylogConnectivity** | `new_polylog_connectivity(n, 0.05)` |
|
||||
|
||||
### Performance Guidelines
|
||||
|
||||
**Exact Algorithm**:
|
||||
```rust
|
||||
// Best for: Most applications
|
||||
let mut mincut = MinCutWrapper::new(1000, MinCutAlgorithm::Exact);
|
||||
```
|
||||
|
||||
**Approximate Algorithm**:
|
||||
```rust
|
||||
// Best for: Large graphs, speed-critical
|
||||
let mut mincut = MinCutWrapper::new_approx(
|
||||
100_000, // Large graph
|
||||
0.1 // 10% approximation is usually fine
|
||||
);
|
||||
```
|
||||
|
||||
**PolylogConnectivity**:
|
||||
```rust
|
||||
// Best for: Real-time systems
|
||||
let mut mincut = MinCutWrapper::new_polylog_connectivity(
|
||||
50_000, // Medium-large graph
|
||||
0.05 // Tight approximation for accuracy
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
You now understand:
|
||||
|
||||
1. **Graph fundamentals**: Vertices, edges, weights, and directions
|
||||
2. **Minimum cut**: Finding the weakest separation in a graph
|
||||
3. **Dynamic algorithms**: Why incremental updates are revolutionary (200× faster!)
|
||||
4. **Algorithm choices**: Exact, approximate, and worst-case deterministic options
|
||||
5. **Data structures**: The sophisticated machinery powering fast dynamic updates
|
||||
6. **Decision making**: How to choose the right algorithm for your application
|
||||
|
||||
**Next Steps**:
|
||||
- Read [API Reference](./03-api-reference.md) for detailed function documentation
|
||||
- Explore [Examples](./04-examples.md) for practical use cases
|
||||
- Check out [Performance Guide](./05-performance.md) for optimization tips
|
||||
|
||||
**Key Takeaway**: RuVector gives you state-of-the-art dynamic minimum cut algorithms that are 100-200× faster than static approaches for graphs that change over time. Choose your algorithm based on whether you need exact results, maximum speed, or worst-case guarantees.
|
||||
1605
vendor/ruvector/crates/ruvector-mincut/docs/guide/03-practical-applications.md
vendored
Normal file
1605
vendor/ruvector/crates/ruvector-mincut/docs/guide/03-practical-applications.md
vendored
Normal file
File diff suppressed because it is too large
Load Diff
2116
vendor/ruvector/crates/ruvector-mincut/docs/guide/04-integration-guide.md
vendored
Normal file
2116
vendor/ruvector/crates/ruvector-mincut/docs/guide/04-integration-guide.md
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1885
vendor/ruvector/crates/ruvector-mincut/docs/guide/05-advanced-examples.md
vendored
Normal file
1885
vendor/ruvector/crates/ruvector-mincut/docs/guide/05-advanced-examples.md
vendored
Normal file
File diff suppressed because it is too large
Load Diff
827
vendor/ruvector/crates/ruvector-mincut/docs/guide/06-ecosystem.md
vendored
Normal file
827
vendor/ruvector/crates/ruvector-mincut/docs/guide/06-ecosystem.md
vendored
Normal file
@@ -0,0 +1,827 @@
|
||||
# RuVector Ecosystem Guide
|
||||
|
||||
This guide provides an overview of the RuVector ecosystem, showing how `ruvector-mincut` integrates with other crates in the family and the broader ruv.io platform.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [RuVector Family](#ruvector-family)
|
||||
- [ruvector-mincut Bindings](#ruvector-mincut-bindings)
|
||||
- [Midstream Integration](#midstream-integration)
|
||||
- [Advanced Integrations](#advanced-integrations)
|
||||
- [ruv.io Platform](#ruvio-platform)
|
||||
- [Ecosystem Architecture](#ecosystem-architecture)
|
||||
- [Resources](#resources)
|
||||
|
||||
## RuVector Family
|
||||
|
||||
The RuVector family is a collection of high-performance Rust crates for vector operations, graph analytics, and machine learning, optimized for SIMD and modern hardware.
|
||||
|
||||
### Core Crates
|
||||
|
||||
#### ruvector-core
|
||||
**Foundation for all RuVector operations**
|
||||
|
||||
- **SIMD Primitives**: Hardware-accelerated vector operations
|
||||
- **Memory Management**: Efficient allocation and alignment
|
||||
- **Math Kernels**: Optimized dot products, distances, norms
|
||||
- **Platform Abstractions**: CPU feature detection, WASM support
|
||||
|
||||
```rust
|
||||
use ruvector_core::{SimdVector, Distance};
|
||||
|
||||
let vec1 = SimdVector::from_slice(&[1.0, 2.0, 3.0, 4.0]);
|
||||
let vec2 = SimdVector::from_slice(&[4.0, 3.0, 2.0, 1.0]);
|
||||
let distance = vec1.euclidean_distance(&vec2);
|
||||
```
|
||||
|
||||
**Use Cases**: Building custom vector operations, low-level optimization
|
||||
|
||||
---
|
||||
|
||||
#### ruvector-graph
|
||||
**Graph database with vector embeddings**
|
||||
|
||||
- **Property Graphs**: Nodes and edges with arbitrary properties
|
||||
- **Vector Embeddings**: Associate embeddings with graph elements
|
||||
- **Graph Queries**: Traversal, pattern matching, shortest paths
|
||||
- **Persistence**: Efficient storage and retrieval
|
||||
|
||||
```rust
|
||||
use ruvector_graph::{Graph, Node, Edge};
|
||||
|
||||
let mut graph = Graph::new();
|
||||
let node1 = graph.add_node_with_embedding(
|
||||
"user_123",
|
||||
&[0.1, 0.2, 0.3], // User embedding
|
||||
);
|
||||
```
|
||||
|
||||
**Use Cases**: Knowledge graphs, social networks, recommendation systems
|
||||
|
||||
---
|
||||
|
||||
#### ruvector-index
|
||||
**High-performance vector indexing**
|
||||
|
||||
- **Multiple Algorithms**: HNSW, IVF, Product Quantization
|
||||
- **Hybrid Search**: Combine vector similarity with filters
|
||||
- **Scalability**: Billions of vectors, sub-millisecond queries
|
||||
- **Incremental Updates**: Add/remove vectors dynamically
|
||||
|
||||
```rust
|
||||
use ruvector_index::{HnswIndex, IndexConfig};
|
||||
|
||||
let config = IndexConfig::default()
|
||||
.with_ef_construction(200)
|
||||
.with_m(16);
|
||||
let index = HnswIndex::new(config);
|
||||
```
|
||||
|
||||
**Use Cases**: Semantic search, image retrieval, deduplication
|
||||
|
||||
---
|
||||
|
||||
#### ruvector-mincut
|
||||
**Graph partitioning and min-cut algorithms (this crate)**
|
||||
|
||||
- **Min-Cut Algorithms**: Karger, Stoer-Wagner, Gomory-Hu
|
||||
- **Graph Partitioning**: Balanced cuts, hierarchical decomposition
|
||||
- **Connectivity Analysis**: Edge connectivity, cut enumeration
|
||||
- **WASM/Node Bindings**: Deploy anywhere
|
||||
|
||||
```rust
|
||||
use ruvector_mincut::{Graph, karger_min_cut};
|
||||
|
||||
let graph = Graph::from_edges(&[(0, 1), (1, 2), (2, 0)]);
|
||||
let (cut_value, partition) = karger_min_cut(&graph, 1000);
|
||||
```
|
||||
|
||||
**Use Cases**: Network analysis, community detection, circuit design
|
||||
|
||||
---
|
||||
|
||||
#### ruvector-attention
|
||||
**Attention mechanisms for transformers**
|
||||
|
||||
- **Multi-Head Attention**: Self-attention, cross-attention
|
||||
- **Optimized Kernels**: Flash Attention, memory-efficient attention
|
||||
- **Position Encodings**: Rotary, ALiBi, learned embeddings
|
||||
- **Masking Support**: Causal, bidirectional, custom masks
|
||||
|
||||
```rust
|
||||
use ruvector_attention::{MultiHeadAttention, AttentionConfig};
|
||||
|
||||
let config = AttentionConfig::new(512, 8); // 512 dim, 8 heads
|
||||
let mha = MultiHeadAttention::new(config);
|
||||
let output = mha.forward(&query, &key, &value, mask);
|
||||
```
|
||||
|
||||
**Use Cases**: Transformers, language models, vision transformers
|
||||
|
||||
---
|
||||
|
||||
#### ruvector-gnn
|
||||
**Graph Neural Networks**
|
||||
|
||||
- **GNN Layers**: GCN, GAT, GraphSAGE, GIN
|
||||
- **Message Passing**: Efficient aggregation on large graphs
|
||||
- **Heterogeneous Graphs**: Multiple node/edge types
|
||||
- **Temporal Graphs**: Dynamic graph learning
|
||||
|
||||
```rust
|
||||
use ruvector_gnn::{GCNLayer, GraphConvolution};
|
||||
|
||||
let gcn = GCNLayer::new(128, 64); // 128 -> 64 dimensions
|
||||
let node_embeddings = gcn.forward(&graph, &features);
|
||||
```
|
||||
|
||||
**Use Cases**: Node classification, link prediction, graph classification
|
||||
|
||||
---
|
||||
|
||||
## ruvector-mincut Bindings
|
||||
|
||||
### ruvector-mincut-wasm
|
||||
**Browser and Edge Deployment**
|
||||
|
||||
Compile min-cut algorithms to WebAssembly for client-side execution.
|
||||
|
||||
```javascript
|
||||
import init, { Graph, karger_min_cut } from 'ruvector-mincut-wasm';
|
||||
|
||||
await init();
|
||||
const graph = new Graph();
|
||||
graph.add_edge(0, 1, 1.0);
|
||||
graph.add_edge(1, 2, 1.0);
|
||||
graph.add_edge(2, 0, 1.0);
|
||||
|
||||
const result = karger_min_cut(graph, 1000);
|
||||
console.log('Min cut:', result.cut_value);
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Zero-copy data transfer
|
||||
- TypeScript definitions
|
||||
- Compatible with all major browsers
|
||||
- Cloudflare Workers, Deno Deploy support
|
||||
|
||||
**Installation:**
|
||||
```bash
|
||||
npm install ruvector-mincut-wasm
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### ruvector-mincut-node
|
||||
**Node.js Native Addon**
|
||||
|
||||
Native Node.js bindings using N-API for maximum performance.
|
||||
|
||||
```javascript
|
||||
const { Graph, kargerMinCut } = require('ruvector-mincut-node');
|
||||
|
||||
const graph = new Graph();
|
||||
graph.addEdge(0, 1, 1.0);
|
||||
graph.addEdge(1, 2, 1.0);
|
||||
|
||||
const result = kargerMinCut(graph, { iterations: 1000 });
|
||||
console.log('Cut value:', result.cutValue);
|
||||
console.log('Partition:', result.partition);
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Native performance (C++ speeds)
|
||||
- Async support with Tokio
|
||||
- Stream processing
|
||||
- Cross-platform (Linux, macOS, Windows)
|
||||
|
||||
**Installation:**
|
||||
```bash
|
||||
npm install ruvector-mincut-node
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Midstream Integration
|
||||
|
||||
**Midstream** is ruv.io's low-latency streaming platform for real-time data processing.
|
||||
|
||||
### Real-Time Graph Updates
|
||||
|
||||
Process streaming graph updates and maintain min-cut information dynamically.
|
||||
|
||||
```rust
|
||||
use ruvector_mincut::incremental::IncrementalMinCut;
|
||||
use midstream::{Stream, StreamProcessor};
|
||||
|
||||
struct MinCutProcessor {
|
||||
min_cut: IncrementalMinCut,
|
||||
}
|
||||
|
||||
impl StreamProcessor for MinCutProcessor {
|
||||
type Input = GraphUpdate;
|
||||
type Output = CutMetrics;
|
||||
|
||||
fn process(&mut self, update: GraphUpdate) -> CutMetrics {
|
||||
match update {
|
||||
GraphUpdate::AddEdge(u, v, w) => {
|
||||
self.min_cut.add_edge(u, v, w);
|
||||
}
|
||||
GraphUpdate::RemoveEdge(u, v) => {
|
||||
self.min_cut.remove_edge(u, v);
|
||||
}
|
||||
}
|
||||
|
||||
CutMetrics {
|
||||
current_min_cut: self.min_cut.current_value(),
|
||||
connectivity: self.min_cut.edge_connectivity(),
|
||||
timestamp: SystemTime::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Event Sourcing Patterns
|
||||
|
||||
Store graph mutations as events for replay and analysis.
|
||||
|
||||
```rust
|
||||
use ruvector_mincut::Graph;
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GraphEvent {
|
||||
EdgeAdded { u: u32, v: u32, weight: f64, timestamp: u64 },
|
||||
EdgeRemoved { u: u32, v: u32, timestamp: u64 },
|
||||
WeightUpdated { u: u32, v: u32, new_weight: f64, timestamp: u64 },
|
||||
}
|
||||
|
||||
fn replay_events(events: &[GraphEvent]) -> Graph {
|
||||
let mut graph = Graph::new();
|
||||
|
||||
for event in events {
|
||||
match event {
|
||||
GraphEvent::EdgeAdded { u, v, weight, .. } => {
|
||||
graph.add_edge(*u, *v, *weight);
|
||||
}
|
||||
GraphEvent::EdgeRemoved { u, v, .. } => {
|
||||
graph.remove_edge(*u, *v);
|
||||
}
|
||||
GraphEvent::WeightUpdated { u, v, new_weight, .. } => {
|
||||
graph.update_edge_weight(*u, *v, *new_weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
graph
|
||||
}
|
||||
```
|
||||
|
||||
### Streaming Analytics
|
||||
|
||||
Combine with Midstream for continuous analytics pipelines.
|
||||
|
||||
```rust
|
||||
// Windowed min-cut analysis
|
||||
let stream = midstream::connect("graph-updates")
|
||||
.window(Duration::from_secs(60))
|
||||
.map(|window| {
|
||||
let graph = build_graph_from_window(window);
|
||||
let (cut_value, partition) = karger_min_cut(&graph, 1000);
|
||||
|
||||
AnalyticsResult {
|
||||
window_start: window.start_time,
|
||||
window_end: window.end_time,
|
||||
min_cut: cut_value,
|
||||
largest_component: partition.largest_size(),
|
||||
}
|
||||
})
|
||||
.into_stream();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Advanced Integrations
|
||||
|
||||
### Combining with GNN for Learned Cut Prediction
|
||||
|
||||
Use Graph Neural Networks to predict good cuts before running expensive algorithms.
|
||||
|
||||
```rust
|
||||
use ruvector_gnn::{GCNLayer, GraphConvolution};
|
||||
use ruvector_mincut::{Graph, stoer_wagner};
|
||||
|
||||
struct LearnedCutPredictor {
|
||||
gcn: GCNLayer,
|
||||
}
|
||||
|
||||
impl LearnedCutPredictor {
|
||||
/// Predict edge importance for cutting
|
||||
fn predict_edge_scores(&self, graph: &Graph) -> Vec<f64> {
|
||||
// Extract graph features
|
||||
let features = extract_node_features(graph);
|
||||
|
||||
// Run GNN
|
||||
let embeddings = self.gcn.forward(graph, &features);
|
||||
|
||||
// Compute edge scores from node embeddings
|
||||
compute_edge_scores(graph, &embeddings)
|
||||
}
|
||||
|
||||
/// Use learned scores to guide min-cut search
|
||||
fn guided_min_cut(&self, graph: &Graph) -> (f64, Vec<u32>) {
|
||||
let edge_scores = self.predict_edge_scores(graph);
|
||||
|
||||
// Weight edges by predicted importance
|
||||
let weighted_graph = graph.with_edge_weights(&edge_scores);
|
||||
|
||||
// Run min-cut on weighted graph
|
||||
stoer_wagner(&weighted_graph)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- Faster convergence for large graphs
|
||||
- Learn domain-specific patterns
|
||||
- Reduce computational cost by 10-100x
|
||||
|
||||
---
|
||||
|
||||
### Vector Similarity for Edge Weighting
|
||||
|
||||
Use vector embeddings to compute semantic edge weights.
|
||||
|
||||
```rust
|
||||
use ruvector_core::{SimdVector, Distance};
|
||||
use ruvector_index::HnswIndex;
|
||||
use ruvector_mincut::Graph;
|
||||
|
||||
fn build_similarity_graph(
|
||||
embeddings: &[Vec<f32>],
|
||||
k: usize, // k-nearest neighbors
|
||||
threshold: f64,
|
||||
) -> Graph {
|
||||
let mut index = HnswIndex::new(IndexConfig::default());
|
||||
|
||||
// Index all embeddings
|
||||
for (i, emb) in embeddings.iter().enumerate() {
|
||||
index.add(i as u32, emb);
|
||||
}
|
||||
|
||||
let mut graph = Graph::new();
|
||||
|
||||
// Connect k-nearest neighbors
|
||||
for (i, emb) in embeddings.iter().enumerate() {
|
||||
let neighbors = index.search(emb, k);
|
||||
|
||||
for (j, distance) in neighbors {
|
||||
if distance < threshold {
|
||||
// Convert distance to similarity weight
|
||||
let weight = 1.0 / (1.0 + distance);
|
||||
graph.add_edge(i as u32, j, weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
graph
|
||||
}
|
||||
```
|
||||
|
||||
**Use Cases:**
|
||||
- Document clustering
|
||||
- Image segmentation
|
||||
- Recommendation systems
|
||||
|
||||
---
|
||||
|
||||
### Attention-Weighted Graphs
|
||||
|
||||
Use attention scores to create dynamic graph structures.
|
||||
|
||||
```rust
|
||||
use ruvector_attention::{MultiHeadAttention, AttentionConfig};
|
||||
use ruvector_mincut::Graph;
|
||||
|
||||
fn attention_to_graph(
|
||||
nodes: &[Vec<f32>],
|
||||
attention_heads: usize,
|
||||
) -> Graph {
|
||||
let dim = nodes[0].len();
|
||||
let config = AttentionConfig::new(dim, attention_heads);
|
||||
let mha = MultiHeadAttention::new(config);
|
||||
|
||||
// Compute attention weights
|
||||
let attention_weights = mha.compute_attention_weights(nodes, nodes);
|
||||
|
||||
// Build graph from attention
|
||||
let mut graph = Graph::new();
|
||||
|
||||
for (i, weights) in attention_weights.iter().enumerate() {
|
||||
for (j, &weight) in weights.iter().enumerate() {
|
||||
if i != j && weight > 0.1 { // Threshold
|
||||
graph.add_edge(i as u32, j as u32, weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
graph
|
||||
}
|
||||
```
|
||||
|
||||
**Applications:**
|
||||
- Transformer attention analysis
|
||||
- Neural architecture search
|
||||
- Interpretability studies
|
||||
|
||||
---
|
||||
|
||||
### Multi-Modal Graph Analysis
|
||||
|
||||
Combine multiple RuVector crates for comprehensive analysis.
|
||||
|
||||
```rust
|
||||
use ruvector_graph::Graph as PropertyGraph;
|
||||
use ruvector_index::HnswIndex;
|
||||
use ruvector_mincut::{Graph as MinCutGraph, hierarchical_partition};
|
||||
use ruvector_gnn::GCNLayer;
|
||||
|
||||
struct MultiModalAnalyzer {
|
||||
property_graph: PropertyGraph,
|
||||
vector_index: HnswIndex,
|
||||
gnn: GCNLayer,
|
||||
}
|
||||
|
||||
impl MultiModalAnalyzer {
|
||||
fn analyze(&self) -> AnalysisResult {
|
||||
// 1. Extract topology for min-cut
|
||||
let topology = self.property_graph.to_topology();
|
||||
let mincut_graph = MinCutGraph::from_edges(&topology.edges);
|
||||
|
||||
// 2. Hierarchical partitioning
|
||||
let hierarchy = hierarchical_partition(&mincut_graph, 4);
|
||||
|
||||
// 3. For each partition, run GNN
|
||||
let mut partition_embeddings = Vec::new();
|
||||
|
||||
for partition in hierarchy.partitions {
|
||||
let subgraph = self.property_graph.subgraph(&partition);
|
||||
let features = extract_features(&subgraph);
|
||||
let embeddings = self.gnn.forward(&subgraph, &features);
|
||||
partition_embeddings.push(embeddings);
|
||||
}
|
||||
|
||||
// 4. Index partition representatives
|
||||
for (i, emb) in partition_embeddings.iter().enumerate() {
|
||||
self.vector_index.add(i as u32, &emb.mean());
|
||||
}
|
||||
|
||||
AnalysisResult {
|
||||
hierarchy,
|
||||
embeddings: partition_embeddings,
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ruv.io Platform
|
||||
|
||||
The ruv.io platform provides cloud services and infrastructure for deploying RuVector applications.
|
||||
|
||||
### Cloud Deployment Options
|
||||
|
||||
#### Serverless Functions
|
||||
Deploy min-cut algorithms as serverless functions.
|
||||
|
||||
```yaml
|
||||
# ruv.yml
|
||||
service: graph-analytics
|
||||
runtime: rust
|
||||
memory: 2048
|
||||
|
||||
functions:
|
||||
compute-mincut:
|
||||
handler: ruvector_mincut::handler
|
||||
timeout: 30
|
||||
events:
|
||||
- http:
|
||||
path: /mincut
|
||||
method: post
|
||||
```
|
||||
|
||||
#### Managed Graph Database
|
||||
Use ruv.io's managed graph database with built-in min-cut support.
|
||||
|
||||
```rust
|
||||
use ruvio_client::{GraphClient, MinCutOptions};
|
||||
|
||||
let client = GraphClient::connect("https://api.ruv.io").await?;
|
||||
|
||||
// Upload graph
|
||||
client.create_graph("my-network").await?;
|
||||
client.batch_add_edges("my-network", &edges).await?;
|
||||
|
||||
// Compute min-cut in cloud
|
||||
let result = client.compute_mincut("my-network", MinCutOptions {
|
||||
algorithm: "stoer-wagner",
|
||||
iterations: 1000,
|
||||
}).await?;
|
||||
```
|
||||
|
||||
#### API Services
|
||||
|
||||
**REST API:**
|
||||
```bash
|
||||
curl -X POST https://api.ruv.io/v1/mincut \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"graph": {
|
||||
"edges": [[0, 1, 1.0], [1, 2, 1.0], [2, 0, 1.0]]
|
||||
},
|
||||
"algorithm": "karger",
|
||||
"iterations": 1000
|
||||
}'
|
||||
```
|
||||
|
||||
**GraphQL API:**
|
||||
```graphql
|
||||
mutation ComputeMinCut {
|
||||
computeMinCut(
|
||||
graphId: "my-network"
|
||||
algorithm: STOER_WAGNER
|
||||
) {
|
||||
cutValue
|
||||
partition {
|
||||
setA
|
||||
setB
|
||||
}
|
||||
executionTime
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Infrastructure Features
|
||||
|
||||
- **Auto-scaling**: Handle traffic spikes automatically
|
||||
- **Global CDN**: Low-latency access worldwide
|
||||
- **Monitoring**: Built-in metrics and tracing
|
||||
- **High Availability**: 99.99% uptime SLA
|
||||
- **Security**: SOC 2 Type II, GDPR compliant
|
||||
|
||||
### Documentation & Support
|
||||
|
||||
- **API Documentation**: https://ruv.io/docs/api
|
||||
- **Tutorials**: https://ruv.io/tutorials
|
||||
- **Community Forum**: https://community.ruv.io
|
||||
- **Enterprise Support**: support@ruv.io
|
||||
|
||||
---
|
||||
|
||||
## Ecosystem Architecture
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "Core Layer"
|
||||
CORE[ruvector-core<br/>SIMD Primitives]
|
||||
end
|
||||
|
||||
subgraph "Data Structures"
|
||||
GRAPH[ruvector-graph<br/>Property Graph]
|
||||
INDEX[ruvector-index<br/>Vector Index]
|
||||
MINCUT[ruvector-mincut<br/>Graph Partitioning]
|
||||
end
|
||||
|
||||
subgraph "ML Layer"
|
||||
ATTENTION[ruvector-attention<br/>Transformers]
|
||||
GNN[ruvector-gnn<br/>Graph Neural Networks]
|
||||
end
|
||||
|
||||
subgraph "Bindings"
|
||||
WASM[ruvector-mincut-wasm<br/>Browser]
|
||||
NODE[ruvector-mincut-node<br/>Node.js]
|
||||
end
|
||||
|
||||
subgraph "Platform"
|
||||
MIDSTREAM[Midstream<br/>Streaming]
|
||||
RUVIO[ruv.io<br/>Cloud Platform]
|
||||
end
|
||||
|
||||
subgraph "Applications"
|
||||
WEB[Web Apps]
|
||||
SERVER[Server Apps]
|
||||
CLOUD[Cloud Services]
|
||||
end
|
||||
|
||||
CORE --> GRAPH
|
||||
CORE --> INDEX
|
||||
CORE --> MINCUT
|
||||
CORE --> ATTENTION
|
||||
CORE --> GNN
|
||||
|
||||
GRAPH --> MINCUT
|
||||
INDEX --> GRAPH
|
||||
GNN --> GRAPH
|
||||
ATTENTION --> GNN
|
||||
|
||||
MINCUT --> WASM
|
||||
MINCUT --> NODE
|
||||
MINCUT --> MIDSTREAM
|
||||
|
||||
WASM --> WEB
|
||||
NODE --> SERVER
|
||||
MIDSTREAM --> CLOUD
|
||||
MINCUT --> RUVIO
|
||||
GRAPH --> RUVIO
|
||||
INDEX --> RUVIO
|
||||
|
||||
style MINCUT fill:#ff6b6b,stroke:#c92a2a,stroke-width:3px
|
||||
style CORE fill:#4dabf7,stroke:#1971c2,stroke-width:2px
|
||||
style RUVIO fill:#51cf66,stroke:#2f9e44,stroke-width:2px
|
||||
```
|
||||
|
||||
### Data Flow Example
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant App as Application
|
||||
participant Index as ruvector-index
|
||||
participant Graph as ruvector-graph
|
||||
participant MinCut as ruvector-mincut
|
||||
participant GNN as ruvector-gnn
|
||||
participant Platform as ruv.io
|
||||
|
||||
App->>Index: Query similar nodes
|
||||
Index-->>App: k-nearest neighbors
|
||||
|
||||
App->>Graph: Build subgraph
|
||||
Graph->>MinCut: Extract topology
|
||||
MinCut-->>Graph: Partition graph
|
||||
|
||||
Graph->>GNN: Train on partitions
|
||||
GNN-->>App: Node embeddings
|
||||
|
||||
App->>Platform: Deploy model
|
||||
Platform-->>App: Inference endpoint
|
||||
```
|
||||
|
||||
### Deployment Options
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "Development"
|
||||
DEV[Local Development]
|
||||
end
|
||||
|
||||
subgraph "Edge"
|
||||
BROWSER[Browser<br/>WASM]
|
||||
EDGE[Edge Workers<br/>WASM]
|
||||
end
|
||||
|
||||
subgraph "Server"
|
||||
NODEJS[Node.js<br/>Native]
|
||||
RUST[Rust Service<br/>Native]
|
||||
end
|
||||
|
||||
subgraph "Cloud"
|
||||
LAMBDA[Serverless<br/>ruv.io]
|
||||
MANAGED[Managed Service<br/>ruv.io]
|
||||
end
|
||||
|
||||
DEV --> BROWSER
|
||||
DEV --> EDGE
|
||||
DEV --> NODEJS
|
||||
DEV --> RUST
|
||||
DEV --> LAMBDA
|
||||
DEV --> MANAGED
|
||||
|
||||
style DEV fill:#fab005,stroke:#f08c00
|
||||
style BROWSER fill:#4dabf7,stroke:#1971c2
|
||||
style EDGE fill:#4dabf7,stroke:#1971c2
|
||||
style NODEJS fill:#51cf66,stroke:#2f9e44
|
||||
style RUST fill:#51cf66,stroke:#2f9e44
|
||||
style LAMBDA fill:#ff6b6b,stroke:#c92a2a
|
||||
style MANAGED fill:#ff6b6b,stroke:#c92a2a
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Resources
|
||||
|
||||
### Official Links
|
||||
|
||||
- **Website**: [ruv.io](https://ruv.io)
|
||||
- **GitHub Organization**: [github.com/ruvnet](https://github.com/ruvnet)
|
||||
- **Main Repository**: [github.com/ruvnet/ruvector](https://github.com/ruvnet/ruvector)
|
||||
|
||||
### Crates.io Pages
|
||||
|
||||
- [ruvector-core](https://crates.io/crates/ruvector-core)
|
||||
- [ruvector-graph](https://crates.io/crates/ruvector-graph)
|
||||
- [ruvector-index](https://crates.io/crates/ruvector-index)
|
||||
- [ruvector-mincut](https://crates.io/crates/ruvector-mincut)
|
||||
- [ruvector-attention](https://crates.io/crates/ruvector-attention)
|
||||
- [ruvector-gnn](https://crates.io/crates/ruvector-gnn)
|
||||
|
||||
### NPM Packages
|
||||
|
||||
- [ruvector-mincut-wasm](https://www.npmjs.com/package/ruvector-mincut-wasm)
|
||||
- [ruvector-mincut-node](https://www.npmjs.com/package/ruvector-mincut-node)
|
||||
|
||||
### Documentation
|
||||
|
||||
- **API Docs**: [docs.ruv.io](https://docs.ruv.io)
|
||||
- **Tutorials**: [ruv.io/tutorials](https://ruv.io/tutorials)
|
||||
- **Examples**: [github.com/ruvnet/ruvector/tree/main/examples](https://github.com/ruvnet/ruvector/tree/main/examples)
|
||||
|
||||
### Community
|
||||
|
||||
- **Discord**: [discord.gg/ruvector](https://discord.gg/ruvector)
|
||||
- **Forum**: [community.ruv.io](https://community.ruv.io)
|
||||
- **Twitter**: [@ruvnet](https://twitter.com/ruvnet)
|
||||
- **Blog**: [ruv.io/blog](https://ruv.io/blog)
|
||||
|
||||
### Support
|
||||
|
||||
- **Issues**: [github.com/ruvnet/ruvector/issues](https://github.com/ruvnet/ruvector/issues)
|
||||
- **Discussions**: [github.com/ruvnet/ruvector/discussions](https://github.com/ruvnet/ruvector/discussions)
|
||||
- **Enterprise Support**: enterprise@ruv.io
|
||||
- **Security Issues**: security@ruv.io
|
||||
|
||||
---
|
||||
|
||||
## Getting Started with the Ecosystem
|
||||
|
||||
### 1. Start with Core
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ruvector-core = "0.1"
|
||||
```
|
||||
|
||||
```rust
|
||||
use ruvector_core::SimdVector;
|
||||
|
||||
let vec = SimdVector::from_slice(&[1.0, 2.0, 3.0, 4.0]);
|
||||
```
|
||||
|
||||
### 2. Add Graph Capabilities
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ruvector-core = "0.1"
|
||||
ruvector-graph = "0.1"
|
||||
ruvector-mincut = "0.1"
|
||||
```
|
||||
|
||||
```rust
|
||||
use ruvector_graph::Graph;
|
||||
use ruvector_mincut::karger_min_cut;
|
||||
|
||||
let graph = Graph::from_edges(&[(0, 1), (1, 2), (2, 0)]);
|
||||
let (cut, partition) = karger_min_cut(&graph, 1000);
|
||||
```
|
||||
|
||||
### 3. Add ML Features
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ruvector-core = "0.1"
|
||||
ruvector-graph = "0.1"
|
||||
ruvector-gnn = "0.1"
|
||||
```
|
||||
|
||||
```rust
|
||||
use ruvector_gnn::GCNLayer;
|
||||
|
||||
let gcn = GCNLayer::new(128, 64);
|
||||
let embeddings = gcn.forward(&graph, &features);
|
||||
```
|
||||
|
||||
### 4. Deploy to Cloud
|
||||
|
||||
```bash
|
||||
# Install ruv.io CLI
|
||||
cargo install ruvio-cli
|
||||
|
||||
# Login
|
||||
ruvio login
|
||||
|
||||
# Deploy
|
||||
ruvio deploy --service graph-analytics
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
- **Explore Examples**: Check out the [examples directory](https://github.com/ruvnet/ruvector/tree/main/examples)
|
||||
- **Join Community**: Connect with other developers on [Discord](https://discord.gg/ruvector)
|
||||
- **Read Tutorials**: Learn patterns at [ruv.io/tutorials](https://ruv.io/tutorials)
|
||||
- **Try Cloud**: Sign up for [ruv.io platform](https://ruv.io/signup)
|
||||
|
||||
---
|
||||
|
||||
**The RuVector ecosystem provides everything you need to build high-performance graph and vector applications, from edge to cloud.**
|
||||
1037
vendor/ruvector/crates/ruvector-mincut/docs/guide/07-api-reference.md
vendored
Normal file
1037
vendor/ruvector/crates/ruvector-mincut/docs/guide/07-api-reference.md
vendored
Normal file
File diff suppressed because it is too large
Load Diff
559
vendor/ruvector/crates/ruvector-mincut/docs/guide/08-troubleshooting.md
vendored
Normal file
559
vendor/ruvector/crates/ruvector-mincut/docs/guide/08-troubleshooting.md
vendored
Normal file
@@ -0,0 +1,559 @@
|
||||
# Troubleshooting Guide
|
||||
|
||||
[← Back to Index](README.md) | [Previous: API Reference](07-api-reference.md)
|
||||
|
||||
---
|
||||
|
||||
## Quick Diagnosis Flowchart
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[Issue Encountered] --> B{Type of Issue?}
|
||||
|
||||
B -->|Compilation| C[Compilation Errors]
|
||||
B -->|Runtime| D[Runtime Errors]
|
||||
B -->|Performance| E[Performance Issues]
|
||||
B -->|Results| F[Unexpected Results]
|
||||
|
||||
C --> C1[Check feature flags]
|
||||
C --> C2[Version compatibility]
|
||||
C --> C3[Missing dependencies]
|
||||
|
||||
D --> D1[Memory issues]
|
||||
D --> D2[Edge not found]
|
||||
D --> D3[Graph disconnected]
|
||||
|
||||
E --> E1[Algorithm selection]
|
||||
E --> E2[Graph size tuning]
|
||||
E --> E3[Caching strategies]
|
||||
|
||||
F --> F1[Verify graph construction]
|
||||
F --> F2[Check edge weights]
|
||||
F --> F3[Understand approximation]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 1. Compilation Errors
|
||||
|
||||
### Feature Flag Issues
|
||||
|
||||
**Error**: `use of undeclared type MonitorBuilder`
|
||||
|
||||
```
|
||||
error[E0433]: failed to resolve: use of undeclared type `MonitorBuilder`
|
||||
```
|
||||
|
||||
**Solution**: Enable the `monitoring` feature:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ruvector-mincut = { version = "0.2", features = ["monitoring"] }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Error**: `use of undeclared type CompactCoreState`
|
||||
|
||||
**Solution**: Enable the `agentic` feature:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ruvector-mincut = { version = "0.2", features = ["agentic"] }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Feature Flag Reference
|
||||
|
||||
| Type/Feature | Required Feature Flag |
|
||||
|--------------|----------------------|
|
||||
| `MonitorBuilder`, `MinCutMonitor` | `monitoring` |
|
||||
| `CompactCoreState`, `BitSet256` | `agentic` |
|
||||
| `SparseGraph` | `approximate` |
|
||||
| SIMD optimizations | `simd` |
|
||||
| WASM support | `wasm` |
|
||||
|
||||
### Version Compatibility
|
||||
|
||||
**Error**: `the trait bound is not satisfied`
|
||||
|
||||
Check your dependency versions are compatible:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
ruvector-mincut = "0.2"
|
||||
ruvector-core = "0.1.2" # Must be compatible
|
||||
ruvector-graph = "0.1.2" # If using integration feature
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Runtime Errors
|
||||
|
||||
### EdgeExists Error
|
||||
|
||||
**Error**: `EdgeExists(1, 2)` when inserting an edge
|
||||
|
||||
```rust
|
||||
// ❌ This will fail - edge already exists
|
||||
mincut.insert_edge(1, 2, 1.0)?;
|
||||
mincut.insert_edge(1, 2, 2.0)?; // Error!
|
||||
```
|
||||
|
||||
**Solution**: Check if edge exists first, or delete before reinserting:
|
||||
|
||||
```rust
|
||||
// ✅ Option 1: Delete first
|
||||
let _ = mincut.delete_edge(1, 2); // Ignore if not found
|
||||
mincut.insert_edge(1, 2, 2.0)?;
|
||||
|
||||
// ✅ Option 2: Check existence (if your API supports it)
|
||||
if !mincut.has_edge(1, 2) {
|
||||
mincut.insert_edge(1, 2, 1.0)?;
|
||||
}
|
||||
```
|
||||
|
||||
### EdgeNotFound Error
|
||||
|
||||
**Error**: `EdgeNotFound(3, 4)` when deleting
|
||||
|
||||
```rust
|
||||
// ❌ Edge doesn't exist
|
||||
mincut.delete_edge(3, 4)?; // Error!
|
||||
```
|
||||
|
||||
**Solution**: Use pattern matching to handle gracefully:
|
||||
|
||||
```rust
|
||||
// ✅ Handle gracefully
|
||||
match mincut.delete_edge(3, 4) {
|
||||
Ok(new_cut) => println!("New min cut: {}", new_cut),
|
||||
Err(MinCutError::EdgeNotFound(_, _)) => {
|
||||
println!("Edge already removed, continuing...");
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
```
|
||||
|
||||
### Disconnected Graph
|
||||
|
||||
**Issue**: Min cut value is 0
|
||||
|
||||
```rust
|
||||
let mincut = MinCutBuilder::new()
|
||||
.with_edges(vec![
|
||||
(1, 2, 1.0),
|
||||
(3, 4, 1.0), // Separate component!
|
||||
])
|
||||
.build()?;
|
||||
|
||||
assert_eq!(mincut.min_cut_value(), 0.0); // Zero because disconnected
|
||||
```
|
||||
|
||||
**Solution**: Ensure your graph is connected, or handle disconnected case:
|
||||
|
||||
```rust
|
||||
if !mincut.is_connected() {
|
||||
println!("Warning: Graph has {} components",
|
||||
mincut.component_count());
|
||||
// Handle each component separately
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Performance Issues
|
||||
|
||||
### Slow Insert/Delete Operations
|
||||
|
||||
**Symptom**: Operations taking longer than expected
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Slow Operations] --> B{Check Graph Size}
|
||||
B -->|< 10K vertices| C[Normal - check algorithm]
|
||||
B -->|10K-100K| D[Consider approximate mode]
|
||||
B -->|> 100K| E[Use ApproxMinCut]
|
||||
```
|
||||
|
||||
**Solutions**:
|
||||
|
||||
1. **Use approximate mode for large graphs**:
|
||||
```rust
|
||||
// Instead of exact mode
|
||||
let mincut = MinCutBuilder::new()
|
||||
.approximate(0.1) // 10% approximation
|
||||
.with_edges(edges)
|
||||
.build()?;
|
||||
```
|
||||
|
||||
2. **Use batch operations**:
|
||||
```rust
|
||||
// ❌ Slow - many individual operations
|
||||
for (u, v, w) in edges {
|
||||
mincut.insert_edge(u, v, w)?;
|
||||
}
|
||||
|
||||
// ✅ Fast - batch operation
|
||||
mincut.batch_insert_edges(&edges);
|
||||
```
|
||||
|
||||
3. **For worst-case guarantees, use PolylogConnectivity**:
|
||||
```rust
|
||||
// O(log³ n) worst-case per operation
|
||||
let mut conn = PolylogConnectivity::new();
|
||||
for (u, v) in edges {
|
||||
conn.insert_edge(u, v);
|
||||
}
|
||||
```
|
||||
|
||||
### Memory Issues
|
||||
|
||||
**Symptom**: High memory usage or OOM errors
|
||||
|
||||
**Solutions**:
|
||||
|
||||
1. **Use approximate mode** (reduces edges via sparsification):
|
||||
```rust
|
||||
let mincut = MinCutBuilder::new()
|
||||
.approximate(0.1) // Sparsifies to O(n log n / ε²) edges
|
||||
.build()?;
|
||||
```
|
||||
|
||||
2. **For WASM/embedded, use compact structures**:
|
||||
```rust
|
||||
#[cfg(feature = "agentic")]
|
||||
{
|
||||
// 6.7KB per core - verified at compile time
|
||||
let state = CompactCoreState::new();
|
||||
}
|
||||
```
|
||||
|
||||
3. **Process in batches for very large graphs**:
|
||||
```rust
|
||||
// Process graph in chunks
|
||||
for chunk in graph_chunks.iter() {
|
||||
let partial = MinCutBuilder::new()
|
||||
.with_edges(chunk)
|
||||
.build()?;
|
||||
// Aggregate results
|
||||
}
|
||||
```
|
||||
|
||||
### Query Performance
|
||||
|
||||
**Symptom**: `min_cut_value()` is slow
|
||||
|
||||
**Explanation**: First query triggers computation; subsequent queries are O(1):
|
||||
|
||||
```rust
|
||||
let mincut = MinCutBuilder::new()
|
||||
.with_edges(edges)
|
||||
.build()?;
|
||||
|
||||
// First query - triggers full computation
|
||||
let cut1 = mincut.min_cut_value(); // May take time
|
||||
|
||||
// Subsequent queries - O(1) cached
|
||||
let cut2 = mincut.min_cut_value(); // Instant
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Unexpected Results
|
||||
|
||||
### Min Cut Value Seems Wrong
|
||||
|
||||
**Checklist**:
|
||||
|
||||
1. **Verify edge weights are correct**:
|
||||
```rust
|
||||
// Weight matters! This is different from weight 1.0
|
||||
mincut.insert_edge(1, 2, 10.0)?;
|
||||
```
|
||||
|
||||
2. **Check for duplicate edges** (weights accumulate):
|
||||
```rust
|
||||
// These DON'T accumulate - second insert fails
|
||||
mincut.insert_edge(1, 2, 5.0)?;
|
||||
mincut.insert_edge(1, 2, 5.0)?; // Error: EdgeExists
|
||||
```
|
||||
|
||||
3. **Understand the cut definition**:
|
||||
```rust
|
||||
// Min cut = minimum total weight of edges to remove
|
||||
// to disconnect the graph
|
||||
let result = mincut.min_cut();
|
||||
println!("Cut value: {}", result.value);
|
||||
println!("Cut edges: {:?}", result.cut_edges);
|
||||
```
|
||||
|
||||
### Approximate Results Vary
|
||||
|
||||
**Issue**: Different runs give different results
|
||||
|
||||
**Explanation**: Approximate mode uses randomized sparsification:
|
||||
|
||||
```rust
|
||||
// Results may vary slightly between builds
|
||||
let mincut1 = MinCutBuilder::new()
|
||||
.approximate(0.1)
|
||||
.with_edges(edges.clone())
|
||||
.build()?;
|
||||
|
||||
let mincut2 = MinCutBuilder::new()
|
||||
.approximate(0.1)
|
||||
.with_edges(edges)
|
||||
.build()?;
|
||||
|
||||
// Values are within (1±ε) of true min cut
|
||||
// but may differ from each other
|
||||
```
|
||||
|
||||
**Solution**: Use a fixed seed if reproducibility is needed:
|
||||
|
||||
```rust
|
||||
let approx = ApproxMinCut::new(ApproxMinCutConfig {
|
||||
epsilon: 0.1,
|
||||
num_samples: 3,
|
||||
seed: 42, // Fixed seed for reproducibility
|
||||
});
|
||||
```
|
||||
|
||||
### Partition Looks Unbalanced
|
||||
|
||||
**Issue**: One side of partition has most vertices
|
||||
|
||||
**Explanation**: Minimum cut doesn't guarantee balanced partitions:
|
||||
|
||||
```rust
|
||||
let result = mincut.min_cut();
|
||||
let (s, t) = result.partition.unwrap();
|
||||
|
||||
// This is valid - min cut found the minimum edges to cut
|
||||
// Partition balance is NOT a constraint
|
||||
println!("Partition sizes: {} vs {}", s.len(), t.len());
|
||||
```
|
||||
|
||||
**Solution**: For balanced partitions, use `GraphPartitioner`:
|
||||
|
||||
```rust
|
||||
use ruvector_mincut::GraphPartitioner;
|
||||
|
||||
let partitioner = GraphPartitioner::new(graph, 2);
|
||||
let balanced = partitioner.partition(); // More balanced
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. WASM-Specific Issues
|
||||
|
||||
### WASM Build Fails
|
||||
|
||||
**Error**: `wasm32 target not installed`
|
||||
|
||||
```bash
|
||||
# Install the target
|
||||
rustup target add wasm32-unknown-unknown
|
||||
|
||||
# Build with wasm-pack
|
||||
wasm-pack build --target web
|
||||
```
|
||||
|
||||
### WASM Memory Limits
|
||||
|
||||
**Issue**: WASM running out of memory
|
||||
|
||||
**Solution**: Use compact structures and limit graph size:
|
||||
|
||||
```rust
|
||||
// Maximum recommended for WASM
|
||||
const MAX_WASM_VERTICES: usize = 50_000;
|
||||
|
||||
if vertices.len() > MAX_WASM_VERTICES {
|
||||
// Use approximate mode or process in chunks
|
||||
let mincut = MinCutBuilder::new()
|
||||
.approximate(0.2) // More aggressive sparsification
|
||||
.build()?;
|
||||
}
|
||||
```
|
||||
|
||||
### Web Worker Integration
|
||||
|
||||
**Issue**: Main thread blocking
|
||||
|
||||
**Solution**: Run min-cut computation in Web Worker:
|
||||
|
||||
```javascript
|
||||
// worker.js
|
||||
import init, { WasmMinCut } from 'ruvector-mincut-wasm';
|
||||
|
||||
self.onmessage = async (e) => {
|
||||
await init();
|
||||
const mincut = new WasmMinCut();
|
||||
// ... compute
|
||||
self.postMessage({ result: mincut.min_cut_value() });
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Node.js-Specific Issues
|
||||
|
||||
### Native Module Build Fails
|
||||
|
||||
**Error**: `node-gyp` or `napi` build errors
|
||||
|
||||
```bash
|
||||
# Ensure build tools are installed
|
||||
# On Ubuntu/Debian:
|
||||
sudo apt-get install build-essential
|
||||
|
||||
# On macOS:
|
||||
xcode-select --install
|
||||
|
||||
# On Windows:
|
||||
npm install --global windows-build-tools
|
||||
```
|
||||
|
||||
### Module Not Found
|
||||
|
||||
**Error**: `Cannot find module 'ruvector-mincut-node'`
|
||||
|
||||
```bash
|
||||
# Rebuild native modules
|
||||
npm rebuild
|
||||
|
||||
# Or reinstall
|
||||
rm -rf node_modules
|
||||
npm install
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Common Patterns That Cause Issues
|
||||
|
||||
### Anti-Pattern: Not Handling Errors
|
||||
|
||||
```rust
|
||||
// ❌ Panics on error
|
||||
let cut = mincut.insert_edge(1, 2, 1.0).unwrap();
|
||||
|
||||
// ✅ Handle errors properly
|
||||
let cut = mincut.insert_edge(1, 2, 1.0)
|
||||
.map_err(|e| {
|
||||
eprintln!("Insert failed: {}", e);
|
||||
e
|
||||
})?;
|
||||
```
|
||||
|
||||
### Anti-Pattern: Rebuilding Instead of Updating
|
||||
|
||||
```rust
|
||||
// ❌ Slow - rebuilds entire structure
|
||||
for update in updates {
|
||||
let mincut = MinCutBuilder::new()
|
||||
.with_edges(all_edges_including_update)
|
||||
.build()?;
|
||||
}
|
||||
|
||||
// ✅ Fast - incremental updates
|
||||
let mut mincut = MinCutBuilder::new()
|
||||
.with_edges(initial_edges)
|
||||
.build()?;
|
||||
|
||||
for (u, v, w) in updates {
|
||||
mincut.insert_edge(u, v, w)?;
|
||||
}
|
||||
```
|
||||
|
||||
### Anti-Pattern: Ignoring Feature Requirements
|
||||
|
||||
```rust
|
||||
// ❌ Compiles but panics at runtime if feature not enabled
|
||||
#[cfg(feature = "monitoring")]
|
||||
let monitor = MonitorBuilder::new().build();
|
||||
|
||||
// ✅ Proper feature gating
|
||||
#[cfg(feature = "monitoring")]
|
||||
{
|
||||
let monitor = MonitorBuilder::new().build();
|
||||
// Use monitor
|
||||
}
|
||||
#[cfg(not(feature = "monitoring"))]
|
||||
{
|
||||
println!("Monitoring not available - enable 'monitoring' feature");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Getting Help
|
||||
|
||||
### Debug Information
|
||||
|
||||
When reporting issues, include:
|
||||
|
||||
```rust
|
||||
// Print diagnostic info
|
||||
println!("ruvector-mincut version: {}", ruvector_mincut::VERSION);
|
||||
println!("Graph: {} vertices, {} edges",
|
||||
mincut.num_vertices(),
|
||||
mincut.num_edges());
|
||||
println!("Algorithm stats: {:?}", mincut.stats());
|
||||
```
|
||||
|
||||
### Resources
|
||||
|
||||
| Resource | URL |
|
||||
|----------|-----|
|
||||
| GitHub Issues | [github.com/ruvnet/ruvector/issues](https://github.com/ruvnet/ruvector/issues) |
|
||||
| Documentation | [docs.rs/ruvector-mincut](https://docs.rs/ruvector-mincut) |
|
||||
| Discord | [ruv.io/discord](https://ruv.io/discord) |
|
||||
| Stack Overflow | Tag: `ruvector` |
|
||||
|
||||
### Minimal Reproducible Example
|
||||
|
||||
When reporting bugs, provide:
|
||||
|
||||
```rust
|
||||
use ruvector_mincut::{MinCutBuilder, MinCutError};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Minimal code that reproduces the issue
|
||||
let mincut = MinCutBuilder::new()
|
||||
.with_edges(vec![
|
||||
// Your specific edges
|
||||
])
|
||||
.build()?;
|
||||
|
||||
// The operation that fails
|
||||
let result = mincut.min_cut_value();
|
||||
|
||||
println!("Result: {}", result);
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference: Error Codes
|
||||
|
||||
| Error | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| `EdgeExists(u, v)` | Duplicate edge insertion | Delete first or check existence |
|
||||
| `EdgeNotFound(u, v)` | Deleting non-existent edge | Use pattern matching |
|
||||
| `InvalidWeight` | Zero or negative weight | Use positive weights |
|
||||
| `GraphTooLarge` | Exceeds memory limits | Use approximate mode |
|
||||
| `NotConnected` | Graph has multiple components | Check connectivity first |
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**Still stuck?** [Open an issue](https://github.com/ruvnet/ruvector/issues/new) with your code and error message.
|
||||
|
||||
[← Back to Index](README.md)
|
||||
|
||||
</div>
|
||||
313
vendor/ruvector/crates/ruvector-mincut/docs/guide/README.md
vendored
Normal file
313
vendor/ruvector/crates/ruvector-mincut/docs/guide/README.md
vendored
Normal file
@@ -0,0 +1,313 @@
|
||||
# RuVector MinCut User Guide
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
**High-performance minimum cut algorithms for Rust, WebAssembly, and Node.js**
|
||||
|
||||
[Quick Start](#quick-start) • [Guide Sections](#guide-sections) • [API Reference](07-api-reference.md) • [Benchmarks](../BENCHMARK_REPORT.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## Welcome
|
||||
|
||||
Welcome to the official **RuVector MinCut User Guide**! This comprehensive documentation will help you master graph minimum cut algorithms and integrate them into your applications.
|
||||
|
||||
RuVector MinCut provides cutting-edge implementations of minimum cut algorithms from recent research papers (2024-2025), optimized for production use across multiple platforms. Whether you're building network reliability systems, image segmentation tools, or distributed infrastructure, this guide will help you leverage the power of efficient minimum cut computation.
|
||||
|
||||
### What You'll Learn
|
||||
|
||||
- 🚀 **Getting Started**: Installation, setup, and your first minimum cut computation
|
||||
- 🧠 **Core Concepts**: Understanding minimum cuts, connectivity, and algorithm selection
|
||||
- 💼 **Practical Applications**: Real-world use cases from network analysis to ML
|
||||
- 🔧 **Integration**: Platform-specific guides for Rust, WASM, and Node.js
|
||||
- 🎯 **Advanced Examples**: Complex workflows and optimization techniques
|
||||
- 🌐 **Ecosystem**: Leverage the full RuVector platform
|
||||
- 📚 **API Reference**: Complete API documentation
|
||||
- 🔍 **Troubleshooting**: Common issues and solutions
|
||||
|
||||
---
|
||||
|
||||
## Guide Structure
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[RuVector MinCut Guide] --> B[01: Getting Started]
|
||||
A --> C[02: Core Concepts]
|
||||
A --> D[03: Practical Applications]
|
||||
A --> E[04: Integration Guide]
|
||||
A --> F[05: Advanced Examples]
|
||||
A --> G[06: RuVector Ecosystem]
|
||||
A --> H[07: API Reference]
|
||||
A --> I[08: Troubleshooting]
|
||||
|
||||
B --> B1[Installation]
|
||||
B --> B2[Quick Start]
|
||||
B --> B3[First Cut]
|
||||
|
||||
C --> C1[Min Cut Theory]
|
||||
C --> C2[Algorithms]
|
||||
C --> C3[Performance]
|
||||
|
||||
D --> D1[Network Reliability]
|
||||
D --> D2[Image Segmentation]
|
||||
D --> D3[Clustering]
|
||||
|
||||
E --> E1[Rust Integration]
|
||||
E --> E2[WASM Integration]
|
||||
E --> E3[Node.js Integration]
|
||||
|
||||
F --> F1[Custom Workflows]
|
||||
F --> F2[Optimization]
|
||||
F --> F3[Large Graphs]
|
||||
|
||||
G --> G1[Vector Database]
|
||||
G --> G2[QUIC Sync]
|
||||
G --> G3[Platform Tools]
|
||||
|
||||
H --> H1[Rust API]
|
||||
H --> H2[WASM API]
|
||||
H --> H3[Node.js API]
|
||||
|
||||
I --> I1[Common Issues]
|
||||
I --> I2[Performance]
|
||||
I --> I3[Debugging]
|
||||
|
||||
style A fill:#4A90E2,stroke:#2E5C8A,stroke-width:3px,color:#fff
|
||||
style B fill:#50C878,stroke:#2E7D52,stroke-width:2px,color:#fff
|
||||
style C fill:#9B59B6,stroke:#6C3483,stroke-width:2px,color:#fff
|
||||
style D fill:#E67E22,stroke:#A04000,stroke-width:2px,color:#fff
|
||||
style E fill:#3498DB,stroke:#21618C,stroke-width:2px,color:#fff
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
New to RuVector MinCut? Start here:
|
||||
|
||||
1. **[Getting Started Guide](01-getting-started.md)** - Install and run your first minimum cut
|
||||
2. **[Core Concepts](02-core-concepts.md)** - Understand the fundamentals
|
||||
3. **[Integration Guide](04-integration-guide.md)** - Platform-specific setup
|
||||
|
||||
Already familiar? Jump to:
|
||||
- **[Practical Applications](03-practical-applications.md)** - Real-world examples
|
||||
- **[Advanced Examples](05-advanced-examples.md)** - Complex workflows
|
||||
- **[API Reference](07-api-reference.md)** - Complete API documentation
|
||||
|
||||
---
|
||||
|
||||
## Guide Sections
|
||||
|
||||
### 📖 [01: Getting Started](01-getting-started.md)
|
||||
|
||||
Your first steps with RuVector MinCut:
|
||||
- **Installation** - Add to your Rust, WASM, or Node.js project
|
||||
- **Quick Start** - Run your first minimum cut in minutes
|
||||
- **Basic Usage** - Simple examples to get you started
|
||||
- **Platform Setup** - Environment-specific configuration
|
||||
|
||||
**Perfect for**: New users, quick evaluation, proof-of-concept projects
|
||||
|
||||
---
|
||||
|
||||
### 🧠 [02: Core Concepts](02-core-concepts.md)
|
||||
|
||||
Deep dive into minimum cut theory and implementation:
|
||||
- **What is a Minimum Cut?** - Mathematical foundations
|
||||
- **Algorithm Overview** - Karger-Stein, Stoer-Wagner, and cutting-edge variants
|
||||
- **Connectivity Analysis** - Understanding graph structure
|
||||
- **Performance Characteristics** - Algorithm selection guide
|
||||
- **Data Structures** - Internal representations and optimizations
|
||||
|
||||
**Perfect for**: Understanding algorithm behavior, making informed choices, optimization
|
||||
|
||||
---
|
||||
|
||||
### 💼 [03: Practical Applications](03-practical-applications.md)
|
||||
|
||||
Real-world use cases and industry applications:
|
||||
- **Network Reliability** - Finding critical connections and bottlenecks
|
||||
- **Image Segmentation** - Computer vision and ML applications
|
||||
- **Community Detection** - Social network analysis
|
||||
- **Infrastructure Planning** - Cloud and distributed systems
|
||||
- **Data Clustering** - Machine learning and analytics
|
||||
- **Risk Assessment** - Financial and security applications
|
||||
|
||||
**Perfect for**: Industry applications, use case research, project planning
|
||||
|
||||
---
|
||||
|
||||
### 🔧 [04: Integration Guide](04-integration-guide.md)
|
||||
|
||||
Platform-specific integration instructions:
|
||||
- **Rust Integration** - Native library usage, features, and best practices
|
||||
- **WebAssembly** - Browser and edge deployment
|
||||
- **Node.js** - Backend and CLI applications
|
||||
- **TypeScript** - Type-safe JavaScript integration
|
||||
- **Build Configuration** - Optimization and compilation
|
||||
- **Deployment** - Production considerations
|
||||
|
||||
**Perfect for**: Production integration, platform-specific questions, deployment
|
||||
|
||||
---
|
||||
|
||||
### 🎯 [05: Advanced Examples](05-advanced-examples.md)
|
||||
|
||||
Complex workflows and optimization techniques:
|
||||
- **Large Graph Processing** - Handling millions of nodes
|
||||
- **Parallel Computation** - Multi-threaded and distributed processing
|
||||
- **Custom Workflows** - Building on top of MinCut APIs
|
||||
- **Performance Tuning** - Memory and speed optimization
|
||||
- **Hybrid Approaches** - Combining multiple algorithms
|
||||
- **Streaming Analysis** - Real-time graph updates
|
||||
|
||||
**Perfect for**: Performance optimization, large-scale systems, advanced users
|
||||
|
||||
---
|
||||
|
||||
### 🌐 [06: RuVector Ecosystem](06-ecosystem.md)
|
||||
|
||||
Leverage the complete RuVector platform:
|
||||
- **Vector Database Integration** - Combine with ruvector-db
|
||||
- **QUIC Synchronization** - Distributed graph analysis
|
||||
- **Platform Services** - Cloud deployment with ruv.io
|
||||
- **Multi-Language Support** - Cross-platform workflows
|
||||
- **Monitoring & Analytics** - Production observability
|
||||
- **Community & Support** - Resources and help
|
||||
|
||||
**Perfect for**: Platform integration, distributed systems, enterprise deployment
|
||||
|
||||
---
|
||||
|
||||
### 📚 [07: API Reference](07-api-reference.md)
|
||||
|
||||
Complete API documentation:
|
||||
- **Rust API** - Full crate documentation
|
||||
- **WASM API** - JavaScript/TypeScript bindings
|
||||
- **Node.js API** - npm package reference
|
||||
- **Type Definitions** - Complete type signatures
|
||||
- **Error Handling** - Exception types and recovery
|
||||
- **Migration Guide** - Version updates and breaking changes
|
||||
|
||||
**Perfect for**: API lookup, type checking, implementation details
|
||||
|
||||
---
|
||||
|
||||
### 🔍 [08: Troubleshooting](08-troubleshooting.md)
|
||||
|
||||
Common issues and solutions:
|
||||
- **Installation Issues** - Dependency and build problems
|
||||
- **Performance Problems** - Memory and speed optimization
|
||||
- **Algorithm Selection** - Choosing the right approach
|
||||
- **Platform-Specific Issues** - WASM, Node.js, and Rust quirks
|
||||
- **Debugging Guide** - Tools and techniques
|
||||
- **FAQ** - Frequently asked questions
|
||||
|
||||
**Perfect for**: Problem solving, debugging, performance issues
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
### Core Documentation
|
||||
- **[RuVector MinCut README](../../README.md)** - Project overview and features
|
||||
- **[Benchmark Report](../BENCHMARK_REPORT.md)** - Performance analysis and comparisons
|
||||
- **[API Documentation](https://docs.rs/ruvector-mincut)** - Full Rust API docs
|
||||
|
||||
### RuVector Platform
|
||||
- **[RuVector Main Repository](https://github.com/ruvnet/ruvector)** - Complete platform
|
||||
- **[RuVector Database](../../../ruvector-db/README.md)** - Vector database integration
|
||||
- **[Platform Website](https://ruv.io)** - Cloud services and support
|
||||
|
||||
### Community
|
||||
- **[GitHub Issues](https://github.com/ruvnet/ruvector/issues)** - Bug reports and feature requests
|
||||
- **[Discussions](https://github.com/ruvnet/ruvector/discussions)** - Community Q&A
|
||||
- **[Contributing Guide](../../CONTRIBUTING.md)** - How to contribute
|
||||
|
||||
---
|
||||
|
||||
## Navigation Tips
|
||||
|
||||
### 🎯 Quick Navigation
|
||||
|
||||
- Use the **table of contents** at the top of each guide page
|
||||
- Follow **"Next Steps"** links at the bottom of each section
|
||||
- Check **cross-references** for related topics
|
||||
- Use the **search** function in your viewer
|
||||
|
||||
### 📱 Mobile-Friendly
|
||||
|
||||
All documentation is optimized for reading on:
|
||||
- Desktop browsers
|
||||
- Mobile devices
|
||||
- Tablets
|
||||
- Documentation viewers (VS Code, GitHub, etc.)
|
||||
|
||||
### 🔖 Bookmarking
|
||||
|
||||
Recommended bookmarks for frequent reference:
|
||||
- [Getting Started](01-getting-started.md) - Quick setup
|
||||
- [API Reference](07-api-reference.md) - API lookup
|
||||
- [Troubleshooting](08-troubleshooting.md) - Problem solving
|
||||
- [Benchmark Report](../BENCHMARK_REPORT.md) - Performance data
|
||||
|
||||
---
|
||||
|
||||
## Document Status
|
||||
|
||||
| Section | Status | Last Updated | Completeness |
|
||||
|---------|--------|--------------|--------------|
|
||||
| Getting Started | ✅ Complete | 2025-12-22 | 100% |
|
||||
| Core Concepts | ✅ Complete | 2025-12-22 | 100% |
|
||||
| Practical Applications | ✅ Complete | 2025-12-22 | 100% |
|
||||
| Integration Guide | ✅ Complete | 2025-12-22 | 100% |
|
||||
| Advanced Examples | ✅ Complete | 2025-12-22 | 100% |
|
||||
| RuVector Ecosystem | ✅ Complete | 2025-12-22 | 100% |
|
||||
| API Reference | ✅ Complete | 2025-12-22 | 100% |
|
||||
| Troubleshooting | ✅ Complete | 2025-12-22 | 100% |
|
||||
|
||||
---
|
||||
|
||||
## About This Guide
|
||||
|
||||
### Version Information
|
||||
- **Guide Version**: 1.0.0
|
||||
- **RuVector MinCut Version**: 0.1.0
|
||||
- **Last Updated**: December 22, 2025
|
||||
- **Maintained By**: RuVector Team
|
||||
|
||||
### Contributing
|
||||
|
||||
Found an issue or want to improve this guide?
|
||||
- **Report Issues**: [GitHub Issues](https://github.com/ruvnet/ruvector/issues)
|
||||
- **Suggest Edits**: [Pull Requests](https://github.com/ruvnet/ruvector/pulls)
|
||||
- **Ask Questions**: [Discussions](https://github.com/ruvnet/ruvector/discussions)
|
||||
|
||||
### License
|
||||
|
||||
This documentation is licensed under the MIT License, same as RuVector MinCut.
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**Ready to get started?**
|
||||
|
||||
[Begin with Getting Started →](01-getting-started.md)
|
||||
|
||||
---
|
||||
|
||||
Built with ❤️ by the [RuVector Team](https://ruv.io)
|
||||
|
||||
[](https://ruv.io)
|
||||
[](https://github.com/ruvnet/ruvector)
|
||||
[](https://docs.rs/ruvector-mincut)
|
||||
|
||||
</div>
|
||||
Reference in New Issue
Block a user