Debian Codegraph @

docs/howto/networkx.md

raw
1 # Convert to/from a NetworkX graph
2
3 `prov.graph` converts a document to and from a
4 [NetworkX](https://networkx.org/) `MultiDiGraph`, useful for running graph algorithms
5 (centrality, shortest paths, community detection, ...) that `prov` itself does not
6 implement. `networkx` is a core dependency — no extra install needed.
7
8 ## Document to graph
9
10 {py:func}`~prov.graph.prov_to_graph` returns one node per element (entity/activity/agent)
11 and one edge per relation. It unifies the document first, so records describing the same
12 identifier are merged into a single node:
13
14 ```python
15 import prov.model as pm
16 from prov.graph import prov_to_graph
17
18 document = pm.ProvDocument()
19 document.set_default_namespace("http://example.org/")
20 e = document.entity("e1")
21 a = document.activity("a1")
22 document.wasGeneratedBy(e, a)
23
24 g = prov_to_graph(document)
25
26 print(list(g.nodes()))
27 # [<ProvEntity: e1>, <ProvActivity: a1>]
28 print(list(g.edges(data=True)))
29 # [(<ProvEntity: e1>, <ProvActivity: a1>, {'relation': <ProvGeneration: (e1, a1)>})]
30 ```
31
32 Each node *is* the `prov` element record (a {py:class}`~prov.model.ProvElement`); each edge
33 carries the originating {py:class}`~prov.model.ProvRelation` under the `"relation"` key so
34 you don't lose PROV-specific information (relation type, extra attributes) while using
35 NetworkX.
36
37 ## Run a NetworkX algorithm
38
39 Because nodes are hashable `prov` objects, any NetworkX algorithm works directly:
40
41 ```python
42 import networkx as nx
43
44 print(nx.is_directed_acyclic_graph(g))
45 ```
46
47 ## Graph back to document
48
49 {py:func}`~prov.graph.graph_to_prov` reverses the conversion for a graph previously
50 produced by `prov_to_graph` (or built to match its shape — nodes are `ProvRecord`
51 instances with a bundle, edges carry a `"relation"` record in their data):
52
53 ```python
54 from prov.graph import graph_to_prov
55
56 reloaded = graph_to_prov(g)
57 assert reloaded == document
58 ```
59
60 ## Round trip
61
62 ```python
63 g = prov_to_graph(document)
64 reloaded = graph_to_prov(g)
65 assert reloaded == document
66 ```