Exemple #1
0
    def test_optional_capacity(self):
        # Test optional capacity parameter.
        G = nx.DiGraph()
        G.add_edge('x','a', spam = 3.0)
        G.add_edge('x','b', spam = 1.0)
        G.add_edge('a','c', spam = 3.0)
        G.add_edge('b','c', spam = 5.0)
        G.add_edge('b','d', spam = 4.0)
        G.add_edge('d','e', spam = 2.0)
        G.add_edge('c','y', spam = 2.0)
        G.add_edge('e','y', spam = 3.0)

        solnFlows = {'x': {'a': 2.0, 'b': 1.0},
                     'a': {'c': 2.0},
                     'b': {'c': 0, 'd': 1.0},
                     'c': {'y': 2.0},
                     'd': {'e': 1.0},
                     'e': {'y': 1.0},
                     'y': {}}
        solnValue = 3.0
        s = 'x'
        t = 'y'
        
        flowValue, flowDict = nx.ford_fulkerson(G, s, t, capacity = 'spam')
        assert_equal(flowValue, solnValue)
        assert_equal(flowDict, solnFlows)
        assert_equal(nx.min_cut(G, s, t, capacity = 'spam'), solnValue)
        assert_equal(nx.max_flow(G, s, t, capacity = 'spam'), solnValue)
        assert_equal(nx.ford_fulkerson_flow(G, s, t, capacity = 'spam'),
                     solnFlows)
Exemple #2
0
def compare_flows(G, s, t, solnFlows, solnValue):
    flowValue, flowDict = nx.ford_fulkerson(G, s, t)
    assert_equal(flowValue, solnValue)
    assert_equal(flowDict, solnFlows)
    assert_equal(nx.min_cut(G, s, t), solnValue)
    assert_equal(nx.max_flow(G, s, t), solnValue)
    assert_equal(nx.ford_fulkerson_flow(G, s, t), solnFlows)
def get_all_zero_edges(G, s, t, topological_dict):
    """
    Get all "zero-edges" from a graph: all the edges that if we remove them,
    the graph won't be connected anymore.
    """
    if nx.min_cut(G, s, t) != 1:
        return []
    auxiliary = nx.copy.deepcopy(G)
    zero_edges = nx.bidirectional_shortest_path(auxiliary, s, t)
    zero_edges = list(zip(zero_edges[:-1], zero_edges[1:]))

    kill_list = []
    for edge in zero_edges:

        auxiliary.remove_edge(edge[0], edge[1])

        try:
            nx.bidirectional_shortest_path(auxiliary, s, t)
            print edge
            kill_list.append(edge)
        except nx.NetworkXNoPath:
            pass
        auxiliary.add_edge(edge[0], edge[1])

    for edge in kill_list:
        zero_edges.remove(edge)
    zero_edges.sort(
        lambda x, y: cmp(topological_dict[x[0]], topological_dict[y[0]]))
    return zero_edges
Exemple #4
0
def compare_flows(G, s, t, solnFlows, solnValue):
    flowValue, flowDict = nx.ford_fulkerson(G, s, t)
    assert_equal(flowValue, solnValue)
    assert_equal(flowDict, solnFlows)
    assert_equal(nx.min_cut(G, s, t), solnValue)
    assert_equal(nx.max_flow(G, s, t), solnValue)
    assert_equal(nx.ford_fulkerson_flow(G, s, t), solnFlows)
Exemple #5
0
def get_all_zero_edges(G, s, t, topological_dict):
    """
    Get all "zero-edges" from a graph: all the edges that if we remove them,
    the graph won't be connected anymore.
    """
    if nx.min_cut(G, s, t) != 1:
        return []
    auxiliary = nx.copy.deepcopy(G)
    zero_edges = nx.bidirectional_shortest_path(auxiliary, s, t)
    zero_edges = list(zip(zero_edges[:-1], zero_edges[1:]))

    kill_list = []
    for edge in zero_edges:

        auxiliary.remove_edge(edge[0], edge[1])

        try:
            nx.bidirectional_shortest_path(auxiliary, s, t)
            print edge
            kill_list.append(edge)
        except nx.NetworkXNoPath:
            pass
        auxiliary.add_edge(edge[0], edge[1])

    for edge in kill_list:
        zero_edges.remove(edge)
    zero_edges.sort(lambda x, y: cmp(topological_dict[x[0]], topological_dict[y[0]]))
    return zero_edges
Exemple #6
0
def compare_flows(G, s, t, solnFlows, solnValue, capacity = 'capacity'):
    flowValue, flowDict = nx.ford_fulkerson(G, s, t, capacity)
    assert_equal(flowValue, solnValue)
    assert_equal(flowDict, solnFlows)
    flowValue, flowDict = nx.preflow_push(G, s, t, capacity)
    assert_equal(flowValue, solnValue)
    validate_flows(G, s, t, flowDict, solnValue, capacity)
    assert_equal(nx.min_cut(G, s, t, capacity), solnValue)
    assert_equal(nx.max_flow(G, s, t, capacity), solnValue)
    assert_equal(nx.ford_fulkerson_flow(G, s, t, capacity), solnFlows)
Exemple #7
0
    def global_mincut(self, G):
        "全域最小カット重みを求める"

        if isinstance(G, networkx.MultiGraph):
            G = self._simplify_multigraph(G)
        mincut = None
        nodes = G.nodes()
        s = nodes.pop()
        for t in nodes:
            tmp = networkx.min_cut(G, s, t, capacity="weight")
            if mincut == None or tmp < mincut:
                mincut = tmp
        return mincut
Exemple #8
0
    def test_optional_capacity(self):
        # Test optional capacity parameter.
        G = nx.DiGraph()
        G.add_edge('x', 'a', spam=3.0)
        G.add_edge('x', 'b', spam=1.0)
        G.add_edge('a', 'c', spam=3.0)
        G.add_edge('b', 'c', spam=5.0)
        G.add_edge('b', 'd', spam=4.0)
        G.add_edge('d', 'e', spam=2.0)
        G.add_edge('c', 'y', spam=2.0)
        G.add_edge('e', 'y', spam=3.0)

        solnFlows = {
            'x': {
                'a': 2.0,
                'b': 1.0
            },
            'a': {
                'c': 2.0
            },
            'b': {
                'c': 0,
                'd': 1.0
            },
            'c': {
                'y': 2.0
            },
            'd': {
                'e': 1.0
            },
            'e': {
                'y': 1.0
            },
            'y': {}
        }
        solnValue = 3.0
        s = 'x'
        t = 'y'

        flowValue, flowDict = nx.ford_fulkerson(G, s, t, capacity='spam')
        assert_equal(flowValue, solnValue)
        assert_equal(flowDict, solnFlows)
        assert_equal(nx.min_cut(G, s, t, capacity='spam'), solnValue)
        assert_equal(nx.max_flow(G, s, t, capacity='spam'), solnValue)
        assert_equal(nx.ford_fulkerson_flow(G, s, t, capacity='spam'),
                     solnFlows)
def compare_flows(G, s, t, solnFlows, solnValue, capacity = 'capacity'):
    flowValue, flowDict = nx.ford_fulkerson(G, s, t, capacity)
    assert_equal(flowValue, solnValue)
    assert_equal(flowDict, solnFlows)
    flowValue, flowDict = nx.preflow_push(G, s, t, capacity)
    assert_equal(flowValue, solnValue)
    validate_flows(G, s, t, flowDict, solnValue, capacity)
    flowValue, flowDict = nx.shortest_augmenting_path(G, s, t, capacity,
                                                      two_phase=False)
    assert_equal(flowValue, solnValue)
    validate_flows(G, s, t, flowDict, solnValue, capacity)
    flowValue, flowDict = nx.shortest_augmenting_path(G, s, t, capacity,
                                                      two_phase=True)
    assert_equal(flowValue, solnValue)
    validate_flows(G, s, t, flowDict, solnValue, capacity)
    assert_equal(nx.min_cut(G, s, t, capacity), solnValue)
    assert_equal(nx.max_flow(G, s, t, capacity), solnValue)
    assert_equal(nx.ford_fulkerson_flow(G, s, t, capacity), solnFlows)
Exemple #10
0
def min_cut(grid):
    G = nx.DiGraph()
    #node name:
    # x-y-(in|out)
    for x in range(w):
        for y in range(h):
            if not grid[x][y]:
                continue
            ad = adj(grid, x, y)
            for a in ad:
                G.add_edge(name(*a)+"-out", name(x,y)+"-in", capacity=1)
                G.add_edge(name(x,y)+"-in", name(x,y)+"-out", capacity=1)
                G.add_edge(name(x,y)+"-out", name(*a)+"-in", capacity=1)
    # supernodes
    for x in range(w):
        if grid[x][0]:
            G.add_edge("start", name(x,0)+"-in", capacity=1)
        if grid[x][h-1]:
            G.add_edge(name(x,h-1)+"-out", "end", capacity=1)
    if "start" not in G or "end" not in G:
        return 0
    return nx.min_cut(G, 'start', 'end')
Exemple #11
0
def compare_flows(G, s, t, solnFlows, solnValue, capacity='capacity'):
    flowValue, flowDict = nx.ford_fulkerson(G, s, t, capacity)
    assert_equal(flowValue, solnValue)
    assert_equal(flowDict, solnFlows)
    flowValue, flowDict = nx.preflow_push(G, s, t, capacity)
    assert_equal(flowValue, solnValue)
    validate_flows(G, s, t, flowDict, solnValue, capacity)
    flowValue, flowDict = nx.shortest_augmenting_path(G,
                                                      s,
                                                      t,
                                                      capacity,
                                                      two_phase=False)
    assert_equal(flowValue, solnValue)
    validate_flows(G, s, t, flowDict, solnValue, capacity)
    flowValue, flowDict = nx.shortest_augmenting_path(G,
                                                      s,
                                                      t,
                                                      capacity,
                                                      two_phase=True)
    assert_equal(flowValue, solnValue)
    validate_flows(G, s, t, flowDict, solnValue, capacity)
    assert_equal(nx.min_cut(G, s, t, capacity), solnValue)
    assert_equal(nx.max_flow(G, s, t, capacity), solnValue)
    assert_equal(nx.ford_fulkerson_flow(G, s, t, capacity), solnFlows)
Exemple #12
0
def compare_value_flows_highest_label(G, s, t, solnValue, capacity='capacity'):
    flowValue, flowDict = nx.highest_label_maxflow(G, s, t, capacity)
    nst.assert_equal(flowValue, solnValue)
    nst.assert_equal(nx.min_cut(G, s, t, capacity), solnValue)
    nst.assert_equal(nx.max_flow(G, s, t, capacity), solnValue)
Exemple #13
0
def compare_value_flows_relabel_to_front(G, s, t, solnValue, capacity='capacity'):
    flowValue, flowDict = nx.relabel_to_front_maxflow(G, s, t, capacity)
    nst.assert_equal(flowValue, solnValue)
    nst.assert_equal(nx.min_cut(G, s, t, capacity), solnValue)
    nst.assert_equal(nx.max_flow(G, s, t, capacity), solnValue)
Exemple #14
0
def compare_value_flows_vanilla_push_relabel(G, s, t, solnValue, capacity='capacity'):
    flowValue, flowDict = nx.vanilla_push_relabel_maxflow(G, s, t, capacity)
    nst.assert_equal(flowValue, solnValue)
    nst.assert_equal(nx.min_cut(G, s, t, capacity), solnValue)
    nst.assert_equal(nx.max_flow(G, s, t, capacity), solnValue)
   # neighbours[2].remove(3)
   # neighbours[3].remove(2)
   # neighbours[4].remove(5)
   # neighbours[5].remove(4)
   # neighbours[3].remove(1)
   # neighbours[1].remove(3)

    #neighbours[0].remove(2)
    #neighbours[2].remove(0)
    #neighbours[0].remove(3)
    #neighbours[3].remove(0)
    clique = eval(sys.argv[2]) #[(0, 3), (0, 4), (0, 5), (1, 2), (1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)] 
    G = nx.Graph()
    G.add_nodes_from(xrange(0, size))
    G.add_edges_from(clique, capacity = 1.0)
    mincut = min(map(lambda x: nx.min_cut(G, x[0], x[1]), itertools.combinations(xrange(0, size), 2)))
    print mincut
    global_order = {(x + 1): (((x+1) % (size - 1)) + 1) for x in xrange(0, size - 1)}
    routing_table = {x: GenerateTable(x, global_order, size) for x in xrange(1, size)}
    tested = 0
    passed = 0
    for perm in itertools.permutations(xrange(1, size)):
        perm_l = list(perm)
        xlate = {x: perm[x - 1] for x in  xrange(1, size)}
        xlate[0] = 0
        ret = CheckTables([routing_table], size, clique, G, mincut - 1, len(clique) - 2, xlate)
        tested = tested + 1
        if ret >= mincut - 1:
            passed = passed + 1
            print str.format("{0} {1}", ret, [xlate[a] for a in xrange(0, size)])
        else:
Exemple #16
0
 nx.set_edge_attributes(G, 'capacity', {k : 1.0 for k in G.edges_iter()})
 umoded_graph = nx.Graph.copy(G)
 try:
   source = nx.periphery(G)[0]
 except:
   continue
 diameter = nx.diameter(G)
 distances = nx.single_source_dijkstra(G, source)
 target = max(distances[1], key=lambda k:distances[0][k])
 nbrs = G.neighbors(source)
 G.graph['source'] = source
 G.graph['dest'] = target
 G.node[source]['source'] = True
 G.node[target]['target'] = True
 paths = []
 mincut = min(map(lambda x: nx.min_cut(G, x[0], x[1]), combinations(xrange(0, nodes), 2)))
 for ordering in permutations(nbrs):
   G = nx.Graph.copy(umoded_graph)
   del paths[:]
   for order in ordering:
     if not nx.has_path(G, order, target):
       break
     else:
       path = nx.dijkstra_path(G, order, target)
       paths.append(path)
       edges = [(path[i], path[i + 1]) for i in xrange(0, len(path) - 1)]
       G.remove_edges_from(edges)
   if len(paths) >= mincut:
     break
 if len(paths) < mincut:
   print str.format("Min-cut = {0}", mincut)
Exemple #17
0

import networkx as nx
import sys

def graph_from_dimacs(filename):
    f = open(filename)
    g = nx.Graph()
    for line in f:
        if line[0] == 'a':
            parsed = line.split()
            a = int(parsed[1])
            b = int(parsed[2])
            c = int(parsed[3])
            g.add_edge(a,b,capacity=c)
    f.close()
    return g

for arg in sys.argv:
    if arg[-4:] == ".txt":
        g = graph_from_dimacs(arg)
        print nx.min_cut(g, 1, len(g.nodes()))

n_trials = int(sys.argv[1])
n = int(sys.argv[2])
m = int(sys.argv[3])
max_cap = float(sys.argv[4])
min_cap = float(sys.argv[5])
epsilon = float(sys.argv[6])
g = networkx.Graph()
all_edges = [(i, j) for i in range(n) for j in range(i+1,n)]
random.shuffle(all_edges)
g.add_edges_from(all_edges[:m])
for e in g.edges():
  cap = random.random() * (max_cap - min_cap) + min_cap
  graph_util.set_edge_capacity(g, e, cap)

min_cut_actual = networkx.min_cut(g, 0, 1, capacity='capacity')

total_elapsed = 0
for i in range(n_trials):
  print 'trial: %d' % i
  t_start = time.clock()
  if max_cap == min_cap:
    sparse_g = sparsification.sparsify(g, epsilon)
  else:
    sparse_g = sparsification.weighted_sparsify(g, epsilon)
  elapsed_time = time.clock() - t_start
  total_elapsed += elapsed_time
  min_cut_sparsed = networkx.min_cut(sparse_g, 0, 1, capacity='capacity')
  error = abs(min_cut_sparsed - min_cut_actual) / abs(min_cut_actual)
  print '|E sparse| / |E|: %f' % (sparse_g.number_of_edges() / g.number_of_edges())
  print 'relative error: %f' % error
Exemple #19
0
import networkx as nx
import sys


def graph_from_dimacs(filename):
    f = open(filename)
    g = nx.Graph()
    for line in f:
        if line[0] == 'a':
            parsed = line.split()
            a = int(parsed[1])
            b = int(parsed[2])
            c = int(parsed[3])
            g.add_edge(a, b, capacity=c)
    f.close()
    return g


for arg in sys.argv:
    if arg[-4:] == ".txt":
        g = graph_from_dimacs(arg)
        print nx.min_cut(g, 1, len(g.nodes()))
Exemple #20
0
            if cnt == 0:
                cnt = 1
            else:
                DG.add_edge(int(j), int(k), capacity=1.0)
        del edges_[:]
    #print DG.edges()
    #print DG.neighbors(1)
    #let's delete all nodes with indegree 1 and outdegree 0 or indegree 0 and outdegree 1
#    for n_ in DG.nodes():
#        if (DG.in_degree(n_) == 1 and DG.out_degree(n_) == 0) or (DG.in_degree(n_) == 0 and DG.out_degree(n_) == 1):
#            DG.remove_node(n_)
    success = False
    for n_1 in DG.nodes():
        for n_2 in DG.nodes():
            if n_1 != n_2:
                min_c = nx.min_cut(DG, n_1, n_2)
                if min_c >= 2:
                    success = True
                    break
        if success == True:
            break
    #if i == 5:
    #nx.draw_spring(DG,node_color=[float(DG.degree(v)) for v in DG],node_size=10,with_labels=True,cmap=plt.cm.Reds,)
    #plt.show()
    #success = False
#    try:
#        top_sort = nx.topological_sort(DG)
#        #if i == 5:
#        #    print top_sort
#        for z in top_sort:
#            if DG.out_degree(z) == 2:
Exemple #21
0
    def st_mincut(self, G, s, t):
        "s-t最小カットを求める"

        if isinstance(G, networkx.MultiGraph):
            G = self._simplify_multigraph(G)
        return networkx.min_cut(G, s, t, capacity="weight")