我正在尝试用Python编写一个数值方案来模拟网络上的偏微分方程。
我使用networkx
来实现网络结构。现在我想使用Multiprocessing
在给定的时间尺度上迭代每个边缘上相同的数值方案。每条边都有一个矩阵E
,E[n,:]
就是n
时的状态。
我试过这个:
def Scheme(G):
NUM_WORKERS = 4
for n in range(0,M): #time iteration
with multiprocessing.Pool(processes=NUM_WORKERS) as pool:
for edge in G.edges: #iteration edges
results = pool.map_async(Single_Scheme,(edge,n))
results.wait()
return G
此处Single_Scheme
是边缘上的算法,它在时间n + 1更新状态。
之前的代码会返回OSError: [Errno 24] Too many open files
。
为什么我收到此错误?
编辑:我尝试添加所有必要的细节。
Single_Scheme
函数定义如下:
def Single_Scheme(graph, edge, time):
V1=edge[0]
V2=edge[1]
if not V1 in W:
l=dt/graph[V1][V2]['dx']
V=Speed(graph,V1,V2,n)
if V1 in S:
graph[V1][V2]['ev_matrix'][n+1,0] = graph[V1][V2]['ev_matrix'][n,0]*(1 - l*V[0])
else:
graph[V1][V2]['ev_matrix'][n+1,0] = graph[V1][V2]['ev_matrix'][n,0]*(1 - l*V[0])
for V0 in list(graph.pred[V1]):
flux_prec = Speed(graph,V0,V1,n)[-1]
graph[V1][V2]['ev_matrix'][n+1,0]= graph[V1][V2]['ev_matrix'][n+1,0] + l*P[V0,V1,V2]*graph[V0][V1]['ev_matrix'][n,-1]*flux_prec
graph[V1][V2]['ev_matrix'][n+1,1:graph[V1][V2]['N']] = graph[V1][V2]['ev_matrix'][n,1:graph[V1][V2]['N']] - l*(V[1:graph[V1][V2]['N']]*graph[V1][V2]['ev_matrix'][n,1:graph[V1][V2]['N']] - V[0:graph[V1][V2]['N']-1]*graph[V1][V2]['ev_matrix'][n,0:graph[V1][V2]['N']-1])
return graph[V1][V2]['ev_matrix'][n+1,:]
此处graph[V1][V2]['ev_matrix][n,:]
是时间步(V1,V2)
边缘n
的状态。
进入主要部分时,它按以下方式调用:
%matplotlib inline
import multiprocessing
import networkx as nx
import numpy as np
from networkx.algorithms import topological_sort
G=nx.DiGraph()
G.add_nodes_from([0,1,2,3,4])
S=[1,2]
W=[3,4]
G.add_edges_from([(1,0),(2,0),(0,3),(0,4)])
G[1][0]['lenght']=1
G[2][0]['lenght']=1
G[0][3]['lenght']=1
G[0][4]['lenght']=1
n_nodes=nx.number_of_nodes(G)
P=np.zeros((n_nodes,n_nodes,n_nodes))
P[1,0,3]=0.5
P[1,0,4]=0.5
for node in list(topological_sort(G)):
for next_n in list(G.succ[node]):
G[node][next_n]['ev_matrix']= np.zeros((51,1001))
G[1][0]['ev_matrix'][0,4*int(np.floor(G[1][0]['N']/10)):6*int(np.floor(G[1][0]['N']/10))] = 1
G[2][0]['ev_matrix'][0,2*int(np.floor(G[2][0]['N']/4)):3*int(np.floor(G[2][0]['N']/4))]=1
G=Scheme(G)