def Edmond(G, a, b): start_time = time() R = edmonds_karp(G, a, b, capacity="weight") for i in range(20): print(1) time_elapsed = time() - start_time return time_elapsed
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) 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 image_processing_pipeline(image, foreground, background): # image is a np.array, in RGB model width, height, depth = np.array(image).shape # rescaling size_y = 100 size_x = int(width * size_y / height) resized_image = image.resize((size_x, size_y), Image.ANTIALIAS) y, u, v = transform_rgb_to_yuv(np.array(resized_image)) bitmaps = [] for channel in ['y', 'u', 'v']: if channel == 'y': im_channel = np.array(y) elif channel == 'u': im_channel = np.array(u) else: im_channel = np.array(v) im_arr = im_channel.reshape( (im_channel.shape[0], im_channel.shape[1], 1)) mu1, std1, mu2, std2 = get_distributions(foreground, background, channel) G = create_graph(im_arr, mu1, std1, mu2, std2) R = edmonds_karp(G, 's', 't') print('Current flow:', R.graph['flow_value'], end=' ') flows = [ R['s'][(i, j)]['flow'] for i in range(im_channel.shape[0]) for j in range(im_channel.shape[1]) ] threshold = 2 * np.mean(flows) ### can be modified with web interface? bitmap = get_bitmap(R, threshold, im_channel.shape[0], im_channel.shape[1]) bitmaps.append(bitmap) print('Slice {}: done!'.format(channel)) result_image = np.array(resized_image) for k in range(result_image.shape[2]): for i in range(result_image.shape[0]): for j in range(result_image.shape[1]): if bitmaps[0][i, j] + bitmaps[1][i, j] + bitmaps[2][i, j] == 0: result_image[i, j] = 255 return Image.fromarray(np.uint8(result_image), 'RGB').resize( (image.size[0], image.size[1]), Image.ANTIALIAS)
def calculate_edmonds_karp(pores, throats, viscosity, A, dP, L): edges = list() for id in throats.index: edges.append((throats.loc[id, 'pore_a'], throats.loc[id, 'pore_b'], { 'capacity': throats.loc[id, 'conductance'] * throats.loc[id, 'length'] * viscosity, 'id': id })) pores_in = pores.left pores_in = pores_in[pores_in] for id in pores_in.index: edges.append(('in_b', id)) edges.append(('in_a', 'in_b')) pores_out = pores.right pores_out = pores_out[pores_out] for id in pores_out.index: edges.append(('out_a', id)) edges.append(('out_a', 'out_b')) G = nx.Graph() G.add_edges_from(edges) R = edmonds_karp(G, 'in_a', 'out_b') cut_value, partition = nx.minimum_cut(G, 'in_a', 'out_b') reachable, non_reachable = partition min_cut_node_pairs = set() for u, nbrs in ((n, G[n]) for n in reachable): min_cut_node_pairs.update((u, v) for v in nbrs if v in non_reachable) min_cut_edges_id = list() for node_pair in min_cut_node_pairs: min_cut_edges_id.append(int(G.adj[node_pair[0]][node_pair[1]]['id'])) min_cut = dict() min_cut['id'] = throats.loc[min_cut_edges_id, 'id'] min_cut['radius'] = throats.loc[min_cut_edges_id, 'radius'] min_cut['velocity'] = throats.loc[min_cut_edges_id, 'velocity'] return R, min_cut
def measurement(self): for i in range(self.number_of_checks): while not self.src or not self.sink: self.get_directed_weighted_graph() self.get_source_and_sink() try: self.karp_times.append( timeit(lambda: edmonds_karp(self.G, self.src, self.sink), number=5) / 5) except: self.karp_times.append('no path') try: self.push_times.append( timeit(lambda: preflow_push(self.G, self.src, self.sink), number=5) / 5) except: self.push_times('no path') try: self.ratio.append(self.karp_times[i] / self.push_times[i]) except: self.ratio.append('----') self.src, self.sink = None, None # print(f"check number {i}") df = pd.DataFrame({ 'Edmonds-Karp': self.karp_times, 'Preflow Push': self.push_times, 'Karp/Preflow': self.ratio }) print( f"\n\t\tTable for {self.V} nodes & {self.E} edges.\n" f"The capacities of edges have been distributed from {self.min_weight}" f" up to {self.max_weight}.") print(df)
def test_raw(): edges, weights = ex_graph() weighted_graph = nx.from_edgelist(edges) for i_edge, edge in enumerate(edges): weighted_graph[edge[0]][edge[1]]['capacity'] = weights[i_edge] r_flow = edmonds_karp(weighted_graph, 0, 11) cutset = minimum_st_edge_cut(weighted_graph, 0, 11, residual=r_flow) weighted_graph.remove_edges_from(cutset) ccs = list(nx.connected_components(weighted_graph)) print("NETWORKX:", cutset) print("NETWORKX:", ccs) g = graph_tool.all.Graph(directed=True) g.add_edge_list(edge_list=np.concatenate([edges, edges[:, [1, 0]]]), hashed=False) cap = g.new_edge_property("float", vals=np.concatenate([weights, weights])) src, tgt = g.vertex(0), g.vertex(11) res = graph_tool.flow.boykov_kolmogorov_max_flow(g, src, tgt, cap) part = graph_tool.all.min_st_cut(g, src, cap, res) rm_edges = [e for e in g.edges() if part[e.source()] != part[e.target()]] print("GRAPHTOOL:", [(rm_edge.source().__str__(), rm_edge.target().__str__()) for rm_edge in rm_edges]) ccs = [] for i_cc in np.unique(part.a): ccs.append(np.where(part.a == i_cc)[0]) print("GRAPHTOOL:", ccs) return edges, weights
def calculate_edmonds_karp(pores, throats, viscosity, A, dP, L): edges = list() for id in throats.index: edges.append((throats.loc[id, 'pore_a'], throats.loc[id, 'pore_b'], { 'capacity': throats.loc[id, 'conductance'] * throats.loc[id, 'length'] * viscosity, 'id': id })) pores_in = pores.left pores_in = pores_in[pores_in] for id in pores_in.index: edges.append(('in_b', id)) edges.append(('in_a', 'in_b')) pores_out = pores.right pores_out = pores_out[pores_out] for id in pores_out.index: edges.append(('out_a', id)) edges.append(('out_a', 'out_b')) G = nx.Graph() G.add_edges_from(edges) R = edmonds_karp(G, 'in_a', 'out_b') print() print('K_edm', R['in_a']['in_b']['flow'] / A) print('Q_edm', R['in_a']['in_b']['flow'] * dP / L / viscosity) # cut_value, partition = nx.minimum_cut(G, 'in_a', 'out_b',flow_func=edmonds_karp) cut_value, partition = nx.minimum_cut(G, 'in_a', 'out_b') reachable, non_reachable = partition print() print('K_cut', cut_value / A) print('Q_cut', cut_value * dP / L / viscosity) reachable, non_reachable = partition min_cut_node_pairs = set() for u, nbrs in ((n, G[n]) for n in reachable): min_cut_node_pairs.update((u, v) for v in nbrs if v in non_reachable) min_cut_edges_id = list() for node_pair in min_cut_node_pairs: min_cut_edges_id.append(int(G.adj[node_pair[0]][node_pair[1]]['id'])) all_edges = G.edges() print() print('edges_n', len(all_edges)) print('min_cut_edges_n', len(min_cut_edges_id)) # print() # print('all_edges', all_edges) # # print() # print('min_cut_edges', sorted(cut_set_edges)) # color_edges = list() # for edge in all_edges: # if edge in min_cut_node_pairs: # color_edges.append('r') # else: # color_edges.append('b') # nx.draw_networkx(G,pos=nx.spring_layout(G),edge_color=color_edges) # plt.show() edges_n = len(all_edges) min_cut_edges_n = len(min_cut_node_pairs) # with open('out/min_cut_max_flow.txt', 'w') as file: # file.write('edges_n, min_cut_edges_n\n') # file.write(str(edges_n) + ', ' + str(min_cut_edges_n) + '\n') min_cut = dict() min_cut['id'] = throats.loc[min_cut_edges_id, 'id'] min_cut['radius'] = throats.loc[min_cut_edges_id, 'radius'] min_cut['velocity'] = throats.loc[min_cut_edges_id, 'velocity'] return R, min_cut
# Get first line first_line = line.rstrip().split(' ') nb_of_machines = int(first_line[0]) if nb_of_machines == 0: break # init graph graph = nx.DiGraph() # Get the second line second_line = next(input_file).rstrip().split(' ') source = second_line[0] sink = second_line[1] nb_connections = int(second_line[2]) # Get the connections for _ in xrange(nb_connections): connection = next(input_file).rstrip().split(' ') machine_a = connection[0] machine_b = connection[1] bandwidth = int(connection[2]) graph.add_edge(machine_a, machine_b, capacity=bandwidth) print "Network %d" % network_index ek = edmonds_karp(graph, source, sink) print "The bandwidth is %d.\n" %\ nx.maximum_flow_value(graph, source, sink) network_index += 1
def Edmond(G, a, b): start_time = time() R = edmonds_karp(G, a, b) time_elapsed = time() - start_time return time_elapsed
} before = datetime.datetime.now() ford_fulkerson(graph, 'S', 'Z') after = datetime.datetime.now() time = after - before print(time) #draw_graph() G = nx.DiGraph() G.add_edge('S', 'A', capacity=10.0) G.add_edge('S', 'C', capacity=10.0) G.add_edge('A', 'C', capacity=2.0) G.add_edge('A', 'B', capacity=4.0) G.add_edge('A', 'D', capacity=8.0) G.add_edge('B', 'Z', capacity=10.0) G.add_edge('C', 'D', capacity=9.0) G.add_edge('D', 'B', capacity=6.0) G.add_edge('D', 'Z', capacity=10.0) before = datetime.datetime.now() R = edmonds_karp(G, 'S', 'Z') after = datetime.datetime.now() time = after - before print(time) flow_value = nx.maximum_flow_value(G, 'S', 'Z') flow_value 3.0 flow_value == R.graph['flow_value'] True print(flow_value)
def mincut_nx(edges: Iterable[Sequence[np.uint64]], affs: Sequence[np.uint64], sources: Sequence[np.uint64], sinks: Sequence[np.uint64], logger: Optional[logging.Logger] = None) -> np.ndarray: """ Computes the min cut on a local graph :param edges: n x 2 array of uint64s :param affs: float array of length n :param sources: uint64 :param sinks: uint64 :return: m x 2 array of uint64s edges that should be removed """ time_start = time.time() original_edges = edges.copy() edges, affs, mapping, remapping = merge_cross_chunk_edges( edges.copy(), affs.copy()) mapping_vec = np.vectorize(lambda a: mapping[a] if a in mapping else a) if len(edges) == 0: return [] if len(mapping) > 0: assert np.unique(list(mapping.keys()), return_counts=True)[1].max() == 1 remapped_sinks = mapping_vec(sinks) remapped_sources = mapping_vec(sources) sinks = remapped_sinks sources = remapped_sources sink_connections = np.array(list(itertools.product(sinks, sinks))) source_connections = np.array(list(itertools.product(sources, sources))) weighted_graph = nx.Graph() weighted_graph.add_edges_from(edges) weighted_graph.add_edges_from(sink_connections) weighted_graph.add_edges_from(source_connections) for i_edge, edge in enumerate(edges): weighted_graph[edge[0]][edge[1]]['capacity'] = affs[i_edge] weighted_graph[edge[1]][edge[0]]['capacity'] = affs[i_edge] # Add infinity edges for multicut for sink_i in sinks: for sink_j in sinks: weighted_graph[sink_i][sink_j]['capacity'] = float_max for source_i in sources: for source_j in sources: weighted_graph[source_i][source_j]['capacity'] = float_max dt = time.time() - time_start if logger is not None: logger.debug("Graph creation: %.2fms" % (dt * 1000)) time_start = time.time() ccs = list(nx.connected_components(weighted_graph)) for cc in ccs: cc_list = list(cc) # If connected component contains no sources and/or no sinks, # remove its nodes from the mincut computation if not np.any(np.in1d(sources, cc_list)) or \ not np.any(np.in1d(sinks, cc_list)): weighted_graph.remove_nodes_from(cc) r_flow = edmonds_karp(weighted_graph, sinks[0], sources[0]) cutset = minimum_st_edge_cut(weighted_graph, sources[0], sinks[0], residual=r_flow) # cutset = nx.minimum_edge_cut(weighted_graph, sources[0], sinks[0], flow_func=edmonds_karp) dt = time.time() - time_start if logger is not None: logger.debug("Mincut comp: %.2fms" % (dt * 1000)) if cutset is None: return [] time_start = time.time() edge_cut = list(list(cutset)) weighted_graph.remove_edges_from(edge_cut) ccs = list(nx.connected_components(weighted_graph)) # assert len(ccs) == 2 for cc in ccs: cc_list = list(cc) if logger is not None: logger.debug("CC size = %d" % len(cc_list)) if np.any(np.in1d(sources, cc_list)): assert np.all(np.in1d(sources, cc_list)) assert ~np.any(np.in1d(sinks, cc_list)) if np.any(np.in1d(sinks, cc_list)): assert np.all(np.in1d(sinks, cc_list)) assert ~np.any(np.in1d(sources, cc_list)) dt = time.time() - time_start if logger is not None: logger.debug("Splitting local graph: %.2fms" % (dt * 1000)) remapped_cutset = [] for cut in cutset: if cut[0] in remapping: pre_cut = remapping[cut[0]] else: pre_cut = [cut[0]] if cut[1] in remapping: post_cut = remapping[cut[1]] else: post_cut = [cut[1]] remapped_cutset.extend(list(itertools.product(pre_cut, post_cut))) remapped_cutset.extend(list(itertools.product(post_cut, pre_cut))) remapped_cutset = np.array(remapped_cutset, dtype=np.uint64) remapped_cutset_flattened_view = remapped_cutset.view(dtype='u8,u8') edges_flattened_view = original_edges.view(dtype='u8,u8') cutset_mask = np.in1d(remapped_cutset_flattened_view, edges_flattened_view) return remapped_cutset[cutset_mask]
# User7 U2P relations G.add_edge('U7','P1', capacity=3.0) G.add_edge('U7','P2', capacity=9.0) G.add_edge('U7','P3', capacity=2.0) G.add_edge('U7','P4', capacity=10.0) G.add_edge('U7','P5', capacity=4.0) G.add_edge('U7','P6', capacity=6.0) G.add_edge('U7','P7', capacity=8.0) # Project to Sink Edges G.add_edge('P1','t', capacity=10.0) G.add_edge('P2','t', capacity=10.0) G.add_edge('P3','t', capacity=10.0) G.add_edge('P4','t', capacity=10.0) G.add_edge('P5','t', capacity=10.0) G.add_edge('P6','t', capacity=10.0) G.add_edge('P7','t', capacity=10.0) #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) R = edmonds_karp(G, 's', 't') print (R.graph['flow_value']*10)/7, '%' nx.draw(R) plt.show()