MoonBit Classic Graph Algorithm Library

MoonBit Classic · graph algorithm library

Ask a graph a question.

One interface, four storage types, and 24 packages of algorithms written once against it. What runs on this page is the library itself — compiled, not drawn by hand — so the numbers on the board are the numbers the algorithms return.

4
storage types
24
packages
408
functions
4
backends
graph console the library, running
01

The pathfinding bench

drag across the board to raise walls · right-click a cell for the menu
pathfinding bench 16 × 11 · eight-connected
cost
—
cells
—
turns
—
board
16 × 11
02

Three decisions the library is built on

Nodes are numbers

From zero, dense, so an algorithm indexes an array instead of hashing a key. Names and records live in the payload, or in Keyed, which keeps the translation at the edge and hands the numbers inward.

Weights are functions

An edge payload can be anything, so a weight is (Int) -> Double over edge numbers. Give one and the algorithm is weighted; leave it out and every edge costs one.

Refusals name the fault

A negative edge in Dijkstra, a cycle in a topological order, a graph in pieces when a spanning tree was asked for: each comes back as Refused, carrying the node, the edge, or a witness cycle.

03

Four storage types, one interface

an algorithm is written once
TypeShapeParallel edgesAfter a deletionReach for it when
Graph[N, E]adjacency listyesnodes renumbered the default: build it, change it, run algorithms on it
StableGraph[N, E]adjacency list with holesyesnumbers kept you hold node numbers across deletions
Csr[N, E]compressed, both directionsyes— read-only, built once, walked a million times
Matrix[E]V × V cellsnorenumbered dense graphs, and the passes that visit every pair

Every one implements Topology; three also implement Inbound, which adds the view of edges coming the other way. A storage type of your own implements the same traits and gets every algorithm without a conversion.

05

Start here

# add the library
moon add moonbitstack/moongraph

# then, in a package
import {
  "moonbitstack/moongraph",
  "moonbitstack/moongraph/path",
}
let g : @moongraph.Graph[Unit, Double] = @moongraph.Graph::new(directed=false)
for _ in 0..<4 {
  g.add_node(()) |> ignore
}
g.add_edge(0, 1, 2.0) |> ignore
g.add_edge(1, 2, 3.0) |> ignore

let paths = @path.dijkstra(g, 0, weight=g.weights(fn(cost) { cost }))
assert_eq(paths.distance[2], Some(5.0))
assert_eq(paths.path_to(2), Some([0, 1, 2]))
assert_eq(paths.distance[3], None) // node 3 has no edge yet
API

Every function, by package

the full reference, with doc comments →

traverse16 · walks, trees, distances

bfs (G, Int32)
bfs_beam (G, Int32, width? : Int32)
bfs_edges (G, Int32)
bfs_layers (G, Array[Int32])
bfs_tree (G, Int32)
descendants_at (G, Int32, Int32)
dfs (G, Int32)
dfs_events (G, Int32)
dfs_labeled (G, Int32)
dfs_postorder (G, Int32)
dfs_tree (G, Int32)
edge_bfs (G, Int32)
edge_dfs (G, Int32)
Event::equal (Self, Self)
Event::not_equal (Self, Self)
Event::to_repr (Self)

path25 · shortest routes, contraction hierarchies

all_simple (G, Int32, Int32)
all_simple_edges (G, Int32, Int32)
astar (G, Int32, Int32, weight? : (Int32)
bellman_ford (G, Int32, weight? : (Int32)
bfs_all (G)
contraction_hierarchy (G, weight? : (Int32)
dijkstra (G, Int32, weight? : (Int32)
dijkstra_all (G, weight? : (Int32)
dijkstra_bidirectional (G, Int32, Int32, weight? : (Int32)
dijkstra_multi (G, Array[Int32], weight? : (Int32)
floyd_warshall (G, weight? : (Int32)
has_path (G, Int32, Int32)
is_simple_path (G, Array[Int32])
johnson (G, weight? : (Int32)
k_shortest (G, Int32, Int32, Int32, weight? : (Int32)
path_weight (G, Array[Int32], weight? : (Int32)
shortest (G, Int32, Int32, weight? : (Int32)
spfa (G, Int32, weight? : (Int32)
voronoi (G, Array[Int32], weight? : (Int32)
voronoi_cells (G, Array[Int32], weight? : (Int32)
widest (G, Int32, weight? : (Int32)
ContractionHierarchy::path (Self, Int32, Int32)
ContractionHierarchy::query (Self, Int32, Int32)
ContractionHierarchy::rank_of (Self, Int32)
ContractionHierarchy::shortcut_count (Self)

grid26 · board search: BFS, A*, JPS, Theta*, D* Lite

DStar::cost (Self)
DStar::path (Self)
DStar::replan (Self, Int32, Array[Int32])
Grid::a_star (Self, Int32, Int32)
Grid::bfs (Self, Int32, Int32)
Grid::block (Self, Int32, Int32)
Grid::blocked_at (Self, Int32)
Grid::d_star_lite (Self, Int32, Int32)
Grid::dijkstra (Self, Int32)
Grid::estimate (Self, Int32, Int32)
Grid::height (Self)
Grid::inside (Self, Int32, Int32)
Grid::is_blocked (Self, Int32, Int32)
Grid::jps (Self, Int32, Int32)
Grid::line_of_sight (Self, Int32, Int32)
Grid::neighbors (Self, Int32)
Grid::new (Int32, Int32)
Grid::node (Self, Int32, Int32)
Grid::path_cost (Self, Array[Int32])
Grid::step_cost (Self, Int32, Int32)
Grid::straight_cost (Self, Array[Int32])
Grid::theta_star (Self, Int32, Int32)
Grid::unblock (Self, Int32, Int32)
Grid::width (Self)
Grid::x (Self, Int32)
Grid::y (Self, Int32)

flow34 · max flow, min cost, cuts

all_min_cuts (G, Int32, Int32, capacity? : (Int32)
edge_connectivity (G, capacity? : (Int32)
edge_connectivity_pair (G, Int32, Int32)
edge_disjoint_paths (G, Int32, Int32)
flow_cost (G, @moongraph.Flow, cost? : (Int32)
gomory_hu (G, capacity? : (Int32)
k_components (G)
k_edge_components (G, Int32)
max_flow (G, Int32, Int32, capacity? : (Int32)
max_flow_min_cost (G, Int32, Int32, cost? : (Int32)
max_flow_value (G, Int32, Int32, capacity? : (Int32)
min_cost_flow (G, Array[Double], cost? : (Int32)
min_cut (G, Int32, Int32, capacity? : (Int32)
min_cut_global (G, capacity? : (Int32)
min_edge_cut (G)
min_node_cut (G)
node_connectivity (G)
node_connectivity_pair (G, Int32, Int32)
node_disjoint_paths (G, Int32, Int32)
split_network (G, Int32, Int32)
Network::boykov_kolmogorov (Self, Int32, Int32)
Network::build (G, (Int32)
Network::dinitz (Self, Int32, Int32)
Network::edmonds_karp (Self, Int32, Int32)
Network::paths (Self, G, Int32, Int32)
Network::paths_split (Self, Int32, Int32)
Network::push_along (Self, Int32, Int32, Double, Array[Int32], Array[Int32])
Network::push_relabel (Self, Int32, Int32)
Network::reachable (Self, Int32)
Network::report (Self, G)
Network::residual_forward (Self, Int32)
Network::shift (Self, Int32, Int32, (Int32)
Network::solve (Self, Int32, Int32, FlowMethod)
Network::source_side (Self, Int32)

matching12 · pairings, assignments, covers

assignment (G, weight~ : (Int32)
bipartition (G)
edge_cover (G)
is_edge_cover (G, @moongraph.Cover)
is_matching (G, Array[(Int32, Int32)
is_maximal_matching (G, Array[(Int32, Int32)
is_perfect_matching (G, Array[(Int32, Int32)
matching_bipartite (G, weight? : (Int32)
matching_maximal (G)
matching_maximum (G, weight? : (Int32)
matching_min_weight (G, weight~ : (Int32)
vertex_cover_bipartite (G)

color7 · colouring, edge colouring, chromatic number

chromatic_number (G, limit? : Int32)
dsatur (G)
edge_coloring (G)
equitable_coloring (G, Int32)
greedy_coloring (G, order? : ColoringOrder, rng? : &@contract.Rng)
is_coloring (G, @moongraph.Coloring)
is_edge_coloring (G, @moongraph.Coloring)

clique15 · cliques, independent sets, chordality

all_cliques (G, at_least? : Int32)
chordal_cliques (G)
chordal_fill_in (G)
chordal_treewidth (G)
clique_graph (G)
clique_number (G)
clique_numbers (G)
independence_number (G)
is_chordal (G)
is_clique (G, Array[Int32])
is_perfect (G)
max_weight_clique (G, weight~ : (Int32)
maximal_cliques (G)
maximum_independent_set (G)
perfect_elimination_order (G)

approx9 · tours, covers, spanners, treewidth bounds

densest_subgraph (G)
dominating_set (G)
random_rewire (G, rng~ : &@contract.Rng)
spanner (G, stretch? : Int32)
tour_length (G, Array[Int32], weight? : (Int32)
traveling_salesman (G, start~ : Int32, weight? : (Int32)
traveling_salesman_exact (G, start~ : Int32, weight? : (Int32)
treewidth_bound (G)
vertex_cover (G)

component24 · pieces, SCC in order, condensation

articulation_points (G)
attracting_components (G)
biconnected_component_nodes (G)
biconnected_components (G)
bridges (G)
chain_decomposition (G)
component_count (G)
component_of (G, Int32)
components (G)
condensation (G)
edge_boundary (G, Array[Int32])
has_bridges (G)
is_biconnected (G)
is_connected (G)
is_semiconnected (G)
is_strongly_connected (G)
is_weakly_connected (G)
local_bridges (G, span? : Int32)
node_boundary (G, Array[Int32])
reachable_count (G, Int32)
scc (G)
strong_components (G)
strong_components_kosaraju (G)
weak_components (G)

dag22 · topological orders, closures, dominance

all_topological_orders (G)
ancestors (G, Int32)
antichains (G)
colliders (G)
descendants (G, Int32)
dominance_frontiers (G, Int32)
dominators (G, Int32)
is_aperiodic (G)
is_dag (G)
longest_path (G, weight? : (Int32)
longest_path_length (G, weight? : (Int32)
topological_generations (G)
topological_order (G)
topological_smallest (G)
transitive_closure (G)
transitive_reduction (G)
Sorter::add (Self, Int32, Array[Int32])
Sorter::finish (Self, Array[Int32])
Sorter::is_active (Self)
Sorter::new (G)
Sorter::order (Self)
Sorter::ready (Self)

cycle15 · cycles, girth, Euler walks, postman

chinese_postman (G, weight? : (Int32)
chordless_cycles (G, length_bound? : Int32)
cycle_basis (G)
eulerian_circuit (G)
eulerian_path (G)
eulerize (G, weight? : (Int32)
feedback_arc_set (G)
find_cycle (G)
girth (G)
has_eulerian_path (G)
is_cyclic (G)
is_eulerian (G)
min_cycle_ratio (G, cost~ : (Int32)
minimum_cycle_basis (G, weight? : (Int32)
simple_cycles (G)

tree22 · spanning trees, Steiner, centres, LCA

branching_weight (G, @moongraph.Spanning, weight? : (Int32)
broadcast_center (G)
from_nested (Nested)
from_prufer (Array[Int32])
maximum_branching (G, weight? : (Int32)
maximum_spanning (G, weight? : (Int32)
minimum_branching (G, weight? : (Int32)
minimum_spanning (G, weight? : (Int32)
prufer_sequence (G)
random_spanning (G, rng~ : &@contract.Rng)
spanning_count (G)
spanning_trees (G, weight? : (Int32)
steiner_tree (G, Array[Int32], weight? : (Int32)
subtree_sizes (G, Int32)
to_nested (G, Int32)
tree_center (G)
tree_centroid (G)
tree_depth (G, Int32)
Lca::ancestor_at (Self, Int32, Int32)
Lca::depth (Self, Int32)
Lca::new (G, Int32)
Lca::of (Self, Int32, Int32)

centrality13 · degree, closeness, betweenness, PageRank

betweenness_centrality (G)
closeness_centrality (G)
degree_centrality (G)
edge_betweenness (G)
eigenvector_centrality (G, iterations? : Int32, tolerance? : Double)
group_betweenness (G, Array[Int32])
group_closeness (G, Array[Int32])
harmonic_centrality (G)
hits (G, iterations? : Int32)
katz (G, alpha? : Double, beta? : Double, iterations? : Int32)
load_centrality (G)
pagerank (G, damping? : Double, iterations? : Int32, tolerance? : Double)
subgraph_centrality (G)

community6 · Louvain, Leiden, label propagation

girvan_newman (G, Int32)
greedy_modularity (G)
k_clique_communities (G, Int32)
label_propagation (G, rounds? : Int32)
leiden (G, resolution? : Double, rounds? : Int32)
louvain (G, resolution? : Double, rounds? : Int32)

metric48 · density, distance, clustering, accessibility

accessibility (G, Double, weight? : (Int32)
accessibility_decay (G, Double, Double, weight? : (Int32)
adamic_adar (G, Int32, Int32)
assortativity (G)
average_clustering (G, neighborhood? : Neighborhood)
average_path_length (G)
barycenter (G, weight? : (Int32)
center (G)
clustering (G, Int32, neighborhood? : Neighborhood)
common_neighbors (G, Int32, Int32)
communicability (G, weight? : (Int32)
constraint (G, weight? : (Int32)
current_flow_betweenness (G, weight? : (Int32)
current_flow_closeness (G, weight? : (Int32)
degree (G)
degree_histogram (G)
density (G)
diameter (G)
distinct_edge_count (G)
eccentricity (G, Int32)
effective_size (G, weight? : (Int32)
efficiency (G)
in_degree (G)
link_prediction (G, kind? : SimilarityKind)
low_connectivity_nodes (G, impedance~ : Double, count~ : Int32, weight? : (Int32)
modularity (G, @moongraph.Partition)
nearest_pois (G, Array[Int32], count? : Int32, cutoff~ : Double, weight? : (Int32)
percolation_centrality (G, Array[Double])
periphery (G)
radius (G)
reciprocity (G)
resistance_distance (G, Int32, Int32, weight? : (Int32)
resistance_matrix (G, weight? : (Int32)
resource_allocation (G, Int32, Int32)
rich_club (G)
rich_club_at (G, Int32)
similarity (G, Int32, Int32, kind? : SimilarityKind)
smallworld_omega (G, lattice~ : H)
smallworld_sigma (G, lattice~ : H, random~ : K)
square_clustering (G, Int32)
total_degree (G)
transitivity (G, neighborhood? : Neighborhood)
triadic_census (G)
triangles (G, neighborhood? : Neighborhood)
voterank (G)
wiener_index (G, weight? : (Int32)
wl_hash (G, iterations? : Int32)
TriadCensus::of (Self, String)

struct28 · what kind of graph this is

bipartition (G)
core_numbers (G)
d_separator (G, Array[Int32], Array[Int32], Array[Int32])
gale_ryser (Array[Int32], Array[Int32])
is_arborescence (G)
is_at_free (G)
is_bipartite (G)
is_branching (G)
is_digraphical (Array[(Int32, Int32)
is_distance_regular (G)
is_forest (G)
is_graphical (Array[Int32])
is_isolate (G, Int32)
is_multigraphical (Array[Int32])
is_planar (G)
is_regular (G)
is_threshold (G)
is_tournament (G)
is_tree (G)
isolates (G)
k_core (G, Int32)
k_shell (G, Int32)
k_truss (G, Int32)
minimal_d_separator (G, Array[Int32], Array[Int32])
moral_graph (G)
onion_layers (G)
planarity_embedding (G)
score_sequence (G)

iso4 · isomorphism, and the mapping

could_be_isomorphic (G, G)
fast_could_be_isomorphic (G, G)
is_isomorphic (G, G)
vf2_mapping (G, G)

op26 · unions, products, contraction, nmap, closure

bind (@moongraph.Graph[Int32, Unit], Array[@moongraph.Graph[Int32, Unit]])
bipartite_projection (G, Array[Int32])
cartesian_product (@moongraph.Graph[Int32, Unit], @moongraph.Graph[Int32, Unit])
closure (@moongraph.Graph[Int32, Unit])
complement (G)
compose (@moongraph.Graph[Int32, Unit], @moongraph.Graph[Int32, Unit])
connect (@moongraph.Graph[Int32, Unit], @moongraph.Graph[Int32, Unit])
contraction (@moongraph.Graph[Int32, Unit], Array[Int32])
difference (@moongraph.Graph[Int32, Unit], @moongraph.Graph[Int32, Unit])
disjoint_union (@moongraph.Graph[Int32, Unit], @moongraph.Graph[Int32, Unit])
edge_subgraph (@moongraph.Graph[Int32, Unit], Array[Int32])
emap (@moongraph.Graph[N, E], (E)
gmap (@moongraph.Graph[N, E], (N)
graph_power (@moongraph.Graph[Int32, Unit], Int32)
intersection (@moongraph.Graph[Int32, Unit], @moongraph.Graph[Int32, Unit])
is_subgraph_of (G, H)
line_graph (@moongraph.Graph[Int32, Unit])
nmap (@moongraph.Graph[N, E], (N)
remove_edge (@moongraph.Graph[N, E], Int32, Int32)
remove_vertex (@moongraph.Graph[N, E], Int32)
reverse (@moongraph.Graph[Int32, Unit])
strong_product (@moongraph.Graph[Int32, Unit], @moongraph.Graph[Int32, Unit])
subgraph (@moongraph.Graph[Int32, Unit], Array[Int32])
symmetric_difference (@moongraph.Graph[Int32, Unit], @moongraph.Graph[Int32, Unit])
tensor_product (@moongraph.Graph[Int32, Unit], @moongraph.Graph[Int32, Unit])
union (@moongraph.Graph[Int32, Unit], @moongraph.Graph[Int32, Unit])

gen16 · named graphs, and the random families

barabasi_albert (Int32, attach~ : Int32, rng~ : &@contract.Rng)
barbell (Int32)
complete (Int32, directed? : Bool)
cycle (Int32)
double_edge_swap (G, swaps~ : Int32, rng~ : &@contract.Rng)
grid (Int32, Int32)
ladder (Int32)
path (Int32, directed? : Bool)
petersen ()
random_gnm (Int32, Int32, rng~ : &@contract.Rng, directed? : Bool)
random_gnp (Int32, probability~ : Double, rng~ : &@contract.Rng, directed? : Bool)
random_regular (Int32, degree~ : Int32, rng~ : &@contract.Rng)
random_tree (Int32, rng~ : &@contract.Rng)
star (Int32)
watts_strogatz (Int32, neighbours~ : Int32, probability~ : Double, rng~ : &@contract.Rng)
wheel (Int32)

io13 · edge lists, adjacency lists, GML, graph6

adjacency_list (G)
edge_list (G, data? : Bool)
gml (G)
graph6 (G)
pajek (G)
parse_adjacency (StringView, directed? : Bool)
parse_edges (StringView, directed? : Bool)
parse_gml (StringView)
parse_graph6 (StringView)
parse_pajek (StringView)
parse_sparse6 (StringView)
sparse6 (G)
text (G)

io/graphml2 · GraphML, on an XML parser

read (StringView)
write (G, labels? : (Int32)

dsu8 · the disjoint-set forest

Dsu::count (Self)
Dsu::find (Self, Int32)
Dsu::groups (Self)
Dsu::length (Self)
Dsu::new (Int32)
Dsu::same (Self, Int32, Int32)
Dsu::size (Self, Int32)
Dsu::union (Self, Int32, Int32)

sat4 · two-variable clauses

TwoSat::add_clause (Self, Int32, Bool, Int32, Bool)
TwoSat::answer (Self)
TwoSat::new (Int32)
TwoSat::satisfiable (Self)

incremental13 · flows that can be changed

CostFlow::add_edge (Self, Int32, Int32, Double, Double)
CostFlow::edge_count (Self)
CostFlow::edge_flow (Self, Int32)
CostFlow::flow (Self, Int32, Int32)
CostFlow::new (Int32)
CostFlow::slope (Self, Int32, Int32)
Flow::add_edge (Self, Int32, Int32, Double)
Flow::change_edge (Self, Int32, Double, Double)
Flow::edge_count (Self)
Flow::edge_flow (Self, Int32)
Flow::flow (Self, Int32, Int32, limit? : Double)
Flow::min_cut (Self, Int32)
Flow::new (Int32)