Exemplo n.º 1
0
def run_simple_iteration(G, ground_motion, demand, multi):
  #G is a graph, demand is a dictionary keyed by source and target of demand per weekday. multi is a boolean that is true if it is a multigraph (can have two parallel edges between nodes)
  #change edge properties
  newG, capacities = damage_network(G, ground_motion, multi) #also returns the number of bridges out
  num_out = sum(x < 100 for x in capacities)
#  util.write_list(time.strftime("%Y%m%d")+'_bridges_scen_1.txt', capacities)   
  #get max flow
  start = time.time()
  #node 5753 is in superdistrict 12, which is santa clara county, and node 3144 is in superdistrict 18, which is alameda county. roughly these are san jose and oakland
  #node 7619 is in superdistrict 1 (7493 is also), which is sf, and node node 3144 is in superdistrict 18, which is alameda county. roughly these are san francisco and oakland
  s = '5753'
  t = '7493' #2702 
  flow = nx.max_flow(newG, s, t, capacity='capacity') #not supported by multigraph
  print 'time to get max flow: ', time.time() - start
#  flow = -1 
  #get ave. shortest path
#  start = time.time()
  sp_dict = nx.single_source_dijkstra_path_length(newG,'7619',weight='distance')
  sp = sum(sp_dict.values())/float(len(sp_dict.values()))
  sp2 = 0
  for target in demand.keys():
    sp2 += sp_dict[target]
  sp2 = sp2 / float(len(demand.keys()))
#  print 'time to get shortest path: ', time.time() - start
  newG = util.clean_up_graph(newG, multi)
  return (num_out, flow, sp, sp2) 
Exemplo n.º 2
0
def solve():
	from networkx import Graph, max_flow
	W, H, B = map(int,input().split())
	R = [[True for _ in range(H)] for _ in range(W)]
	
	for _ in range(B):
		x0, y0, x1, y1 = map(int,input().split())
		for x in range(x0,x1+1):
			for y in range(y0,y1+1):
				R[x][y] = False
	
	G = Graph()
	
	for x in range(W):
		for y in range(H):
			if R[x][y]:
				G.add_edge(('start',x,y),('end',x,y),capacity=1)
			
				if y == 0:
					G.add_edge('source',('start',x,y))
				else:
					if R[x][y-1]:
						#G.add_edge(('end',x,y),('start',x,y-1))
						pass
				
				if y == H-1:
					G.add_edge(('end',x,y),'sink')
				else:
					if R[x][y+1]:
						G.add_edge(('end',x,y),('start',x,y+1))
	
	return max_flow(G,'source','sink','capacity')
Exemplo n.º 3
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)
Exemplo n.º 4
0
 def test_disconnected(self):
     G = nx.Graph()
     G.add_weighted_edges_from([(0,1,1),(1,2,1),(2,3,1)],weight='capacity')
     G.remove_node(1)
     assert_equal(nx.max_flow(G,0,3),0)
     flowSoln = {0: {}, 2: {3: 0}, 3: {2: 0}}
     compare_flows(G, 0, 3, flowSoln, 0)
Exemplo n.º 5
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)
Exemplo n.º 6
0
Arquivo: 6.py Projeto: qifanyyy/CLCDSA
def solve(W, H, Bseq):
    mp = [[False] * H for _ in range(W)]

    for x0, y0, x1, y1 in Bseq:
        for x in range(x0, x1 + 1):
            for y in range(y0, y1 + 1):
                mp[x][y] = True

    G = networkx.DiGraph()

    def neigh(x, y):
        for ox, oy in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
            nx = ox + x
            ny = oy + y
            if 0 <= nx < W and 0 <= ny < H:
                yield nx, ny

    for x in range(W):
        for y in range(H):
            if not mp[x][y]:
                G.add_edge(hash(('in', x, y)), hash(('out', x, y)), capacity=1)
                for nx, ny in neigh(x, y):
                    if not mp[nx][ny]:
                        G.add_edge(hash(('out', x, y)),
                                   hash(('in', nx, ny)),
                                   capacity=1000000)

    for x in range(W):
        G.add_edge(hash('src'), hash(('in', x, 0)), capacity=1)
    for x in range(W):
        G.add_edge(hash(('out', x, H - 1)), hash('snk'), capacity=1000000)

    flow = networkx.max_flow(G, hash('src'), hash('snk'))
    return int(flow)
Exemplo n.º 7
0
def runPhysicalTest():
    interfModelType = 'simple-physical'
    gridSize = 3
    source = 0
    dest = gridSize * gridSize - 1
    G = wnj_interference.createConnectivityGraph(gridSize, interfModelType)
    wiredNetworkFlow = nx.max_flow(G, source, dest)
    print "wiredNetworkFlow:", wiredNetworkFlow
    
    ConflictGraph = wnj_interference.createConflictGraph(G, interfModelType)
    #print ConflictGraph.edges(data=True)
    
    ISets = []
    capacityDuals = dict([(edge, 1.0) for edge in G.edges()])
    count = 0
    maxWeight, selected = wnj_interference.maxWtIndepSet(ConflictGraph, capacityDuals, interfModelType)
    ISets.append(selected)
    #print "selected ", selected
    interdictionFeasibleRegion = [(i+0.5, j+0.5) for i in range(gridSize - 1) for j in range(gridSize - 1)]
    interdictionVars = dict([(tuple, 1.0) for tuple in interdictionFeasibleRegion])
    wnj_interference.createThroughputModel(G, source, dest, [selected], interdictionVars)
    while True:
        print "ITERATION", count
        maxWeight, selected = wnj_interference.maxWtIndepSet(ConflictGraph, capacityDuals, interfModelType)
        ISets.append(selected)
        print "selected ", selected
        throughput, capacityDuals, jammingDuals, usageDual = wnj_interference.addISetAsCol_AndSolveTHProb(G, interdictionVars, ISets, selected, count)
        if((maxWeight - (usageDual + sum([jammingDuals[key] for key in jammingDuals.keys()]))) <= 0.0001):
            break
        count += 1
Exemplo n.º 8
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)
Exemplo n.º 9
0
 def test_disconnected(self):
     G = nx.Graph()
     G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)],
                               weight='capacity')
     G.remove_node(1)
     assert_equal(nx.max_flow(G, 0, 3), 0)
     flowSoln = {0: {}, 2: {3: 0}, 3: {2: 0}}
     compare_flows(G, 0, 3, flowSoln, 0)
 def calc_relatedness(self, first_entity, second_entity):
     """ Returns the relatedness of the two entities. Relatedness is a value that corresponds to how semantically connected two words are. Note that this is not necessarily a measure of how similar two words are to each other in meaning. To illustrate the distinction between these two ideas, consider that "cat" and "mouse", depending on the dataset, might be as related as "mouse" and "rat", even though "mouse" and "rat" are much more similar to each other than "cat" and "mouse" are.
     Relatedness is calculated by first constructing what is deemed a "decaying subgraph" centered on the two words. This is constructed starting with a graph that is comprised of only the two words. Then, all of the edges connected to those two words are added to the graph. The strength of those connections is equal to the strength of those connections in the Semantic_Network. Then, all of the neightboring edges to the neighbors of the initial words are added, but this time, each connection has only half of the strength it does in the greater Semantic_Network. This is repeated to contain edges 3 steps away from the two central words. Each level out from the central words, the strength of the connections in the decaying subgraph are halved again, thus, the connections at the third level away from the central words have 25% of the strength that they do in the greater Semantic_Network.
     Once this decaying subgraph is constructed, the max flow between the two words, using strengths of connections as path capacitites, is calculated between the two words. The max flow is returned as the relatedness of the two entities.
     """
     subgraph = get_decaying_subgraph(self.graph,
                                      [first_entity, second_entity])
     return nx.max_flow(subgraph, first_entity, second_entity)
Exemplo n.º 11
0
def calculate_z(G, commodities):
    '''
    Calculates Z = min(z_i/d_i) where z_i is the max flow of commodity i
    and d_i is the demand for commodity i
    '''
    zList = []
    for commodity in commodities:
        zList.append(nx.max_flow(G, commodity.source, commodity.sink) / float(commodity.demand))
    return min(zList)
Exemplo n.º 12
0
    def calc_relatedness(self, first_entity, second_entity):
        """ Returns the relatedness of the two entities. Relatedness is a value that corresponds to how semantically connected two words are. Note that this is not necessarily a measure of how similar two words are to each other in meaning. To illustrate the distinction between these two ideas, consider that "cat" and "mouse", depending on the dataset, might be as related as "mouse" and "rat", even though "mouse" and "rat" are much more similar to each other than "cat" and "mouse" are.

        Relatedness is calculated by first constructing what is deemed a "decaying subgraph" centered on the two words. This is constructed starting with a graph that is comprised of only the two words. Then, all of the edges connected to those two words are added to the graph. The strength of those connections is equal to the strength of those connections in the Semantic_Network. Then, all of the neightboring edges to the neighbors of the initial words are added, but this time, each connection has only half of the strength it does in the greater Semantic_Network. This is repeated to contain edges 3 steps away from the two central words. Each level out from the central words, the strength of the connections in the decaying subgraph are halved again, thus, the connections at the third level away from the central words have 25% of the strength that they do in the greater Semantic_Network.

        Once this decaying subgraph is constructed, the max flow between the two words, using strengths of connections as path capacitites, is calculated between the two words. The max flow is returned as the relatedness of the two entities. 
        """
        subgraph = get_decaying_subgraph(self.graph, 
                                        [first_entity, second_entity])
        return nx.max_flow(subgraph, first_entity, second_entity)
Exemplo n.º 13
0
 def max_flow(self):
     if self.recipient.alias not in self.graph.nodes() or self.payer.alias not in self.graph.nodes():
         return 0
     try:
         amount = nx.max_flow(
             unmulti(self.graph), self.payer.alias, self.recipient.alias)
     except nx.NetworkXUnbounded:
         return D('Infinity')
     else:
         return unscale_flow_amount(amount)
Exemplo n.º 14
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)
Exemplo n.º 15
0
def compute_flow(damaged_graph):
	'''compute max flow between a start and end'''
	s=  'sf' #another option is '1000001'
	t = 'oak' #other options are '1000002' and 'sfo'
	try:
		flow = networkx.max_flow(damaged_graph, s, t, capacity='capacity') #not supported by multigraph
	except networkx.exception.NetworkXError as e:
		print 'found an ERROR: ', e
		pdb.set_trace()
	return flow
Exemplo n.º 16
0
 def max_flow(self):
     if (self.recipient.alias not in self.graph.nodes() or
         self.payer.alias not in self.graph.nodes()):
         return 0
     try:
         amount = nx.max_flow(
             unmulti(self.graph), self.payer.alias, self.recipient.alias)
     except nx.NetworkXUnbounded:
         return D('Infinity')
     else:
         return unscale_flow_amount(amount)
Exemplo n.º 17
0
def main(rounds=80):
    sys.setrecursionlimit(100000)

    a = sources.digital_source_int_circuit(0x67452301, 32)
    b = sources.digital_source_int_circuit(0xEFCDAB89, 32)
    c = sources.digital_source_int_circuit(0x98BADCFE, 32)
    d = sources.digital_source_int_circuit(0x10325476, 32)
    e = sources.digital_source_int_circuit(0xC3D2E1F0, 32)

    message_circuit = sources.digital_source_int_circuit(random.getrandbits(512), 512)

    h0, h1, h2, h3, h4 = builder.block_operation(message_circuit, a, b, c, d, e, rounds)

    # Concatenate results
    h01 = circuit.stack_circuits('h01', h0, h1)
    h012 = circuit.stack_circuits('h012', h01, h2)
    h0123 = circuit.stack_circuits('h0123', h012, h3)

    h = circuit.stack_circuits('H', h0123, h4)

    g = to_graph(message_circuit._outputs)

    # All gates/nodes that input hooks into
    # a = set()
    # for gate in message_circuit._outputs:
    #     a |= set(g.neighbors(gate))
    #     g.remove_node(gate)
    #
    # g.add_node('source')
    # for gate in a:
    #     g.add_edge('source', gate)
    #
    # g.add_node('sink')
    # for gate in h._outputs:
    #     g.add_edge(gate, 'sink')

    g.add_node('source')
    for gate in message_circuit._outputs:
        g.add_edge('source', gate, capacity=1)

    g.add_node('sink')
    for gate in h._outputs:
        g.add_edge(gate, 'sink', capacity=1)

    print '\n'
    print '---- Min-Cut on Reduced Rounds %d Rounds ----' % rounds
    print 'Number of nodes in circuit graph: %d' % len(g.nodes())
    print 'Number of edges in circuit graph: %d' % len(g.edges())
    print 'Total number of instantiated components: %d' % ComponentBase.count

    mc = nx.max_flow(g, 'source', 'sink')

    print 'Min-cut size: %d' % mc
def solve():
    source = input()
    Sspeed, Dspeed = get_ints()
    Icount, Rcount = get_ints()
    G = nx.DiGraph()
    for _ in range(Rcount):
        from_node, to_node, type, lanes = get_strs()
        # don't need roads arriving source or leaving target
        if to_node != source and from_node != target:
            total_speed = int(lanes) * (Sspeed if type == "normal" else Dspeed)
            vfrom = 0 if from_node == source else int(from_node)+1
            vto = Rcount+1 if to_node == target else int(to_node)+1
            G.add_edge(vfrom, vto, capacity=total_speed)
    max_flow = nx.max_flow(G, 0, Rcount+1)
    return "{} {}".format(source, max_flow * CARS)
Exemplo n.º 19
0
def compute_flow(damaged_graph):

  s= 'sf'
  t = 'oak'
  try:
    flow = nx.max_flow(damaged_graph, s, t, capacity='capacity') #not supported by multigraph
  except nx.exception.NetworkXError as e:
    print 'found an ERROR: ', e
    flow = -1
    print s in damaged_graph
    print t in damaged_graph
    print len(damaged_graph.nodes())
    print len(damaged_graph.edges())
    pdb.set_trace()
  return flow
Exemplo n.º 20
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)
Exemplo n.º 21
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)
Exemplo n.º 22
0
def find_number_of_cars_in_hour(city, roads):
	# Directed graph, roads are unidirectional
	g = nx.DiGraph()
	# Each road is represented by the start point, the end point and the
	# number of cars that can go through it in an hour
	for from_road, to_road, capacity in roads:
		# In case there is more than one road joining the same two points,
		# the total capacity of that section is the sum of each individual
		# road.
		# And, as the graph overwrites the old data of an edge when
		# the same one is added, capacity must be summed before adding it
		if g.has_edge(from_road, to_road):
			capacity += g[from_road][to_road]['capacity']
		# Add edge with the capacity as an attribute, used later when
		# calculating the max flow
		g.add_edge(from_road, to_road, capacity=capacity)
	# Obtain the maximum flow of the graph from the city to AwesomeCity, using
	# the capacity attribute as the capacity of the edge
	return nx.max_flow(g, city, AWESOMEVILLE)
Exemplo n.º 23
0
def runPhysicalWithJamming_Test():
    global interfModelType, g_ConflictGraph
    interfModelType = 'simple-physical'
    gridSize = 3
    source = 0
    dest = gridSize * gridSize - 1
    G = wnj_interference.createConnectivityGraph(gridSize, interfModelType, 'grid')
    print G.edges(data=True)
    wiredNetworkFlow = nx.max_flow(G, source, dest)
    print "wiredNetworkFlow:", wiredNetworkFlow
    
    g_ConflictGraph = wnj_interference.createConflictGraph(G, interfModelType)
    
    JammingGraph = wnj_interference.createPotentialJammingLocations(gridSize)
    jammingSolution = [0] * (gridSize*2)**2
    #jammingSolution[18] = 1
    print "jammingSolution", jammingSolution
    
    counter = 0
    for node in JammingGraph.nodes():
        JammingGraph.node[node]['selected'] = jammingSolution[counter]
        counter += 1
    print "jammed", [node for node in JammingGraph.nodes() if JammingGraph.node[node]['selected'] > 0.0]
    ISets = []
    capacityDuals = dict([(edge, 1.0) for edge in G.edges()])
    jammingDuals = dict([(node, 1.0) for node in JammingGraph.nodes()])
    count = 0
    maxWeight, selected = wnj_interference.maxWtIndepSet(g_ConflictGraph, capacityDuals, interfModelType)
    ISets.append(selected)
    wnj_interference.createThroughputModel(G, source, dest, [selected], JammingGraph, interfModelType)
    while True:
        print "ITERATION", count
        nodeWeights = wnj_interference.getWeightsForMaxIndSet(G, JammingGraph, capacityDuals, jammingDuals, interfModelType)
        print "node weights", nodeWeights
        maxWeight, selected = wnj_interference.maxWtIndepSet(g_ConflictGraph, nodeWeights, interfModelType)
        ISets.append(selected)
        throughput, capacityDuals, jammingDuals, usageDual = wnj_interference.addISetAsCol_AndSolveTHProb(G, JammingGraph, ISets, selected, count, interfModelType)
        print "selected ", selected
        if((maxWeight - usageDual) <= 0.0001):
            break
        count += 1
Exemplo n.º 24
0
def run_simple_iteration(G, ground_motion, demand, multi, j, targets, clean_up = True):
  #G is a graph (not a multigraph!), demand is a dictionary keyed by source and target of demand per weekday. multi is a boolean that is true if it is a multigraph (can have two parallel edges between nodes)
  #change edge properties
  newG, capacities = damage_network(G, ground_motion, multi) #also returns the number of bridges out
  num_out = sum(x < 100 for x in capacities)
  update_bridge_damage_dataset(capacities)
  if j in targets:
    affected_bridges = []
    for i in range(len(capacities)):
      if capacities[i] < 100:
        if (i+1) not in SPECIALLY_RETROFITTED_BRIDGES:
          affected_bridges.append(str(i+1))
    util.write_list('20130902_modifyingCapacity/' + time.strftime("%Y%m%d")+'_modifyingCapacitytab' + str(j) + '.txt', affected_bridges) 
  #get max flow
  start = time.time()
  #node 5753 is in superdistrict 12, which is santa clara county, and node 3144 is in superdistrict 18, which is alameda county. roughly these are san jose and oakland
  #node 7619 is in superdistrict 1 (7493 is also), which is sf, and node node 3144 is in superdistrict 18, which is alameda county. roughly these are san francisco and oakland
  s = '3144'
  t = '7493' #2702 
  try:
    flow = nx.max_flow(newG, s, t, capacity='capacity') #not supported by multigraph
  except nx.exception.NetworkXError as e:
    print 'found an ERROR: ', e
    flow = -1
    print s in newG
    print t in newG
    print len(newG.nodes())
    print len(newG.edges())
  # sp_dict = nx.single_source_dijkstra_path_length(newG,'7493',weight='distance')
  # sp = sum(sp_dict.values())/float(len(sp_dict.values()))
  # sp2 = 0
  # for target in demand.keys():
  #   sp2 += sp_dict[target]
  # sp2 = sp2 / float(len(demand.keys()))
  sp = 0
  sp2 = 0
  if clean_up == True:
    damagedG= util.clean_up_graph(newG)
  return (num_out, flow, sp, sp2, newG) 
Exemplo n.º 25
0
    def _flowProblem(self):
        """Create and run the network for the feasibility flow problem"""
        D = nx.DiGraph()
        
        #nodes are rows/columns, edges are row->column,
        #B defines edge capacities
        D.add_nodes_from(range(self.m+self.n))
        for ii in range(self.m):
            for jj in range(self.n):
                if self.B[ii][jj]>0:
                    D.add_edge(ii,self.m+jj,capacity=self.B[ii][jj])
                    
        #source and sink nodes, row/column sums define capacities on the
        # source/sink edges
        D.add_node('s')
        D.add_node('t')
        for ii in range(self.m):
            D.add_edge('s',ii,capacity=self.r[ii])
        for jj in range(self.n):
            D.add_edge(jj+self.m,'t',capacity=self.c[jj])

        return nx.max_flow(D,'s','t',capacity='capacity')
Exemplo n.º 26
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)
Exemplo n.º 27
0
def local_edge_connectivity(G, u, v, aux_digraph=None):
    r"""Returns local edge connectivity for nodes s and t in G.

    Local edge connectivity for two nodes s and t is the minimum number
    of edges that must be removed to disconnect them.

    This is a flow based implementation of edge connectivity. We compute the
    maximum flow on an auxiliary digraph build from the original
    network (see below for details). This is equal to the local edge
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .

    Parameters
    ----------
    G : NetworkX graph
        Undirected or directed graph

    s : node
        Source node

    t : node
        Target node

    aux_digraph : NetworkX DiGraph (default=None)
        Auxiliary digraph to compute flow based edge connectivity. If None
        the auxiliary digraph is build.

    Returns
    -------
    K : integer
        local edge connectivity for nodes s and t

    Examples
    --------
    >>> # Platonic icosahedral graph has edge connectivity 5
    >>> # for each non adjacent node pair
    >>> G = nx.icosahedral_graph()
    >>> nx.local_edge_connectivity(G,0,6)
    5

    Notes
    -----
    This is a flow based implementation of edge connectivity. We compute the
    maximum flow using the Ford and Fulkerson algorithm on an auxiliary digraph
    build from the original graph:

    If the input graph is undirected, we replace each edge (u,v) with
    two reciprocal arcs `(u,v)` and `(v,u)` and then we set the attribute
    'capacity' for each arc to 1. If the input graph is directed we simply
    add the 'capacity' attribute. This is an implementation of algorithm 1
    in [1]_.

    The maximum flow in the auxiliary network is equal to the local edge
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem).

    See also
    --------
    local_node_connectivity
    node_connectivity
    edge_connectivity
    max_flow
    ford_fulkerson

    References
    ----------
    .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
        http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
    """
    if aux_digraph is None:
        H = _aux_digraph_edge_connectivity(G)
    else:
        H = aux_digraph
    return nx.max_flow(H, u, v)
Exemplo n.º 28
0
def local_node_connectivity(G, s, t, aux_digraph=None, mapping=None):
    r"""Computes local node connectivity for nodes s and t.

    Local node connectivity for two non adjacent nodes s and t is the
    minimum number of nodes that must be removed (along with their incident
    edges) to disconnect them.

    This is a flow based implementation of node connectivity. We compute the
    maximum flow on an auxiliary digraph build from the original input
    graph (see below for details). This is equal to the local node
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    s : node
        Source node

    t : node
        Target node

    aux_digraph : NetworkX DiGraph (default=None)
        Auxiliary digraph to compute flow based node connectivity. If None
        the auxiliary digraph is build.

    mapping : dict (default=None)
        Dictionary with a mapping of node names in G and in the auxiliary digraph.

    Returns
    -------
    K : integer
        local node connectivity for nodes s and t

    Examples
    --------
    >>> # Platonic icosahedral graph has node connectivity 5
    >>> # for each non adjacent node pair
    >>> G = nx.icosahedral_graph()
    >>> nx.local_node_connectivity(G,0,6)
    5

    Notes
    -----
    This is a flow based implementation of node connectivity. We compute the
    maximum flow using the Ford and Fulkerson algorithm on an auxiliary digraph
    build from the original input graph:

    For an undirected graph G having `n` nodes and `m` edges we derive a
    directed graph D with 2n nodes and 2m+n arcs by replacing each
    original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
    arc in `D`. Then for each edge (`u`, `v`) in G we add two arcs
    (`u_B`, `v_A`) and (`v_B`, `u_A`) in `D`. Finally we set the attribute
    capacity = 1 for each arc in `D` [1]_ .

    For a directed graph G having `n` nodes and `m` arcs we derive a
    directed graph `D` with `2n` nodes and `m+n` arcs by replacing each
    original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
    arc `(v_A, v_B)` in D. Then for each arc `(u,v)` in G we add one arc
    `(u_B,v_A)` in `D`. Finally we set the attribute capacity = 1 for
    each arc in `D`.

    This is equal to the local node connectivity because the value of
    a maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford
    and Fulkerson theorem).

    See also
    --------
    node_connectivity
    all_pairs_node_connectivity_matrix
    local_edge_connectivity
    edge_connectivity
    max_flow
    ford_fulkerson

    References
    ----------
    .. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and
        Erlebach, 'Network Analysis: Methodological Foundations', Lecture
        Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
        http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
    """
    if aux_digraph is None or mapping is None:
        H, mapping = _aux_digraph_node_connectivity(G)
    else:
        H = aux_digraph
    return nx.max_flow(H, "%sB" % mapping[s], "%sA" % mapping[t])
Exemplo n.º 29
0
            cj_out = str(cj) + 'out'
            
            if (d_ci[0] - d_cj[0])**2 + (d_ci[1]- d_cj[1])**2 <= (d_ci[2]+d_cj[2])**2:
                g.add_edge(ci_out, cj_in, capacity=1  )
                g.add_edge(cj_out, ci_in, capacity=1  )
            


N= int( raw_input() ) 

for _ in range(N):
    w, h , nc = raw_input().split()
    w = int(w)
    h = int(h)
    nc= int(nc)
    g = nx.DiGraph()
    g.add_node('s')
    g.add_node('t')
    detec_list = []
    for _ in range(nc):
        x, y , r =  raw_input().split()
        x = int(x)
        y = int(y)
        r = int(r)
        detec_list.append( (x,y,r) )

    build_graph(g, detec_list, w)
    print  nx.max_flow(g, 's', 't')

        
Exemplo n.º 30
0
            if residual[u][v][capacity] == 0:
                residual.remove_edge(u, v)
                residual.remove_edge(v, u)
            u = v

    return total_flow, residual


def minCut(G, s, t, capacity="weight"):

    (cut_cap, residual) = FordFulkerson(G, s, t, capacity)
    [S, S_comp] = nx.connected_components(residual.to_undirected())

    return S, S_comp


if __name__ == "__main__":
    G = nx.Graph()

    G.add_edge("s", "a", weight=2)
    G.add_edge("s", "b", weight=1)
    G.add_edge("a", "b", weight=2)
    G.add_edge("a", "t", weight=1)
    G.add_edge("b", "t", weight=3)
    G.add_edge("b", "c", weight=6)
    G.add_edge("s", "c", weight=2)

    print "NX:", nx.max_flow(G, "s", "t", capacity="weight")
    print "Max flow:", FordFulkerson(G, "s", "t")[0]
    print "Min cut:", minCut(G, "s", "t")
Exemplo n.º 31
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)
Exemplo n.º 32
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)
Exemplo n.º 33
0
 def test_disconnected(self):
     G = nx.Graph()
     G.add_weighted_edges_from([(0,1,1),(1,2,1),(2,3,1)],weight='capacity')
     G.remove_node(1)
     assert_equal(nx.max_flow(G,0,3),0)
Exemplo n.º 34
0
 def maximum_flow_value(g, x, y):
     return nx.max_flow(g, x, y)
Exemplo n.º 35
0
def max_flow_min_cost(G, s, t, capacity = 'capacity', weight = 'weight'):
    """Return a maximum (s, t)-flow of minimum cost.
    
    G is a digraph with edge costs and capacities. There is a source
    node s and a sink node t. This function finds a maximum flow from
    s to t whose total cost is minimized.

    Parameters
    ----------
    G : NetworkX graph
        DiGraph on which a minimum cost flow satisfying all demands is
        to be found.

    s: node label
        Source of the flow.

    t: node label
        Destination of the flow.

    capacity: string
        Edges of the graph G are expected to have an attribute capacity
        that indicates how much flow the edge can support. If this
        attribute is not present, the edge is considered to have
        infinite capacity. Default value: 'capacity'.

    weight: string
        Edges of the graph G are expected to have an attribute weight
        that indicates the cost incurred by sending one unit of flow on
        that edge. If not present, the weight is considered to be 0.
        Default value: 'weight'.

    Returns
    -------
    flowDict: dictionary
        Dictionary of dictionaries keyed by nodes such that
        flowDict[u][v] is the flow edge (u, v).

    Raises
    ------
    NetworkXError
        This exception is raised if the input graph is not directed or
        not connected.

    NetworkXUnbounded
        This exception is raised if there is an infinite capacity path
        from s to t in G. In this case there is no maximum flow. This
        exception is also raised if the digraph G has a cycle of
        negative cost and infinite capacity. Then, the cost of a flow
        is unbounded below.

    See also
    --------
    cost_of_flow, ford_fulkerson, min_cost_flow, min_cost_flow_cost,
    network_simplex

    Examples
    --------
    >>> G = nx.DiGraph()
    >>> G.add_edges_from([(1, 2, {'capacity': 12, 'weight': 4}),
    ...                   (1, 3, {'capacity': 20, 'weight': 6}),
    ...                   (2, 3, {'capacity': 6, 'weight': -3}),
    ...                   (2, 6, {'capacity': 14, 'weight': 1}),
    ...                   (3, 4, {'weight': 9}),
    ...                   (3, 5, {'capacity': 10, 'weight': 5}),
    ...                   (4, 2, {'capacity': 19, 'weight': 13}),
    ...                   (4, 5, {'capacity': 4, 'weight': 0}),
    ...                   (5, 7, {'capacity': 28, 'weight': 2}),
    ...                   (6, 5, {'capacity': 11, 'weight': 1}),
    ...                   (6, 7, {'weight': 8}),
    ...                   (7, 4, {'capacity': 6, 'weight': 6})])
    >>> mincostFlow = nx.max_flow_min_cost(G, 1, 7)
    >>> nx.cost_of_flow(G, mincostFlow)
    373
    >>> maxFlow = nx.ford_fulkerson_flow(G, 1, 7)
    >>> nx.cost_of_flow(G, maxFlow)
    428
    >>> mincostFlowValue = (sum((mincostFlow[u][7] for u in G.predecessors(7)))
    ...                     - sum((mincostFlow[7][v] for v in G.successors(7))))
    >>> mincostFlowValue == nx.max_flow(G, 1, 7)
    True
    
    
    """
    maxFlow = nx.max_flow(G, s, t, capacity = capacity)
    H = nx.DiGraph(G)
    H.add_node(s, demand = -maxFlow)
    H.add_node(t, demand = maxFlow)
    return min_cost_flow(H, capacity = capacity, weight = weight)
Exemplo n.º 36
0
def max_flow_min_cost(G, s, t, capacity='capacity', weight='weight'):
    """Return a maximum (s, t)-flow of minimum cost.
    
    G is a digraph with edge costs and capacities. There is a source
    node s and a sink node t. This function finds a maximum flow from
    s to t whose total cost is minimized.

    Parameters
    ----------
    G : NetworkX graph
        DiGraph on which a minimum cost flow satisfying all demands is
        to be found.

    s: node label
        Source of the flow.

    t: node label
        Destination of the flow.

    capacity: string
        Edges of the graph G are expected to have an attribute capacity
        that indicates how much flow the edge can support. If this
        attribute is not present, the edge is considered to have
        infinite capacity. Default value: 'capacity'.

    weight: string
        Edges of the graph G are expected to have an attribute weight
        that indicates the cost incurred by sending one unit of flow on
        that edge. If not present, the weight is considered to be 0.
        Default value: 'weight'.

    Returns
    -------
    flowDict: dictionary
        Dictionary of dictionaries keyed by nodes such that
        flowDict[u][v] is the flow edge (u, v).

    Raises
    ------
    NetworkXError
        This exception is raised if the input graph is not directed or
        not connected.

    NetworkXUnbounded
        This exception is raised if there is an infinite capacity path
        from s to t in G. In this case there is no maximum flow. This
        exception is also raised if the digraph G has a cycle of
        negative cost and infinite capacity. Then, the cost of a flow
        is unbounded below.

    See also
    --------
    cost_of_flow, ford_fulkerson, min_cost_flow, min_cost_flow_cost,
    network_simplex

    Examples
    --------
    >>> G = nx.DiGraph()
    >>> G.add_edges_from([(1, 2, {'capacity': 12, 'weight': 4}),
    ...                   (1, 3, {'capacity': 20, 'weight': 6}),
    ...                   (2, 3, {'capacity': 6, 'weight': -3}),
    ...                   (2, 6, {'capacity': 14, 'weight': 1}),
    ...                   (3, 4, {'weight': 9}),
    ...                   (3, 5, {'capacity': 10, 'weight': 5}),
    ...                   (4, 2, {'capacity': 19, 'weight': 13}),
    ...                   (4, 5, {'capacity': 4, 'weight': 0}),
    ...                   (5, 7, {'capacity': 28, 'weight': 2}),
    ...                   (6, 5, {'capacity': 11, 'weight': 1}),
    ...                   (6, 7, {'weight': 8}),
    ...                   (7, 4, {'capacity': 6, 'weight': 6})])
    >>> mincostFlow = nx.max_flow_min_cost(G, 1, 7)
    >>> nx.cost_of_flow(G, mincostFlow)
    373
    >>> maxFlow = nx.ford_fulkerson_flow(G, 1, 7)
    >>> nx.cost_of_flow(G, maxFlow)
    428
    >>> mincostFlowValue = (sum((mincostFlow[u][7] for u in G.predecessors(7)))
    ...                     - sum((mincostFlow[7][v] for v in G.successors(7))))
    >>> mincostFlowValue == nx.max_flow(G, 1, 7)
    True
    
    
    """
    maxFlow = nx.max_flow(G, s, t, capacity=capacity)
    H = nx.DiGraph(G)
    H.add_node(s, demand=-maxFlow)
    H.add_node(t, demand=maxFlow)
    return min_cost_flow(H, capacity=capacity, weight=weight)
 def test_disconnected(self):
     G = nx.Graph()
     G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)],
                               weight='capacity')
     G.remove_node(1)
     assert_equal(nx.max_flow(G, 0, 3), 0)
Exemplo n.º 38
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)
Exemplo n.º 39
0
def local_node_connectivity(G, s, t, aux_digraph=None, mapping=None):
    r"""Computes local node connectivity for nodes s and t.

    Local node connectivity for two non adjacent nodes s and t is the
    minimum number of nodes that must be removed (along with their incident
    edges) to disconnect them.

    This is a flow based implementation of node connectivity. We compute the
    maximum flow on an auxiliary digraph build from the original input
    graph (see below for details). This is equal to the local node
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    s : node
        Source node

    t : node
        Target node

    aux_digraph : NetworkX DiGraph (default=None)
        Auxiliary digraph to compute flow based node connectivity. If None
        the auxiliary digraph is build.

    mapping : dict (default=None)
        Dictionary with a mapping of node names in G and in the auxiliary digraph.

    Returns
    -------
    K : integer
        local node connectivity for nodes s and t

    Examples
    --------
    >>> # Platonic icosahedral graph has node connectivity 5
    >>> # for each non adjacent node pair
    >>> G = nx.icosahedral_graph()
    >>> nx.local_node_connectivity(G,0,6)
    5

    Notes
    -----
    This is a flow based implementation of node connectivity. We compute the
    maximum flow using the Ford and Fulkerson algorithm on an auxiliary digraph
    build from the original input graph:

    For an undirected graph G having `n` nodes and `m` edges we derive a
    directed graph D with 2n nodes and 2m+n arcs by replacing each
    original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
    arc in `D`. Then for each edge (`u`, `v`) in G we add two arcs
    (`u_B`, `v_A`) and (`v_B`, `u_A`) in `D`. Finally we set the attribute
    capacity = 1 for each arc in `D` [1]_ .

    For a directed graph G having `n` nodes and `m` arcs we derive a
    directed graph `D` with `2n` nodes and `m+n` arcs by replacing each
    original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
    arc `(v_A, v_B)` in D. Then for each arc `(u,v)` in G we add one arc
    `(u_B,v_A)` in `D`. Finally we set the attribute capacity = 1 for
    each arc in `D`.

    This is equal to the local node connectivity because the value of
    a maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford
    and Fulkerson theorem).

    See also
    --------
    node_connectivity
    all_pairs_node_connectivity_matrix
    local_edge_connectivity
    edge_connectivity
    max_flow
    ford_fulkerson

    References
    ----------
    .. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and
        Erlebach, 'Network Analysis: Methodological Foundations', Lecture
        Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
        http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
    """
    if aux_digraph is None or mapping is None:
        H, mapping = _aux_digraph_node_connectivity(G)
    else:
        H = aux_digraph
    return nx.max_flow(H, '%sB' % mapping[s], '%sA' % mapping[t])
Exemplo n.º 40
0
#print(['%s %0.2f'%(node,centrality[node]) for node in centrality])
#print nx.eigenvector_centrality(G, max_iter=100, tol=1e-02, nstart=None)

#print nx.communicability(G)

#print nx.triangles(G)
#directed Graphでなくてはだめ

#print(nx.clustering(G,0))
#print nx.average_clustering(G)

# print nx.diameter(G, e=None)
#print nx.center(G, e=None)

print "max_flow(G, 'Fosl2.48h', 'Hoxa9.48h')"
print nx.max_flow(G, 'Fosl2.48h', 'Hoxa9.48h')

#print nx.network_simplex(G)

#print nx.pagerank(G,alpha=0.9)

print "pagerank_numpy"
print nx.pagerank_numpy(G,alpha=0.9)

print "hits_numpy"
print nx.hits_numpy(G)

# print(nx.shortest_path(G,source=0,target=4))
# print(nx.average_shortest_path_length(G))

#paths = nx.all_simple_paths(G, source=0, target=3, cutoff=2)
Exemplo n.º 41
0
def local_edge_connectivity(G, u, v, aux_digraph=None):
    r"""Returns local edge connectivity for nodes s and t in G.

    Local edge connectivity for two nodes s and t is the minimum number
    of edges that must be removed to disconnect them.

    This is a flow based implementation of edge connectivity. We compute the
    maximum flow on an auxiliary digraph build from the original
    network (see below for details). This is equal to the local edge
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .

    Parameters
    ----------
    G : NetworkX graph
        Undirected or directed graph

    s : node
        Source node

    t : node
        Target node

    aux_digraph : NetworkX DiGraph (default=None)
        Auxiliary digraph to compute flow based edge connectivity. If None
        the auxiliary digraph is build.

    Returns
    -------
    K : integer
        local edge connectivity for nodes s and t

    Examples
    --------
    >>> # Platonic icosahedral graph has edge connectivity 5
    >>> # for each non adjacent node pair
    >>> G = nx.icosahedral_graph()
    >>> nx.local_edge_connectivity(G,0,6)
    5

    Notes
    -----
    This is a flow based implementation of edge connectivity. We compute the
    maximum flow using the Ford and Fulkerson algorithm on an auxiliary digraph
    build from the original graph:

    If the input graph is undirected, we replace each edge (u,v) with
    two reciprocal arcs `(u,v)` and `(v,u)` and then we set the attribute
    'capacity' for each arc to 1. If the input graph is directed we simply
    add the 'capacity' attribute. This is an implementation of algorithm 1
    in [1]_.

    The maximum flow in the auxiliary network is equal to the local edge
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem).

    See also
    --------
    local_node_connectivity
    node_connectivity
    edge_connectivity
    max_flow
    ford_fulkerson

    References
    ----------
    .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
        http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
    """
    if aux_digraph is None:
        H = _aux_digraph_edge_connectivity(G)
    else:
        H = aux_digraph
    return nx.max_flow(H, u, v)