Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/networkx/readwrite/json_graph/tree.py: 14%
43 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
1from itertools import chain
3import networkx as nx
5__all__ = ["tree_data", "tree_graph"]
8def tree_data(G, root, ident="id", children="children"):
9 """Returns data in tree format that is suitable for JSON serialization
10 and use in JavaScript documents.
12 Parameters
13 ----------
14 G : NetworkX graph
15 G must be an oriented tree
17 root : node
18 The root of the tree
20 ident : string
21 Attribute name for storing NetworkX-internal graph data. `ident` must
22 have a different value than `children`. The default is 'id'.
24 children : string
25 Attribute name for storing NetworkX-internal graph data. `children`
26 must have a different value than `ident`. The default is 'children'.
28 Returns
29 -------
30 data : dict
31 A dictionary with node-link formatted data.
33 Raises
34 ------
35 NetworkXError
36 If `children` and `ident` attributes are identical.
38 Examples
39 --------
40 >>> from networkx.readwrite import json_graph
41 >>> G = nx.DiGraph([(1, 2)])
42 >>> data = json_graph.tree_data(G, root=1)
44 To serialize with json
46 >>> import json
47 >>> s = json.dumps(data)
49 Notes
50 -----
51 Node attributes are stored in this format but keys
52 for attributes must be strings if you want to serialize with JSON.
54 Graph and edge attributes are not stored.
56 See Also
57 --------
58 tree_graph, node_link_data, adjacency_data
59 """
60 if G.number_of_nodes() != G.number_of_edges() + 1:
61 raise TypeError("G is not a tree.")
62 if not G.is_directed():
63 raise TypeError("G is not directed.")
64 if not nx.is_weakly_connected(G):
65 raise TypeError("G is not weakly connected.")
67 if ident == children:
68 raise nx.NetworkXError("The values for `id` and `children` must be different.")
70 def add_children(n, G):
71 nbrs = G[n]
72 if len(nbrs) == 0:
73 return []
74 children_ = []
75 for child in nbrs:
76 d = {**G.nodes[child], ident: child}
77 c = add_children(child, G)
78 if c:
79 d[children] = c
80 children_.append(d)
81 return children_
83 return {**G.nodes[root], ident: root, children: add_children(root, G)}
86@nx._dispatch(graphs=None)
87def tree_graph(data, ident="id", children="children"):
88 """Returns graph from tree data format.
90 Parameters
91 ----------
92 data : dict
93 Tree formatted graph data
95 ident : string
96 Attribute name for storing NetworkX-internal graph data. `ident` must
97 have a different value than `children`. The default is 'id'.
99 children : string
100 Attribute name for storing NetworkX-internal graph data. `children`
101 must have a different value than `ident`. The default is 'children'.
103 Returns
104 -------
105 G : NetworkX DiGraph
107 Examples
108 --------
109 >>> from networkx.readwrite import json_graph
110 >>> G = nx.DiGraph([(1, 2)])
111 >>> data = json_graph.tree_data(G, root=1)
112 >>> H = json_graph.tree_graph(data)
114 See Also
115 --------
116 tree_data, node_link_data, adjacency_data
117 """
118 graph = nx.DiGraph()
120 def add_children(parent, children_):
121 for data in children_:
122 child = data[ident]
123 graph.add_edge(parent, child)
124 grandchildren = data.get(children, [])
125 if grandchildren:
126 add_children(child, grandchildren)
127 nodedata = {
128 str(k): v for k, v in data.items() if k != ident and k != children
129 }
130 graph.add_node(child, **nodedata)
132 root = data[ident]
133 children_ = data.get(children, [])
134 nodedata = {str(k): v for k, v in data.items() if k != ident and k != children}
135 graph.add_node(root, **nodedata)
136 add_children(root, children_)
137 return graph