CHSZLabLib
State-of-the-art graph algorithms of the Algorithm Engineering Group Heidelberg from C++
Easy to use in Python
Python frontend for C++ algorithm libraries.
Built for humans and AI agents.
For scientific studies: If you use any of the algorithms in a research paper, please cite and refer to the original repositories listed in the table below. Those repositories contain the full documentation, parameter spaces, and experimental setups used in the respective publications and give full credit to the respective authors.
For maximum performance: The bundled C++ libraries are compiled with default settings for broad compatibility. For peak performance and access to every tuning knob, use the latest main branch of the original repositories directly (linked in the table below). The python front end is meant for usability, not for performance measurements.
Super Quick Start
python3 -m venv chszlab_env
source chszlab_env/bin/activate
pip install chszlablib
Or via Homebrew (macOS 15+ ARM64, Linux x86_64):
brew tap CHSZLab/chszlablib
brew trust chszlab/chszlablib # Homebrew 7+ only loads formulae from trusted taps
brew install chszlablib
About
The Algorithm Engineering Group Heidelberg at Heidelberg University develops high-performance C++ algorithms for a wide range of combinatorial optimization problems on graphs — graph partitioning, minimum and maximum cuts, community detection, independent sets, edge orientation, and more. These solvers represent the state of the art in their respective domains.
CHSZLabLib wraps some of these libraries into a single, easy-to-use Python interface. Graph and HyperGraph objects, consistent method signatures, typed result objects, and zero-copy NumPy arrays — designed to be productive for end users and fully discoverable by AI agents (LLMs).
For full algorithmic control (custom parameter tuning, every possible knob), use the underlying C/C++ repositories directly. This library prioritizes convenience and a unified interface – not full speed.
Group Members (Main Contributors)
Current:
- Christian Schulz (Group Leader)
- Adil Chhabra (PhD Student)
- Henning Woydt (PhD Student)
- Kenneth Langedal (PostDoc)
- Ernestine Großmann (PostDoc, former PhD)
- Henrik Reinstädtler (PostDoc, former PhD)
Student Research Assistants:
- Fabian Walliser
- Shai Dorian Peretz
- Markus Everling
Alumni:
- Alexander Noe (PhD)
- Marcelo Fonseca Faraj (PhD)
- Antonie Lea Wagner (Student Research Assistant)
- Marlon Dittes (Student Research Assistant)
- Jannick Borowitz (Student Research Assistant)
- Dominik Schweisgut (Student Research Assistant)
- Thomas Möller (Student Research Assistant)
- Patrick Steil (Student Research Assistant)
- Joseph Holten (Student Research Assistant)
Collaborators (Full List → EOF)
- S. M. Ferdous
- Monika Henzinger
- Ivor van der Hoog
- Felix Joos
- Henning Meyerhenke
- Matthias Mnich
- Alex Pothen
- Eva Rotenberg
- Peter Sanders
- Sebastian Schlag
- Daniel Seemaier
- Darren Strash
- Jesper Larsson Träff
- Bora Ucar
Table of Contents
Overview of Integrated Libraries
Decomposition — Partitioning
| Library |
Domain |
Algorithms |
| KaHIP |
Graph partitioning |
KaFFPa (7 modes incl. ultra), connected blocks, KaFFPaE (evolutionary), node separators, nested dissection |
| HeiStream |
Streaming partitioning |
Fennel, BuffCut, parallel pipeline, restreaming |
| FREIGHT |
Streaming hypergraph partitioning |
Fennel, Fennel Approx Sqrt, LDG, Hashing (one-pass, O(k+nets) memory) |
| SharedMap |
Process mapping |
Hierarchical process mapping (fast/eco/strong modes) |
Decomposition — Clustering
| Library |
Domain |
Algorithms |
| VieClus |
Community detection |
Modularity-maximizing evolutionary clustering, optional Leiden mode (connected clusters) |
| SCC |
Correlation clustering |
Label propagation + evolutionary on signed graphs |
| HeidelbergMotifClustering |
Local clustering |
Triangle-motif-based flow and partitioning methods |
| CluStRE |
Streaming graph clustering |
Streaming modularity clustering with restreaming and local search |
Decomposition — Cuts
| Library |
Domain |
Algorithms |
| VieCut |
Minimum cuts |
Inexact (parallel heuristic), Exact (parallel), Cactus (parallel), Stoer-Wagner |
| fpt-max-cut |
Maximum cut |
FPT kernelization + heuristic/exact solvers |
| HeiCut |
Hypergraph minimum cut |
Kernelization, submodular minimization, ILP, k-trimmed certificates |
IndependenceProblems — Maximum independent set and maximum weight independent set.
| Library |
Domain |
Algorithms |
| KaMIS |
Independent set |
ReduMIS, OnlineMIS, Branch&Reduce, MMWIS |
| CHILS |
Weighted independent set |
Concurrent heuristic independent local search |
| LearnAndReduce |
MWIS kernelization |
GNN-guided reduction rules + kernel solve + lift |
| HyperMIS |
Hypergraph independent set |
Kernelization reductions + exact ILP on the kernel (Gurobi) |
| HeiHGM/Bmatching |
Hypergraph b-matching |
Greedy (7 orderings), reductions+ILP+unfold, ILS |
| HeiHGM/Streaming |
Streaming hypergraph matching |
Naive, greedy, greedy_set, best_evict, lenient |
| red2pack |
Maximum 2-packing set |
Exact, DRP, CHILS, HtWIS, HILS, MMWIS, OnlineMIS, ILP |
Orientation — Edge orientation for minimum maximum out-degree.
| Library |
Domain |
Algorithms |
| HeiOrient |
Edge orientation |
2-approx greedy, DFS local search, Eager Path Search |
DynamicProblems — Fully dynamic graph algorithms (insert/delete edges incrementally).
| Library |
Domain |
Algorithms |
| DynDeltaOrientation |
Dynamic edge orientation |
BFS, K-Flips, Random Walk, Brodal-Fagerberg, Naive/Improved/Strong Opt |
| DynDeltaApprox |
Dynamic edge orientation (approx) |
CCHHQRS, Limited/Strong/Improved BFS, Packed CCHHQRS variants |
| DynMatch |
Dynamic matching |
Blossom, Random Walk, Baswana-Gupta-Sen, Neiman-Solomon, Static Blossom |
| DynWMIS |
Dynamic weighted MIS |
Simple, Greedy, Degree-Greedy, BFS, Static (with KaMIS fork) |
Quick Start
1. Install CHSZLabLib:
python3 -m venv chszlab_env
source chszlab_env/bin/activate
pip install chszlablib
Or via Homebrew:
brew tap CHSZLab/chszlablib
brew trust chszlab/chszlablib # Homebrew 7+ only loads formulae from trusted taps
brew install chszlablib
2. Download a sample graph from the 10th DIMACS Implementation Challenge:
wget https://sites.cc.gatech.edu/dimacs10/archive/data/clustering/cond-mat-2005.graph.bz2
bunzip2 cond-mat-2005.graph.bz2
3. Run the demo (exercises all 26 algorithm modules on the downloaded graph):
wget https://raw.githubusercontent.com/CHSZLab/CHSZLabLib/main/examples/demo.py
python3 demo.py cond-mat-2005.graph
4. Or try it in Python directly:
from chszlablib import Graph, Decomposition, IndependenceProblems, Orientation, DynamicProblems
# Build a small graph
g = Graph(num_nodes=6)
for u, v in [(0,1), (1,2), (2,0), (3,4), (4,5), (5,3), (2,3)]:
g.add_edge(u, v)
# --- Partitioning (KaHIP) ---
p = Decomposition.partition(g, num_parts=2, mode="strong")
print(f"Edge cut: {p.edgecut}, assignment: {p.assignment}")
# Every block a connected subgraph (KaHIP connected blocks)
cp = Decomposition.partition(g, num_parts=2, mode="strong", connected_blocks=True)
# Evolutionary partitioning (KaHIP)
ep = Decomposition.evolutionary_partition(g, num_parts=2, time_limit=5)
print(f"Evolutionary edge cut: {ep.edgecut}")
# Node separator (KaHIP)
ns = Decomposition.node_separator(g, mode="eco")
print(f"Separator size: {ns.num_separator_vertices}")
# Nested dissection ordering (KaHIP)
nd = Decomposition.node_ordering(g, mode="eco")
print(f"Ordering: {nd.ordering}")
# --- Streaming partitioning (HeiStream) ---
sp = Decomposition.stream_partition(g, k=3, imbalance=3.0)
print(f"Stream assignment: {sp.assignment}")
# --- Streaming hypergraph partitioning (FREIGHT) ---
from chszlablib import HyperGraph
hg = HyperGraph.from_edge_list([[0, 1, 2], [2, 3, 4], [4, 5, 0]], num_nodes=6)
shp = Decomposition.stream_hypergraph_partition(hg, k=2)
print(f"Hypergraph partition: {shp.assignment}")
# --- Process mapping (SharedMap) ---
pm = Decomposition.process_map(g, hierarchy=[2, 3], distance=[1, 10], mode="fast")
print(f"Communication cost: {pm.comm_cost}, PE assignment: {pm.assignment}")
# --- Community detection (VieClus) ---
c = Decomposition.cluster(g, time_limit=1.0)
print(f"Modularity: {c.modularity:.4f}, clusters: {c.num_clusters}")
# --- Correlation clustering (SCC) ---
cc = Decomposition.correlation_clustering(g, time_limit=1.0)
print(f"Correlation clusters: {cc.num_clusters}, edge cut: {cc.edge_cut}")
# Evolutionary correlation clustering (SCC)
ecc = Decomposition.evolutionary_correlation_clustering(g, time_limit=5.0)
print(f"Evo correlation clusters: {ecc.num_clusters}, edge cut: {ecc.edge_cut}")
# --- Local motif clustering (HeidelbergMotifClustering) ---
mc = Decomposition.motif_cluster(g, seed_node=0, method="social")
print(f"Motif cluster: {mc.cluster_nodes}, conductance: {mc.motif_conductance:.4f}")
# --- Streaming graph clustering (CluStRE) ---
sc = Decomposition.stream_cluster(g, mode="strong")
print(f"Clusters: {sc.num_clusters}, modularity: {sc.modularity:.4f}")
# --- Global minimum cut (VieCut) ---
mc = Decomposition.mincut(g, algorithm="inexact")
print(f"Min-cut value: {mc.cut_value}")
# --- Maximum cut (fpt-max-cut) ---
mxc = Decomposition.maxcut(g, method="heuristic", time_limit=1.0)
print(f"Max-cut value: {mxc.cut_value}")
# --- Hypergraph minimum cut (HeiCut) ---
hg2 = HyperGraph.from_edge_list([[0, 1, 2], [2, 3, 4], [4, 5]])
r = Decomposition.hypergraph_mincut(hg2, algorithm="kernelizer")
print(f"Hypergraph min-cut: {r.cut_value}, time: {r.time:.2f}s")
# --- Maximum independent set (KaMIS) ---
r = IndependenceProblems.redumis(g, time_limit=5.0)
print(f"MIS (ReduMIS): size {r.size}")
r = IndependenceProblems.online_mis(g, time_limit=5.0)
print(f"MIS (OnlineMIS): size {r.size}")
# --- Maximum weight independent set (KaMIS) ---
for i in range(g.num_nodes):
g.set_node_weight(i, (i + 1) * 10)
r = IndependenceProblems.branch_reduce(g, time_limit=5.0)
print(f"MWIS (Branch&Reduce): weight {r.weight}")
r = IndependenceProblems.mmwis(g, time_limit=5.0)
print(f"MWIS (MMWIS): weight {r.weight}")
# --- Maximum weight independent set (CHILS) ---
r = IndependenceProblems.chils(g, time_limit=5.0, num_concurrent=4)
print(f"MWIS (CHILS): weight {r.weight}, vertices: {r.vertices}")
# --- GNN-guided MWIS kernelization (LearnAndReduce) ---
r = IndependenceProblems.learn_and_reduce(g, time_limit=5.0)
print(f"MWIS (LearnAndReduce): weight {r.weight}")
# --- Hypergraph independent set (HyperMIS) ---
hg3 = HyperGraph.from_edge_list([[0, 1, 2], [2, 3, 4], [4, 5]])
r = IndependenceProblems.hypermis(hg3, time_limit=5.0)
print(f"Hypergraph IS size: {r.size}, vertices: {r.vertices}")
# --- Hypergraph b-matching (HeiHGM) ---
from chszlablib import StreamingBMatcher
hg4 = HyperGraph.from_edge_list([[0,1],[1,2],[2,3],[3,4]], num_nodes=5, edge_weights=[5,3,7,2])
r = IndependenceProblems.bmatching(hg4, algorithm="greedy_weight_desc")
print(f"B-matching: {r.num_matched} edges, weight {r.total_weight}")
# --- Streaming hypergraph matching (HeiHGM) ---
sm = StreamingBMatcher(5, algorithm="greedy")
for nodes, w in [([0,1], 5), ([1,2], 3), ([2,3], 7), ([3,4], 2)]:
sm.add_edge(nodes, w)
r = sm.finish()
print(f"Streaming matching: {r.num_matched} edges, weight {r.total_weight}")
# --- Maximum 2-packing set (red2pack) ---
from chszlablib import TwoPackingKernel
g2 = Graph.from_edge_list([(0,1),(1,2),(2,3),(3,4)])
r = IndependenceProblems.two_packing(g2, algorithm="chils", time_limit=10.0)
print(f"2-packing: {r.size} vertices, weight {r.weight}")
# --- Edge ori
提示:代码过长已自动截断
Build from Source
git clone --recursive https://github.com/CHSZLab/CHSZLabLib.git
cd CHSZLabLib
bash build.sh
The build script handles everything automatically:
- Initializes and updates all Git submodules
- Creates a Python virtual environment in
.venv/
- Compiles all C/C++ extensions via CMake + pybind11
- Builds and installs the Python wheel
- Runs the full test suite
Requirements:
| Dependency |
Version |
| Python |
>= 3.9 |
| C++ compiler |
GCC or Clang with C++17 support |
| CMake |
>= 3.15 |
| NumPy |
>= 1.20 |
Optional dependencies:
| Package |
Purpose |
networkx |
Graph.from_networkx() / to_networkx() conversions |
scipy |
Graph.from_scipy_sparse() / to_scipy_sparse() conversions |
gurobipy |
Exact ILP solver used by IndependenceProblems.hypermis — requires a Gurobi license |
| OpenMP |
Optional (enables parallelism in VieClus, CHILS, HeiStream) |
Graph Construction
All algorithms operate on the Graph class, which stores data in Compressed Sparse Row (CSR) format. Three construction methods are available:
Builder API (edge-by-edge)
from chszlablib import Graph
g = Graph(num_nodes=5)
g.add_edge(0, 1, weight=3)
g.add_edge(1, 2)
g.add_edge(2, 3, weight=7)
g.add_edge(3, 4)
g.set_node_weight(0, 10)
g.finalize() # converts to CSR; auto-called on first property access
print(g.num_nodes) # 5
print(g.num_edges) # 4
print(g.xadj) # CSR row pointers
print(g.adjncy) # CSR column indices
print(g.edge_weights) # per-entry edge weights
print(g.node_weights) # per-node weights
Direct CSR construction
For large graphs or interoperability with SciPy/NetworkX:
import numpy as np
from chszlablib import Graph
# 4-node cycle: 0-1-2-3-0
g = Graph.from_csr(
xadj = np.array([0, 2, 4, 6, 8]),
adjncy = np.array([1, 3, 0, 2, 1, 3, 0, 2]),
edge_weights = np.array([1, 2, 1, 3, 3, 5, 2, 5]), # optional
)
From METIS file
from chszlablib import Graph, read_metis
# Class method
g = Graph.from_metis("mesh.graph")
# Module function (equivalent)
g = read_metis("mesh.graph")
# Write back
g.to_metis("output.graph")
From edge list
from chszlablib import Graph
g = Graph.from_edge_list([(0, 1), (1, 2), (2, 3)]) # unweighted
g = Graph.from_edge_list([(0, 1, 5), (1, 2, 3)], num_nodes=4) # weighted, explicit node count
From NetworkX / SciPy (optional dependencies)
import networkx as nx
from chszlablib import Graph
# NetworkX → CHSZLabLib
g = Graph.from_networkx(nx.karate_club_graph())
# CHSZLabLib → NetworkX
G_nx = g.to_networkx()
# SciPy CSR ↔ CHSZLabLib
import scipy.sparse as sp
g = Graph.from_scipy_sparse(csr_matrix)
A = g.to_scipy_sparse()
# Graph → HyperGraph (each edge becomes a size-2 hyperedge)
hg = g.to_hypergraph()
HyperGraph Construction
For algorithms that operate on hypergraphs (edges connecting two or more vertices), use the HyperGraph class. It stores data in dual CSR format — both vertex-to-edge and edge-to-vertex adjacency arrays.
Builder API (edge-by-edge)
from chszlablib import HyperGraph
hg = HyperGraph(num_nodes=5, num_edges=2)
hg.set_edge(0, [0, 1, 2]) # hyperedge 0 contains vertices {0, 1, 2}
hg.set_edge(1, [2, 3, 4]) # hyperedge 1 contains vertices {2, 3, 4}
hg.set_node_weight(0, 10)
hg.set_edge_weight(1, 5)
hg.finalize() # converts to dual CSR; auto-called on first property access
print(hg.num_nodes) # 5
print(hg.num_edges) # 2
print(hg.eptr, hg.everts) # edge-to-vertex CSR
print(hg.vptr, hg.vedges) # vertex-to-edge CSR
From edge list
hg = HyperGraph.from_edge_list(
[[0, 1, 2], [2, 3, 4], [4, 5]],
node_weights=np.array([1, 2, 3, 4, 5, 6]), # optional
)
From a graph
from chszlablib import Graph, HyperGraph
g = Graph.from_edge_list([(0, 1, 5), (1, 2, 3)])
hg = HyperGraph.from_graph(g) # each edge → size-2 hyperedge, weights preserved
From hMETIS file
from chszlablib import HyperGraph, read_hmetis
hg = HyperGraph.from_hmetis("mesh.hgr") # class method
hg = read_hmetis("mesh.hgr") # module function (equivalent)
hg.to_hmetis("output.hgr") # write back
Clique expansion (HyperGraph → Graph)
Convert a hypergraph to a regular graph by replacing each hyperedge with a clique over its vertices:
g = hg.to_graph() # returns a Graph; can be used with any graph algorithm
API Reference
The library organizes algorithms into four namespace classes. Each class is a pure namespace (no instantiation) with static methods. Methods take a Graph (or HyperGraph where noted) and return a typed dataclass with NumPy arrays.
Decomposition
Graph decomposition: partitioning, clustering, cuts, and process mapping.
Partitioning
Clustering
Cuts
Decomposition.partition(g, ...) — Balanced Graph Partitioning (KaHIP)
Problem. Given an undirected graph $G = (V, E)$ with node weights $c : V \to \mathbb{R}{\geq 0}$ and edge weights $\omega : E \to \mathbb{R}{\geq 0}$, find a partition of $V$ into $k$ disjoint blocks $V_1, \dotsc, V_k$ that minimizes the edge cut
$$\text{cut}(\mathcal{P}) = \sum_{\substack{\lbrace u,v \rbrace \in E \ \pi(u) \neq \pi(v)}} \omega(\lbrace u,v \rbrace),$$
where $\pi(v)$ denotes the block of node $v$, subject to the balance constraint
$$c(V_i) \leq (1 + \varepsilon) \left\lceil \frac{c(V)}{k} \right\rceil \quad \text{for all } i = 1, \dotsc, k,$$
where $\varepsilon \geq 0$ is the allowed imbalance. The problem is NP-hard; KaHIP uses a multilevel approach with local search refinement.
Decomposition.partition(g, num_parts=2, mode="eco", imbalance=0.03, seed=0,
connected_blocks=False) -> PartitionResult
| Parameter |
Type |
Default |
Description |
num_parts |
int |
2 |
Number of blocks |
mode |
str |
"eco" |
Quality/speed trade-off |
imbalance |
float |
0.03 |
Allowed weight imbalance (0.03 = 3%) |
seed |
int |
0 |
Random seed for reproducibility |
connected_blocks |
bool |
False |
Make every block a connected subgraph (requires mode="strong" and a connected input graph) |
Partitioning modes:
| Mode |
Speed |
Quality |
Best for |
"fast" |
Fastest |
Good |
Large-scale exploration |
"eco" |
Balanced |
Very good |
Default choice |
"strong" |
Slow |
Very high |
Final production partitions |
"ultra" |
Slowest (~2x "strong") |
Best |
Highest quality (KaHIP v3.28 preconfiguration) |
"fastsocial" |
Fastest |
Good |
Social / power-law networks |
"ecosocial" |
Balanced |
Very good |
Social / power-law networks |
"strongsocial" |
Slowest |
Best |
Social / power-law networks |
node_separator and node_ordering accept the same modes except "ultra".
Connected blocks. With connected_blocks=True, KaHIP ensures that every block induces a connected subgraph, using connectivity-aware refinement, component elimination and greedy rebalancing. This is supported only with mode="strong"; other modes raise ValueError. If the input graph is disconnected, connected blocks cannot be guaranteed.
Result: PartitionResult — edgecut (int), assignment (ndarray).
from chszlablib import Graph, Decomposition
g = Graph.from_metis("mesh.graph")
p = Decomposition.partition(g, num_parts=8, mode="strong", imbalance=0.01)
print(f"Edgecut: {p.edgecut}")
u = Decomposition.partition(g, num_parts=8, mode="ultra")
c = Decomposition.partition(g, num_parts=8, mode="strong", connected_blocks=True)
Decomposition.evolutionary_partition(g, ...) — Evolutionary Balanced Graph Partitioning (KaHIP)
Problem. Same objective as partition (minimize edge cut subject to balance constraints). KaFFPaE solves this using a memetic (evolutionary) algorithm: a population of partitions is maintained and improved through recombination operators and multilevel local search over a given time budget. Supports warm-starting from an existing partition to refine a previously computed solution.
Decomposition.evolutionary_partition(g, num_parts, time_limit, mode="strong",
imbalance=0.03, seed=0,
initial_partition=None,
connected_blocks=False) -> PartitionResult
Modes: all partition modes (including "ultra") plus "ultrafastsocial". connected_blocks=True (with mode="strong") makes every block a connected subgraph, as in partition.
Result: PartitionResult with edgecut, assignment, and balance.
from chszlablib import Graph, Decomposition
g = Graph.from_metis("large_mesh.graph")
seed_part = Decomposition.partition(g, num_parts=16, mode="eco")
refined = Decomposition.evolutionary_partition(
g, num_parts=16, time_limit=60,
initial_partition=seed_part.assignment,
)
print(f"Refined edgecut: {refined.edgecut} (balance: {refined.balance:.4f})")
Decomposition.node_separator(g, ...) — Balanced Node Separator (KaHIP)
Problem. Given an undirected graph $G = (V, E)$, find a set $S \subset V$ of minimum cardinality such that removing $S$ partitions $V \setminus S$ into two non-empty sets $A$ and $B$ with no edges between them, i.e., $\lbrace u, v \rbrace \notin E$ for all $u \in A, v \in B$, subject to the balance constraint
$$\max\bigl(|A|, |B|\bigr) \leq (1 + \varepsilon) \left\lceil \frac{|V \setminus S|}{2} \right\rceil.$$
Node separators are a fundamental tool in divide-and-conquer algorithms, nested dissection orderings for sparse matrix factorization, and VLSI design.
Decomposition.node_separator(g, num_parts=2, mode="eco", imbalance=0.03, seed=0) -> SeparatorResult
Result: SeparatorResult — num_separator_vertices (int), separator (ndarray).
Decomposition.node_ordering(g, ...) — Nested Dissection Ordering (KaHIP)
Problem. Given a sparse symmetric positive-definite matrix $A$ (represented as its adjacency graph $G$), compute a permutation $\sigma$ of $\lbrace 0, \dotsc, n-1 \rbrace$ such that the fill-in — the number of new non-zeros introduced during Cholesky factorization of $P A P^T$ — is minimized. The algorithm uses recursive nested dissection: it finds a node separator $S$, orders $S$ last, then recurses on the two disconnected subgraphs. High-quality separators (via KaHIP) yield orderings that significantly reduce fill-in and factorization time for large sparse systems.
Decomposition.node_ordering(g, mode="eco", seed=0) -> OrderingResult
Result: OrderingResult — ordering (ndarray permutation).
Decomposition.stream_partition(g, ...) — Streaming Graph Partitioning (HeiStream)
Problem. Same objective as partition — minimize the edge cut subject to balance constraints — but solved in a streaming model where nodes and their adjacencies are presented sequentially and each node must be assigned to a block upon arrival (or after a bounded buffer delay). The algorithm requires $O(n + B)$ memory where $B$ is the buffer size, compared to $O(n + m)$ for full in-memory partitioning. HeiStream supports Fennel (direct one-pass assignment), BuffCut (buffered assignment with local optimization), and restreaming (multiple passes for improved quality).
Decomposition.stream_partition(g, k=2, imbalance=3.0, seed=0, max_buffer_size=0,
batch_size=0, num_streams_passes=1,
run_parallel=False) -> StreamPartitionResult
Result: StreamPartitionResult — assignment (ndarray).
HeiStreamPartitioner — Incremental Streaming Partitioning (HeiStream)
Problem. Same as stream_partition, but exposes a node-by-node streaming interface for scenarios where the graph is not available as a complete Graph object — e.g., when edges arrive from a network stream, a database cursor, or an online graph generator.
from chszlablib import HeiStreamPartitioner
hs = HeiStreamPartitioner(k=4, imbalance=3.0, max_buffer_size=1000)
hs.new_node(0, [1, 2])
hs.new_node(1, [0, 3])
hs.new_node(2, [0])
hs.new_node(3, [1])
result = hs.partition()
print(result.assignment)
hs.reset() # reuse for a different graph
Decomposition.stream_hypergraph_partition(hg, ...) — Streaming Hypergraph Partitioning (FREIGHT)
Problem. Given a hypergraph $H = (V, E)$ with vertex weights and hyperedge weights, partition $V$ into $k$ blocks minimizing the cut-net or connectivity objective, using a streaming model where nodes are processed sequentially in a single pass. FREIGHT extends the Fennel objective to hypergraphs and requires only $O(k + |E|)$ memory — the full hypergraph is never stored.
Decomposition.stream_hypergraph_partition(hg, k=2, imbalance=3.0, algorithm="fennel_approx_sqrt",
objective="cut_net", seed=0, num_streams_passes=1,
hierarchical=False, suppress_output=True) -> StreamHypergraphPartitionResult
| Parameter |
Type |
Default |
Description |
hg |
HyperGraph |
— |
Input hypergraph |
k |
int |
2 |
Number of partition blocks (>= 2) |
imbalance |
float |
3.0 |
Allowed imbalance in percent |
algorithm |
str |
"fennel_approx_sqrt" |
Algorithm variant |
objective |
str |
"cut_net" |
"cut_net" or "connectivity" |
seed |
int |
0 |
Random seed |
num_streams_passes |
int |
1 |
Restreaming passes for improved quality |
hierarchical |
bool |
False |
Enable hierarchical recursive bisection |
Algorithms:
| Algorithm |
Identifier |
Characteristics |
| Fennel Approx Sqrt |
"fennel_approx_sqrt" |
Default; fast square-root approximation |
| Fennel |
"fennel" |
Full Fennel objective with exact power computation |
| LDG |
"ldg" |
Linear Deterministic Greedy |
| Hashing |
"hashing" |
Random assignment (fastest, lowest quality) |
Result: StreamHypergraphPartitionResult — assignment (ndarray, partition block ID per node).
from chszlablib import HyperGraph, Decomposition
hg = HyperGraph.from_edge_list([[0, 1, 2], [2, 3, 4], [4, 5, 0]], num_nodes=6)
result = Decomposition.stream_hypergraph_partition(hg, k=2, algorithm="fennel")
print(f"Assignment: {result.assignment}")
FreightPartitioner — True Streaming Hypergraph Partitioning (FREIGHT)
Problem. Same as stream_hypergraph_partition, but exposes a node-by-node streaming interface for scenarios where the hypergraph is not available as a complete HyperGraph object. Each assign_node() call immediately returns the partition block ID. Memory: $O(k + |E|)$ — the full hypergraph is never stored.
from chszlablib import FreightPartitioner
fp = FreightPartitioner(num_nodes=6, num_nets=3, k=2)
block = fp.assign_node(0, nets=[[0, 1, 2], [0, 4, 5]]) # returns block ID immediately
block = fp.assign_node(1, nets=[[0, 1, 2]])
# ... assign remaining nodes ...
result = fp.get_assignment() # -> StreamHypergraphPartitionResult
Nets are identified by their sorted vertex sets — [0, 2, 1] and [0, 1, 2] are automatically recognized as the same net.
Decomposition.process_map(g, ...) — Hierarchical Process Mapping (SharedMap)
Problem. Given a communication graph where edge weights represent communication volume and a hierarchical machine description, assign processes to processing elements minimizing total weighted communication cost across hierarchy levels.
SharedMap uses KaHIP for serial partitioning and Mt-KaHyPar for parallel partitioning with configurable quality/speed trade-offs. See docs/process-mapping.md for full parameter documentation.
from chszlablib import Graph, Decomposition
g = Graph.from_edge_list([(0,1,10), (1,2,20), (2,3,10), (3,0,20)])
# Map to 2 nodes x 2 cores (4 PEs), intra-node cost=1, inter-node cost=10
result = Decomposition.process_map(g, hierarchy=[2, 2], distance=[1, 10], mode="fast")
print(f"Communication cost: {result.comm_cost}")
print(f"PE assignment: {result.assignment}")
Parameters: hierarchy (list of ints — machine levels, e.g. [4, 8] = 4 nodes x 8 cores), distance (list of ints — cost per level, same length as hierarchy), mode ("fast", "eco", "strong"), imbalance (float, default 0.03), threads (int, default 1), seed (int).
Result: ProcessMappingResult — comm_cost (int), assignment (ndarray[int32], PE index per vertex).
Problem. Given an undirected graph $G = (V, E)$ with $m = |E|$, find a partition $\mathcal{C} = \lbrace C_1, \dotsc, C_k \rbrace$ of $V$ — where $k$ is determined automatically — that maximizes the Newman–Girvan modularity
$$Q = \frac{1}{2m} \sum_{u, v \in V} \left[ A_{uv} - \frac{d_u ~ d_v}{2m} \right] \delta\bigl(c(u), c(v)\bigr),$$
where $A_{uv}$ is the adjacency matrix entry, $d_v$ is the degree of node $v$, $c(v)$ denotes the cluster of $v$, and $\delta$ is the Kronecker delta. Modularity quantifies the density of edges within clusters relative to a random graph with the same degree sequence. VieClus uses an evolutionary algorithm with multilevel refinement to maximize this objective. With leiden=True, VieClus uses the Leiden algorithm (Traag, Waltman, van Eck, 2019) instead of Louvain as its core clustering method, which guarantees that every cluster is a connected subgraph; leiden_theta (default 0.01) is the Leiden refinement temperature.
Decomposition.cluster(g, time_limit=1.0, seed=0, cluster_upperbound=0, leiden=False, leiden_theta=0.01) -> ClusterResult
Result: ClusterResult — modularity (float), num_clusters (int), assignment (ndarray).
Decomposition.correlation_clustering(g, ...) — Correlation Clustering (SCC)
Problem. Given a graph $G = (V, E)$ with signed edge weights $\omega : E \to \mathbb{R}$, find a partition $\mathcal{C}$ of $V$ into an arbitrary number of clusters that minimizes the edge cut, i.e., the sum of all edge weights between clusters:
$$\text{cut}(\mathcal{C}) = \sum_{\substack{\lbrace u,v \rbrace \in E \ c(u) \neq c(v)}} \omega(\lbrace u,v \rbrace).$$
Unlike standard clustering, the number of clusters $k$ is not fixed but determined by the optimization. SCC uses multilevel label propagation to solve this efficiently.
Decomposition.correlation_clustering(g, seed=0, time_limit=0) -> CorrelationClusteringResult
Decomposition.evolutionary_correlation_clustering(g, ...) — Evolutionary Correlation Clustering (SCC)
Problem. Same objective as correlation_clustering (minimize edge cut on a signed graph). This variant uses a population-based memetic evolutionary algorithm that maintains a pool of clusterings and improves them through recombination and multilevel local search over a given time budget, yielding higher-quality solutions at the cost of increased runtime.
Decomposition.evolutionary_correlation_clustering(g, seed=0, time_limit=5.0) -> CorrelationClusteringResult
Result: CorrelationClusteringResult — edge_cut (int), num_clusters (int), assignment (ndarray).
Decomposition.motif_cluster(g, ...) — Local Motif Clustering (HeidelbergMotifClustering)
Problem. Given an undirected graph $G = (V, E)$ and a seed node $v \in V$, find a cluster $C \ni v$ that minimizes the triangle-motif conductance
$$\phi_{\triangle}© = \frac{t_{\partial}©}{\min\bigl(t©, t(V \setminus C)\bigr)},$$
where $t©$ is the number of triangles with all three vertices in $C$, and $t_{\partial}©$ is the number of triangles with vertices in both $C$ and $V \setminus C$. Unlike global clustering, this operates locally — the algorithm explores only the neighborhood of the seed node via BFS and does not need to process the entire graph. Applications include community detection around a query node in social networks.
Decomposition.motif_cluster(g, seed_node, method="social", bfs_depths=None,
time_limit=60, seed=0) -> MotifClusterResult
| Method |
Identifier |
Characteristics |
| SOCIAL |
"social" |
Flow-based; faster |
| LMCHGP |
"lmchgp" |
Graph-partitioning-based |
Result: MotifClusterResult — cluster_nodes (ndarray), motif_conductance (float).
Decomposition.stream_cluster(g, ...) — Streaming Graph Clustering (CluStRE)
Problem. Given an undirected, unweighted graph $G = (V, E)$, find a partition $\mathcal{C} = \lbrace C_1, \dotsc, C_k \rbrace$ of $V$ — where $k$ is determined automatically — that maximizes a modularity-based objective, using a streaming model where nodes are processed sequentially with bounded memory. CluStRE supports multiple streaming passes (restreaming) and local search refinement for improved quality.
Decomposition.stream_cluster(g, mode="strong", seed=0, num_streams_passes=2,
resolution_param=0.5, max_num_clusters=-1,
ls_time_limit=600, ls_frac_time=0.5,
cut_off=0.05, suppress_output=True) -> StreamClusterResult
| Parameter |
Type |
Default |
Description |
g |
Graph |
— |
Input graph (undirected, unweighted; edge weights ignored) |
mode |
str |
"strong" |
Quality/speed trade-off |
seed |
int |
0 |
Random seed |
num_streams_passes |
int |
2 |
Number of streaming passes |
resolution_param |
float |
0.5 |
CPM resolution parameter; higher = more clusters |
max_num_clusters |
int |
-1 |
Maximum clusters (-1 = unlimited) |
ls_time_limit |
int |
600 |
Local search time limit in seconds |
ls_frac_time |
float |
0.5 |
Fraction of total time for local search |
cut_off |
float |
0.05 |
Convergence cut-off for local search |
suppress_output |
bool |
True |
Suppress C++ stdout/stderr |
Clustering modes:
| Mode |
Speed |
Quality |
Best for |
"light" |
Fastest |
Good |
Single-pass, large-scale exploration |
"light_plus" |
Fast |
Better |
Restreaming + local search |
"evo" |
Slower |
Very good |
Evolutionary with quotient graph updates |
"strong" |
Slowest |
Best |
Final production clusterings |
Result: StreamClusterResult — modularity (float), num_clusters (int), assignment (ndarray).
from chszlablib import Graph, Decomposition
g = Graph.from_edge_list([(0,1),(1,2),(2,0),(2,3),(3,4),(4,5),(5,3)])
# Best quality clustering
sc = Decomposition.stream_cluster(g, mode="strong")
print(f"{sc.num_clusters} clusters, modularity={sc.modularity:.4f}")
print(f"Assignment: {sc.assignment}")
# Fast single-pass with higher resolution (more clusters)
sc = Decomposition.stream_cluster(g, mode="light", resolution_param=1.0)
# Control number of clusters
sc = Decomposition.stream_cluster(g, max_num_clusters=3)
CluStReClusterer — Incremental Streaming Clustering (CluStRE)
Problem. Same as stream_cluster, but exposes a node-by-node streaming interface for scenarios where the graph is not available as a complete Graph object — e.g., when edges arrive from a network stream, a database cursor, or an online graph generator.
from chszlablib import CluStReClusterer
cs = CluStReClusterer(mode="strong")
cs.new_node(0, [1, 2])
cs.new_node(1, [0, 3])
cs.new_node(2, [0])
cs.new_node(3, [1])
result = cs.cluster()
print(f"{result.num_clusters} clusters, modularity={result.modularity:.4f}")
Decomposition.mincut(g, ...) — Global Minimum Cut (VieCut)
Problem. Given an undirected graph $G = (V, E)$ with edge weights $\omega : E \to \mathbb{R}_{\geq 0}$, find a partition of $V$ into two non-empty sets $S$ and $\bar{S} = V \setminus S$ that minimizes the cut weight
$$\lambda(G) = \min_{\emptyset \neq S \subset V} \sum_{\substack{\lbrace u,v \rbrace \in E \ u \in S, v \in \bar{S}}} \omega(\lbrace u,v \rbrace).$$
The value $\lambda(G)$ is the edge connectivity of the graph. The minimum cut identifies the most vulnerable bottleneck in a network. Applications include network reliability analysis, image segmentation, and connectivity certification.
Decomposition.mincut(g, algorithm="inexact", seed=0) -> MincutResult
| Algorithm |
Identifier |
Characteristics |
| VieCut (heuristic) |
"inexact" |
Parallel near-linear time; best for large graphs |
| Exact |
"exact" |
Shared-memory parallel exact algorithm |
| Cactus |
"cactus" |
Enumerates all minimum cuts (parallel) |
| Stoer-Wagner |
"sw" |
Exact, sequential; for small and medium graphs |
Result: MincutResult — cut_value (int), partition (ndarray 0/1).
Decomposition.maxcut(g, ...) — Maximum Cut (fpt-max-cut)
Problem. Given an undirected graph $G = (V, E)$ with edge weights $\omega : E \to \mathbb{R}_{\geq 0}$, find a partition of $V$ into two sets $S$ and $\bar{S} = V \setminus S$ that maximizes the cut weight
$$\text{maxcut}(G) = \max_{S \subseteq V} \sum_{\substack{\lbrace u,v \rbrace \in E \ u \in S, v \in \bar{S}}} \omega(\lbrace u,v \rbrace).$$
This is the dual of the minimum cut problem and is NP-hard. The solver applies FPT kernelization rules (parameterized by the number of edges above the Edwards bound) to reduce the instance, followed by either a heuristic or an exact branch-and-bound solver.
Decomposition.maxcut(g, method="heuristic", time_limit=1.0) -> MaxCutResult
| Method |
Identifier |
Characteristics |
| Heuristic |
"heuristic" |
Fast; good for large graphs |
| Exact |
"exact" |
FPT algorithm; feasible when kernelization reduces the instance sufficiently |
Result: MaxCutResult — cut_value (int), partition (ndarray 0/1).
Decomposition.hypergraph_mincut(hg, ...) — Exact Hypergraph Minimum Cut (HeiCut)
Problem. Given a hypergraph $H = (V, E)$ with vertex weights $c : V \to \mathbb{R}{\geq 0}$ and hyperedge weights $\omega : E \to \mathbb{R}{\geq 0}$, find a bipartition of $V$ into two non-empty sets $S$ and $\bar{S} = V \setminus S$ that minimizes the hyperedge cut
$$\lambda(H) = \min_{\emptyset \neq S \subset V} \sum_{\substack{e \in E \ e \cap S \neq \emptyset \ e \cap \bar{S} \neq \emptyset}} \omega(e).$$
A hyperedge $e$ is cut if it has vertices on both sides of the partition. HeiCut provides four exact algorithms, including a kernelization-based approach that typically runs orders of magnitude faster than solving the full instance directly.
Decomposition.hypergraph_mincut(hg, algorithm="kernelizer", *, base_solver="submodular",
ilp_timeout=7200.0, ilp_mode="bip",
ordering_type="tight", ordering_mode="single",
seed=0, threads=1, unweighted=False) -> HypergraphMincutResult
| Parameter |
Type |
Default |
Description |
hg |
HyperGraph |
— |
Input hypergraph |
algorithm |
str |
"kernelizer" |
Algorithm to use |
base_solver |
str |
"submodular" |
Base solver for kernelizer: "submodular" or "ilp" |
ilp_timeout |
float |
7200.0 |
ILP time limit in seconds |
ilp_mode |
str |
"bip" |
ILP formulation: "bip" (binary IP) or "milp" (mixed ILP) |
ordering_type |
str |
"tight" |
Vertex ordering for submodular/trimmer |
ordering_mode |
str |
"single" |
"single" or "multi" ordering pass |
seed |
int |
0 |
Random seed |
threads |
int |
1 |
Number of threads |
unweighted |
bool |
False |
Force unit edge weights |
Algorithms:
| Algorithm |
Identifier |
Characteristics |
| Kernelizer |
"kernelizer" |
Kernelization + base solver; fastest in practice |
| ILP |
"ilp" |
Integer linear programming (requires gurobipy) |
| Submodular |
"submodular" |
Submodular function minimization |
| Trimmer |
"trimmer" |
k-trimmed certificates (unweighted only) |
Result: HypergraphMincutResult — cut_value (int), time (float, seconds).
from chszlablib import HyperGraph, Decomposition
hg = HyperGraph.from_edge_list([[0, 1, 2], [1, 2, 3], [2, 3, 4]])
# Kernelizer with submodular base solver (default, fastest)
r = Decomposition.hypergraph_mincut(hg)
print(f"Min cut: {r.cut_value}, time: {r.time:.3f}s")
# Submodular with queyranne ordering
r = Decomposition.hypergraph_mincut(hg, algorithm="submodular", ordering_type="queyranne")
# Multi-threaded kernelizer
r = Decomposition.hypergraph_mincut(hg, algorithm="kernelizer", threads=4)
IndependenceProblems
Maximum independent set, maximum weight independent set, and matching solvers.
| Method |
Problem |
Library |
redumis |
Maximum independent set (evolutionary) |
KaMIS |
online_mis |
Maximum independent set (local search) |
KaMIS |
branch_reduce |
Maximum weight independent set (exact) |
KaMIS |
mmwis |
Maximum weight independent set (evolutionary) |
KaMIS |
chils |
Maximum weight independent set (concurrent local search) |
CHILS |
learn_and_reduce |
Maximum weight independent set (GNN-guided kernelization) |
LearnAndReduce |
two_packing |
Maximum (weighted) 2-packing set (reduce-and-transform) |
red2pack |
hypermis |
Maximum independent set on hypergraphs (reductions + exact ILP) |
HyperMIS |
bmatching |
Hypergraph b-matching (greedy, reductions+ILP, ILS) |
HeiHGM/Bmatching |
StreamingBMatcher |
Streaming hypergraph matching |
HeiHGM/Streaming |
IndependenceProblems.redumis(g, ...) — Maximum Independent Set (KaMIS)
Problem. Given an undirected graph $G = (V, E)$, find an independent set $I \subseteq V$ of maximum cardinality, i.e.,
$$\max_{I \subseteq V} |I| \quad \text{subject to} \quad \lbrace u, v \rbrace \notin E \quad \text{for all } u, v \in I.$$
The maximum independent set problem is NP-hard and hard to approximate. ReduMIS combines graph reduction rules (crown, LP, domination, twin) that provably simplify the instance with an evolutionary algorithm that operates on the reduced kernel.
IndependenceProblems.redumis(g, time_limit=10.0, seed=0) -> MISResult
IndependenceProblems.online_mis(g, ...) — Maximum Independent Set via Local Search (KaMIS)
Problem. Same objective as redumis (maximum cardinality independent set). OnlineMIS uses iterated local search with perturbation and incremental updates — significantly faster but generally produces smaller independent sets than ReduMIS.
IndependenceProblems.online_mis(g, time_limit=10.0, seed=0, ils_iterations=15000) -> MISResult
Result: MISResult — size (int), weight (int), vertices (ndarray).
IndependenceProblems.branch_reduce(g, ...) — Maximum Weight Independent Set, Exact (KaMIS)
Problem. Given an undirected graph $G = (V, E)$ with node weights $c : V \to \mathbb{R}_{\geq 0}$, find an independent set of maximum total weight, i.e.,
$$\max_{I \subseteq V} \sum_{v \in I} c(v) \quad \text{subject to} \quad \lbrace u, v \rbrace \notin E \quad \text{for all } u, v \in I.$$
Branch & Reduce is an exact solver that applies data reduction rules to shrink the instance and then solves the reduced kernel via branch-and-bound. It is guaranteed to find an optimal solution but may require exponential time in the worst case.
IndependenceProblems.branch_reduce(g, time_limit=10.0, seed=0) -> MISResult
IndependenceProblems.mmwis(g, ...) — Maximum Weight Independent Set, Evolutionary (KaMIS)
Problem. Same objective as branch_reduce (maximum weight independent set). MMWIS uses a memetic evolutionary algorithm — a population of independent sets is evolved through recombination and local search, guided by reduction rules. Trades exactness for scalability on larger instances where branch-and-bound is infeasible.
IndependenceProblems.mmwis(g, time_limit=10.0, seed=0) -> MISResult
IndependenceProblems.chils(g, ...) — Maximum Weight Independent Set (CHILS)
Problem. Same objective as branch_reduce (maximum weight independent set). CHILS runs multiple concurrent independent local searches in parallel, each exploring different regions of the solution space. The concurrent design with GNN-accelerated reductions makes it particularly effective for large instances where exact methods are infeasible.
IndependenceProblems.chils(g, time_limit=10.0, num_concurrent=4, seed=0) -> MWISResult
Result: MWISResult — weight (int), vertices (ndarray).
from chszlablib import Graph, IndependenceProblems
g = Graph(num_nodes=5)
for u, v in [(0,1), (1,2), (2,3), (3,4)]:
g.add_edge(u, v)
for i in range(5):
g.set_node_weight(i, (i + 1) * 10)
result = IndependenceProblems.chils(g, time_limit=5.0, num_concurrent=8)
print(f"Weight: {result.weight}, vertices: {result.vertices}")
IndependenceProblems.learn_and_reduce(g, ...) — GNN-Guided MWIS Kernelization (LearnAndReduce)
Problem. Same objective as branch_reduce (maximum weight independent set). LearnAndReduce uses trained graph neural networks to predict which expensive reduction rules will succeed, dramatically speeding up the preprocessing (kernelization) phase. The reduced kernel is then solved with a chosen solver (CHILS, Branch&Reduce, or MMWIS) and the solution is lifted back to the original graph. Also available as a two-step API via LearnAndReduceKernel.
IndependenceProblems.learn_and_reduce(
g, solver="chils", config="cyclic_fast", gnn_filter="initial_tight",
time_limit=1000.0, solver_time_limit=10.0, seed=0, num_concurrent=4,
) -> MWISResult
| Parameter |
Type |
Default |
Description |
g |
Graph |
— |
Input graph with node weights |
solver |
str |
"chils" |
Kernel solver: "chils", "branch_reduce", "mmwis" |
config |
str |
"cyclic_fast" |
Reduction preset: "cyclic_fast" or "cyclic_strong" |
gnn_filter |
str |
"initial_tight" |
GNN filter mode: "initial_tight", "initial", "always", "never" |
time_limit |
float |
1000.0 |
Time limit for kernelization in seconds |
solver_time_limit |
float |
10.0 |
Time limit for the kernel solver in seconds |
Result: MWISResult — size (int), weight (int), vertices (ndarray).
from chszlablib import Graph, IndependenceProblems, LearnAndReduceKernel
import numpy as np
# Full pipeline (one call)
g = Graph.from_metis("weighted_graph.graph")
result = IndependenceProblems.learn_and_reduce(g, solver="chils", time_limit=60.0)
print(f"Weight: {result.weight}, vertices: {result.vertices}")
# Two-step workflow (kernelization-only)
lr = LearnAndReduceKernel(g, config="cyclic_fast")
kernel = lr.kernelize()
if lr.kernel_nodes > 0:
sol = IndependenceProblems.chils(kernel, time_limit=10.0)
result = lr.lift_solution(sol.vertices)
else:
result = lr.lift_solution(np.array([], dtype=np.int32))
print(f"Weight: {result.weight}")
Available constants: IndependenceProblems.LEARN_AND_REDUCE_CONFIGS, LEARN_AND_REDUCE_GNN_FILTERS, LEARN_AND_REDUCE_SOLVERS.
IndependenceProblems.two_packing(g, ...) — Maximum 2-Packing Set (red2pack)
Problem. Given an undirected graph $G = (V, E)$ with optional node weights $c : V \to \mathbb{R}_{\geq 0}$, find a 2-packing set $S \subseteq V$ of maximum (weighted) cardinality, i.e.,
$$\max_{S \subseteq V} \sum_{v \in S} c(v) \quad \text{subject to} \quad \text{dist}(u, v) \geq 3 \quad \text{for all } u, v \in S, u \neq v.$$
A 2-packing set (also called a distance-3 independent set) is a subset of vertices where no two vertices share a common neighbor. red2pack uses a reduce-and-transform strategy: it applies problem-specific reduction rules to shrink the instance, transforms the remainder into an equivalent maximum weight independent set (MWIS) problem, and solves it with a chosen backend solver. Also available as a two-step API via TwoPackingKernel.
IndependenceProblems.two_packing(
g, algorithm="chils", time_limit=100.0, seed=0, reduction_style="",
) -> TwoPackingResult
| Parameter |
Type |
Default |
Description |
g |
Graph |
— |
Input graph (optionally with node weights) |
algorithm |
str |
"chils" |
Algorithm: "exact", "exact_weighted", "chils", "drp", "htwis", "hils", "mmwis", "online", "ilp" |
time_limit |
float |
100.0 |
Time limit in seconds |
seed |
int |
0 |
Random seed for reproducibility |
reduction_style |
str |
"" |
Reduction preset (empty = default reductions) |
Result: TwoPackingResult — size (int), weight (int), vertices (ndarray).
from chszlablib import Graph, IndependenceProblems, TwoPackingKernel
# One-shot solve
g = Graph.from_edge_list([(0,1),(1,2),(2,3),(3,4)])
result = IndependenceProblems.two_packing(g, algorithm="chils", time_limit=10.0)
print(f"2-packing size: {result.size}, vertices: {result.vertices}")
# Two-step workflow (reduce-and-transform, then solve MIS kernel)
tpk = TwoPackingKernel(g)
kernel = tpk.reduce_and_transform()
if tpk.kernel_nodes > 0:
sol = IndependenceProblems.branch_reduce(kernel, time_limit=10.0)
result = tpk.lift_solution(sol.vertices)
else:
import numpy as np
result = tpk.lift_solution(np.array([], dtype=np.int32))
print(f"2-packing weight: {result.weight}, vertices: {result.vertices}")
Available constants: IndependenceProblems.TWO_PACKING_ALGORITHMS. The "ilp" algorithm uses TwoPackingKernel for reduction, then solves the remaining MIS kernel exactly via ILP (requires pip install gurobipy and a valid Gurobi license).
IndependenceProblems.hypermis(hg, ...) — Maximum Independent Set on Hypergraphs (HyperMIS)
Problem. Given a hypergraph $H = (V, E)$ where each hyperedge $e \in E$ contains two or more vertices, find a strongly independent set $I \subseteq V$ of maximum cardinality, i.e.,
$$\max_{I \subseteq V} |I| \quad \text{subject to} \quad |I \cap e| \leq 1 \quad \text{for all } e \in E.$$
This is stricter than graph independence: every hyperedge may contribute at most one vertex to $I$. HyperMIS first applies its kernelization reductions in C++ (including unconfined vertex removal), then solves the remaining kernel exactly via an ILP formulation using gurobipy. Requires pip install gurobipy and a valid Gurobi license.
IndependenceProblems.hypermis(hg, time_limit=60.0, seed=0) -> HyperMISResult
| Parameter |
Type |
Default |
Description |
hg |
HyperGraph |
— |
Input hypergraph |
time_limit |
float |
60.0 |
Time budget in seconds for reductions plus ILP (the ILP gets the time left after reductions) |
seed |
int |
0 |
Random seed for reproducibility |
Result: HyperMISResult — size (int), weight (int), vertices (ndarray), offset (int — vertices fixed by reductions), reduction_time (float — seconds spent reducing), is_optimal (bool — True if the ILP proved optimality).
from chszlablib import HyperGraph, IndependenceProblems
hg = HyperGraph.from_edge_list([[0, 1, 2], [2, 3, 4], [4, 5]])
# Reductions + exact ILP on the kernel (requires: pip install gurobipy)
result = IndependenceProblems.hypermis(hg, time_limit=10.0)
print(f"IS size: {result.size}, vertices: {result.vertices}, optimal: {result.is_optimal}")
Note: Check IndependenceProblems.HYPERMIS_ILP_AVAILABLE at runtime to see if gurobipy is installed; without it, hypermis raises ImportError.
IndependenceProblems.bmatching(hg, ...) — Hypergraph B-Matching (HeiHGM)
Problem. Given a hypergraph $H = (V, E)$ with edge weights $w : E \to \mathbb{R}{\geq 0}$ and vertex capacities $b : V \to \mathbb{Z}{\geq 1}$, find a set of edges $M \subseteq E$ (b-matching) that maximizes
$$\sum_{e \in M} w(e) \quad \text{subject to} \quad |{e \in M : v \in e}| \leq b(v) \quad \forall v \in V.$$
When all capacities are 1, this is a standard maximum weight matching.
IndependenceProblems.bmatching(hg, algorithm="greedy_weight_desc", seed=0,
ils_iterations=15, ils_time_limit=1800.0,
ILP_time_limit=1000.0) -> BMatchingResult
| Parameter |
Type |
Default |
Description |
hg |
HyperGraph |
(required) |
Input hypergraph with edge weights and vertex capacities |
algorithm |
str |
"greedy_weight_desc" |
Algorithm: "greedy_random", "greedy_weight_desc", "greedy_weight_asc", "greedy_degree_asc", "greedy_degree_desc", "greedy_weight_degree_ratio_desc", "greedy_weight_degree_ratio_asc", "reductions", "ils" |
seed |
int |
0 |
Random seed |
ils_iterations |
int |
15 |
Max ILS perturbation iterations (only for "ils") |
ils_time_limit |
float |
1800.0 |
ILS time limit in seconds (only for "ils") |
ILP_time_limit |
float |
1000.0 |
ILP time limit in seconds (only for "reductions") |
Returns BMatchingResult with fields: matched_edges (int array of edge indices), total_weight (float), num_matched (int), is_optimal (bool — True if the ILP solver proved optimality, only for "reductions").
from chszlablib import HyperGraph, IndependenceProblems
hg = HyperGraph.from_edge_list([[0,1],[1,2],[2,3],[3,4]], num_nodes=5, edge_weights=[5,3,7,2])
result = IndependenceProblems.bmatching(hg, algorithm="greedy_weight_desc")
print(f"Matched {result.num_matched} edges, total weight: {result.total_weight}")
# With custom capacities (b-matching)
hg2 = HyperGraph(5, 4)
for i, (edge, w) in enumerate(zip([[0,1],[1,2],[2,3],[3,4]], [5,3,7,2])):
hg2.set_edge(i, edge)
hg2.set_edge_weight(i, w)
hg2.set_capacities([2, 2, 2, 2, 2]) # each node can participate in up to 2 matched edges
result = IndependenceProblems.bmatching(hg2, algorithm="ils")
print(f"B-matching: {result.num_matched} edges, weight: {result.total_weight}")
Note: Valid algorithms are listed in IndependenceProblems.BMATCHING_ALGORITHMS. The "reductions" algorithm applies preprocessing reductions (edge folding, domination removal), solves the reduced instance exactly via ILP (requires gurobipy and a valid Gurobi license), and unfolds to recover a valid matching in the original hypergraph. The result’s is_optimal flag indicates whether Gurobi proved optimality within the time limit. The "ils" algorithm uses iterated local search with perturbation.
StreamingBMatcher — Streaming Hypergraph Matching (HeiHGM)
Problem. Same as b-matching, but edges arrive one at a time in a data stream. Each edge is processed on arrival (single pass), making this suitable for large-scale hypergraphs that don’t fit in memory.
StreamingBMatcher(num_nodes, algorithm="greedy", capacities=None, seed=0, epsilon=0.0)
| Parameter |
Type |
Default |
Description |
num_nodes |
int |
(required) |
Number of vertices |
algorithm |
str |
"greedy" |
Algorithm: "naive", "greedy", "greedy_set", "best_evict", "lenient" |
capacities |
array-like |
None (all ones) |
Per-vertex capacities |
seed |
int |
0 |
Random seed |
epsilon |
float |
0.0 |
Approximation parameter for greedy |
Methods:
add_edge(nodes, weight=1.0) — Feed one hyperedge
finish() -> BMatchingResult — Finalize and return matching
reset() — Reset state for re-streaming
from chszlablib import StreamingBMatcher
sm = StreamingBMatcher(num_nodes=1000, algorithm="greedy")
for nodes, weight in edge_stream: # edges arrive one by one
sm.add_edge(nodes, weight)
result = sm.finish()
print(f"Matched {result.num_matched} edges, weight: {result.total_weight}")
Note: Valid algorithms are listed in StreamingBMatcher.ALGORITHMS. The default "greedy" provides the best quality/speed tradeoff. "naive" is fastest but lowest quali
README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论