Ejemplo n.º 1
0
 def test_to_graph_tool(self):
     from graph_tool.spectral import adjacency
     for G in self.graphs + [self.weighted]:
         gt = G.to_graph_tool()
         if G.is_weighted():
             adj = adjacency(gt, weight=gt.ep['weight']).A.T
         else:
             adj = adjacency(gt).A.T
         assert_array_equal(G.matrix('dense'), adj)
Ejemplo n.º 2
0
 def test_to_graph_tool(self):
   from graph_tool.spectral import adjacency
   for G in self.graphs + [self.weighted]:
     gt = G.to_graph_tool()
     if G.is_weighted():
       adj = adjacency(gt, weight=gt.ep['weight']).A.T
     else:
       adj = adjacency(gt).A.T
     assert_array_equal(G.matrix(dense=True), adj)
Ejemplo n.º 3
0
def cycle_signature(inGraph, maxCycleLength, mode="transition", normalize=True):    
    assert(mode == "transition" or mode == "adjacency")
    if mode == "transition":
        A    = spectral.transition(inGraph)
    if mode == "adjacency":
        A    = spectral.adjacency(inGraph)
    
    temp = A.copy()
    n    = A.shape[0]    # Number of nodes.
    sigs = np.empty((maxCycleLength, n))

    if mode == "transition":                
        for t in xrange(maxCycleLength):
            temp = temp.dot(A)            
            sigs[t,:] = temp.diagonal()

        
    if mode == "adjacency":
        for t in xrange(maxCycleLength):
            temp = temp.dot(A)
            if normalize:                
                sigs[t,:] = temp.diagonal() / np.sum(temp.diagonal())  # factorial(t+1)
            else:
                sigs[t,:] = temp.diagonal()

    return np.transpose(sigs)
Ejemplo n.º 4
0
def gt_graph_to_adj_matrix(g: gt.Graph,
                           edge_weights: Optional[gt.EdgePropertyMap] = NOT_SET,
                           dtype: str = T.float_x(),
                           device: Optional[str] = None,
                           ) -> T.SparseTensor:
    if edge_weights is NOT_SET:
        if 'weights' in g.ep:
            edge_weights = g.ep['weights']
        else:
            edge_weights = None
    adj_matrix = spectral.adjacency(g, weight=edge_weights)
    return T.sparse.from_spmatrix(
        adj_matrix, dtype=dtype, device=device, force_coalesced=True)
Ejemplo n.º 5
0
def makeISOLaplacians(graphExample, gcc, save=False, saveAt=None):

    g = load_GT_graph(
        graphExample, gcc, removeSL=True, removePE=True
    )  #For forming the Laplacian, we have to remove the Self-Loops and Parallel Edges if any.
    Ag = spectral.adjacency(g).todense(
    )  #Despite this todense() the Laplacian is going to be sparse. It is though taking more time to create it.
    gp, forwardMap = createIsoGraph(Ag)

    Lg = spectral.laplacian(g)  #create the Laplacians
    Lgp = spectral.laplacian(gp)

    if save:
        assert (saveAt != None)
        save_data(saveAt, Lg, Lgp, forwardMap)

    return Lg, Lgp, forwardMap
Ejemplo n.º 6
0
def makeISOPoisson(numberOfNodes, averDegree, gcc, save=False, saveAt=None):
    def degreeSample():
        return np.random.poisson(averDegree)

    g = generation.random_graph(numberOfNodes, degreeSample, directed=False)
    if gcc:
        l = topology.label_largest_component(
            g)  #Keep Largest Connected Component
        g.set_vertex_filter(l)
        g.purge_vertices()

    Ag = spectral.adjacency(g).todense()
    gp, forwardMap = graph_analysis.IO.createIsoGraph(Ag)

    if save:
        assert (saveAt != None)
        graph_analysis.IO.save_data(saveAt, g, gp, forwardMap)

    return g, gp, forwardMap
Ejemplo n.º 7
0
def vertex_sim(inGraph, alpha=.95, dist=False):
    '''
    Implementation of the node similarity metric described in
    "Vertex Similarity in networks, Leicht, Holme, Newman."
    '''
    n = inGraph.num_vertices()
    A = spectral.adjacency(inGraph)
    evals, evecs = linalg.eigsh(A, k=1, which='LM', tol=1E-3)
    scale = alpha / evals[0]
    S = linalg.inv(identity(n, format='csc') - scale * A.tocsc())
    d = inGraph.degree_property_map("total").a
    S = diags(1.0 / d, 0) * S * diags(1.0 / d, 0)
    S[np.diag_indices_from(S)] = 1  # Each node is self-similar.

    if dist:
        S = 1 - S.toarray()

    S = 0.5 * (S + S.T
               )  # Force S to be symmetric and guards to numerical errors.

    return S
Ejemplo n.º 8
0
    def __init__(self, graph, k, weight=None):
        if k >= graph.num_vertices():
            raise ValueError('k must be in the range ' +
                             '[0, graph.num_vertices()). ' +
                             'This is due to scipy.sparse.linalg restrictions')

        self.lap = gt_spectral.laplacian(graph, normalized=True, weight=weight)
        self.adj = gt_spectral.adjacency(graph, weight=weight)
        self._deg_vec = np.asarray(self.adj.sum(axis=1))

        self._weight = weight

        self._vol_graph = utils.graph_volume(graph, self._weight)
        self._n = graph.num_vertices()
        self._vertex_index = graph.vertex_index

        self.eig_val, self.eig_vec = eigsh(self.lap, k, which='SM')

        self._deg_vec = np.asarray(self.adj.sum(axis=1))
        self.basis = np.multiply(np.power(self._deg_vec, -0.5), self.eig_vec)
        self._deg_vec = np.squeeze(self._deg_vec)
Ejemplo n.º 9
0
def write_motifs_results(output, motifs_list, z_scores,
                         n_shuf, model="uncorrelated"):
    """Write the adjacency matrix of motifs in the `motifs_list`
    and its corresponding z-scores to file.
    Naming convention: blogcatalog_3um.motifslog
    Parameters
    ==========
        output: name of file will be writen to disk
        motifs_list: list of motifs (graph-tool graph instances)
        z_scores: corresponding z_scores to each motif.
        n_shuf: number of random graph generated
        model: name of the random graph generation algorithm"""
    assert len(motifs_list) == len(z_scores)
    with open(output, 'w') as f:
        f.write("Number of shuffles: {} ({})\n".format(n_shuf, model))
        for i, m in enumerate(motifs_list):
            f.write("Motif {} - z-score: {}\n".format(i+1, z_scores[i]))
            for rows in adjacency(m).toarray():
                f.write(str(rows) + '\n')
            f.write('\n')
    return output
Ejemplo n.º 10
0
def signLessLaplacianSpectrum(inGraph, graphName, eigsToCompute="all", save=True):
    '''
    Assumes the inGraph is connected.
    '''
    if eigsToCompute == "all":
        eigsToCompute = inGraph.num_vertices() - 1             
    eigsWhere    = "../Data/Spectrums/SignLess_L/"+graphName+"_"+str(eigsToCompute)+"_Eigs"
    if os.path.isfile(eigsWhere):
        print "Loading Spectrum"
        evals, evecs = IO.load_data(eigsWhere)
    else:
        Ld  = spectral.laplacian(inGraph).diagonal()       #TODO replace with degree vector to avoid building the laplacian 
        Ls  = spectral.adjacency(inGraph)
        Ls.setdiag(Ld)        
        evals, evecs = computeSpectrum(Ls, eigsToCompute, small=False)  #For sign less Laplacian big eigpairs matter
        #sort so that big eigen-pairs are first
        
        evals = evals[::-1]
        evecs = np.flipud(evecs)        
        if save:
            IO.save_data(eigsWhere, evals, evecs)
    return evals, evecs
Ejemplo n.º 11
0
def panos_sim_4(inGraph,
                graphName,
                eigs="all",
                strategy=None,
                compressed=True,
                sigma=0.1):

    A = spectral.adjacency(inGraph)
    degrees = inGraph.degree_property_map("total").a
    M = A + diags(degrees + 1, 0)

    if eigs == "all":
        eigs = len(degrees) - 1

    evals, evecs = gk.computeSpectrum(M, eigs, small=False, verbose=True)
    print evals

    n = evecs.shape[1]  # Number of nodes.
    signatures = np.empty((n, len(evals)))

    squaredEigVectors = evecs**2
    squaredEigVectors = np.transpose(evecs)

    #     for node in xrange(n):
    #         signatures[node, :] = squaredEigVectors[node, :] * ((degrees[node] - evals)**2)
    #
    #     for i in xrange(10):
    #         signaturesNew = gk.neighbor_signatures(signatures, inGraph, "average")
    #         if np.allclose(signatures, signaturesNew):
    #             break
    #     signatures = signaturesNew

    if compressed:
        signatures = compress_spectral_signatures(signatures,
                                                  evals,
                                                  sigma=sigma)

    print "Signature was created."
    return signatures
Ejemplo n.º 12
0
def compute_bounds(g):
    """Computes bounds for chromatic number based on hoffman bound, generalized hoffman bound, woc-elp conjetural bound, and wilf's theorem.

    Takes a graph and computes the bounds, then outputs a summary array which includes vertex degree information and an estimate for
    the actual chromatic number of the graph based on actual colorings.

    Args:
        g (graph_tool graph)

    Returns:
        numpy array [hoffman bound, generalized hoffman bound, woc-elp bound, wilf bound, max degree, average degree, computed coloring number]
    """

    # Get degree info
    n = g.num_vertices()
    m = g.num_edges()
    average_degree = 2 * m / n
    max_degree = max([vertex.out_degree() for vertex in g.vertices()])

    # Get spectral info
    A = spectral.adjacency(g)
    Aw, Av = linalg.eig(A.todense())
    eigenvalues = sorted(Aw, reverse=True)

    results = []
    # compute eigen-bounds
    results.append(compute_hoff(eigenvalues))
    results.append(compute_gen_hoff(eigenvalues))
    results.append(compute_woc_elp(eigenvalues))
    results.append(compute_wilf(eigenvalues))
    # stats
    results.append(max_degree)
    results.append(average_degree)
    # compute coloring
    results.append(get_best_coloring(g)[0])

    return numpy.array(results)
Ejemplo n.º 13
0
	def get_mat_adjacency(self):
		return adjacency(self.__graph, self.get_weights())
Ejemplo n.º 14
0
	def getAdjacency(self):
		if self.isWeighted():
			return adjacency(self.graph, self.graph.edge_properties["weight"])
		else:
			return adjacency(self.graph)
Ejemplo n.º 15
0
def adjacency_matrix(graph, weight=None):
    return adjacency(graph, weight).toarray().T
Ejemplo n.º 16
0
 def getAdjacency(self):
     if self.isWeighted():
         return adjacency(self.graph, self.graph.edge_properties["weight"])
     else:
         return adjacency(self.graph)
Ejemplo n.º 17
0
from evolution import *
import numpy as np
from math import inf
from time import time
import array
from optimized.cyFns import *
from cpython cimport array
from libc.math cimport exp
from libc.math cimport log, exp
from libc.stdlib cimport rand, RAND_MAX
import cython

#%%
N=500
graph = initUniformRandomGraph(N)
from graph_tool.spectral import adjacency
x=crandint(0,N-1)
y=crandint(0,N-1)
mat = adjacency(graph).tolil()
rows = mat.rows.copy() 
#%%
%timeit np.random.choice(graph.get_all_neighbors(x))
%timeit graph.get_all_neighbors(x)[crandint(0, graph.get_out_degrees([x])[0]-1)]
%timeit np.random.choice(graph.get_out_neighbors(x))
%timeit graph.get_out_neighbors(x)[crandint(0, graph.get_out_degrees([x])[0]-1)]
%timeit np.random.choice(rows[x])
%timeit rows[x][crandint(0, graph.get_out_degrees([x])[0]-1)]
# %%
%timeit graph.get_all_neighbors(x)
%timeit adjacency(graph).tolil().rows[x]