本文整理汇总了Python中Graph.add_edge方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.add_edge方法的具体用法?Python Graph.add_edge怎么用?Python Graph.add_edge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Graph
的用法示例。
在下文中一共展示了Graph.add_edge方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: genrate_actualtour
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
def genrate_actualtour(self, StartCity):
"""
This method generates the graph of the bestTour.
It calls the move_branch method with a given StartCity. From the bestTour
stack it filters out only the interestCities by leaving out all the
intersection points. It then creates an instance of graph class in the same
order as in bestTour.
"""
tour = Stack() # create a new stack
self.currentTour.push(StartCity) # push the startCity in currentTour stack
self.mark_visit(StartCity) # mark it visited
self.move_branch(StartCity) # call move_branch recursive function, with the given city
# The following block of code removes vertices from bestTour and filters out
# only the interest points and adds it to tour Stack
while self.bestTour.size() != 0:
city = self.bestTour.pop()
if city in self.interestCities:
tour.push(city)
# The following block of code generates a Graph object from the tour Stack
newGraph = Graph(tour.items) # adds only the vertices in the graph
for i in range(len(tour.items)-1):
newEdge = Edge(tour.items[i], tour.items[i+1]) # create an edge within two consecutive vertices
newGraph.add_edge(newEdge) # add the edge to the graph
return newGraph
示例2: main
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
def main():
read = ReadMap()
read.read_file("test.map")
print read.names
grapher = BestPath(read.names[:5])
grapher.set_map(read.graph)
bestTour = grapher.genrate_actualtour(Vertex(read.names[4]))
print bestTour
newGraph = Graph(bestTour.items)
for i in range(len(bestTour.items) - 1):
newEdge = Edge(bestTour.items[i], bestTour.items[i + 1])
newGraph.add_edge(newEdge)
layout = RandomLayout(newGraph)
# draw the graph
gw = GraphWorld()
gw.show_graph(newGraph, layout)
gw.mainloop()
示例3: Graph
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
v = G.get_vertex(to)
if v.get_distance() > (u.get_distance() + u.get_weight(v)):
v.set_previous(u)
v.set_distance(u.get_distance() + u.get_weight(v))
#loop over all nodes and print their distances
for i in G.get_vertices():
u = G.get_vertex(i)
print "Node", u.get_vertex_ID(), "with distance", u.get_distance()
# Test Code
#create an empty graph
G = Graph()
#add vertices to the graph
for i in ["a", "b", "c", "d", "e"]:
G.add_vertex(i)
#add edges to the graph - need one for each edge to make them undirected
#since the edges are unweighted, make all cost 1
G.add_edge("a", "c", 6)
G.add_edge("a", "d", 3)
G.add_edge("b", "a", 3)
G.add_edge("c", "d", 2)
G.add_edge("d", "c", 1)
G.add_edge("d", "b", 1)
G.add_edge("e", "b", 4)
G.add_edge("e", "d", 2)
bellman_ford(G, "a")
示例4: Nearest_Neighbour
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
class Nearest_Neighbour(object):
def __init__(self, labels=[], coordinates = []):
self.cost_of_best_tour_so_far = float('inf') # sets cost of best tour to infinity inititally
self.cost_of_tour = 0 # cost of one tour
self.labels = labels # a list containing all the labels of the vertices
self.best_label = [] # a list containing all the labels for for a given tour
self.best_label_so_far = [] # a list containing all the labels for the best possible tour
self.all_coordinates = coordinates # a list containing all the given coordinates
self.coordinates = [] # a list containing the deep copy of the given coordinates
self.best_coordinates = [] # a list containing the coordinates in the order of travel for a given tour
self.best_coordinates_so_far = [] # a list containing the coordinates in the order of travel for the best possible tour
self.unvisited_cities = [] # a list containing all the unvivited citites(list of Vertex objects)
self.vertices = [Vertex(c) for c in self.labels] # a list of all the cities generated using all the labels
self.best_tour = Graph(self.vertices) # a graph object containing a given tour
self.best_tour_so_far = Graph(self.vertices) # a graph object containing the best tour so far
self.currentcity = None # Vertex object to contain the current city
self.currentcity_coordinate = () # a tuple containing the coordinates for the current city
self.startcity = None # Vertex containing the start city
self.nearestcity = None # Vertex containing the nearest city
self.cost_to_nearest_city = float('inf') # Cost of travelling to the nearest city
for i in range(len(self.vertices)):
self.vertices[i].pos = self.all_coordinates[i]
def mark_unvisited_cities(self):
'''
Marks all cities unvisited by resetting the list of coordinates and vertices
'''
self.coordinates = copy.deepcopy(self.all_coordinates) # adds all the coordinates back in self.coordiantes
self.vertices = [Vertex(c) for c in self.labels] # add all the vertices back in self.vertices
for i in range(len(self.vertices)):
self.vertices[i].pos = self.all_coordinates[i]
def empty_tour(self):
'''
Clears all the edges of the current tour
'''
self.best_tour = Graph(self.vertices) # resets self.best_tour to an empty graph containing vertices
self.best_label = [] # empties self.best_label
self.best_coordinates =[] # epmties self.best_coordinates
def calculate_nearneighbor(self):
"""
Pre: List of all unvisitied vertices
Post: Update the nearest city and cost of travelling to the nearest city
"""
for i in range(len(self.vertices)): # goes through each city
v = self.coordinates[i] # finds the coordinate of the next city
distance = ((self.currentcity_coordinate[0]-v[0])**2+(self.currentcity_coordinate[1]-v[1])**2)**0.5 # distance of travelling to the next city
if distance < self.cost_to_nearest_city:
self.cost_to_nearest_city = distance # if distance is less the update cost
self.nearestcity = self.vertices[i] # upade nearest city
def mark_visited(self):
'''
Pre: list of all unvisited citites
Post: pop current city from self.vertices and self.labels and add the city to best_coordinates and best_label
'''
self.currentcity_coordinate = self.coordinates[self.vertices.index(self.currentcity)] # gets the coordinate for current city before removing it from the list
i = self.vertices.index(self.currentcity) # gets index for the current city in the list of vertices
self.vertices.pop(i) # removes the vertex of current city from the self.vertices
n = self.coordinates.pop(i) # removes the cooordinate of current city from self.coordinates
self.best_label.append(self.currentcity.label) # adds the current cities label to the best_label
self.best_coordinates.append(n) # adds the current city to the list of best_coordinates
def add_currcity_tour(self):
"""
Pre:
Post: creates an edge between current city and nearest city
"""
e = Edge(self.currentcity, self.nearestcity) # creates and edge between current city and nearest city
self.best_tour.add_edge(e) # adds the edge to the graph best_tour
def add_tourCost(self):
"""
Pre: Takes in two parameters, the nearest city and the current city
Post: Calculates the tourCost (i.e. calculates the distance between currentcity and nearest city)"""
self.cost_of_tour += self.cost_to_nearest_city # updates tour_cost
self.cost_to_nearest_city = float('inf') # resets cost_to_nearest city to infinity
示例5: generate_cfg
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
def generate_cfg(self, start_addr, ret_addr=None, start_clnum=0, end_clnum=0):
if start_clnum == 0:
start_clnum = self.t.get_minclnum() + 1
if end_clnum == 0:
end_clnum = self.t.get_maxclnum() - 1
traces = []
enter_call = 0
enter_sub_call = 0
for i in range(start_clnum, end_clnum + 1):
pc = self.get_pc(i)
asm = self.get_disasm(pc)
if enter_call == 0:
if pc == start_addr:
if ret_addr is None:
end_addr = self.get_ret_addr(i - 1)
print hex(end_addr)
else:
end_addr = ret_addr
enter_call = 1
trace = [(i, pc, asm)]
else:
if end_addr == pc:
print 'exit call'
enter_call = 0
traces.append(trace)
trace = []
if enter_sub_call == 0:
trace.append((i, pc, asm))
if asm.startswith('call'):
enter_sub_call = 1
sub_call_ret = self.get_ret_addr(i)
else:
if pc == sub_call_ret:
trace.append((i, pc, asm))
enter_sub_call = 0
graph = Graph()
pcs = []
for trace in traces:
print trace
for trace in traces:
exist_node = None
exist_index = 1
new_node = None
for ins in trace:
if ins[1] not in pcs:
pcs.append(ins[1])
if exist_node is None:
if new_node is None:
new_node = Node([Assemble(ins[1], ins[2])])
graph.add_node(new_node)
else:
new_node.add_asm(Assemble(ins[1], ins[2]))
else:
new_node = Node([Assemble(ins[1], ins[2])])
graph.add_node(new_node)
if len(exist_node.asm_seqs) == exist_index:
graph.add_edge(exist_node, new_node)
else:
node1, node2 = graph.split_node(exist_node, exist_index, count=exist_node.count - 1)
graph.add_edge(node1, new_node)
exist_node = None
exist_index = 0
else:
if exist_node is None:
if new_node is None:
exist_node = graph.search_and_split(ins[1])
exist_node.add_count()
exist_index = 1
else:
node, index = graph.search_node(ins[1])
if index == 0:
graph.add_edge(new_node, node)
node2 = node
else:
node1, node2 = graph.split_node(node, index)
if node == new_node:
graph.add_edge(node2, node2)
else:
graph.add_edge(new_node, node2)
new_node = None
exist_node = node2
node2.add_count()
exist_index = 1
else:
if new_node is None:
if len(exist_node.asm_seqs) == exist_index:
node3 = graph.search_and_split(ins[1])
graph.add_edge(exist_node, node3)
exist_node = node3
node3.add_count()
exist_index = 1
else:
if exist_node.asm_seqs[exist_index].addr == ins[1]:
exist_index += 1
#.........这里部分代码省略.........
示例6: Graph
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
v = G.get_vertex(t[1])
#for each vertex w adjacent to v
for w in v.get_connections():
if w.get_distance() > (v.get_distance() + v.get_weight(w)):
w.set_previous(v)
w.set_distance(v.get_distance() + v.get_weight(w))
#loop over all nodes and print their distances
for v in G:
print "Node", v.get_vertex_ID(), "with distance", v.get_distance()
# Test Code
#create an empty graph
G = Graph()
#add vertices to the graph
for i in ["a", "b", "c", "d", "e"]:
G.add_vertex(i)
#add edges to the graph - need one for each edge to make them undirected
#since the edges are unweighted, make all cost 1
G.add_edge("a", "b", 4)
G.add_edge("a", "c", 1)
G.add_edge("b", "e", 4)
G.add_edge("c", "b", 2)
G.add_edge("c", "d", 4)
G.add_edge("d", "e", 4)
dijkstra(G, "a")
示例7: Vertex
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
"""
from Graph import *
from Dist import Dist
# make the initial graph
v1 = Vertex()
v2 = Vertex()
e = Edge(v1, v2)
g = Graph([v1, v2], [e])
# add new vertices and edges
for i in range(2000):
v1 = Vertex()
v2 = g.random_vertex()
e = Edge(v1, v2)
g.add_vertex(v1)
g.add_edge(e)
# plot the histogram of degrees
d = Dist()
vs = g.vertices()
for v in vs:
d.count(v.degree)
d.plot_ccdf(loglog)
show()
示例8: print
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
for w in v.get_connections():
if w.get_distance() is None:
w.set_previous(v)
w.set_distance(1 + v.get_distance())
q.enqueue(w)
#loop over all nodes and print their distances
for v in g:
print("Node", v.get_vertex_ID(), "with distance", v.get_distance())
#create an empty graph
g = Graph()
#add vertices to the graph
for i in ["a", "b", "c", "d", "e"]:
g.add_vertex(i)
#add edges to the graph - need one for each edge to make them undirected
#since the edges are unweighted, make all cost 1
g.add_edge("a", "b", 1)
g.add_edge("a", "d", 1)
g.add_edge("b", "d", 1)
g.add_edge("b", "e", 1)
g.add_edge("c", "a", 1)
g.add_edge("c", "f", 1)
g.add_edge("d", "f", 1)
g.add_edge("d", "g", 1)
g.add_edge("e", "g", 1)
g.add_edge("g", "f", 1)
unweighted_shortest_path(g, "a")
示例9: TwoOpt
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
#.........这里部分代码省略.........
def generate_rand_graph(self):
'''
Pre: A list if lables and coordinates
Post: Updates self.tour with a randomly generated graph and
and updates self.costOfTour with the cost of that generated tour
'''
copyOfLabels = copy.deepcopy(self.labels) # creates a copy of labels
copyofCoordinates = copy.deepcopy(self.coordinates) # creates a copy of coordinates
self.tour_edges = [] # reset tour edges
self.tour_vertices = [] # reset tour vertices
i = random.randrange(0, len(copyOfLabels)) # generate a random first city
start_city = Vertex(copyOfLabels.pop(i))
start_city.pos = copyofCoordinates.pop(i)
previous_city = start_city # assign start city to previous city
self.tour_vertices.append(start_city) # append it to tour vertices
for x in range(len(copyOfLabels)): # find the next random naumber
i = random.randrange(0, len(copyOfLabels))
v = Vertex(copyOfLabels.pop(i)) # pop that vertex at that random number
v.pos = copyofCoordinates.pop(i) # pop out the coordinate for that vertex and create that new vertex
self.tour_vertices.append(v) # append it to the list
e = Edge(previous_city, v) # create a new edge between the previous city and new randomly generated city
self.tour_edges.append(e) # append the edge to edge list
self.costOfTour += self.cal_distance_of_edge(e) # update the cost of the tour for travelling to the new city
previous_city = v # assign the new city to previous city
e = Edge(previous_city, start_city) # join the last edge to go back to the start city
self.tour_edges.append(e)
self.tour = Graph(self.tour_vertices, self.tour_edges)
self.costOfTour += self.cal_distance_of_edge(e) # update teh cost of the tour for going back to the start city
def generate_rand_vertices(self):
'''
Pre: self.tour is a randomly generated graph
Post: Randomly select two indices from the vertex list, whose subsequent vertices are note same.
'''
index_list = list(xrange(len(self.tour_vertices))) # creates an list of indices of tour_vertices
ran_num = random.randrange(len(index_list)-1) # finds a random index
self.index1 = index_list[ran_num]
# creates a new list separating the already selected index and the indices before and after the selected index.
if self.index1 == 0:
new_index_list = index_list[2:-1]
elif self.index1 == len(index_list)-1:
new_index_list = index_list[1:len(index_list)-2]
else:
new_index_list = index_list[ran_num+2:]+ index_list[:ran_num-1]
ran_num_2 = random.randrange(len(new_index_list)-1) # find a second random index from the new list
self.index2 = new_index_list[ran_num_2]
def find_random_edge(self):
'''
find the corresponding edges from the list of vertices using the randomly generated indices
'''
x1 = self.tour_vertices[self.index1-1]
y1 = self.tour_vertices[self.index1]
x2 = self.tour_vertices[self.index2-1]
y2 = self.tour_vertices[self.index2]
self.edge1 = Edge(x1, y1)
self.edge2 = Edge(x2, y2)
def remove_edges(self):
"""
Pre: edge1 and edge2 should be given by generate random edges
Post: Removes edge1 and edge2 from self.tour"""
self.tour.remove_edge(self.edge1)
self.tour.remove_edge(self.edge2)
def find_new_edge(self):
'''
Switch (x1,y1) and (x2,y2) with (x1, x2) and (y1, y2) for creating two new edge
'''
x1 = self.tour_vertices[self.index1-1]
y1 = self.tour_vertices[self.index1]
x2 = self.tour_vertices[self.index2-1]
y2 = self.tour_vertices[self.index2]
self.new_edge1 = Edge(x1, x2) # create a new edge by switching the vertices
self.new_edge2 = Edge(y1, y2)
def add_edge_reversely(self):
'''
Pre: self.new_edge1 and self.new_edge2 is present
Post: Updates the self.tour with two newly generated edges
'''
self.tour.add_edge(self.new_edge1)
self.tour.add_edge(self.new_edge2)
# updates the self.tour_vertices such that vertices are in sequential order of a directed graph
if self.index1 < self.index2:
reverse_lis = self.tour_vertices[self.index1:self.index2]
reverse_lis.reverse() # reverses the part of the vertices list in the middle of two chosen vertices
self.tour_vertices = self.tour_vertices[:self.index1] + reverse_lis + self.tour_vertices[self.index2:]
else:
reverse_lis = self.tour_vertices[self.index2:self.index1]
reverse_lis.reverse()
self.tour_vertices = self.tour_vertices[:self.index2] + reverse_lis + self.tour_vertices[self.index1:]
示例10: ReadMap
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
class ReadMap(object):
"""This class reads a database file with .map extension
Attributes:
header: a list containing the header section of the file
filename: The name of the database
graph: a graph object generated after reading the file, initially empty
names: a list that only consists of the names of the buildings in the map
"""
def __init__(self):
self.header = []
self.filename = ""
self.graph = Graph()
self.names = []
def read_file(self, filename):
"""Reads an ASCII file with .map extension to crate the map of campus
Reads an An ASCII file where each line will be an edge.
The first column will contain a vertex, second column a vertex, and third column
will contain distance of the edge. All the column separated by spaces.
Update self.graph and self.names by extracting the edges from the file.
"""
f = open(filename, "r")
for i in range(5):
self.header.append(f.readline()) # reads and stores the header section of the file
line = f.readline()
while line != "EOF":
sp_line = line.split() # split the first line by spaces
v1 = Vertex(sp_line[0]) # create the first vertex obj from the first column
v2 = Vertex(sp_line[1]) # create second vertex obj from secomd column
newEdge = Edge(v1, v2) # create and edge between those two edges
if v1 not in self.graph.vertices(): # if v1 is not already added
self.graph.add_vertex(v1) # add that to the graph
# the following block is trick used to extrach the names of the buildings
# all the vertex labels other than name of buildings have been stored as numbers
# so every vertex label is first tried to convert into number
# if the label is not a number, it raises the exception, and we know
# that it is the name of the buiding
try:
a = int(v1.label)
except:
self.names.append(v1.label)
if v2 not in self.graph.vertices():
self.graph.add_vertex(v2)
try:
a = int(v2.label)
except:
self.names.append(v2.label)
self.graph.add_edge(newEdge) # add the edge to the graph
newEdge.set_distance(int(sp_line[2])) # set the distance of the edge
line = f.readline()
self.filename = filename # updates the filename
示例11: __init__
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import add_edge [as 别名]
class VisibilityGraph:
def __init__(self):
self.graph = Graph()
self.start_node_index = None
self.goal_node_index = None
self.obstacles = None
self.shortest_path = None
self.wall = None
'''
start_point: object of class Point
goal_point: object of class Point
obstacles: list of objects of class Obstacle
'''
def construct_visibility_graph(self, start_point, goal_point, obstacles, wall):
self.obstacles = obstacles
self.wall = wall
# if start point or goal point is inside obstacles,
# then we certainly can not find a collision-free path from start point to end point
# here we set current_obstacle_index to -1 because start_point and end_point are not vertices of any obstacles
# what if start_point or end_point is vertex of some obstacle? (answered)
# answer: no difference. no effect
if start_point.is_in_obstacles(obstacles, -1) == True:
print('error. start point is inside an obstacle')
exit(1)
if goal_point.is_in_obstacles(obstacles, -1) == True:
print('error. goal point is inside an obstacle')
exit(1)
start_point.set_to_be_visible()
goal_point.set_to_be_visible()
node_index = -2 # index of nodes, auxiliary variable to help construct graph
node_index += 1
start_point.set_index(node_index)
start_node = Node(start_point.get_index(), start_point.get_x_coord(), start_point.get_y_coord())
self.start_node_index = node_index
self.graph.add_node(start_node) # add start_node to graph
node_index += 1
goal_point.set_index(node_index)
goal_node = Node(goal_point.get_index(), goal_point.get_x_coord(), goal_point.get_y_coord())
self.goal_node_index = node_index
self.graph.add_node(goal_node) # add goal_node to graph
# add all visible vertices of obstacles into visibility graph
# for a vertex of a obstacle, we should judge whether or not it inside other obstacles
# previous: judge whether of not it is inside one obstacle (considering all obstacles)
# previous method is unreasonable. (bug fixed)
# add variable current_obstacle_index to keep track of the obstacle that the vertex comes from
current_obstacle_index = 0 # the index of obstacle in obstacles (a list of object of class Obstacle)
for obstacle in obstacles:
for vertex in obstacle.get_all_vertices():
node_index += 1
vertex.set_index(node_index)
if vertex.is_in_obstacles(obstacles, current_obstacle_index) == False:
vertex.set_to_be_visible()
vertex_node = Node(vertex.get_index(), vertex.get_x_coord(), vertex.get_y_coord())
self.graph.add_node(vertex_node)
current_obstacle_index += 1
# add all visible edges of obstacles into visibility graph
current_obstacle_index = 0
for obstacle in obstacles:
for edge in obstacle.get_all_edges():
seg_start_point = edge.get_seg_start_point()
seg_end_point = edge.get_seg_end_point()
if (seg_start_point.is_visible() == True) and (seg_end_point.is_visible() == True):
if edge.is_intersected_with_an_obstacle(self.wall):
continue
# TODO
copy_obstacle_index = 0
copy_obstacles = []
for copy_obstacle in obstacles:
if copy_obstacle_index == current_obstacle_index:
copy_obstacle_index += 1
continue
copy_obstacles.append(copy_obstacle)
copy_obstacle_index += 1
if (edge.is_in_some_obstacle(copy_obstacles) == False):
for other_obstacle in copy_obstacles:
if edge.is_intersected_with_an_obstacle(other_obstacle):
continue
self.graph.add_edge(self.graph.get_node_by_index(seg_start_point.get_index()),
self.graph.get_node_by_index(seg_end_point.get_index()))
current_obstacle_index += 1
start_to_goal_segment = Segment(start_point, goal_point)
if start_to_goal_segment.is_intersected_with_obstacles(obstacles, -1, -1, -1, -1, self.wall) == False:
self.graph.add_edge(self.graph.get_node_by_index(start_point.get_index()),
self.graph.get_node_by_index(goal_point.get_index()))
# add all visible edges connecting start_point to vertices of obstacles into visibility graph
obstacle_index = 0
for obstacle in obstacles:
vertex_index = 0
for vertex in obstacle.get_all_vertices():
if vertex.is_visible() == False:
vertex_index += 1
#.........这里部分代码省略.........