Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 59 additions & 3 deletions docs/graph-algorithms.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,65 @@ scores = pa.table({"id": g.node_keys, "pagerank": pagerank.run().scores()})
exactly `pyarrow==26.0.1`, imports only when `networkx` is installed, and on macOS needs OpenMP from
Homebrew (`brew install libomp`).

For a weighted graph, pass the weights after the in-edge arrays:
`ib.Graph.fromCSR(w.num_nodes, w.directed, w.out_indices, w.out_indptr, w.in_indices, w.in_indptr,
w.out_weights, w.in_weights)`. Algorithms such as `ib.distance.Dijkstra` then use them.
### Weighted algorithms in icebug

An export with [weights](#weighted-graphs) gives icebug a weighted graph when you pass the weight arrays after
the in-edge arrays:

<!-- skip-check -->
```python
graph = ib.Graph.fromCSR(
w.num_nodes, w.directed, w.out_indices, w.out_indptr, w.in_indices, w.in_indptr,
w.out_weights, w.in_weights,
)
```

The export's part ends there. Whether an algorithm then uses the weights is up to icebug, and not every one
does: some return an unweighted answer on a weighted graph without a warning. The table below lists what each
algorithm does with them in icebug 13.6. We worked it out by running each one on the same graph with and without
weights:

| Module | Uses the weights | Ignores the weights, without a warning |
| --- | --- | --- |
| `distance` | `Dijkstra`, `BidirectionalDijkstra`, `AStar`, `APSP`, `Diameter` | `BFS`, `Eccentricity` |
| `centrality` | `PageRank`, `Betweenness`, `ApproxBetweenness`, `EstimateBetweenness`, `Closeness`, `ApproxCloseness`, `HarmonicCloseness`, `TopHarmonicCloseness`, `EigenvectorCentrality`, `KatzCentrality`, `ForestCentrality`, `SpanningEdgeCentrality` (on a copy) | `KadabraBetweenness`, `TopCloseness`, `DegreeCentrality`, `CoreDecomposition`, `LocalClusteringCoefficient` |
| `community` | `PLM` (Louvain), `ParallelLeiden`, `PLP` | `LPDegreeOrdered` |
| `graph` | `RandomMaximumSpanningForest` | `SpanningForest` |
| `matching` | `PathGrowingMatcher`, `SuitorMatcher` | |
| `flow` | `EdmondsKarp` (on a copy) | |

`centrality.ApproxElectricalCloseness` is the one algorithm that refuses a weighted graph: it raises an error.
`KadabraBetweenness` is the one most likely to catch you out, since it looks like a faster `Betweenness` but
computes unweighted betweenness.

`SpanningEdgeCentrality` and `EdmondsKarp` need edge ids, which `indexEdges()` adds. A graph built by `fromCSR`
is read-only, so `indexEdges()` raises an error on it, and these two run on a copy instead. Pass `weighted=True`
to the copy, because without it the copy leaves the weights out:

<!-- skip-check -->
```python
editable = ib.Graph(graph, weighted=True, directed=graph.isDirected())
editable.indexEdges()
max_flow = ib.flow.EdmondsKarp(editable, source, target).run().getMaxFlow()
```

The copy holds the whole graph a second time in memory.

!!! note "What needs a change in icebug"

lance-csr can't change any of these limits; they need changes in icebug. If icebug let a graph built by
`fromCSR` index its edges, `SpanningEdgeCentrality` and `EdmondsKarp` would run without the copy. Weights in
the algorithms of the right-hand column, or in `ApproxElectricalCloseness`, would need icebug to add them to
those algorithms.

The algorithms that use the weights don't all read them the same way. Shortest paths, betweenness and closeness
treat a weight as a length, so a lower weight brings two nodes closer. PageRank, eigenvector and Katz
centrality, community detection, maximum spanning forests and matchings treat it as a strength, so a higher
weight ties two nodes more closely. One column rarely suits both. To run shortest paths over a strength such as
`messages`, pass its inverse, `pyarrow.compute.divide(1.0, w.out_weights)`, and the same for `in_weights`. Dijkstra and the
algorithms built on it also assume that no weight is negative, and the export doesn't check this.

### Other libraries

Other libraries take the same arrays. For example, `scipy.sparse.csr_array((data, g.out_indices, g.out_indptr))`
builds an adjacency matrix, after converting the arrays with `to_numpy()`, which doesn't copy them either.
Expand Down
73 changes: 68 additions & 5 deletions python/python/tests/test_graph_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,15 @@ def test_icebug_weighted_shortest_paths():
g = CypherEngine(CONFIG, {"Person": nodes, "KNOWS": edges}).export_graph(
weight="cost"
)
graph = ib.Graph.fromCSR(
graph = _weighted_icebug_graph(ib, g)
assert graph.isWeighted()
dijkstra = ib.distance.Dijkstra(graph, 0)
dijkstra.run()
assert dijkstra.getDistances() == [0.0, 1.0, 2.0]


def _weighted_icebug_graph(ib, g: GraphExport):
return ib.Graph.fromCSR(
g.num_nodes,
g.directed,
g.out_indices,
Expand All @@ -295,10 +303,65 @@ def test_icebug_weighted_shortest_paths():
g.out_weights,
g.in_weights,
)
assert graph.isWeighted()
dijkstra = ib.distance.Dijkstra(graph, 0)
dijkstra.run()
assert dijkstra.getDistances() == [0.0, 1.0, 2.0]


# Two routes from 0 to 3: through 1 (weights 1 + 1) and through 2 (weights 5 + 5).
ROUTES_NODES = pa.table({"id": [0, 1, 2, 3]})
ROUTES = pa.table({"src": [0, 1, 0, 2], "dst": [1, 3, 2, 3], "w": [1.0, 1.0, 5.0, 5.0]})


def test_icebug_weighted_betweenness():
ib = pytest.importorskip("icebug")
engine = CypherEngine(CONFIG, {"Person": ROUTES_NODES, "KNOWS": ROUTES})
g = engine.export_graph(directed=False, weight="w")
graph = _weighted_icebug_graph(ib, g)
scores = ib.centrality.Betweenness(graph).run().scores()
# Only the cheap route is a shortest path, so 2 lies on none.
assert scores[1] > 0 and scores[2] == 0

u = engine.export_graph(directed=False)
unweighted = ib.Graph.fromCSR(u.num_nodes, False, u.out_indices, u.out_indptr)
scores = ib.centrality.Betweenness(unweighted).run().scores()
assert scores[1] == scores[2] > 0


def test_icebug_weighted_communities():
ib = pytest.importorskip("icebug")
# Every pair of six nodes is linked, so only the weights separate {0, 1, 2}
# from {3, 4, 5}: 10 inside each group, 1 between them.
pairs = [(a, b) for a in range(6) for b in range(a + 1, 6)]
edges = pa.table(
{
"src": [a for a, _ in pairs],
"dst": [b for _, b in pairs],
"w": [10.0 if (a < 3) == (b < 3) else 1.0 for a, b in pairs],
}
)
nodes = pa.table({"id": list(range(6))})
g = CypherEngine(CONFIG, {"Person": nodes, "KNOWS": edges}).export_graph(
directed=False, weight="w"
)
graph = _weighted_icebug_graph(ib, g)
community = ib.community.PLM(graph, refine=True).run().getPartition()
groups = [community.subsetOf(v) for v in range(6)]
assert groups[0] == groups[1] == groups[2] != groups[3] == groups[4] == groups[5]


def test_icebug_weighted_copy_for_edge_ids():
ib = pytest.importorskip("icebug")
g = CypherEngine(CONFIG, {"Person": ROUTES_NODES, "KNOWS": ROUTES}).export_graph(
weight="w"
)
graph = _weighted_icebug_graph(ib, g)
# A graph built by fromCSR is read-only, and a copy keeps the weights only
# with weighted=True.
with pytest.raises(RuntimeError, match="read-only"):
graph.indexEdges()
assert not ib.Graph(graph).isWeighted()
editable = ib.Graph(graph, weighted=True, directed=graph.isDirected())
editable.indexEdges()
# The weights are capacities: 1 through node 1 plus 5 through node 2.
assert ib.flow.EdmondsKarp(editable, 0, 3).run().getMaxFlow() == 6.0


def test_write_node_column(tmp_path):
Expand Down
Loading