def test_participation():
    W = np.eye(3)
    ci = np.array([1, 1, 2])

    assert np.allclose(bct.participation_coef(W, ci), [0, 0, 0])
    assert np.allclose(bct.participation_coef_sign(W, ci)[0], [0, 0, 0])

    W = np.ones((3, 3))
    assert np.allclose(bct.participation_coef(W, ci), [
                       0.44444444, 0.44444444, 0.44444444])
    assert np.allclose(bct.participation_coef_sign(W, ci)[0], [
                       0.44444444, 0.44444444, 0.44444444])

    W = np.eye(3)
    W[0, 1] = 1
    W[0, 2] = 1
    assert np.allclose(bct.participation_coef(W, ci), [0.44444444, 0, 0])
    assert np.allclose(bct.participation_coef_sign(W, ci)
                       [0], [0.44444444, 0, 0])

    W = np.eye(3)
    W[0, 1] = -1
    W[0, 2] = -1
    W[1, 2] = 1
    assert np.allclose(bct.participation_coef_sign(W, ci)[0], [0.,  0.5,  0.])
def participation_test():
    W = np.eye(3)
    ci = np.array([1, 1, 2])

    assert np.allclose(bct.participation_coef(W, ci), [0, 0, 0])
    assert np.allclose(bct.participation_coef_sign(W, ci)[0], [0, 0, 0])

    W = np.ones((3, 3))
    assert np.allclose(bct.participation_coef(W, ci), [
                       0.44444444, 0.44444444, 0.44444444])
    assert np.allclose(bct.participation_coef_sign(W, ci)[0], [
                       0.44444444, 0.44444444, 0.44444444])

    W = np.eye(3)
    W[0, 1] = 1
    W[0, 2] = 1
    assert np.allclose(bct.participation_coef(W, ci), [0.44444444, 0, 0])
    assert np.allclose(bct.participation_coef_sign(W, ci)
                       [0], [0.44444444, 0, 0])

    W = np.eye(3)
    W[0, 1] = -1
    W[0, 2] = -1
    W[1, 2] = 1
    assert np.allclose(bct.participation_coef_sign(W, ci)[0], [0.,  0.5,  0.])
 def calculate_communities(self, reorder=False, **kwargs):
     assert self.community_alg is not None, \
         print("Community algorithm has not been set!")
     G = self.G
     graph_mat = self.graph_mat
     # calculate community structure
     comm, mod = self.community_alg(graph_mat, **kwargs)
     # if there is a reference, relabel communities based on their closest association
     if self.ref_community:
         comm = self._relabel_community(comm, self.ref_community)
     # label vertices of G
     G.vs['community'] = comm
     G.vs['within_module_degree'] = bct.module_degree_zscore(
         graph_mat, comm)
     if np.min(graph_mat) < 0:
         participation_pos, participation_neg = bct.participation_coef_sign(
             graph_mat, comm)
         G.vs['part_coef_pos'] = participation_pos
         G.vs['part_coef_neg'] = participation_neg
     else:
         G.vs['part_coef'] = bct.participation_coef(graph_mat, comm)
     if reorder:
         self.reorder()
     # calculate subgraph (within-community) characteristics
     self._subgraph_analysis()
     return mod
 def calculate_communities(self, reorder=False, **kwargs):
     assert self.community_alg is not None, \
         print("Community algorithm has not been set!")
     G = self.G
     graph_mat = self.graph_mat
     # calculate community structure
     comm, mod = self.community_alg(graph_mat, **kwargs)
     # if there is a reference, relabel communities based on their closest association    
     if self.ref_community:
         comm = self._relabel_community(comm,self.ref_community)
     # label vertices of G
     G.vs['community'] = comm
     G.vs['within_module_degree'] = bct.module_degree_zscore(graph_mat,comm)
     if np.min(graph_mat) < 0:
         participation_pos, participation_neg = bct.participation_coef_sign(graph_mat, comm)
         G.vs['part_coef_pos'] = participation_pos
         G.vs['part_coef_neg'] = participation_neg
     else:
         G.vs['part_coef'] = bct.participation_coef(graph_mat, comm)
     if reorder:
         self.reorder()
     # calculate subgraph (within-community) characteristics
     self._subgraph_analysis()
     return mod
    ciN = a.assignbctResult(ci[0])
    extras.writeResults(QWt, "QWt", ofbT, propDict=propDict, append=appValT)
    extras.writeResults(ciN, "ciWt", ofbT, propDict=propDict, append=appValT)
    del QWt
    
    nMWt = len(np.unique(ci[0]))
    nM[n] = nMWt
    extras.writeResults(nMWt, "nMWt", ofbT, propDict=propDict, append=appValT)
    del(nMWt)

    wmdWt = extras.withinModuleDegree(a.G, ciN, weight='weight')
    wmd[:,n] = [wmdWt[v] for v in a.G.nodes()]
    extras.writeResults(wmdWt, "wmdWt", ofbT, propDict=propDict, append=appValT)
    del wmdWt
    
    pcCentWt = bct.participation_coef_sign(a.bctmat,ci[0])
    pcCent[:,n] = pcCentWt
    pcCentWt = a.assignbctResult(pcCentWt)
    extras.writeResults(pcCentWt, "pcCentWt", ofbT, propDict=propDict, append=appValT)
    
#    # infomap partitioning
#    bIM = infomap.nx2infomap(a.G)
#    del(bIM)
#    f = open("nxdigraph.clu", "r") # recapture results from output file
#    modules = mbt.np.array([int(v.strip('\n')) for v in f.readlines()[1:]])
#    f.close()
#    remove("nxdigraph.clu")
#    
#    ciNIM = a.assignbctResult(modules)
#    QIMWt = community.modularity(ciNIM, a.G)
#    QIM[n] = QIMWt
Example #6
0
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, [args.in_length_matrix, args.in_conn_matrix])

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    if not args.append_json:
        assert_outputs_exist(parser, args, args.out_json)
    else:
        logging.debug('Using --append_json, make sure to delete {} '
                      'before re-launching a group analysis.'.format(
                          args.out_json))

    if args.append_json and args.overwrite:
        parser.error('Cannot use the append option at the same time as '
                     'overwrite.\nAmbiguous behavior, consider deleting the '
                     'output json file first instead.')

    conn_matrix = load_matrix_in_any_format(args.in_conn_matrix)
    len_matrix = load_matrix_in_any_format(args.in_length_matrix)

    if args.filtering_mask:
        mask_matrix = load_matrix_in_any_format(args.filtering_mask)
        conn_matrix *= mask_matrix
        len_matrix *= mask_matrix
    N = len_matrix.shape[0]

    if args.avg_node_wise:
        func_cast = avg_cast
    else:
        func_cast = list_cast

    gtm_dict = {}
    betweenness_centrality = bct.betweenness_wei(len_matrix) / ((N - 1) *
                                                                (N - 2))
    gtm_dict['betweenness_centrality'] = func_cast(betweenness_centrality)
    ci, gtm_dict['modularity'] = bct.modularity_louvain_und(conn_matrix,
                                                            seed=0)

    gtm_dict['assortativity'] = bct.assortativity_wei(conn_matrix, flag=0)
    gtm_dict['participation'] = func_cast(
        bct.participation_coef_sign(conn_matrix, ci)[0])
    gtm_dict['clustering'] = func_cast(bct.clustering_coef_wu(conn_matrix))

    gtm_dict['nodal_strength'] = func_cast(bct.strengths_und(conn_matrix))
    gtm_dict['local_efficiency'] = func_cast(
        bct.efficiency_wei(len_matrix, local=True))
    gtm_dict['global_efficiency'] = func_cast(bct.efficiency_wei(len_matrix))
    gtm_dict['density'] = func_cast(bct.density_und(conn_matrix)[0])

    # Rich club always gives an error for the matrix rank and gives NaN
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        tmp_rich_club = bct.rich_club_wu(conn_matrix)
    gtm_dict['rich_club'] = func_cast(tmp_rich_club[~np.isnan(tmp_rich_club)])

    # Path length gives an infinite distance for unconnected nodes
    # All of this is simply to fix that
    empty_connections = np.where(np.sum(len_matrix, axis=1) < 0.001)[0]
    if len(empty_connections):
        len_matrix = np.delete(len_matrix, empty_connections, axis=0)
        len_matrix = np.delete(len_matrix, empty_connections, axis=1)

    path_length_tuple = bct.distance_wei(len_matrix)
    gtm_dict['path_length'] = func_cast(path_length_tuple[0])
    gtm_dict['edge_count'] = func_cast(path_length_tuple[1])

    if not args.avg_node_wise:
        for i in empty_connections:
            gtm_dict['path_length'].insert(i, -1)
            gtm_dict['edge_count'].insert(i, -1)

    if args.small_world:
        gtm_dict['omega'], gtm_dict['sigma'] = omega_sigma(len_matrix)

    if os.path.isfile(args.out_json) and args.append_json:
        with open(args.out_json) as json_data:
            out_dict = json.load(json_data)
        for key in gtm_dict.keys():
            if isinstance(out_dict[key], list):
                out_dict[key].append(gtm_dict[key])
            else:
                out_dict[key] = [out_dict[key], gtm_dict[key]]
    else:
        out_dict = {}
        for key in gtm_dict.keys():
            out_dict[key] = [gtm_dict[key]]

    with open(args.out_json, 'w') as outfile:
        json.dump(out_dict,
                  outfile,
                  indent=args.indent,
                  sort_keys=args.sort_keys)
Example #7
0
def calc_graph_vector(filename, thresholds) :
    '''
    This function calculates graph measures for connectivity matrix loaded from textfile
    and save results under the same name with additional superscript +'_GV' (in same dir
    filename is located)
    
    Input arguments:                                               
        filename(str):     name of file containing connectivity matrix (txt extension)
        thresholds(list):  list containing thresholds of interest        #
    
    Kamil Bonna, 14.08.2018 
    '''
    #--- check inputs
    import os
    if not os.path.exists(filename):
        raise Exception('{} does not exist'.format(filename))
    if type(thresholds) != list: 
        raise Exception('thresholds should be a list!')
        
    import numpy as np
    import bct

    #=== inner variables
    N_rep_louvain = 10   # number of Louvain algorithm repetitions
    N_measures = 10      # number of graph measures
    gamma = 1            # Louvain resolution parameter
    
    #--- load matrix 
    A_raw = np.loadtxt(filename)
    N = A_raw.shape[0]   # number of nodes
    M_sat = N*(N-1)/2    # max number of connections 

    #=== calculate output
    graph_measures = np.zeros([ len(thresholds), N_measures ])  # create empty output matrix
    for thr in range(len(thresholds)) : 
        #--- thresholding 
        A = bct.threshold_proportional( A_raw, p=thresholds[thr], copy=True );
        A[np.nonzero(A<0)] = 0                                  # ensure only positive weights
        M_act = A[np.nonzero(A>0)].shape[0] / 2                 # actual number of nonzero connections
        #--- calculate measures
        #-- mean connection strenght 
        S = np.sum(A)/M_act
        #-- connection strenght std
        Svar = np.std(A[np.nonzero(A)])
        #-- modularity
        [M,Q] = bct.modularity_louvain_und(A, gamma)
        for i in range(N_rep_louvain) :
            [Mt,Qt] = bct.modularity_louvain_und(A, gamma)
            if Qt > Q :
                Q = Qt
                M = Mt
        #-- participation coefficient
        P = np.mean(bct.participation_coef_sign(A, M))
        #-- clustering 
        C = np.mean(bct.clustering_coef_wu(A))
        #-- transitivity 
        T = bct.transitivity_wu(A)
        #-- assortativity
        Asso = bct.assortativity_wei(A)
        #-- global & local efficiency 
        Eglo = bct.efficiency_wei(A)
        Eloc = np.mean(bct.efficiency_wei(A, local=True))
        #-- mean eigenvector centralit
        Eig = np.mean(bct.eigenvector_centrality_und(A))
        #--- write vector to matrix
        graph_measures[thr] = [ S, Svar, Q, P, C, T, Asso, Eglo, Eloc, Eig ]

    #=== save results to file
    np.savetxt( filename[:-4]+'_GV.txt', graph_measures )