コード例 #1
0
def testing_Standard_HKS_New_input(exampleG,
                                   eigsToLoad,
                                   eigsToUse,
                                   nstep,
                                   smallest=True,
                                   plot=False):
    ###PARAMETERS###
    gcc = True
    kernel = gk.heatKernel
    topKs = [1, 2]
    #####-#####-#####

    graphWhere = "../Data/Graphs/synthetic/" + exampleG
    g, gp, forwardMap, equivsG = graph_analysis.IO.load_data(graphWhere)

    evals1, evecs1, evals2, evecs2 = computeSpectrums(spectral.laplacian(g),
                                                      spectral.laplacian(gp),
                                                      eigsToLoad, smallest,
                                                      exampleG)

    res = []
    if type(eigsToUse) == list:  #many eigenvalues to test_myRolx
        for k in eigsToUse:
            timeSample1 = gk.logTimeScale(evals1, k, nstep)
            sig1 = gk.HKS(evals1, evecs1, k, timeSample1)

            timeSample2 = gk.logTimeScale(evals2, k, nstep)
            sig2 = gk.HKS(evals2, evecs2, k, timeSample2)

            nodeMapping = gk.signatureBasedMapping(sig1, sig2, kernel,
                                                   topKs[-1])
            resK = gk.mappingAccuracy(nodeMapping, forwardMap, topKs, equivsG)
            print "Eigenvalues used: " + str(k)
            print resK
            res.append(resK)

        accForAllTopK = []
        for i, topK in enumerate(topKs):
            accForAllTopK.append([exp[i][3] for exp in res])
        label = ["TopK=" + str(topK) for topK in topKs]
        inText = "Heat Kernel\nLogTimeSample |t|=" + str(nstep)
        myPLT.xQuantityVsAccuracy(exampleG,
                                  eigsToUse,
                                  accForAllTopK,
                                  "Eigenvalues",
                                  label,
                                  inText,
                                  save=True)
    else:
        timeSample1 = gk.logTimeScale(evals1, eigsToUse, nstep)
        sig1 = gk.HKS(evals1, evecs1, eigsToUse, timeSample1)

        timeSample2 = gk.logTimeScale(evals2, eigsToUse, nstep)
        sig2 = gk.HKS(evals2, evecs2, eigsToUse, timeSample2)

        nodeMapping = gk.signatureBasedMapping(sig1, sig2, kernel, topKs[-1])
        resK = gk.mappingAccuracy(nodeMapping, forwardMap, topKs, equivsG)
        print resK
コード例 #2
0
ファイル: synthGraphs.py プロジェクト: optas/graph_roles
def example_signaturesAndPCA():
    #     Calculate signatures of random+clique+lattices+circles mixture graph and plot their PCA
    crc = erdos_circles_cliques([1000, 5000],
                                nCliques=20,
                                cliqueSize=15,
                                nCircles=20,
                                circleSize=30,
                                save=False)
    gFinal = append_lattices(crc, nLatte=20, latticeSize=[5, 5])
    colors = colorNodes(gFinal, ["cliq", "circ", "late"])
    Lg = spectral.laplacian(gFinal)

    eigsToCompute = 100
    eigsWhere = "../Data/Spectrums/LM/mix2" + str(eigsToCompute + 1) + "_Eigs"
    evals, evecs = graph_analysis.IO.compute_or_load(gk.computeSpectrum,
                                                     eigsWhere,
                                                     False,
                                                     Lg,
                                                     eigsToCompute + 1,
                                                     small=True)
    timeSample = gk.heatTimeSample3(evals[0], evals[-1], 10)
    sig = gk.HKS(evals, evecs, eigsToCompute, timeSample)

    sigsPCA = PCA(sig)
    print "Fraction of Variance in the first three PCA dimensions: " + str(
        sum(sigsPCA.fracs[0:3]))
    saveAt = "gnp_cliques_circles__lattices_1K_5K_20_15_20_30_20_25.pdf"
    myPLT.plot_PCA_Res(
        sigsPCA,
        dim=3,
        legendLabel=["Gnp_Nodes", "Cliques", "Circles", "Lattices"],
        colorMap=[colors, palets("typeToColor")],
        save=False,
        saveAt=saveAt)
コード例 #3
0
ファイル: IO.py プロジェクト: optas/graph_roles
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
コード例 #4
0
ファイル: graph_kernels.py プロジェクト: optas/graph_roles
def laplacian_pseudo_inverse(inGraph=None, evals=None, evecs=None):
    
    if evals!=None and evecs !=None:
        nodes = evecs.shape[1]
        Lpseudo = np.zeros((nodes, nodes))
        for i in xrange(len(evals)):
            Lpseudo += (1.0/evals[i]) * evecs[i,:].dot(evecs[i,:])        
    else:
        L = spectral.laplacian(inGraph)
        Lpseudo = np.linalg.pinv(L.todense())
        
    return Lpseudo
コード例 #5
0
ファイル: graph_kernels.py プロジェクト: optas/graph_roles
def laplacian_spectrum(inGraph, graphName, eigsToCompute="all", edgeW=None, tryLoad=True, save=False, saveAt=None):
    '''
    Assumes the inGraph is connected.
    '''
    
    if eigsToCompute == "all":
        eigsToCompute = inGraph.num_vertices() - 1             

    eigsWhere    = "../Data/Spectrums/SM/"+graphName+"_"+str(eigsToCompute)+"_Eigs"
    
    if tryLoad:
        if os.path.isfile(eigsWhere):
            print "Loading Spectrum..."
            evals, evecs = IO.load_data(eigsWhere)            
            print "Spectrum Loaded."
            return evals, evecs             #If the data are loaded then the function exist without re-saving the loaded data
            
    if edgeW == None: #construct the Laplacian matrix
        print "Using simple Laplacian."
        Lg = spectral.laplacian(inGraph)
    else:
        print "Using weighted Laplacian."
        Lg = spectral.laplacian(inGraph, weight=edgeW)
    
    if eigsToCompute == inGraph.num_vertices() - 1: # We will compute the largest eigenvalues for efficiency.
        evals, evecs = computeSpectrum(Lg, eigsToCompute, small=False)
        assert(is_increasing(evals))
    else:
        evals, evecs = computeSpectrum(Lg, eigsToCompute+1, small=True)
        #Discard The 1st eigenpair (0-constant)
        evals = evals[1:]; evecs = evecs[1:, :]
    
    if save:
        if saveAt != None:
            IO.save_data(saveAt, evals, evecs)
        else:
            IO.save_data(eigsWhere, evals, evecs)
        
    return evals, evecs
コード例 #6
0
ファイル: IO.py プロジェクト: optas/graph_roles
def saveLaplacianToMatlab(graph, normal=False, saveAt=None):
    '''
    Save the laplacian of the -graph- in the sparse format that is used by Matlab.
    '''
    nodes = graph.num_vertices()
    outFormat = "%d %d %d\n"
    with open(saveAt, "w") as outF:
        outF.write(outFormat % (nodes, nodes, 0))  #specify size of full matrix
        cx = spectral.laplacian(graph, normalized=normal).tocoo()
        for i, j, v in itertools.izip(cx.row, cx.col, cx.data):
            outF.write(outFormat %
                       (i + 1, j + 1, v))  #Matlab indexes arrays from 1.


#     print "IO module: Running main()"
#     import myBlockModels as myBM
#     N = 1000                    #Keep Note
#     imageMatrix, edgeDisMatrix       = myBM.manufacturingImage()
#     roleDistribution                 = [0.10, 0.15, 0.15, 0.25, 0.10, 0.25]
#     graphName                        = "manufacturing_2"
#     inGraph                          = myBM.buildModel(N, imageMatrix, roleDistribution, edgeDisMatrix)
#     inGraph                          = myBM.applyManufacturingConstraints(inGraph)
#
#     save_data("../Data/Graphs/synthetic/" + graphName + ".GT.graph", inGraph)
#
#     from_GT_To_Greach(inGraph, "../Data/Graphs/synthetic/" + graphName + ".greach.graph")
#     from_GT_To_Snap(  inGraph, "../Data/Graphs/synthetic/" + graphName + ".snap.graph")

# if __name__ == "__main__":
#
#     graph_name = "serengeti-foodweb"
#     save_at    =  graph_name + "_adjacency_matlab"
#
#     in_graph, group_taxa, blackList, x_tick_marks = mc.prepare_input_graph(graph_name, metric="default")
#     print blackList
#
#     nodes = in_graph.num_vertices()
#     edges = in_graph.num_edges()
#     output_format = "%d %d %d\n"
#
#     with open(save_at, "w") as outF:
#         outF.write(output_format % (nodes, 0, 0)) # Specify number of nodes.
#         outF.write(output_format % (edges, 0, 0)) # Specify number of edges.
#         cx    = spectral.adjacency(in_graph).tocoo()
#         for i,j,v in itertools.izip(cx.row, cx.col, cx.data):
#             outF.write(output_format % (i+1, j+1, v))         # Matlab indexes arrays from 1.
#
#
#     sys.exit("Normal Exiting")
コード例 #7
0
def num_spanning_trees_dense(g, weights=None):
    """compute number of spanning trees

    it converts the sparse laplacian into a dense one
    so it's **memory inefficient**
    
    Param:
    ---------

    g: Graph
    """
    l = laplacian(g, weight=weights)
    l = l.todense()
    l0 = l[:-1, :-1]
    return np.linalg.det(l0)
コード例 #8
0
ファイル: ppr.py プロジェクト: marianotepper/sgft
    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)
コード例 #9
0
ファイル: graph_kernels.py プロジェクト: optas/graph_roles
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
コード例 #10
0
    def __init__(self, grid, implementation='combinatorial'):
        """

        Parameters
        ----------
        grid: an instance of the Grid class
        implementation: string
            one of 'combinatorial', 'cotan', 'edge-length'
        """

        assert implementation in [
            'combinatorial', 'cotan', 'cotan2', 'edge-length'
        ], 'implementation parameter not recognized'
        self.implementation = implementation

        if implementation == 'combinatorial':
            self.matrix = laplacian(grid.graph)

        if implementation == 'edge-length':
            self.edge_length = grid.graph.new_edge_property('float')
            for e in grid.graph.edges():
                v_0 = grid.graph.vertex_index[e.source()]
                v_1 = grid.graph.vertex_index[e.target()]
                self.edge_length[e] = np.linalg.norm(grid.vertices[v_0] -
                                                     grid.vertices[v_1])
            self.matrix = laplacian(grid.graph, weight=self.edge_length)

        if implementation == 'cotan':
            """
            For the cotan implementation the weights are assigned by summation
                over the cotan-values corresponding to the angles opposing the
                edge.
            In the representation below the edge e_01 would have the weight
                (1/2) * (cotan(a_01) + cotan(b_01))
            #        v_2
            #       /  \
            #      /a_01\
            #     /      \
            #    /        \
            #   v_0--e_01-v_1
            #    \        /
            #     \      /
            #      \b_01/
            #       \  /
            #        v_3
            We iterate above the trianges, adding the cotans of each angle to
            the weight of the opposing edge
            """
            self.cotan_weight = grid.graph.new_edge_property('float')
            for f in grid.faces:
                v_0, v_1, v_2 = f
                e_01 = grid.graph.edge(v_0, v_1)
                e_02 = grid.graph.edge(v_0, v_2)
                e_12 = grid.graph.edge(v_1, v_2)
                e_01_vector = grid.vertices[v_1] - grid.vertices[v_0]
                e_02_vector = grid.vertices[v_2] - grid.vertices[v_0]
                e_12_vector = grid.vertices[v_2] - grid.vertices[v_1]
                e_01_vector /= np.linalg.norm(e_01_vector)
                e_02_vector /= np.linalg.norm(e_02_vector)
                e_12_vector /= np.linalg.norm(e_12_vector)
                # both vectors need to be reversed here, so we don't need to
                #    multiply by -1
                self.cotan_weight[e_01] += 0.5 / np.tan(
                    np.arccos(np.dot(e_02_vector, e_12_vector)))
                # the 01-vector needs to be reversed here, so we multiply by -1
                self.cotan_weight[e_02] += 0.5 / np.tan(
                    np.arccos(np.dot(-1 * e_01_vector, e_12_vector)))
                self.cotan_weight[e_12] += 0.5 / np.tan(
                    np.arccos(np.dot(e_01_vector, e_02_vector)))
            self.matrix = laplacian(grid.graph, weight=self.cotan_weight)

        if implementation == 'cotan2':
            """ the weight w_ij is given by |e*_ij|/|e_ij| where
                |e*_ij| = signed euclidean length of dual edge intersecting
                    edge e_ij
                |e_ij| = euclidean length of edge e_ij
            """
            if not hasattr(grid, 'dual_grid'):
                grid.get_barycentric_dual()

            self.weight = grid.graph.new_edge_property('float')
            for e in grid.graph.edges():
                v_0 = grid.graph.vertex_index[e.source()]
                v_1 = grid.graph.vertex_index[e.target()]
                primal_edge_length = np.linalg.norm(grid.vertices[v_0] -
                                                    grid.vertices[v_1])
                self.weight[e] = (grid.dual_edge_length[e] /
                                  primal_edge_length)

            self.matrix = laplacian(grid.graph, weight=self.weight)
コード例 #11
0
 def __init__(self, graph, n_eigs, tau, weight=None):
     SGFT.__init__(self, graph, n_eigs)
     lap = gt_spectral.laplacian(graph, normalized=False, weight=weight)
     eig_val, self.basis = eigsh(lap, n_eigs, which="SM")
     self.normalization_constant = np.power(graph.num_vertices(), 0.5)
     self.g_hat = np.exp(-tau * eig_val)
コード例 #12
0
ファイル: IO.py プロジェクト: optas/graph_roles
def mcSherryFromGraph(inGraph):
    lng = spectral.laplacian(inGraph, normalized=True)
    lng = -lng
    lng.setdiag(np.zeros(lng.diagonal().shape))
    return lng
コード例 #13
0
#Make binary label for SVM
for v in g.vertices():
    if g.vp['partOs'][v][0] == 'N':
        nodesLabels.append(1)
    else:
        nodesLabels.append(0)

eigsToCompute = 500
eigsToUse = 50
timePoints = 10
save = True
small = True

eigsWhere = "../Data/Spectrums/SM/" + novel + "_" + lang + "_NounVsVerb_" + "_Eigs_" + str(
    eigsToCompute + 1)
Lg = spectral.laplacian(g, weight=g.ep['weights'])
evals, evecs = graph_analysis.IO.compute_or_load(gk.computeSpectrum,
                                                 eigsWhere,
                                                 save,
                                                 Lg,
                                                 eigsToCompute + 1,
                                                 small=small)

timeSamples = gk.logTimeScale(evals, eigsToUse, timePoints)
sig = gk.HKS(evals, evecs, eigsToUse, timeSamples)

sig = PCA(sig).Y[:, 0:3]
# print sigsPCA.shape
# p()

#