コード例 #1
0
ファイル: graph_tools.py プロジェクト: joeloren/ic-eval
def SmallWorld(n):
    # slow
    graph = SparseGraph(n)
    generator = SmallWorldGenerator(0.3, 50)
    graph = generator.generate(graph)
    l, _ = graph.adjacencyList()
    return convertAdjListToEdgeList(l)
コード例 #2
0
def BarabasiAlbertEdgeList(n):
    graph = SparseGraph(n)
    generator = BarabasiAlbertGenerator(10, 10)
    graph = generator.generate(graph)
    l, _ = graph.adjacencyList()

    return convertAdjListToEdgeList(l)
コード例 #3
0
ファイル: graph_tools.py プロジェクト: joeloren/ic-eval
def BarabasiAlbertEdgeList(n):
    graph = SparseGraph(n)
    generator = BarabasiAlbertGenerator(10, 10)
    graph = generator.generate(graph)
    l, _ = graph.adjacencyList()
    
    return convertAdjListToEdgeList(l)
コード例 #4
0
def SmallWorld(n):
    # slow
    graph = SparseGraph(n)
    generator = SmallWorldGenerator(0.3, 50)
    graph = generator.generate(graph)
    l, _ = graph.adjacencyList()
    return convertAdjListToEdgeList(l)
コード例 #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 createGraph(dictuniq):
    g = SparseGraph(len(dictuniq), False, dtype = numpy.int32)
    mts = dictuniq.keys()
    for mt in mts:
        if mt.strip() != '':
            relmts = [k for k in mts if k.strip() != '' and k in mt and k != mt]
            relmts.sort(key=len, reverse=True)
            currentGrandchildren = set([])
            for relmt in relmts:
                if relmt not in currentGrandchildren:
                    g.addEdge(dictuniq[mt], dictuniq[relmt])
                    currentGrandchildren = currentGrandchildren.union([k for k in mts if k.strip() != '' and k in relmt])
    return g
コード例 #7
0
ファイル: graph_tools.py プロジェクト: joeloren/ic-eval
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)
コード例 #8
0
class ThreeClustIterator(object): 
    def __init__(self, p=0.1, numClusters=3, seed=21): 
        numpy.random.seed(seed)
        self.numClusters = numClusters
        self.startClusterSize = 20
        self.endClusterSize = 60
        self.clusterStep = 5
        self.pClust = 0.3
                
        self.numVertices = self.numClusters*self.endClusterSize
        vList = GeneralVertexList(self.numVertices)
        
        subgraphIndicesList = [range(0, self.startClusterSize)]
        subgraphIndicesList[0].extend(range(self.endClusterSize, self.endClusterSize+self.startClusterSize))
        subgraphIndicesList[0].extend(range(2*self.endClusterSize, 2*self.endClusterSize+self.startClusterSize))
        
        for i in range(self.startClusterSize, self.endClusterSize-self.clusterStep+1, self.clusterStep):
            subgraphIndices = copy.copy(subgraphIndicesList[-1])
            subgraphIndices.extend(range(i, i+self.clusterStep))
            subgraphIndices.extend(range(self.endClusterSize+i, self.endClusterSize+i+self.clusterStep))
            subgraphIndices.extend(range(2*self.endClusterSize+i, 2*self.endClusterSize+i+self.clusterStep))
            subgraphIndicesList.append(subgraphIndices)
        
        # to test removing
        # - increasing graph
        # do nothing
        # - decreasing graph
        #subgraphIndicesList.reverse()
        # - increasing and decreasing graph
        tmp = copy.copy(subgraphIndicesList[:-1])
        tmp.reverse()
        subgraphIndicesList.extend(tmp)
        self.subgraphIndicesList = subgraphIndicesList
        self.p = p 
        
        W = numpy.ones((self.numVertices, self.numVertices))*self.p
        
        for i in range(numClusters):
            W[self.endClusterSize*i:self.endClusterSize*(i+1), self.endClusterSize*i:self.endClusterSize*(i+1)] = self.pClust
            
        P = numpy.random.rand(self.numVertices, self.numVertices)
        W = numpy.array(P < W, numpy.float)
        upTriInds = numpy.triu_indices(self.numVertices)
        W[upTriInds] = 0
        W = W + W.T
        self.graph = SparseGraph(vList)
        self.graph.setWeightMatrix(W)
        
    def getIterator(self):
        return IncreasingSubgraphListIterator(self.graph, self.subgraphIndicesList)
コード例 #9
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
コード例 #10
0
ファイル: GraphIterators.py プロジェクト: charanpald/sandbox
    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
コード例 #11
0
ファイル: GraphIterators.py プロジェクト: rezaarmand/sandbox
    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
コード例 #12
0
    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
コード例 #13
0
ファイル: FowlkesExp.py プロジェクト: charanpald/wallhack
def run(): 
    W = createDataset()
    
    numVertices = W.shape[0]
    graph = SparseGraph(GeneralVertexList(numVertices))
    graph.setWeightMatrix(W)
    L = graph.normalisedLaplacianSym()
    #L = GraphUtils.shiftLaplacian(scipy.sparse.csr_matrix(W)).todense()
    n = 100 
    omega, Q = numpy.linalg.eigh(L)
    omega2, Q2 = Nystrom.eigpsd(L, n)
    
    print(omega)
    print(omega2)
    
    plt.figure(1)
    plt.plot(numpy.arange(omega.shape[0]), omega)
    plt.plot(numpy.arange(omega2.shape[0]), omega2)
    plt.show()

#run()
コード例 #14
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)
コード例 #15
0
ファイル: pvf.py プロジェクト: notokay/eecs_491_project
def construct_graph(samples, S):
    """
    Constructs an undirected graph using the
    Another Python Graph Library (apgl) SparseGraph
    class.

    samples are the samples used to construct the graph
    S is the number of states

    This method returns the constructed graph object
    """

    graph = SparseGraph(S)

    # loop through all samples
    # for each state transition
    # make the adjacency cell 1
    for sample in samples:
        if graph[sample.state, sample.nextstate] != 1:
            graph.addEdge(sample.state, sample.nextstate)

    return graph
コード例 #16
0
ファイル: redspline.py プロジェクト: kfray/spectral_spline
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
コード例 #17
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
コード例 #18
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
コード例 #19
0
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
コード例 #20
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
コード例 #21
0
ファイル: LaplacianExp3.py プロジェクト: malcolmreynolds/APGL
#Same plots with Fowlkes dataset 
#There is no eigengap in this case so bound does poorly 
W = scipy.sparse.csr_matrix(createDataset(sigma=1.5))
nystromNs = numpy.arange(20, 151, 10) 
k = 2

errors = numpy.zeros((len(nystromNs), numMethods))  
innerProds = numpy.zeros((len(nystromNs), numMethods))  

L = GraphUtils.shiftLaplacian(W)
L2 = GraphUtils.normalisedLaplacianSym(W)

print(L2.todense())

#Find connected components 
graph = SparseGraph(GeneralVertexList(W.shape[0]))
graph.setWeightMatrix(W)
components = graph.findConnectedComponents()
print(len(components)) 

#Compute exact eigenvalues 
omega, Q = numpy.linalg.eigh(L.todense())
inds = numpy.flipud(numpy.argsort(omega)) 
omega, Q = omega[inds], Q[:, inds]
omegak, Qk = omega[0:k], Q[:, 0:k]    

print(omega)
print(Q)

omegaHat, Qhat = numpy.linalg.eigh(L2.todense())
inds = numpy.argsort(omegaHat)
コード例 #22
0
class CitationIterGenerator(object):
    """
    A class to load the high energy physics data and generate an iterator. The 
    dataset is found in http://snap.stanford.edu/data/cit-HepTh.html
    """
    def __init__(self, minGraphSize=500, maxGraphSize=None, dayStep=30):
        
        dataDir = PathDefaults.getDataDir() + "cluster/"
        edgesFilename = dataDir + "Cit-HepTh.txt"
        dateFilename = dataDir + "Cit-HepTh-dates.txt"

        #Note the IDs are integers but can start with zero so we prefix "1" to each ID 
        edges = []
        file = open(edgesFilename, 'r')
        file.readline()
        file.readline()
        file.readline()
        file.readline()

        for line in file:
            (vertex1, sep, vertex2) = line.partition("\t")
            vertex1 = vertex1.strip()
            vertex2 = vertex2.strip()
            edges.append([vertex1, vertex2])
            
            #if vertex1 == vertex2: 
            #    print(vertex1)

        file.close()

        logging.info("Loaded edge file " + str(edgesFilename) + " with " + str(len(edges)) + " edges")

        #Keep an edge graph 
        graph = DictGraph(False)
        graph.addEdges(edges)
        logging.info("Created directed citation graph with " + str(graph.getNumEdges()) + " edges and " + str(graph.getNumVertices()) + " vertices")

        #Read in the dates articles appear in a dict which used the year and month
        #as the key and the value is a list of vertex ids. For each month we include
        #all papers uploaded that month and those directed cited by those uploads. 
        startDate = datetime.date(1990, 1, 1)

        file = open(dateFilename, 'r')
        file.readline()
        numLines = 0 
        subgraphIds = []

        for line in file:
            (id, sep, date) = line.partition("\t")
            id = id.strip()
            date = date.strip()
            

            inputDate = datetime.datetime.strptime(date.strip(), "%Y-%m-%d")
            inputDate = inputDate.date()

            if graph.vertexExists(id):
                tDelta = inputDate - startDate
                            
                graph.vertices[id] = tDelta.days 
                subgraphIds.append(id)
                
                #If a paper cites another, it must have been written before 
                #the citing paper - enforce this rule. 
                for neighbour in graph.neighbours(id): 
                    if graph.getVertex(neighbour) == None: 
                        graph.setVertex(neighbour, tDelta.days) 
                        subgraphIds.append(neighbour)
                    elif tDelta.days < graph.getVertex(neighbour): 
                        graph.setVertex(neighbour, tDelta.days) 
                        
            numLines += 1 
            
        file.close()
        
        subgraphIds = set(subgraphIds)
        graph = graph.subgraph(list(subgraphIds))
        logging.debug(graph)
        logging.info("Loaded date file " + str(dateFilename) + " with " + str(len(subgraphIds)) + " dates and " + str(numLines) + " lines")

        W = graph.getSparseWeightMatrix()
        W = W + W.T
        
        vList = VertexList(W.shape[0], 1)
        vList.setVertices(numpy.array([graph.getVertices(graph.getAllVertexIds())]).T)
        
        #Note: we have 16 self edges and some two-way citations so this graph has fewer edges than the directed one 
        self.graph = SparseGraph(vList, W=W)
        logging.debug(self.graph)
        
        #Now pick the max component 
        components = self.graph.findConnectedComponents()
        self.graph = self.graph.subgraph(components[0])
        
        logging.debug("Largest component graph: " + str(self.graph))
        
        self.minGraphSize = minGraphSize
        self.maxGraphSize = maxGraphSize 
        self.dayStep = dayStep 
        
    def getIterator(self):
        """
        Return an iterator which outputs the citation graph for each month. Note
        that the graphs are undirected but we make them directed.
        """
        vertexArray = self.graph.getVertexList().getVertices()
        dates = vertexArray[:, 0]
        firstVertex = numpy.argmin(dates)
        
        dayList = range(int(numpy.min(dates)), int(numpy.max(dates)), self.dayStep)
        dayList.append(numpy.max(dates))
        
        subgraphIndicesList = []

        #Generate subgraph indices list 
        for i in dayList:
            subgraphIndices = numpy.nonzero(dates <= i)[0]
            
            #Check subgraphIndices are sorted 
            subgraphIndices = numpy.sort(subgraphIndices)
            currentSubgraph = self.graph.subgraph(subgraphIndices)
            compIndices = currentSubgraph.depthFirstSearch(list(subgraphIndices).index(firstVertex))
            subgraphIndices =  subgraphIndices[compIndices]        
            
            if self.maxGraphSize != None and subgraphIndices.shape[0] > self.maxGraphSize: 
                break 
            
            print(subgraphIndices.shape[0])
            
            if subgraphIndices.shape[0] >= self.minGraphSize: 
                subgraphIndicesList.append(subgraphIndices)
                
        iterator = IncreasingSubgraphListIterator(self.graph, subgraphIndicesList)
        return iterator 
コード例 #23
0
    def __init__(self, minGraphSize=500, maxGraphSize=None, dayStep=30):
        
        dataDir = PathDefaults.getDataDir() + "cluster/"
        edgesFilename = dataDir + "Cit-HepTh.txt"
        dateFilename = dataDir + "Cit-HepTh-dates.txt"

        #Note the IDs are integers but can start with zero so we prefix "1" to each ID 
        edges = []
        file = open(edgesFilename, 'r')
        file.readline()
        file.readline()
        file.readline()
        file.readline()

        for line in file:
            (vertex1, sep, vertex2) = line.partition("\t")
            vertex1 = vertex1.strip()
            vertex2 = vertex2.strip()
            edges.append([vertex1, vertex2])
            
            #if vertex1 == vertex2: 
            #    print(vertex1)

        file.close()

        logging.info("Loaded edge file " + str(edgesFilename) + " with " + str(len(edges)) + " edges")

        #Keep an edge graph 
        graph = DictGraph(False)
        graph.addEdges(edges)
        logging.info("Created directed citation graph with " + str(graph.getNumEdges()) + " edges and " + str(graph.getNumVertices()) + " vertices")

        #Read in the dates articles appear in a dict which used the year and month
        #as the key and the value is a list of vertex ids. For each month we include
        #all papers uploaded that month and those directed cited by those uploads. 
        startDate = datetime.date(1990, 1, 1)

        file = open(dateFilename, 'r')
        file.readline()
        numLines = 0 
        subgraphIds = []

        for line in file:
            (id, sep, date) = line.partition("\t")
            id = id.strip()
            date = date.strip()
            

            inputDate = datetime.datetime.strptime(date.strip(), "%Y-%m-%d")
            inputDate = inputDate.date()

            if graph.vertexExists(id):
                tDelta = inputDate - startDate
                            
                graph.vertices[id] = tDelta.days 
                subgraphIds.append(id)
                
                #If a paper cites another, it must have been written before 
                #the citing paper - enforce this rule. 
                for neighbour in graph.neighbours(id): 
                    if graph.getVertex(neighbour) == None: 
                        graph.setVertex(neighbour, tDelta.days) 
                        subgraphIds.append(neighbour)
                    elif tDelta.days < graph.getVertex(neighbour): 
                        graph.setVertex(neighbour, tDelta.days) 
                        
            numLines += 1 
            
        file.close()
        
        subgraphIds = set(subgraphIds)
        graph = graph.subgraph(list(subgraphIds))
        logging.debug(graph)
        logging.info("Loaded date file " + str(dateFilename) + " with " + str(len(subgraphIds)) + " dates and " + str(numLines) + " lines")

        W = graph.getSparseWeightMatrix()
        W = W + W.T
        
        vList = VertexList(W.shape[0], 1)
        vList.setVertices(numpy.array([graph.getVertices(graph.getAllVertexIds())]).T)
        
        #Note: we have 16 self edges and some two-way citations so this graph has fewer edges than the directed one 
        self.graph = SparseGraph(vList, W=W)
        logging.debug(self.graph)
        
        #Now pick the max component 
        components = self.graph.findConnectedComponents()
        self.graph = self.graph.subgraph(components[0])
        
        logging.debug("Largest component graph: " + str(self.graph))
        
        self.minGraphSize = minGraphSize
        self.maxGraphSize = maxGraphSize 
        self.dayStep = dayStep 
コード例 #24
0
    lmbdaSqSum =  (lmbda[0:k]**2).sum()
    
    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)
コード例 #25
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)
コード例 #26
0
ファイル: networkStatistics.py プロジェクト: venkatvi/EYB
	print "Average clustering coefficient: " 
	print average_clustering(G)
	
#	print "Communicability centrality: "
#	print communicability(G)

	print "Diameter"
	print diameter(G)
	
	print "Radius: " 
	print radius(G)

	print "Eccentricity: "
	print eccentricity(G)
	
	sparseGraph = SparseGraph.fromNetworkXGraph(G)

	print "Size"
	print sparseGraph.size

	#1. mean degree
	degrees = sparseGraph.degreeSequence()
	sumDegree = np.sum(degrees)
	meanDegree = sumDegree / len(degrees)
	print "Mean Degree"
	print meanDegree

	#2. diameter
	print "SG Diameter"
	print sparseGraph.diameter()
コード例 #27
0
ファイル: original.py プロジェクト: SajidQ/AI_CS382_Projects
    for i in range(rowLength):
        obstacles.append([0, i])
        obstacles.append([colLength-1,i])

#############################################################################
################################################################################
################################################################################
#############################################################################
#---- Making the Graph ---------------------------------------------
# This initializes the graph, just basic things (its in the SparseGraph Ex)
numFeatures=0
numVertices=(rowLength-1)*(colLength-1)
vList=GeneralVertexList(numVertices)
weightMatrix = scipy.sparse.lil_matrix((numVertices, numVertices))
graph = SparseGraph(vList,True, W=weightMatrix)  # HERE IS YOUR GRAPH!


#-- This assigns to each vertex an array as a value. In the array, the first value is the x location, and then y (row), and 1 implies the vertex is unexplored. 0 will mean it is closed. The fourth value determines whether the vertex is in the fringe (1) or not (0)
#-- 5th value-g(A*), h(A*), f(A*), g(Theta*), h(Theta*), f(Theta*)
row=1
for i in range (graph.getNumVertices()):
    if(i%(colLength-1)==0 and i!=0):
        row=row+1
    graph.setVertex(i, [(i%(colLength-1))+1,row, 1, 0,100000000000.0,0.0, 100000000000.0,100000000000.0, 0.0, 100000000000.0])

""" check the vertex values
for i in range (graph.getNumVertices()):
    print "vertexVal: "+str(i)+ " " + str(graph.getVertex(i))
"""
コード例 #28
0
ファイル: dredis2cm.py プロジェクト: fgolemo/dsrcMedQA
def graphInfo(keyslen, wheigts):
	graph = SparseGraph(keyslen, W=wheigts.tocsr())
	print('graph size:' + str(graph.size))
	print('graph density:' + str(graph.density()) )
コード例 #29
0
ファイル: main.py プロジェクト: SajidQ/AI_CS382_Projects
        obstacles.append([i, rowLength-1])

    for i in range(rowLength):
        obstacles.append([0, i])
        obstacles.append([colLength-1,i])

##############################################################################
##############################################################################
##############################################################################
#---- Making the Graph ---------------------------------------------
# This initializes the graph, just basic things (its in the SparseGraph Ex)
numFeatures=0
numVertices=(rowLength-1)*(colLength-1)
vList=GeneralVertexList(numVertices)
weightMatrix = scipy.sparse.lil_matrix((numVertices, numVertices))
graph = SparseGraph(vList,True, W=weightMatrix)  # HERE IS YOUR GRAPH!


#-- This assigns to each vertex an array as a value. In the array, the first value is the x location, and then y (row), and 1 implies the vertex is unexplored. 0 will mean it is closed. The fourth value determines whether the vertex is in the fringe (1) or not (0)
#-- 5th value-g(A*), h(A*), f(A*), g(Theta*), h(Theta*), f(Theta*)
row=1
for i in range (graph.getNumVertices()):
    if(i%(colLength-1)==0 and i!=0):
        row=row+1
    graph.setVertex(i, [(i%(colLength-1))+1,row, 1, 0,100000000000.0,0.0, 100000000000.0,100000000000.0, 0.0, 100000000000.0])


#----- Connect vertices
# This just runs through and connects the vertices
# This is pretty complicated, and you don't need to worry about it. The code here should be right becuase the red edges are draen correctly
コード例 #30
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
コード例 #31
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()
コード例 #32
0
ファイル: GraphMatch.py プロジェクト: kentwang/sandbox
    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