コード例 #1
0
ファイル: utilities.py プロジェクト: sidious1991/old_TH
def sortNodes(path, graph, comms, partition, type_sorting):
    
    if path is None and graph is None:
        return ()
    
    g = nx.read_gpickle(path) if path is not None else graph
    
    degrees_x = []
    degrees_y = []
    sorted_x = []
    sorted_y = []
    
    #in_degree     
    if type_sorting == 0:
        
        degrees_x = g.in_degree(comms[0]) #comm X -- to be ordered
        degrees_y = g.in_degree(comms[1]) #comm Y -- to be ordered
    
        sorted_x = sorted(degrees_x ,key=lambda tup: tup[1], reverse=True)
        sorted_y = sorted(degrees_y ,key=lambda tup: tup[1], reverse=True)
    
    #ratio
    elif type_sorting == 1:
        for i in comms[0]:
            degrees_x.append((i,g.in_degree(i)/(g.out_degree(i)+1)))
                    
        for j in comms[1]:
            degrees_y.append((j,g.in_degree(j)/(g.out_degree(j)+1)))
            
        sorted_x = sorted(degrees_x ,key=lambda tup: tup[1], reverse=True)
        sorted_y = sorted(degrees_y ,key=lambda tup: tup[1], reverse=True)
        
    #betweenness centrality
    elif type_sorting == 2:
        centrality_x = nx.betweenness_centrality_subset(g, comms[0], comms[1], normalized=True)
        centrality_y = nx.betweenness_centrality_subset(g, comms[1], comms[0], normalized=True)
    
        sorted_x = sorted([i for i in centrality_x.iteritems() if partition[i[0]] == 0], key=lambda (k,v):(v,k), reverse=False)
        sorted_y = sorted([i for i in centrality_y.iteritems() if partition[i[0]] == 1], key=lambda (k,v):(v,k), reverse=False)

    else:
        for i in comms[0]:
            degrees_x.append((i,AvgInDegree(i, g)))
            
        for j in comms[1]:
            degrees_y.append((j,AvgInDegree(j, g)))

        sorted_x = sorted(degrees_x ,key=lambda tup: tup[1], reverse=True)
        sorted_y = sorted(degrees_y ,key=lambda tup: tup[1], reverse=True)

    return (sorted_x, sorted_y)
コード例 #2
0
def bet_subset():

    graph = {
        "nodes": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        "edges": [[1, 2], [1, 4], [2, 3], [2, 5], [3, 4], [3, 6], [2, 7],
                  [3, 8], [7, 9], [5, 9], [9, 10], [10, 6]],
        "weights": [3, 4, 5, 6, 7, 8, 9, 10]
    }

    # G = nx.Graph()
    G = nx.DiGraph()
    G.add_nodes_from(graph['nodes'])
    G.add_edges_from(graph['edges'])
    source_nodes = [5, 7]
    target_nodes = [6]

    result = nx.betweenness_centrality_subset(G, source_nodes, target_nodes,
                                              False)

    print(result)
    # print(list(max(result.items(), key=lambda k: k[1])))
    # print(result.items())
    # print(max(result.items(), key=operator.itemgetter(1)))

    highest = max(result.values())
    print(highest)
    print([k for k, v in result.items() if v == highest])

    result = nx.edge_betweenness_centrality_subset(G, source_nodes,
                                                   target_nodes, False)
    print(result)

    highest = max(result.values())
    print(highest)
    print([k for k, v in result.items() if v == highest])
コード例 #3
0
ファイル: heuristic15.py プロジェクト: gold9598/PPGSM
def dummy_edge_mix_BC_weighted_choice(G,node_to_add,destination_node):
    #average degree
    D = list(map(lambda x : x[1], list(G.degree(G.nodes))))
    edge_to_add = int(np.mean(D)*0.5)
    DegreeDict = {};
    DummyDegreeDict = {};
    #calculate betweenness centrality.
    Bdict = nx.betweenness_centrality_subset(G,sources=set(G.nodes()),targets=set({destination_node}))
    B = []
    for key in Bdict.keys():
        B.append((key,Bdict[key]))
        DegreeDict[key] = G.degree[key];
        DummyDegreeDict[key] = 0;
    #Weighted k-sampling
    for dummy in range(0, node_to_add):
        Bdg = []
        for element in B:
            m = DegreeDict[element[0]]
            n = DummyDegreeDict[element[0]]
            Bdg.append((element[0],element[1]))
        target_nodes1 = random.choices(list(map(lambda x : x[0], Bdg)),weights=list(map(lambda x : x[1], Bdg)),k=edge_to_add)
        target_nodes2 = random.choices(list(map(lambda x : x[0], Bdg)),weights=list(map(lambda x : 1-x[1], Bdg)),k=edge_to_add)
        while len(list(set(target_nodes1).intersection(target_nodes2))) > 0:
            target_nodes1 = random.choices(list(map(lambda x : x[0], Bdg)),weights=list(map(lambda x : x[1], Bdg)),k=edge_to_add)
            target_nodes2 = random.choices(list(map(lambda x : x[0], Bdg)),weights=list(map(lambda x : 1-x[1], Bdg)),k=edge_to_add)
        target_nodes = target_nodes1+target_nodes2
        #add dummy node
        G.add_node(G.number_of_nodes())
        dummyNode = G.number_of_nodes()-1
        #add dummy edge
        for target in target_nodes:
            G.add_edge(target,dummyNode);
            G.add_edge(dummyNode,target);
            DummyDegreeDict[target]+=1;
コード例 #4
0
 def get_path_subgraph(self, sources, targets):
     """Return an induced subgraph of all paths connecting two sets of nodes.
     
     Parameters
     ----------
     sources : list
         A list of node names to be used as path sources.
         
     targets : list
         A list of node names to be used as path targets.
     
     Returns
     -------
     networkx.Graph
         An induced subgraph that contains all nodes and edges between ``sources`` and ``targets``.
     
     """
     bc = networkx.betweenness_centrality_subset(self,
                                                 sources=sources,
                                                 targets=targets)
     path_nodes = [
         key for key, value in bc.items()
         if value > 0 or key in sources or key in targets
     ]
     return (self.subgraph(path_nodes))
コード例 #5
0
def getNodeSpecBetweenness():
    global outfile
    global data
    global source
    global sink
    global distance
    global dist_mat
    weight = []
    sources = []
    sinks = []
    sinks.append(sink)
    for i in range(0, len(dist_mat[source])):
        if dist_mat[source, i] <= distance:
            sources.append(i)
    print "sources are: ", sources
    print "sinks are: ", sinks
    G = nx.from_numpy_matrix(data)
    for i in xrange(len(data)):
        for j in xrange(i + 1, len(data)):
            if (data[i, j] != 0):
                weight.append(data[i, j])

    G = nx.from_numpy_matrix(data)
    net = nx.betweenness_centrality_subset(G,
                                           sources=sources,
                                           targets=sinks,
                                           normalized=False,
                                           weight="weight")
    f = open(outfile, 'w')
    with open(outfile, 'w') as f:
        for key, value in net.items():
            f.write('%s %s\n' % (key, value))
コード例 #6
0
 def test_K5(self):
     """Betweenness centrality: K5"""
     G = networkx.complete_graph(5)
     b = betweenness_centrality_subset(G, sources=[0], targets=[1, 3], weighted_edges=False)
     b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #7
0
def choose_who_to_vaccinate(graph: networkx.Graph) -> List:
    people_to_vaccinate = []
    # T = networkx.algorithms.maximum_spanning_tree(graph)
    node2degree = dict(graph.degree)
    sorted_nodes = sorted(node2degree.items(),
                          key=lambda item: item[1],
                          reverse=True)[:100]
    l1 = [node[0] for node in sorted_nodes]
    g2 = graph.subgraph(l1)
    l2 = networkx.closeness_centrality(g2)
    sorted_by_closness = sorted(l2.items(),
                                key=lambda item: item[1],
                                reverse=True)[:70]
    l3 = [i[0] for i in sorted_by_closness]
    g3 = graph.subgraph(l3)
    contenders = networkx.betweenness_centrality_subset(g3,
                                                        l3,
                                                        l3,
                                                        normalized=True)
    sorted_nodes = sorted(contenders.items(),
                          key=lambda item: item[1],
                          reverse=True)[:50]
    people_to_vaccinate = [i[0] for i in sorted_nodes]
    patientsRand = []
    graph.remove_nodes_from(
        [n for n in graph if n in set(people_to_vaccinate)])
    for i in range(50):
        patientsRand.append(np.random.choice(graph.nodes()))
    # ICM(graph, patientsRand, 6)
    return people_to_vaccinate
コード例 #8
0
ファイル: hw1.py プロジェクト: aadame87/BigDataNetworks
def _betmap(G_normalized_weight_sources_tuple):
    """Pool for multiprocess only accepts functions with one argument.
    This function uses a tuple as its only argument. We use a named tuple for
    python 3 compatibility, and then unpack it when we send it to
    `betweenness_centrality_source`
    """
    return nx.betweenness_centrality_subset(*G_normalized_weight_sources_tuple)
コード例 #9
0
    def test_diamond_multi_path(self):
        """Betweenness Centrality Subset: Diamond Multi Path"""
        G = nx.Graph()
        G.add_edges_from([(1, 2), (1, 3), (1, 4), (1, 5), (1, 10), (10, 11),
                          (11, 12), (12, 9), (2, 6), (3, 6), (4, 6), (5, 7),
                          (7, 8), (6, 8), (8, 9)])
        b = nx.betweenness_centrality_subset(G,
                                             sources=[1],
                                             targets=[9],
                                             weight=None)

        expected_b = {
            1: 0,
            2: 1. / 10,
            3: 1. / 10,
            4: 1. / 10,
            5: 1. / 10,
            6: 3. / 10,
            7: 1. / 10,
            8: 4. / 10,
            9: 0,
            10: 1. / 10,
            11: 1. / 10,
            12: 1. / 10,
        }

        for n in sorted(G):
            assert_almost_equal(b[n], expected_b[n])
コード例 #10
0
 def test_P5_multiple_target(self):
     """Betweenness centrality: P5 multiple target"""
     G = networkx.Graph()
     G.add_path(range(5))
     b_answer = {0: 0, 1: 1, 2: 1, 3: 0.5, 4: 0, 5: 0}
     b = betweenness_centrality_subset(G, sources=[0], targets=[3, 4], weighted_edges=False)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
 def test_K5(self):
     """Betweenness Centrality Subset: K5"""
     G = nx.complete_graph(5)
     b = nx.betweenness_centrality_subset(G, sources=[0], targets=[1, 3],
                                          weight=None)
     b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n])
 def test_P5_multiple_target(self):
     """Betweenness Centrality Subset: P5 multiple target"""
     G = nx.Graph()
     nx.add_path(G, range(5))
     b_answer = {0: 0, 1: 1, 2: 1, 3: 0.5, 4: 0, 5: 0}
     b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3, 4],
                                          weight=None)
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n])
コード例 #13
0
 def test_box(self):
     """Betweenness centrality: box"""
     G = nx.Graph()
     G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
     b_answer = {0: 0, 1: 0.25, 2: 0.25, 3: 0}
     b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3],
                                          weight=None)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #14
0
 def test_box_and_path2(self):
     """Betweenness centrality: box and path multiple target"""
     G = nx.Graph()
     G.add_edges_from([(0, 1), (1, 2), (2, 3), (1, 20), (20, 3), (3, 4)])
     b_answer = {0: 0, 1: 1.0, 2: 0.5, 20: 0.5, 3: 0.5, 4: 0}
     b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3, 4],
                                          weight=None)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #15
0
    def most_important_nodes_edges_subset(self, graph, source_nodes, target_nodes, T=0, normalized=False, directed=False):

        cv=check_graph_validity.Graphs()
        ret = cv.is_valid_most_important_graph(graph, source_nodes, target_nodes,T)
        if(not ret[0]):
            ret.append({})
            print (ret)
            return ret
      
        try:
            # construct networkx graph from given graph
            if (directed):
                G=nx.DiGraph()
            else:    
                G = nx.Graph()
            G.add_nodes_from(graph['nodes'])
            G.add_edges_from(graph['edges'])

            if 'weights' in graph:
                for i in range(len(graph['edges'])):
                    G[graph['edges'][i][0]][graph['edges'][i][1]]['weight'] = graph['weights'][i]
        except Exception as e:
            return ["False", str(e),{}]

        output={}
        # clearDict={}
       
        result = None

        if (T == 0):
            
            result=nx.betweenness_centrality_subset(G, source_nodes, target_nodes, normalized, weight='weights')
            #remove nodes that are either in source_node or in target_node
            # for key,val in result.items():
            #     if (not(key in source_nodes or key in target_nodes)):
            #      clearDict[key]=val
            # print(clearDict)

            
        elif (T == 1):
            result =nx.edge_betweenness_centrality_subset(G, source_nodes, target_nodes, normalized, weight='weights')
            # for key,val in result.items():
            #      #remove nodes that are either in source_node or in target_node
            #     if(not(key[0] in source_nodes or key[0] in target_nodes or key[1] in source_nodes or key[1] in target_nodes)):
            #         clearDict[key]=val
            # print(clearDict)

        # output["betweenness_centrality"] = list(max(clearDict.items(), key=lambda k: k[1]))

        highest = max(result.values())
        nodes_list = [k for k, v in result.items() if v == highest]
        output["betweenness_centrality"] = [nodes_list,highest]    #result

        print (output)


        return [True, 'success', output]
コード例 #16
0
 def test_P5(self):
     """Betweenness centrality: P5"""
     G = nx.Graph()
     nx.add_path(G, range(5))
     b_answer = {0: 0, 1: 0.5, 2: 0.5, 3: 0, 4: 0, 5: 0}
     b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3],
                                          weight=None)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
 def test_box(self):
     """Betweenness Centrality Subset: box"""
     G = nx.Graph()
     G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
     b_answer = {0: 0, 1: 0.25, 2: 0.25, 3: 0}
     b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3],
                                          weight=None)
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n])
 def test_box_and_path2(self):
     """Betweenness Centrality Subset: box and path multiple target"""
     G = nx.Graph()
     G.add_edges_from([(0, 1), (1, 2), (2, 3), (1, 20), (20, 3), (3, 4)])
     b_answer = {0: 0, 1: 1.0, 2: 0.5, 20: 0.5, 3: 0.5, 4: 0}
     b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3, 4],
                                          weight=None)
     for n in sorted(G):
         assert almost_equal(b[n], b_answer[n])
コード例 #19
0
 def test_P5_multiple_target(self):
     """Betweenness Centrality Subset: P5 multiple target"""
     G = nx.Graph()
     nx.add_path(G, range(5))
     b_answer = {0: 0, 1: 1, 2: 1, 3: 0.5, 4: 0, 5: 0}
     b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3, 4],
                                          weight=None)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #20
0
 def test_P5_directed(self):
     """Betweenness Centrality Subset: P5 directed"""
     G = nx.DiGraph()
     nx.add_path(G, range(5))
     b_answer = {0: 0, 1: 1, 2: 1, 3: 0, 4: 0, 5: 0}
     b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3],
                                          weight=None)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #21
0
 def Btw(self, U, rho):
     max = -1
     node = 0
     btw = nx.betweenness_centrality_subset(self.G, U, self.G.nodes(),
                                            False, None)
     for u in U:
         if btw[u] > max:
             max = btw[u]
             node = u
     return node
コード例 #22
0
 def test_K5(self):
     """Betweenness centrality: K5"""
     G = networkx.complete_graph(5)
     b = betweenness_centrality_subset(G,
                                       sources=[0],
                                       targets=[1, 3],
                                       weighted_edges=False)
     b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #23
0
 def test_box(self):
     """Betweenness centrality: box"""
     G = networkx.Graph()
     G.add_edge(0, 1)
     G.add_edge(0, 2)
     G.add_edge(1, 3)
     G.add_edge(2, 3)
     b_answer = {0: 0, 1: 0.25, 2: 0.25, 3: 0}
     b = betweenness_centrality_subset(G, sources=[0], targets=[3], weighted_edges=False)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #24
0
 def test_P5_multiple_target(self):
     """Betweenness centrality: P5 multiple target"""
     G = networkx.Graph()
     G.add_path(list(range(5)))
     b_answer = {0: 0, 1: 1, 2: 1, 3: 0.5, 4: 0, 5: 0}
     b = betweenness_centrality_subset(G,
                                       sources=[0],
                                       targets=[3, 4],
                                       weighted_edges=False)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #25
0
 def test_box_and_path(self):
     """Betweenness Centrality Subset: box and path"""
     G = nx.Graph()
     G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (3, 4), (4, 5)])
     b_answer = {0: 0, 1: 0.5, 2: 0.5, 3: 0.5, 4: 0, 5: 0}
     b = nx.betweenness_centrality_subset(G,
                                          sources=[0],
                                          targets=[3, 4],
                                          weight=None)
     for n in sorted(G):
         assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
コード例 #26
0
 def test_P5(self):
     """Betweenness centrality: P5"""
     G = nx.Graph()
     nx.add_path(G, range(5))
     b_answer = {0: 0, 1: 0.5, 2: 0.5, 3: 0, 4: 0, 5: 0}
     b = betweenness_centrality_subset(G,
                                       sources=[0],
                                       targets=[3],
                                       weight=None)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #27
0
 def test_P5(self):
     """Betweenness Centrality Subset: P5"""
     G = nx.Graph()
     nx.add_path(G, range(5))
     b_answer = {0: 0, 1: 0.5, 2: 0.5, 3: 0, 4: 0, 5: 0}
     b = nx.betweenness_centrality_subset(G,
                                          sources=[0],
                                          targets=[3],
                                          weight=None)
     for n in sorted(G):
         assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
コード例 #28
0
 def test_box_and_path(self):
     """Betweenness centrality: box and path"""
     G = nx.Graph()
     G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (3, 4), (4, 5)])
     b_answer = {0: 0, 1: 0.5, 2: 0.5, 3: 0.5, 4: 0, 5: 0}
     b = nx.betweenness_centrality_subset(G,
                                          sources=[0],
                                          targets=[3, 4],
                                          weight=None)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
 def test_P5_directed(self):
     """Betweenness centrality: P5 directed"""
     G=networkx.DiGraph()
     G.add_path(list(range(5)))
     b_answer={0:0,1:1,2:1,3:0,4:0,5:0}
     b=betweenness_centrality_subset(G,
                                     sources=[0],
                                     targets=[3],
                                     weight=None)
     for n in sorted(G):
         assert_almost_equal(b[n],b_answer[n])
コード例 #30
0
def all_tftg_candidates(instance):
    nx_obj, dict_tf_comm, dict_tg_comm, tf_id, tg_id = instance[0], instance[1], instance[2], instance[3], instance[4]
    tfs, tgs = dict_tf_comm[tf_id], dict_tg_comm[tg_id]
    tfs_common, tgs_common = set(tfs).intersection(nx_obj.nodes()), set(tgs).intersection(nx_obj.nodes())
    dict_cent_allnodes=nx.betweenness_centrality_subset(nx_obj,tfs_common,tgs_common)
    set_nodes = set(pd.DataFrame.from_dict(dict_cent_allnodes,orient='index',columns=['paths']).loc[lambda x:x.paths !=0].index.to_list())
    nx_obj = nx_obj.subgraph(set_nodes.union(tfs).union(tgs)) ###########
    dict_res = {}
    li_li_edges = pd.DataFrame(nx_obj.edges).values.tolist()
    set_tup_edges = [(i1,i2) for i1,i2 in li_li_edges]
    dict_res[(tf_id,tg_id)] = set_tup_edges
    return dict_res
コード例 #31
0
def function(sample):
    pnm_params = {
        'data_path': r"Z:\Robert_TOMCAT_3_netcdf4_archives\for_PNM",
        # 'data_path': r"A:\Robert_TOMCAT_3_netcdf4_archives\processed_1200_dry_seg_aniso_sep",
        'sample': sample
        # 'sample': 'T3_100_7_III',
        # 'sample': 'T3_025_3_III',
        # 'sample': 'T3_300_8_III',
    }
    pnm = PNM(**pnm_params)
    graph = pnm.graph
    sourcesraw = np.unique(pnm.data['label_matrix'][:, :, 0])[1:]
    targetsraw = np.unique(pnm.data['label_matrix'][:, :, -1])[1:]
    sources = []
    targets = []
    for k in sourcesraw:
        if k in graph.nodes():
            sources.append(k)
    for k in targetsraw:
        if k in graph.nodes():
            targets.append(k)
    centrality = np.array(list(nx.betweenness_centrality(graph).values()))
    centrality2 = np.array(
        list(
            nx.betweenness_centrality_subset(graph,
                                             sources,
                                             targets,
                                             normalized=True).values()))
    centrality5 = np.array(
        list(
            nx.betweenness_centrality_source(graph, sources=sources).values()))
    waiting_times = np.zeros(len(centrality))
    vx = pnm.data.attrs['voxel']
    V = pnm.data['volume'].sum(dim='label')
    V0 = 0.95 * V.max()
    ref = V[V < V0].argmax()
    meanflux = (V0 * vx**3 / pnm.data['time'][ref])
    # meanflux = V[-1]*vx**3/pnm.data['time'][-1]
    meanflux = meanflux.data

    i = 0
    for node in graph.nodes():
        wt = 0
        nb = list(nx.neighbors(graph, node))
        if len(nb) > 0:
            t0 = pnm.data['sig_fit_data'].sel(label=node, sig_fit_var='t0 [s]')
            t0nb = pnm.data['sig_fit_data'].sel(label=nb, sig_fit_var='t0 [s]')
            upstream_nb = np.where(t0nb < t0)
            if len(upstream_nb[0]) > 0:
                wt = t0 - t0nb[upstream_nb].max()
        waiting_times[i] = wt
        i += 1
    return centrality, waiting_times, meanflux, centrality5, centrality2, sample
コード例 #32
0
 def all_tftg_candidates(nx_obj, tfs, tgs):
     tfs_common, tgs_common = set(tfs).intersection(nx_obj.nodes()), set(tgs).intersection(nx_obj.nodes())
     dict_cent_allnodes=nx.betweenness_centrality_subset(nx_obj,tfs_common,tgs_common)
     set_nodes = set(pd.DataFrame.from_dict(dict_cent_allnodes,orient='index',columns=['paths']).loc[lambda x:x.paths !=0].index.to_list()) ##########
     nx_obj = nx_obj.subgraph(set_nodes.union(tfs).union(tgs)) ###########
     dict_tftgs = nx.to_dict_of_lists(nx_obj)
     dict_tftgs_filtered ={}
     for key in dict_tftgs:
         if len(dict_tftgs[key])==0:
             continue
         else:
             dict_tftgs_filtered[key] = dict_tftgs[key]
     return nx_obj, dict_tftgs_filtered
コード例 #33
0
 def test_box_and_path2(self):
     """Betweenness centrality: box and path multiple target"""
     G = networkx.Graph()
     G.add_edge(0, 1)
     G.add_edge(1, 2)
     G.add_edge(2, 3)
     G.add_edge(1, 20)
     G.add_edge(20, 3)
     G.add_edge(3, 4)
     b_answer = {0: 0, 1: 1.0, 2: 0.5, 20: 0.5, 3: 0.5, 4: 0}
     b = betweenness_centrality_subset(G, sources=[0], targets=[3, 4])
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #34
0
 def test_box_and_path2(self):
     """Betweenness centrality: box and path multiple target"""
     G = networkx.Graph()
     G.add_edge(0, 1)
     G.add_edge(1, 2)
     G.add_edge(2, 3)
     G.add_edge(1, 20)
     G.add_edge(20, 3)
     G.add_edge(3, 4)
     b_answer = {0: 0, 1: 1.0, 2: 0.5, 20: 0.5, 3: 0.5, 4: 0}
     b = betweenness_centrality_subset(G, sources=[0], targets=[3, 4])
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
コード例 #35
0
    def prune(self,
              remove_singletons=True,
              trim_leaves=False,
              remove_placeholders=False,
              sources=None,
              targets=None):
        """Remove specific parts of the graph.
        
        Parameters
        ----------
        remove_singletons : bool, optional
            Should singletons be removed? [default: True]
            
        trim_leaves : bool, optional
            Iteratively remove all nodes with degree one, effectively
            keeping only nodes that are in cycles? [default: False]
        
        remove_placeholders : bool, optional
            Should placeholder nodes be removed? [default: False]
        
        sources, targets : list, optional
            Lists of node names. If provided, nodes that are not on any path
            between ``sources`` and ``targets`` will be removed. [default: None]
        
        """
        if remove_placeholders == True:
            self.remove_nodes_from(self.placeholders)

        if sources is not None and targets is not None:
            bc = networkx.betweenness_centrality_subset(self,
                                                        sources=sources,
                                                        targets=targets)
            remove_bc = [
                key for key, value in bc.items()
                if value == 0 and not key in sources and not key in targets
            ]
            self.remove_nodes_from(remove_bc)

        if trim_leaves:
            degrees = dict(self.degree())
            while 1 in degrees.values():
                for key, value in degrees.items():
                    if (value == 1):
                        self.remove_node(key)
                degrees = dict(self.degree())

        if remove_singletons:
            degrees = dict(self.degree())
            for key, value in degrees.items():
                if (value == 0):
                    self.remove_node(key)
コード例 #36
0
 def test_box(self):
     """Betweenness centrality: box"""
     G = networkx.Graph()
     G.add_edge(0, 1)
     G.add_edge(0, 2)
     G.add_edge(1, 3)
     G.add_edge(2, 3)
     b_answer = {0: 0, 1: 0.25, 2: 0.25, 3: 0}
     b = betweenness_centrality_subset(G,
                                       sources=[0],
                                       targets=[3],
                                       weighted_edges=False)
     for n in sorted(G):
         assert_almost_equal(b[n], b_answer[n])
 def test_box_and_path(self):
     """Betweenness centrality: box and path"""
     G=networkx.Graph()
     G.add_edge(0,1)
     G.add_edge(0,2)
     G.add_edge(1,3)
     G.add_edge(2,3)
     G.add_edge(3,4)
     G.add_edge(4,5)
     b_answer={0:0,1:0.5,2:0.5,3:0.5,4:0,5:0}
     b=betweenness_centrality_subset(G,
                                     sources=[0],
                                     targets=[3,4],
                                     weight=None)
     for n in sorted(G):
         assert_almost_equal(b[n],b_answer[n])
コード例 #38
0
def getNodeSpecBetweenness():
    global outfile
    global data
    global sources
    global sinks
    weight = []
    G=nx.from_numpy_matrix(data)
    for i in xrange(len(data)):
        for j in xrange(i+1,len(data)):
            if(data[i,j] != 0):
                weight.append(data[i,j])

    G=nx.from_numpy_matrix(data)
    net=nx.betweenness_centrality_subset(G,sources=sources,targets=sinks,normalized=False,weight="weight")
    f=open(outfile, 'w')
    with open(outfile, 'w') as f:
        for key, value in net.items():
            f.write('%s %s\n' % (key, value))
コード例 #39
0
    def test_diamond_multi_path(self):
        """Betweenness Centrality Subset: Diamond Multi Path"""
        G = nx.Graph()
        G.add_edges_from([
            (1,2), 
            (1,3), 
            (1,4), 
            (1,5), 
            (1,10), 
            (10,11), 
            (11,12), 
            (12,9), 
            (2,6), 
            (3,6), 
            (4,6), 
            (5,7), 
            (7,8), 
            (6,8), 
            (8,9)
        ])
        b = nx.betweenness_centrality_subset(
            G,
            sources=[1],
            targets=[9],
            weight=None
        )

        expected_b = {
        1: 0,
        2: 1./10,
        3: 1./10,
        4: 1./10,
        5: 1./10,
        6: 3./10,
        7:1./10,
        8:4./10,
        9:0,
        10:1./10,
        11:1./10,
        12:1./10,
        }

        for n in sorted(G):
            assert_almost_equal(b[n], expected_b[n])
コード例 #40
0
ファイル: algorithms.py プロジェクト: eriknw/metagraph-1
 def nx_betweenness_centrality(
     graph: NetworkXGraph,
     nodes: mg.Optional[PythonNodeSet],
     normalize: bool,
     # include_endpoints: bool,
 ) -> PythonNodeMap:
     if nodes is None:
         sources = targets = graph.value.nodes
     else:
         sources = targets = nodes.value
     node_to_score_map = nx.betweenness_centrality_subset(
         graph.value,
         sources=sources,
         targets=targets,
         normalized=normalize,
         weight=graph.edge_weight_label,
         # endpoints=include_endpoints,
     )
     return PythonNodeMap(node_to_score_map, )
コード例 #41
0
def betweeness_centrality_subset():

    nodes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    edges_sources = [[1, 2], [1, 3], [3, 4], [4, 5], [5, 6], [6, 7]]
    edges_targets = [[8, 9], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15],
                     [10, 13], [9, 15], [8, 14]]
    edges_interconnections = [[4, 8], [6, 10], [7, 14]
                              ]  # Connection between source and target nodes

    edges = []

    G = nx.Graph()
    G.add_nodes_from(nodes)
    G.add_edges_from(edges_sources)
    G.add_edges_from(edges_targets)
    G.add_edges_from(edges_interconnections)

    # print(G.edges)

    result = nx.betweenness_centrality_subset(G, [1, 2, 3, 4, 5],
                                              [1, 13, 14, 15])
    print(result)
    result = nx.betweenness_centrality_subset(G, [
        1,
        2,
        3,
    ], [13, 14, 15])
    print(result)
    result = nx.edge_betweenness_centrality_subset(G, [1, 2, 3, 4, 5],
                                                   [12, 13, 14, 15])
    print(result)

    print('--------------------------')

    nodes = [1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15]
    edges_sources = [[1, 2], [1, 3], [3, 4], [4, 6], [6, 7]]  # 5 removed here
    edges_targets = [[8, 9], [10, 11], [11, 13], [13, 14], [14, 15], [10, 13],
                     [9, 15], [8, 14]]  # 12 removed here
    edges_interconnections = [[4, 8], [6, 10], [7, 14]
                              ]  # Connection between source and target nodes

    edges = []

    G = nx.Graph()
    G.add_nodes_from(nodes)
    G.add_edges_from(edges_sources)
    G.add_edges_from(edges_targets)
    G.add_edges_from(edges_interconnections)

    # print(G.edges)

    result = nx.betweenness_centrality_subset(G, [1, 2, 3, 4, 5], [13, 14, 15])
    print(result)
    result = nx.betweenness_centrality_subset(G, [1, 2, 3, 4], [13, 14, 15])
    print(result)
    result = nx.edge_betweenness_centrality_subset(G, [1, 2, 3, 4, 5],
                                                   [12, 13, 14, 15])
    print(result)

    print('-------------------------')
    print(G.edges)
    G[1][2]['weight'] = 0.8
    G[1][2]['weightre'] = 0.83
    print(G[1][2])