Example #1
0
 def test_multigraph(self):
     assert nx.bellman_ford_path(self.MXG, "s", "v") == ["s", "x", "u", "v"]
     assert nx.bellman_ford_path_length(self.MXG, "s", "v") == 9
     assert nx.single_source_bellman_ford_path(self.MXG, "s")["v"] == [
         "s",
         "x",
         "u",
         "v",
     ]
     assert nx.single_source_bellman_ford_path_length(self.MXG,
                                                      "s")["v"] == 9
     D, P = nx.single_source_bellman_ford(self.MXG, "s", target="v")
     assert D == 9
     assert P == ["s", "x", "u", "v"]
     P, D = nx.bellman_ford_predecessor_and_distance(self.MXG, "s")
     assert P["v"] == ["u"]
     assert D["v"] == 9
     P, D = nx.goldberg_radzik(self.MXG, "s")
     assert P["v"] == "u"
     assert D["v"] == 9
     assert nx.bellman_ford_path(self.MXG4, 0, 2) == [0, 1, 2]
     assert nx.bellman_ford_path_length(self.MXG4, 0, 2) == 4
     assert nx.single_source_bellman_ford_path(self.MXG4, 0)[2] == [0, 1, 2]
     assert nx.single_source_bellman_ford_path_length(self.MXG4, 0)[2] == 4
     D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2)
     assert D == 4
     assert P == [0, 1, 2]
     P, D = nx.bellman_ford_predecessor_and_distance(self.MXG4, 0)
     assert P[2] == [1]
     assert D[2] == 4
     P, D = nx.goldberg_radzik(self.MXG4, 0)
     assert P[2] == 1
     assert D[2] == 4
Example #2
0
    def delete_high_betweenness_centrality(self, infectG):
        subinfectG = commons.get_subGraph_true(infectG)
        sort_list = Partion_common.get_layer_node_between(subinfectG)
        #根据中介性分层然后删除。
        print('sort_list', sort_list)  #先验证高中介性节点是否在中间。
        # for every_node in sort_list:
        first_layer_between = [x[0] for x in sort_list[0]]  #取第一层节点
        two_source = random.sample(first_layer_between,
                                   2)  # 从list中随机获取2个元素,作为一个片断返回

        lengthA_B = 100000
        good_two_result = []
        best_node_two_result = None
        for iter in range(0, 100):
            # 对这两个点进行Djstra,计算所有点到他们的距离。
            print('two_source', two_source)
            lengthA_dict = nx.single_source_bellman_ford_path_length(
                subinfectG, two_source[0], weight='weight')
            lengthB_dict = nx.single_source_bellman_ford_path_length(
                subinfectG, two_source[1], weight='weight')
            # 初始化两个集合,用来保存两个类别节点集合。
            node_twolist = [[], []]  # 保存两个类别节点集合
            node_diff_twolist = [[], []]  # 保存不同点
            for node in list(subinfectG.nodes):
                if lengthA_dict[node] > lengthB_dict[node]:  # 这个点离b近一些。
                    node_twolist[1].append(node)
                    node_diff_twolist[1].append(node)
                elif lengthA_dict[node] < lengthB_dict[node]:
                    node_twolist[0].append(node)
                    node_diff_twolist[0].append(node)
                else:
                    node_twolist[0].append(node)
                    node_twolist[1].append(node)
            print('node_twolist', len(node_twolist[1]))
            # 在两个list中找到中心位置,有几种中心性可以度量的。或者进行快速算法。
            # 判断这次找的两个中心好不好。

            lengthA_sum = 0  # a这个不同点,
            lengthB_sum = 0
            for i in node_diff_twolist[0]:  # 距离a近,第一个源点近的点。统计它跟自己区域点的距离之和
                lengthA_sum += lengthA_dict[i]
            for j in node_diff_twolist[1]:  # 距离b近,第二个源点近的点。统计它跟自己区域点的距离之和
                lengthB_sum += lengthB_dict[j]

            sums = lengthA_sum + lengthB_sum
            if sums < lengthA_B:
                print('sums', sums)
                # 是比原来好的的两个源。
                lengthA_B = sums
                good_two_result = two_source
                best_node_two_result = node_twolist
            else:
                # 重新长生两个源吧。这里还是可以做优化的,选择的方向问题。
                two_source = random.sample(first_layer_between, 2)

        print('good_two_result', good_two_result)
        print('good_node_two_result', best_node_two_result)

        return [[good_two_result[0], best_node_two_result[0]],
                [good_two_result[1], best_node_two_result[1]]]
Example #3
0
 def test_multigraph(self):
     assert nx.bellman_ford_path(self.MXG, 's', 'v') == ['s', 'x', 'u', 'v']
     assert nx.bellman_ford_path_length(self.MXG, 's', 'v') == 9
     assert nx.single_source_bellman_ford_path(
         self.MXG, 's')['v'] == ['s', 'x', 'u', 'v']
     assert nx.single_source_bellman_ford_path_length(self.MXG,
                                                      's')['v'] == 9
     D, P = nx.single_source_bellman_ford(self.MXG, 's', target='v')
     assert D == 9
     assert P == ['s', 'x', 'u', 'v']
     P, D = nx.bellman_ford_predecessor_and_distance(self.MXG, 's')
     assert P['v'] == ['u']
     assert D['v'] == 9
     P, D = nx.goldberg_radzik(self.MXG, 's')
     assert P['v'] == 'u'
     assert D['v'] == 9
     assert nx.bellman_ford_path(self.MXG4, 0, 2) == [0, 1, 2]
     assert nx.bellman_ford_path_length(self.MXG4, 0, 2) == 4
     assert nx.single_source_bellman_ford_path(self.MXG4, 0)[2] == [0, 1, 2]
     assert nx.single_source_bellman_ford_path_length(self.MXG4, 0)[2] == 4
     D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2)
     assert D == 4
     assert P == [0, 1, 2]
     P, D = nx.bellman_ford_predecessor_and_distance(self.MXG4, 0)
     assert P[2] == [1]
     assert D[2] == 4
     P, D = nx.goldberg_radzik(self.MXG4, 0)
     assert P[2] == 1
     assert D[2] == 4
Example #4
0
 def test_multigraph(self):
     assert_equal(nx.bellman_ford_path(self.MXG, 's', 'v'), ['s', 'x', 'u', 'v'])
     assert_equal(nx.bellman_ford_path_length(self.MXG, 's', 'v'), 9)
     assert_equal(nx.single_source_bellman_ford_path(self.MXG, 's')['v'], ['s', 'x', 'u', 'v'])
     assert_equal(nx.single_source_bellman_ford_path_length(self.MXG, 's')['v'], 9)
     D, P = nx.single_source_bellman_ford(self.MXG, 's', target='v')
     assert_equal(D, 9)
     assert_equal(P, ['s', 'x', 'u', 'v'])
     P, D = nx.bellman_ford_predecessor_and_distance(self.MXG, 's')
     assert_equal(P['v'], ['u'])
     assert_equal(D['v'], 9)
     P, D = nx.goldberg_radzik(self.MXG, 's')
     assert_equal(P['v'], 'u')
     assert_equal(D['v'], 9)
     assert_equal(nx.bellman_ford_path(self.MXG4, 0, 2), [0, 1, 2])
     assert_equal(nx.bellman_ford_path_length(self.MXG4, 0, 2), 4)
     assert_equal(nx.single_source_bellman_ford_path(self.MXG4, 0)[2], [0, 1, 2])
     assert_equal(nx.single_source_bellman_ford_path_length(self.MXG4, 0)[2], 4)
     D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2)
     assert_equal(D, 4)
     assert_equal(P, [0, 1, 2])
     P, D = nx.bellman_ford_predecessor_and_distance(self.MXG4, 0)
     assert_equal(P[2], [1])
     assert_equal(D[2], 4)
     P, D = nx.goldberg_radzik(self.MXG4, 0)
     assert_equal(P[2], 1)
     assert_equal(D[2], 4)
Example #5
0
 def test_multigraph(self):
     assert_equal(nx.bellman_ford_path(self.MXG, 's', 'v'),
                  ['s', 'x', 'u', 'v'])
     assert_equal(nx.bellman_ford_path_length(self.MXG, 's', 'v'), 9)
     assert_equal(
         nx.single_source_bellman_ford_path(self.MXG, 's')['v'],
         ['s', 'x', 'u', 'v'])
     assert_equal(
         dict(nx.single_source_bellman_ford_path_length(self.MXG,
                                                        's'))['v'], 9)
     D, P = nx.single_source_bellman_ford(self.MXG, 's', target='v')
     assert_equal(D['v'], 9)
     assert_equal(P['v'], ['s', 'x', 'u', 'v'])
     P, D = nx.bellman_ford_predecessor_and_distance(self.MXG, 's')
     assert_equal(P['v'], ['u'])
     assert_equal(D['v'], 9)
     P, D = nx.goldberg_radzik(self.MXG, 's')
     assert_equal(P['v'], 'u')
     assert_equal(D['v'], 9)
     assert_equal(nx.bellman_ford_path(self.MXG4, 0, 2), [0, 1, 2])
     assert_equal(nx.bellman_ford_path_length(self.MXG4, 0, 2), 4)
     assert_equal(
         nx.single_source_bellman_ford_path(self.MXG4, 0)[2], [0, 1, 2])
     assert_equal(
         dict(nx.single_source_bellman_ford_path_length(self.MXG4, 0))[2],
         4)
     D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2)
     assert_equal(D[2], 4)
     assert_equal(P[2], [0, 1, 2])
     P, D = nx.bellman_ford_predecessor_and_distance(self.MXG4, 0)
     assert_equal(P[2], [1])
     assert_equal(D[2], 4)
     P, D = nx.goldberg_radzik(self.MXG4, 0)
     assert_equal(P[2], 1)
     assert_equal(D[2], 4)
Example #6
0
    def get_partion_bound(self,infectG, subinfecG, two_center_list, source_number=2):
        #边界点。
        bound_list = []
        for node_temp in list(infectG.nodes()):
            print(node_temp)
            if infectG.node[node_temp]['SI']==2:
                neighbors_list = list(nx.neighbors(infectG, node_temp))
                neighbors_infect_list = [ x for x in neighbors_list if infectG.node[x]['SI']==2 ]
                if len(neighbors_list)!= 1 and len(neighbors_infect_list) ==1:
                # if  len(neighbors_infect_list) == 1:
                        bound_list.append(node_temp)

        print('boundelist',len(bound_list))
        #求得所有点到他们的距离,把和加起来求得最小值。












        #看下是否是边界点。













        plot_main.plot_G_node_color(infectG,subinfecG,bound_list,two_center_list)



        #能否找到大小为k的点,以最小的h覆盖这些边界点。

        #先检测源点距离他们的距离
        lengthA_dict = nx.single_source_bellman_ford_path_length(subinfecG, two_center_list[0],
                                        weight='weight')
        lengthB_dict = nx.single_source_bellman_ford_path_length(subinfecG, two_center_list[1], weight='weight')

        distance_list =[ [], []]
        for bound in bound_list:
            distance_list[0].append(lengthA_dict[bound])
            distance_list[1].append(lengthB_dict[bound])

        print('distance_list',distance_list[0])
        print('distance_list',distance_list[1])
Example #7
0
    def findmultiplesource(self, infectionG, subinfectG, sourceNumber=2):
        # 首先需要判断是否多源。不断找源点去对这个区域。
        tempGraph = nx.Graph()
        tempGraph = subinfectG
        tempGraphNodelist = []
        for node in list(tempGraph.nodes):
            tempGraphNodelist.append(node)
        print('这个传播子图的节点个数,也是我们用来做u的备选集合的' + str(len(set(tempGraphNodelist))))
        print('这个感染区域的传播图节点个数')
        print(tempGraph.number_of_nodes())
        Alternativenodeset = list(tempGraph.nodes())  # 备选集合。
        print('tempgraph的所有点数' + str(len(Alternativenodeset)))
        minCoverlist = []
        print('在源点在' + str(sourceNumber) + '个数的情况下')
        # print('在h为' + str(h) + '的情况下')
        # 计算图的拉普拉斯
        k = 1
        sourceNum = 2
        # while 1:
        minCoverlist = []
        print('在源点在' + str(sourceNum) + '个数的情况下')
        # print('在h为' + str(h) + '的情况下')

        #基于k-means的方法。
        if sourceNum == 2:
            partion_region = []
            #选择距离最远的点。
            distance_iter = nx.shortest_path_length(subinfectG)
            everynode_distance = []
            for node, node_distance in distance_iter:
                # print(node_distance)
                sort_list = sorted(node_distance.items(),
                                   key=lambda x: x[1],
                                   reverse=True)
                # print('sort_list',sort_list)
                everynode_distance.append(
                    [node, sort_list[0][0], sort_list[0][1]])
            # print('everynode_idstance',everynode_distance)
            sort_every_distance = sorted(everynode_distance,
                                         key=lambda x: x[2],
                                         reverse=True)
            # print(sort_every_distance)
            node_twolist = [[], []]
            lengthA_dict = nx.single_source_bellman_ford_path_length(
                subinfectG, sort_every_distance[0][0], weight='weight')
            lengthB_dict = nx.single_source_bellman_ford_path_length(
                subinfectG, sort_every_distance[0][1], weight='weight')
            for node in list(subinfectG.nodes):
                if lengthA_dict[node] > lengthB_dict[node]:  # 这个点离b近一些。
                    node_twolist[1].append(node)
                elif lengthA_dict[node] < lengthB_dict[node]:
                    node_twolist[0].append(node)
                else:
                    node_twolist[0].append(node)
                    node_twolist[1].append(node)
            print('len(node_twolist[0]', len(node_twolist[0]))
            print('len(node_twolist[1]', len(node_twolist[1]))
            return node_twolist
Example #8
0
    def test_others(self):
        assert_equal(nx.bellman_ford_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v'])
        assert_equal(nx.bellman_ford_path_length(self.XG, 's', 'v'), 9)
        assert_equal(nx.single_source_bellman_ford_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v'])
        assert_equal(dict(nx.single_source_bellman_ford_path_length(self.XG, 's'))['v'], 9)
        D, P = nx.single_source_bellman_ford(self.XG, 's', target='v')
        assert_equal(D['v'], 9)
        assert_equal(P['v'], ['s', 'x', 'u', 'v'])
        (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, 's')
        assert_equal(P['v'], ['u'])
        assert_equal(D['v'], 9)
        (P, D) = nx.goldberg_radzik(self.XG, 's')
        assert_equal(P['v'], 'u')
        assert_equal(D['v'], 9)

        G = nx.path_graph(4)
        assert_equal(nx.single_source_bellman_ford_path(G, 0),
                     {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]})
        assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)),
                     {0: 0, 1: 1, 2: 2, 3: 3})
        assert_equal(nx.single_source_bellman_ford(G, 0),
                     ({0: 0, 1: 1, 2: 2, 3: 3}, {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]}))
        assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0),
                     ({0: [None], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3}))
        assert_equal(nx.goldberg_radzik(G, 0),
                     ({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3}))
        assert_equal(nx.single_source_bellman_ford_path(G, 3),
                     {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]})
        assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 3)),
                     {0: 3, 1: 2, 2: 1, 3: 0})
        assert_equal(nx.single_source_bellman_ford(G, 3),
                     ({0: 3, 1: 2, 2: 1, 3: 0}, {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]}))
        assert_equal(nx.bellman_ford_predecessor_and_distance(G, 3),
                     ({0: [1], 1: [2], 2: [3], 3: [None]}, {0: 3, 1: 2, 2: 1, 3: 0}))
        assert_equal(nx.goldberg_radzik(G, 3),
                     ({0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0}))

        G = nx.grid_2d_graph(2, 2)
        dist, path = nx.single_source_bellman_ford(G, (0, 0))
        assert_equal(sorted(dist.items()),
                     [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
        assert_equal(sorted(path.items()),
                     [((0, 0), [(0, 0)]), ((0, 1), [(0, 0), (0, 1)]),
                      ((1, 0), [(0, 0), (1, 0)]),  ((1, 1), [(0, 0), (0, 1), (1, 1)])])
        pred, dist = nx.bellman_ford_predecessor_and_distance(G, (0, 0))
        assert_equal(sorted(pred.items()),
                     [((0, 0), [None]), ((0, 1), [(0, 0)]),
                      ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])])
        assert_equal(sorted(dist.items()),
                     [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
        pred, dist = nx.goldberg_radzik(G, (0, 0))
        assert_equal(sorted(pred.items()),
                     [((0, 0), None), ((0, 1), (0, 0)),
                      ((1, 0), (0, 0)), ((1, 1), (0, 1))])
        assert_equal(sorted(dist.items()),
                     [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
Example #9
0
 def test_path_graph(self):
     G = nx.path_graph(4)
     assert nx.single_source_bellman_ford_path(G, 0) == {
         0: [0],
         1: [0, 1],
         2: [0, 1, 2],
         3: [0, 1, 2, 3],
     }
     assert nx.single_source_bellman_ford_path_length(G, 0) == {
         0: 0,
         1: 1,
         2: 2,
         3: 3,
     }
     assert nx.single_source_bellman_ford(G, 0) == (
         {0: 0, 1: 1, 2: 2, 3: 3},
         {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]},
     )
     assert nx.bellman_ford_predecessor_and_distance(G, 0) == (
         {0: [], 1: [0], 2: [1], 3: [2]},
         {0: 0, 1: 1, 2: 2, 3: 3},
     )
     assert nx.goldberg_radzik(G, 0) == (
         {0: None, 1: 0, 2: 1, 3: 2},
         {0: 0, 1: 1, 2: 2, 3: 3},
     )
     assert nx.single_source_bellman_ford_path(G, 3) == {
         0: [3, 2, 1, 0],
         1: [3, 2, 1],
         2: [3, 2],
         3: [3],
     }
     assert nx.single_source_bellman_ford_path_length(G, 3) == {
         0: 3,
         1: 2,
         2: 1,
         3: 0,
     }
     assert nx.single_source_bellman_ford(G, 3) == (
         {0: 3, 1: 2, 2: 1, 3: 0},
         {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]},
     )
     assert nx.bellman_ford_predecessor_and_distance(G, 3) == (
         {0: [1], 1: [2], 2: [3], 3: []},
         {0: 3, 1: 2, 2: 1, 3: 0},
     )
     assert nx.goldberg_radzik(G, 3) == (
         {0: 1, 1: 2, 2: 3, 3: None},
         {0: 3, 1: 2, 2: 1, 3: 0},
     )
    def single_source_bydistance_coverage(self, infectG, subinfectG,
                                          true_source):

        # for node in list(infectG.nodes()):
        #     print(len(list(nx.neighbors(infectG,node))))
        #
        # print(nx.find_cycle(infectG))
        sort_dict = commons.partion_layer_dict(infectG, 10)  # 分层
        print('sort_list', sort_dict)
        node_cal = []
        for node in subinfectG:
            node_import = 0
            length_dict = nx.single_source_bellman_ford_path_length(
                subinfectG, node, weight='weight')
            for othernode, ditance in length_dict.items():
                lens_degree = len(list(nx.neighbors(infectG, othernode)))
                node_import += sort_dict[othernode] * lens_degree / (ditance +
                                                                     1)
            node_cal.append([node, node_import])
        sort_list = sorted(node_cal, key=lambda x: x[1], reverse=True)
        print(sort_list)
        # print('在的', [x[0] for x in sort_list[:100] if x[0] == true_source])
        # 只需要返回在你排序的集合中,源点在第几位就可以了。
        index_list = []
        print('sort_list', sort_list)
        print('true_list', true_source)
        for index in range(0, len(sort_list)):
            if true_source[0] == sort_list[index][0] or (
                    true_source[1] == sort_list[index][0]):
                index_list.append(index)

        return index_list
Example #11
0
 def test_single_source_shortest_path_length(self):
     ans = dict(nx.shortest_path_length(self.cycle, 0))
     assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
     assert ans == dict(nx.single_source_shortest_path_length(
         self.cycle, 0))
     ans = dict(nx.shortest_path_length(self.grid, 1))
     assert ans[16] == 6
     # now with weights
     ans = dict(nx.shortest_path_length(self.cycle, 0, weight="weight"))
     assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
     assert ans == dict(nx.single_source_dijkstra_path_length(
         self.cycle, 0))
     ans = dict(nx.shortest_path_length(self.grid, 1, weight="weight"))
     assert ans[16] == 6
     # weights and method specified
     ans = dict(
         nx.shortest_path_length(self.cycle,
                                 0,
                                 weight="weight",
                                 method="dijkstra"))
     assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
     assert ans == dict(nx.single_source_dijkstra_path_length(
         self.cycle, 0))
     ans = dict(
         nx.shortest_path_length(self.cycle,
                                 0,
                                 weight="weight",
                                 method="bellman-ford"))
     assert ans == {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}
     assert ans == dict(
         nx.single_source_bellman_ford_path_length(self.cycle, 0))
Example #12
0
 def path_length(v):
     if method == "unweighted":
         return nx.single_source_shortest_path_length(G, v)
     elif method == "dijkstra":
         return nx.single_source_dijkstra_path_length(G, v, weight=weight)
     elif method == "bellman-ford":
         return nx.single_source_bellman_ford_path_length(G, v, weight=weight)
Example #13
0
 def test_single_source_shortest_path_length(self):
     ans = dict(nx.shortest_path_length(self.cycle, 0))
     assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
     assert_equal(ans,
                  dict(nx.single_source_shortest_path_length(self.cycle,
                                                             0)))
     ans = dict(nx.shortest_path_length(self.grid, 1))
     assert_equal(ans[16], 6)
     # now with weights
     ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight'))
     assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
     assert_equal(ans, dict(nx.single_source_dijkstra_path_length(
         self.cycle, 0)))
     ans = dict(nx.shortest_path_length(self.grid, 1, weight='weight'))
     assert_equal(ans[16], 6)
     # weights and method specified
     ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight',
                                        method='dijkstra'))
     assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
     assert_equal(ans, dict(nx.single_source_dijkstra_path_length(
         self.cycle, 0)))
     ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight',
                                        method='bellman-ford'))
     assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
     assert_equal(ans, dict(nx.single_source_bellman_ford_path_length(
         self.cycle, 0)))
Example #14
0
 def single_source_bydistance_coverage(self, infectG, subinfectG,
                                       true_source):
     sort_dict = commons.partion_layer_dict(infectG, 10)  # 分层
     print('sort_list', sort_dict)
     node_cal = []
     for node in subinfectG:
         node_import = 0
         length_dict = nx.single_source_bellman_ford_path_length(
             infectG, source=node, weight='weight')
         #获取附近3层节点得覆盖率来计算某个点的重要性,越靠近中心,覆盖率越高。
         root = node
         edges = nx.bfs_edges(infectG, root, depth_limit=3)
         nodes = [root] + [v for u, v in edges]
         neihbor_h_len = len(nodes)
         count1 = 0
         for neihbor_h_node in nodes:
             if infectG.node[neihbor_h_node]['SI'] == 2:
                 count1 += 1
         node_import = count1 / neihbor_h_len
         # for neihbor_h in nodes:
         #     lens_degree = len(list(nx.neighbors(infectG, neihbor_h)))
         #     node_import += sort_dict[neihbor_h] * lens_degree/neihbor_h_len
         node_cal.append([node, node_import])
     sort_list = sorted(node_cal, key=lambda x: x[1], reverse=True)
     print(sort_list)
     # print('在的', [x[0] for x in sort_list[:100] if x[0] == true_source])
     #只需要返回在你排序的集合中,源点在第几位就可以了。
     for index in range(0, len(sort_list)):
         if true_source == sort_list[index][0]:
             return index
Example #15
0
 def test_single_source_shortest_path_length(self):
     ans = dict(nx.shortest_path_length(self.cycle, 0))
     assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
     assert_equal(ans,
                  dict(nx.single_source_shortest_path_length(self.cycle,
                                                             0)))
     ans = dict(nx.shortest_path_length(self.grid, 1))
     assert_equal(ans[16], 6)
     # now with weights
     ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight'))
     assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
     assert_equal(ans, dict(nx.single_source_dijkstra_path_length(
         self.cycle, 0)))
     ans = dict(nx.shortest_path_length(self.grid, 1, weight='weight'))
     assert_equal(ans[16], 6)
     # weights and method specified
     ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight',
                                        method='dijkstra'))
     assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
     assert_equal(ans, dict(nx.single_source_dijkstra_path_length(
         self.cycle, 0)))
     ans = dict(nx.shortest_path_length(self.cycle, 0, weight='weight',
                                        method='bellman-ford'))
     assert_equal(ans, {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
     assert_equal(ans, dict(nx.single_source_bellman_ford_path_length(
         self.cycle, 0)))
Example #16
0
    def correctness(self):
        #initialize the boolean value for testing Dijkstra's correctness
        boolean = True
        print("testing for correctness of Dijkstra...")
        #looping through graphs from my graphs and graphs by networkx
        for answer, my_graph in zip(self.test_list, self.compare_list):
            # if the graph has no nodes, break, automatically true
            if len(answer.nodes) > 0:
                #pick the smallest id to be source
                source = min(answer.nodes())
                #run networkx's dijkstra
                length, path = nx.single_source_dijkstra(answer,
                                                         source,
                                                         weight='weight')
                #run my dijkstra
                my_solution = Dijkstra(my_graph)
                dist, path = my_solution.solver(source)

                #getting rid of all the node that cannot be reached by the source
                for k, v in dist.items():
                    if v == float("inf"):
                        del dist[k]

                #testing for correctness
                boolean = boolean and dist == length

        if boolean:
            print("Dijkstra test passed")
        else:
            print("No")

        #initialize the boolean value for testing BF's correctness
        boolean = True
        print("testing for correctness of BF algorithm ...")
        #looping through graphs from my graphs and graphs by networkx
        for answer, my_graph in zip(self.test_list, self.compare_list):
            # if the graph has no nodes, break, automatically true
            if len(answer.nodes) > 0:
                #pick the smallest id to be source
                source = min(answer.nodes())
                #run networkx's Bellman_ford
                length = nx.single_source_bellman_ford_path_length(
                    answer, source, weight='weight')
                #run my Bellman_ford
                my_solution = Bellman_Ford(my_graph)
                dist, path = my_solution.solver(source)

                #getting rid of all the node that cannot be reached by the source
                for k, v in dist.items():
                    if v == float("inf"):
                        del dist[k]

                #correctness
                boolean = boolean and dist == length

        if boolean:
            print("Bellman_Ford test passed")
        else:
            print("No")
Example #17
0
 def test_single_node_graph(self):
     G = nx.DiGraph()
     G.add_node(0)
     assert nx.single_source_bellman_ford_path(G, 0) == {0: [0]}
     assert nx.single_source_bellman_ford_path_length(G, 0) == {0: 0}
     assert nx.single_source_bellman_ford(G, 0) == ({0: 0}, {0: [0]})
     assert nx.bellman_ford_predecessor_and_distance(G, 0) == ({0: []}, {0: 0})
     assert nx.goldberg_radzik(G, 0) == ({0: None}, {0: 0})
Example #18
0
 def test_single_node_graph(self):
     G = nx.DiGraph()
     G.add_node(0)
     assert_equal(nx.single_source_bellman_ford_path(G, 0), {0: [0]})
     assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0})
     assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0}, {0: [0]}))
     assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: []}, {0: 0}))
     assert_equal(nx.goldberg_radzik(G, 0), ({0: None}, {0: 0}))
Example #19
0
 def get_partion(self, subinfecG, two_center_list):
     node_twolist = [[], []]
     lengthA_dict = nx.single_source_bellman_ford_path_length(
         subinfecG, two_center_list[0], weight='weight')
     lengthB_dict = nx.single_source_bellman_ford_path_length(
         subinfecG, two_center_list[1], weight='weight')
     for node in list(subinfecG.nodes):
         if lengthA_dict[node] > lengthB_dict[node]:  # 这个点离b近一些。
             node_twolist[1].append(node)
         elif lengthA_dict[node] < lengthB_dict[node]:
             node_twolist[0].append(node)
         else:
             node_twolist[0].append(node)
             node_twolist[1].append(node)
     print('len(node_twolist[0]', len(node_twolist[0]))
     print('len(node_twolist[1]', len(node_twolist[1]))
     return node_twolist
Example #20
0
 def test_single_node_graph(self):
     G = nx.DiGraph()
     G.add_node(0)
     assert_equal(nx.single_source_bellman_ford_path(G, 0), {0: [0]})
     assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0})
     assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0}, {0: [0]}))
     assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: [None]}, {0: 0}))
     assert_equal(nx.goldberg_radzik(G, 0), ({0: None}, {0: 0}))
     assert_raises(nx.NodeNotFound, nx.bellman_ford_predecessor_and_distance, G, 1)
     assert_raises(nx.NodeNotFound, nx.goldberg_radzik, G, 1)
Example #21
0
 def path_length(v):
     if method == 'unweighted':
         return nx.single_source_shortest_path_length(G, v)
     elif method == 'dijkstra':
         return nx.single_source_dijkstra_path_length(G, v, weight=weight)
     elif method == 'bellman-ford':
         return nx.single_source_bellman_ford_path_length(G, v,
                                                          weight=weight)
     else:
         raise ValueError('method not supported: {}'.format(method))
Example #22
0
 def single_source_bydistance(self, subinfectG):
     node_cal = []
     for node in subinfectG:
         node_import = 0
         length_dict = nx.single_source_bellman_ford_path_length(
             subinfectG, node, weight='weight')
         for othernode, ditance in length_dict.items():
             node_import += ditance
         node_cal.append([node, node_import])
     sort_list = sorted(node_cal, key=lambda x: x[1])
     print(sort_list)
     return sort_list[0]
Example #23
0
 def test_path_graph(self):
     G = nx.path_graph(4)
     assert_equal(nx.single_source_bellman_ford_path(G, 0),
                  {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]})
     assert_equal(nx.single_source_bellman_ford_path_length(G, 0),
                  {0: 0, 1: 1, 2: 2, 3: 3})
     assert_equal(nx.single_source_bellman_ford(G, 0),
                  ({0: 0, 1: 1, 2: 2, 3: 3}, {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]}))
     assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0),
                  ({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3}))
     assert_equal(nx.goldberg_radzik(G, 0),
                  ({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3}))
     assert_equal(nx.single_source_bellman_ford_path(G, 3),
                  {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]})
     assert_equal(nx.single_source_bellman_ford_path_length(G, 3),
                  {0: 3, 1: 2, 2: 1, 3: 0})
     assert_equal(nx.single_source_bellman_ford(G, 3),
                  ({0: 3, 1: 2, 2: 1, 3: 0}, {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]}))
     assert_equal(nx.bellman_ford_predecessor_and_distance(G, 3),
                  ({0: [1], 1: [2], 2: [3], 3: []}, {0: 3, 1: 2, 2: 1, 3: 0}))
     assert_equal(nx.goldberg_radzik(G, 3),
                  ({0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0}))
Example #24
0
    def findPath_SingleTarget(self, startPoints, endPoint):
        dist = euclidean_distances([endPoint], self.gridPoints)
        self.targetConfigIdx = np.argmin(dist)
        dist = euclidean_distances(startPoints, self.gridPoints)
        self.startConfigIdx = np.argmin(dist, axis=1)

        allLength = dict(
            nx.single_source_bellman_ford_path_length(self.NX_G,
                                                      self.targetConfigIdx))

        queryLength = [allLength[i] for i in self.startConfigIdx]

        return queryLength
Example #25
0
def std_bellman_ford(graph, src_vertex):
    """
    From a given start vertex, finds the shortest paths to every other
    (reachable) vertex in the graph.

    graph: weighted graph
    src_vertex: source vertex

    return: Vector of computed distances
    """
    res = nx.single_source_bellman_ford_path_length(graph, src_vertex)

    return [dist for _, dist in sorted(res.items())]
Example #26
0
 def check_th7(g, c):  # O(V^3)
     bfg = nx.MultiDiGraph()
     bfg.add_weighted_edges_from([(e[1], e[0], w(g, e)) for e in g.edges])
     bfg.add_weighted_edges_from([
         (v, u, W[u, v] - 1) for u in g.nodes for v in g.nodes
         if (u, v) in W and (u, v) in D and D[u, v] > c
         and not (D[u, v] - d(g, v) > c or D[u, v] - d(g, u) > c)
     ])
     root = 'root'
     bfg.add_weighted_edges_from([(root, n, 0) for n in bfg.nodes])
     try:
         return nx.single_source_bellman_ford_path_length(bfg, root)
     except nx.exception.NetworkXUnbounded:
         return None
Example #27
0
 def test_others(self):
     assert_equal(nx.bellman_ford_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v'])
     assert_equal(nx.bellman_ford_path_length(self.XG, 's', 'v'), 9)
     assert_equal(nx.single_source_bellman_ford_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v'])
     assert_equal(nx.single_source_bellman_ford_path_length(self.XG, 's')['v'], 9)
     D, P = nx.single_source_bellman_ford(self.XG, 's', target='v')
     assert_equal(D, 9)
     assert_equal(P, ['s', 'x', 'u', 'v'])
     (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, 's')
     assert_equal(P['v'], ['u'])
     assert_equal(D['v'], 9)
     (P, D) = nx.goldberg_radzik(self.XG, 's')
     assert_equal(P['v'], 'u')
     assert_equal(D['v'], 9)
Example #28
0
 def test_others(self):
     assert_equal(nx.bellman_ford_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v'])
     assert_equal(nx.bellman_ford_path_length(self.XG, 's', 'v'), 9)
     assert_equal(nx.single_source_bellman_ford_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v'])
     assert_equal(nx.single_source_bellman_ford_path_length(self.XG, 's')['v'], 9)
     D, P = nx.single_source_bellman_ford(self.XG, 's', target='v')
     assert_equal(D, 9)
     assert_equal(P, ['s', 'x', 'u', 'v'])
     (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, 's')
     assert_equal(P['v'], ['u'])
     assert_equal(D['v'], 9)
     (P, D) = nx.goldberg_radzik(self.XG, 's')
     assert_equal(P['v'], 'u')
     assert_equal(D['v'], 9)
Example #29
0
 def test_others(self):
     assert nx.bellman_ford_path(self.XG, 's', 'v') == ['s', 'x', 'u', 'v']
     assert nx.bellman_ford_path_length(self.XG, 's', 'v') == 9
     assert nx.single_source_bellman_ford_path(self.XG, 's')['v'] == ['s', 'x', 'u', 'v']
     assert nx.single_source_bellman_ford_path_length(self.XG, 's')['v'] == 9
     D, P = nx.single_source_bellman_ford(self.XG, 's', target='v')
     assert D == 9
     assert P == ['s', 'x', 'u', 'v']
     (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, 's')
     assert P['v'] == ['u']
     assert D['v'] == 9
     (P, D) = nx.goldberg_radzik(self.XG, 's')
     assert P['v'] == 'u'
     assert D['v'] == 9
Example #30
0
    def test_not_connected(self):
        G = nx.complete_graph(6)
        G.add_edge(10, 11)
        G.add_edge(10, 12)
        assert_equal(nx.single_source_bellman_ford_path(G, 0),
                     {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]})
        assert_equal(nx.single_source_bellman_ford_path_length(G, 0),
                     {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
        assert_equal(nx.single_source_bellman_ford(G, 0),
                     ({0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
                      {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]}))
        assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0),
                     ({0: [], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0]},
                      {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
        assert_equal(nx.goldberg_radzik(G, 0),
                     ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
                      {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))

        # not connected, with a component not containing the source that
        # contains a negative cost cycle.
        G = nx.complete_graph(6)
        G.add_edges_from([('A', 'B', {'load': 3}),
                          ('B', 'C', {'load': -10}),
                          ('C', 'A', {'load': 2})])
        assert_equal(nx.single_source_bellman_ford_path(G, 0, weight='load'),
                     {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]})
        assert_equal(nx.single_source_bellman_ford_path_length(G, 0, weight='load'),
                     {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
        assert_equal(nx.single_source_bellman_ford(G, 0, weight='load'),
                     ({0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
                      {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]}))
        assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0, weight='load'),
                     ({0: [], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0]},
                      {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
        assert_equal(nx.goldberg_radzik(G, 0, weight='load'),
                     ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
                      {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
Example #31
0
    def test_not_connected(self):
        G = nx.complete_graph(6)
        G.add_edge(10, 11)
        G.add_edge(10, 12)
        assert_equal(nx.single_source_bellman_ford_path(G, 0),
                     {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]})
        assert_equal(nx.single_source_bellman_ford_path_length(G, 0),
                     {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
        assert_equal(nx.single_source_bellman_ford(G, 0),
                     ({0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
                      {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]}))
        assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0),
                     ({0: [None], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0]},
                      {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
        assert_equal(nx.goldberg_radzik(G, 0),
                     ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
                      {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))

        # not connected, with a component not containing the source that
        # contains a negative cost cycle.
        G = nx.complete_graph(6)
        G.add_edges_from([('A', 'B', {'load': 3}),
                          ('B', 'C', {'load': -10}),
                          ('C', 'A', {'load': 2})])
        assert_equal(nx.single_source_bellman_ford_path(G, 0, weight='load'),
                     {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]})
        assert_equal(nx.single_source_bellman_ford_path_length(G, 0, weight='load'),
                     {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
        assert_equal(nx.single_source_bellman_ford(G, 0, weight='load'),
                     ({0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
                      {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]}))
        assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0, weight='load'),
                     ({0: [None], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0]},
                      {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
        assert_equal(nx.goldberg_radzik(G, 0, weight='load'),
                     ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
                      {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
Example #32
0
    def produce_source(self, initG, source_number):
        #从某个树图中产生某个离边界点近的节点。
        #从0出发,找出最长的路径,然后取一半路径长度的为源点。

        length_dict = nx.single_source_bellman_ford_path_length(
            initG, 0, weight='weight')

        sort_list = sorted(length_dict.items(),
                           key=lambda x: x[1],
                           reverse=True)
        print('最长的为', sort_list[0][1])
        true_source = None
        for node, distance in sort_list:
            if distance == sort_list[0][1] // 2:
                true_source = node
        print('实验结果', length_dict[true_source])
        return [true_source]
Example #33
0
    def _bellman_ford_checker(self, clock: int):
        """
        Check if a legal retiming exists given a clock duration using Bellman Ford algorithm
        :param clock:
        :return: If the retiming is legal and the retiming to apply
        """
        feasibility_graph = nx.DiGraph()
        feasibility_graph.add_nodes_from(self.graph.nodes)

        # add first type of constraint from the original graph -> r(u) - r(v) <= w(e), so create arc v -> u
        feasibility_graph.add_weighted_edges_from([
            (target, source, weight[self._wire_delay])
            for (source, target, weight) in self.graph.edges.data()
        ])

        # add second type of constraint from the original graph: r(u) - r(v) <= W(u,v) - 1 if D(u,v) > c
        feasibility_graph.add_weighted_edges_from([
            (target, source, self.w[int(source)][int(target)] - 1)
            for (source, target) in
            #Do the nodes cartesian product
            list(
                itertools.product(feasibility_graph.nodes,
                                  feasibility_graph.nodes))
            if self.d[int(source)][int(target)] > clock
        ])
        # add extra node for Bellman Ford
        extra_node = 'extra_node'
        feasibility_graph.add_node(extra_node)
        # add extra edges from the extra node to all the other ones
        feasibility_graph.add_weighted_edges_from([
            (extra_node, node, 0) for node in self.graph.nodes
        ])

        try:
            retimings = nx.single_source_bellman_ford_path_length(
                G=feasibility_graph, source=extra_node)
            retimings.pop(extra_node)
            return True, np.array([
                x[1]
                for x in sorted(retimings.items(), key=lambda x: int(x[0]))
            ],
                                  dtype=int)
        except nx.exception.NetworkXUnbounded:
            print("Negative cost cycle detected for clock {}...".format(clock))
            return False, None
Example #34
0
 def single_source_bydistance_coverage_SECOND(self, infectG, subinfectG,
                                              true_source):
     sort_dict = commons.partion_layer_dict(infectG, 10)  # 分层
     print('sort_list', sort_dict)
     node_cal = []
     for node in subinfectG:
         node_import = 0
         length_dict = nx.single_source_bellman_ford_path_length(
             subinfectG, node, weight='weight')
         for othernode, ditance in length_dict.items():
             lens_degree = len(list(nx.neighbors(infectG, othernode)))
             node_import += sort_dict[othernode] * lens_degree / (ditance +
                                                                  1)
         node_cal.append([node, node_import])
     sort_list = sorted(node_cal, key=lambda x: x[1], reverse=True)
     print(sort_list)
     print('在的', [x[0] for x in sort_list[:200] if x[0] == true_source])
     return sort_list[0]
Example #35
0
 def test_others(self):
     assert nx.bellman_ford_path(self.XG, "s", "v") == ["s", "x", "u", "v"]
     assert nx.bellman_ford_path_length(self.XG, "s", "v") == 9
     assert nx.single_source_bellman_ford_path(self.XG, "s")["v"] == [
         "s",
         "x",
         "u",
         "v",
     ]
     assert nx.single_source_bellman_ford_path_length(self.XG, "s")["v"] == 9
     D, P = nx.single_source_bellman_ford(self.XG, "s", target="v")
     assert D == 9
     assert P == ["s", "x", "u", "v"]
     (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, "s")
     assert P["v"] == ["u"]
     assert D["v"] == 9
     (P, D) = nx.goldberg_radzik(self.XG, "s")
     assert P["v"] == "u"
     assert D["v"] == 9
Example #36
0
    def single_source_byQuality_centrality(self, infectG, subinfectG):
        #你好,再见
        for edge in infectG.edges:
            # G.add_edge(edge[0], edge[1], weight=1)
            randomnum = random.random()
            infectG.add_edge(edge[0],
                             edge[1],
                             weight=self.effectDistance(randomnum))
        m_list_add = [
            x for x in list(infectG.nodes()) if infectG.node[x]['SI'] == 2
        ]
        m_list_dif = [
            x for x in list(infectG.nodes()) if infectG.node[x]['SI'] == 1
        ]
        print('len(m_list_dif', len(m_list_add))
        print(subinfectG.number_of_nodes())
        len_add = len(m_list_add)
        len_dif = len(m_list_dif)
        CQ_dict = defaultdict(int)
        for node_temp in m_list_add:
            length_dict = nx.single_source_bellman_ford_path_length(
                infectG, source=node_temp, weight='weight')
            d_add_all = 0
            d_dif_all = 0
            d_dif_avg = 0
            d_add_avg = 0
            for add in m_list_add:
                d_dif_all += length_dict[add]
            for dif in m_list_dif:
                d_add_all += length_dict[dif]

            d_dif_avg = d_dif_all / len_dif
            d_add_avg = d_add_all / len_add
            CQ_dict[node_temp] = (d_dif_avg - d_add_avg) / d_add_avg

        CQ_dict_sort = sorted(CQ_dict.items(),
                              key=lambda x: x[1],
                              reverse=True)
        print('CQ_dict_sort', CQ_dict_sort)
        return CQ_dict_sort[0]
 def single_source_bydistance_coverage_SECOND(self, infectG, subinfectG,
                                              true_source):
     sort_dict = commons.partion_layer_dict(infectG, 10)  # 分层
     print('sort_list', sort_dict)
     node_cal = []
     for node in subinfectG:
         node_import = 0
         length_dict = nx.single_source_bellman_ford_path_length(
             subinfectG, node, weight='weight')
         for othernode, ditance in length_dict.items():
             lens_degree = len(list(nx.neighbors(infectG, othernode)))
             node_import += sort_dict[othernode] / (ditance + 1)
         node_cal.append([node, node_import])
     sort_list = sorted(node_cal, key=lambda x: x[1], reverse=True)
     print('sort_list', sort_list)
     print('true_list', true_source)
     index_list = []
     for index in range(0, len(sort_list)):
         if true_source[0] == sort_list[index][0] or (
                 true_source[1] == sort_list[index][0]):
             index_list.append(index)
     return index_list
Example #38
0
 def test_negative_weight_cycle(self):
     G = nx.cycle_graph(5, create_using=nx.DiGraph())
     G.add_edge(1, 2, weight=-7)
     for i in range(5):
         assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, i)
         assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, i)
         assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, i)
         assert_raises(nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, i)
         assert_raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, i)
     G = nx.cycle_graph(5)  # undirected Graph
     G.add_edge(1, 2, weight=-3)
     for i in range(5):
         assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, i)
         assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, i)
         assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, i)
         assert_raises(nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, i)
         assert_raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, i)
     G = nx.DiGraph([(1, 1, {'weight': -1})])
     assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, 1)
     assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, 1)
     assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, 1)
     assert_raises(nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, 1)
     assert_raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 1)
     # no negative cycle but negative weight
     G = nx.cycle_graph(5, create_using=nx.DiGraph())
     G.add_edge(1, 2, weight=-3)
     assert_equal(nx.single_source_bellman_ford_path(G, 0),
                  {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4]})
     assert_equal(nx.single_source_bellman_ford_path_length(G, 0),
                  {0: 0, 1: 1, 2: -2, 3: -1, 4: 0})
     assert_equal(nx.single_source_bellman_ford(G, 0),
                  ({0: 0, 1: 1, 2: -2, 3: -1, 4: 0},
                   {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4]}))
     assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0),
                  ({0: [], 1: [0], 2: [1], 3: [2], 4: [3]},
                   {0: 0, 1: 1, 2: -2, 3: -1, 4: 0}))
     assert_equal(nx.goldberg_radzik(G, 0),
                  ({0: None, 1: 0, 2: 1, 3: 2, 4: 3},
                   {0: 0, 1: 1, 2: -2, 3: -1, 4: 0}))