即时问题
解析器对您的输入感到困惑。我以前从未使用过 gml,但我一次将您的 gml 文件构建为一个文件,并发现了两个问题。
shape
没有价值的钥匙
- 具有元组值的键
(132, 258)
假设这个引用是正确的,有 4 种可能的值类型:
一个值可能有四种可能类型中的一种,整数(类型 gml$ _$int)、双精度类型(类型 gml$ _$double)、字符串(类型 gml$ _$string)或 GML 对象列表(输入 gml$ _$list)。
因此(132, 258)
无效,我相信没有价值也是无效的。
试试下面注释掉的gml,它会加载。
graph [
directed 1
node [
id 0
label 1
#shape
name "square"
#center (132, 258)
]
node [
id 1
label 2
#shape
name "triangle"
#center (132, 128)
]
edge [
source 0
target 1
relation "below"
]
edge [
source 1
target 0
relation "above"
]
]
替代解决方案
我发现某处nx.write_gml
不支持混合图,包括嵌套图。因此,即使您正确创建了图形,也不会将其正确写入文件。
这是一个替代的平面结构,虽然我不知道这是否是构建数据的好方法。它制作的标签可以用来识别每个形状的角。
import networkx as nx
dg = nx.DiGraph()
# square data
square_label = '0'
square_corners = [(0, 0), (0, 1), (1, 1), (1, 0)]
# main square node
dg.add_node(square_label, name='square')
# shape data for square
base_id = '{0}.corners.'.format(square_label)
last_corner_id = '{0}{1}'.format(base_id, len(square_corners)-1)
for i, corner in enumerate(square_corners):
x, y = corner
corner_id = '{0}{1}'.format(base_id, i)
dg.add_node(corner_id, x=x, y=y)
# instead of linking the square to every corner, you might want to link
# only to one corner and handle the cycle with edges between the corners
# or whatever. there are many ways it could be done I guess.
dg.add_edge(square_label, corner_id) # link from square to each corner
dg.add_edge(last_corner_id, corner_id) # corner to corner edges
last_corner_id = corner_id
nx.write_gml(dg, 'test.gml')
输出:
graph [
directed 1
node [
id 1
label "0"
name "square"
]
node [
id 0
label "0.corners.1"
y 1
x 0
]
node [
id 2
label "0.corners.3"
y 0
x 1
]
node [
id 3
label "0.corners.2"
y 1
x 1
]
node [
id 4
label "0.corners.0"
y 0
x 0
]
edge [
source 0
target 3
]
edge [
source 1
target 0
]
edge [
source 1
target 4
]
edge [
source 1
target 2
]
edge [
source 1
target 3
]
edge [
source 2
target 4
]
edge [
source 3
target 2
]
edge [
source 4
target 0
]
]