def make_f_flow(edges, l_caps, r_caps, f): """ See tst2 for sample usage. Note: this is sub-optimal and unnecessarily complex. """ n_edges = np.max(edges) g = create_bipartite_graph(edges, l_caps, r_caps) flow_value, flow_dict = nx.maximum_flow(g, 0, n_edges + 1) while flow_value < f: for i in range(len(l_caps) + len(r_caps)): if i <= len(l_caps) - 1: edge = g[0][i + 1] flow_val = flow_dict[0][i + 1] else: edge = g[i + 1][n_edges + 1] flow_val = flow_dict[i + 1][n_edges + 1] if edge['capacity'] == flow_val: edge['capacity'] += 1 ## If we knew the upwards critical edges, we wouldn't have to run # max flow in a loop. # See: http://people.csail.mit.edu/moitra/docs/6854hw4.pdf nu_flow_value, nu_flow_dict = nx.maximum_flow( g, 0, n_edges + 1) if nu_flow_value == flow_value: edge['capacity'] -= 1 else: flow_value, flow_dict = nu_flow_value, nu_flow_dict if nu_flow_value == f: break flow_dict = nx.max_flow_min_cost(g, 0, n_edges + 1) return flow_dict
def flow_test(self,graph): """ Calculates the flow from sources to sinks in a graph. """ flow_graph_1=copy.deepcopy(graph[0]) flow_graph_2=copy.deepcopy(graph[1]) # Create flow graphs for testing #add aggregate sinks for i in xrange(len(self.sink[0])): flow_graph_1.add_edge(self.sink[0][i],'sink',capacity=self.sink_magnitude[0][i]) for i in xrange(len(self.sink[1])): flow_graph_2.add_edge(self.sink[1][i],'sink',capacity=self.sink_magnitude[1][i]) #add aggregate source flow_graph_1.add_node('place_holder') #fixes indexing error in maximum_flow for i in xrange(len(self.source[0])): flow_graph_1.add_edge('source',self.source[0][i],capacity=self.source_magnitude[0][i]) flow_graph_2.add_node('place_holder') #fixes indexing error in maximum_flow for i in xrange(len(self.source[1])): flow_graph_2.add_edge('source',self.source[1][i],capacity=self.source_magnitude[1][i]) flow_graph=[flow_graph_1,flow_graph_2] flow=[] # Test for cascading failures while True: #get flow values flow_value=[[],[]] flow_dict=[[],[]] flow_value[0], flow_dict[0] = nx.maximum_flow(flow_graph[0], 'source', 'sink') flow_value[1], flow_dict[1] = nx.maximum_flow(flow_graph[1], 'source', 'sink') flow.append(flow_value) failure=0 for link in self.links: #if sink in linked nodes fails, corresponding source fails receiving=link[0] #system recieving flow sending=link[1] #system sending flow node=link[2] sending_node_index=self.sink[sending].index(node) sending_flow=flow_dict[sending][node]['sink'] sending_threshold=float(self.sink_magnitude[sending][sending_node_index])*self.sink_threshold[sending][sending_node_index] failure=0 if sending_flow < sending_threshold: #sink fails and linked source fails failure=1 #emulate failure by cutting node off from aggregate source flow_graph[receiving]['source'][node]['capacity']=0 if failure==0 or (len(flow)>=2 and (flow[-1]==flow[-2])): #continue until steady-state break return flow_value, flow_dict
def Asynchronously_Graph_Theory_Maximum_Flow_In_Emulsion_Line_Backend(id_of_double_clicked_cell): G=Generate_The_G_Object_Of_Graph_For_Networkx() cpf_objects=mxGraph_Cells_Table_Class.query.filter(mxGraph_Cells_Table_Class.asset_type=='CPF').all() for cpf_object in cpf_objects: CPF_source='FN_out_'+str(cpf_object.cell_id) G.add_edge(CPF_source,'Master_CPF') #Master_CPF is the fake CPF that connects with all CPFs in the graph #this is necessary to allow us to find maximum flow when CPFs are interconnected specific_cell_objects=Cell_Id_And_Capacity_Table_Class.query.filter().all() for specific_cell_object in specific_cell_objects: specific_cell='FN_out_'+str(specific_cell_object.cell_id) try: flow_value, flow_dict = nx.maximum_flow(G,specific_cell,'Master_CPF') specific_cell_object.actual_possible_maximum_throughput=flow_value db.session.commit() except: continue #don't use 'pass', as pass willl make the loop stop, whereas 'continue' makes it go to the next iteration double_clicked_cell_object=Cell_Id_And_Capacity_Table_Class.query.filter(Cell_Id_And_Capacity_Table_Class.cell_id==id_of_double_clicked_cell).first() return str(double_clicked_cell_object.actual_possible_maximum_throughput)
def variacion_f(self, repeticiones, replicas): #Varia el destino self.tabla_f = [] self.best_f = [] for fila in range(self.dim_x): for columna in range(self.dim_y): if (fila, columna) != self.final: inicio = (fila, columna) for i in range(repeticiones): t_inicial = time.time() for i in range(replicas): flow_value, flow_dict = nx.maximum_flow( self.G, inicio, self.final, capacity='weight') t_final = time.time() self.tabla_f.append([ inicio, self.final, round(t_final - t_inicial, 2), round(flow_value, 2) ]) #print('-----------') #print('{} {} {:10.3f}{:10.3f}'.format(inicio,self.final,t_final-t_inicial,flow_value)) if flow_value - self.objetivo > 0.05: self.best_f.append(inicio) self.tabla_f = pd.DataFrame(self.tabla_f, columns=['I', 'F', 'TE', 'FO'])
def variacion_d(self, repeticiones, replicas): #Varia el final #aux=self. self.tabla_d = [] self.best_d = [] for fila in range(self.dim_x): for columna in range(self.dim_y): if (fila, columna) != self.inicio: final = (fila, columna) for i in range(repeticiones): t_inicial = time.time() for i in range(replicas): flow_value, flow_dict = nx.maximum_flow( self.G, self.inicio, final, capacity='weight') t_final = time.time() self.tabla_d.append([ self.inicio, final, round(t_final - t_inicial, 2), round(flow_value, 2) ]) #print('{} {} {:10.3f}{:10.3f}'.format(self.inicio,final,t_final-t_inicial,flow_value)) if flow_value - self.objetivo > 0.05: self.best_d.append(final) self.tabla_d = pd.DataFrame(self.tabla_d, columns=['I', 'F', 'TE', 'FO'])
def obtain_paths(self): """ Used to be a method of NeuralTriGraph. Moved here to avoid circular import. the argument, self is an instance of NeuralTriGraph. """ _, flow_dict = nx.maximum_flow(self.flow_graph, 'source', 'sink') self.vert_disjoint_paths = max_matching_to_paths(flow_dict) final_paths = [] for pth in self.vert_disjoint_paths: if len(pth) == 3: final_paths.append(pth) elif len(pth) == 2: left_layer = self.determine_layer(pth[0]) right_layer = self.determine_layer(pth[1]) if left_layer == 0 and right_layer == 2: central_candidates = self.layer_1_dict[pth[0]]\ .intersection(self.layer_3_dict[pth[1]]) # Randomly pick a central vertex. central = np.random.sample(central_candidates, 1)[0] pth1 = [pth[0], central, pth[1]] final_paths.append(pth1) elif left_layer == 0: right_sampled = np.random.sample( self.central_vert_dict[pth[1]].r_edges, 1)[0] pth1 = [pth[0], pth[1], right_sampled] final_paths.append(pth1) elif right_layer == 2: left_sampled = np.random.sample( self.central_vert_dict[pth[0]].l_edges, 1)[0] pth1 = [left_sampled, pth[0], pth[1]] final_paths.append(pth1) self.final_paths = final_paths
def getMaximumCoverageWalk(focalGraph,bubbleNodes,covMap): sources = [] sinks = [] directedGraph = nx.DiGraph(focalGraph.subgraph(bubbleNodes)) inDegree = directedGraph.in_degree(directedGraph.nodes()) reachableSources = [] for node,nDegree in inDegree: if nDegree == 0: sources.append(node) outDegree = directedGraph.out_degree(directedGraph.nodes()) for node,nDegree in outDegree: if nDegree == 0: sinks.append(node) if len(sources) > 0 and len(sinks) > 0: directedGraph.add_node('source') for source in sources: directedGraph.add_edge('source',source) directedGraph.add_node('sink') for sink in sinks: directedGraph.add_edge(sink,'sink') capacities = {} for e in directedGraph.edges: if e[1] == 'sink': capacities[e] = sys.float_info.max else: unitigU = e[1][:-1] capacities[e] = np.sum(covMap[unitigU]) nx.set_edge_attributes(directedGraph,capacities,'capacity') flow_value, flow_dict = nx.maximum_flow(directedGraph, 'source', 'sink') maxWalk = [] node = 'source' bProblem = False while node != 'sink': maxWalk.append(node) if len(flow_dict[node]) > 0: node = max(flow_dict[node], key=flow_dict[node].get) else: break bProblem = True if bProblem == False: maxWalk.pop(0) else: flow_value = None maxWalk = None return (flow_value, maxWalk)
def max_flow_solve(foods): G = nx.DiGraph() tmp_m, tmp_n = zip(*foods) all_i = set.union(*tmp_m) all_a = set.union(*tmp_n) allg_holders = { allg: set(i for i, f in enumerate(foods) if allg in f[1]) for allg in all_a } for i in all_i: G.add_edge("source", i, capacity=1.0) G.add_edge(i, "safe") for a in all_a: G.add_edge(a, "sink", capacity=1.0) possible_i = set.intersection(*(foods[f][0] for f in allg_holders[a])) for i in possible_i: G.add_edge(i, a, capacity=1.0) G.add_edge("safe", "sink", capacity=len(all_i) - len(all_a)) _, flow_dict = nx.maximum_flow(G, "source", "sink") solution = { k: max(v, key=v.get) for k, v in flow_dict.items() if k in all_i } return solution
def get_schedule(probs_left, probs_right, edges, num_nodes=20): source = 0 dest = np.max(edges) + 1 left_max_ix = max(edges[::, 0]) right_max_ix = max(edges[::, 1]) g = nx.DiGraph() for v in probs_left.keys(): cap = int(probs_left[v] * num_nodes) g.add_edge(source, v, capacity=cap, weight=1 / (cap + 1e-3)) for u, v in edges: g.add_edge(u, v, capacity=np.inf, weight=1) for v in probs_right.keys(): cap = int(probs_right[v] * num_nodes) g.add_edge(v, dest, capacity=cap, weight=1 / (cap + 1e-3)) flowed = 0 while flowed < num_nodes: # print("Now running networkx max-flow-min-cost " + str(right_max_ix)) # res_dict = nx.max_flow_min_cost(g, source, dest) res_val, res_dict = nx.maximum_flow(g, source, dest) flowed = res_val if np.random.uniform() > 0.5: h = np.random.choice(left_max_ix) + 1 g[0][h]['capacity'] += 1 else: v = np.random.choice(np.arange(left_max_ix + 1, right_max_ix + 1)) g[v][dest]['capacity'] += 1 return res_dict
def classificaGrafo(g): # 5.1 - Número de Nós n = g.number_of_nodes() # 5.2 - Número de Arcos a = g.number_of_edges() # 5.8 - |Arcos|/|Nos| r = a / n # 5.9 - Grau max dos nós ld_aux = g.degree ldegree = [i[1] for i in ld_aux] gdmax = max(ldegree) gdmin = min(ldegree) # 5.10 - Fluxo Máximo # 5.11 - Maior caminho mínimo maxmf = 0 maxcmin = 0 for i in range(n): for j in range(n): if i != j: mxf, _ = nkx.maximum_flow(g, i, j) cmin = nkx.shortest_path_length(g, i, j) if mxf > maxmf: maxmf = mxf if cmin > maxcmin: maxcmin = cmin ind = [n, a, r, gdmax, gdmin, maxmf, maxcmin] return ind
def create_assignments(g): flow_value, flow_dict = nx.maximum_flow(g, 'source', 'sink') assignments = {} num_assignments = {} for lab in labs: assignments[lab] = [] for ai, l in flow_dict.items(): if ai in lab_counts: assigned = 0 for lab, val in l.items(): if val == 1: assignments[lab].append(ai) assigned += 1 num_assignments[ai] = assigned print( "The following AIs have not been matched to the correct number of labs:" ) for ai in num_assignments: if num_assignments[ai] != lab_counts[ai]: print("AI: {}, Expected: {}, Assigned: {}".format( ai, lab_counts[ai], num_assignments[ai])) print() print( "Below are the assignments. Feel free to rerun this algorithm if they are not satisfactory." ) for lab in assignments: print('----{}----'.format(lab)) for ai in assignments[lab]: print(ai)
def strategise_enemy_fault_lines(self, world, player): possible_sources_and_sinks = [] territory_graph= nx.DiGraph() for a in world.areas: for t in world.areas[a].territories: for adj in t.adjacent(): if not adj.owner.name == player.name and not t.owner.name == player.name: territory_graph.add_edge(t.name, adj.name, capacity=-adj.forces) possible_sources_and_sinks.append(adj) possible_sources_and_sinks = compose(list, set)(possible_sources_and_sinks) graphs=list(nx.strongly_connected_component_subgraphs(territory_graph)) fault_lines = [] for g in graphs: sources_and_sinks_in_graph = [p for p in possible_sources_and_sinks if p.name in g.nodes()] ordered_pairs = [] for s in sources_and_sinks_in_graph: for d in sources_and_sinks_in_graph: if not s.name == d.name: ordered_pairs.append((s,d)) for s,d in ordered_pairs: flow_value, flow_dict = nx.maximum_flow(g, s.name, d.name) fault_lines.append((flow_value, flow_dict)) paths = [] for (f,p) in fault_lines: paths.append(unwrap_dict_of_dicts(p)) shortest_fault_line = [] shortest_fault_line_length = 50 for p in paths: if len(p) < shortest_fault_line_length: shortest_fault_line_length = len(p) shortest_fault_line = p self.fault_line = shortest_fault_line self.deceptive_attack.extend(self.fault_line)
def compute_mcf(self, servers): # Add super source and sink n = self.G.number_of_nodes() source, sink = n, n+1 self.G.add_node(source, demand=-self.total_demand) self.G.add_node(sink, demand=self.total_demand) # super source --> servers for i in servers: self.G.add_edge(source, i, cost=0, capacity=self.output_cap[servers[i]]) # cus --> super sink for i in self.cus_list: self.G.add_edge(i, sink, cost=0, capacity=self.cus_list[i]) for i in range(n): self.G.node[i]['demand'] = 0 min_cost_flow = nx.max_flow_min_cost(self.G, source, sink, weight='cost') min_cost = nx.cost_of_flow(self.G, min_cost_flow, weight='cost') max_flow = nx.maximum_flow(self.G, source, sink)[0] is_feasible = (max_flow == self.total_demand) print min_cost, max_flow, is_feasible # Delete edges for i in servers: self.G.remove_edge(source, i) for i in self.cus_list: self.G.remove_edge(i, sink) # Delete nodes self.G.remove_node(source) self.G.remove_node(sink) return min_cost, max_flow, is_feasible
def max_flow(G, fasta): if len(G) > 1: Jsum = sum(G.node[N]['intensity'] for N in G) bP = get_break_point(next(G.nodes_iter())[0], fasta) FG = nx.DiGraph() FG.add_node('S') # start FG.add_node('T') # terminus/sink for C in G: if C[0][0] == 'c': Cintensity = G.node[C]['intensity'] FG.add_node(C) FG.add_edge('S', C, capacity=Cintensity) for Z in G[C]: Zintensity = G.node[Z]['intensity'] FG.add_node(Z) FG.add_edge(C, Z) FG.add_edge(Z, 'T', capacity=Zintensity) flow_val, flows = nx.maximum_flow(FG, 'S', 'T') TotalFrags = Jsum - flow_val TotalETnoD = 0 TotalPTR = 0 for C, Z in G.edges_iter(): if C[0][0] == 'z': C, Z = Z, C TotalETnoD += flows[C][Z] * G.edge[C][Z]['ETnoD'] TotalPTR += flows[C][Z] * G.edge[C][Z]['PTR'] else: (nType, nQ, nG), Data = G.nodes(data=True)[0] I = Data['intensity'] bP = get_break_point(nType, fasta) TotalPTR = 0 TotalETnoD = 0 TotalFrags = I return Counter({'ETnoD': TotalETnoD, 'PTR': TotalPTR, bP: TotalFrags})
def findMaxFlow(self, is_plot_graph: bool = True): """ 寻找最大流 """ self.flow_graph = nx.DiGraph() for edge in self.edge_list: self.flow_graph.add_edge(edge[0], edge[1], capacity=edge[2]) # 计算最大流即每条边的流量 self.max_flow_value, self.max_flow_dict = nx.maximum_flow( self.flow_graph, self.start_node, self.end_node) print('最大流为:', self.max_flow_value) # 将最大流字典转换为列表 self.max_flow_edges = [] for node, nodes in self.max_flow_dict.items(): for node_, flow in nodes.items(): if flow > 0: self.max_flow_edges.append((node, node_, flow)) # 绘制图像 if is_plot_graph: # 原始图 fig = plt.figure() # type:plt.Figure ax = fig.add_subplot(121) _, pos = drawFlow(self.edge_list, ax) # 最大流图 ax_ = fig.add_subplot(122) self.max_flow_graph, _ = drawFlow(self.max_flow_edges, ax_, pos) ax_.set_title('Max Flow Graph')
def partition_matroid_intersection(self, pivots, partition): flow_graph = nx.DiGraph() for pivot in pivots: for rep in partition[pivot]: flow_graph.add_edge("s", "l" + str(pivot), capacity=1) flow_graph.add_edge("l" + str(pivot), "m" + str(rep), capacity=1) flow_graph.add_edge("m" + str(rep), "r" + str(self.groups[rep]), capacity=1) for i in range(self.g): flow_graph.add_edge("r" + str(i), "t", capacity=self.capacities[i]) flow_value, flow_dict = nx.maximum_flow(flow_graph, "s", "t") if flow_value != len(pivots): return [] solution_chen_etal = [] for pivot in pivots: for rep in partition[pivot]: rep_dict = flow_dict["m" + str(rep)] for edge in rep_dict.keys(): if rep_dict[edge] == 1: solution_chen_etal.append(rep) caps = self.capacities.copy() for point in solution_chen_etal: caps[self.groups[point]] -= 1 if caps[self.groups[point]] < 0: print(solution_chen_etal) return solution_chen_etal
def MFComponents(edges, n, filterZero=True): # Graph is created. G = nx.DiGraph() for edge in edges: i, j = edge G.add_node(i) G.add_node(j) G.add_edge(i, j, capacity=1) G.add_edge(j, i, capacity=1) CC = [] while True: if len(CC) == 0: missing = set(G.nodes) else: missing = list( set(G.nodes).difference(set(reduce(lambda x, y: x + y, CC)))) if len(missing) == 0: break newNode = missing.pop() newCC = [newNode] for i in missing: flow_value, flow_dict = nx.maximum_flow(G, newNode, i) if flow_value >= 1: newCC.append(i) CC.append(newCC) if filterZero: out = [elem for elem in CC if 0 not in elem] return out return CC
def graph_optimizn(): w5,l5,w,l,r,to_play=BaseballElim.w5,BaseballElim.l5,\ BaseballElim.w,BaseballElim.l,BaseballElim.r,\ BaseballElim.to_play g = nx.DiGraph() g.add_edge('s', '1-2', capacity=to_play[0, 1]) g.add_edge('s', '1-3', capacity=to_play[0, 2]) g.add_edge('s', '2-3', capacity=to_play[1, 2]) g.add_edge('s', '1-4', capacity=to_play[0, 3]) g.add_edge('s', '2-4', capacity=to_play[1, 3]) g.add_edge('s', '3-4', capacity=to_play[2, 3]) g.add_edge('1-2', '1', capacity=np.inf) g.add_edge('1-2', '2', capacity=np.inf) g.add_edge('1-3', '1', capacity=np.inf) g.add_edge('1-3', '3', capacity=np.inf) g.add_edge('2-3', '2', capacity=np.inf) g.add_edge('2-3', '3', capacity=np.inf) g.add_edge('1-4', '1', capacity=np.inf) g.add_edge('1-4', '4', capacity=np.inf) g.add_edge('2-4', '2', capacity=np.inf) g.add_edge('2-4', '4', capacity=np.inf) g.add_edge('3-4', '3', capacity=np.inf) g.add_edge('3-4', '4', capacity=np.inf) g.add_edge('1', 't', capacity=w[4] + r[4] - w[0]) g.add_edge('2', 't', capacity=w[4] + r[4] - w[1]) g.add_edge('3', 't', capacity=w[4] + r[4] - w[2]) g.add_edge('4', 't', capacity=w[4] + r[4] - w[3]) flow_value, flow_dict = nx.maximum_flow(g, 's', 't') #Greater than zero means eliminated detroit_eliminated = sum(sum(to_play[:4, :4])) / 2 - flow_value
def compute_solution_for_pivots_and_reps(self, pivots, representatives): flow_graph = nx.DiGraph() for pivot in pivots: flow_graph.add_edge("s", "l" + str(pivot), capacity=1) for i in range(self.g): flow_graph.add_edge("r" + str(i), "t", capacity=self.capacities[i]) for i in range(self.g): for pivot in pivots: if representatives[pivot].get(i) is not None: flow_graph.add_edge("l" + str(pivot), "r" + str(i), capacity=1) start = time.time() flow_value, flow_dict = nx.maximum_flow(flow_graph, "s", "t") end = time.time() if flow_value != len(pivots): return [] solution = [] for pivot in pivots: flow_edges_dict = flow_dict["l" + str(pivot)] for edge in flow_edges_dict.keys(): if flow_edges_dict[edge] == 1: rep_group = int(edge[1:]) rep = representatives[pivot][rep_group] solution.append(rep) caps = self.capacities.copy() for point in solution: caps[self.groups[point]] -= 1 if caps[self.groups[point]] < 0: print(solution) return solution
def networkx_graphviz(): """ Just a small test example """ import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() G.add_edge('x', 'a', capacity=3.0) G.add_edge('x', 'b', capacity=1.0) G.add_edge('a', 'c', capacity=3.0) G.add_edge('b', 'c', capacity=5.0) G.add_edge('b', 'd', capacity=4.0) G.add_edge('d', 'e', capacity=2.0) G.add_edge('c', 'y', capacity=2.0) G.add_edge('e', 'y', capacity=3.0) flow_value, flow_dict = nx.maximum_flow(G, 'x', 'y') nx.draw(G) plt.show() def draw_graphviz(G): plt.clf() pos = nx.drawing.nx_agraph.graphviz_layout(G, prog='dot') nx.draw(G, pos)
def FordFulkerson(node_values_1, node_values_2, source_node, target_node, capacity='capacity', weight=1): # deprecated, issues with infinite capacity G = nx.DiGraph() # nx.Graph() for i in range(len(node_values_1)): G.add_edge(node_values_1[i], node_values_2[i], capacity=weight, color='black') from matplotlib.pyplot import figure figure(num=None, figsize=(25, 25), dpi=120, facecolor='w', edgecolor='k') pos = nx.circular_layout(G) edges = G.edges() colors = [G[u][v]['color'] for u, v in edges] weights = [G[u][v]['capacity'] for u, v in edges] # R = ford_fulkerson(G, source_node, target_node, capacity) flow_value, flow_dict = nx.maximum_flow(G, source_node, target_node, capacity, flow_func=ford_fulkerson)
def find_flow(N, A, method): """Return flow dictionary for list of type,row,col starting locations""" G = nx.DiGraph() used = set() for t, r, c in A: s, e, occupied = find_connections(t, r, c, method) if occupied: assert s not in used assert e not in used used.add(s) used.add(e) G.add_edge('source', s, capacity=1) G.add_edge(e, 'sink', capacity=1) G.add_edge(s, e, capacity=1) starts = set() ends = set() for r in range(1, N + 1): for c in range(1, N + 1): s, e, _ = find_connections('o', r, c, method) starts.add(s) ends.add(e) if s in used or e in used: continue G.add_edge(s, e, capacity=1) for s in starts: if s in used: continue G.add_edge('source', s, capacity=1) for e in ends: if e in used: continue G.add_edge(e, 'sink', capacity=1) value, flow_dict = nx.maximum_flow(G, 'source', 'sink') return value, flow_dict
def part2(): # Note: Takes about 5 seconds to run tiles = process_input() flow_network = build_flow_network(tiles) _, flow_dict = nx.maximum_flow(flow_network, 'source', 'sink') for tile in flow_network.predecessors('sink'): if flow_dict[tile]['sink'] == 2: corner_tile = tile break tile_conns = generate_tile_conns(flow_network, flow_dict, corner_tile) conns_copy = tile_conns.copy() image_layout = generate_image_layout(tile_conns, corner_tile) full_image = create_full_image(conns_copy, tiles, image_layout) arrangements = process_sea_monster() for arrng in arrangements: num_sea_monsters = find_sea_monsters(full_image, arrng) if num_sea_monsters: break eval_roughness = lambda grid: sum([list(row).count('1') for row in grid]) total_roughness = eval_roughness(full_image) monsters_roughness = eval_roughness(arrangements[0]) * num_sea_monsters # Draw the flow network with capacities and flow amounts # draw_flow_network(flow_network, "Capacities") # draw_flow_network(flow_network, "Flow amounts", flow_dict) return total_roughness - monsters_roughness
def cb_RCC_violation(model, where): global RCC_count RCC_count = 0 if where == GRB.Callback.MIPSOL: rel = model.cbGetSolution(x) for (i, j ) in T: # check Graph-condition for every timeslot separately # Graph Generation active_lectures = [k for k in l if round(rel[k, (i, j)]) == 1] G = nx.DiGraph() G.add_node('s') G.add_nodes_from(s) G.add_nodes_from(b) G.add_node('t') for room in b: G.add_edge(room, 't', capacity=1) for k in s: G.add_edge('s', k, capacity=round(rel[k, (i, j)])) for room in b: if s[k] <= b[room]: G.add_edge(k, room, capacity=1) # print(G.number_of_nodes()) fmax, flow = nx.maximum_flow(G, 's', 't') if len(active_lectures) > fmax: model.cbLazy( quicksum(x[k, (i, j)] for k in active_lectures) <= fmax) RCC_count += 1
def MaximumFlow(dfed, source, target, from_label='node1', to_label='node2', capacity_label='capacity', flow_label='flow', **kwargs): """ 最大流問題 入力 dfed: 辺のDataFrameもしくはCSVファイル名 source: 開始点 target: 終了点 from_label: 元点の属性文字 to_label: 先点の属性文字 capacity_label: 辺の容量の属性文字 flow_label: 辺の流量の属性文字(結果) 出力 最大流と辺のDataFrame """ g, _, dfed = graph_from_table(None, dfed, from_label=from_label, to_label=to_label, from_to='FrTo_', **kwargs) r, t = nx.maximum_flow(g, source, target, capacity=capacity_label) dftmp = pd.DataFrame([(f'{min(i,j)}-{max(i,j)}', f) for i, d in t.items() for j, f in d.items() if f], columns=['FrTo_', flow_label]) return r, pd.merge(dfed, dftmp).drop('FrTo_', 1)
def compute_solution_for_pivots_and_reps(pivots, representatives): global g global capacities flow_graph = nx.DiGraph() for pivot in pivots: flow_graph.add_edge("s", "l" + str(pivot.id), capacity=1) for i in range(g): flow_graph.add_edge("r" + str(i), "t", capacity=capacities[i]) for i in range(g): for pivot in pivots: if representatives[pivot.id].get(i) is not None: flow_graph.add_edge("l" + str(pivot.id), "r" + str(i), capacity=1) flow_value, flow_dict = nx.maximum_flow(flow_graph, "s", "t") if flow_value != len(pivots): return [] solution = [] for pivot in pivots: flow_edges_dict = flow_dict["l" + str(pivot.id)] for edge in flow_edges_dict.keys(): if flow_edges_dict[edge] == 1: rep_group = int(edge[1:]) rep = representatives[pivot.id][rep_group] solution.append(rep) caps = capacities.copy() # Sanity check for point in solution: caps[point.group] -= 1 if caps[point.group] < 0: print(solution) return solution
def searchByTrainNo(date, trainNo, oriStation, arrStation): query = seatTable.loc[(seatTable['trnNo'] == trainNo) & (seatTable['trnOpDate'] == date)].replace(Tags) query['freeSeats'] = query['freeSeats'].astype(int) #Construct node information for nx.Digraph() availStaPair = list(map(tuple, query.iloc[:,2:4].itertuples(index=False))) freeSeatRecord = query.iloc[:,4:5].to_dict('records') for i in range(0, len(availStaPair)): tmp = list(availStaPair[i]) tmp.insert(2,freeSeatRecord[i]) availStaPair[i] = tuple(tmp) #Make a digraph for query allPairsGraph = nx.DiGraph() allPairsGraph.add_edges_from(availStaPair) allEdgeLabels = {} k = 0 for i in allPairsGraph.edges(): allEdgeLabels.update({i:query['freeSeats'].iloc[k]}) k += 1 try: availPath = nx.shortest_path(allPairsGraph, source=oriStation, target=arrStation) except: availPath = [] if len(availPath) > 3 or len(availPath) == 0: #沒票或超過台鐵單次可訂段數 return [], 0, allPairsGraph shortestGraph = allPairsGraph.subgraph(availPath) freeSeats = nx.get_edge_attributes(shortestGraph,'freeSeats') maxTicketCount, flow_dict = nx.maximum_flow(shortestGraph, oriStation,arrStation, capacity='freeSeats') return availPath, maxTicketCount, allPairsGraph
def node_attribute(G,node,nodeT): global total_data for i in range(10): data = {} start_time = time.time() for j in range(100): nx.maximum_flow(G, node, nodeT) data["G"] = G.degree(node) data["A"]= nx.clustering(G, node) data["C"] = nx.closeness_centrality(G, node) data["Ce"] = nx.load_centrality(G, node) data["E"] = nx.eccentricity(G, node) pageRank = nx.pagerank(G, weight="capacity") data["P"] = pageRank[node] data["Tiempo"] = time.time() - start_time total_data.append(data)
def match_students(students, projects): G = create_graph(students, projects) teams = [] flow_value, flow_dict = nx.maximum_flow(G, 'source', 'sink', capacity='capacity', flow_func=edmonds_karp) R = edmonds_karp(G, 'source', 'sink', capacity='capacity') team_number = 1 matched_students = [] for p in projects: studs = [] for s in students: if s.assigned == True: if p.project_id in flow_dict[s.email]: if flow_dict[s.email][p.project_id] == 1.0: studs.append(s) matched_students.append(s) teams.append(Team(p, studs, team_number)) team_number = team_number + 1 students_left = find_non_matched_students(R, students, matched_students) avaliable_projects = find_avaliable_projects(R, projects) if len(students_left) > 0: teams = match_remaining_students(teams, G, flow_dict, students_left, avaliable_projects, projects) return teams
def obtain_paths(self): _, flow_dict = nx.maximum_flow(self.flow_graph, 'source', 'sink') self.vert_disjoint_paths = max_matching_to_paths(flow_dict) final_paths = [] for pth in self.vert_disjoint_paths: if len(pth)==3: final_paths.append(pth) elif len(pth)==2: left_layer = self.determine_layer(pth[0]) right_layer = self.determine_layer(pth[1]) if left_layer==0 and right_layer==2: central_candidates = self.layer_1_dict[pth[0]]\ .intersection(self.layer_3_dict[pth[1]]) ## Randomly pick a central vertex. central = random.sample(central_candidates,1)[0] pth1 = [pth[0],central,pth[1]] final_paths.append(pth1) elif left_layer==0: right_sampled = random.sample(self.central_vert_dict[pth[1]]\ .r_edges,1)[0] pth1 = [pth[0],pth[1],right_sampled] final_paths.append(pth1) elif right_layer==2: left_sampled = random.sample(self.central_vert_dict[pth[0]]\ .l_edges,1)[0] pth1 = [left_sampled,pth[0],pth[1]] final_paths.append(pth1) self.final_paths = final_paths
def main(): """The main function. Returns: None. """ # This graph is borrowed from: # http://en.wikipedia.org/wiki/Maximum_flow_problem G = nx.DiGraph() G.add_edges_from((('s', 'o', dict(capacity=3)), ('s', 'p', dict(capacity=3)), ('o', 'p', dict(capacity=2)), ('o', 'q', dict(capacity=3)), ('q', 'r', dict(capacity=4)), ('q', 't', dict(capacity=2)), ('p', 'r', dict(capacity=2)), ('r', 't', dict(capacity=3)),)) flow_value, flows = nx.maximum_flow(G, 's', 't') print(f'maximum flow: {flow_value}') caps = nx.get_edge_attributes(G, 'capacity') for u in nx.topological_sort(G): for v, flow in sorted(flows[u].items()): print(f'({u}, {v}): {flow}/{caps[(u, v)]}')
def disjoint_paths_detail(self, s, G): s = s + 1000 flow_value, flow_dict = nx.maximum_flow(G, s, 'T') #print flow_value, flow_dict d = flow_dict G_ = nx.DiGraph() for key, value in d.iteritems(): for key2, value2 in value.iteritems(): if value2: #print key, key2, value2 G_.add_edge(key, key2) #O = [] Ij = G_.predecessors('T') O = [[] for _ in range(len(Ij))] F = [] i = 0 for c in Ij: cRel = G.node[c]['ctrl_rel'] for p in nx.all_simple_paths(G_, s, c): pRel = 1.0 for j in range(1, len(p) - 1): rel = G[p[j - 1]][p[j]].get('reliability') # print rel # if (rel > 1.0): # print rel, j-1, j, p assert (rel <= 1.0) pRel = pRel * rel #assert (k%2==0) #if k >0: #hop = k/2 # Oi is the individual failure probability Oi = 1.0 - pRel # else: # Oi = self.RCTRL #print k, path, Oi O[i].append(Oi) Fi = reduce(lambda x, y: x * y, O[i]) * cRel + 1 - cRel F.append(Fi) i += 1 R = 1 - reduce(lambda x, y: x * y, F) #nx.predecessor() #Ij = [] #if R >self.RREQ: return R, [i - 2000 for i in Ij]
def test_max_flow_mst_cong_approx(s): epsilon = 0.1 for i in range(20): g = graph_util.diluted_complete_graph(10, 0.9) if not g.has_edge(0, 1): g.add_edge(0, 1, {'capacity': 1}) cong_approx = MstCongestionApprox(g.to_undirected()) sherman_flow = sherman.ShermanFlow(g, cong_approx) _, flow_value = sherman_flow.max_st_flow(0, 1, epsilon) actual_flow_value, _ = nx.maximum_flow(g.to_undirected(), 0, 1) s.assertGreaterEqual(flow_value, (1.0 - epsilon) * actual_flow_value) s.assertLessEqual(flow_value, (1.0 + epsilon) * actual_flow_value)
def test_max_flow_conductance_cong_approx(s): epsilon = 0.1 n = 10 for p in [0.7, 0.8, 0.9, 1.0]: for i in range(100): g = graph_util.diluted_complete_graph(n, p) if not g.has_edge(0, 1): g.add_edge(0, 1, {'capacity': 1}) cong_approx = ConductanceCongestionApprox(g) sherman_flow = sherman.ShermanFlow(g, cong_approx) _, flow_value = sherman_flow.max_st_flow(0, 1, epsilon) actual_flow_value, _ = nx.maximum_flow(g.to_undirected(), 0, 1) s.assertGreaterEqual(flow_value, (1.0 - epsilon) * actual_flow_value) s.assertLessEqual(flow_value, (1.0 + epsilon) * actual_flow_value)
def flow_with_demands(G): """Computes a flow with demands over the given graph. Args: graph: A directed graph with nodes annotated with 'demand' properties and edges annotated with 'capacity' properties. Returns: A dict of dicts containing the flow on each edge. For instance, flow[s1][s2] should provide the flow along edge (s1, s2). Raises: NetworkXUnfeasible: An error is thrown if there is no flow satisfying the demands. """ # TODO: Implement the function. def flowreturn(flow,G): GH=G.copy() for edge in G.edges(): s1,s2=edge GH.edge[s1][s2]['flow']=flow[s1][s2] return GH.edge GC = G.copy() # add new source and terminal nodes GC.add_node('source') GC.add_node('terminal') # add edges of required capacity for node in G.nodes(): demand = G.node[node]['demand'] if demand < 0: GC.add_edge('source', node) obj=GC['source'][node]['capacity'] = -demand if demand > 0: GC.add_edge(node, 'terminal') GC[node]['terminal']['capacity'] = demand flow_value, flow_with_demands = nx.maximum_flow(GC, 'source', 'terminal') if(flow_value!=obj): raise nx.NetworkXUnfeasible("No flow satisfying the demands ") else: return flowreturn(flow_with_demands,G)
def maxFlowOpt(reads, maxReadsPerPos, minReadsPerPos): """ reads: maxReadsPerPos: maximum coverage (aka k) minReadsPerPos: minimum coverage (aka t) """ # flatten read start and end into one list positions = sorted(set([x for sublist in reads for x in sublist])) backboneCapacity = maxReadsPerPos - minReadsPerPos sourceSinkCapacity = maxReadsPerPos readIntervalCapacity = 1 superSource = -1 superSink = positions[-1] + 1 g = nx.DiGraph() # we remove reads directly from the list reads = copy.copy(reads) # add backbone g.add_edge(superSource, positions[0], {'capacity': sourceSinkCapacity}) g.add_edge(positions[-1], superSink, {'capacity': sourceSinkCapacity}) for (p0, p1) in utils.pairwise(positions): g.add_edge(p0, p1, {'capacity': backboneCapacity}) # add intervals for read in reads: g.add_edge(read[0], read[1], {'capacity': readIntervalCapacity}) # TODO: implement flow algorithm val, mincostFlow = nx.maximum_flow(g, superSource, superSink) pruned = [] # TODO: this is in O(n) -> we can do it in O(log n) for key, values in mincostFlow.items(): for value, weight in values.items(): if weight is 0: toRemove = (key, value) if toRemove in reads: pruned.append((key, value)) reads.remove((key, value)) return reads, pruned, mincostFlow
def set_flow(self): try: self.flow = nx.max_flow_min_cost(self, self.source, self.sink) self.flow_cost = nx.cost_of_flow(self, self.flow) self.max_flow = nx.maximum_flow(self, self.source, self.sink)[0] except nx.NetworkXUnfeasible: print 'Allocation satisfying the lower bounds is not possible.' print 'Try reducing lower bounds.' sys.exit(1) except nx.NetworkXError: print "The input graph is not directed or not connected." print "Please check the data:" print "e.g. if all the choices on the level 1 list are" \ " included in the level 2 list and same for levels 2, 3." sys.exit(1) except nx.NetworkXUnbounded: print "Allocation is not possible because some upper capacity" \ "bounds at level 1 have not been set up. Please check " \ "the data." sys.exit(1)
def MQI(G,A,B,VolA,VolB,c): H,s,t=Build_Direct_Graph(G,A,B,VolA,VolB,c) if (c!=0): HH=nx.DiGraph.reverse(H) flow_value,flow_dict=nx.maximum_flow(HH,t,s,capacity='capacity') print 'flow_value='+repr(flow_value) if (flow_value < c*len(A)): change=1 A_new=Build_A_new(HH,s,t,flow_dict) B_new=[] VolA_new=0 VolB_new=0 for x in range(len(G.nodes())): if (G.nodes()[x] in A_new): VolA_new+=G.degree(G.nodes()[x]) else: B_new.append(G.nodes()[x]) VolB_new+=G.degree(G.nodes()[x]) c_new=0 for x in range(len(G.edges())): node0=G.edges()[x][0] node1=G.edges()[x][1] if (((node0 in A_new)and(node1 in B_new))or((node1 in A_new)and(node0 in B_new))): c_new+=1 else: change=0 A_new=A B_new=B VolA_new=VolA VolB_new=VolB c_new=c else: change=0 A_new=A B_new=B VolA_new=VolA VolB_new=VolB c_new=c conductance_new=c_new/(VolA_new*1.00) return A_new,B_new,VolA_new,VolB_new,c_new,change,conductance_new
split_graph.add_edge(uV, vV, weight=udat['ratio'] * vdat['ratio']) # For each connected component of the graph # calculate the pairwise maximum flow where capacity is set equal to snp edge weights. # write each pairwise set as a matrix. # for n, sg in enumerate(nx.connected_component_subgraphs(split_graph, copy=True)): flows = None header = [] for i, u in enumerate(sg.nodes_iter()): header.append(str(u)) fr = [] for j, v in enumerate(sg.nodes_iter()): if i >= j: # calculating only half of the symmetric matrix fr.append(0) continue fv, fd = nx.maximum_flow(sg, u, v, capacity='weight') fr.append(fv) if flows is None: flows = np.array(fr, dtype=float) else: flows = np.vstack((flows, fr)) # to get a sensibly formatted matrix, use Pandas df = pd.DataFrame(flows, columns=header, index=header) df.to_csv('sg{0}.txt'.format(n), sep=' ', float_format='%.4f') nx.write_graphml(split_graph, sys.argv[2])
start_time = time.clock() cong_approx = ConductanceCongestionApprox(g) sherman_flow = sherman.ShermanFlow(g, cong_approx) flow, flow_value = sherman_flow.max_flow(demands, epsilon) stop_time = time.clock() print 'sherman flow:\n',flow print 'sherman flow value:',flow_value print 'sherman time:', stop_time - start_time elif algorithm == 'networkx': g = g.to_undirected() super_source = max(g.nodes()) + 1 g.add_node(super_source) super_sink = max(g.nodes()) + 1 g.add_node(super_sink) for s in sources: g.add_edge(super_source, s) for s in sinks: g.add_edge(s, super_sink) print 'starting networkx max flow' start_time = time.clock() flow_val, flow = nx.maximum_flow(g, super_source, super_sink) stop_time = time.clock() print 'Networkx flow value:',flow_val print 'Networkx time:', stop_time - start_time else: print 'Unknown algorithm: `%s`' % algorithm exit(1) exit(0)
if len(words) == 1: # case when there is empty line - list size is 1 b/c of empty string GG.append(G) G = nx.DiGraph() continue if not words[0].isdigit(): # case when there is line that has word at start if requests > 0: # case when there are still requests G.add_edge("s", words[0], capacity=req) # add edge between s and x G.add_edge(words[0], words[1], capacity=1) # add edge between x & y requests -= 1 else: # case when there are no more requests - time to process classes G.add_edge(words[0], "t", capacity=int(words[1])) # add edge between y and t else: # case when there is line that has number at start if int(words[0]) == 0 and int(words[1]) == 0 and int(words[2]) == 0: break else: requests = int(words[0]) classes = int(words[1]) req = int(words[2]) for graph in GG: flow_value = nx.maximum_flow(graph, "s", "t", capacity='capacity', flow_func=shortest_augmenting_path) if flow_value[0] >= req: print 'yes' else: print 'no' # print flow_value # my_dict = get_edge_attributes(graph, 'capacity') # for edge in my_dict: # print edge, my_dict[edge]
G.add_edge(source, i, capacity=capacity) print(fmt_str.format(source, i, capacity)) # from layter 1 to layer 2 for i in range(1, nr_nodes_per_layer + 1): j = i + nr_nodes_per_layer capacity = random.gammavariate(alpha, beta) G.add_edge(i, j, capacity=capacity) print(fmt_str.format(i, j, capacity)) # rom layer 2 to sink for i in range(nr_nodes_per_layer + 1, 2*nr_nodes_per_layer + 1): capacity = random.gammavariate(alpha, beta) G.add_edge(i, sink, capacity=capacity) print(fmt_str.format(i, sink, capacity)) return G, source, sink def print_flow_dict(G, flow_dict): for edge in G.edges_iter(): i, j = edge print('flow {0} -> {1}: {2:.3f}'.format(i, j, flow_dict[i][j])) if __name__ == '__main__': arg_parser = ArgumentParser(description='experiment with maximum flow ' 'algorithm') arg_parser.add_argument('--n', type=int, help='number of nodes/layer') options = arg_parser.parse_args() G, source, sink = create_graph(options.n) flow_value, flow_dict = nx.maximum_flow(G, source, sink) print('value = {0:.3f}'.format(flow_value)) print_flow_dict(G, flow_dict)
def maxflow(self): logging.info("Calculate max flow.") _, flows = networkx.maximum_flow(self.g, self.source, self.sink) return flows
# In[3]: # add capacities to the edges G.edge['s']['u']['capacity'] = 20 G.edge['s']['v']['capacity'] = 10 G.edge['u']['v']['capacity'] = 30 G.edge['u']['t']['capacity'] = 10 G.edge['v']['t']['capacity'] = 20 # We can now solve the max flow problem in just a single call. # In[4]: flow_value, maximum_flow = nx.maximum_flow(G, 's', 't') # this gives a cleaner way to print out the flow def print_flow(flow): for edge in G.edges(): n1, n2 = edge print edge, flow[n1][n2] print 'Flow value =', flow_value print 'Flow =' print_flow(maximum_flow) # The maximum flow should equal the minimum cut.