ruvector-mincut 2.0.6

World's first subpolynomial dynamic min-cut: self-healing networks, AI optimization, real-time graph analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
# Integration Guide

This guide covers all methods for integrating `ruvector-mincut` into your applications across different platforms and languages.

## Table of Contents

- [Rust Crate Integration]#rust-crate-integration
- [WebAssembly (WASM)]#webassembly-wasm
- [Node.js Integration]#nodejs-integration
- [Python Integration]#python-integration
- [REST API Service]#rest-api-service
- [GraphQL Integration]#graphql-integration
- [Architecture Patterns]#architecture-patterns

---

## Rust Crate Integration

### Basic Setup

Add `ruvector-mincut` to your `Cargo.toml`:

```toml
[dependencies]
ruvector-mincut = "0.1.0"
ruvector-graph = "0.1.0"  # For graph database features

# Optional: Enable specific features
[dependencies.ruvector-mincut]
version = "0.1.0"
features = ["parallel", "advanced", "visualization"]
```

### Feature Flags

The crate supports several feature combinations:

```toml
[features]
default = []

# Core features
parallel = ["rayon"]           # Parallel execution with rayon
advanced = ["petgraph"]        # Advanced algorithms (Nagamochi-Ibaraki, etc.)
visualization = ["plotters"]   # Graph visualization support

# Performance features
simd = []                      # SIMD optimizations
native = []                    # Native CPU optimizations

# Serialization
serde = ["dep:serde"]
bincode = ["dep:bincode"]

# All features
full = ["parallel", "advanced", "visualization", "simd", "serde"]
```

### Workspace Setup

For multi-crate workspaces:

```toml
# workspace/Cargo.toml
[workspace]
members = [
    "app",
    "algorithms",
]

[workspace.dependencies]
ruvector-mincut = { version = "0.1.0", features = ["parallel", "advanced"] }

# app/Cargo.toml
[dependencies]
ruvector-mincut = { workspace = true }

# algorithms/Cargo.toml
[dependencies]
ruvector-mincut = { workspace = true, features = ["visualization"] }
```

### Basic Usage Example

```rust
use ruvector_mincut::{MinCutWrapper, MinCutAlgorithm};
use ruvector_mincut::graph::GraphBuilder;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Build a graph
    let mut builder = GraphBuilder::new();
    builder.add_edge(0, 1, 1.0);
    builder.add_edge(1, 2, 1.0);
    builder.add_edge(2, 3, 1.0);
    builder.add_edge(3, 0, 1.0);
    builder.add_edge(0, 2, 0.5);

    let graph = builder.build()?;

    // Create wrapper and find minimum cut
    let mut wrapper = MinCutWrapper::new(graph);
    let result = wrapper.compute_min_cut(MinCutAlgorithm::StoerWagner)?;

    println!("Minimum cut value: {}", result.cut_value);
    println!("Partition 1: {:?}", result.partition1);
    println!("Partition 2: {:?}", result.partition2);

    Ok(())
}
```

### Advanced Usage with Features

```rust
#[cfg(feature = "parallel")]
use rayon::prelude::*;

use ruvector_mincut::{
    MinCutWrapper,
    MinCutAlgorithm,
    algorithms::PaperAlgorithm,
};

fn parallel_analysis(graphs: Vec<Graph>) -> Vec<MinCutResult> {
    #[cfg(feature = "parallel")]
    {
        graphs.par_iter()
            .map(|g| {
                let mut wrapper = MinCutWrapper::new(g.clone());
                wrapper.compute_min_cut(MinCutAlgorithm::FlowBased).unwrap()
            })
            .collect()
    }

    #[cfg(not(feature = "parallel"))]
    {
        graphs.iter()
            .map(|g| {
                let mut wrapper = MinCutWrapper::new(g.clone());
                wrapper.compute_min_cut(MinCutAlgorithm::FlowBased).unwrap()
            })
            .collect()
    }
}

#[cfg(feature = "advanced")]
fn use_paper_algorithms(graph: &Graph) -> Result<f64, MinCutError> {
    use ruvector_mincut::PaperAlgorithm;

    let mut wrapper = MinCutWrapper::new(graph.clone());

    // Use state-of-the-art algorithm from SODA 2025
    let result = wrapper.compute_paper_algorithm(
        PaperAlgorithm::RandomizedMinCutVerification
    )?;

    Ok(result.cut_value)
}
```

---

## WebAssembly (WASM)

### Building for WASM Target

#### Prerequisites

```bash
# Install wasm-pack
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

# Add wasm32 target
rustup target add wasm32-unknown-unknown
```

#### Build Commands

```bash
# Development build
wasm-pack build --target web --dev crates/ruvector-mincut-wasm

# Production build with optimizations
wasm-pack build --target web --release crates/ruvector-mincut-wasm

# Build for Node.js
wasm-pack build --target nodejs crates/ruvector-mincut-wasm

# Build for bundlers (webpack, rollup)
wasm-pack build --target bundler crates/ruvector-mincut-wasm
```

#### Optimization Tips

```toml
# Cargo.toml for WASM builds
[profile.release]
opt-level = "z"           # Optimize for size
lto = true               # Link-time optimization
codegen-units = 1        # Better optimization
panic = "abort"          # Smaller binary
strip = true             # Strip symbols

[profile.release.package."*"]
opt-level = "z"
```

### Browser Integration

#### HTML Setup

```html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>RuVector MinCut Demo</title>
</head>
<body>
    <h1>Minimum Cut Calculator</h1>

    <div>
        <label>Number of nodes:</label>
        <input type="number" id="nodeCount" value="10" min="2" max="1000">
    </div>

    <div>
        <label>Edge density:</label>
        <input type="range" id="density" min="0.1" max="1.0" step="0.1" value="0.3">
        <span id="densityValue">0.3</span>
    </div>

    <button id="computeBtn">Compute Min Cut</button>

    <div id="results"></div>
    <canvas id="graphCanvas" width="800" height="600"></canvas>

    <script type="module">
        import init, {
            MinCutWrapper,
            GraphBuilder,
            MinCutAlgorithm
        } from './pkg/ruvector_mincut_wasm.js';

        async function run() {
            // Initialize WASM module
            await init();

            document.getElementById('computeBtn').addEventListener('click', computeMinCut);
            document.getElementById('density').addEventListener('input', (e) => {
                document.getElementById('densityValue').textContent = e.target.value;
            });
        }

        async function computeMinCut() {
            const nodeCount = parseInt(document.getElementById('nodeCount').value);
            const density = parseFloat(document.getElementById('density').value);

            // Build random graph
            const builder = new GraphBuilder();

            for (let i = 0; i < nodeCount; i++) {
                for (let j = i + 1; j < nodeCount; j++) {
                    if (Math.random() < density) {
                        const weight = Math.random() * 10;
                        builder.add_edge(i, j, weight);
                    }
                }
            }

            const graph = builder.build();

            // Compute minimum cut
            const wrapper = new MinCutWrapper(graph);
            const startTime = performance.now();

            const result = wrapper.compute_min_cut(MinCutAlgorithm.StoerWagner);

            const elapsed = performance.now() - startTime;

            // Display results
            document.getElementById('results').innerHTML = `
                <h2>Results</h2>
                <p><strong>Minimum Cut Value:</strong> ${result.cut_value.toFixed(4)}</p>
                <p><strong>Partition 1 Size:</strong> ${result.partition1.length}</p>
                <p><strong>Partition 2 Size:</strong> ${result.partition2.length}</p>
                <p><strong>Computation Time:</strong> ${elapsed.toFixed(2)} ms</p>
                <p><strong>Edges in Cut:</strong> ${result.cut_edges.length}</p>
            `;

            // Visualize (optional - requires additional canvas code)
            visualizeGraph(graph, result);
        }

        function visualizeGraph(graph, result) {
            const canvas = document.getElementById('graphCanvas');
            const ctx = canvas.getContext('2d');

            // Clear canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // Simple force-directed layout visualization
            // (Simplified version - production would use D3.js or similar)
            const nodes = result.partition1.concat(result.partition2);
            const positions = layoutNodes(nodes, canvas.width, canvas.height);

            // Draw edges
            ctx.strokeStyle = '#ccc';
            ctx.lineWidth = 1;
            // ... edge drawing code

            // Draw nodes
            result.partition1.forEach(nodeId => {
                drawNode(ctx, positions[nodeId], '#3498db');
            });

            result.partition2.forEach(nodeId => {
                drawNode(ctx, positions[nodeId], '#e74c3c');
            });
        }

        function drawNode(ctx, pos, color) {
            ctx.fillStyle = color;
            ctx.beginPath();
            ctx.arc(pos.x, pos.y, 8, 0, 2 * Math.PI);
            ctx.fill();
        }

        function layoutNodes(nodes, width, height) {
            // Simple circular layout
            const positions = {};
            const radius = Math.min(width, height) * 0.4;
            const centerX = width / 2;
            const centerY = height / 2;

            nodes.forEach((nodeId, i) => {
                const angle = (2 * Math.PI * i) / nodes.length;
                positions[nodeId] = {
                    x: centerX + radius * Math.cos(angle),
                    y: centerY + radius * Math.sin(angle)
                };
            });

            return positions;
        }

        run();
    </script>
</body>
</html>
```

#### TypeScript Integration

```typescript
// mincut-worker.ts
import init, {
    MinCutWrapper,
    GraphBuilder,
    MinCutAlgorithm,
    type MinCutResult
} from 'ruvector-mincut-wasm';

interface GraphData {
    nodes: number;
    edges: Array<[number, number, number]>;
}

interface ComputeRequest {
    type: 'compute';
    graph: GraphData;
    algorithm: string;
}

let initialized = false;

self.onmessage = async (e: MessageEvent<ComputeRequest>) => {
    if (!initialized) {
        await init();
        initialized = true;
    }

    const { graph, algorithm } = e.data;

    try {
        // Build graph
        const builder = new GraphBuilder();
        graph.edges.forEach(([from, to, weight]) => {
            builder.add_edge(from, to, weight);
        });

        const g = builder.build();

        // Compute minimum cut
        const wrapper = new MinCutWrapper(g);
        const algo = MinCutAlgorithm[algorithm as keyof typeof MinCutAlgorithm];
        const result = wrapper.compute_min_cut(algo);

        self.postMessage({
            success: true,
            result: {
                cutValue: result.cut_value,
                partition1: Array.from(result.partition1),
                partition2: Array.from(result.partition2),
                cutEdges: Array.from(result.cut_edges)
            }
        });
    } catch (error) {
        self.postMessage({
            success: false,
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
};
```

#### Main Application

```typescript
// app.ts
import type { MinCutResult } from './types';

class MinCutService {
    private worker: Worker;
    private requestId = 0;
    private pending = new Map<number, {
        resolve: (result: MinCutResult) => void;
        reject: (error: Error) => void;
    }>();

    constructor() {
        this.worker = new Worker(
            new URL('./mincut-worker.ts', import.meta.url),
            { type: 'module' }
        );

        this.worker.onmessage = (e) => {
            const { id, success, result, error } = e.data;
            const pending = this.pending.get(id);

            if (pending) {
                if (success) {
                    pending.resolve(result);
                } else {
                    pending.reject(new Error(error));
                }
                this.pending.delete(id);
            }
        };
    }

    async computeMinCut(
        graph: GraphData,
        algorithm: string = 'StoerWagner'
    ): Promise<MinCutResult> {
        return new Promise((resolve, reject) => {
            const id = this.requestId++;
            this.pending.set(id, { resolve, reject });

            this.worker.postMessage({
                type: 'compute',
                id,
                graph,
                algorithm
            });
        });
    }

    terminate() {
        this.worker.terminate();
    }
}

// Usage
const service = new MinCutService();

const graph = {
    nodes: 6,
    edges: [
        [0, 1, 2.0],
        [1, 2, 3.0],
        [2, 3, 1.0],
        [3, 4, 2.0],
        [4, 5, 1.0],
        [5, 0, 2.0],
        [0, 3, 0.5]
    ]
};

const result = await service.computeMinCut(graph);
console.log('Min cut value:', result.cutValue);
```

---

## Node.js Integration

### Installation

```bash
# Using npm
npm install ruvector-mincut-node

# Using yarn
yarn add ruvector-mincut-node

# Using pnpm
pnpm add ruvector-mincut-node
```

### TypeScript Setup

```typescript
// types/mincut.d.ts
declare module 'ruvector-mincut-node' {
    export interface Edge {
        from: number;
        to: number;
        weight: number;
    }

    export interface MinCutResult {
        cutValue: number;
        partition1: number[];
        partition2: number[];
        cutEdges: Array<[number, number]>;
    }

    export interface ConnectivityCurve {
        numClusters: number;
        cutValue: number;
    }

    export enum MinCutAlgorithm {
        StoerWagner = 'StoerWagner',
        FlowBased = 'FlowBased',
        KargerStein = 'KargerStein',
        NagamochiIbaraki = 'NagamochiIbaraki',
        Hierarchical = 'Hierarchical'
    }

    export class GraphBuilder {
        constructor();
        addEdge(from: number, to: number, weight: number): void;
        build(): Graph;
    }

    export class Graph {
        nodeCount(): number;
        edgeCount(): number;
    }

    export class MinCutWrapper {
        constructor(graph: Graph);
        computeMinCut(algorithm: MinCutAlgorithm): Promise<MinCutResult>;
        computeConnectivityCurve(maxClusters?: number): Promise<ConnectivityCurve[]>;
        computeLocalKCut(k: number, sourceNode: number): Promise<MinCutResult>;
    }

    export class PaperAlgorithm {
        static RandomizedMinCutVerification: string;
        static BoundedMinCutEnumeration: string;
        static ApproximateGlobalMinCut: string;
    }
}
```

### Basic Usage

```typescript
// src/mincut.ts
import {
    GraphBuilder,
    MinCutWrapper,
    MinCutAlgorithm,
    type MinCutResult
} from 'ruvector-mincut-node';

async function computeMinimumCut(
    edges: Array<[number, number, number]>
): Promise<MinCutResult> {
    // Build graph
    const builder = new GraphBuilder();

    for (const [from, to, weight] of edges) {
        builder.addEdge(from, to, weight);
    }

    const graph = builder.build();

    // Compute minimum cut
    const wrapper = new MinCutWrapper(graph);
    const result = await wrapper.computeMinCut(MinCutAlgorithm.StoerWagner);

    return result;
}

// Example usage
const edges: Array<[number, number, number]> = [
    [0, 1, 1.0],
    [1, 2, 1.0],
    [2, 3, 1.0],
    [3, 0, 1.0],
    [0, 2, 0.5]
];

computeMinimumCut(edges).then(result => {
    console.log('Minimum cut value:', result.cutValue);
    console.log('Partition 1:', result.partition1);
    console.log('Partition 2:', result.partition2);
});
```

### Express.js Service

```typescript
// src/server.ts
import express, { Request, Response } from 'express';
import {
    GraphBuilder,
    MinCutWrapper,
    MinCutAlgorithm
} from 'ruvector-mincut-node';

const app = express();
app.use(express.json());

interface MinCutRequest {
    edges: Array<[number, number, number]>;
    algorithm?: string;
}

app.post('/api/mincut', async (req: Request<{}, {}, MinCutRequest>, res: Response) => {
    try {
        const { edges, algorithm = 'StoerWagner' } = req.body;

        if (!edges || !Array.isArray(edges)) {
            return res.status(400).json({
                error: 'Invalid request: edges array required'
            });
        }

        // Validate edges
        for (const edge of edges) {
            if (!Array.isArray(edge) || edge.length !== 3) {
                return res.status(400).json({
                    error: 'Invalid edge format: expected [from, to, weight]'
                });
            }
        }

        // Build graph
        const builder = new GraphBuilder();
        edges.forEach(([from, to, weight]) => {
            builder.addEdge(from, to, weight);
        });

        const graph = builder.build();

        // Compute minimum cut
        const wrapper = new MinCutWrapper(graph);
        const algo = MinCutAlgorithm[algorithm as keyof typeof MinCutAlgorithm]
                     || MinCutAlgorithm.StoerWagner;

        const result = await wrapper.computeMinCut(algo);

        res.json({
            success: true,
            data: {
                cutValue: result.cutValue,
                partition1: result.partition1,
                partition2: result.partition2,
                cutEdges: result.cutEdges,
                algorithm: algorithm
            }
        });
    } catch (error) {
        console.error('Error computing min cut:', error);
        res.status(500).json({
            success: false,
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
});

app.post('/api/connectivity-curve', async (req: Request, res: Response) => {
    try {
        const { edges, maxClusters = 10 } = req.body;

        const builder = new GraphBuilder();
        edges.forEach(([from, to, weight]: [number, number, number]) => {
            builder.addEdge(from, to, weight);
        });

        const graph = builder.build();
        const wrapper = new MinCutWrapper(graph);

        const curve = await wrapper.computeConnectivityCurve(maxClusters);

        res.json({
            success: true,
            data: curve
        });
    } catch (error) {
        console.error('Error computing connectivity curve:', error);
        res.status(500).json({
            success: false,
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`MinCut service running on port ${PORT}`);
});
```

### Async Patterns with Worker Threads

```typescript
// src/worker-pool.ts
import { Worker } from 'worker_threads';
import { cpus } from 'os';

interface WorkerTask {
    id: number;
    edges: Array<[number, number, number]>;
    algorithm: string;
}

interface WorkerResult {
    id: number;
    result: any;
    error?: string;
}

export class MinCutWorkerPool {
    private workers: Worker[] = [];
    private queue: Array<{
        task: WorkerTask;
        resolve: (result: any) => void;
        reject: (error: Error) => void;
    }> = [];
    private activeWorkers = 0;
    private taskId = 0;

    constructor(private poolSize: number = cpus().length) {
        this.initializeWorkers();
    }

    private initializeWorkers() {
        for (let i = 0; i < this.poolSize; i++) {
            const worker = new Worker('./mincut-worker.js');

            worker.on('message', (result: WorkerResult) => {
                this.activeWorkers--;

                const pending = this.queue.shift();
                if (pending) {
                    if (result.error) {
                        pending.reject(new Error(result.error));
                    } else {
                        pending.resolve(result.result);
                    }
                }

                this.processQueue();
            });

            worker.on('error', (error) => {
                console.error('Worker error:', error);
                this.activeWorkers--;
                this.processQueue();
            });

            this.workers.push(worker);
        }
    }

    async computeMinCut(
        edges: Array<[number, number, number]>,
        algorithm: string = 'StoerWagner'
    ): Promise<any> {
        return new Promise((resolve, reject) => {
            const task: WorkerTask = {
                id: this.taskId++,
                edges,
                algorithm
            };

            this.queue.push({ task, resolve, reject });
            this.processQueue();
        });
    }

    private processQueue() {
        while (this.activeWorkers < this.poolSize && this.queue.length > 0) {
            const { task } = this.queue[0];
            const worker = this.workers[this.activeWorkers];

            this.activeWorkers++;
            worker.postMessage(task);
        }
    }

    terminate() {
        this.workers.forEach(worker => worker.terminate());
        this.workers = [];
    }
}

// Usage
const pool = new MinCutWorkerPool();

const tasks = [
    pool.computeMinCut([[0, 1, 1], [1, 2, 1]], 'StoerWagner'),
    pool.computeMinCut([[0, 1, 2], [1, 2, 3]], 'FlowBased'),
    pool.computeMinCut([[0, 1, 1], [1, 2, 1], [2, 0, 1]], 'KargerStein')
];

const results = await Promise.all(tasks);
console.log('All results:', results);
```

---

## Python Integration

### PyO3 Bindings Concept

```python
# ruvector_mincut/__init__.py
"""
Python bindings for ruvector-mincut library.

This module provides Python access to high-performance minimum cut algorithms
implemented in Rust.
"""

from typing import List, Tuple, Optional, Dict, Any
from enum import Enum

class MinCutAlgorithm(Enum):
    """Available minimum cut algorithms."""
    STOER_WAGNER = "StoerWagner"
    FLOW_BASED = "FlowBased"
    KARGER_STEIN = "KargerStein"
    NAGAMOCHI_IBARAKI = "NagamochiIbaraki"
    HIERARCHICAL = "Hierarchical"


class MinCutResult:
    """Result of a minimum cut computation."""

    def __init__(
        self,
        cut_value: float,
        partition1: List[int],
        partition2: List[int],
        cut_edges: List[Tuple[int, int]]
    ):
        self.cut_value = cut_value
        self.partition1 = partition1
        self.partition2 = partition2
        self.cut_edges = cut_edges

    def __repr__(self) -> str:
        return (
            f"MinCutResult(cut_value={self.cut_value}, "
            f"partition1={self.partition1}, "
            f"partition2={self.partition2})"
        )

    def to_dict(self) -> Dict[str, Any]:
        """Convert result to dictionary."""
        return {
            'cut_value': self.cut_value,
            'partition1': self.partition1,
            'partition2': self.partition2,
            'cut_edges': self.cut_edges
        }


class GraphBuilder:
    """Builder for constructing graphs."""

    def __init__(self):
        """Initialize a new graph builder."""
        self._edges: List[Tuple[int, int, float]] = []

    def add_edge(self, from_node: int, to_node: int, weight: float = 1.0) -> 'GraphBuilder':
        """
        Add an edge to the graph.

        Args:
            from_node: Source node ID
            to_node: Target node ID
            weight: Edge weight (default: 1.0)

        Returns:
            Self for method chaining
        """
        self._edges.append((from_node, to_node, weight))
        return self

    def build(self) -> 'Graph':
        """
        Build the graph.

        Returns:
            Constructed Graph object
        """
        # This would call the Rust implementation
        from . import _native
        return Graph(_native.build_graph(self._edges))


class Graph:
    """Graph data structure."""

    def __init__(self, handle):
        """Initialize with native handle (internal use)."""
        self._handle = handle

    def node_count(self) -> int:
        """Get the number of nodes in the graph."""
        from . import _native
        return _native.graph_node_count(self._handle)

    def edge_count(self) -> int:
        """Get the number of edges in the graph."""
        from . import _native
        return _native.graph_edge_count(self._handle)


class MinCutWrapper:
    """Wrapper for minimum cut computations."""

    def __init__(self, graph: Graph):
        """
        Initialize wrapper with a graph.

        Args:
            graph: Graph to analyze
        """
        self.graph = graph
        from . import _native
        self._handle = _native.create_mincut_wrapper(graph._handle)

    def compute_min_cut(
        self,
        algorithm: MinCutAlgorithm = MinCutAlgorithm.STOER_WAGNER
    ) -> MinCutResult:
        """
        Compute the minimum cut.

        Args:
            algorithm: Algorithm to use

        Returns:
            MinCutResult containing the cut value and partitions

        Raises:
            ValueError: If computation fails
        """
        from . import _native

        result = _native.compute_min_cut(self._handle, algorithm.value)

        return MinCutResult(
            cut_value=result['cut_value'],
            partition1=result['partition1'],
            partition2=result['partition2'],
            cut_edges=result['cut_edges']
        )

    def compute_connectivity_curve(
        self,
        max_clusters: Optional[int] = None
    ) -> List[Dict[str, Any]]:
        """
        Compute connectivity curve showing cut values at different cluster counts.

        Args:
            max_clusters: Maximum number of clusters (default: node_count)

        Returns:
            List of dictionaries with 'num_clusters' and 'cut_value'
        """
        from . import _native
        return _native.compute_connectivity_curve(self._handle, max_clusters)

    def compute_local_k_cut(
        self,
        k: int,
        source_node: int
    ) -> MinCutResult:
        """
        Compute local k-cut around a source node.

        Args:
            k: Target cluster count
            source_node: Source node for local cut

        Returns:
            MinCutResult for the local cut
        """
        from . import _native

        result = _native.compute_local_k_cut(self._handle, k, source_node)

        return MinCutResult(
            cut_value=result['cut_value'],
            partition1=result['partition1'],
            partition2=result['partition2'],
            cut_edges=result['cut_edges']
        )


# Convenience functions
def compute_min_cut(
    edges: List[Tuple[int, int, float]],
    algorithm: MinCutAlgorithm = MinCutAlgorithm.STOER_WAGNER
) -> MinCutResult:
    """
    Convenience function to compute minimum cut from edge list.

    Args:
        edges: List of (from, to, weight) tuples
        algorithm: Algorithm to use

    Returns:
        MinCutResult

    Example:
        >>> edges = [(0, 1, 1.0), (1, 2, 1.0), (2, 0, 1.0)]
        >>> result = compute_min_cut(edges)
        >>> print(f"Cut value: {result.cut_value}")
    """
    builder = GraphBuilder()
    for from_node, to_node, weight in edges:
        builder.add_edge(from_node, to_node, weight)

    graph = builder.build()
    wrapper = MinCutWrapper(graph)
    return wrapper.compute_min_cut(algorithm)
```

### Python Usage Example

```python
# examples/python_example.py
from ruvector_mincut import (
    GraphBuilder,
    MinCutWrapper,
    MinCutAlgorithm,
    compute_min_cut
)
import matplotlib.pyplot as plt
import networkx as nx

def basic_example():
    """Basic usage example."""
    # Build a simple graph
    builder = GraphBuilder()
    builder.add_edge(0, 1, 1.0)
    builder.add_edge(1, 2, 1.0)
    builder.add_edge(2, 3, 1.0)
    builder.add_edge(3, 0, 1.0)
    builder.add_edge(0, 2, 0.5)

    graph = builder.build()

    # Compute minimum cut
    wrapper = MinCutWrapper(graph)
    result = wrapper.compute_min_cut(MinCutAlgorithm.STOER_WAGNER)

    print(f"Minimum cut value: {result.cut_value}")
    print(f"Partition 1: {result.partition1}")
    print(f"Partition 2: {result.partition2}")
    print(f"Cut edges: {result.cut_edges}")


def connectivity_analysis():
    """Analyze connectivity curve."""
    # Create a larger graph
    edges = []
    for i in range(10):
        edges.append((i, (i + 1) % 10, 1.0))
        if i % 2 == 0:
            edges.append((i, (i + 5) % 10, 0.5))

    builder = GraphBuilder()
    for from_node, to_node, weight in edges:
        builder.add_edge(from_node, to_node, weight)

    graph = builder.build()
    wrapper = MinCutWrapper(graph)

    # Get connectivity curve
    curve = wrapper.compute_connectivity_curve(max_clusters=5)

    # Plot
    clusters = [c['num_clusters'] for c in curve]
    cut_values = [c['cut_value'] for c in curve]

    plt.figure(figsize=(10, 6))
    plt.plot(clusters, cut_values, marker='o')
    plt.xlabel('Number of Clusters')
    plt.ylabel('Minimum Cut Value')
    plt.title('Connectivity Curve')
    plt.grid(True)
    plt.savefig('connectivity_curve.png')
    print("Saved connectivity curve to connectivity_curve.png")


def visualize_cut():
    """Visualize the minimum cut."""
    # Build graph
    edges = [
        (0, 1, 1.0), (1, 2, 1.0), (2, 3, 1.0),
        (3, 4, 1.0), (4, 5, 1.0), (5, 0, 1.0),
        (0, 3, 0.5), (1, 4, 0.5), (2, 5, 0.5)
    ]

    # Compute minimum cut
    result = compute_min_cut(edges)

    # Create NetworkX graph for visualization
    G = nx.Graph()
    for from_node, to_node, weight in edges:
        G.add_edge(from_node, to_node, weight=weight)

    # Color nodes by partition
    colors = []
    for node in G.nodes():
        if node in result.partition1:
            colors.append('lightblue')
        else:
            colors.append('lightcoral')

    # Highlight cut edges
    edge_colors = []
    for edge in G.edges():
        if edge in result.cut_edges or (edge[1], edge[0]) in result.cut_edges:
            edge_colors.append('red')
        else:
            edge_colors.append('gray')

    # Draw
    plt.figure(figsize=(10, 8))
    pos = nx.spring_layout(G)
    nx.draw(G, pos, node_color=colors, edge_color=edge_colors,
            node_size=500, with_labels=True, width=2)
    plt.title(f'Minimum Cut (value: {result.cut_value})')
    plt.savefig('mincut_visualization.png')
    print("Saved visualization to mincut_visualization.png")


if __name__ == '__main__':
    print("Running basic example...")
    basic_example()

    print("\nAnalyzing connectivity...")
    connectivity_analysis()

    print("\nVisualizing cut...")
    visualize_cut()
```

---

## REST API Service

### Actix-Web Service

```rust
// src/api/mod.rs
use actix_web::{web, App, HttpResponse, HttpServer, middleware};
use serde::{Deserialize, Serialize};
use ruvector_mincut::{MinCutWrapper, MinCutAlgorithm, MinCutError};
use ruvector_mincut::graph::GraphBuilder;

#[derive(Debug, Deserialize)]
struct Edge {
    from: usize,
    to: usize,
    weight: f64,
}

#[derive(Debug, Deserialize)]
struct MinCutRequest {
    edges: Vec<Edge>,
    algorithm: Option<String>,
}

#[derive(Debug, Serialize)]
struct MinCutResponse {
    cut_value: f64,
    partition1: Vec<usize>,
    partition2: Vec<usize>,
    cut_edges: Vec<(usize, usize)>,
    algorithm: String,
    computation_time_ms: f64,
}

#[derive(Debug, Serialize)]
struct ErrorResponse {
    error: String,
    details: Option<String>,
}

#[derive(Debug, Deserialize)]
struct ConnectivityRequest {
    edges: Vec<Edge>,
    max_clusters: Option<usize>,
}

#[derive(Debug, Serialize)]
struct ConnectivityPoint {
    num_clusters: usize,
    cut_value: f64,
}

#[derive(Debug, Serialize)]
struct ConnectivityResponse {
    curve: Vec<ConnectivityPoint>,
    computation_time_ms: f64,
}

// Health check endpoint
async fn health() -> HttpResponse {
    HttpResponse::Ok().json(serde_json::json!({
        "status": "healthy",
        "version": env!("CARGO_PKG_VERSION")
    }))
}

// Compute minimum cut endpoint
async fn compute_min_cut(req: web::Json<MinCutRequest>) -> HttpResponse {
    let start = std::time::Instant::now();

    // Build graph
    let mut builder = GraphBuilder::new();
    for edge in &req.edges {
        builder.add_edge(edge.from, edge.to, edge.weight);
    }

    let graph = match builder.build() {
        Ok(g) => g,
        Err(e) => {
            return HttpResponse::BadRequest().json(ErrorResponse {
                error: "Failed to build graph".to_string(),
                details: Some(e.to_string()),
            });
        }
    };

    // Parse algorithm
    let algorithm = match req.algorithm.as_deref() {
        Some("StoerWagner") | None => MinCutAlgorithm::StoerWagner,
        Some("FlowBased") => MinCutAlgorithm::FlowBased,
        Some("KargerStein") => MinCutAlgorithm::KargerStein,
        Some("NagamochiIbaraki") => MinCutAlgorithm::NagamochiIbaraki,
        Some("Hierarchical") => MinCutAlgorithm::Hierarchical,
        Some(algo) => {
            return HttpResponse::BadRequest().json(ErrorResponse {
                error: "Invalid algorithm".to_string(),
                details: Some(format!("Unknown algorithm: {}", algo)),
            });
        }
    };

    // Compute minimum cut
    let mut wrapper = MinCutWrapper::new(graph);
    let result = match wrapper.compute_min_cut(algorithm) {
        Ok(r) => r,
        Err(e) => {
            return HttpResponse::InternalServerError().json(ErrorResponse {
                error: "Computation failed".to_string(),
                details: Some(e.to_string()),
            });
        }
    };

    let elapsed = start.elapsed();

    HttpResponse::Ok().json(MinCutResponse {
        cut_value: result.cut_value,
        partition1: result.partition1,
        partition2: result.partition2,
        cut_edges: result.cut_edges,
        algorithm: format!("{:?}", algorithm),
        computation_time_ms: elapsed.as_secs_f64() * 1000.0,
    })
}

// Connectivity curve endpoint
async fn connectivity_curve(req: web::Json<ConnectivityRequest>) -> HttpResponse {
    let start = std::time::Instant::now();

    // Build graph
    let mut builder = GraphBuilder::new();
    for edge in &req.edges {
        builder.add_edge(edge.from, edge.to, edge.weight);
    }

    let graph = match builder.build() {
        Ok(g) => g,
        Err(e) => {
            return HttpResponse::BadRequest().json(ErrorResponse {
                error: "Failed to build graph".to_string(),
                details: Some(e.to_string()),
            });
        }
    };

    // Compute connectivity curve
    let mut wrapper = MinCutWrapper::new(graph);
    let curve = match wrapper.compute_connectivity_curve(req.max_clusters) {
        Ok(c) => c,
        Err(e) => {
            return HttpResponse::InternalServerError().json(ErrorResponse {
                error: "Computation failed".to_string(),
                details: Some(e.to_string()),
            });
        }
    };

    let elapsed = start.elapsed();

    let response_curve: Vec<ConnectivityPoint> = curve
        .into_iter()
        .map(|point| ConnectivityPoint {
            num_clusters: point.num_clusters,
            cut_value: point.cut_value,
        })
        .collect();

    HttpResponse::Ok().json(ConnectivityResponse {
        curve: response_curve,
        computation_time_ms: elapsed.as_secs_f64() * 1000.0,
    })
}

// List available algorithms
async fn list_algorithms() -> HttpResponse {
    HttpResponse::Ok().json(serde_json::json!({
        "algorithms": [
            {
                "name": "StoerWagner",
                "description": "Exact algorithm with O(V³) time complexity",
                "exact": true
            },
            {
                "name": "FlowBased",
                "description": "Maximum flow based algorithm",
                "exact": true
            },
            {
                "name": "KargerStein",
                "description": "Randomized algorithm with high probability guarantees",
                "exact": false
            },
            {
                "name": "NagamochiIbaraki",
                "description": "O(VE + V²log V) deterministic algorithm",
                "exact": true
            },
            {
                "name": "Hierarchical",
                "description": "Hierarchical clustering based approach",
                "exact": false
            }
        ]
    }))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

    let port = std::env::var("PORT")
        .unwrap_or_else(|_| "8080".to_string())
        .parse::<u16>()
        .expect("Invalid PORT");

    log::info!("Starting MinCut API server on port {}", port);

    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Logger::default())
            .wrap(middleware::Compress::default())
            .route("/health", web::get().to(health))
            .route("/api/mincut", web::post().to(compute_min_cut))
            .route("/api/connectivity", web::post().to(connectivity_curve))
            .route("/api/algorithms", web::get().to(list_algorithms))
    })
    .bind(("0.0.0.0", port))?
    .run()
    .await
}
```

### API Client Example

```typescript
// client/mincut-api-client.ts
export interface Edge {
    from: number;
    to: number;
    weight: number;
}

export interface MinCutResult {
    cutValue: number;
    partition1: number[];
    partition2: number[];
    cutEdges: Array<[number, number]>;
    algorithm: string;
    computationTimeMs: number;
}

export interface ConnectivityPoint {
    numClusters: number;
    cutValue: number;
}

export class MinCutAPIClient {
    constructor(private baseUrl: string = 'http://localhost:8080') {}

    async computeMinCut(
        edges: Edge[],
        algorithm?: string
    ): Promise<MinCutResult> {
        const response = await fetch(`${this.baseUrl}/api/mincut`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ edges, algorithm })
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error || 'API request failed');
        }

        return response.json();
    }

    async computeConnectivityCurve(
        edges: Edge[],
        maxClusters?: number
    ): Promise<{ curve: ConnectivityPoint[]; computationTimeMs: number }> {
        const response = await fetch(`${this.baseUrl}/api/connectivity`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ edges, max_clusters: maxClusters })
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error || 'API request failed');
        }

        return response.json();
    }

    async listAlgorithms(): Promise<any> {
        const response = await fetch(`${this.baseUrl}/api/algorithms`);
        return response.json();
    }
}

// Usage
const client = new MinCutAPIClient();

const edges = [
    { from: 0, to: 1, weight: 1.0 },
    { from: 1, to: 2, weight: 1.0 },
    { from: 2, to: 0, weight: 1.0 }
];

const result = await client.computeMinCut(edges, 'StoerWagner');
console.log(result);
```

---

## GraphQL Integration

### Schema Definition

```graphql
# schema.graphql
type Query {
  """Get available algorithms"""
  algorithms: [Algorithm!]!

  """Check service health"""
  health: HealthStatus!
}

type Mutation {
  """Compute minimum cut for a graph"""
  computeMinCut(input: MinCutInput!): MinCutResult!

  """Compute connectivity curve"""
  computeConnectivityCurve(input: ConnectivityInput!): ConnectivityCurve!

  """Compute local k-cut around a source node"""
  computeLocalKCut(input: LocalKCutInput!): MinCutResult!
}

input EdgeInput {
  from: Int!
  to: Int!
  weight: Float!
}

input MinCutInput {
  edges: [EdgeInput!]!
  algorithm: AlgorithmType = STOER_WAGNER
}

input ConnectivityInput {
  edges: [EdgeInput!]!
  maxClusters: Int
}

input LocalKCutInput {
  edges: [EdgeInput!]!
  k: Int!
  sourceNode: Int!
}

enum AlgorithmType {
  STOER_WAGNER
  FLOW_BASED
  KARGER_STEIN
  NAGAMOCHI_IBARAKI
  HIERARCHICAL
}

type Algorithm {
  name: String!
  description: String!
  exact: Boolean!
  timeComplexity: String!
}

type MinCutResult {
  cutValue: Float!
  partition1: [Int!]!
  partition2: [Int!]!
  cutEdges: [[Int!]!]!
  algorithm: String!
  computationTimeMs: Float!
}

type ConnectivityPoint {
  numClusters: Int!
  cutValue: Float!
}

type ConnectivityCurve {
  curve: [ConnectivityPoint!]!
  computationTimeMs: Float!
}

type HealthStatus {
  status: String!
  version: String!
}
```

### Resolver Implementation

```rust
// src/graphql/mod.rs
use async_graphql::{
    Context, Object, Schema, EmptySubscription, SimpleObject, Enum, InputObject
};
use ruvector_mincut::{MinCutWrapper, MinCutAlgorithm};
use ruvector_mincut::graph::GraphBuilder;

#[derive(InputObject)]
struct EdgeInput {
    from: usize,
    to: usize,
    weight: f64,
}

#[derive(InputObject)]
struct MinCutInput {
    edges: Vec<EdgeInput>,
    #[graphql(default)]
    algorithm: AlgorithmType,
}

#[derive(InputObject)]
struct ConnectivityInput {
    edges: Vec<EdgeInput>,
    max_clusters: Option<usize>,
}

#[derive(InputObject)]
struct LocalKCutInput {
    edges: Vec<EdgeInput>,
    k: usize,
    source_node: usize,
}

#[derive(Enum, Copy, Clone, Eq, PartialEq)]
enum AlgorithmType {
    StoerWagner,
    FlowBased,
    KargerStein,
    NagamochiIbaraki,
    Hierarchical,
}

impl From<AlgorithmType> for MinCutAlgorithm {
    fn from(algo: AlgorithmType) -> Self {
        match algo {
            AlgorithmType::StoerWagner => MinCutAlgorithm::StoerWagner,
            AlgorithmType::FlowBased => MinCutAlgorithm::FlowBased,
            AlgorithmType::KargerStein => MinCutAlgorithm::KargerStein,
            AlgorithmType::NagamochiIbaraki => MinCutAlgorithm::NagamochiIbaraki,
            AlgorithmType::Hierarchical => MinCutAlgorithm::Hierarchical,
        }
    }
}

#[derive(SimpleObject)]
struct Algorithm {
    name: String,
    description: String,
    exact: bool,
    time_complexity: String,
}

#[derive(SimpleObject)]
struct MinCutResultGQL {
    cut_value: f64,
    partition1: Vec<usize>,
    partition2: Vec<usize>,
    cut_edges: Vec<Vec<usize>>,
    algorithm: String,
    computation_time_ms: f64,
}

#[derive(SimpleObject)]
struct ConnectivityPointGQL {
    num_clusters: usize,
    cut_value: f64,
}

#[derive(SimpleObject)]
struct ConnectivityCurveGQL {
    curve: Vec<ConnectivityPointGQL>,
    computation_time_ms: f64,
}

#[derive(SimpleObject)]
struct HealthStatus {
    status: String,
    version: String,
}

pub struct QueryRoot;

#[Object]
impl QueryRoot {
    async fn algorithms(&self) -> Vec<Algorithm> {
        vec![
            Algorithm {
                name: "StoerWagner".to_string(),
                description: "Exact algorithm with O(V³) time complexity".to_string(),
                exact: true,
                time_complexity: "O(V³)".to_string(),
            },
            Algorithm {
                name: "FlowBased".to_string(),
                description: "Maximum flow based algorithm".to_string(),
                exact: true,
                time_complexity: "O(V²E)".to_string(),
            },
            Algorithm {
                name: "KargerStein".to_string(),
                description: "Randomized algorithm with high probability".to_string(),
                exact: false,
                time_complexity: "O(V²log³V)".to_string(),
            },
            Algorithm {
                name: "NagamochiIbaraki".to_string(),
                description: "Deterministic near-linear algorithm".to_string(),
                exact: true,
                time_complexity: "O(VE + V²log V)".to_string(),
            },
            Algorithm {
                name: "Hierarchical".to_string(),
                description: "Hierarchical clustering approach".to_string(),
                exact: false,
                time_complexity: "O(V²log V)".to_string(),
            },
        ]
    }

    async fn health(&self) -> HealthStatus {
        HealthStatus {
            status: "healthy".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
        }
    }
}

pub struct MutationRoot;

#[Object]
impl MutationRoot {
    async fn compute_min_cut(&self, input: MinCutInput) -> async_graphql::Result<MinCutResultGQL> {
        let start = std::time::Instant::now();

        // Build graph
        let mut builder = GraphBuilder::new();
        for edge in input.edges {
            builder.add_edge(edge.from, edge.to, edge.weight);
        }
        let graph = builder.build()?;

        // Compute minimum cut
        let mut wrapper = MinCutWrapper::new(graph);
        let result = wrapper.compute_min_cut(input.algorithm.into())?;

        let elapsed = start.elapsed();

        Ok(MinCutResultGQL {
            cut_value: result.cut_value,
            partition1: result.partition1,
            partition2: result.partition2,
            cut_edges: result.cut_edges.into_iter()
                .map(|(a, b)| vec![a, b])
                .collect(),
            algorithm: format!("{:?}", input.algorithm),
            computation_time_ms: elapsed.as_secs_f64() * 1000.0,
        })
    }

    async fn compute_connectivity_curve(
        &self,
        input: ConnectivityInput
    ) -> async_graphql::Result<ConnectivityCurveGQL> {
        let start = std::time::Instant::now();

        // Build graph
        let mut builder = GraphBuilder::new();
        for edge in input.edges {
            builder.add_edge(edge.from, edge.to, edge.weight);
        }
        let graph = builder.build()?;

        // Compute connectivity curve
        let mut wrapper = MinCutWrapper::new(graph);
        let curve = wrapper.compute_connectivity_curve(input.max_clusters)?;

        let elapsed = start.elapsed();

        Ok(ConnectivityCurveGQL {
            curve: curve.into_iter()
                .map(|p| ConnectivityPointGQL {
                    num_clusters: p.num_clusters,
                    cut_value: p.cut_value,
                })
                .collect(),
            computation_time_ms: elapsed.as_secs_f64() * 1000.0,
        })
    }

    async fn compute_local_k_cut(
        &self,
        input: LocalKCutInput
    ) -> async_graphql::Result<MinCutResultGQL> {
        let start = std::time::Instant::now();

        // Build graph
        let mut builder = GraphBuilder::new();
        for edge in input.edges {
            builder.add_edge(edge.from, edge.to, edge.weight);
        }
        let graph = builder.build()?;

        // Compute local k-cut
        let mut wrapper = MinCutWrapper::new(graph);
        let result = wrapper.compute_local_k_cut(input.k, input.source_node)?;

        let elapsed = start.elapsed();

        Ok(MinCutResultGQL {
            cut_value: result.cut_value,
            partition1: result.partition1,
            partition2: result.partition2,
            cut_edges: result.cut_edges.into_iter()
                .map(|(a, b)| vec![a, b])
                .collect(),
            algorithm: "LocalKCut".to_string(),
            computation_time_ms: elapsed.as_secs_f64() * 1000.0,
        })
    }
}

pub type MinCutSchema = Schema<QueryRoot, MutationRoot, EmptySubscription>;

pub fn create_schema() -> MinCutSchema {
    Schema::build(QueryRoot, MutationRoot, EmptySubscription).finish()
}
```

### GraphQL Server

```rust
// src/graphql_server.rs
use actix_web::{web, App, HttpServer, guard, middleware};
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql_actix_web::{GraphQLRequest, GraphQLResponse};

mod graphql;
use graphql::create_schema;

async fn graphql_playground() -> actix_web::HttpResponse {
    actix_web::HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")
        .body(playground_source(
            GraphQLPlaygroundConfig::new("/graphql")
        ))
}

async fn graphql_handler(
    schema: web::Data<graphql::MinCutSchema>,
    req: GraphQLRequest,
) -> GraphQLResponse {
    schema.execute(req.into_inner()).await.into()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

    let schema = create_schema();

    log::info!("GraphQL Playground: http://localhost:8080/playground");

    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(schema.clone()))
            .wrap(middleware::Logger::default())
            .service(
                web::resource("/graphql")
                    .guard(guard::Post())
                    .to(graphql_handler)
            )
            .service(
                web::resource("/playground")
                    .guard(guard::Get())
                    .to(graphql_playground)
            )
    })
    .bind(("0.0.0.0", 8080))?
    .run()
    .await
}
```

---

## Architecture Patterns

### WASM Browser Deployment

```mermaid
graph TB
    subgraph "Browser Environment"
        UI[Web UI<br/>React/Vue/Svelte]
        Worker[Web Worker<br/>WASM Runtime]
        Canvas[Canvas<br/>Visualization]
    end

    subgraph "WASM Module"
        WasmBind[wasm-bindgen<br/>JS Bindings]
        MinCut[MinCut Algorithms<br/>Rust Core]
        Graph[Graph Structures]
    end

    UI -->|Post Message| Worker
    Worker -->|Load & Initialize| WasmBind
    WasmBind -->|Call| MinCut
    MinCut -->|Use| Graph
    Worker -->|Results| UI
    UI -->|Render| Canvas

    style UI fill:#3498db
    style Worker fill:#2ecc71
    style WasmBind fill:#e74c3c
    style MinCut fill:#f39c12
```

### Node.js Server Architecture

```mermaid
graph TB
    subgraph "Client Layer"
        Web[Web Clients]
        Mobile[Mobile Apps]
        CLI[CLI Tools]
    end

    subgraph "API Layer"
        REST[REST API<br/>Express/Fastify]
        GraphQL[GraphQL API<br/>Apollo Server]
        WS[WebSocket<br/>Real-time]
    end

    subgraph "Service Layer"
        Pool[Worker Pool<br/>Thread Pool]
        Cache[Redis Cache<br/>Results]
        Queue[Task Queue<br/>Bull/BullMQ]
    end

    subgraph "Core Layer"
        Native[Native Module<br/>ruvector-mincut-node]
        Rust[Rust Core<br/>MinCut Algorithms]
    end

    Web --> REST
    Mobile --> GraphQL
    CLI --> REST

    REST --> Pool
    GraphQL --> Pool
    WS --> Queue

    Pool --> Cache
    Pool --> Native
    Queue --> Native
    Native --> Rust

    style Web fill:#3498db
    style REST fill:#2ecc71
    style Pool fill:#e74c3c
    style Native fill:#f39c12
```

### Microservice Integration

```mermaid
graph TB
    subgraph "API Gateway"
        Gateway[Kong/Traefik<br/>API Gateway]
    end

    subgraph "MinCut Service"
        API[MinCut API<br/>Actix-Web]
        Compute[Compute Workers<br/>Rayon Thread Pool]
        Cache[Local Cache<br/>LRU]
    end

    subgraph "Supporting Services"
        Graph[Graph Service<br/>ruvector-graph]
        Metrics[Metrics<br/>Prometheus]
        Trace[Tracing<br/>Jaeger]
    end

    subgraph "Storage Layer"
        DB[(Graph Database<br/>Neo4j/AgentDB)]
        Object[(Object Storage<br/>S3/MinIO)]
    end

    Gateway --> API
    API --> Compute
    API --> Cache
    API --> Graph
    API --> Metrics
    API --> Trace

    Graph --> DB
    Compute --> Object

    style Gateway fill:#3498db
    style API fill:#2ecc71
    style Compute fill:#e74c3c
    style Graph fill:#f39c12
    style DB fill:#9b59b6
```

### Distributed Processing

```mermaid
graph TB
    subgraph "Load Balancer"
        LB[HAProxy/Nginx]
    end

    subgraph "Service Instances"
        S1[MinCut Service 1]
        S2[MinCut Service 2]
        S3[MinCut Service 3]
    end

    subgraph "Message Queue"
        Queue[RabbitMQ/Kafka<br/>Task Distribution]
    end

    subgraph "Worker Nodes"
        W1[Worker 1<br/>GPU Acceleration]
        W2[Worker 2<br/>CPU Intensive]
        W3[Worker 3<br/>Memory Optimized]
    end

    subgraph "Coordination"
        Coord[Coordinator<br/>Task Scheduling]
        Monitor[Monitor<br/>Health Checks]
    end

    LB --> S1
    LB --> S2
    LB --> S3

    S1 --> Queue
    S2 --> Queue
    S3 --> Queue

    Queue --> Coord
    Coord --> W1
    Coord --> W2
    Coord --> W3

    Monitor --> S1
    Monitor --> S2
    Monitor --> S3
    Monitor --> W1
    Monitor --> W2
    Monitor --> W3

    style LB fill:#3498db
    style Queue fill:#2ecc71
    style Coord fill:#e74c3c
    style W1 fill:#f39c12
```

---

## Integration with ruvector-graph

For graph database features and persistent storage, integrate with `ruvector-graph`:

```rust
use ruvector_mincut::MinCutWrapper;
use ruvector_graph::{GraphDB, Query};

// Load graph from database
let db = GraphDB::connect("localhost:7687")?;
let graph = db.query("MATCH (n)-[r]-(m) RETURN n, r, m")?;

// Compute minimum cut
let mut wrapper = MinCutWrapper::new(graph);
let result = wrapper.compute_min_cut(MinCutAlgorithm::StoerWagner)?;

// Store results back to database
db.execute(
    "CREATE (r:MinCutResult {value: $value})",
    &[("value", result.cut_value)]
)?;
```

---

## Best Practices

### Performance Optimization

1. **Use Web Workers for WASM** - Keep UI responsive
2. **Worker Pools for Node.js** - Utilize all CPU cores
3. **Caching** - Cache results for identical graphs
4. **Batch Processing** - Process multiple graphs in parallel
5. **Algorithm Selection** - Choose appropriate algorithm for graph size

### Error Handling

```typescript
try {
    const result = await computeMinCut(edges);
} catch (error) {
    if (error.message.includes('memory')) {
        // Graph too large, try different algorithm
    } else if (error.message.includes('timeout')) {
        // Computation timeout, use approximate algorithm
    } else {
        // Other errors
    }
}
```

### Security Considerations

1. **Input Validation** - Validate graph size limits
2. **Rate Limiting** - Prevent abuse of compute resources
3. **Timeout Protection** - Set computation timeouts
4. **Resource Limits** - Limit memory usage per request

---

## Next Steps

- [Performance Optimization Guide]./05-performance-optimization.md
- [API Reference]../api/README.md
- [Examples]../../examples/README.md