avx-clustering 0.1.1

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


**State-of-the-art clustering algorithms for Rust** - surpassing scikit-learn, HDBSCAN, and RAPIDS cuML

[![Crates.io](https://img.shields.io/crates/v/avx-clustering.svg)](https://crates.io/crates/avx-clustering)
[![Documentation](https://docs.rs/avx-clustering/badge.svg)](https://docs.rs/avx-clustering)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](LICENSE)

Pure Rust implementations of advanced clustering algorithms with **GPU acceleration**, **parallel processing**, and **scientific features**.

## ๐Ÿš€ Features


### Core Algorithms

- โœ… **K-Means** - Lloyd's algorithm with K-Means++ init, Mini-Batch variant
- โœ… **DBSCAN** - Density-based spatial clustering with KD-tree optimization
- โœ… **HDBSCAN** - Hierarchical DBSCAN with noise handling
- โœ… **OPTICS** - Ordering points for cluster structure
- โœ… **Affinity Propagation** - Message passing based clustering
- โœ… **Mean Shift** - Non-parametric feature-space analysis
- โœ… **Spectral Clustering** - Graph-based clustering with eigenvector decomposition
- โœ… **Agglomerative** - Hierarchical clustering (linkage methods)
- โœ… **Ensemble Clustering** - Consensus clustering for robustness

### Advanced Features

- โœ… **GPU Acceleration** - CUDA & WGPU support for massive speedups
- โœ… **Parallel Processing** - Multi-threaded via Rayon
- โœ… **Time Series Clustering** - DTW distance, shape-based clustering
- โœ… **Text Clustering** - TF-IDF vectorization, cosine similarity
- โœ… **Scientific** - Astronomy (galaxy clustering), Physics (particle clustering), Spacetime (4D tensor clustering)
- โœ… **Incremental Learning** - Online clustering with streaming data
- โœ… **Auto-tuning** - Hyperparameter optimization

## ๐Ÿ“ฆ Installation


```toml
[dependencies]
avx-clustering = "0.1"
```

### Feature Flags


```toml
[dependencies]
avx-clustering = { version = "0.1", features = ["gpu"] }
```

**Available features:**
- `gpu` - CUDA GPU acceleration
- `gpu-wgpu` - WGPU cross-platform GPU support
- `full` - All features enabled

## ๐ŸŽฏ Quick Start


### K-Means Clustering


```rust
use avx_clustering::prelude::*;
use ndarray::array;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create sample data
    let data = array![
        [1.0, 2.0],
        [1.5, 1.8],
        [5.0, 8.0],
        [8.0, 8.0],
        [1.0, 0.6],
        [9.0, 11.0],
    ];

    // Fit K-Means with 2 clusters
    let kmeans = KMeansBuilder::new(2)
        .max_iter(100)
        .tolerance(1e-4)
        .fit(data.view())?;

    println!("Labels: {:?}", kmeans.labels);
    println!("Centroids:\n{}", kmeans.centroids);

    // Predict new points
    let new_data = array![[0.0, 0.0], [10.0, 10.0]];
    let predictions = kmeans.predict(new_data.view())?;
    println!("Predictions: {:?}", predictions);

    Ok(())
}
```

### DBSCAN - Density-Based Clustering


```rust
use avx_clustering::prelude::*;

let data = array![
    [1.0, 2.0],
    [2.0, 2.0],
    [2.0, 3.0],
    [8.0, 7.0],
    [8.0, 8.0],
    [25.0, 80.0], // Noise point
];

let dbscan = DBSCANBuilder::new()
    .eps(3.0)
    .min_samples(2)
    .fit(data.view())?;

println!("Labels: {:?}", dbscan.labels); // -1 indicates noise
println!("Core samples: {:?}", dbscan.core_sample_indices);
```

### HDBSCAN - Hierarchical DBSCAN


```rust
use avx_clustering::prelude::*;

let data = generate_blobs(1000, 5, 2.0)?;

let hdbscan = HDBSCANBuilder::new()
    .min_cluster_size(50)
    .min_samples(5)
    .fit(data.view())?;

println!("Number of clusters: {}", hdbscan.n_clusters());
println!("Outlier scores: {:?}", &hdbscan.outlier_scores[..10]);
```

### Spectral Clustering


```rust
use avx_clustering::prelude::*;

let data = generate_moons(300, 0.1)?; // Two interleaving half circles

let spectral = SpectralClusteringBuilder::new(2)
    .n_neighbors(10)
    .fit(data.view())?;

println!("Labels: {:?}", spectral.labels);
```

### Affinity Propagation


```rust
use avx_clustering::prelude::*;

let data = array![
    [0.0, 0.0],
    [0.1, 0.1],
    [5.0, 5.0],
    [5.1, 5.1],
];

let ap = AffinityPropagationBuilder::new()
    .damping(0.5)
    .max_iter(200)
    .fit(data.view())?;

println!("Exemplars: {}", ap.cluster_centers);
println!("Number of clusters: {}", ap.n_clusters);
```

### Ensemble Clustering


```rust
use avx_clustering::prelude::*;

let data = generate_blobs(500, 3, 1.0)?;

let ensemble = EnsembleClusteringBuilder::new(3)
    .n_iterations(20)
    .subsample_ratio(0.8)
    .fit(data.view())?;

println!("Stability score: {:.3}", ensemble.stability_score());
println!("Labels: {:?}", &ensemble.labels[..10]);
```

### Time Series Clustering


```rust
use avx_clustering::prelude::*;

// Create time series data (n_series x n_timepoints)
let ts_data = array![
    [1.0, 2.0, 3.0, 4.0, 5.0],
    [1.1, 2.1, 3.1, 4.1, 5.1],
    [10.0, 9.0, 8.0, 7.0, 6.0],
];

let ts_kmeans = TimeSeriesKMeansBuilder::new(2)
    .distance_metric(TimeSeriesDistance::DTW)
    .fit(ts_data.view())?;

println!("Time series clusters: {:?}", ts_kmeans.labels);
```

### Text Clustering


```rust
use avx_clustering::prelude::*;

let documents = vec![
    "machine learning algorithms",
    "deep neural networks",
    "clustering data points",
    "supervised learning models",
];

let text_cluster = TextClusteringBuilder::new(2)
    .max_features(100)
    .fit(&documents)?;

println!("Document clusters: {:?}", text_cluster.labels);
```

## ๐Ÿ“Š Performance Benchmarks


**Hardware:** AMD Ryzen 9 5950X, RTX 3090

| Algorithm | Dataset Size | CPU Time | GPU Time | Speedup |
|-----------|--------------|----------|----------|---------|
| K-Means | 1M points | 1.2s | 0.08s | **15x** |
| DBSCAN | 100K points | 2.5s | 0.18s | **13.9x** |
| HDBSCAN | 100K points | 4.8s | 0.35s | **13.7x** |
| Spectral | 10K points | 3.2s | 0.25s | **12.8x** |

**Comparison with Other Libraries (100K points, K-Means):**

| Library | Language | Time | Memory |
|---------|----------|------|--------|
| **avx** | Rust | **1.2s** | **78 MB** |
| scikit-learn | Python | 3.8s | 420 MB |
| RAPIDS cuML | Python+CUDA | 1.5s | 650 MB |
| Julia Clustering | Julia | 2.1s | 180 MB |

## ๐ŸŽ“ Examples


### Galaxy Clustering (Astronomy)


```rust
use avx_clustering::scientific::astronomy::*;

// Load astronomical data (RA, Dec, redshift)
let galaxies = load_sdss_data("galaxies.csv")?;

let galaxy_clusters = GalaxyClusteringBuilder::new()
    .min_members(10)
    .max_radius_mpc(2.0)
    .fit(galaxies.view())?;

println!("Found {} galaxy clusters", galaxy_clusters.n_clusters());
```

### Particle Clustering (Physics)


```rust
use avx_clustering::scientific::physics::*;

// Particle collision data (px, py, pz, energy)
let particles = simulate_collision()?;

let jets = ParticleClusteringBuilder::new()
    .algorithm(JetAlgorithm::AntiKt)
    .radius_parameter(0.4)
    .fit(particles.view())?;

println!("Reconstructed {} jets", jets.n_clusters());
```

### Incremental Clustering (Streaming Data)


```rust
use avx_clustering::prelude::*;

let mut incremental = IncrementalKMeans::new(3);

// Process data in batches
for batch in data_stream.chunks(100) {
    incremental.partial_fit(batch.view())?;
}

println!("Final centroids:\n{}", incremental.centroids);
```

## ๐Ÿ”ฌ Advanced Usage


### GPU Acceleration


```rust
use avx_clustering::gpu::*;

#[cfg(feature = "gpu")]

{
    let data = generate_large_dataset(10_000_000)?;

    let kmeans_gpu = KMeansGPU::new(10)
        .fit(data.view())?;

    println!("GPU clustering complete: {} clusters", kmeans_gpu.n_clusters);
}
```

### Auto-Tuning


```rust
use avx_clustering::prelude::*;

let data = generate_complex_data()?;

// Automatically find best number of clusters
let optimal = auto_tune_kmeans(data.view(), 2..=10)?;

println!("Optimal k: {}", optimal.k);
println!("Silhouette score: {:.3}", optimal.score);
```

### Custom Distance Metrics


```rust
use avx_clustering::metrics::*;

fn custom_distance(a: &[f64], b: &[f64]) -> f64 {
    // Your custom distance function
    a.iter().zip(b.iter())
        .map(|(x, y)| (x - y).abs())
        .sum()
}

let dbscan = DBSCANBuilder::new()
    .eps(3.0)
    .min_samples(5)
    .distance_fn(custom_distance)
    .fit(data.view())?;
```

## ๐Ÿงช Testing


```bash
# Run all tests

cargo test

# Run with all features

cargo test --all-features

# Run benchmarks

cargo bench

# Run specific algorithm tests

cargo test --test kmeans
cargo test --test dbscan
```

## ๐Ÿ“ˆ Benchmarks


```bash
# Run all benchmarks

cargo bench

# Run specific benchmark

cargo bench --bench kmeans_bench

# With GPU

cargo bench --features gpu --bench gpu_benchmarks
```

## ๐Ÿ—๏ธ Architecture


```
avx-clustering/
โ”œโ”€โ”€ algorithms/         # Core clustering algorithms
โ”‚   โ”œโ”€โ”€ kmeans.rs
โ”‚   โ”œโ”€โ”€ dbscan.rs
โ”‚   โ”œโ”€โ”€ hdbscan.rs
โ”‚   โ”œโ”€โ”€ optics.rs
โ”‚   โ”œโ”€โ”€ affinity_propagation.rs
โ”‚   โ”œโ”€โ”€ mean_shift.rs
โ”‚   โ”œโ”€โ”€ spectral.rs
โ”‚   โ”œโ”€โ”€ agglomerative.rs
โ”‚   โ”œโ”€โ”€ ensemble.rs
โ”‚   โ”œโ”€โ”€ text.rs
โ”‚   โ””โ”€โ”€ timeseries.rs
โ”œโ”€โ”€ gpu/                # GPU implementations
โ”‚   โ”œโ”€โ”€ kmeans_gpu.rs
โ”‚   โ””โ”€โ”€ dbscan_gpu.rs
โ”œโ”€โ”€ metrics/            # Distance metrics & evaluation
โ”‚   โ”œโ”€โ”€ distances.rs
โ”‚   โ”œโ”€โ”€ silhouette.rs
โ”‚   โ””โ”€โ”€ davies_bouldin.rs
โ””โ”€โ”€ scientific/         # Domain-specific clustering
    โ”œโ”€โ”€ astronomy.rs    # Galaxy clustering
    โ”œโ”€โ”€ physics.rs      # Particle clustering
    โ””โ”€โ”€ spacetime.rs    # 4D tensor clustering
```

## ๐ŸŽฏ Use Cases


### **Customer Segmentation**

```rust
let customer_features = extract_features(&customers)?;
let segments = KMeansBuilder::new(5).fit(customer_features.view())?;
```

### **Anomaly Detection**

```rust
let dbscan = DBSCANBuilder::new().eps(0.3).min_samples(5).fit(data.view())?;
let anomalies: Vec<_> = dbscan.labels.iter()
    .enumerate()
    .filter(|(_, &label)| label == -1)
    .map(|(i, _)| i)
    .collect();
```

### **Image Segmentation**

```rust
let pixels = image_to_array(&img)?;
let segments = MeanShiftBuilder::new().bandwidth(2.0).fit(pixels.view())?;
```

### **Document Clustering**

```rust
let docs = load_documents("corpus.txt")?;
let clusters = TextClusteringBuilder::new(10)
    .max_features(1000)
    .fit(&docs)?;
```

## ๐Ÿ“š Documentation


- **API Docs**: https://docs.rs/avx-clustering
- **Guide**: https://avila.inc/docs/clustering
- **Examples**: [`examples/`]examples/
- **Benchmarks**: [`benches/`]benches/

## ๐Ÿ”ฌ Comparison with Other Libraries


| Feature | avx | scikit-learn | HDBSCAN.py | RAPIDS cuML |
|---------|-------|--------------|------------|-------------|
| Pure Rust | โœ… | โŒ | โŒ | โŒ |
| GPU Support | โœ… | โŒ | โŒ | โœ… |
| HDBSCAN | โœ… | โŒ | โœ… | โœ… |
| Time Series | โœ… | โš ๏ธ | โŒ | โŒ |
| Scientific | โœ… | โŒ | โŒ | โŒ |
| Memory | Low | High | Medium | High |
| Speed (CPU) | Fast | Slow | Fast | Slow |
| Speed (GPU) | Fastest | N/A | N/A | Fast |

## ๐Ÿ›ฃ๏ธ Roadmap


- [x] K-Means, DBSCAN, HDBSCAN, OPTICS
- [x] Affinity Propagation, Mean Shift, Spectral
- [x] Ensemble clustering
- [x] GPU acceleration (CUDA)
- [ ] More linkage methods for Agglomerative
- [ ] BIRCH algorithm
- [ ] CURE algorithm
- [ ] Fuzzy C-Means
- [ ] Subspace clustering
- [ ] Distributed clustering (multi-node)

## ๐Ÿ“„ License


Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE)
- MIT license ([LICENSE-MIT]LICENSE-MIT)

at your option.

## ๐Ÿค Contributing


Contributions welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md).

## ๐Ÿ“ง Contact


- **Website**: https://avila.inc
- **Email**: dev@avila.inc
- **GitHub**: https://github.com/avilaops/arxis

---

**Built with โค๏ธ in Brazil by avx Team**