在晶格中计算大小为l的窗口中的节点

时间:2019-06-24 23:49:05

标签: python python-3.x numpy graph networkx

我有一个networkx格子-

G=nx.grid_2d_graph(5,5,periodic=True)

现在,我想创建一个大小为l的窗口,其中l可以在晶格上变化,其中窗口的中心是晶格的中心。

我所有的节点都有一个附加值。该功能是-

 def node_status(self, node, time):
        r'''
        returns the status of a given node at a given time.

        :Arguments:

        **node**
            the node
        **time** float
            the time of interest.

        :Returns:

        **status** string ('S', 'I', or 'R')
            status of node at time.
        '''

因此,我想计算大小为l的窗口中“ R”节点的数量。我可以通过在窗口中的每个节点上调用函数来获取节点的状态。

供参考-

enter image description here

完整代码-

import matplotlib.pyplot as plt
import networkx as nx
import EoN

G=nx.grid_2d_graph(5,5)
m=5

initial_infections = [print(type()) for (u,v) in G if u==int(m/2) and v==int(m/2)]

sim = EoN.basic_discrete_SIR(G,0.5,initial_infecteds = initial_infections,
               return_full_data=True, tmax = 25)

pos = {node:node for node in G}
sim.set_pos(pos)
sim.display(1, node_size = 40) #display time 6
plt.show()

def linear_distance(x1, x2, m):
    if x2>x1:
        return min(x2-x1, x1+m-x2)
    else:
        return min(x1-x2, x2+m-x1)

def in_window(node1, node2, m,L):
    D1 = linear_distance(node1[0], node2[0], m)
    D2 = linear_distance(node1[1], node2[1], m)
    max_distance = max(D1, D2)
    return max_distance <= L #True if in window

def count_nodes(G, center, m, L):
    nearby_R = [node for node in G if sim.node_status(node,1) is 'R' and in_window(node, center, m,L)]
    return len(nearby_R)

count_nodes(G,(2,2),5,3)

1 个答案:

答案 0 :(得分:1)

挑战很可能是要计算一个节点是否在中心的给定距离内,特别是因为它是周期性的。因此,我定义了一个函数linear_distance,该函数检查1维距离,并考虑周期性。然后,我定义一个函数in_window,该函数使用linear_distance来判断节点是否在给定的窗口内。最后,我创建一个列表推导,其中包括窗口内所有具有所需状态的节点。您需要根据需要更新命令status(node)

def linear_distance(x1, x2, m):
    if x2>x1:
        return min(x2-x1, x1+m-x2)
    else:
        return min(x1-x2, x2+m-x1)

def in_window(node1, node2, m,L):
    D1 = linear_distance(node1[0], node2[0], m)
    D2 = linear_distance(node1[1], node2[1], m)
    max_distance = max(D1, D2)
    return max_distance <= L #True if in window

def count_nodes(G, center, m, L):
    nearby_R = [node for node in G if status(node) is 'R' and in_window(node, center, m,L)]
    return len(nearby_R)