对于键渗滤模型,我想使用grid_2d_graph(l,l)
与NetworkX一起构建方阵。这给了我一个lxl
大小的方格,每个边open
。
这个想法是,我想随机选择图形的一条边,然后检查该边是否已被分配(1保留该边不变,0将该边添加到要从中删除的边列表中图),如果尚未分配(边缘为'state' = -1
),我想以特定概率p
随机选择,如果边缘是开放的(保持原样),或者如果它是封闭的(将其放在要删除的边缘列表上)。
因此,我将所有具有数据属性'state' = -1
的边保存为列表,然后尝试随机访问此列表的条目,然后将属性'state'
更改为某个值。但是似乎不允许执行此操作。当我尝试编辑状态时,出现以下错误:
File "bond-percolation.py", line 39, in <module>
ed[10][2] = 1
TypeError: 'tuple' object does not support item assignment
所以我的问题是,如何才能随机选择一条边并有效地更改'state'
的值?
这是我的代码:
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import random
#Width of the quadratic lattice
l = 30
#Create grid
G = nx.grid_2d_graph(l,l)
#Total number of edges in the lattice
n = 2 * l * (l-1)
m = 0
#Set probability if an edge is open
p = 0.17
#Create empty list to add closed edges later
ed = []
ld = []
for e in G.edges(data = 'state', default = -1):
ed.append(e)
#Creating the lattice
while (m != n):
i = np.random.randint(n-1)
a = random.random()
if (ed[i][2] == -1):
if (a > p):
ld.append(ed[i])
else:
ed[i][2] = 1
m = m + 1
#We need this so that the lattice is drawn vertically to the horizon
pos = dict( (l,l) for l in G.nodes() )
#Draw the lattice
nx.draw_networkx(G, pos = pos, with_labels = False, node_size = 0)
#Plot it on the screen
plt.axis('off')
plt.show()
答案 0 :(得分:0)
我相信您可以使用edge selector进行搜索。
没有内置的选择器(afaik),但是您可以创建一个帮助函数,该帮助器循环遍历边缘并返回列表。
def filter_edges(value):
edge_list = []
for u,v,s in G.edges(data='state'):
if s == value:
edge_list.append((u,v))
return edge_list
答案 1 :(得分:0)
重新读取您的错误,我认为您的错误与随机拾取边缘无关。相反,您错误地尝试分配状态值。
ed[10][2]
返回整个边缘(大概是字典)。刚运行ed[10][2]
时包括输出将很有帮助。
您不能为此分配一个int。您可能想做ed[10][2]['state'] = 1