1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
|
import networkx as nx
__all__ = ["cytoscape_data", "cytoscape_graph"]
# TODO: Remove in NX 3.0
_attrs = dict(name="name", ident="id")
def cytoscape_data(G, attrs=None):
"""Returns data in Cytoscape JSON format (cyjs).
Parameters
----------
G : NetworkX Graph
The graph to convert to cytoscape format
attrs : dict or None (default=None)
A dictionary containing the keys 'name' and 'ident' which are mapped to
the 'name' and 'id' node elements in cyjs format. All other keys are
ignored. Default is `None` which results in the default mapping
``dict(name="name", ident="id")``.
.. deprecated:: 2.6
The `attrs` keyword argument will be replaced with `name` and
`ident` in networkx 3.0
Returns
-------
data: dict
A dictionary with cyjs formatted data.
Raises
------
NetworkXError
If the `name` and `ident` attributes are identical.
See Also
--------
cytoscape_graph: convert a dictionary in cyjs format to a graph
References
----------
.. [1] Cytoscape user's manual:
http://manual.cytoscape.org/en/stable/index.html
Examples
--------
>>> G = nx.path_graph(2)
>>> nx.cytoscape_data(G) # doctest: +SKIP
{'data': [],
'directed': False,
'multigraph': False,
'elements': {'nodes': [{'data': {'id': '0', 'value': 0, 'name': '0'}},
{'data': {'id': '1', 'value': 1, 'name': '1'}}],
'edges': [{'data': {'source': 0, 'target': 1}}]}}
"""
# ------ TODO: Remove between the lines in 3.0 ----- #
if attrs is None:
attrs = _attrs
else:
import warnings
msg = (
"\nThe function signature for cytoscape_data will change in "
"networkx 3.0.\n"
"The `attrs` keyword argument will be replaced with \n"
"explicit `name` and `ident` keyword arguments, e.g.\n\n"
" >>> cytoscape_data(G, attrs={'name': 'foo', 'ident': 'bar'})\n\n"
"should instead be written as\n\n"
" >>> cytoscape_data(G, name='foo', ident='bar')\n\n"
"in networkx 3.0.\n"
"The default values for 'name' and 'ident' will not change."
)
warnings.warn(msg, FutureWarning, stacklevel=2)
attrs.update({k: v for (k, v) in _attrs.items() if k not in attrs})
name = attrs["name"]
ident = attrs["ident"]
# -------------------------------------------------- #
if name == ident:
raise nx.NetworkXError("name and ident must be different.")
jsondata = {"data": list(G.graph.items())}
jsondata["directed"] = G.is_directed()
jsondata["multigraph"] = G.is_multigraph()
jsondata["elements"] = {"nodes": [], "edges": []}
nodes = jsondata["elements"]["nodes"]
edges = jsondata["elements"]["edges"]
for i, j in G.nodes.items():
n = {"data": j.copy()}
n["data"]["id"] = j.get(ident) or str(i)
n["data"]["value"] = i
n["data"]["name"] = j.get(name) or str(i)
nodes.append(n)
if G.is_multigraph():
for e in G.edges(keys=True):
n = {"data": G.adj[e[0]][e[1]][e[2]].copy()}
n["data"]["source"] = e[0]
n["data"]["target"] = e[1]
n["data"]["key"] = e[2]
edges.append(n)
else:
for e in G.edges():
n = {"data": G.adj[e[0]][e[1]].copy()}
n["data"]["source"] = e[0]
n["data"]["target"] = e[1]
edges.append(n)
return jsondata
def cytoscape_graph(data, attrs=None):
"""
Create a NetworkX graph from a dictionary in cytoscape JSON format.
Parameters
----------
data : dict
A dictionary of data conforming to cytoscape JSON format.
attrs : dict or None (default=None)
A dictionary containing the keys 'name' and 'ident' which are mapped to
the 'name' and 'id' node elements in cyjs format. All other keys are
ignored. Default is `None` which results in the default mapping
``dict(name="name", ident="id")``.
.. deprecated:: 2.6
The `attrs` keyword argument will be replaced with `name` and
`ident` in networkx 3.0
Returns
-------
graph : a NetworkX graph instance
The `graph` can be an instance of `Graph`, `DiGraph`, `MultiGraph`, or
`MultiDiGraph` depending on the input data.
Raises
------
NetworkXError
If the `name` and `ident` attributes are identical.
See Also
--------
cytoscape_data: convert a NetworkX graph to a dict in cyjs format
References
----------
.. [1] Cytoscape user's manual:
http://manual.cytoscape.org/en/stable/index.html
Examples
--------
>>> data_dict = {
... 'data': [],
... 'directed': False,
... 'multigraph': False,
... 'elements': {'nodes': [{'data': {'id': '0', 'value': 0, 'name': '0'}},
... {'data': {'id': '1', 'value': 1, 'name': '1'}}],
... 'edges': [{'data': {'source': 0, 'target': 1}}]}
... }
>>> G = nx.cytoscape_graph(data_dict)
>>> G.name
''
>>> G.nodes()
NodeView((0, 1))
>>> G.nodes(data=True)[0]
{'id': '0', 'value': 0, 'name': '0'}
>>> G.edges(data=True)
EdgeDataView([(0, 1, {'source': 0, 'target': 1})])
"""
# ------ TODO: Remove between the lines in 3.0 ----- #
if attrs is None:
attrs = _attrs
else:
import warnings
msg = (
"\nThe function signature for cytoscape_data will change in "
"networkx 3.0.\n"
"The `attrs` keyword argument will be replaced with \n"
"explicit `name` and `ident` keyword arguments, e.g.\n\n"
" >>> cytoscape_data(G, attrs={'name': 'foo', 'ident': 'bar'})\n\n"
"should instead be written as\n\n"
" >>> cytoscape_data(G, name='foo', ident='bar')\n\n"
"in networkx 3.0.\n"
"The default values for 'name' and 'ident' will not change."
)
warnings.warn(msg, FutureWarning, stacklevel=2)
attrs.update({k: v for (k, v) in _attrs.items() if k not in attrs})
name = attrs["name"]
ident = attrs["ident"]
# -------------------------------------------------- #
if name == ident:
raise nx.NetworkXError("name and ident must be different.")
multigraph = data.get("multigraph")
directed = data.get("directed")
if multigraph:
graph = nx.MultiGraph()
else:
graph = nx.Graph()
if directed:
graph = graph.to_directed()
graph.graph = dict(data.get("data"))
for d in data["elements"]["nodes"]:
node_data = d["data"].copy()
node = d["data"]["value"]
if d["data"].get(name):
node_data[name] = d["data"].get(name)
if d["data"].get(ident):
node_data[ident] = d["data"].get(ident)
graph.add_node(node)
graph.nodes[node].update(node_data)
for d in data["elements"]["edges"]:
edge_data = d["data"].copy()
sour = d["data"]["source"]
targ = d["data"]["target"]
if multigraph:
key = d["data"].get("key", 0)
graph.add_edge(sour, targ, key=key)
graph.edges[sour, targ, key].update(edge_data)
else:
graph.add_edge(sour, targ)
graph.edges[sour, targ].update(edge_data)
return graph
|