Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/networkx/readwrite/json_graph/adjacency.py: 11%
57 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
1import networkx as nx
3__all__ = ["adjacency_data", "adjacency_graph"]
5_attrs = {"id": "id", "key": "key"}
8def adjacency_data(G, attrs=_attrs):
9 """Returns data in adjacency format that is suitable for JSON serialization
10 and use in JavaScript documents.
12 Parameters
13 ----------
14 G : NetworkX graph
16 attrs : dict
17 A dictionary that contains two keys 'id' and 'key'. The corresponding
18 values provide the attribute names for storing NetworkX-internal graph
19 data. The values should be unique. Default value:
20 :samp:`dict(id='id', key='key')`.
22 If some user-defined graph data use these attribute names as data keys,
23 they may be silently dropped.
25 Returns
26 -------
27 data : dict
28 A dictionary with adjacency formatted data.
30 Raises
31 ------
32 NetworkXError
33 If values in attrs are not unique.
35 Examples
36 --------
37 >>> from networkx.readwrite import json_graph
38 >>> G = nx.Graph([(1, 2)])
39 >>> data = json_graph.adjacency_data(G)
41 To serialize with json
43 >>> import json
44 >>> s = json.dumps(data)
46 Notes
47 -----
48 Graph, node, and link attributes will be written when using this format
49 but attribute keys must be strings if you want to serialize the resulting
50 data with JSON.
52 The default value of attrs will be changed in a future release of NetworkX.
54 See Also
55 --------
56 adjacency_graph, node_link_data, tree_data
57 """
58 multigraph = G.is_multigraph()
59 id_ = attrs["id"]
60 # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
61 key = None if not multigraph else attrs["key"]
62 if id_ == key:
63 raise nx.NetworkXError("Attribute names are not unique.")
64 data = {}
65 data["directed"] = G.is_directed()
66 data["multigraph"] = multigraph
67 data["graph"] = list(G.graph.items())
68 data["nodes"] = []
69 data["adjacency"] = []
70 for n, nbrdict in G.adjacency():
71 data["nodes"].append({**G.nodes[n], id_: n})
72 adj = []
73 if multigraph:
74 for nbr, keys in nbrdict.items():
75 for k, d in keys.items():
76 adj.append({**d, id_: nbr, key: k})
77 else:
78 for nbr, d in nbrdict.items():
79 adj.append({**d, id_: nbr})
80 data["adjacency"].append(adj)
81 return data
84@nx._dispatch(graphs=None)
85def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs):
86 """Returns graph from adjacency data format.
88 Parameters
89 ----------
90 data : dict
91 Adjacency list formatted graph data
93 directed : bool
94 If True, and direction not specified in data, return a directed graph.
96 multigraph : bool
97 If True, and multigraph not specified in data, return a multigraph.
99 attrs : dict
100 A dictionary that contains two keys 'id' and 'key'. The corresponding
101 values provide the attribute names for storing NetworkX-internal graph
102 data. The values should be unique. Default value:
103 :samp:`dict(id='id', key='key')`.
105 Returns
106 -------
107 G : NetworkX graph
108 A NetworkX graph object
110 Examples
111 --------
112 >>> from networkx.readwrite import json_graph
113 >>> G = nx.Graph([(1, 2)])
114 >>> data = json_graph.adjacency_data(G)
115 >>> H = json_graph.adjacency_graph(data)
117 Notes
118 -----
119 The default value of attrs will be changed in a future release of NetworkX.
121 See Also
122 --------
123 adjacency_graph, node_link_data, tree_data
124 """
125 multigraph = data.get("multigraph", multigraph)
126 directed = data.get("directed", directed)
127 if multigraph:
128 graph = nx.MultiGraph()
129 else:
130 graph = nx.Graph()
131 if directed:
132 graph = graph.to_directed()
133 id_ = attrs["id"]
134 # Allow 'key' to be omitted from attrs if the graph is not a multigraph.
135 key = None if not multigraph else attrs["key"]
136 graph.graph = dict(data.get("graph", []))
137 mapping = []
138 for d in data["nodes"]:
139 node_data = d.copy()
140 node = node_data.pop(id_)
141 mapping.append(node)
142 graph.add_node(node)
143 graph.nodes[node].update(node_data)
144 for i, d in enumerate(data["adjacency"]):
145 source = mapping[i]
146 for tdata in d:
147 target_data = tdata.copy()
148 target = target_data.pop(id_)
149 if not multigraph:
150 graph.add_edge(source, target)
151 graph[source][target].update(target_data)
152 else:
153 ky = target_data.pop(key, None)
154 graph.add_edge(source, target, key=ky)
155 graph[source][target][ky].update(target_data)
156 return graph