Exemple #1
0
    def test_directed_laplacian(self):
        "Directed Laplacian"
        # Graph used as an example in Sec. 4.1 of Langville and Meyer,
        # "Google's PageRank and Beyond". The graph contains dangling nodes, so
        # the pagerank random walk is selected by directed_laplacian
        G = nx.DiGraph()
        G.add_edges_from(((1,2), (1,3), (3,1), (3,2), (3,5), (4,5), (4,6),
                          (5,4), (5,6), (6,4)))
        GL = numpy.array([[ 0.9833, -0.2941, -0.3882, -0.0291, -0.0231, -0.0261],
                          [-0.2941,  0.8333, -0.2339, -0.0536, -0.0589, -0.0554],
                          [-0.3882, -0.2339,  0.9833, -0.0278, -0.0896, -0.0251],
                          [-0.0291, -0.0536, -0.0278,  0.9833, -0.4878, -0.6675],
                          [-0.0231, -0.0589, -0.0896, -0.4878,  0.9833, -0.2078],
                          [-0.0261, -0.0554, -0.0251, -0.6675, -0.2078,  0.9833]])
        assert_almost_equal(nx.directed_laplacian_matrix(G, alpha=0.9), GL, decimal=3)

        # Make the graph strongly connected, so we can use a random and lazy walk
        G.add_edges_from((((2,5), (6,1))))
        GL = numpy.array([[ 1.    , -0.3062, -0.4714,  0.    ,  0.    , -0.3227],
                          [-0.3062,  1.    , -0.1443,  0.    , -0.3162,  0.    ],
                          [-0.4714, -0.1443,  1.    ,  0.    , -0.0913,  0.    ],
                          [ 0.    ,  0.    ,  0.    ,  1.    , -0.5   , -0.5   ],
                          [ 0.    , -0.3162, -0.0913, -0.5   ,  1.    , -0.25  ],
                          [-0.3227,  0.    ,  0.    , -0.5   , -0.25  ,  1.    ]])
        assert_almost_equal(nx.directed_laplacian_matrix(G, walk_type='random'), GL, decimal=3)

        GL = numpy.array([[ 0.5   , -0.1531, -0.2357,  0.    ,  0.    , -0.1614],
                          [-0.1531,  0.5   , -0.0722,  0.    , -0.1581,  0.    ],
                          [-0.2357, -0.0722,  0.5   ,  0.    , -0.0456,  0.    ],
                          [ 0.    ,  0.    ,  0.    ,  0.5   , -0.25  , -0.25  ],
                          [ 0.    , -0.1581, -0.0456, -0.25  ,  0.5   , -0.125 ],
                          [-0.1614,  0.    ,  0.    , -0.25  , -0.125 ,  0.5   ]])
        assert_almost_equal(nx.directed_laplacian_matrix(G, walk_type='lazy'), GL, decimal=3)
    def get_graph_laplacian(self,
                            edge_types: list,
                            node_list=None,
                            databases=None):
        """
        Returns an adjacency matrix from edges with type specified in :param edge_types: and nodes specified in
        :param edge_types: A list of edge types letter codes in ["d", "u", "u_n"]
        :param node_list: A list of node names
        :return: A csr_matrix sparse adjacency matrix
        """
        if "d" in edge_types:
            directed = True
        elif "u" in edge_types:
            directed = False
        else:
            raise Exception("edge_types must be either 'd' or 'u'")

        if hasattr(self, "laplacian_adj"):
            laplacian_adj = self.laplacian_adj

        else:
            if databases is not None:
                if directed:
                    edge_list = [
                        (u, v)
                        for u, v, d in self.G.edges(nbunch=self.node_list,
                                                    data=True)
                        if 'database' in d and d['database'] in databases
                    ]
                    laplacian_adj = nx.directed_laplacian_matrix(
                        nx.DiGraph(incoming_graph_data=edge_list),
                        nodelist=self.node_list)
                else:
                    edge_list = [(u, v) for u, v, d in self.G_u.edges(
                        nbunch=self.node_list, data=True)
                                 if d['type'] in edge_types]
                    laplacian_adj = nx.normalized_laplacian_matrix(
                        nx.Graph(incoming_graph_data=edge_list),
                        nodelist=self.node_list)
            elif directed:
                laplacian_adj = nx.directed_laplacian_matrix(
                    self.G.subgraph(nodes=self.node_list),
                    nodelist=self.node_list)
            elif not directed:
                laplacian_adj = nx.normalized_laplacian_matrix(
                    self.G_u.subgraph(nodes=self.node_list),
                    nodelist=self.node_list)
            else:
                raise Exception()
            self.laplacian_adj = laplacian_adj

        if node_list is None or node_list == self.node_list:
            return laplacian_adj
        elif set(node_list) <= set(self.node_list):
            return self.slice_adj(laplacian_adj, node_list, None)
        elif not (set(node_list) < set(self.node_list)):
            raise Exception("A node in node_l is not in self.node_list.")

        return laplacian_adj
def compute(tribes, adj_matrix, conv, precision):
    import networkx as nx

    spectra = []
    pbar = progressbar.ProgressBar()

    for tribe in pbar(tribes):
        tribe_ids = conv.indices(tribe)
        adj_submat = adj_matrix[np.ix_(tribe_ids, tribe_ids)]
        G = nx.from_scipy_sparse_matrix(adj_submat, create_using=nx.DiGraph)

        # Find the largest connected component of the graph
        largest = max(nx.strongly_connected_components(G), key=len)
        if len(largest) <= 2:  # Needs at least a certain size...
            spectra.append([])
        else:
            # Compute the Chung's laplacian matrix of tribe's largest connected component
            L = nx.directed_laplacian_matrix(G.subgraph(largest))

            # Find the eigenvalues
            eig = scipy.linalg.eig(L)[0]

            # Order the non-zero eigenvalues and round to desired precision
            spectrum = np.unique(np.round(eig[np.nonzero(eig)], precision))
            spectra.append(spectrum)
            
    return spectra
Exemple #4
0
def directed_heat_kernel(G, t):
    # Input: DiGraph G and time parameter t
    # Output: heat kernel matrix
    # Automatically computes directed laplacian matrix and then exponentiates

    L = np.asarray(nx.directed_laplacian_matrix(G))
    lam, phi = np.linalg.eigh(L)
    return heat_kernel(lam, phi, t)
Exemple #5
0
    def do(self):
        logger.info("SPECTRAL Eigenvalues %i" % (self.spectral_eigenvalues, ))
        logger.info("SPECTRAL Dimensions %i" % (self.spectral_dimensions,))
        logger.info("SPECTRAL Laplacian %i" % (self.spectral_laplacian,))
        logger.info("SPECTRAL Eigenvector %i" % (self.spectral_eigenvector,))

        logger.info("SPECTRAL Compute Neuron Graph")
        neuron_graph = self.database.db2graph()

        logger.info("SPECTRAL Compute Laplacian Matrix")
        if self.spectral_laplacian == Config.SPECTRAL_LAPLACIAN_DIRECTED:
            neuron_graph_laplacian = networkx.directed_laplacian_matrix(neuron_graph, weight=None,
                                                                        walk_type='pagerank', alpha=0.95)
        elif self.spectral_laplacian == Config.SPECTRAL_LAPLACIAN_UNDIRECTED:
            neuron_graph = neuron_graph.to_undirected()
            neuron_graph_laplacian = networkx.normalized_laplacian_matrix(neuron_graph, weight=None)
        else:
            logger.critical("SPECTRAL Laplacian Method not supported")
            raise RuntimeError()

        logger.info("SPECTRAL Compute Lapalcian Eigenvectors")
        if self.spectral_eigenvector == Config.EIGENVECTOR_LEFT:
            eigenvalues, eigenvectors = scipy.sparse.linalg.eigen.arpack.eigs(neuron_graph_laplacian,
                                                                              self.spectral_eigenvalues,
                                                                              sigma=0, which='LM')
        elif self.spectral_eigenvector == Config.EIGENVECTOR_RIGHT:
            eigenvalues, eigenvectors = scipy.sparse.linalg.eigen.arpack.eigs(neuron_graph_laplacian,
                                                                              self.spectral_eigenvalues)
        else:
            logger.critical("SPECTRAL Eigenvector direction not supported")
            raise RuntimeError()

        points = eigenvectors.real[:, :self.spectral_dimensions]

        database_session = self.database.new_session()
        db_populations = {p.id: p for p in
                          database_session.query(orm.population.Population).filter_by(shadow=False).all()}

        self.data = dict()
        for neuron, neuron_data in neuron_graph.nodes_iter(data=True):
            pop_id = neuron_data['p']
            
            if pop_id not in self.data .keys():
                self.data[pop_id] = dict()
                self.data[pop_id]['label'] = db_populations[pop_id].label
                self.data[pop_id]['neurons'] = db_populations[pop_id].neurons
                self.data[pop_id]['neurons_core'] = db_populations[pop_id].neurons_core
                self.data[pop_id]['space'] = dict()
                self.data[pop_id]['clusters'] = dict()
                self.data[pop_id]['nodes'] = dict()

            pop_neuron_id = neuron_data['n']
            self.data[pop_id]['space'][pop_neuron_id] = points[neuron_graph.nodes().index(neuron)]

        return self.data
Exemple #6
0
def algebraicConnectivity(g):
    
    if nx.is_directed(g):
    
        laplacian=nx.directed_laplacian_matrix(g, weight=None)
    else:
        tmplaplacian=nx.laplacian_matrix(g)
        laplacian=tmplaplacian.todense()
    #print laplacian
    laplacian_eig=np.linalg.eig(laplacian)
    eigs=laplacian_eig[0]
    return np.min(eigs[eigs> 1e-7 ])
Exemple #7
0
def directed_spectral_worker(G):
    #eigs = eigvalsh(nx.normalized_laplacian_matrix(G).todense())
    eigs = np.linalg.eigvalsh(
        nx.directed_laplacian_matrix(G).tolist().todense())
    spectral_pmf, _ = np.histogram(eigs,
                                   bins=200,
                                   range=(-1e-5, 2),
                                   density=False)
    spectral_pmf = spectral_pmf / spectral_pmf.sum()
    # from scipy import stats
    # kernel = stats.gaussian_kde(eigs)
    # positions = np.arange(0.0, 2.0, 0.1)
    # spectral_density = kernel(positions)

    # import pdb; pdb.set_trace()
    return spectral_pmf
def networkX_laplacian(adj_graph, sym, norm, weight='weight'):
    # Compute the laplacian matrix using NetworkX built in functions.
    #
    # Can take symmetric or directed graphs (sym='sym' or sym='').
    # Can take weighted or unweighted graphs (weight='weight' or weight=None).
    # Can create normalized or non-normalized matrices (norm='norm' or norm='').
    #
    if (sym=='sym') and (norm=='norm'):
        B = nx.normalized_laplacian_matrix(adj_graph,weight=weight).A # nx returns is numpy martrix, .A returns array.
    elif sym=='' and norm=='norm':
        B = nx.directed_laplacian_matrix(adj_graph,weight=weight).A  # nx returns is numpy martrix, .A returns array.
    else:
        B = nx.laplacian_matrix(adj_graph,weight=weight).toarray()  # nx returns scipy sparse, toarray() returns a np array.
                                                            # Ensures cohesion with nx normalized and nx directed modules,
                                                            # and supports np.array indexing conventions.

    return B
Exemple #9
0
    def run(self, graph, n=2000, c=0.1):
        """
        :param graph: not a networkx graph, but an instance of the wrapper class in graphs.py
        :param n: number of wave equation time steps
        :param c: wave speed
        """

        # graph state should be uninitialized; if not, then clear it
        graph.state = None

        # initialize t = -1, 0 states
        init = np.random.uniform(size=(1, len(graph.nodes)))
        graph.update_state(np.append(init, init, axis=0))
        if graph.is_directed():
            laplacian = np.asarray(nx.directed_laplacian_matrix(graph))
        else:
            laplacian = nx.laplacian_matrix(graph).toarray()
        relaxation = tqdm(range(n))
        relaxation.set_description('Relaxation: ')

        for t in relaxation:
            # sum over all neighbors
            neighbors = np.dot(
                (2 * np.identity(len(laplacian)) - (c**2) * laplacian),
                graph.state[t + 1])

            # t-1, t-2
            relaxation = graph.state[t]

            graph.update_state([neighbors - relaxation])

        # if a WaveEquationSimulation acts on a single graph at a time, then functions below like
        # highlight_clusters, etc only make sense inside WaveEquationSimulation if it maintains a local copy of
        # the current graph after running the simulation

        self.graph = graph
        self.peaks = self.__fft_peaks()
        dummy_peaks = {}
        mapping = sorted(self.graph.nodes)
        for it, key in enumerate(sorted(self.peaks.keys())):
            dummy_peaks[mapping[it]] = self.peaks[key]

        self.peaks = dummy_peaks
Exemple #10
0
def SVD_perSlice(G_times, directed=True, num_eigen=6, top=True, max_size=500):
    Temporal_eigenvalues = []
    activity_vecs = []  #eigenvector of the largest eigenvalue
    counter = 0

    for G in G_times:
        if (len(G) < max_size):
            for i in range(len(G), max_size):
                G.add_node(
                    -1 *
                    i)  #add empty node with no connectivity (zero padding)
        if (directed):
            L = nx.directed_laplacian_matrix(G)

        else:
            L = nx.laplacian_matrix(G)
            L = L.asfptype()

        #top = False
        #compute svd, find diagonal matrix and append the diagonal entries
        #only consider 6 eigenvalues for now as the number of graph is small
        #num_eigenvalues=6
        #k=min(L.shape)-1
        if (top):
            which = "LM"
        else:
            which = "SM"

        u, s, vh = svds(L, k=num_eigen, which=which)
        # u, s, vh = randomized_svd(L, num_eigen)
        vals = s
        vecs = u
        #vals, vecs= LA.eig(L)
        max_index = list(vals).index(max(list(vals)))
        activity_vecs.append(np.asarray(vecs[max_index]))
        Temporal_eigenvalues.append(np.asarray(vals))

        print("processing " + str(counter), end="\r")
        counter = counter + 1

    return (Temporal_eigenvalues, activity_vecs)
Exemple #11
0
def eigenDAG(DAG, DAG_Size, Top_k_Eigenvalue_Number, norm=False):
    # Matrix to Sparse
    DAG = sp.csr_matrix(DAG)
    # Create Graph
    G = nx.DiGraph(DAG)  # Create The Directed Graph
    # Calculate Directed laclacian
    Laplacian = nx.directed_laplacian_matrix(G,
                                             nodelist=None,
                                             weight='weight',
                                             walk_type=None,
                                             alpha=0.95)
    # Normalize the matrix
    if norm:
        Laplacian = NormalizeMatrix(Laplacian)
    # Eigen value of Laplacian
    eigenvalues, eigenvectors = np.linalg.eig(Laplacian)
    # Sorting the eigenvalues
    np.matrix.sort(eigenvalues)
    # Top K EigenValues
    Top_k_Eigenvalue = eigenvalues[(DAG_Size -
                                    Top_k_Eigenvalue_Number):DAG_Size]

    ## If the test is for 2nd Eigen Value then this line will choose the 2nd one otherwise 1st one
    Top_k_Eigenvalue = Top_k_Eigenvalue[0]

    # Getting the index for Max value
    Top_k_Eigenvalue_Index = sorted(range(len(eigenvalues)),
                                    key=lambda i: eigenvalues[i])[-2:]

    # List of Top Eigen Vactors
    Top_k_Eigenvector = np.zeros
    Top_k_Eigenvector = eigenvectors[:, Top_k_Eigenvalue_Index[0]]
    for i in range(Top_k_Eigenvalue_Number - 1):
        Top_k_Eigenvector = np.column_stack(
            (Top_k_Eigenvector, eigenvectors[:,
                                             Top_k_Eigenvalue_Index[i + 1]]))

    return Top_k_Eigenvalue, Top_k_Eigenvector, Top_k_Eigenvalue_Index, Laplacian

fig = plt.Figure()
fig.set_canvas(plt.gcf().canvas)
nx.draw_networkx_nodes(B, pos, node_size=200,node_color=col ,cmap=plt.get_cmap('jet'),labels=B.nodes())#,,
nx.draw_networkx_labels(B,pos,font_size=10)
nx.draw_networkx_edges(B, pos, edge_color='b', arrows=True)
os.chdir(fig_path)
plt.savefig('bipartite_Network_1.pdf')

#plt.show()
    
### Algebraic connectivity
### second-smallest eigenvalue of the Laplacian matrix 

L=nx.directed_laplacian_matrix(G)
eigenValues,eigenVectors=np.linalg.eig(L)


idx = eigenValues.argsort()   
eigenValues = eigenValues[idx]
eigenVectors = eigenVectors[:,idx]



sec_min=idx[1]
np.set_printoptions(precision=4)
AC=eigenValues[sec_min]


g_ac = "%0.4f" % AC