def radialAssign(g, sink=False): global visited visited = list() graph = g.copy() # graph = g # print graph gSorted = list() visited = list() # Toposort goes HERE: GA = GraphAnalysis(graph) gSorted = GA.topologicalSort() if len(gSorted) < 1: gSorted.append(graph.getNodeList()[0]) gSorted[0].PosX = 0 gSorted[0].PosY = 0 # root.PosX=0 # root.PosY=0 d = False if graph.Type == 1: d = True # print graph visited.append(gSorted[0]) # TODO: Add support for multiple roots __recRadial(graph, gSorted[0], 360, 0, 1, d) # print graph return graph
def radialAssign(g, sink = False): global visited visited = list() graph = g.copy() # graph = g # print graph gSorted = list() visited = list() # Toposort goes HERE: GA = GraphAnalysis(graph) gSorted = GA.topologicalSort() if len(gSorted)<1: gSorted.append(graph.getNodeList()[0]) gSorted[0].PosX=0 gSorted[0].PosY=0 # root.PosX=0 # root.PosY=0 d = False if graph.Type == 1 : d = True # print graph visited.append(gSorted[0]) # TODO: Add support for multiple roots __recRadial(graph, gSorted[0], 360, 0, 1, d) # print graph return graph
def written_paths_analysis(paths: Collection[GraphAnalysis.Path]) -> str: '''Returns a string containing analysis of the given paths.''' shortest_path = GraphAnalysis.shortest_path(paths) longest_path = GraphAnalysis.longest_path(paths) written_paths_analysis = f''' ----------General Paths---------- Path count : {len(paths)} Average length : {GraphAnalysis.average_length(paths):.3f} Average weight : {GraphAnalysis.average_total_weight(paths):.3f} ----------Shortest Path---------- Length : {shortest_path.length()} Weight : {shortest_path.total_weight:.1f} {written_path(shortest_path)} ----------Longest Path----------- Length : {longest_path.length()} Weight : {longest_path.total_weight:.1f} {written_path(longest_path)} ''' return written_paths_analysis
def display_labyrinth_graph_analysis(): ''' Displays the analysis of the Labyrinth of Theseus as a graph in the console. ''' begin = time.time() print('Building graph ...') graph = GraphAnalysis.import_graph() print('Done!') # All acyclic paths from the entry to the exit of the labyrinth print('Analysing graph ...') acyclic_paths = GraphAnalysis.all_acyclic_paths(graph, '0a', '37a') cyclic_paths = GraphAnalysis.all_distinct_cycles(graph) print('Done!') end = time.time() print(f'Time passed: {end - begin: .2f} seconds') print(f''' ----------Labyrinth of Theseus graph analysis---------- Node count : {graph.node_count()} Edge count : {graph.edge_count()} -----------Acyclic paths from entry to exit------------ {written_paths_analysis(acyclic_paths)} -------------------Distinct cycles--------------------- {written_paths_analysis(cyclic_paths)} ''')
def tikGraph(graph, l = None): analysis = GraphAnalysis(graph) n = analysis.numberOfNodes() #scaleFactor = 1 / log(n) scaleFactor = 0.9 #print n, scaleFactor #exit() output = "" output += "% Tik output from JumanG\n" output += "\\documentclass[class=minimal,border=0pt]{article}\n" output += "\\usepackage{tikz}\n" output += "\\pagestyle{empty}\n" output += "\\usepackage{verbatim}\n" output += "\\begin{document}\n" #output += "\\resizebox{100}{100}{\n" output += "\\begin{tikzpicture}[scale="+"{0:.2f}".format(scaleFactor)+", transform shape]\n" output += "\t\\tikzstyle{every node} = [circle, fill=gray!30, minimum size = 1.8cm]\n" for n in graph.getNodeList(): cleanedName = n.Name cleanedName = cleanedName.replace("_","") x = n.PosX y = n.PosY output+="\t\\node ("+cleanedName+") at ("+"{0:.2f}".format(n.PosX)+", "+"{0:.2f}".format(n.PosY)+") {"+cleanedName+"};\n" for n1 in graph.getNodeList(): for (n2, t) in graph.AdjacencyList[n1]: cleanedN = n1.Name cleanedN = cleanedN.replace("_", "") cleanedN2 = n2.Name cleanedN2 = cleanedN2.replace("_","") if t.Type==1: output+="\t\\draw [->] ("+cleanedN+")--("+cleanedN2+");\n" else: output+="\t\\draw [-] ("+cleanedN+")--("+cleanedN2+");\n" output += "\\end{tikzpicture}\n" #output += "}\n" output += "\\end{document}\n" if l: f=open(l, "w") f.write(output) else: print output
def split_into_sections(data): toadd = [] final_sections = [] for data_point in range(len(data)): for x in range(2): use = data[data_point] # If x = 0 then it is the first section and you need to have the operator as + to go right across the data if x == 0: op = operator.add length = 0 else: op = operator.sub length = len(use) - 1 point = GraphAnalysis.go_along_data(use, length, op) toadd.append(point) final_sections.append(toadd[:]) toadd.clear() returnsections = [] passback = [] # Work out the peaks for section in range(len(final_sections)): firstpeak = data[section][0:final_sections[section][0]] middlepeak = data[section][ final_sections[section][0]:final_sections[section][1]] lastpeak = data[section][final_sections[section][1]:len(data[section])] returnsections.append(firstpeak) returnsections.append(middlepeak) returnsections.append(lastpeak) passback.append(returnsections[:]) returnsections.clear() return final_sections, passback
def reputationDistr(): reputation_dist = reputation_distribution(g.db) img = plot_distribution(reputation_dist) img2 = reputation_answers_dependency(g.db) user_graph = GAnalysis.buildGraph(g.db) #Centralities betweenness_centrality = GAnalysis.between_centrality(g.db, user_graph, 5) eigenvector_centrality = GAnalysis.eigenvector_centrality(g.db, user_graph, 5) ass_k = GAnalysis.assortativity_coefficient(user_graph) #Communities partition = GAnalysis.best_partition(user_graph) modularity = GAnalysis.modularity(partition, user_graph) number_of_communities = GAnalysis.number_of_communities(partition) return render_template('reputation.html', repDist=img, repVSans=img2, reputations=reputation_dist[:10], betweenness_centrality=betweenness_centrality, eigenvector_centrality=eigenvector_centrality, assortativity_coefficient=ass_k, modularity=modularity, number_of_communities=number_of_communities )
def decrease_values(data): newvals = [] toreturn = [] for intensityrow in data: background = GraphAnalysis.get_background_signal(intensityrow) for x in intensityrow: if x - background <= 0: newvals.append(0) else: newvals.append(x - background) toreturn.append(newvals[:]) newvals.clear() return toreturn
def getGraphAnalysisResults(): edgeList = [(1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6), (7, 8), (8, 9), (8, 10), (9, 10),(11,12),(11,13),(12,14),(13,14)] g = ga.initializeGraph(edgeList) graph = ga.gg.generateGraph(edgeList) vertices = ga.gg.getVertices(edgeList) indegreeMap = ga.gg.getIndegree(vertices, graph) outdegreeMap = ga.gg.getOutDegree(vertices, graph) #inserting sourceNodes into the list print("Source Nodes ID from Mapped transactions : ") sourceNodes = ga.dg.getSourceNodes(indegreeMap) for sn in sourceNodes : customer = ga.getCustomerId(sn) list2.insert(END,str(customer) + "\n") #Inserting destNodes into the list print("Destination Nodes ID from Mapped transactions : ") destNodes = ga.dg.getDestNodes(outdegreeMap) for dn in destNodes: customer = ga.getCustomerId(dn) list3.insert(END, str(customer) + "\n") newEdgeList = ga.dg.splitEdgeList(edgeList, graph, sourceNodes) print("Vertex Set after splitting") vertexSet = [] count = 0 for edgeList in newEdgeList: try: vertexSet.append(ga.dg.depthFirstSearch(edgeList, graph, sourceNodes[count])) except: vertexSet = [ga.dg.depthFirstSearch(edgeList, graph, sourceNodes[count])] count += 1 print("New Node Values after splitting") newNodeValues = [] count = 0 for vertices in vertexSet: try: newNodeValues.append(ga.gg.genNodeValues(vertices, sourceNodes[count])) except: newNodeValues = [ga.gg.genNodeValues(vertices, sourceNodes[count])] count += 1 count = 0 for edgeList in newEdgeList: #list to store pdf info data1 = [["Mapping of Nodes",""],["Node","CustomerId"]] data2 = [["Edges involved in transactions","","","","",""],["nameOrig","nameDest","type","amt","newBalOrig","newBalDest"]] data3 = [["SourceNode","DestinationNode"]] data4 = [["Edges involved in Longest Path"],["nameOrig","nameDest","type","amt","newBalOrig","newBalDest"]] data5 = [] sub_data1 = [] for vertex in vertexSet[count]: print("Vertex : "+ str(vertex)) sub_data1 = [str(vertex)] sub_data1.append(str(ga.getCustomerId(vertex))) print(sub_data1) data1.append(sub_data1) print(data1) transactInfo = ga.getTransactionInformation(edgeList) for transactions in transactInfo: sub_data2 = [] for k,v in transactions.items(): list1.insert(END, str(k) + " " + str(v)) try: sub_data2.append(str(v)) except: sub_data2 = [str(v)] list1.insert(END,"\n") data2.append(sub_data2) g = ga.initializeGraph(edgeList) g.topologicalSort() mapOfNodes = ga.mapTopologicalStack(g) longestPathInfo = ga.longestDistance(newNodeValues[count], mapOfNodes, g) print("Longest Path for dest = %d and source = %d" % (destNodes[count],sourceNodes[count])) agentIntegrator = [ga.getCustomerId(sourceNodes[count]),ga.getCustomerId(destNodes[count])] data3.append(agentIntegrator) longestPath = ga.getlongestPath(longestPathInfo,destNodes[count],sourceNodes[count]) #For Calculating the total amount involved in transactions total_amount = 0 sub_data5 = ["Total Transaction Amount"] for items in ga.getTransactionInformation(longestPath): sub_data4 = [] for k,v in items.items(): list4.insert(END,str(k) + " " + str(v)) try: sub_data4.append(str(v)) except: sub_data4 = [str(v)] if k == "amount" and (v != None or v != 0): total_amount += v list4.insert(END,"\n") data4.append(sub_data4) sub_data5.append(str(total_amount)) data5.append(sub_data5) print("Total_amount : " + str(total_amount)) generatePdf("Graph" + str(count) + ".png",data1,data2,data3,data4,data5,"Graph" + str(count) + ".pdf") count += 1
def arrange(g): global toAdjust graph = g.copy() GA = GraphAnalysis(graph) nodepairs = GA.topologicalSort(True) #(_,lengthOfGraph) = nodepairs[-1] #armLength = 3 / log(lengthOfGraph) nodes = list() nodes.append(list()) most = 0 current = 0 layerCount = {} for (n, l) in nodepairs: layerCount[l] = layerCount.get(l, 0) + 1 if l > current: nodes.append(list()) nodes[l].append(n) for layer in layerCount: count = layerCount[layer] if count > most: most = count # Here, we try to minimize edge crossings between the nodes if len(nodes) > 2: # We keep track of two layers. Our current layer and the layer above it. layer1 = nodes[0] layer2 = nodes[1] for i in xrange(2, len(nodes)): layer3 = nodes[i] layer1Size = len(layer1) layer2Size = len(layer2) layer3Size = len(layer3) #print "layer 1 size: ", layer1Size #print "layer 2 size: ", layer2Size weightedLayer2Values = [] for nodej in xrange(len(layer2)): nodejWeight = 0 nodejCount = 0 node2 = layer2[nodej] for nodei in xrange(len(layer1)): node1 = layer1[nodei] isAdjacent = graph.isAdjacent(node1, node2) if isAdjacent: nodejCount += 1 nodejWeight += nodei * layer1Size for nodek in xrange(len(layer3)): node3 = layer3[nodek] isAdjacent = graph.isAdjacent(node2, node3) if isAdjacent: nodejCount += 1 nodejWeight += nodek * layer3Size normalizedWeight = nodejWeight / nodejCount #print node2.Name, "normalizedWeight:",normalizedWeight, nodejWeight, nodejCount weightedLayer2Values.append((node2, normalizedWeight)) sorted_by_second = sorted(weightedLayer2Values, key=lambda tup: tup[1]) for nodej in xrange(len(layer2)): layer2[nodej] = sorted_by_second[nodej][0] layer1 = layer2 layer2 = layer3 layout(nodes, most) return graph
def __init__(self, infile): self.Parser = DotParser() self.Graph = self.Parser.readFile(infile) self.Analysis = GraphAnalysis(self.Graph) self.State = NBODY
class JumanG: def __init__(self, infile): self.Parser = DotParser() self.Graph = self.Parser.readFile(infile) self.Analysis = GraphAnalysis(self.Graph) self.State = NBODY def outputToTikz(self, graph, outfile): TW.tikGraph(graph, outfile) def runRadial(self): return RD.radialAssign(self.Graph) def runNBody(self, useRadialSeed=True): if useRadialSeed: return NB.reposition(self.runRadial(), False) else: return NB.reposition(self.Graph, True) def runCirco(self): outputFile = "a.png" call(["circo", "-Tpng", self.Parser.FileName, "-o", outputFile]) call(["eog", outputFile]) return self.Graph def runTopDown(self): return TD.arrange(self.Graph) def chooseSolver(self): (numberOfNodes, numberOfEdges, numberOfLeaves) = self.Analysis.numberOfNodesEdgesAndLeaves() rootNodes = self.Analysis.getRootNodes() numberOfRootNodes = len(rootNodes) hasCycles = True #If it is an acyclic graph, we can run topdown if self.Graph.Type == 1 and rootNodes: hasCycles = self.Analysis.BFS(rootNodes[0], True) if not hasCycles: topoList = self.Analysis.topologicalSort(True) treeDepth = topoList[-1][1] print "numberOfNodes", numberOfNodes, "treeDepth", treeDepth if numberOfNodes > pow(3, treeDepth) and numberOfRootNodes == 1: self.State = RADIAL return self.State else: self.State = TOPDOWN return self.State #If we have an acyclic graph that has no roots. Its some form of ring. elif self.Graph.Type == 1: self.State = CIRCO return self.State else: # undirected graph # Metric for graph: connectedness: #nodes/#edges, < 3 connectedness = self.Graph.getNumEdges() / float(numberOfNodes) print connectedness if connectedness < 3: #radial -> nbody self.State = NBODY else: #nbody random self.State = NBODY_JITTER return self.State def runChosenSolver(self, choice=None): if choice == None: choice = self.State #print "TEST",choice, CIRCO if choice == NBODY: return self.runNBody() if choice == NBODY_RADIAL: return self.runNBody(True) if choice == NBODY_JITTER: return self.runNBody(False) if choice == TOPDOWN: return self.runTopDown() if choice == RADIAL: return self.runRadial() if choice == CIRCO: return self.runCirco() return self.runNBody() '''return { NBODY:self.runNBody(), NBODY_RADIAL:self.runNBody(True), NBODY_JITTER:self.runNBody(False), TOPDOWN:self.runTopDown(), RADIAL:self.runRadial(), CIRCO:self.runCirco(), #NBODYJ:self.runNBody(False), }.get(choice,self.runNBody()) ''' def printChoice(self): return { NBODY: "NBODY", NBODY_RADIAL: "NBODY_RADIAL", NBODY_JITTER: "NBODY_JITTER", TOPDOWN: "TOPDOWN", RADIAL: "RADIAL", CIRCO: "CIRCO", }.get(self.State, "???")
def arrange(g): global toAdjust graph = g.copy() GA = GraphAnalysis(graph) nodepairs = GA.topologicalSort(True) # (_,lengthOfGraph) = nodepairs[-1] # armLength = 3 / log(lengthOfGraph) nodes = list() nodes.append(list()) most = 0 current = 0 layerCount = {} for (n, l) in nodepairs: layerCount[l] = layerCount.get(l, 0) + 1 if l > current: nodes.append(list()) nodes[l].append(n) for layer in layerCount: count = layerCount[layer] if count > most: most = count # Here, we try to minimize edge crossings between the nodes if len(nodes) > 2: # We keep track of two layers. Our current layer and the layer above it. layer1 = nodes[0] layer2 = nodes[1] for i in xrange(2, len(nodes)): layer3 = nodes[i] layer1Size = len(layer1) layer2Size = len(layer2) layer3Size = len(layer3) # print "layer 1 size: ", layer1Size # print "layer 2 size: ", layer2Size weightedLayer2Values = [] for nodej in xrange(len(layer2)): nodejWeight = 0 nodejCount = 0 node2 = layer2[nodej] for nodei in xrange(len(layer1)): node1 = layer1[nodei] isAdjacent = graph.isAdjacent(node1, node2) if isAdjacent: nodejCount += 1 nodejWeight += nodei * layer1Size for nodek in xrange(len(layer3)): node3 = layer3[nodek] isAdjacent = graph.isAdjacent(node2, node3) if isAdjacent: nodejCount += 1 nodejWeight += nodek * layer3Size normalizedWeight = nodejWeight / nodejCount # print node2.Name, "normalizedWeight:",normalizedWeight, nodejWeight, nodejCount weightedLayer2Values.append((node2, normalizedWeight)) sorted_by_second = sorted(weightedLayer2Values, key=lambda tup: tup[1]) for nodej in xrange(len(layer2)): layer2[nodej] = sorted_by_second[nodej][0] layer1 = layer2 layer2 = layer3 layout(nodes, most) return graph
class JumanG: def __init__(self, infile): self.Parser = DotParser() self.Graph = self.Parser.readFile(infile) self.Analysis = GraphAnalysis(self.Graph) self.State = NBODY def outputToTikz(self, graph, outfile): TW.tikGraph(graph, outfile) def runRadial(self): return RD.radialAssign(self.Graph) def runNBody(self, useRadialSeed = True): if useRadialSeed: return NB.reposition(self.runRadial(),False) else: return NB.reposition(self.Graph,True) def runCirco(self): outputFile = "a.png" call(["circo","-Tpng",self.Parser.FileName,"-o",outputFile]) call(["eog",outputFile]) return self.Graph def runTopDown(self): return TD.arrange(self.Graph) def chooseSolver(self): (numberOfNodes,numberOfEdges,numberOfLeaves) = self.Analysis.numberOfNodesEdgesAndLeaves() rootNodes = self.Analysis.getRootNodes() numberOfRootNodes = len(rootNodes) hasCycles = True #If it is an acyclic graph, we can run topdown if self.Graph.Type==1 and rootNodes: hasCycles = self.Analysis.BFS(rootNodes[0],True) if not hasCycles: topoList = self.Analysis.topologicalSort(True) treeDepth = topoList[-1][1] print "numberOfNodes",numberOfNodes,"treeDepth",treeDepth if numberOfNodes > pow(3,treeDepth) and numberOfRootNodes==1: self.State = RADIAL return self.State else: self.State = TOPDOWN return self.State #If we have an acyclic graph that has no roots. Its some form of ring. elif self.Graph.Type == 1: self.State = CIRCO return self.State else: # undirected graph # Metric for graph: connectedness: #nodes/#edges, < 3 connectedness = self.Graph.getNumEdges()/float(numberOfNodes) print connectedness if connectedness < 3: #radial -> nbody self.State = NBODY else: #nbody random self.State = NBODY_JITTER return self.State def runChosenSolver(self, choice = None): if choice == None: choice = self.State #print "TEST",choice, CIRCO if choice == NBODY: return self.runNBody() if choice == NBODY_RADIAL: return self.runNBody(True) if choice == NBODY_JITTER: return self.runNBody(False) if choice == TOPDOWN: return self.runTopDown() if choice == RADIAL: return self.runRadial() if choice == CIRCO: return self.runCirco() return self.runNBody() '''return { NBODY:self.runNBody(), NBODY_RADIAL:self.runNBody(True), NBODY_JITTER:self.runNBody(False), TOPDOWN:self.runTopDown(), RADIAL:self.runRadial(), CIRCO:self.runCirco(), #NBODYJ:self.runNBody(False), }.get(choice,self.runNBody()) ''' def printChoice(self): return { NBODY:"NBODY", NBODY_RADIAL:"NBODY_RADIAL", NBODY_JITTER:"NBODY_JITTER", TOPDOWN:"TOPDOWN", RADIAL:"RADIAL", CIRCO:"CIRCO", }.get(self.State,"???")