Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/networkx/readwrite/json_graph/cytoscape.py: 8%
62 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__ = ["cytoscape_data", "cytoscape_graph"]
6def cytoscape_data(G, name="name", ident="id"):
7 """Returns data in Cytoscape JSON format (cyjs).
9 Parameters
10 ----------
11 G : NetworkX Graph
12 The graph to convert to cytoscape format
13 name : string
14 A string which is mapped to the 'name' node element in cyjs format.
15 Must not have the same value as `ident`.
16 ident : string
17 A string which is mapped to the 'id' node element in cyjs format.
18 Must not have the same value as `name`.
20 Returns
21 -------
22 data: dict
23 A dictionary with cyjs formatted data.
25 Raises
26 ------
27 NetworkXError
28 If the values for `name` and `ident` are identical.
30 See Also
31 --------
32 cytoscape_graph: convert a dictionary in cyjs format to a graph
34 References
35 ----------
36 .. [1] Cytoscape user's manual:
37 http://manual.cytoscape.org/en/stable/index.html
39 Examples
40 --------
41 >>> G = nx.path_graph(2)
42 >>> nx.cytoscape_data(G) # doctest: +SKIP
43 {'data': [],
44 'directed': False,
45 'multigraph': False,
46 'elements': {'nodes': [{'data': {'id': '0', 'value': 0, 'name': '0'}},
47 {'data': {'id': '1', 'value': 1, 'name': '1'}}],
48 'edges': [{'data': {'source': 0, 'target': 1}}]}}
49 """
50 if name == ident:
51 raise nx.NetworkXError("name and ident must be different.")
53 jsondata = {"data": list(G.graph.items())}
54 jsondata["directed"] = G.is_directed()
55 jsondata["multigraph"] = G.is_multigraph()
56 jsondata["elements"] = {"nodes": [], "edges": []}
57 nodes = jsondata["elements"]["nodes"]
58 edges = jsondata["elements"]["edges"]
60 for i, j in G.nodes.items():
61 n = {"data": j.copy()}
62 n["data"]["id"] = j.get(ident) or str(i)
63 n["data"]["value"] = i
64 n["data"]["name"] = j.get(name) or str(i)
65 nodes.append(n)
67 if G.is_multigraph():
68 for e in G.edges(keys=True):
69 n = {"data": G.adj[e[0]][e[1]][e[2]].copy()}
70 n["data"]["source"] = e[0]
71 n["data"]["target"] = e[1]
72 n["data"]["key"] = e[2]
73 edges.append(n)
74 else:
75 for e in G.edges():
76 n = {"data": G.adj[e[0]][e[1]].copy()}
77 n["data"]["source"] = e[0]
78 n["data"]["target"] = e[1]
79 edges.append(n)
80 return jsondata
83@nx._dispatch(graphs=None)
84def cytoscape_graph(data, name="name", ident="id"):
85 """
86 Create a NetworkX graph from a dictionary in cytoscape JSON format.
88 Parameters
89 ----------
90 data : dict
91 A dictionary of data conforming to cytoscape JSON format.
92 name : string
93 A string which is mapped to the 'name' node element in cyjs format.
94 Must not have the same value as `ident`.
95 ident : string
96 A string which is mapped to the 'id' node element in cyjs format.
97 Must not have the same value as `name`.
99 Returns
100 -------
101 graph : a NetworkX graph instance
102 The `graph` can be an instance of `Graph`, `DiGraph`, `MultiGraph`, or
103 `MultiDiGraph` depending on the input data.
105 Raises
106 ------
107 NetworkXError
108 If the `name` and `ident` attributes are identical.
110 See Also
111 --------
112 cytoscape_data: convert a NetworkX graph to a dict in cyjs format
114 References
115 ----------
116 .. [1] Cytoscape user's manual:
117 http://manual.cytoscape.org/en/stable/index.html
119 Examples
120 --------
121 >>> data_dict = {
122 ... 'data': [],
123 ... 'directed': False,
124 ... 'multigraph': False,
125 ... 'elements': {'nodes': [{'data': {'id': '0', 'value': 0, 'name': '0'}},
126 ... {'data': {'id': '1', 'value': 1, 'name': '1'}}],
127 ... 'edges': [{'data': {'source': 0, 'target': 1}}]}
128 ... }
129 >>> G = nx.cytoscape_graph(data_dict)
130 >>> G.name
131 ''
132 >>> G.nodes()
133 NodeView((0, 1))
134 >>> G.nodes(data=True)[0]
135 {'id': '0', 'value': 0, 'name': '0'}
136 >>> G.edges(data=True)
137 EdgeDataView([(0, 1, {'source': 0, 'target': 1})])
138 """
139 if name == ident:
140 raise nx.NetworkXError("name and ident must be different.")
142 multigraph = data.get("multigraph")
143 directed = data.get("directed")
144 if multigraph:
145 graph = nx.MultiGraph()
146 else:
147 graph = nx.Graph()
148 if directed:
149 graph = graph.to_directed()
150 graph.graph = dict(data.get("data"))
151 for d in data["elements"]["nodes"]:
152 node_data = d["data"].copy()
153 node = d["data"]["value"]
155 if d["data"].get(name):
156 node_data[name] = d["data"].get(name)
157 if d["data"].get(ident):
158 node_data[ident] = d["data"].get(ident)
160 graph.add_node(node)
161 graph.nodes[node].update(node_data)
163 for d in data["elements"]["edges"]:
164 edge_data = d["data"].copy()
165 sour = d["data"]["source"]
166 targ = d["data"]["target"]
167 if multigraph:
168 key = d["data"].get("key", 0)
169 graph.add_edge(sour, targ, key=key)
170 graph.edges[sour, targ, key].update(edge_data)
171 else:
172 graph.add_edge(sour, targ)
173 graph.edges[sour, targ].update(edge_data)
174 return graph