问题描述
我正在尝试将 Cytoscape Json (*cyjs) 读入 NetworkX 图。到目前为止没有运气,我也尝试了其他格式。这是一个示例输入:
{
"format_version" : "1.0","generated_by" : "cytoscape-3.8.2","target_cytoscapejs_version" : "~2.1","data" : {
"shared_name" : "Network","name" : "Network","SUID" : 172,"__Annotations" : [ ],"selected" : true
},"elements" : {
"nodes" : [ {
"data" : {
"id" : "187","shared_name" : "Node 3","name" : "Node 3","SUID" : 187,"selected" : false
},"position" : {
"x" : -387.81580333030377,"y" : 6.552640965689666
},"selected" : false
},{
"data" : {
"id" : "185","shared_name" : "Node 2","name" : "Node 2","SUID" : 185,"position" : {
"x" : -236.0,"y" : -66.0
},{
"data" : {
"id" : "183","shared_name" : "Node 1","name" : "Node 1","SUID" : 183,"position" : {
"x" : -392.0,"y" : -89.0
},"selected" : false
} ],"edges" : [ {
"data" : {
"id" : "189","source" : "187","target" : "185","shared_name" : "Node 3 (interacts with) Node 2","shared_interaction" : "interacts with","name" : "Node 3 (interacts with) Node 2","interaction" : "interacts with","SUID" : 189,{
"data" : {
"id" : "191","source" : "183","shared_name" : "Node 1 (interacts with) Node 2","name" : "Node 1 (interacts with) Node 2","SUID" : 191,"selected" : false
} ]
}
}
这是一个简单的有向图:
当我尝试使用 Netorkx 阅读时
import json
from networkx.readwrite.json_graph import cytoscape_data,cytoscape_graph
cyjs = json.load(open("Network.cyjs"))
graph = cytoscape_graph(cyjs)
我得到以下信息:
...
graph = cytoscape_graph(cyjs)
File "/$HOMEDIR/.local/lib/python3.8/site-packages/networkx/readwrite/json_graph/cytoscape.py",line 89,in cytoscape_graph
node = d["data"]["value"]
KeyError: 'value'
有人有从 Cytoscape 成功输入 NetworkX 的工作示例吗?
任何帮助或见解将不胜感激。
解决方法
使用 json 编写自己的解析器,提取边列表,从边列表构建图。类似的东西(确保这里的名称是唯一的)
import networkx as nx
import json
def cyjs2graph(cyjs_file_name):
cyjson = json.load(open(cyjs_file_name))
name_from_id = {}
for node in cyjson["elements"]["nodes"]:
name_from_id[node['data']['id']] = node['data']['name']
edge_list = []
for edge in cyjson["elements"]["edges"]:
src_id = edge['data']['source']
src_name = name_from_id[src_id]
tgt_id = edge['data']['target']
tgt_name = name_from_id[tgt_id]
edge_list.append([src_name,tgt_name])
graph = nx.from_edgelist(edge_list,create_using=nx.DiGraph)
return graph