def test_shortest_augmenting_path_two_phase(): k = 5 p = 1000 G = nx.DiGraph() for i in range(k): G.add_edge('s', (i, 0), capacity=1) G.add_path(((i, j) for j in range(p)), capacity=1) G.add_edge((i, p - 1), 't', capacity=1) R = shortest_augmenting_path(G, 's', 't', two_phase=True) assert_equal(R.graph['flow_value'], k) R = shortest_augmenting_path(G, 's', 't', two_phase=False) assert_equal(R.graph['flow_value'], k)
def test_shortest_augmenting_path_two_phase(): k = 5 p = 1000 G = nx.DiGraph() for i in range(k): G.add_edge("s", (i, 0), capacity=1) nx.add_path(G, ((i, j) for j in range(p)), capacity=1) G.add_edge((i, p - 1), "t", capacity=1) R = shortest_augmenting_path(G, "s", "t", two_phase=True) assert R.graph["flow_value"] == k R = shortest_augmenting_path(G, "s", "t", two_phase=False) assert R.graph["flow_value"] == k
def test_cutoff(self): k = 5 p = 1000 G = nx.DiGraph() for i in range(k): G.add_edge('s', (i, 0), capacity=2) G.add_path(((i, j) for j in range(p)), capacity=2) G.add_edge((i, p - 1), 't', capacity=2) R = shortest_augmenting_path(G, 's', 't', two_phase=True, cutoff=k) ok_(k <= R.graph['flow_value'] <= 2 * k) R = shortest_augmenting_path(G, 's', 't', two_phase=False, cutoff=k) ok_(k <= R.graph['flow_value'] <= 2 * k) R = edmonds_karp(G, 's', 't', cutoff=k) ok_(k <= R.graph['flow_value'] <= 2 * k)
def test_cutoff(self): k = 5 p = 1000 G = nx.DiGraph() for i in range(k): G.add_edge("s", (i, 0), capacity=2) nx.add_path(G, ((i, j) for j in range(p)), capacity=2) G.add_edge((i, p - 1), "t", capacity=2) R = shortest_augmenting_path(G, "s", "t", two_phase=True, cutoff=k) assert k <= R.graph["flow_value"] <= (2 * k) R = shortest_augmenting_path(G, "s", "t", two_phase=False, cutoff=k) assert k <= R.graph["flow_value"] <= (2 * k) R = edmonds_karp(G, "s", "t", cutoff=k) assert k <= R.graph["flow_value"] <= (2 * k)
def solve(testlist): G = nx.DiGraph() dict1 = {} a = 0 while a < (len(testlist)): b = 0 G.add_node(str(a)) dict1[str(a)] = len(testlist[a]) while b < len(testlist[a]): s = testlist[a][b] G.add_edge(str(a), s, capacity=1.0) b += 1 a += 1 a = 0 c = 0 while a < (len(testlist)): b = a + 1 while b < (len(testlist)): if dict1[str(a)] >= c and dict1[str(b)] >= c: res = shortest_augmenting_path(G, str(a), str(b), two_phase=True) flow = res.graph['flow_value'] if flow > c: c = int(flow) b += 1 a += 1 return (c)
def Maxflow(G, a, b): tiempo_inicial = dt.datetime.now() # d =shortest_augmenting_path(G, a, b, capacity="weight") for i in range(40): d = shortest_augmenting_path(G, a, b, capacity="weight") print(dt.datetime.now()) tiempo_final = (dt.datetime.now() - tiempo_inicial).total_seconds() return tiempo_final
def find_substrate_path(self, copied_substrate, vnr, embedding_s_nodes): embedding_s_paths = {} directed_copied_substrate = copied_substrate.net.to_directed() # mapping the virtual nodes and substrate_net nodes for src_v_node, dst_v_node, edge_data in vnr.net.edges(data=True): v_link = (src_v_node, dst_v_node) src_s_node = embedding_s_nodes[src_v_node][0] dst_s_node = embedding_s_nodes[dst_v_node][0] v_bandwidth_demand = edge_data['bandwidth'] if src_s_node == dst_s_node: s_links_in_path = [] embedding_s_paths[v_link] = (s_links_in_path, v_bandwidth_demand) else: subnet = nx.subgraph_view( copied_substrate.net, filter_edge=lambda node_1_id, node_2_id: \ True if copied_substrate.net.edges[(node_1_id, node_2_id)][ 'bandwidth'] >= v_bandwidth_demand else False ) # Just for assertion # for u, v, a in subnet.edges(data=True): # assert a["bandwidth"] >= v_bandwidth_demand if len(subnet.edges) == 0 or not nx.has_path(subnet, source=src_s_node, target=dst_s_node): self.num_link_embedding_fails += 1 msg = "VNR {0} REJECTED ({1}): 'no suitable LINK for bandwidth demand: {2} {3}".format( vnr.id, self.num_link_embedding_fails, v_bandwidth_demand, vnr ) self.logger.info("{0} {1}".format(utils.step_prefix(self.time_step), msg)) return None MAX_K = 1 # shortest_s_path = utils.k_shortest_paths(subnet, source=src_s_node, target=dst_s_node, k=MAX_K)[0] # https://networkx.org/documentation/stable//reference/algorithms/generated/networkx.algorithms.flow.shortest_augmenting_path.html residual_network = shortest_augmenting_path(directed_copied_substrate, src_s_node, dst_s_node, capacity='bandwidth', cutoff=v_bandwidth_demand) s_links_in_path = [] path = [] for src_r_node, dst_r_node, r_edge_data in residual_network.edges(data=True): if r_edge_data['flow'] > 0: s_links_in_path.append((src_r_node, dst_r_node)) # s_links_in_path = [] # for node_idx in range(len(shortest_s_path) - 1): # s_links_in_path.append((shortest_s_path[node_idx], shortest_s_path[node_idx + 1])) for s_link in s_links_in_path: # assert copied_substrate.net.edges[s_link]['bandwidth'] >= v_bandwidth_demand copied_substrate.net.edges[s_link]['bandwidth'] -= v_bandwidth_demand embedding_s_paths[v_link] = (s_links_in_path, v_bandwidth_demand) return embedding_s_paths
def matching_or_cset(G): DG = gen_di_graph(G) # Use networkx min cut to find matching or constricted set min_f, part = nx.minimum_cut(DG, "source", "sink") num_xs = len([n for n, d in G.nodes(data=True) if d["bipartite"]==0]) num_ys = len([n for n, d in G.nodes(data=True) if d["bipartite"]==1]) residual = shortest_augmenting_path(DG, "source", "sink") if num_xs == num_ys and num_xs == min_f: ret = [] for edge in residual.edges.data(): if edge[0] != "source" and edge[1] != "sink" and edge[2]["flow"] > 0: ret.append((edge[0], edge[1])) return (ret, True) # return matching set and True return ([x for x in part[0] if x!="source" and x!="sink" and DG.nodes[x]["bipartite"]==0], False) # return constricted set and False
def caculatemaxConcurrentMFPRoute(filename, consumerList, producerList): # Traffic Matrix d[1,5] represent interest from node 1 to node 5 e, n = readTopology(filename) d = OrderedDict() for i in range(len(consumerList)): d[consumerList[i], producerList[i]] = 1 #model=maxConcurrentMFP(n, e, d) model = maxConcurrentFlowMinCostMFP(n, e, d) model.hideOutput() model.optimize() vlamb, x = model.data lamb = model.getVal(vlamb) print " --------variant lambda is:", lamb print " --------obj is: ", model.getObjVal() ''' for v in model.getVars(): if model.getVal(v)>EPS: print('{0}={1}'.format(v.name,model.getVal(v))) for (s,t) in d.keys(): if(d[s,t]>EPS): for (i,j) in e.keys(): if(model.getVal(x[i,j,s,t])>EPS): print('--------x[{0},{1},{2},{3}]={4}'.format(i,j,s,t,model.getVal(x[i,j,s,t]))) ''' routeList = [] probability = 1.0 rG = nx.DiGraph() for (s, t) in d.keys(): # 2018-3-26,为了去掉解中的路由环路 rG.clear() for (i, j) in e.keys(): if (model.getVal(x[i, j, s, t]) > EPS): rG.add_edge(i, j, capacity=model.getVal(x[i, j, s, t])) R = shortest_augmenting_path(rG, s, t) if R.graph['flow_value'] + EPS < lamb: print "2018-3-26 全局解的最大流没有达到lambda" print "最大流:{0}".format(R.graph['flow_value']) continue ''' ******traffic split 实现方法********* 因为即使没有环路,也不能保证一种商品流的多条路径没有公共节点,当有公共节点时,例如节点 Node5流入有两条边共200 流出有2条(边的容量是100)。在转发时,默认的转发策略ncc和Flooding一样,向所有端口复制,导致每条边都有200, 由于超出带宽,会被迫丢包,但是丢包不能保证公平,所以仿真结果和预期差别较大 为避免上述情况,这里是针对源节点,分流概率为 流量/lamb,对于中继节点,概率=流量/流入该节点的总和 当使用概率转发时,可以split流量,和cpp中的多路径不一样 ''' # 计算节点的流入流量总和 inFlow = {} for aNode in R.nodes: inFlow[aNode] = 0 for (eStart, aNode) in rG.in_edges(aNode): inFlow[aNode] = inFlow[aNode] + R[eStart][aNode]['flow'] for (i, j) in rG.edges: if (R[i][j]['flow'] > EPS): if (i == s): totalInFlow = lamb else: totalInFlow = inFlow[i] if (totalInFlow == 0): print("i={0},j={1},s={2},t={3},flow={4},inFlow={5}". format(i, j, s, t, R[i][j]['flow'], inFlow[i])) r = { 'edgeStart': i, 'edgeEnd': j, 'prefix': "/" + t, 'cost': 1, 'probability': (R[i][j]['flow'] / totalInFlow) } routeList.append(r) print r return lamb, routeList
nx.draw_networkx_edges(G, position, width=widths, edge_color='black') nx.draw_networkx_edge_labels(G, position, edge_labels=labels, font_size=10, label_pos=.5) nx.draw_networkx_labels(G, position, font_size=15) df = pd.DataFrame(position) df.to_csv("position1" + ".csv", index=None, header=None) plt.axis("off") plt.savefig("Grafo1a" + ".png", bbox_inches='tight') plt.savefig("Grafo1a" + ".eps", bbox_inches='tight') plt.show(G) d = shortest_augmenting_path(G, 4, 8, capacity="weight") flowma = [] widths1 = [] widths0 = [] widths2 = [] widths3 = [] maxi = 0 nodos = [] nodosF = [4] nodosS = [8] nodos = listnodos(d, 4, 8) for edges in d.edges(): widths.append(d.edges[edges]["flow"]) if d.edges[edges]["flow"] > 0: widths1.append(d.edges[edges]["capacity"]) widths0.append(edges)
import networkx as nx from networkx.algorithms.flow import shortest_augmenting_path G = nx.DiGraph() G.add_edge('x','a', capacity=100) G.add_edge('x','b', capacity=100) G.add_edge('a','c', capacity=100) G.add_edge('b','c', capacity=100) G.add_edge('b','d', capacity=100) G.add_edge('d','e', capacity=100) G.add_edge('c','y', capacity=100) G.add_edge('e','y', capacity=100) R = shortest_augmenting_path(G, 'x', 'y') flow_value = nx.maximum_flow_value(G, 'x', 'y') print flow_value print flow_value == R.graph['flow_value']
def betterUse(self, p1, p2, newc): R = shortest_augmenting_path(G, 's', 't') self.flow_value = R.graph['flow_value']