1 · A first graph
A graph is built by adding nodes and edges; both answer with the number they were given. The numbers are the identity of a node: there is no handle to keep, and no lookup to make.
let g : @moongraph.Graph[String, Double] = @moongraph.Graph::new(
directed=false,
)
let a = g.add_node("a")
let b = g.add_node("b")
let c = g.add_node("c")
g.add_edge(a, b, 1.5) |> ignore
g.add_edge(b, c, 2.0) |> ignore
assert_eq(a, 0) // the number the node was given
assert_eq(g.neighbors(a).to_owned(), [b])
assert_eq(g.node_data(c), "c")
An undirected edge is reported from both of its endpoints; a directed one only from its
source. Parallel edges are allowed and each keeps its own number, so
find_edge answers the lowest one and find_edges answers them all.
let e = g.add_edge(a, b, 9.0)
assert_eq(g.find_edges(a, b), [0, 2]) // two edges, numbers kept
assert_eq(g.endpoints(e), (0, 1))
assert_eq(g.edge_data(e), 9.0)
Removing a node renumbers the nodes above it, which is the one operation that invalidates
numbers. StableGraph exists for the case where that matters: it leaves a hole
and never moves a node.
2 · Names instead of numbers
When the data is keyed by name, wrap the graph in Keyed: keys go in, keys come
out, and the numbers stay inside where the algorithms want them.
let inner : @moongraph.Graph[Unit, Double] = @moongraph.Graph::new()
let k = @moongraph.Keyed::new(graph=inner)
k.add_node("oslo", ()) |> ignore
k.add_node("bergen", ()) |> ignore
k.add_edge("oslo", "bergen", 3.0) |> ignore
assert_eq(k.node("bergen"), Some(1))
assert_eq(k.key(0), Some("oslo"))
Adding a key that is already there is refused rather than silently overwriting the node, and an edge whose endpoint has no key is refused too — the two sides cannot drift apart.
3 · Weights and routes
A weight is a function from edge number to cost. Graph::weights adapts one over
payloads; leaving the argument out means every edge costs one.
let g : @moongraph.Graph[Unit, Double] = @moongraph.Graph::new(directed=false)
for _ in 0..<5 {
g.add_node(()) |> ignore
}
g.add_edge(0, 1, 1.0) |> ignore
g.add_edge(1, 2, 2.0) |> ignore
g.add_edge(0, 2, 5.0) |> ignore
g.add_edge(1, 3, 1.0) |> ignore
g.add_edge(3, 2, 2.0) |> ignore
let w = g.weights(fn(cost) { cost })
let paths = @path.dijkstra(g, 0, weight=w)
assert_eq(paths.distance[2], Some(3.0)) // 0 to 1 to 2 beats 0 to 2
assert_eq(paths.path_to(2), Some([0, 1, 2]))
assert_eq(paths.distance[4], None) // node 4 is not reached
distance holds Double? and previous holds
Int?, both indexed by node number: no entry can be missing, and an unreached node
is None rather than a number that looks like a distance.
A negative weight is not a puzzle to be worked around: Dijkstra refuses it and says which edge
carried it. bellman_ford and johnson handle negatives, and refuse
only a negative cycle — the one case where no cost exists.
let paid : @moongraph.Graph[Unit, Double] = @moongraph.Graph::new(
directed=false,
)
paid.add_node(()) |> ignore
paid.add_node(()) |> ignore
paid.add_edge(0, 1, -1.0) |> ignore
let outcome = try {
let _ = @path.dijkstra(paid, 0, weight=paid.weights(fn(cost) { cost }))
"answered"
} catch {
@moongraph.Refused::NegativeWeight(edge~) =>
"edge " + edge.to_string() + " is negative"
_ => "something else"
}
assert_eq(outcome, "edge 0 is negative")
4 · Walks
Every walk visits the edges of a node in ascending neighbour number, so two runs over the
same graph agree. bfs answers the discovery order — by distance, then by node
number — and dfs the preorder of a walk that dives in.
let g : @moongraph.Graph[Unit, Unit] = @moongraph.Graph::from_edges(
[(0, 1), (1, 2), (0, 2)],
node=(),
edge=(),
directed=false,
)
assert_eq(@traverse.bfs(g, 0), [0, 1, 2])
assert_eq(@traverse.bfs_layers(g, [0]), [[0], [1, 2]])
assert_eq(@traverse.dfs(g, 0), [0, 1, 2])
A depth-first walk can also be read as events: entering a node, leaving it, and looking at an edge back to a node still on the stack. That is what cycle detection wants, without a visitor object.
5 · What shape is this
Components, strong components and the structure that survives a single cut all answer with arrays indexed by node.
let parts = @component.components(g)
assert_eq(parts.count, 1)
assert_eq(parts.label, [0, 0, 0])
assert_eq(@component.bridges(g), []) // every edge is on a cycle
assert_eq(@component.articulation_points(g), [])
6 · Trees and flow
A spanning tree comes back as its edge numbers and its weight; a maximum flow comes back as its value and the flow on every edge.
let net : @moongraph.Graph[Unit, Double] = @moongraph.Graph::new(
directed=false,
)
for _ in 0..<4 {
net.add_node(()) |> ignore
}
net.add_edge(0, 1, 1.0) |> ignore
net.add_edge(1, 2, 2.0) |> ignore
net.add_edge(0, 2, 5.0) |> ignore
net.add_edge(1, 3, 1.0) |> ignore
net.add_edge(3, 2, 2.0) |> ignore
let weight = net.weights(fn(cost) { cost })
let tree = @tree.minimum_spanning(net, weight~)
assert_eq(tree.edges, [0, 3, 1]) // three edges for four nodes
assert_eq(tree.weight, 4.0)
let errand : @moongraph.Graph[Unit, Double] = @moongraph.Graph::new(
directed=true,
)
for _ in 0..<4 {
errand.add_node(()) |> ignore
}
errand.add_edge(0, 2, 1.0) |> ignore
errand.add_edge(0, 1, 1.0) |> ignore
errand.add_edge(1, 3, 1.0) |> ignore
errand.add_edge(2, 3, 1.0) |> ignore
let flow = @flow.max_flow(
errand,
0,
3,
capacity=errand.weights(fn(cost) { cost }),
)
assert_eq(flow.value, 2.0)
assert_eq(flow.flow, [1.0, 1.0, 1.0, 1.0]) // the amount on each edge
A minimum spanning tree refuses a graph in pieces instead of quietly returning a forest: the
five-node graph of section 3 has an isolated node, and asking it for a tree answers
Refused::Disconnected. Ask for components first if a forest is what
you want.
7 · Cycles and Euler walks
The girth is the length of the shortest cycle, and in a directed graph it is the shortest
closed walk the arcs allow. Three nodes can be joined in a triangle whose arcs only go one
way, and then there is no cycle to measure at all: girth answers the reading the
graph itself has, and None when the arcs never come back.
let ring : @moongraph.Graph[Unit, Unit] = @moongraph.Graph::from_edges(
[(0, 1), (1, 2), (2, 0)],
node=(),
edge=(),
directed=true,
)
assert_eq(@cycle.girth(ring), Some(3))
assert_true(@cycle.is_eulerian(ring))
assert_eq(@cycle.eulerian_circuit(ring).length(), 3)
let fan : @moongraph.Graph[Unit, Unit] = @moongraph.Graph::from_edges(
[(0, 1), (0, 2)],
node=(),
edge=(),
directed=true,
)
assert_eq(@cycle.girth(fan), None) // the arcs never come back
assert_false(@cycle.is_eulerian(fan)) // two out of 0, nothing in
assert_false(@cycle.has_eulerian_path(fan))
An Eulerian graph is one whose edges can all be walked in a single closed trail. In an
undirected graph that is every degree being even; in a directed one it is as many arcs
leaving a node as entering it, which is a different question and answers differently — two
arcs out of one node and none in are even by degree and have no way back.
eulerian_circuit walks the trail, has_eulerian_path answers for a
trail that is not closed, and eulerize with chinese_postman takes
the shortest route over every edge of a graph that has neither.
A pair of parallel edges is a cycle of two and a self loop one of one, in a graph of either direction, which is what the traversals that use them mean by a cycle.
8 · Reading and writing
Seven formats, and one reader shape: what could not be read is refused with the byte offset, the line and the column.
let text = @io.edge_list(g)
assert_eq(text, "0 1\n1 2\n0 2\n")
let back = @io.parse_edges(text)
assert_eq(@io.graph6(back), "Bw") // a node count, then one bit an edge
assert_eq(@io.sparse6(back), ":BcN") // only the edges that are there
let zeroes : @moongraph.Graph[Unit, Unit] = @moongraph.Graph::new()
assert_eq(@io.sparse6(zeroes), ":?")
The two bit formats are the graph itself rather than a list of it: graph6 writes
one bit per possible edge, and sparse6 one pair of node numbers per edge that is
there. Both start with the node count, which takes one byte up to 62 nodes, four up to
258047, and eight above that, and both pad the last byte so that a reader stops at the end of
the edges instead of inventing one; a graph of another implementation's writing reads back
byte for byte.
let loaded = @graphml.read(document)
assert_eq(loaded.graph.node_count(), 2)
assert_eq(loaded.graph.edge_data(0), 2.5)
GraphML lives in io/graphml so that the XML parser it needs stays behind that
one package; nothing in the algorithms carries it.
9 · Measuring the whole graph
The measures that describe a network rather than answer a route are all in
metric, and each reads the graph it is given: nothing is precomputed, nothing
is stored on the side. A triangle census counts the sixteen shapes a directed triple can
take; the rich-club coefficient asks whether the well-connected nodes are connected to each
other; constraint and effective size are Burt's structural holes; resistance distance reads
the graph as a circuit.
let ring : @moongraph.Graph[Unit, Unit] = @moongraph.Graph::from_edges(
[(0, 1), (1, 2), (2, 0), (0, 3)],
node=(),
edge=(),
directed=true,
)
let census = @metric.triadic_census(ring)
assert_eq(census.of("030C"), Some(1)) // one cycle, three arcs
assert_eq(census.count.length(), 16) // every shape, counted
assert_eq(@metric.wiener_index(net), Some(7.0)) // every distance, added up
assert_eq(@metric.wl_hash(net).length(), 32) // one fingerprint, 16 bytes
wl_hash is a fingerprint rather than a number: each round replaces a node's label
with the digest of its neighbours' labels, and the answer is the digest of the histogram after
every round. Two graphs that agree locally for the rounds it takes share it, and a directed
node is told apart by what it points at as well as what points at it.
A directed graph has more than one neighbourhood, and the field has never settled on which
one a triangle coefficient is about: the same graph can be read with its arcs dropped, with
the arcs followed, or from the nodes each arc leaves. So the reading is a parameter rather
than a decision made here. Outward, the default, reads the nodes the arcs
leave and closes a corner when either direction joins the two; Undirected
drops the directions; Transitive closes a corner only when an arc runs from
the first successor to the second. All three agree on a graph without arcs.
let diamond : @moongraph.Graph[Unit, Unit] = @moongraph.Graph::from_edges(
[(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)],
node=(),
edge=(),
directed=true,
)
assert_eq(@metric.transitivity(diamond), 1.0) // the default: what the arcs leave
assert_eq(@metric.transitivity(diamond, neighborhood=Undirected), 0.75) // arcs dropped
assert_eq(@metric.transitivity(diamond, neighborhood=Transitive), 0.5) // arcs followed
The default is also the cheapest of the three, because it collects one list per node
instead of two. clustering, average_clustering and
triangles take the same parameter, so a reader who wants the graph with its
directions dropped asks for it by name instead of building the graph again.
None of them is defined everywhere, and none of them guesses. A graph in pieces has no Wiener
index — the sum would be infinite, and an infinite answer is not a measurement — so the answer
is None instead of a number that looks like one.
Link prediction scores pairs that have no edge between them, so a graph can propose the
edges it is missing: common_neighbors, Jaccard, Dice, cosine, overlap, Adamic-Adar,
resource allocation, preferential attachment, and link_prediction to walk every
non-edge at once.
assert_eq(@metric.similarity(net, 0, 3), 1.0) // Jaccard, by default
assert_eq(@metric.similarity(net, 0, 3, kind=AdamicAdar), 1.8204784532536746)
assert_eq(@path.voronoi(net, [0, 3]), [0, 0, 0, 3]) // the nearest centre
assert_eq(@metric.link_prediction(net), [(0, 3, 1.0)]) // no edge, but close
assert_eq(@approx.traveling_salesman_exact(net, start=0), [0, 2, 3, 1, 0])
Two of those numbers are worth reading twice. The resistance between nodes 0 and 3 is one
rather than two because the two routes of two sit in parallel, and it comes back as
0.9999999999999996 because it was computed in floating point. The same pair
scores 1 by Jaccard and 1.8204784532536746 by Adamic-Adar, which is the whole point of the
second measure: a neighbour that few others share counts for more than one everybody has.
Every one of these is checked against an independent implementation on the same graphs,
answer by answer, in the test suite — the coefficients, the sixteen census counts, the
resistance matrix against a pseudo-inverse, the tour against a brute force. Where a measure
is undefined the answer is None, and the test insists the reference agrees it
is undefined.
10 · Boards, forests and clauses
Not every question is about a graph you build edge by edge. A board is a graph whose nodes
are cells and whose edges are steps, and grid owns the searches that know it:
breadth first when every step costs one, Dijkstra when they do not, A* steered by the octile
distance, the jump-point search that skips the straight runs A* would expand one cell at a
time, Theta* for routes that may leave the cell boundaries, and D* Lite for a board that
changes underfoot. A diagonal step costs the diagonal of a unit square.
let board = @grid.Grid::new(4, 4)
let route = board.jps(0, 15).unwrap()
assert_eq(route[0], 0)
assert_eq(route[route.length() - 1], 15)
assert_eq(board.path_cost(route), 4.242640687119286) // three diagonals
board.block(1, 1)
let around = board.jps(0, 15).unwrap()
assert_eq(board.path_cost(around), 4.82842712474619) // one wall, one detour
The jump-point search answers a route cell by cell, not just the corners it jumped to, so the cost of what it returns is the cost of what A* returns. Blocking one cell takes the diagonal away and the walk pays for the two straight steps that replace it.
dsu is the disjoint-set forest as a value you can ask questions of: merge two
pieces, ask whether two numbers are in the same one, and read the pieces back. It is what the
spanning-tree family and the community passes reach for, exposed because a caller with a
merging problem of its own wants it without a graph. sat is the same kind of
question one level up: a clause over two variables is a pair of implications, so two-variable
satisfiability is a question about the strong pieces of an implication graph.
let forest = @dsu.Dsu::new(6)
forest.union(0, 1) |> ignore
forest.union(1, 2) |> ignore
forest.union(4, 5) |> ignore
assert_eq(forest.count(), 3)
assert_eq(forest.groups(), [[0, 1, 2], [3], [4, 5]])
assert_true(forest.same(2, 0))
let clauses = @sat.TwoSat::new(2)
clauses.add_clause(0, true, 1, false) // x0, or x1 is false
assert_true(clauses.satisfiable())
let model = clauses.answer().unwrap()
assert_true(model[0] || !model[1])
A clause that names one variable twice is a unit clause — (x, true, x, true) says
x is true — and the encoding reads it as one, which is the degenerate case rather
than a special one. Add the opposite unit clause and the instance has no model at all.
Flow is usually a question asked once. incremental is for the network you keep:
the capacities change, the flow already found is the starting point, and each call pushes only
what the change made possible. The answer is what was added, and the total is the sum of the
calls — the shape that makes a second question cheap instead of a rebuild.
let net = @incremental.Flow::new(4)
net.add_edge(0, 1, 2.0) |> ignore
net.add_edge(1, 3, 2.0) |> ignore
net.add_edge(0, 2, 1.0) |> ignore
net.add_edge(2, 3, 1.0) |> ignore
assert_eq(net.flow(0, 3), 3.0) // both routes, filled
net.change_edge(0, 4.0, 2.0) // widen the first edge only
assert_eq(net.flow(0, 3), 0.0) // the second is still the bottleneck
net.change_edge(1, 4.0, 2.0) // widen that one too
assert_eq(net.flow(0, 3), 2.0) // two more units, without rebuilding
assert_eq(net.min_cut(0), [true, false, false, false])
Widening the first edge alone changes nothing, because the edge after it is still full; widen
that one and the two units the first edge gained have somewhere to go. min_cut
reads the same network from the other side and names the side the source can still reach.
CostFlow in the same package answers the whole price curve instead of one number:
the points where the cost of the next unit changes, which is how a planner decides how much of
a shipment is worth sending.
11 · Where to go next
The demo runs the library in the browser: pick a graph, pick an algorithm, and click a node to start somewhere else. The API reference lists every public item with the paragraph that explains it. The repository has the examples.