Пример #1
0
def splitGraph(graph, random=True, p=1 / float(3)):
    all_edges = graph.getAllEdges()
    vertices = graph.vlist
    inc = bernoulli.rvs(p, size=len(all_edges))
    train = SparseGraph(vertices)
    test = SparseGraph(vertices)
    train.addEdges(all_edges[inc == 0])
    test.addEdges(all_edges[inc == 1])
    return train, test
Пример #2
0
def SmallWorld(n):
    # slow
    graph = SparseGraph(n)
    generator = SmallWorldGenerator(0.3, 50)
    graph = generator.generate(graph)
    l, _ = graph.adjacencyList()
    return convertAdjListToEdgeList(l)
Пример #3
0
def BarabasiAlbertEdgeList(n):
    graph = SparseGraph(n)
    generator = BarabasiAlbertGenerator(10, 10)
    graph = generator.generate(graph)
    l, _ = graph.adjacencyList()

    return convertAdjListToEdgeList(l)
    def toSparseGraph(self):
        """
        Convert the current graph to a SparseGraph. Currently, vertex labels 
        are not converted. 
        """
        from apgl.graph import SparseGraph

        W = self.getSparseWeightMatrix(format="csr")
        graph = SparseGraph(W.shape[0], W=W, undirected=self.undirected)

        return graph
Пример #5
0
def ConfigurationModel(edges_list):
    deg_dict = defaultdict(int)

    for u, v in edges_list:
        deg_dict[v] += 1
    l = array(deg_dict.values())
    n = len(l)
    graph = SparseGraph(n)
    generator = ConfigModelGenerator(l)
    graph = generator.generate(graph)
    l, _ = graph.adjacencyList()
    return convertAdjListToEdgeList(l)
Пример #6
0
def KroneckerEdgeList(n):
    init = SparseGraph(4)
    init[0, 1] = 1
    init[0, 2] = 1
    init[0, 3] = 1
    for i in range(4):
        init[i, i] = 1
    k = int(log(n, 4)) + 1
    generator = KroneckerGenerator(init, k)
    graph = generator.generate()
    l, _ = graph.adjacencyList()
    return convertAdjListToEdgeList(l)
Пример #7
0
def adj_from_listfile(adj_list, n, vertices=False, skip=4):
    if not vertices:
        vertices = range(n)
    adj = SparseGraph(len(vertices))
    print "sparse graph created"
    adj1, adj2 = getList(adj_list, skip)
    for i, j in zip(adj1, adj2):
        if i >= n:
            break
        if j >= n:
            pass
        elif i in vertices and j in vertices:
            adj[i, j] = 1
    print "adj list constructed"
    return adj
Пример #8
0
def adj_from_listfile(adj_list, n, vertices=False, skip=4):
    if not vertices:
        vertices = range(n)
    adj = SparseGraph(len(vertices))
    with open(adj_list, 'r') as a:
        k = 0
        for line in a:
            if k < skip:
                k += 1
            else:
                i, j = line.split()
                i = int(i)
                j = int(j)
                if i in vertices and j in vertices:
                    adj[i, j] = 1
                    adj[j, i] = 1
    return adj
Пример #9
0
    def __next__(self):

        if self.emit == False:
            # We need a "do while" loop here to manage situations where self.graphIterator is already exhausted
            while True:
                W = next(self.graphIterator)
                graph = SparseGraph(W.shape[0], W=W)
                numComponents = len(graph.findConnectedComponents())
                if __debug__:
                    logging.debug("graph size = " + str(graph.size) +
                                  " num components = " + str(numComponents))

                if numComponents < self.maxComponents:
                    #                    self.emit = True
                    break
        else:
            W = self.graphIterator.next()

        return W
def ingest(filename):
    f = open(filename, "r")

    # exit if file not in readmode
    if f.mode != 'r':
        exit()

    # stream graph text file
    content = f.readlines()
    f.close()

    # retrieve meta data
    cadMeta = content[0].split(" ")

    # get number of nodes
    numNodes = int(cadMeta[0])

    # get number of time sequences
    t = int(cadMeta[1])

    # generate t amount of graphs
    G = []
    for _ in range(t):
        G.append(SparseGraph(numNodes))

    # iterate through every node connection
    # store in sparse graph for specific time sequence
    for line in content[1:]:
        data = line.split(" ")
        n1 = int(data[0])
        n2 = int(data[1])
        w = int(data[2])
        t = int(data[3])
        G[t][n1, n2] = w

    return G
Пример #11
0
def dijkstra(graph):

    #pre process graph
    adj = graph.adjacencyList()
    connections = adj[0]
    weights = adj[1]
    nvert = graph.getNumVertices()
    nodes = list(range(nvert))
    distances = {}
    for i in range(nvert):  # i = source
        distances.update({i: dict(zip(connections[i], weights[i]))})

    ct = SparseGraph(nvert)
    for i in range(nvert):
        unvisited = {node: None for node in nodes}  #using None as +inf
        visited = {}
        current = i
        currentDistance = 0
        unvisited[current] = currentDistance

        while True:
            for neighbour, distance in distances[current].items():
                if neighbour not in unvisited: continue
                newDistance = currentDistance + distance
                if unvisited[neighbour] is None or unvisited[
                        neighbour] > newDistance:
                    unvisited[neighbour] = newDistance
            visited[current] = currentDistance
            if i != current:
                ct[i, current] = currentDistance
            del unvisited[current]
            if not unvisited: break
            candidates = [node for node in unvisited.items() if node[1]]
            current, currentDistance = sorted(candidates,
                                              key=lambda x: x[1])[0]
    return ct
Пример #12
0
    def match(self, graph1, graph2):
        """
        Take two graphs are match them. The two graphs must be AbstractMatrixGraphs 
        with VertexLists representing the vertices.  
        
        :param graph1: A graph object 
        
        :param graph2: The second graph object to match 
        
        :return permutation: A vector of indices representing the matching of elements of graph1 to graph2 
        :return distance: The graph distance list [graphDistance, fDistance, fDistanceExact] 
        """
        #Deal with case where at least one graph is emty
        if graph1.size == 0 and graph2.size == 0:
            permutation = numpy.array([], numpy.int)
            distanceVector = [0, 0, 0]
            time = 0
            return permutation, distanceVector, time
        elif graph1.size == 0 or graph2.size == 0:
            if graph1.size == 0:
                graph1 = SparseGraph(
                    VertexList(graph2.size,
                               graph2.getVertexList().getNumFeatures()))
            else:
                graph2 = SparseGraph(
                    VertexList(graph1.size,
                               graph1.getVertexList().getNumFeatures()))

        numTempFiles = 5
        tempFileNameList = []

        for i in range(numTempFiles):
            fileObj = tempfile.NamedTemporaryFile(delete=False)
            tempFileNameList.append(fileObj.name)
            fileObj.close()

        configFileName = tempFileNameList[0]
        graph1FileName = tempFileNameList[1]
        graph2FileName = tempFileNameList[2]
        similaritiesFileName = tempFileNameList[3]
        outputFileName = tempFileNameList[4]

        if self.useWeightM:
            W1 = graph1.getWeightMatrix()
            W2 = graph2.getWeightMatrix()
        else:
            W1 = graph1.adjacencyMatrix()
            W2 = graph2.adjacencyMatrix()

        numpy.savetxt(graph1FileName, W1, fmt='%.5f')
        numpy.savetxt(graph2FileName, W2, fmt='%.5f')

        #Compute matrix similarities
        C = self.vertexSimilarities(graph1, graph2)
        numpy.savetxt(similaritiesFileName, C, fmt='%.5f')

        #Write config file
        configFile = open(configFileName, 'w')

        configStr = "graph_1=" + graph1FileName + " s\n"
        configStr += "graph_2=" + graph2FileName + " s\n"
        configStr += "C_matrix=" + similaritiesFileName + " s\n"
        configStr += "algo=" + self.algorithm + " s\n"
        configStr += "algo_init_sol=" + self.init + " s\n"
        configStr += "alpha_ldh=" + str(self.alpha) + " d\n"
        configStr += "cdesc_matrix=A c\n"
        configStr += "cscore_matrix=A c\n"
        configStr += "hungarian_max=10000 d\n"
        configStr += "algo_fw_xeps=0.01 d\n"
        configStr += "algo_fw_feps=0.01 d\n"
        configStr += "dummy_nodes=0 i\n"
        configStr += "dummy_nodes_fill=" + str(self.rho) + " d\n"
        configStr += "dummy_nodes_c_coef=" + str(self.gamma) + " d\n"
        configStr += "qcvqcc_lambda_M=" + str(self.lambdaM) + " d\n"
        configStr += "qcvqcc_lambda_min=1e-3 d\n"
        configStr += "blast_match=0 i\n"
        configStr += "blast_match_proj=0 i\n"
        configStr += "exp_out_file=" + outputFileName + " s\n"
        configStr += "exp_out_format=Compact Permutation s\n"
        configStr += "verbose_mode=0 i\n"
        configStr += "verbose_file=cout s\n"

        configFile.write(configStr)
        configFile.close()

        fnull = open(os.devnull, 'w')

        home = expanduser("~")
        argList = [home + "/.local/bin/graphm", configFileName]
        subprocess.call(argList, stdout=fnull, stderr=fnull)

        fnull.close()

        #Next: parse input files
        outputFile = open(outputFileName, 'r')

        line = outputFile.readline()
        line = outputFile.readline()
        line = outputFile.readline()
        line = outputFile.readline()

        graphDistance = float(outputFile.readline().split()[2])
        fDistance = float(outputFile.readline().split()[2])
        fDistanceExact = float(outputFile.readline().split()[2])
        time = float(outputFile.readline().split()[1])

        line = outputFile.readline()
        line = outputFile.readline()

        permutation = numpy.zeros(
            max(graph1.getNumVertices(), graph2.getNumVertices()), numpy.int)

        i = 0
        for line in outputFile:
            permutation[i] = int(line.strip()) - 1
            i += 1

        #Delete files
        os.remove(graph1FileName)
        os.remove(graph2FileName)
        os.remove(similaritiesFileName)
        os.remove(configFileName)
        os.remove(outputFileName)

        distanceVector = [graphDistance, fDistance, fDistanceExact]
        return permutation, distanceVector, time
Пример #13
0
"""
Name: Generate Graph:
Author: Jia_qiu Wang(王佳秋)
Data: December, 2016
function:
"""

from apgl.graph import GeneralVertexList, SparseGraph
import numpy

numVertices = 5  # 顶点个数
graph = SparseGraph(numVertices)  # 具有5个顶点个数的图数据结构
graph[0, 1] = 1
graph[0, 2] = 3
graph[1, 2] = 0.1
graph[3, 4] = 2
graph.setVertex(0, "abc")
graph.setVertex(1, 123)
print(graph.findConnectedComponents())  # 输出联通分量

print(graph.getWeightMatrix())  # 输出图的邻接矩阵

# print(graph.degreeDistribution())

print(graph.neighbours(0))

print(graph)
Пример #14
0
    r2 = max((k - r), 0)
    sigmaSqSum = (sigma[0:r2]**2).sum()
    bound = gammaSqSum + lmbdaSqSum - 2 * sigmaSqSum
    print("r=" + str(r))

    print("gammaSqSum=" + str(gammaSqSum))
    print("lmbdaSqSum=" + str(lmbdaSqSum))
    print("sigmaSqSum=" + str(sigmaSqSum))

    return bound


#Change to work with real Laplancian
numRows = 100
graph = SparseGraph(GeneralVertexList(numRows))

p = 0.1
generator = ErdosRenyiGenerator(p)
graph = generator.generate(graph)

print(graph)

AA = graph.normalisedLaplacianSym()

p = 0.001
generator.setP(p)
graph = generator.generate(graph, requireEmpty=False)

AA2 = graph.normalisedLaplacianSym()