本文整理汇总了Python中Graph.Graph类的典型用法代码示例。如果您正苦于以下问题:Python Graph类的具体用法?Python Graph怎么用?Python Graph使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Graph类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_add_edge
def test_add_edge(self):
graph1 = Graph("Graphec")
graph1.add_edge("A", "B")
self.assertEqual(graph1.Nodes["A"].name, "A")
self.assertEqual(graph1.Nodes["B"].name, "B")
self.assertEqual(graph1.Edges[0].froms, graph1.Nodes["A"])
self.assertEqual(graph1.Edges[0].to, graph1.Nodes["B"])
示例2: parseGraphFromFile
def parseGraphFromFile(fileName):
file = open(fileName, 'r')
line = file.readline()
graph = Graph()
# take out any extra whitespace, such as 1 $ 2 , 3...
line = re.sub("\s*", "", line)
# partition returns a 3-tuple of the string before the
# specified delimiter, the delimiter, and the string after
# the delimiter
parts = line.partition('$')
# the first part contains the list of nodes
# add each node to the graph
numNodes = parts[0]
for i in range(int(numNodes)):
graph.addNode()
# each edge has the form node1, node2, cost
edgeList = parts[2].split(';')
for edge in edgeList:
n1, n2, cost = edge.split(',')
n1 = int(n1)
n2 = int(n2)
cost = int(cost)
graph.addEdge(n1, n2, cost)
return graph
示例3: NewGraph
def NewGraph(self, Directed=1, Euclidean=1, IntegerVertexWeights=0, VertexWeights='None',
IntegerEdgeWeights=0, EdgeWeights='One', Grid=1):
if self.dirty == 1:
if not askokcancel("New Graph","Graph changed since last saved. Do you want to overwrite it?"):
return
G=None
self.SetGraphMenuDirected(Directed)
self.SetGraphMenuEuclidean(Euclidean)
self.SetGraphMenuIntegerVertexWeights(IntegerVertexWeights)
self.SetGraphMenuVertexWeights(VertexWeights)
self.SetGraphMenuIntegerEdgeWeights(IntegerEdgeWeights)
self.SetGraphMenuEdgeWeights(EdgeWeights)
self.SetGraphMenuGrid(Grid)
self.defaultButton.select()
G = Graph()
G.directed = Directed
G.euclidian = Euclidean
self.graphName = "New"
self.ShowGraph(G,self.graphName)
self.RegisterGraphInformer(WeightedGraphInformer(G,"weight"))
self.fileName = None
self.makeDirty()
self.dirty = 0
self.SetTitle("Gred %s - New Graph" % gatoVersion)
示例4: buildGraph
def buildGraph(wordFile):
# algorithm connects words (vertices) by placing them in a bucket whose name is a (wildcard)+string of letters(n-1)...
# ... that way only one letter varies
bucketDictionary = {}
# create the graph
g = Graph()
fileObject = open(wordFile)
# create buckets of words that differ by a letter
for line in fileObject:
word = line[:-1] # strip off '\n' character
for index in range(len(word)):
# _ indicates the wildcard character
bucket = word[:index] + '_' + word[index+1:]
# check if bucket has already been created..
# yes..-> append the word to the correct bucket
if bucket in bucketDictionary:
bucketDictionary[bucket].append(word)
else:
bucketDictionary[bucket]= [word]
# connect words in a bucket by creating an edge between them
for bucket in bucketDictionary.keys():
for word1 in bucket:
for word2 in bucket:
# do not check for one way relationship because this is a non-directed graph
if word1 != word2:
# add edge method creates vertices if they do not already exist
g.addEdge(word1, word2, 0)
fileObject.close()
return g
示例5: __init__
def __init__(self, vs, k, p):
Graph.__init__(self, vs, [])
self.add_regular_edges(k)
self.rewire(p)
self.assign_edge_lengths()
self.clust = self.clustering_coefficient()
self.length = self.average_length()
示例6: addEdge
def addEdge(u, v, weight):
Graph.addEdge(u, v);
queues[u].add(WeightedEdge(u, v, weight))
n = [u, v, weight]
self.edges.append([])
for i in n:
self.edges[len(self.edges) - 1].append(i)
示例7: PathTestMashUp
def PathTestMashUp(startPt, endPt, runDis, ):
startCor = GeoCode(startPt);
endCor = GeoCode(endPt)
miniGraph = Graph()
bounds = createMiniWorld(miniGraph, startCor, endCor)
startNode = [0, 0]
dist = miniGraph.findNearestNode(startCor, startNode)
print 'the closest node found to startPt is '+ str(startNode) +', with dist '+str(dist)
endNode = [0, 0]
dist = miniGraph.findNearestNode(endCor, endNode)
print 'the closest node found to endPt is '+str(endNode) +', with dist '+str(dist)
startNode = cor2ID(startNode)
endNode = cor2ID(endNode)
K=5
pathDict = miniGraph.findPath(startNode, endNode, runDis, K)
for k in range(0, K):
print 'The actual path dis is '+ str(pathDict[k]['cost'])
#print pathDict[k]['path']
return {'miniGraph': miniGraph,
'startPt':startCor,
'endPt':endCor,
'startNode':startNode,
'endNode':endNode,
'pathDict':pathDict}
示例8: main
def main(script, n='5', *args):
# create n Vertices
n = int(n)
#labels = string.ascii_lowercase + string.ascii_uppercase
#vs = [Vertex(c) for c in labels[:n]]
v = Vertex('v')
v.pos = (1110,-100)
w = Vertex('w')
w.pos = (20000,40)
x = Vertex('x')
x.pos = (100,-2000)
y = Vertex('y')
y.pos = (-15,15000)
# create a graph and a layout
g = Graph([v, w, x, y])
g.add_all_edges()
# layout = CircleLayout(g)
# layout = RandomLayout(g)
layout = CartesianLayout(g)
# draw the graph
gw = GraphWorld()
gw.show_graph(g, layout)
gw.mainloop()
示例9: repaint
def repaint():
canvas.delete("point")
if len(circles) == 0: return # Nothing to paint
# Build the edges
edges = []
for i in range(len(circles)):
for j in range(i + 1, len(circles)):
if distance(circles[i], circles[j]) <= 2 * radius:
edges.append([i, j])
edges.append([j, i])
graph = Graph(circles, edges)
tree = graph.dfs(0)
isAllCirclesConnected = \
len(circles) == tree.getNumberOfVerticesFound()
for [x, y] in circles:
if isAllCirclesConnected: # All circles are connected
canvas.create_oval(x - radius, y - radius, x + radius,
y + radius, fill = "red", tags = "point")
else:
canvas.create_oval(x - radius, y - radius, x + radius,
y + radius, tags = "point")
示例10: getRTTGraph
def getRTTGraph(self):
graph = Graph(self.conf.getNumNodes());
for i, node1 in enumerate(self.nodes):
for j, node2 in enumerate(self.nodes):
rtt = getNorm(getVet(node1, node2))
graph.addVertex(i, j, rtt)
return graph
示例11: PathTestMashUp
def PathTestMashUp(startPt, endPt, targetDis):
startCor = GeoCode(startPt);
endCor = GeoCode(endPt)
miniGraph = Graph()
bounds = createMiniWorld(miniGraph, startCor, endCor)
startNode = [0, 0]
dist = miniGraph.findNearestNode(startCor, startNode)
print 'the closest node found to startPt is '+ str(startNode) +', with dist '+str(dist)
endNode = [0, 0]
dist = miniGraph.findNearestNode(endCor, endNode)
print 'the closest node found to endPt is '+str(endNode) +', with dist '+str(dist)
startNode = cor2ID(startNode)
endNode = cor2ID(endNode)
myPath = miniGraph.MonteCarloBestPath(startNode, endNode, targetDis)
print 'The actual path dis is '+ str(myPath['dist'])
return {'miniGraph': miniGraph,
'startPt':startCor,
'endPt':endCor,
'startNode':startNode,
'endNode':endNode,
'dist': myPath['dist'],
'path': myPath['path']}
示例12: GraphTest
class GraphTest(unittest.TestCase):
def setUp(self):
self.v = Vertex('v')
self.w = Vertex('w')
self.x = Vertex('x')
self.y = Vertex('y')
self.z = Vertex('z')
self.e = Edge(self.v, self.w)
self.e2 = Edge(self.v, self.x)
self.g = Graph([self.v, self.w ,self.x, self.y],[self.e, self.e2])
def test_get_edge_not_exist(self):
edge = self.g.get_edge(self.v, self.y)
self.assertIsNone(edge)
def test_get_edge_exist(self):
edge = self.g.get_edge(self.v, self.w)
self.assertEqual(edge, self.e)
def test_remove_edge_is_removed( self ):
'''
La prueba checa si el Edge esta por ahi.
Depende de la funcion de get_edge
'''
edge = self.g.remove_edge( self.e )
self.assertIsNone( self.g.get_edge( self.v, self.w ) )
示例13: test_add_vertex
def test_add_vertex(self):
g = Graph()
# Tests that a label is used only once.
g.add_vertex(Vertex('label1'))
g.add_vertex(Vertex('label2'))
g.add_vertex(Vertex('label2'))
self.assertEqual(g, {Vertex('label1'):{}, Vertex('label2'):{}})
示例14: bfs
def bfs(self):
self.lines = True
graph = Graph(self.point, self.edge)
bfs = graph.bfs(eval(self.v1.get()))
order = bfs.getSearchOrders()
for i in range( 1, len(order)):
parent = bfs.getParent(i)
self.canvas.create_line(self.node[parent][0], self.node[parent][1], self.node[order[i]][0], self.node[order[i]][1], arrow = LAST, fill = "red")
示例15: create_Graph_from_file
def create_Graph_from_file(file_name):
graph = Graph()
with open(file_name) as inputfile:
next(inputfile)
for line in inputfile:
print line
graph.add_node_to_Graph(line)
return graph