def testGenerate(self):
        numFeatures = 1
        numVertices = 20

        vList = VertexList(numVertices, numFeatures)
        graph = SparseGraph(vList)

        ell = 2
        m = 0
        generator = BarabasiAlbertGenerator(ell, m)

        graph = generator.generate(graph)
        self.assertEquals(graph.getNumEdges(), 0)

        ell = 5
        graph.removeAllEdges()
        generator.setEll(ell)
        graph = generator.generate(graph)
        self.assertEquals(graph.getNumEdges(), 0)

        #Now test case where we m != 0
        ell = 2
        m = 1
        graph.removeAllEdges()
        generator.setEll(ell)
        generator.setM(m)
        graph = generator.generate(graph)
        self.assertEquals(graph.getNumEdges(), (numVertices-ell)*m)

        m = 2
        graph.removeAllEdges()
        generator.setM(m)
        graph = generator.generate(graph)
        self.assertEquals(graph.getNumEdges(), (numVertices-ell)*m)
    def testGenerate(self):
        numFeatures = 1
        numVertices = 20

        vList = VertexList(numVertices, numFeatures)
        graph = SparseGraph(vList)

        ell = 2
        m = 0
        generator = BarabasiAlbertGenerator(ell, m)

        graph = generator.generate(graph)
        self.assertEquals(graph.getNumEdges(), 0)

        ell = 5
        graph.removeAllEdges()
        generator.setEll(ell)
        graph = generator.generate(graph)
        self.assertEquals(graph.getNumEdges(), 0)

        #Now test case where we m != 0
        ell = 2
        m = 1
        graph.removeAllEdges()
        generator.setEll(ell)
        generator.setM(m)
        graph = generator.generate(graph)
        self.assertEquals(graph.getNumEdges(), (numVertices - ell) * m)

        m = 2
        graph.removeAllEdges()
        generator.setM(m)
        graph = generator.generate(graph)
        self.assertEquals(graph.getNumEdges(), (numVertices - ell) * m)
    def testGenerateGraph(self):
        numFeatures = 0
        numVertices = 20

        vList = VertexList(numVertices, numFeatures)
        graph = SparseGraph(vList)

        alpha1 = 10.0
        alpha2 = 20.0
        p = 0.001
        dim = 2
        generator = GeometricRandomGenerator(graph)

        graph = generator.generateGraph(alpha1, p, dim)
        numEdges1 = graph.getNumEdges()

        #Check no self edges
        for i in range(numVertices):
            self.assertTrue(graph.getEdge(i, i) == None)

        graph.removeAllEdges()
        graph = generator.generateGraph(alpha2, p, dim)
        numEdges2 = graph.getNumEdges()

        #self.assertTrue(numEdges1 >= numEdges2)
        logging.debug(numEdges1)
        logging.debug(numEdges2)

        for i in range(numVertices):
            self.assertTrue(graph.getEdge(i, i) == None)

        #Test case with p=0 and alpha huge 
        p = 0.0
        alpha = 100.0
        graph.removeAllEdges()
        graph = generator.generateGraph(alpha, p, dim)

        self.assertEquals(graph.getNumEdges(),  0)

        #When alpha=0, should get max edges
        alpha = 0.0
        graph.removeAllEdges()
        graph = generator.generateGraph(alpha, p, dim)

        #self.assertEquals(graph.getNumEdges(), int(0.5*(numVertices + numVertices**2) - numVertices))

        #TODO: Test variations in dimension 

        """
    def testGenerateGraph(self):
        numFeatures = 0
        numVertices = 20

        vList = VertexList(numVertices, numFeatures)
        graph = SparseGraph(vList)

        alpha1 = 10.0
        alpha2 = 20.0
        p = 0.001
        dim = 2
        generator = GeometricRandomGenerator(graph)

        graph = generator.generateGraph(alpha1, p, dim)
        numEdges1 = graph.getNumEdges()

        #Check no self edges
        for i in range(numVertices):
            self.assertTrue(graph.getEdge(i, i) == None)

        graph.removeAllEdges()
        graph = generator.generateGraph(alpha2, p, dim)
        numEdges2 = graph.getNumEdges()

        #self.assertTrue(numEdges1 >= numEdges2)
        logging.debug(numEdges1)
        logging.debug(numEdges2)

        for i in range(numVertices):
            self.assertTrue(graph.getEdge(i, i) == None)

        #Test case with p=0 and alpha huge 
        p = 0.0
        alpha = 100.0
        graph.removeAllEdges()
        graph = generator.generateGraph(alpha, p, dim)

        self.assertEquals(graph.getNumEdges(),  0)

        #When alpha=0, should get max edges
        alpha = 0.0
        graph.removeAllEdges()
        graph = generator.generateGraph(alpha, p, dim)

        #self.assertEquals(graph.getNumEdges(), int(0.5*(numVertices + numVertices**2) - numVertices))

        #TODO: Test variations in dimension 

        """
    def testGraphDisplay(self):
        try:
            import networkx
            import matplotlib
        except ImportError as error:
            logging.debug(error)
            return 

        #Show
        numFeatures = 1
        numVertices = 20

        vList = VertexList(numVertices, numFeatures)
        graph = SparseGraph(vList)

        p = 0.2
        generator = ErdosRenyiGenerator(p)

        graph = generator.generate(graph)
        logging.debug((graph.getNumEdges()))

        nxGraph = graph.toNetworkXGraph()
        nodePositions = networkx.spring_layout(nxGraph)
        nodesAndEdges = networkx.draw_networkx(nxGraph, pos=nodePositions)
        ax = matplotlib.pyplot.axes()
        ax.set_xticklabels([])
        ax.set_yticklabels([])
 def testGenerate2(self): 
     numVertices = 20
     graph = SparseGraph(GeneralVertexList(numVertices))
     p = 0.2
     generator = ErdosRenyiGenerator(p)
     graph = generator.generate(graph)
     
     self.assertTrue((graph.getNumEdges() - p*numVertices*numVertices/2) < 8)
Esempio n. 7
0
    def readFromFile(self, fileName):
        """
            Read vertices and edges of the graph from the given file name. The file
            must have as its first line "Vertices" followed by a list of
            vertex indices (one per line). Then the lines following "Arcs" or "Edges"
            have a list of pairs of vertex indices represented directed or undirected
            edges.
            """
        infile = open(fileName, "r")
        line = infile.readline()
        line = infile.readline()
        ind = 0
        vertexIdDict = {}

        while infile and line != "Edges" and line != "Arcs":
            vertexIdDict[int(line)] = ind
            line = infile.readline().strip()
            ind += 1

        if line == "Edges":
            undirected = True
        elif line == "Arcs":
            undirected = False
        else:
            raise ValueError("Unknown edge types: " + line)

        numVertices = len(vertexIdDict)
        numFeatures = 0
        vList = VertexList(numVertices, numFeatures)
        sGraph = SparseGraph(vList, undirected)
        line = infile.readline()

        while line:
            s = line.split()
            try:
                i = vertexIdDict[int(s[0].strip(',').strip())]
                j = vertexIdDict[int(s[1].strip(',').strip())]
                k = float(s[2].strip(',').strip())
            except KeyError:
                print("Vertex not found in list of vertices.")
                raise

            sGraph.addEdge(i, j, k)
            line = infile.readline()

        logging.info("Read graph with " + str(numVertices) + " vertices and " +
                     str(sGraph.getNumEdges()) + " edges")

        return sGraph
    def readFromFile(self, fileName):
        X = numpy.loadtxt(fileName, skiprows=1, converters=self.converters)
        vertexIds = numpy.zeros(X.shape[0] * 2)

        #First, we will map the vertex Ids to a set of numbers
        for i in range(0, X.shape[0]):
            vertexIds[2 * i] = X[i, self.vertex1IdIndex]
            vertexIds[2 * i + 1] = X[i, self.vertex2IdIndex]

        vertexIds = numpy.unique(vertexIds)

        numVertices = vertexIds.shape[0]
        numFeatures = len(self.vertex1Indices)

        vList = VertexList(numVertices, numFeatures)
        sGraph = SparseGraph(vList, self.undirected)

        for i in range(0, X.shape[0]):
            vertex1Id = X[i, self.vertex1IdIndex]
            vertex2Id = X[i, self.vertex2IdIndex]

            vertex1 = X[i, self.vertex1Indices]
            vertex2 = X[i, self.vertex2Indices]

            vertex1VListId = numpy.nonzero(vertexIds == vertex1Id)[0]
            vertex2VListId = numpy.nonzero(vertexIds == vertex2Id)[0]

            vertex1VListId = int(vertex1VListId)
            vertex2VListId = int(vertex2VListId)
            vList.setVertex(vertex1VListId, vertex1)
            vList.setVertex(vertex2VListId, vertex2)

            sGraph.addEdge(vertex1VListId, vertex2VListId, self.edgeWeight)

        logging.info("Read " + fileName + " with " +
                     str(sGraph.getNumVertices()) + " vertices and " +
                     str(sGraph.getNumEdges()) + " edges")

        return sGraph
    def testGenerate(self):
        #undirected = True 
        p = 0.0
             
        self.graph.removeAllEdges()
        self.erg.setP(p)
        graph = self.erg.generate(self.graph)
        self.assertEquals(graph.getNumEdges(), 0)
        
        undirected = False
        self.graph = SparseGraph(self.vList, undirected)
        self.graph.removeAllEdges()
        self.erg = ErdosRenyiGenerator(p)
        graph = self.erg.generate(self.graph)
        self.assertEquals(graph.getNumEdges(), 0)
        
        p = 1.0
        undirected = True
        self.graph = SparseGraph(self.vList, undirected)
        self.graph.removeAllEdges()
        self.erg = ErdosRenyiGenerator(p)
        graph = self.erg.generate(self.graph)
        self.assertEquals(graph.getNumEdges(), (self.numVertices*self.numVertices-self.numVertices)/2)
        
        p = 1.0
        undirected = False
        self.graph = SparseGraph(self.vList, undirected)
        self.graph.removeAllEdges()
        self.erg = ErdosRenyiGenerator(p)
        graph = self.erg.generate(self.graph)
        self.assertEquals(graph.getNumEdges(), self.numVertices*self.numVertices-self.numVertices)
        
        self.assertEquals(graph.getEdge(1, 2), 1)
        self.assertEquals(graph.getEdge(1, 1), None)

        p = 0.5
        numVertices = 1000
        numFeatures = 0

        vList = VertexList(numVertices, numFeatures)
        undirected = False
        self.graph = SparseGraph(vList, undirected)
        self.erg = ErdosRenyiGenerator(p)
        graph = self.erg.generate(self.graph)

        self.assertAlmostEquals(graph.getNumEdges()/float(numVertices**2 - numVertices), p, places=2)

        p = 0.1
        self.graph = SparseGraph(vList, undirected)
        self.erg = ErdosRenyiGenerator(p)
        graph = self.erg.generate(self.graph)

        self.assertAlmostEquals(graph.getNumEdges()/float(numVertices**2 - numVertices), p, places=2)

        #Test the case in which we have a graph with edges
        p = 0.5
        numVertices = 10 
        vList = VertexList(numVertices, numFeatures)
        graph = SparseGraph(vList, undirected)
        graph.addEdge(0, 1, 5)
        graph.addEdge(0, 2)
        graph.addEdge(0, 5, 0.7)
        graph.addEdge(1, 8)
        graph.addEdge(2, 9)
        numEdges = graph.getNumEdges()

        graph = self.erg.generate(graph, False)
        self.assertTrue(graph.getNumEdges() > numEdges)
Esempio n. 10
0
from pyamg import smoothed_aggregation_solver
from apgl.generator.ErdosRenyiGenerator import ErdosRenyiGenerator
from apgl.graph.SparseGraph import SparseGraph
from apgl.graph.GeneralVertexList import GeneralVertexList

numpy.set_printoptions(suppress=True, precision=4, linewidth=100)
numpy.random.seed(21)

p = 0.001
numVertices = 10000
generator = ErdosRenyiGenerator(p)
graph = SparseGraph(GeneralVertexList(numVertices))
graph = generator.generate(graph)

print("Num vertices = " + str(graph.getNumVertices()))
print("Num edges = " + str(graph.getNumEdges()))

L = graph.normalisedLaplacianSym(sparse=True)
# L = csr_matrix(L)
print("Created Laplacian")

# ml = smoothed_aggregation_solver(L)
# M = ml.aspreconditioner()


start = time.clock()
w, V = scipy.sparse.linalg.eigsh(L, k=20)
totalTime = time.clock() - start
print(totalTime)

# print(w)
    def readFromFile(self, fileName):
        X = numpy.loadtxt(fileName, skiprows=1, converters=self.converters)
        vertexIds = numpy.zeros(X.shape[0]*2)
        
        #First, we will map the vertex Ids to a set of numbers
        for i in range(0, X.shape[0]):
            vertexIds[2*i] = X[i, self.vertex1IdIndex]
            vertexIds[2*i+1] = X[i, self.vertex2IdIndex]

        vertexIds = numpy.unique(vertexIds)

        numVertices = vertexIds.shape[0]
        numFeatures = len(self.vertex1Indices)
        
        vList = VertexList(numVertices, numFeatures)
        sGraph = SparseGraph(vList, self.undirected)

        for i in range(0, X.shape[0]):
            vertex1Id = X[i, self.vertex1IdIndex]
            vertex2Id = X[i, self.vertex2IdIndex]
            
            vertex1 = X[i, self.vertex1Indices]
            vertex2 = X[i, self.vertex2Indices]

            vertex1VListId = numpy.nonzero(vertexIds==vertex1Id)[0]
            vertex2VListId = numpy.nonzero(vertexIds==vertex2Id)[0]

            vertex1VListId = int(vertex1VListId)
            vertex2VListId = int(vertex2VListId)
            vList.setVertex(vertex1VListId, vertex1)
            vList.setVertex(vertex2VListId, vertex2)

            sGraph.addEdge(vertex1VListId, vertex2VListId, self.edgeWeight)

        logging.info("Read " + fileName + " with " + str(sGraph.getNumVertices()) + " vertices and " + str(sGraph.getNumEdges()) + " edges")

        return sGraph 
        def readFromFile(self, fileName):
            """
            Read vertices and edges of the graph from the given file name. The file
            must have as its first line "Vertices" followed by a list of
            vertex indices (one per line). Then the lines following "Arcs" or "Edges"
            have a list of pairs of vertex indices represented directed or undirected
            edges.
            """
            infile = open(fileName, "r")
            line = infile.readline()
            line = infile.readline()
            ind = 0
            vertexIdDict = {}

            while infile and line != "Edges" and line != "Arcs":
                vertexIdDict[int(line)] = ind
                line = infile.readline().strip()
                ind += 1 

            if line == "Edges":
                undirected = True
            elif line == "Arcs":
                undirected = False
            else:
                raise ValueError("Unknown edge types: " + line)

            numVertices = len(vertexIdDict)
            numFeatures = 0
            vList = VertexList(numVertices, numFeatures)
            sGraph = SparseGraph(vList, undirected)
            line = infile.readline()

            while line:
                s = line.split()
                try:
                    i = vertexIdDict[int(s[0].strip(',').strip())]
                    j = vertexIdDict[int(s[1].strip(',').strip())]
                    k = float(s[2].strip(',').strip())
                except KeyError:
                    print("Vertex not found in list of vertices.")
                    raise 

                sGraph.addEdge(i, j, k)
                line = infile.readline()

            logging.info("Read graph with " + str(numVertices) + " vertices and " + str(sGraph.getNumEdges()) + " edges")

            return sGraph
Esempio n. 13
0
from pyamg import smoothed_aggregation_solver
from apgl.generator.ErdosRenyiGenerator import ErdosRenyiGenerator
from apgl.graph.SparseGraph import SparseGraph
from apgl.graph.GeneralVertexList import GeneralVertexList

numpy.set_printoptions(suppress=True, precision=4, linewidth=100)
numpy.random.seed(21)

p = 0.001
numVertices = 10000
generator = ErdosRenyiGenerator(p)
graph = SparseGraph(GeneralVertexList(numVertices))
graph = generator.generate(graph)

print("Num vertices = " + str(graph.getNumVertices()))
print("Num edges = " + str(graph.getNumEdges()))

L = graph.normalisedLaplacianSym(sparse=True)
#L = csr_matrix(L)
print("Created Laplacian")

#ml = smoothed_aggregation_solver(L)
#M = ml.aspreconditioner()

start = time.clock()
w, V = scipy.sparse.linalg.eigsh(L, k=20)
totalTime = time.clock() - start
print(totalTime)

#print(w)