Exemplo n.º 1
0
 def test_digraph2(self):
     # Example from ticket #430 from mfrasca. Original source:
     # http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11.
     G = nx.DiGraph()
     G.add_edge('s', 1, capacity=12)
     G.add_edge('s', 2, capacity=6)
     G.add_edge('s', 3, capacity=14)
     G.add_edge(1, 2, capacity=11)
     G.add_edge(2, 3, capacity=9)
     G.add_edge(1, 4, capacity=5)
     G.add_edge(1, 5, capacity=2)
     G.add_edge(2, 5, capacity=4)
     G.add_edge(2, 6, capacity=2)
     G.add_edge(3, 6, capacity=31)
     G.add_edge(4, 5, capacity=18)
     G.add_edge(5, 5, capacity=9)
     G.add_edge(4, 't', capacity=3)
     G.add_edge(5, 't', capacity=7)
     G.add_edge(6, 't', capacity=22)
     flow = nx.max_flow_min_cost(G, 's', 't')
     soln = {1: {2: 5, 4: 5, 5: 2},
             2: {3: 6, 5: 3, 6: 2},
             3: {6: 20},
             4: {5: 2, 't': 3},
             5: {5: 0, 't': 7},
             6: {'t': 22},
             's': {1: 12, 2: 6, 3: 14},
             't': {}}
     assert_equal(flow, soln)
Exemplo n.º 2
0
def max_flow(bandwidth, src_dict, dst_dict):

    """ 最小费用最大流:给定多源点和多汇点及其流量,返回最大流矩阵 """

    # 转换为networkx格式的图,边权均为1
    G = nx.DiGraph()
    for i in range(len(bandwidth)):
        for j in range(len(bandwidth)):
            if bandwidth[i][j] > 0:
                G.add_edge(i, j, capacity=bandwidth[i][j], weight=1)

    # 添加虚拟源点-1和汇点-2
    for (s, value) in src_dict.items():
        G.add_edge(-1, s, capacity=value, weight=1)
    for (d, value) in dst_dict.items():
        G.add_edge(d, -2, capacity=value, weight=1)

    # 最小费用最大流
    flow = nx.max_flow_min_cost(G, -1, -2)

    flow_matrix = [[0 for col in range(len(bandwidth))] for row in range(len(bandwidth))]
    for i in range(len(bandwidth)):
        for (j, f) in flow[i].items():
            if j >= 0:
                flow_matrix[i][j] = f

    # 返回流矩阵
    return flow_matrix
Exemplo n.º 3
0
    def test_max_flow_min_cost(self):
        G = nx.DiGraph()
        G.add_edge('s', 'a', bandwidth=6)
        G.add_edge('s', 'c', bandwidth=10, cost=10)
        G.add_edge('a', 'b', cost=6)
        G.add_edge('b', 'd', bandwidth=8, cost=7)
        G.add_edge('c', 'd', cost=10)
        G.add_edge('d', 't', bandwidth=5, cost=5)
        soln = {'s': {'a': 5, 'c': 0},
                'a': {'b': 5},
                'b': {'d': 5},
                'c': {'d': 0},
                'd': {'t': 5},
                't': {}}
        flow = nx.max_flow_min_cost(G, 's', 't', capacity='bandwidth',
                                    weight='cost')
        assert_equal(flow, soln)
        assert_equal(nx.cost_of_flow(G, flow, weight='cost'), 90)

        G.add_edge('t', 's', cost=-100)
        flowCost, flow = nx.capacity_scaling(G, capacity='bandwidth',
                                             weight='cost')
        G.remove_edge('t', 's')
        assert_equal(flowCost, -410)
        assert_equal(flow['t']['s'], 5)
        del flow['t']['s']
        assert_equal(flow, soln)
        assert_equal(nx.cost_of_flow(G, flow, weight='cost'), 90)
Exemplo n.º 4
0
def tst():
    G = nx.DiGraph()
    edges = [(0, 1, {
        'capacity': 5,
        'weight': 1
    }), (0, 2, {
        'capacity': 3,
        'weight': 0.5
    }), (0, 3, {
        'capacity': 1,
        'weight': 1
    }), (4, 6, {
        'capacity': 4,
        'weight': 1
    }), (5, 6, {
        'capacity': 5,
        'weight': 1
    }), (1, 4, {
        'capacity': np.inf,
        'weight': 1
    }), (2, 4, {
        'capacity': np.inf,
        'weight': 1
    }), (3, 5, {
        'capacity': np.inf,
        'weight': 1
    })]
    G.add_edges_from(edges)
    mincostflow = nx.max_flow_min_cost(G, 0, 6)
    mincost = nx.cost_of_flow(G, mincostflow)
    max_flow = nx.maximum_flow_value(G, 0, 6)
Exemplo n.º 5
0
Arquivo: 8.py Projeto: qifanyyy/CLCDSA
def solve():
    n = int(sys.stdin.readline())
    topics = []
    for i in xrange(n):
        topics.append(sys.stdin.readline().split())

    left = set()
    right = set()

    for a, b in topics:
        left.add(a)
        right.add(b)

    G = nx.DiGraph()
    for a, b in topics:
        G.add_edges_from([((a, 0), (b, 1), {'capacity': 1, 'weight': 1})])

    for a in left:
        G.add_edges_from([(0, (a, 0), {'capacity': 1, 'weight': 0})])
    for b in right:
        G.add_edges_from([((b, 1), 1, {'capacity': 1, 'weight': 0})])

    mincostFlow = nx.max_flow_min_cost(G, 0, 1)
    mincost = nx.cost_of_flow(G, mincostFlow)
    # print mincost

    needed_arcs = len(left) + len(right) - mincost

    faked = len(topics) - needed_arcs
    print faked
Exemplo n.º 6
0
    def test_max_flow_min_cost(self):
        G = nx.DiGraph()
        G.add_edge('s', 'a', bandwidth=6)
        G.add_edge('s', 'c', bandwidth=10, cost=10)
        G.add_edge('a', 'b', cost=6)
        G.add_edge('b', 'd', bandwidth=8, cost=7)
        G.add_edge('c', 'd', cost=10)
        G.add_edge('d', 't', bandwidth=5, cost=5)
        soln = {'s': {'a': 5, 'c': 0},
                'a': {'b': 5},
                'b': {'d': 5},
                'c': {'d': 0},
                'd': {'t': 5},
                't': {}}
        flow = nx.max_flow_min_cost(G, 's', 't', capacity='bandwidth',
                                    weight='cost')
        assert flow == soln
        assert nx.cost_of_flow(G, flow, weight='cost') == 90

        G.add_edge('t', 's', cost=-100)
        flowCost, flow = nx.capacity_scaling(G, capacity='bandwidth',
                                             weight='cost')
        G.remove_edge('t', 's')
        assert flowCost == -410
        assert flow['t']['s'] == 5
        del flow['t']['s']
        assert flow == soln
        assert nx.cost_of_flow(G, flow, weight='cost') == 90
Exemplo n.º 7
0
 def test_max_flow_min_cost(self):
     G = nx.DiGraph()
     G.add_edge('s', 'a', bandwidth=6)
     G.add_edge('s', 'c', bandwidth=10, cost=10)
     G.add_edge('a', 'b', cost=6)
     G.add_edge('b', 'd', bandwidth=8, cost=7)
     G.add_edge('c', 'd', cost=10)
     G.add_edge('d', 't', bandwidth=5, cost=5)
     soln = {
         's': {
             'a': 5,
             'c': 0
         },
         'a': {
             'b': 5
         },
         'b': {
             'd': 5
         },
         'c': {
             'd': 0
         },
         'd': {
             't': 5
         },
         't': {}
     }
     flow = nx.max_flow_min_cost(G,
                                 's',
                                 't',
                                 capacity='bandwidth',
                                 weight='cost')
     assert_equal(flow, soln)
     assert_equal(nx.cost_of_flow(G, flow, weight='cost'), 90)
def optimal_procurement(supply_cost, x_max, demand_quantity, holding_cost, backlogging_cost, xh_0=0, xh_n=0):
    """Calculates optimal procurement planning.

    Arguments:
    supply_cost -- Supply cost at each time period
    x_max -- Maximum supply quantity at each time period.
    demand_quantity -- Demand quantity at each time period
    holding_cost -- Holding cost.
    backlogging_cost -- Backlogging cost.
    xh_0 -- Initial inventory.
    x_hn -- Final inventory target.
    """

    G = nx.DiGraph()
    n = len(supply_cost)
    for t in range(n):
        G.add_edge("source", t, {'capacity': x_max[t], 'weight': supply_cost[t]})
        G.add_edge(t, "sink", {'capacity': demand_quantity[t], 'weight': 0})
        G.add_edge(t, t + 1, {'capacity': np.inf, 'weight': holding_cost})
        G.add_edge(t + 1, t, {'capacity': np.inf, 'weight': backlogging_cost})

    G.add_edge("source", -1, {'capacity': xh_0, 'weight': 0})
    G.add_edge(-1, 0, {'capacity': xh_0, 'weight': 0})

    G.add_edge(n, "sink", {'capacity': xh_n, 'weight': 0})

    mincost_flow = nx.max_flow_min_cost(G, "source", "sink")
    cost = nx.cost_of_flow(G, mincost_flow)
    return cost, np.array([mincost_flow['source'][t] for t in range(n)])
Exemplo n.º 9
0
 def test_digraph2(self):
     # Example from ticket #430 from mfrasca. Original source:
     # http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11.
     G = nx.DiGraph()
     G.add_edge('s', 1, capacity=12)
     G.add_edge('s', 2, capacity=6)
     G.add_edge('s', 3, capacity=14)
     G.add_edge(1, 2, capacity=11)
     G.add_edge(2, 3, capacity=9)
     G.add_edge(1, 4, capacity=5)
     G.add_edge(1, 5, capacity=2)
     G.add_edge(2, 5, capacity=4)
     G.add_edge(2, 6, capacity=2)
     G.add_edge(3, 6, capacity=31)
     G.add_edge(4, 5, capacity=18)
     G.add_edge(5, 5, capacity=9)
     G.add_edge(4, 't', capacity=3)
     G.add_edge(5, 't', capacity=7)
     G.add_edge(6, 't', capacity=22)
     flow = nx.max_flow_min_cost(G, 's', 't')
     soln = {1: {2: 5, 4: 5, 5: 2},
             2: {3: 6, 5: 3, 6: 2},
             3: {6: 20},
             4: {5: 2, 't': 3},
             5: {5: 0, 't': 7},
             6: {'t': 22},
             's': {1: 12, 2: 6, 3: 14},
             't': {}}
     assert_equal(flow, soln)
Exemplo n.º 10
0
    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
Exemplo n.º 11
0
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
Exemplo n.º 12
0
    def test_max_flow_min_cost(self):
        G = nx.DiGraph()
        G.add_edge("s", "a", bandwidth=6)
        G.add_edge("s", "c", bandwidth=10, cost=10)
        G.add_edge("a", "b", cost=6)
        G.add_edge("b", "d", bandwidth=8, cost=7)
        G.add_edge("c", "d", cost=10)
        G.add_edge("d", "t", bandwidth=5, cost=5)
        soln = {
            "s": {"a": 5, "c": 0},
            "a": {"b": 5},
            "b": {"d": 5},
            "c": {"d": 0},
            "d": {"t": 5},
            "t": {},
        }
        flow = nx.max_flow_min_cost(G, "s", "t", capacity="bandwidth", weight="cost")
        assert flow == soln
        assert nx.cost_of_flow(G, flow, weight="cost") == 90

        G.add_edge("t", "s", cost=-100)
        flowCost, flow = nx.capacity_scaling(G, capacity="bandwidth", weight="cost")
        G.remove_edge("t", "s")
        assert flowCost == -410
        assert flow["t"]["s"] == 5
        del flow["t"]["s"]
        assert flow == soln
        assert nx.cost_of_flow(G, flow, weight="cost") == 90
Exemplo n.º 13
0
    def findMaxFlowMinCost(self, is_plot_graph: bool = True):
        """ 寻找最小费用最大流 """
        self.flow_cost_graph = nx.DiGraph()
        for edge in self.edge_list:
            self.flow_cost_graph.add_edge(edge[0],
                                          edge[1],
                                          capacity=edge[2],
                                          weight=edge[3])

        # 计算最小费用最大流
        self.max_flow_min_cost_dict = nx.max_flow_min_cost(
            self.flow_cost_graph, self.start_node, self.end_node)
        self.min_cost_value = nx.cost_of_flow(
            self.flow_cost_graph, self.max_flow_min_cost_dict)  # type:float
        print('最小费用为:', self.min_cost_value)

        # 将最大流字典转换为列表
        self.max_flow_min_cost_edges = []  # type:List[Tuple[int,int,int]]
        for node, nodes in self.max_flow_min_cost_dict.items():
            for node_, flow in nodes.items():
                if flow > 0:
                    self.max_flow_min_cost_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_min_cost_edges,
                                              ax_, pos)
            ax_.set_title('Max Flow Min Cost Graph')
Exemplo n.º 14
0
 def repair(self, DG): #new_feature = repair_feature(feature, create_graph(feature))
   mincostFlow = nx.max_flow_min_cost(DG, 's', 't') #max_flow_min_cost returns Dictionary of dictionaries. Keyed by nodes such that mincostFlow[u][v] is the flow edge (u,v)
   bin_dict = self.bin_fulldata
   index_dict = self.bin_index_dict_reverse
   size_data = len(self.data)
   repair_bin_dict = {}
   repair_data = [0]*size_data #initialize repaired data to be 0. If there are zero's after we fill it in the those observations belong in the overflow, "no category"
   k = self.num_bins
   overflow = 0
   for i in range(0,k): #for each lefthand side node i
     overflow += mincostFlow[i][2*k]
     for j in range(k, 2*k): #for each righthand side node j
       edgeflow = mincostFlow[i][j] #get the int (edgeflow) representing the amount of observations going from node i to j
       group = random.sample(bin_dict[i], int(edgeflow)) #randomly sample x (edgeflow) unique elements from the list of observations in that category.
       q=j-k #q is the category index for a righhand side node
       for elem in group: #for each element in the randomly selected group list
         bin_dict[i].remove(elem) #remove the element from the list of observation in that category
         repair_data[elem] = index_dict[q] #Mutate repair data at the index of the observation (elem) with its new category (it was 0) which is the category index for the righthand side node it flows to
       if q in repair_bin_dict: #if the category index is already keyed
         repair_bin_dict[q].extend(group) #extend the list of observations with a new list of observations in that category
       else:
         repair_bin_dict[q] = group #otherwise key that category index and set it's value as the group list in that category
   new_feature = CategoricalFeature(repair_data) #initialize our new_feature (repaired feature)
   new_feature.bin_fulldata = repair_bin_dict
   return [new_feature,overflow]
Exemplo n.º 15
0
def gen_test_cases(n_iter=100, seed=123):
    random.seed(seed)
    n = 8

    for _ in range(n_iter):
        while True:
            m = random.randint(n, 50)
            DG = nx.gnm_random_graph(n, m, seed=random.randint(1000, 10000), directed=True)

            WG = nx.DiGraph()
            WG.add_nodes_from(DG.nodes())

            for (u, v) in DG.edges():
                WG.add_edge(u, v, capacity=random.randint(
                    1, 8), weight=random.randint(1, 3))

            inp = io.StringIO()
            inp.write(f"{n} {m}\n")
            for u, v in WG.edges():
                edge = WG[u][v]
                inp.write(f"{u + 1} {v + 1} {edge['capacity']} {edge['weight']}\n")

            flow = nx.max_flow_min_cost(WG, 0, n - 1)
            cost = nx.cost_of_flow(WG, flow)
            if cost:
                break

        yield inp.getvalue(), cost, flow
Exemplo n.º 16
0
def hungarian_matching(left_nodes, right_nodes, threshold, dist_fn):
    """
    node shoud be [id, features]
    """

    if len(right_nodes) == 0 or left_nodes is None or len(left_nodes) == 0:
        return []

    G = nx.DiGraph()
    edges = []
    for left_node in left_nodes:
        if isinstance(left_node, Iterable):
            left_id = int(left_node[0])
        else:
            left_id = int(left_node)
        costs = dist_fn(left_node, right_nodes)
        valid_idxs = np.where(costs < threshold)[0]

        for valid_idx in valid_idxs:
            edges.append((
                f"p{left_id}",
                f"c{valid_idx}",
                {
                    "capacity": 1,
                    "weight": int(costs[valid_idx] * 100)
                },
            ))

        edges.append(("s", f"p{left_id}", {"capacity": 1, "weight": 0}))

    for i in range(len(right_nodes)):
        right_node = right_nodes[i]
        if isinstance(right_node, Iterable):
            right_id = right_node[0]
        else:
            right_id = right_node
        if right_id == -1:
            edges.append((f"c{i}", "t", {"capacity": np.inf, "weight": 0}))
        else:
            edges.append((f"c{i}", "t", {"capacity": 1, "weight": 0}))

    G.add_edges_from(edges)
    mincostFlow = nx.max_flow_min_cost(G, "s", "t")

    result = []
    for start_point, sflow in mincostFlow["s"].items():
        if sflow == 1:
            for end_point, eflow in mincostFlow[start_point].items():
                if eflow == 1:
                    left_id = int(start_point[1:])
                    right_idx = int(end_point[1:])
                    right_node = right_nodes[right_idx]
                    if isinstance(right_node, Iterable):
                        right_id = right_node[0]
                    else:
                        right_id = right_node
                    result.append((left_id, right_id))
                    break
    return result
Exemplo n.º 17
0
def computeSchedule():
    _logger.info('Scheduling AWS now')
    test_graph(g_)
    _logger.info('Computing max-flow, min-cost')
    res = nx.max_flow_min_cost(g_, 'source', 'sink')
    _logger.info('\t Computed. Getting schedules now ...')
    sch = getMatches(res)
    return sch
Exemplo n.º 18
0
def run_max_flow(G):
    '''Return edges in max flow analysis.

    G is a bipartite graph created from create_bipartite_graph().

    '''
    edges = nx.max_flow_min_cost(G, 'S', 'T')
    return edges
    def compute_flow(self):
        flow = nx.max_flow_min_cost(self._graph, 's', 't')
        total_flow = 0
        for site in self.sites:
            total_flow += flow.get(site)['t']

        total_flow = sum(flow['s'].values())
        return flow, total_flow
 def update_plan(self, G, t):
     #if 's' in nodes and 't' in nodes:
     nodes = G.nodes()
     if len(nodes) != 0:
         M = nx.max_flow_min_cost(G, 's', 't')
     else:
         M = False
     #print(M)
     return M
Exemplo n.º 21
0
def compute_solution():
    global g_
    flow = nx.max_flow_min_cost(g_, 'source', 'sink')
    scheduled, notScheduled = flow_to_solution(flow)
    daysToAWS = print_solution(scheduled)
    cost = nx.cost_of_flow(g_, flow)
    print('Cost of solution = %d' % cost)
    print('Mean gap=%d, Min gap=%d, Max Gap=%d' %
          (np.mean(daysToAWS), min(daysToAWS), max(daysToAWS)))
    return scheduled
	def update_plan(self, G,t):
		#if 's' in nodes and 't' in nodes:
		nodes=G.nodes()
		if len(nodes)!=0:
			M = nx.max_flow_min_cost(G, 's', 't')
			#print(M)
		else:
			M=False
		#print(M)
		#M = MinCost_MaxFlow(s,t) # dict of dict form
		return M
Exemplo n.º 23
0
def pr345():
    G = nx.DiGraph()
    n = len(data)
    for i in range(n): 
        G.add_edge('s', 'A'+str(i), weight=0, capacity=1)
        G.add_edge('B'+str(i), 't', weight=0, capacity=1)
    for i in range(n):
        for j in range(n):
            G.add_edge('A'+str(i), 'B'+str(j), weight=-data[i][j], capacity=1)
    flow = nx.max_flow_min_cost(G, 's', 't')
    return -nx.cost_of_flow(G, flow)
Exemplo n.º 24
0
    def __round_fractional_topology_giant_switch(self, fractional_adj_matrix):
        integer_adj_matrix = np.zeros((self.num_groups, self.num_groups))
        nnodes = 2 + (2 * self.num_groups)
        G = nx.DiGraph()
        edges = []
        num_interblock_link_per_group = self.num_switches_per_group * self.h
        # add edges from src to first layer nodes and between second layer nodes to sink
        for i in range(self.num_groups):
            egress_sum = 0.
            ingress_sum = 0.
            for j in range(self.num_groups):
                if i != j:
                    egress_sum += math.floor(fractional_adj_matrix[i][j])
                    ingress_sum += math.floor(fractional_adj_matrix[j][i])
            edges.append((0, i + 1, {
                'capacity': num_interblock_link_per_group - egress_sum,
                'weight': 0
            }))
            edges.append((self.num_groups + i + 1, nnodes - 1, {
                'capacity': num_interblock_link_per_group - ingress_sum,
                'weight': 0
            }))
        # next, add edges between first layer nodes and second layer nodes
        for i in range(self.num_groups):
            for j in range(self.num_groups):
                if i != j:
                    score = int((math.ceil(fractional_adj_matrix[i][j]) -
                                 fractional_adj_matrix[i][j]) * 1E6)
                    edges.append((i + 1, self.num_groups + j + 1, {
                        'capacity': 1,
                        'weight': score
                    }))

        # next, add the edges set into the graph
        G.add_edges_from(edges)
        mincostFlow = nx.max_flow_min_cost(G, 0, nnodes - 1)
        for i in range(self.num_groups):
            for j in range(self.num_groups):
                if i != j:
                    assert (mincostFlow[i + 1][self.num_groups + j + 1] <= 1)
                    integer_adj_matrix[i][j] = int(
                        math.floor(fractional_adj_matrix[i][j]) +
                        mincostFlow[i + 1][self.num_groups + j + 1])
        ## Finally, check to see if some links are 0
        for i in range(self.num_groups):
            for j in range(self.num_groups):
                if i != j and integer_adj_matrix[i][j] < 1:
                    assert (False)
        return integer_adj_matrix
Exemplo n.º 25
0
 def maxFlowMinCost(self, diNet):
     ''' graph must have one node s and one node t '''
     w = {}
     flow = {}
     residual_capacity = {}
     mfmc = nx.max_flow_min_cost(diNet, s='s', t='t', capacity='capacity', weight='weight')
     for k, v in mfmc.items():
         if isinstance(v, dict):
             for k2, v2 in v.items():
                 w[(k, k2)] = (diNet[k][k2]['capacity'], v2)
                 flow[(k, k2)] = v2
                 residual_capacity[(k, k2)] = diNet.get_edge_data(k, k2)['capacity'] - v2
         else:
             print("oops")
     return w, flow, residual_capacity
Exemplo n.º 26
0
 def test_max_flow_min_cost(self):
     G = nx.DiGraph()
     G.add_edge('s', 'a', bandwidth = 6)
     G.add_edge('s', 'c', bandwidth = 10, cost = 10)
     G.add_edge('a', 'b', cost = 6)
     G.add_edge('b', 'd', bandwidth = 8, cost = 7)
     G.add_edge('c', 'd', cost = 10)
     G.add_edge('d', 't', bandwidth = 5, cost = 5)
     soln = {'s': {'a': 5, 'c': 0},
             'a': {'b': 5},
             'b': {'d': 5},
             'c': {'d': 0},
             'd': {'t': 5},
             't': {}}
     flow = nx.max_flow_min_cost(G, 's', 't', capacity = 'bandwidth',
                                 weight = 'cost')
     assert_equal(flow, soln)
     assert_equal(nx.cost_of_flow(G, flow, weight = 'cost'), 90)
Exemplo n.º 27
0
    def test_digraph3(self):
        """Combinatorial Optimization: Algorithms and Complexity,
        Papadimitriou Steiglitz at page 140 has an example, 7.1, but that
        admits multiple solutions, so I alter it a bit. From ticket #430
        by mfrasca."""

        G = nx.DiGraph()
        G.add_edge('s', 'a')
        G['s']['a'].update({0: 2, 1: 4})
        G.add_edge('s', 'b')
        G['s']['b'].update({0: 2, 1: 1})
        G.add_edge('a', 'b')
        G['a']['b'].update({0: 5, 1: 2})
        G.add_edge('a', 't')
        G['a']['t'].update({0: 1, 1: 5})
        G.add_edge('b', 'a')
        G['b']['a'].update({0: 1, 1: 3})
        G.add_edge('b', 't')
        G['b']['t'].update({0: 3, 1: 2})

        "PS.ex.7.1: testing main function"
        sol = nx.max_flow_min_cost(G, 's', 't', capacity=0, weight=1)
        flow = sum(v for v in sol['s'].values())
        assert_equal(4, flow)
        assert_equal(23, nx.cost_of_flow(G, sol, weight=1))
        assert_equal(sol['s'], {'a': 2, 'b': 2})
        assert_equal(sol['a'], {'b': 1, 't': 1})
        assert_equal(sol['b'], {'a': 0, 't': 3})
        assert_equal(sol['t'], {})

        G.add_edge('t', 's')
        G['t']['s'].update({1: -100})
        flowCost, sol = nx.capacity_scaling(G, capacity=0, weight=1)
        G.remove_edge('t', 's')
        flow = sum(v for v in sol['s'].values())
        assert_equal(4, flow)
        assert_equal(sol['t']['s'], 4)
        assert_equal(flowCost, -377)
        del sol['t']['s']
        assert_equal(sol['s'], {'a': 2, 'b': 2})
        assert_equal(sol['a'], {'b': 1, 't': 1})
        assert_equal(sol['b'], {'a': 0, 't': 3})
        assert_equal(sol['t'], {})
        assert_equal(nx.cost_of_flow(G, sol, weight=1), 23)
    def test_digraph3(self):
        """Combinatorial Optimization: Algorithms and Complexity,
        Papadimitriou Steiglitz at page 140 has an example, 7.1, but that
        admits multiple solutions, so I alter it a bit. From ticket #430
        by mfrasca."""

        G = nx.DiGraph()
        G.add_edge("s", "a")
        G["s"]["a"].update({0: 2, 1: 4})
        G.add_edge("s", "b")
        G["s"]["b"].update({0: 2, 1: 1})
        G.add_edge("a", "b")
        G["a"]["b"].update({0: 5, 1: 2})
        G.add_edge("a", "t")
        G["a"]["t"].update({0: 1, 1: 5})
        G.add_edge("b", "a")
        G["b"]["a"].update({0: 1, 1: 3})
        G.add_edge("b", "t")
        G["b"]["t"].update({0: 3, 1: 2})

        "PS.ex.7.1: testing main function"
        sol = nx.max_flow_min_cost(G, "s", "t", capacity=0, weight=1)
        flow = sum(v for v in sol["s"].values())
        assert 4 == flow
        assert 23 == nx.cost_of_flow(G, sol, weight=1)
        assert sol["s"] == {"a": 2, "b": 2}
        assert sol["a"] == {"b": 1, "t": 1}
        assert sol["b"] == {"a": 0, "t": 3}
        assert sol["t"] == {}

        G.add_edge("t", "s")
        G["t"]["s"].update({1: -100})
        flowCost, sol = nx.capacity_scaling(G, capacity=0, weight=1)
        G.remove_edge("t", "s")
        flow = sum(v for v in sol["s"].values())
        assert 4 == flow
        assert sol["t"]["s"] == 4
        assert flowCost == -377
        del sol["t"]["s"]
        assert sol["s"] == {"a": 2, "b": 2}
        assert sol["a"] == {"b": 1, "t": 1}
        assert sol["b"] == {"a": 0, "t": 3}
        assert sol["t"] == {}
        assert nx.cost_of_flow(G, sol, weight=1) == 23
Exemplo n.º 29
0
    def test_digraph3(self):
        """Combinatorial Optimization: Algorithms and Complexity,
        Papadimitriou Steiglitz at page 140 has an example, 7.1, but that
        admits multiple solutions, so I alter it a bit. From ticket #430
        by mfrasca."""

        G = nx.DiGraph()
        G.add_edge('s', 'a')
        G['s']['a'].update({0: 2, 1: 4})
        G.add_edge('s', 'b')
        G['s']['b'].update({0: 2, 1: 1})
        G.add_edge('a', 'b')
        G['a']['b'].update({0: 5, 1: 2})
        G.add_edge('a', 't')
        G['a']['t'].update({0: 1, 1: 5})
        G.add_edge('b', 'a')
        G['b']['a'].update({0: 1, 1: 3})
        G.add_edge('b', 't')
        G['b']['t'].update({0: 3, 1: 2})

        "PS.ex.7.1: testing main function"
        sol = nx.max_flow_min_cost(G, 's', 't', capacity=0, weight=1)
        flow = sum(v for v in sol['s'].values())
        assert_equal(4, flow)
        assert_equal(23, nx.cost_of_flow(G, sol, weight=1))
        assert_equal(sol['s'], {'a': 2, 'b': 2})
        assert_equal(sol['a'], {'b': 1, 't': 1})
        assert_equal(sol['b'], {'a': 0, 't': 3})
        assert_equal(sol['t'], {})

        G.add_edge('t', 's')
        G['t']['s'].update({1: -100})
        flowCost, sol = nx.capacity_scaling(G, capacity=0, weight=1)
        G.remove_edge('t', 's')
        flow = sum(v for v in sol['s'].values())
        assert_equal(4, flow)
        assert_equal(sol['t']['s'], 4)
        assert_equal(flowCost, -377)
        del sol['t']['s']
        assert_equal(sol['s'], {'a': 2, 'b': 2})
        assert_equal(sol['a'], {'b': 1, 't': 1})
        assert_equal(sol['b'], {'a': 0, 't': 3})
        assert_equal(sol['t'], {})
        assert_equal(nx.cost_of_flow(G, sol, weight=1), 23)
Exemplo n.º 30
0
def buildGraph(inputData):
    """

    :param inputData:
    """
    sellerArray, customerArray, costMatrix = inputData
    G = nx.Graph()
    for i in range(1, len(sellerArray) + 1):
        for j in range(1, 1 + len(customerArray)):
            G.add_edge(i, j + len(sellerArray), capacity=inf, weight=int(costMatrix[i - 1][j - 1]))
        G.add_edge(0, i, {'capacity': sellerArray[i - 1], 'weight': int(0)})
    sum = len(sellerArray) + len(customerArray) + 1
    for j in range(len(customerArray)):
        G.add_edge(len(sellerArray) + j + 1, sum, capacity=customerArray[j - 1], weight=0)
        #minCostFlow = nx.max_flow_min_cost(G)
    c1 = 25000 / len(sellerArray)
    c2 = 25000 / len(customerArray)
    pos = {0: (15000.0, -12000.0), len(sellerArray) + len(customerArray) + 1: (15000.0, 12000.0)}
    for i in range(0, len(sellerArray)):
        pos[i + 1] = (i * c1, -7500.0)
    for n in range(len(sellerArray), len(sellerArray) + len(customerArray)):
        pos[n + 1] = ((n - len(sellerArray)) * c2, 7500.0)
        colors = [d['weight'] for (u, v, d) in G.edges(data=True)]
    flow = nx.max_flow_min_cost(G, 0, len(sellerArray) + len(customerArray) + 1)
    costOfFlow = nx.cost_of_flow(G, flow)
    print("Cost: " + str(costOfFlow))
    newEdgeList = []
    for k, v in flow.items():
        for i, j in v.items():
            if G.has_edge(k, i) and j > 0:
                newEdgeList.append([k, i])

    edge_labels = {}
    for u, v, d in G.edges(data=True):
        if flow[u][v] > 0:
            edge_labels[(u, v,)] = str(flow[u][v]) + "/" + str(d['weight'])
    print(costOfFlow, flow)
    nx.draw_networkx(G, pos, edgelist=newEdgeList, node_shape='o', node_color='#A0CBE2', edge_labels=edge_labels,
                     width=1.5, alpha=1,
                     edge_cmap=P.cm.ma,
                     with_labels=True)
    nx.draw_networkx_edge_labels(G, pos, edge_labels, label_pos=0.7, font_size=8)
    P.show()
Exemplo n.º 31
0
 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)
Exemplo n.º 32
0
    def test_digraph2(self):
        # Example from ticket #430 from mfrasca. Original source:
        # http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11.
        G = nx.DiGraph()
        G.add_edge("s", 1, capacity=12)
        G.add_edge("s", 2, capacity=6)
        G.add_edge("s", 3, capacity=14)
        G.add_edge(1, 2, capacity=11, weight=4)
        G.add_edge(2, 3, capacity=9, weight=6)
        G.add_edge(1, 4, capacity=5, weight=5)
        G.add_edge(1, 5, capacity=2, weight=12)
        G.add_edge(2, 5, capacity=4, weight=4)
        G.add_edge(2, 6, capacity=2, weight=6)
        G.add_edge(3, 6, capacity=31, weight=3)
        G.add_edge(4, 5, capacity=18, weight=4)
        G.add_edge(5, 6, capacity=9, weight=5)
        G.add_edge(4, "t", capacity=3)
        G.add_edge(5, "t", capacity=7)
        G.add_edge(6, "t", capacity=22)
        flow = nx.max_flow_min_cost(G, "s", "t")
        soln = {
            1: {2: 6, 4: 5, 5: 1},
            2: {3: 6, 5: 4, 6: 2},
            3: {6: 20},
            4: {5: 2, "t": 3},
            5: {6: 0, "t": 7},
            6: {"t": 22},
            "s": {1: 12, 2: 6, 3: 14},
            "t": {},
        }
        assert flow == soln

        G.add_edge("t", "s", weight=-100)
        flowCost, flow = nx.capacity_scaling(G)
        G.remove_edge("t", "s")
        assert flow["t"]["s"] == 32
        assert flowCost == -3007
        del flow["t"]["s"]
        assert flow == soln
        assert nx.cost_of_flow(G, flow) == 193
def optimal_procurement(supply_cost,
                        x_max,
                        demand_quantity,
                        holding_cost,
                        backlogging_cost,
                        xh_0=0,
                        xh_n=0):
    """Calculates optimal procurement planning.

    Arguments:
    supply_cost -- Supply cost at each time period
    x_max -- Maximum supply quantity at each time period.
    demand_quantity -- Demand quantity at each time period
    holding_cost -- Holding cost.
    backlogging_cost -- Backlogging cost.
    xh_0 -- Initial inventory.
    x_hn -- Final inventory target.
    """

    G = nx.DiGraph()
    n = len(supply_cost)
    for t in range(n):
        G.add_edge("source", t, {
            'capacity': x_max[t],
            'weight': supply_cost[t]
        })
        G.add_edge(t, "sink", {'capacity': demand_quantity[t], 'weight': 0})
        G.add_edge(t, t + 1, {'capacity': np.inf, 'weight': holding_cost})
        G.add_edge(t + 1, t, {'capacity': np.inf, 'weight': backlogging_cost})

    G.add_edge("source", -1, {'capacity': xh_0, 'weight': 0})
    G.add_edge(-1, 0, {'capacity': xh_0, 'weight': 0})

    G.add_edge(n, "sink", {'capacity': xh_n, 'weight': 0})

    mincost_flow = nx.max_flow_min_cost(G, "source", "sink")
    cost = nx.cost_of_flow(G, mincost_flow)
    return cost, np.array([mincost_flow['source'][t] for t in range(n)])
Exemplo n.º 34
0
    def test_digraph2(self):
        # Example from ticket #430 from mfrasca. Original source:
        # http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11.
        G = nx.DiGraph()
        G.add_edge('s', 1, capacity=12)
        G.add_edge('s', 2, capacity=6)
        G.add_edge('s', 3, capacity=14)
        G.add_edge(1, 2, capacity=11, weight=4)
        G.add_edge(2, 3, capacity=9, weight=6)
        G.add_edge(1, 4, capacity=5, weight=5)
        G.add_edge(1, 5, capacity=2, weight=12)
        G.add_edge(2, 5, capacity=4, weight=4)
        G.add_edge(2, 6, capacity=2, weight=6)
        G.add_edge(3, 6, capacity=31, weight=3)
        G.add_edge(4, 5, capacity=18, weight=4)
        G.add_edge(5, 6, capacity=9, weight=5)
        G.add_edge(4, 't', capacity=3)
        G.add_edge(5, 't', capacity=7)
        G.add_edge(6, 't', capacity=22)
        flow = nx.max_flow_min_cost(G, 's', 't')
        soln = {1: {2: 6, 4: 5, 5: 1},
                2: {3: 6, 5: 4, 6: 2},
                3: {6: 20},
                4: {5: 2, 't': 3},
                5: {6: 0, 't': 7},
                6: {'t': 22},
                's': {1: 12, 2: 6, 3: 14},
                't': {}}
        assert_equal(flow, soln)

        G.add_edge('t', 's', weight=-100)
        flowCost, flow = nx.capacity_scaling(G)
        G.remove_edge('t', 's')
        assert_equal(flow['t']['s'], 32)
        assert_equal(flowCost, -3007)
        del flow['t']['s']
        assert_equal(flow, soln)
        assert_equal(nx.cost_of_flow(G, flow), 193)
Exemplo n.º 35
0
    def test_digraph2(self):
        # Example from ticket #430 from mfrasca. Original source:
        # http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11.
        G = nx.DiGraph()
        G.add_edge('s', 1, capacity=12)
        G.add_edge('s', 2, capacity=6)
        G.add_edge('s', 3, capacity=14)
        G.add_edge(1, 2, capacity=11, weight=4)
        G.add_edge(2, 3, capacity=9, weight=6)
        G.add_edge(1, 4, capacity=5, weight=5)
        G.add_edge(1, 5, capacity=2, weight=12)
        G.add_edge(2, 5, capacity=4, weight=4)
        G.add_edge(2, 6, capacity=2, weight=6)
        G.add_edge(3, 6, capacity=31, weight=3)
        G.add_edge(4, 5, capacity=18, weight=4)
        G.add_edge(5, 6, capacity=9, weight=5)
        G.add_edge(4, 't', capacity=3)
        G.add_edge(5, 't', capacity=7)
        G.add_edge(6, 't', capacity=22)
        flow = nx.max_flow_min_cost(G, 's', 't')
        soln = {1: {2: 6, 4: 5, 5: 1},
                2: {3: 6, 5: 4, 6: 2},
                3: {6: 20},
                4: {5: 2, 't': 3},
                5: {6: 0, 't': 7},
                6: {'t': 22},
                's': {1: 12, 2: 6, 3: 14},
                't': {}}
        assert_equal(flow, soln)

        G.add_edge('t', 's', weight=-100)
        flowCost, flow = nx.capacity_scaling(G)
        G.remove_edge('t', 's')
        assert_equal(flow['t']['s'], 32)
        assert_equal(flowCost, -3007)
        del flow['t']['s']
        assert_equal(flow, soln)
        assert_equal(nx.cost_of_flow(G, flow), 193)
Exemplo n.º 36
0
def main(departure_locations, meeting_options, departure_date):
    G = nx.DiGraph()
    G = create_graph(departure_locations, meeting_options, departure_date)
    flow_dict = nx.max_flow_min_cost(G, 'SOURCE', 'DEST')

    print(flow_dict)
    mincost = nx.cost_of_flow(G, flow_dict)
    print(mincost)

    pairs = []

    for u in flow_dict.keys():
        for v in (flow_dict[u]).keys():
            if int(flow_dict[u][v]) > 0:
                print(u, v, flow_dict[u][v])
                pairs.append((u, v))

    max_people = 0
    best_loc = ''
    for pair in pairs:
        if pair[1] == 'DEST':
            if int(flow_dict[pair[0]][pair[1]]) > max_people:
                best_loc = pair[0]
                max_people = int(flow_dict[pair[0]][pair[1]])

    print('Best location is ', best_loc)

    response = amadeus.reference_data.locations.get(subType='AIRPORT',
                                                    keyword=best_loc)
    city_name = response.data[0]["address"]["cityName"]
    state_name = response.data[0]["address"]["stateCode"]

    location = city_name + ', ' + state_name
    print('My location is ', location)

    return location, mincost
Exemplo n.º 37
0
    sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
    plt.colorbar(sm, ax=ax, alpha=.8)


def draw_flow(graph, flow_dict, pos):
    flow_labels = {(k, v1): 'flow: ' + str(v2)
                   for k, v in flow_dict.items() for v1, v2 in v.items()}
    nx.draw_networkx(graph, pos=pos)
    nx.draw_networkx_edge_labels(graph, pos, edge_labels=flow_labels)
    plt.show()


#%% Solve max flow without constraints

draw_graph_with_edges(g, gpos)
unconstrained = nx.max_flow_min_cost(g, s=1, t=4)
draw_flow(g, unconstrained, gpos)

#%% Augment with source and sink
aug_g = g.copy()
aug_gpos = gpos.copy()
aug_gpos['super_source'] = (min([x for x, y in gpos.values()]) - 1,
                            max([y for x, y in gpos.values()]) + 1)
aug_gpos['super_sink'] = (max([x for x, y in gpos.values()]) + 1,
                          max([y for x, y in gpos.values()]) + 1)
sum_demand = sum([d for n, d in g.nodes(data='demand') if d > 0])
max_weight = max([w for u, v, w in g.edges(data='weight')])
# Add edge with 0 weight from super source to nodes with negative demand (demand nodes)
aug_g.add_weighted_edges_from([('super_source', n, 0) for n in g.nodes()
                               if g.nodes[n]['demand'] < 0])
aug_g.nodes['super_source']['demand'] = -sum_demand
    vector = buildNetwork(devices)

    # print(vector)
    paths, SchematicGraph, ImpactGraph, ExploitabilityGraph, edge_labels, schematic_dotstr, impact_dotstr, exploitability_dotstr, targets = buildCircuit(
        devices, vector)
    print(nx.get_edge_attributes(ExploitabilityGraph, "weight"))
    print(nx.get_edge_attributes(ExploitabilityGraph, "demand"))
    print(nx.get_edge_attributes(ExploitabilityGraph, "capacity"))
    ### find max flow values ###
    max_impact = max_exploitability = 0
    for target in targets:
        max_impact += nx.maximum_flow_value(ImpactGraph,
                                            "Non-CVE info: Router", target)
        try:
            min_cost = nx.max_flow_min_cost(ExploitabilityGraph, "Attacker",
                                            target)
            print("Min cost flow, " + target + ": ", min_cost)
        except:
            print("Min cost flow, " + target + ": no path")

    print("Max Impact: ", max_impact)

    print("Time: " + str(time.time() - timestamp))
    ### save ###

    # snap.DrawGViz(home_network, snap.gvlDot, "deliverables/home_network.png", "Home Network", network_labels)
    schematic_dotfile = open("deliverables/schematic_circuit.dot", "w")
    schematic_dotfile.write(schematic_dotstr)
    schematic_dotfile.close()
    impact_dotfile = open("deliverables/impact_circuit.dot", "w")
    impact_dotfile.write(impact_dotstr)
Exemplo n.º 39
0
def active_colloids_tracking_pipeline(frames, segmentation_method,
                                      simple_threshold):
    G = nx.DiGraph()
    num_frames = len(frames)
    num_cores = multiprocessing.cpu_count()

    if segmentation_method == 'two_cc':
        segments = Parallel(n_jobs=num_cores)(
            delayed(two_cc.two_connected_components)(
                frames[i], channel="red", thresh=86)
            for i in range(len(frames)))
    elif segmentation_method == 'watershed':
        segments = Parallel(n_jobs=num_cores)(
            delayed(simple_segmentation.simple_segmentation)(frames[i])
            for i in range(len(frames)))
    elif segmentation_method == 'rag_merging':
        segments = Parallel(n_jobs=num_cores)(
            delayed(simple_segmentation.rag_merging_segmentation)(frames[i])
            for i in range(len(frames)))
    elif segmentation_method == 'simple_threshold':
        segments = Parallel(n_jobs=num_cores)(delayed(
            simple_segmentation.simple_threshold)(frames[i], simple_threshold)
                                              for i in range(len(frames)))

    all_mass_centers = []
    all_mass_centers = Parallel(n_jobs=num_cores)(
        delayed(get_frame_mass_centers)(segments[i])
        for i in range(num_frames))

    # adding nodes
    for i in range(len(segments)):
        frame_mass_centers = all_mass_centers[i]
        for j in range(len(frame_mass_centers)):
            pos_x = frame_mass_centers[j][0]
            pos_y = frame_mass_centers[j][1]
            frame_number = i
            G.add_node((pos_x, pos_y, frame_number), pos=(pos_x, pos_y))
    end = time.time()

    # adding edges (arcs)
    d_max = 20  # TODO generalize

    for frame_number in range(num_frames - 1):  # we set attributes for FF
        for vertex1 in vertices_from_ith_frame(G, frame_number):
            for vertex2 in vertices_from_ith_frame(G, frame_number + 1):
                if get_distance(vertex1, vertex2) < d_max:
                    weight = int(10 * get_distance(vertex1, vertex2) / d_max)
                    G.add_edge(vertex1, vertex2, capacity=10, weight=weight)

    dist_border = 100000  #### TODO generalize

    print('Number of edges before the refinement', len(G.edges))
    initial_graph_refinement(G, d_max, dist_border)
    print('Number of edges before the refinement', len(G.edges))

    # new nodes
    source = (-1, -1, -1)
    G.add_node(source, pos=(-1, 1))  # source
    sink = (-2, -2, -2)
    G.add_node(sink, pos=(700, 1))  # sink

    # new edges
    for vertex in vertices_from_ith_frame(G, 0):
        G.add_edge(source, vertex, capacity=10, weight=0)

    for vertex in vertices_from_ith_frame(G, get_num_frames(G) - 1):
        G.add_edge(vertex, sink, capacity=10, weight=0)

    # weights should not be floats! We use only integers, otherwise calculations will last forever!
    resultFlowDict = nx.max_flow_min_cost(G,
                                          source,
                                          sink,
                                          capacity='capacity',
                                          weight='weight')

    detected_objects = []

    visited = {}
    for node in G.nodes:
        visited[node] = False

    results = [np.array(f) for f in segments]

    radius = 20
    for node in G.nodes:
        if not visited[node]:
            detected_objects.append(node)
            color = (int(random() * 255), int(random() * 255),
                     int(random() * 255))
            while node != (-2, -2, -2):
                center = (node[1], node[0])
                frame = node[2]
                results[frame] = cv2.circle(results[frame],
                                            center,
                                            radius,
                                            color,
                                            thickness=3)
                if resultFlowDict[node] == {}:
                    break
                visited[node] = True
                node = list(resultFlowDict[node].keys())[0]

    results = [Image.fromarray(r) for r in results]

    return results, G, resultFlowDict
Exemplo n.º 40
0
def buildGraph(inputData):
    """

    :param inputData:
    """
    sellerArray, customerArray, costMatrix = inputData
    G = nx.Graph()
    for i in range(1, len(sellerArray) + 1):
        for j in range(1, 1 + len(customerArray)):
            G.add_edge(i,
                       j + len(sellerArray),
                       capacity=inf,
                       weight=int(costMatrix[i - 1][j - 1]))
        G.add_edge(0, i, {'capacity': sellerArray[i - 1], 'weight': int(0)})
    sum = len(sellerArray) + len(customerArray) + 1
    for j in range(len(customerArray)):
        G.add_edge(len(sellerArray) + j + 1,
                   sum,
                   capacity=customerArray[j - 1],
                   weight=0)
        #minCostFlow = nx.max_flow_min_cost(G)
    c1 = 25000 / len(sellerArray)
    c2 = 25000 / len(customerArray)
    pos = {
        0: (15000.0, -12000.0),
        len(sellerArray) + len(customerArray) + 1: (15000.0, 12000.0)
    }
    for i in range(0, len(sellerArray)):
        pos[i + 1] = (i * c1, -7500.0)
    for n in range(len(sellerArray), len(sellerArray) + len(customerArray)):
        pos[n + 1] = ((n - len(sellerArray)) * c2, 7500.0)
        colors = [d['weight'] for (u, v, d) in G.edges(data=True)]
    flow = nx.max_flow_min_cost(G, 0,
                                len(sellerArray) + len(customerArray) + 1)
    costOfFlow = nx.cost_of_flow(G, flow)
    print("Cost: " + str(costOfFlow))
    newEdgeList = []
    for k, v in flow.items():
        for i, j in v.items():
            if G.has_edge(k, i) and j > 0:
                newEdgeList.append([k, i])

    edge_labels = {}
    for u, v, d in G.edges(data=True):
        if flow[u][v] > 0:
            edge_labels[(
                u,
                v,
            )] = str(flow[u][v]) + "/" + str(d['weight'])
    print(costOfFlow, flow)
    nx.draw_networkx(G,
                     pos,
                     edgelist=newEdgeList,
                     node_shape='o',
                     node_color='#A0CBE2',
                     edge_labels=edge_labels,
                     width=1.5,
                     alpha=1,
                     edge_cmap=P.cm.ma,
                     with_labels=True)
    nx.draw_networkx_edge_labels(G,
                                 pos,
                                 edge_labels,
                                 label_pos=0.7,
                                 font_size=8)
    P.show()