本文整理汇总了Python中Graph.addEdge方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.addEdge方法的具体用法?Python Graph.addEdge怎么用?Python Graph.addEdge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Graph
的用法示例。
在下文中一共展示了Graph.addEdge方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: initGraph
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
def initGraph(data):
g = Graph()
for i in range(len(data)/2):
g.addNode(i)
for j in range(i):
g.addEdge(i, j, distance(float(data[i * 2]) * scale, float(data[i * 2 + 1]) * scale, float(data[j * 2]) * scale, float(data[j * 2 + 1]) * scale))
return g
示例2: graph_creationF
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
class graph_creationF(object):
def __init__(self, weighted, wgraph):
self.fname = wgraph
self.wg = weighted
self.g = Graph()
def get_file(self, which_alg):
self.g.alg = which_alg
try:
#self.fname = raw_input("Enter graph file: ")
#self.wg = raw_input("Do you want to create a weighted Graph? ")
file = open(self.fname, 'r')
if self.wg[0] == 'y' or self.wg[0] == 'Y':
for line in file:
s = line.split()
self.g.addEdge(s[0], s[1], int(s[2]))
elif self.wg[0] == 'n' or self.wg[0] == 'N':
for line in file:
s = line.split()
self.g.addEdge(s[0], s[1], 1)
file.close()
return self.g
except:
print "-----Graph File does not exist-----"
示例3: main
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
def main():
v1 = Vertex('A')
v2 = Vertex('B')
v3 = Vertex('C')
e1 = Edge(v1,v3)
e = Edge(v1,v2)
print e
g = Graph()
g.addVertex(v1)
g.addVertex(v2)
g.addVertex(v3)
print g.addEdge(e)
print g.addEdge(e1)
print g
print "Will try to delete edge"
print g.delEdge(v1,v2)
print g
v4 = Vertex('A')
g.delVertex(v4)
print g
示例4: main
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
def main():
g = Graph()
for i in range(6):
g.addVertex(i)
g.addEdge(0,1,5)
g.addEdge(0,5,2)
g.addEdge(1,2,4)
g.addEdge(2,3,9)
g.addEdge(3,4,7)
g.addEdge(3,5,3)
g.addEdge(4,0,1)
print "result:"
connected = BFS(g,0,3)
print connected
示例5: loadGraph
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
def loadGraph():
graph = Graph()
try:
aux = open(sys.argv[2])
for line in aux:
line = line.replace(':',',').replace('\n','').split(',')
v1 = Vertex(line[0])
graph.addVertex(v1)
for n in range(1,len(line)):
if not line[n]:
continue
v2 = Vertex(line[n])
if (not graph.isVertex(v2)):
graph.addVertex(v2)
graph.addEdge(v1,v2)
return graph
except KeyError:
print "An error has occurred"
except IndexError:
usage()
except IOError:
print "Verify parameters, input file does not exist"
return False
示例6: FSM
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
class FSM(object):
def __init__(self):
self.name = "go"
self.actionset = []
self.startstates = []
self.edgeset = []
self.cases = []
self.g = None
def generateEdgeByState(self, state):
untracked = [state]
tracked = []
edgset = []
while(len(untracked) > 0):
midstates = []
state = untracked.pop()
tracked.append(state)
for action in self.actionset:
#get new status
newsta = action.transfer(copy.deepcopy(state))
#get new edge
edge = Edge(state,newsta, 0, action)
#add to edge set if it's new
if not edge in edgset:
edgset.append(edge)
#add to midstatus set if it's a new state
if not newsta in tracked and not newsta in midstates:
midstates.append(newsta)
untracked = midstates
return edgset
def generateEdge(self):
#generate all edges
for start in self.startstates:
self.edgeset += self.generateEdgeByState(start)
self.edgeset = list(set(self.edgeset))
def explore(self):
self.g = Graph()
#generate all edges
self.generateEdge()
#add all edges in graph
self.g.addEdge(self.edgeset)
#set start states
self.g.setVexPtype(self.startstates, 1)
self.g.eulerize()
edges = self.g.getEurlerCircuit()
'''
print "===========Eu=========="
self.g.outputpath(edges)
print "===========End========="
'''
self.cases = self.g.getPathSet(edges)
def execute_one(self, case):
for edge in case:
print "executing " + edge.action.name + " ... ..."
if not edge.action.execute():
return False
return True
def execute(self):
for case in self.cases:
print "=============Execution================"
result = self.execute_one(case)
print("================%s=================" % str(result) )
def dumpcase(self):
i = 0
for case in self.cases:
print("Case " + str(i) + ": " ),
self.g.outputpath(case)
i+=1
def savesvg(self):
self.g.savesvg()
示例7: __init__
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
class DotParser:
def __init__(self):
self.Graph = Graph()
self.FileName = None
def readFile(self, filename):
self.FileName = filename
FILE = open(filename,'r')
FILE = FILE.read()
# find outer { }
outer = 0
for x in FILE:
outer = outer + 1
if x == "{":
break
if outer == 0:
print "ERROR"
exit()
outerClose = outer
braceStack = 1
for x in range(outer,len(FILE)):
if FILE[x] == "{":
braceStack = braceStack + 1
if FILE[x] == "}":
braceStack = braceStack - 1
if braceStack == 0:
break
outerClose = outerClose + 1
header = FILE[:outer-1]
self.readNameAndType(header)
# From within the outer { } braces, we parse the graph
graphText = FILE[outer:outerClose].strip().split("\n")
commentBlock = False
for line in graphText:
# Strip away surrounding whitespace
line = line.strip()
#Handling comments
if commentBlock and ("*/" not in line):
continue
elif "*/" in line:
commentBlock = False
line = line[line.index("*/")+2:]
if "/*" in line:
commentBlock = True
line = line[:line.index("/*")]
if "//" in line:
line = line[:line.index("//")]
if len(line) == 0:
continue
# Gets rid of the semicolon at the end.
if line[-1] == ";":
line = line[:-1]
# Directed Edges
if "->" in line:
#Strip away the edge attributes
(line,attributes) = stripAttributes(line)
edgeLine = line.strip().split("->")
n1 = Node(edgeLine[0].strip())
n2 = Node(edgeLine[1].strip())
e = Edge(n1,n2,"->")
self.Graph.addEdge(e)
# Undirected Edges
elif "--" in line:
#Strip away the edge attributes
(line,attributes) = stripAttributes(line)
edgeLine = line.strip().split("--")
n1 = Node(edgeLine[0].strip())
n2 = Node(edgeLine[1].strip())
e1 = Edge(n1,n2,"--")
e2 = Edge(n2,n1,"--")
e1.Attributes = attributes
e2.Attributes = attributes
self.Graph.addEdge(e1)
self.Graph.addEdge(e2)
elif "[" in line and "]" in line:
#Information about the node
(line,attributes) = stripAttributes(line)
name = line.strip()
n = Node(name)
n.Attributes = attributes
self.Graph.addNode(n)
for n in self.Graph.AdjacencyList:
self.Graph.addNode(n)
return self.Graph
#.........这里部分代码省略.........
示例8: DotParser
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
if __name__ == "__main__":
parser = DotParser()
n1 = Node("A")
print n1
n2 = Node("B")
print n2
e1 = Edge(n1,n2, "--")
print e1
g = Graph("Z")
g.addEdge(e1)
print g
print "----"
print
#try:
filename = argv[1]
graph = parser.readFile(filename)
print graph
# except(IndexError):
# print "ERROR: No file given"
示例9: Stack
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
#Creates a stack and tests a stack of 10 integers. Implements LIFO 0 goes in first up to 9 then nine comes out first
sizeofstack = 10
i = 0;
stack = Stack()
while i < sizeofstack:
stack.push(i)
i += 1
print "testing stack"
while stack.checkSize() != 0:
print stack.pop()
print " "
#Graph
#creates a Graph intially with 10 unconnected nodes then randomly connects the nodes
#then randomly searches for 5 nodes
graph = Graph()
i = 0
while i < 10:
graph.addVertex(i)
i += 1
i = 0
while i < 20:
graph.addEdge(randint(0,9), randint(0,9))
i += 1
i = 0
while i < 5:
graph.findVertex(randint(0,10))
i += 1
示例10: sleep
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
alt = dist[u] + unb[nb][0]
if Q.check(nb) :
reng = render.render(graph,dist,c_dist,tup=tup)
if alt < dist[nb]:
#print 'altered',nb,dist[nb],'->',alt
dist[nb] = alt
sleep(1.25)
#reng = render.render(graph,'0')
#prev[nb] = u
Q.editPriority([nb,alt])# changed Q.editPriority([v,alt]) --> ...([nb,alt] )
reng = render.render(graph,dist,c_dist,tup=tup)
#return dist[tar_id]
[n,m] = map(int,raw_input().split())
graph = Graph()
#dumb_graph = Graph()
for i in range(m):
[u,v,d] = map(int, raw_input().split())
graph.addEdge(u,v,d)
graph.addEdge(v,u,d)
#dumb_graph.addEdge(u,v,d)
k = int(raw_input())
for i in range(k):
[u,v] = map(int, raw_input().split())
print dij(graph,u,v)
示例11: __init__
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
def __init__(self):
graph = Graph()
self.outFile = open("output", 'w')
try:
filename = sys.argv[1]
f = open(filename, 'r')
for line in f:
split = line.split()
graph.addEdge(split[0], split[1], split[2])
f.close()
except IndexError:
print("Input file was not passed while calling the function")
while(True):
userInput = input().split()
if userInput == None or len(userInput) == 0:
continue
self.writeInFile(" ".join(userInput))
command = userInput.pop(0)
if command == "print":
if len(userInput) != 0:
print("print wont take argument.\nUsage :print")
continue
for key,value in sorted(graph.vertexMap.items()):
if not graph.vertexMap[key].status:
key += " DOWN"
print(key)
self.writeInFile(key)
orderedAdj = sorted(value.adj, key = lambda x: x.destination.name)
for edge in orderedAdj :
s = ""
if not edge.status:
s = "DOWN"
self.writeInFile((" %s %s %s" %(edge.destination.name, edge.transit_time, s)))
print(" %s %s %s" %(edge.destination.name, edge.transit_time, s))
self.writeInFile("")
elif command=="addedge":
if len(userInput) != 3:
print("addedge takes exactly 3 arguments.\nUsage :addedge <source Vertex> "
"<destination Vertex> <transit time>")
continue
tailvertex, headvertex, transit_time = userInput[0],userInput[1], userInput[2]
graph.updateEdge(tailvertex, headvertex, transit_time)
elif command == "deleteedge":
if len(userInput) != 2:
print("addedge takes exactly 2 arguments.\nUsage :deleteedge <source Vertex> "
"<destination Vertex>")
continue
tailvertex, headvertex = userInput[0],userInput[1]
graph.deleteEdge(tailvertex, headvertex)
elif command == "edgeup":
if len(userInput) != 2:
print("edgeup takes exactly 2 arguments.\nUsage :edgeup <source Vertex> "
"<destination Vertex>")
continue
tailvertex, headvertex = userInput[0],userInput[1]
graph.upEdgeStatus(tailvertex, headvertex)
elif command == "edgedown":
if len(userInput) != 2:
print("edgedown takes exactly 2 arguments.\nUsage :edgedown <source Vertex> "
"<destination Vertex>")
continue
tailvertex, headvertex = userInput[0],userInput[1]
graph.downEdgeStatus(tailvertex, headvertex)
elif command == "vertexup":
if len(userInput) != 1:
print("vertexup takes exactly 1 argument.\nUsage :vertexup <Vertex name>")
continue
vertex = userInput[0]
graph.upVertexStatus(vertex)
elif command == "vertexdown" :
if len(userInput) != 1:
print("vertexdown takes exactly 1 argument.\nUsage :vertexdown <Vertex name>")
continue
vertex = userInput[0]
graph.downVertexStatus(vertex)
elif command == "reachable":
if len(userInput) != 0:
print("reachable wont take argument.\nUsage :reachable")
continue
# BFS(graph).printReachableVerticesFromAllSource()
self.graph = graph
bfs = BFS(self.graph)
self.printReachableVerticesFromAllSource(bfs)
elif command == "path":
if len(userInput) != 2:
print("vertexdown takes exactly 2 argument.\nUsage :path <source Vertex>"
" <destination Vertex>")
continue
source, destination = userInput[0],userInput[1]
dijkstra = Dijkstra()
#.........这里部分代码省略.........
示例12: __init__
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import addEdge [as 别名]
class Robot:
def __init__(self, sensors, motion, initialPosition, name):
self.sensors = sensors
self.motion = motion
# initialize the graph
self.graph = Graph()
self.name = name
# create a first node for the initial position
node = Node(initialPosition, "position", 0)
node.robot = self.name
self.graph.addNode(node)
# add a prior
edge = PriorEdge(initialPosition, node, np.diag([1e-20,1e-20,1e-20]))
self.graph.addEdge(edge)
# keep track of the most recent position for dead reakoning
self.pos = initialPosition
self.posNode = node # node of the current position
def move(self, cmd):
"""create a new node and edge with dead reakoned initial value"""
nextPos = self.motion.move(self.pos, cmd)
# create a new node for the next position
# the descriptor is the index in time
nextPosNode = Node(nextPos, "position", self.posNode.descriptor + 1)
nextPosNode.robot = self.name
self.graph.addNode(nextPosNode)
# create a new edge between them
edge = MotionEdge(self.motion, cmd, self.posNode, nextPosNode, "motion")
self.graph.addEdge(edge)
# update internal state
self.pos = nextPos
self.posNode = nextPosNode
def simSense(self, simMap, simPos):
"""
Simulate sensing landmarks on a map. The simulator gives the
robots actual position.
Create a new node for the landmark if necessay with a dead
reakoned initial value with respect to the position node.
"""
for sensor in self.sensors:
sensorObsverations = sensor.simSense(simPos, simMap)
for lmObs in sensorObsverations:
# check if this landmark has been observed before
lmNode = self.graph.getNodeOfTypeAndDescriptor(lmObs['sensorType'], lmObs['descriptor'])
if lmNode == None:
# if this landmark hasn't been observed before
# create a new node
lmPos = sensor.deadReckon(self.pos,lmObs['obs'])
# print self.pos
# print lmPos
# print lmObs['obs']
# wait()
lmNode = Node(lmPos, lmObs['sensorType'], lmObs['descriptor'])
self.graph.addNode(lmNode)
else:
# update landmark guess as the average
lmPos = sensor.deadReckon(self.pos,lmObs['obs'])
lmNode.value = (lmNode.value + lmPos)/2.
# create an edge between the nodes
edge = ObservationEdge(sensor, lmObs['obs'], self.posNode, lmNode, "observation")
self.graph.addEdge(edge)
def reset(self):
# initial position
node = self.graph.nodes[0]
# prior
edge = self.graph.edges[0]
self.posNode = node
self.pos = node.value
self.graph = Graph()
self.graph.addNode(node)
self.graph.addEdge(edge)
def trajectory(self):
positions = self.graph.getNodesOfType("position")
sortedPos = sorted(positions, key=lambda x: x.descriptor)
traj = map(lambda x: x.value, sortedPos)
return array(traj)
def trajectoryXY(self):
positions = filter(lambda x: x.nodeType == "position" and x.robot == self.name, self.graph.nodes)
sortedPos = sorted(positions, key=lambda x: x.descriptor)
traj = map(lambda x: x.value, sortedPos)
traj = array(traj)
return traj[:, 0:2] # hack off the angle
def position(self):
traj = self.trajectory()
#.........这里部分代码省略.........