示例#1
0
    def shortest_path(self, origin, destination, weighted_poly):
        """Find and return shortest path between origin and destination.

        Will return in-order list of Points of the shortest path found. If
        origin or destination are not in the visibility graph, their respective
        visibility edges will be found, but only kept temporarily for finding
        the shortest path. 
        """

        origin_exists = origin in self.visgraph
        dest_exists = destination in self.visgraph
        if origin_exists and dest_exists:
            return shortest_path(self.visgraph, origin, destination,
                                 weighted_poly)
        orgn = None if origin_exists else origin
        dest = None if dest_exists else destination
        add_to_visg = Graph([])
        if not origin_exists:
            for v in visible_vertices(origin, self.graph, destination=dest):
                add_to_visg.add_edge(Edge(origin, v))
        if not dest_exists:
            for v in visible_vertices(destination, self.graph, origin=orgn):
                add_to_visg.add_edge(Edge(destination, v))
        return shortest_path(self.visgraph, origin, destination, weighted_poly,
                             add_to_visg)
示例#2
0
def traverse(player, destination):
    #find a path to the destination
    path = shortest_path(player.current_room, destination, player.abilities)
    print(f'{player.name} is traveling to room {destination}')
    print(f"{player.name}'s path: {path}")

    while path is not None:
        #must be faster to teleport to the beginning
        if path[0] is 'recall' and 'recall' in player.abilities:
            room_info = player.recall()
            print(f'{player.name} recalled to room {room_info["room_id"]}')

        elif 'dash' in player.abilities and len(
                path) > 1 and path[0][1] == path[1][1]:
            room_ids = []
            current_direction = path[0][1]
            for room in path:
                if room[1] == current_direction: room_ids.append(room[0])
                else: break
            room_info = player.dash_to(current_direction, room_ids)
            print(
                f'{player.name} dashed through {room_ids} to room {room_ids[-1]}'
            )

        else:
            room_info = player.move_to(path[0][1], path[0][0])
            print(f'{player.name} moved {path[0][1]} to room {path[0][0]}')

        path = shortest_path(player.current_room, destination,
                             player.abilities)

    print(f'{player.name} has arrived at room {destination}.')
示例#3
0
	def calculateGraphDiameter(self):
		connected=self.__graph.isConnected()
		if connected==1:
			diameter={}
			for s in self.__switch:
				self.__sp[s]=priority_dict.priority_dict()
				diameter[s]=0
				sp=shortest_path.shortest_path(self.__switch,self.__edges)
				dist=sp.shortestPath(s)
				
				self.__sp[s]=dist.copy()

				while (dist and dist[dist.smallest()]!=999999999999):
					diameter[s]=dist[dist.smallest()]
					dist.pop_smallest()

			i=0
			max_d=0
			for k,v in diameter.iteritems():
				if i==0:
					max_d=diameter[k]
				else:
					if (diameter[k]>max_d):
						max_d=diameter[k]
				i=i+1
			self.__graphDiameter=max_d
示例#4
0
    def timeToDeliver(self, path_str):
        start, end, graph = self.create_graph(path_str)           

        path = shortest_path(graph, start, end)
        dist = shortest_distance(graph, start, end)
        instructions = self.get_min_moves(path)
        cost = self.get_cost(instructions)

        return path, dist, instructions, cost
示例#5
0
    def timeToDeliver(self, path_str):
        start, end, graph = self.create_graph(path_str)

        path = shortest_path(graph, start, end)
        dist = shortest_distance(graph, start, end)
        instructions = self.get_min_moves(path)
        cost = self.get_cost(instructions)

        return path, dist, instructions, cost
示例#6
0
 def __init__(self, color, pos):
     self.color = color
     self.head = block(pos)
     self.body.append(self.head)
     self.directionX = 0
     self.directionY = 1
     self.human = human()
     self.shortest = shortest_path()
     self.longest = longest_path()
     self.hamilton = hamilton()
示例#7
0
    def lowest(self, harmful_areas, deadly_areas):
        
        matrix = list()
        for row in range(0, size):
            row = list()
            matrix.append(row)

            for col in range(0, size):
                row.append(safe)
        
        for h in harmful_areas:
            x1, y1, x2, y2 = [int(n) for n in h.split()]
            for i in range(min(x1, x2), max(x1, x2) + 1):
                for j in range(min(y1, y2), max(y1, y2) + 1):
                    matrix[i][j] = harmful

        for d in deadly_areas:
            x1, y1, x2, y2 = [int(n) for n in d.split()]
            for i in range(min(x1, x2), max(x1, x2) + 1):
                for j in range(min(y1, y2), max(y1, y2) + 1):
                    matrix[i][j] = deadly 

        graph = {}
        for i in range(0, size):
            for j in range(0, size):

                state = matrix[i][j]
                
                if (state == deadly and not (i == 0 and j == 0)):
                    continue

                node = (i, j)
                neighbours = list()

                if i > 0 and matrix[i - 1][j] != deadly :
                    neighbours.append(((i - 1, j), matrix[i - 1][j]))
                
                if i < size - 1  and matrix[i + 1][j] != deadly :
                    neighbours.append(((i + 1, j), matrix[i + 1][j]))
 
                if j > 0 and matrix[i][j - 1] != deadly :
                    neighbours.append(((i, j - 1), matrix[i][j - 1]))

                if j < size - 1 and matrix[i][j + 1] != deadly :
                    neighbours.append(((i, j + 1), matrix[i][j + 1]))

                graph[node] = neighbours

        matrix = None 

        min_path = shortest_path(graph, (0, 0), (size - 1, size - 1))
        min_dist = shortest_distance(graph, (0, 0), (size - 1, size - 1))

        return min_dist
示例#8
0
 def reset(self, pos):
     self.head = block(pos)
     self.body = []
     self.body.append(self.head)
     self.turns = {}
     self.directionX = 0
     self.directionY = 1
     self.human = human()
     self.shortest = shortest_path()
     self.longest = longest_path()
     self.hamilton = hamilton()
示例#9
0
	def getMaxControlDist(self,controller):
		maxDist=0
		sp=shortest_path.shortest_path(self.__switch,self.__edges)
		
		for s in self.__switch:
			dist=sp.shortestPath(s)

			while (dist and dist[dist.smallest()]!=999999999999):
				if dist.smallest() in controller:
					if dist[dist.smallest()]>maxDist:
						maxDist=dist[dist.smallest()]
				dist.pop_smallest()

		return maxDist
示例#10
0
	def __init__(self,ng,ca,d,theta,ctr,mu):
		self.__ng=ng
		self.__switch=self.__ng.getSwitch()
		self.__edge=self.__ng.getGraph()
		self.__controller=ctr
		self.__ca=ca
		self.__d=d
		self.__theta=theta
		self.__sp=shortest_path.shortest_path(self.__switch,self.__edge)
		self.__nf=priority_dict.priority_dict()
		self.__minFreq=dict()
		self.__avgFreq=dict()
		self.__res=dict()
		for k in self.__controller:
			self.__res[k]=mu
		self.__cost=[]
		self.__initialSet=dict()
		self.__ctrCover=dict()
		self.__mu=mu
示例#11
0
	def graphReconstruct(self):
		edge=self.__ng.getGraph()
		edge_new=dict()
		switch=self.__ng.getSwitch()
		sp=shortest_path.shortest_path(switch,edge)
		self.__geoCord=self.__gi.getGeoCord()

		for s in switch:
			dist=sp.shortestPath(s)
			if s not in edge_new:
				edge_new[s]=priority_dict.priority_dict()
			edge_new[s]=dist

		self.__newGraph=edge_new

		for k,v in self.__geoCord.iteritems():
			lat=v[0]
			longi=v[1]
			if v[1]<0:
				longi=180+abs(v[1])
			self.__geoCord[k]=(float(lat),float(longi))
示例#12
0
# This is a short test file, given to you to ensure that our grading scripts can grade your file.
# Please do not modify it.
# You should only submit "graph_adjacency_list.py", "graph_edge_list.py", and "shortest_path.py".

# This tests the simplest case: adding a single edge to the graph and checking the shortest path from one node to the other.

from graph_adjacency_list import Graph as AdjacencyGraph
from graph_edge_list import Graph as EdgeGraph
from shortest_path import shortest_path
import sys

try:
    print("Testing with adjacency list graph...")
    adjacency_graph = AdjacencyGraph()
    adjacency_graph.add_edge('a', 'b', 1)
    if shortest_path(adjacency_graph, 'a', 'b') != (['a', 'b'], 1):
        print(
            "Your code ran, but did NOT output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added."
        )
    else:
        print(
            "Your code ran, and it correctly output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added."
        )
except:
    print(
        "Your code produced this error when adding edge ('a', 'b', 1) to the adjacency list graph or getting the shortest path from 'a' to 'b'."
    )
    print(sys.exc_info()[0])

try:
    print("Testing with edge list graph...")
示例#13
0
# Please do not modify it.
# You should only submit "graph_adjacency_list.py", "graph_edge_list.py", and "shortest_path.py".

# This tests the simplest case: adding a single edge to the graph and checking the shortest path from one node to the other.

from graph_adjacency_list import Graph as AdjacencyGraph
from graph_edge_list import Graph as EdgeGraph
from shortest_path import shortest_path
import sys

try:
    print("Testing with adjacency list graph...")
    adjacency_graph = AdjacencyGraph()
    adjacency_graph.add_edge('a', 'b', 1)

    if shortest_path(adjacency_graph, 'a', 'b') != (['a', 'b'], 1):
        print "Your code ran, but did NOT output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added."
    else:
        print "Your code ran, and it correctly output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added."
except:
    print "Your code produced this error when adding edge ('a', 'b', 1) to the adjacency list graph or getting the shortest path from 'a' to 'b'."
    print sys.exc_info()[0]

try:
    print("Testing with edge list graph...")
    edge_graph = EdgeGraph()
    edge_graph.add_edge('a', 'b', 1)
    edge_graph.add_edge('b', 'c', 2)
    edge_graph.add_edge('c', 'd', 3)
    edge_graph.add_edge('a', 'f', 1)
    edge_graph.add_edge('f', 'd', 1)
示例#14
0
    run_mst( w_ugraph, 1 ) #run kruskal
    print("-------") 
    run_mst( w_ugraph, 0)  #run prim

    print("------------------- running shortest path --------------------- ")
    w_dgraph = weight_direct_graph(len(l))
    set_weight_direct_graph(w_dgraph)
    check_graph_properties(w_dgraph, l)
    
    print("Entire graph")
    for e in w_dgraph.edges():
        print(e)

    print("-------")
    print("Dijkstra")
    sp = shortest_path(w_dgraph,0)

    for v in range(w_dgraph.V()):
        if sp.exist_path(v):
            print("Dist path from 0 to ", v, " is =", sp.get_dist(v))
            print("Path is ")
            for e in sp.get_path(v):
                print(e)

    print("-------")
    print("Bellaman Ford")
    set_negative_weight_direct_graph(w_dgraph)
    check_graph_properties(w_dgraph, l)
    
    print("Entire graph")
    for e in w_dgraph.edges():
示例#15
0
				fo=open(demandPath+".txt","r+")
				for s in switch:
					line=fo.readline()
					d[str(s)]=float(line[:-2])

				fo.close()

				s=ng.getSwitch()
				n_ctr=len(s)

				c=ng.getController()

				mapping=dict()
				ctr=[]

				sp=shortest_path.shortest_path(s,edge)
				node_dist=dict()
				for n in s:
					node_dist[n]=sp.shortestPath(n)

				ctr_cnt=0
				while s:
					node_asg={}
					nodehp=priority_dict.priority_dict()
					for ele in c:
						#print node_dist[ele]
						node_asg[ele]=[]
						neighbour=[]
						cnt=0
						ca=queuing.queuing(mu)
示例#16
0
#   print(shortest_path(adjacency_graph, '1', '7'))
#   if shortest_path(adjacency_graph, 'a', 'b') != (['a','b'], 1):
#     print "Your code ran, but did NOT output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added."
#   else:
#     print "Your code ran, and it correctly output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added."
# except:
#   print "Your code produced this error when adding edge ('a', 'b', 1) to the adjacency list graph or getting the shortest path from 'a' to 'b'."
#   print sys.exc_info()[0]

try:
    print("Testing with edge list graph...")
    edge_graph = EdgeGraph()
    edge_graph.add_edge('s', 'a', 3)
    edge_graph.add_edge('s', 'b', 4)
    edge_graph.add_edge('a', 'c', 2)
    edge_graph.add_edge('a', 'f', 7)
    edge_graph.add_edge('a', 'b', 6)
    edge_graph.add_edge('b', 'f', 5)
    edge_graph.add_edge('c', 'f', 1)
    edge_graph.add_edge('c', 't', 8)
    edge_graph.add_edge('f', 't', 4)
    print(shortest_path(edge_graph, 's', 't'))
    if shortest_path(edge_graph, 's', 't') != (['a', 'b', 'c', 'd'], 11):
        print "Your code ran, but did NOT output the shortest distance from 'a' to 'b' when your edge list graph had the edge ('a', 'b', 1) added."
    else:
        print "Your code ran, and it correctly output the shortest distance from 'a' to 'b' when your edge list graph had the edge ('a', 'b', 1) added."
except AttributeError:
    print "Your code produced this error when adding edge ('a', 'b', 1) to the edge list graph or getting the shortest path from 'a' to 'b'."
    print sys.exc_info()[0]
    traceback.print_exc()
def test_shortest_path(target_node, expected_distance):
    graph = {0: [1, 4], 1: [0, 4, 2, 3], 2: [1, 3], 3: [1, 4, 2], 4: [3, 0, 1]}
    actual = shortest_path(graph, target_node)
    assert actual == expected_distance
示例#18
0
from ast import literal_eval

with open("test.txt", 'r') as testfile:
    L = testfile.readlines()
    num_tests_run = 0

    for l in L:
        (testname, g, s, t, expected_output) = l.strip().split(";")
        num_tests_run += 1

        # Parse the graph
        edge_graph = EdgeGraph()
        edge_graph.graph = literal_eval(g)

        # testcase = (g,s,t)
        test_result = str(shortest_path(edge_graph, s, t))

        if test_result == expected_output:
            # print("Passed test with name %s" % testname)
            print(test_result)
            continue

        elif test_result != expected_output:
            print("Failed test with name %s" % testname)
            print(test_result)
            print(expected_output)
            break

print("Correctly ran %d tests" % num_tests_run)
示例#19
0
	def greedySelection(self,mu,theta,d_dict):
		s=list(self.__switch)
		c=list(self.__switch)

		switch=self.__ng.getSwitch()
		edge=self.__ng.getGraph()
		
		sp=shortest_path.shortest_path(switch,edge)
		node_dist=dict()
		for n in s:
			node_dist[n]=sp.shortestPath(n)

		ctr_cnt=0
		ctr=[]

		ns=dict()
		while s:
			node_asg={}
			nodehp=priority_dict.priority_dict()
			for ele in c:
				node_asg[ele]=[]
				neighbour=[]
				cnt=0
				ca=queuing.queuing(mu)

				for n,dist in node_dist[ele].iteritems():
					if n in s:
						if n!=ele:
							d=d_dict[n]
							t=2*dist/300000000+ca.queuingTime(n,ele,d)
							
							if t<=theta:
								ca.updateAssignment(n,ele,d)
								neighbour.append(n)
								cnt=cnt+1
							
				nodehp[ele]=cnt
				node_asg[ele]=neighbour

			largest=""
			c_node=""

			while nodehp:
				c_node=nodehp.smallest()
				nodehp.pop_smallest()

			ctr.append(c_node)
			ns[c_node]=node_asg[c_node]


			ctr_cnt=ctr_cnt+1
			s.remove(c_node)
			c.remove(c_node)

			for node in node_asg[c_node]:
				if node in s:
					s.remove(node)
				if node in c:
					c.remove(node)

		#print ns
		#print ctr
		for k,v in ns.iteritems():
			ns[k].append(k)
		self.__ns=ns
		return ctr_cnt
#   else:
#     break
#   if shortest_path(adjacency_graph, 's', 't') != (test_function[0], test_function[3]):
#     print("pass adjacency_graph")
#   else:
#     break

####################### TEST 0

try:
    adjacency_graph = AdjacencyGraph()
    adjacency_graph.add_edge('s', 'a', 4)
    adjacency_graph.add_edge('a', 't', 3)
    adjacency_graph.add_edge('s', 'b', 5)
    adjacency_graph.add_edge('b', 't', 5)
    if shortest_path(adjacency_graph, 's', 't') != (['s', 'a', 't'], 7):
        print("ERROR: TEST 0A, WRONG DISTANCE")
    else:
        print("pass test 0A")
except:
    print("ERROR: TEST 0A, ADDING EDGE")
    print(sys.exc_info()[0])

try:
    edge_graph = EdgeGraph()
    edge_graph.add_edge('s', 'a', 4)
    edge_graph.add_edge('a', 't', 3)
    if shortest_path(edge_graph, 's', 't') != (['s', 'a', 't'], 7):
        print("ERROR: TEST 0B, WRONG DISTANCE")
    else:
        print("pass test 0B")
示例#21
0
文件: PTAS.py 项目: mengqwang2/SDN
	def run(self):
		print "Running PTAS"
		epsilon=0.1
		beta=0.3
		d=self.__d
		light_speed=3*math.pow(10,8)
		u=30000
		mu=30000

		numCluster=self.__numController

		controllers=self.__km.initialCluster(numCluster/2)
		maxControlDist=self.__ng.getMaxControlDist(controllers)
		theta=maxControlDist*2/light_speed+5/1000
		self.__B=theta

		controllers=self.__km.initialCluster(numCluster)
		self.__controllers=controllers
		print controllers

		edge=self.__ng.getGraph()
		switch=self.__ng.getSwitch()

		ds=self.__ds

		adj={}

		for s1 in switch:
			adj[s1]={}
			for s2 in self.__controllers:
				adj[s1][s2]=0

		d_node={}

		count=0
		for node in adj:
			d_node[str(node)]=0
			count=count+1

		x=math.pow(1+count*epsilon,(1-epsilon)/epsilon)
		x=1/x
		y=math.pow((1-epsilon)/(count*(count-1)),1/epsilon)

		gamma=x*y

		curCost=float(0)

		bv1=0

		while (curCost<theta*len(switch)):
			
			print "Current budget is: {}".format(theta*len(switch))
			
			u_edge={}
			phi={}
			flow={}
			cost={}
			path={}

			ca=queuing.queuing(mu)

			for node,edge in adj.iteritems():
				if node not in u_edge:
					u_edge[str(node)]={}
				if node not in flow:
					flow[str(node)]={}
				if node not in phi:
					phi[str(node)]={}
				for k,v in edge.iteritems():
					if k not in u_edge:
						u_edge[str(k)]={}
					if k not in flow:
						flow[str(k)]={}
					if k not in phi:
						phi[str(k)]={}

					if node!=k:
						phi[str(node)][str(k)]=gamma/self.__B
						u_edge[str(node)][str(k)]=3*d[str(node)]
						flow[str(node)][str(k)]=0

					phi[str(k)][str(k)]=gamma/self.__B
					u_edge[str(k)][str(k)]=u
					flow[str(k)][str(k)]=0
				cost[node]=0

			mg=MCFGraph.MCFGraph(adj,u_edge,phi,flow,cost)
			mg.graphUpdate(gamma,ca,ds,d)
			adj_mcf=mg.getGraph()

			sp=shortest_path.shortest_path(switch,adj_mcf)
			
			node_dist=priority_dict.priority_dict()

			for c in controllers:
				d_node[str(c)]=d_node[str(c)]+beta*d[str(c)]
				mg.updateFlow(str(c),str(c),d_node[str(c)])
				path[c]=str(c)
				dist=0
				ca.updateAssignment(c,str(c),d_node)
				t=ca.queuingTime(str(c))
				rtt=t
				cur_demand=d_node[str(c)]
				mg.updateCost(c,rtt)
				mg.relaxation(epsilon,self.__B,cur_demand,c,str(c),ca,ds)
				adj_mcf=mg.getGraph()
				sp=shortest_path.shortest_path(switch,adj_mcf)

			totalDemand=0
			for s in switch:
				if s not in controllers:
					if bv1==0:
						d_node[str(s)]=d[str(s)]
						totalDemand=totalDemand+d_node[str(s)]
						cur_demand=d_node[str(s)]
						u_edge=mg.getCapacity()
						flow=mg.getFlow()

						node_dist[s]=sp.shortestPath(s)

						c_found=node_dist[s].smallest()

						
						while (flow[str(c_found)][str(c_found)]+cur_demand>u_edge[str(c_found)][str(c_found)]):
							node_dist[s].pop_smallest()
							if len(node_dist[s])>0:
								if node_dist[s].smallest() in self.__controllers:
									c_found=node_dist[s].smallest()
							else:
								bv1=1
								break

						if bv1==0:
							c_found=node_dist[s].smallest()

							mg.updateFlow(str(s),str(c_found),cur_demand)

							path[s]=str(c_found)

							dist=ds[s][str(c_found)]

							ca.updateAssignment(s,str(c_found),d_node)

							t=ca.queuingTime(str(c_found))

							rtt=dist*2/light_speed+t

							mg.updateCost(s,rtt)

							mg.relaxation(epsilon,self.__B,cur_demand,s,str(c_found),ca,ds)

							adj_mcf=mg.getGraph()

							sp=shortest_path.shortest_path(switch,adj_mcf)
						
			totalCost=mg.calculateCost()
			curCost=float(totalCost)
			print "Total demand is {}.".format(totalDemand)
			print "Cost is {}, K is {}.".format(curCost,len(controllers))
			
			self.__path=path
			self.__cost=curCost

			if bv1==0:
				numCluster=numCluster-1
			else:
				numCluster=numCluster+1
				bv1=0

			controllers=self.__km.initialCluster(numCluster)
			self.__controllers=controllers

			adj={}

			for s1 in switch:
				adj[s1]={}
				for s2 in self.__controllers:
					adj[s1][s2]=0

			print controllers

			print "Iteration ends."
示例#22
0
def path_to_descendant(x,y):
	inverse = invert_options_func.invert_options_func(y,lambda x: x.those_can_be_within())
	result = shortest_path.shortest_path(x,y,inverse)
	return result
示例#23
0
def main():
    # Create ROS node
    rospy.init_node('marker_test', anonymous=False)

    # Publish markers to 'marker_test' topic
    pub_node = rospy.Publisher('visualization_marker_array', MarkerArray, queue_size=10)

    # Initialize MarkerArray
    marker_arr = MarkerArray()
    marker_cnt = 0

    # Marker for growing obstacles
    # marker1 = initialize_marker('red')

    from grow_obstacles import grow_obstacles
    obstacles, _ = grow_obstacles()
    for obstacle in obstacles:
        # Create a new marker for each obstacle
        marker = initialize_marker(marker_cnt, 'strip', 'red')
	marker_cnt += 1
        points = []
        for point in obstacle:
            pt = Point(point[0] * .01, point[1] * .01, 0)
	    # print(pt)
            points.append(pt)
	points.append(points[0]) # to make lines connect
	marker.points = points
        marker_arr.markers.append(marker)

    # Marker for visibility graph
    from gene_vgraph import gene_vgraph
    edges, _ = gene_vgraph(obstacles_file, goal_file)
    # Create a new marker for edges
    marker = initialize_marker(marker_cnt, 'list', 'blue', alpha=.3)
    marker_cnt += 1
    points = []
    for edge in edges:
        pt1 = Point(edge[0][0] * .01, edge[0][1] * .01, 0)
        pt2 = Point(edge[1][0] * .01, edge[1][1] * .01, 0)
        points.append(pt1)
        points.append(pt2)
    marker.points = points
    marker_arr.markers.append(marker)

    # Marker for shortest path
    from shortest_path import shortest_path
    path, _ = shortest_path(obstacles_file, goal_file)
    # Create a new marker for shortest path
    marker = initialize_marker(marker_cnt, 'strip', 'green')
    marker_cnt += 1
    points = []
    for point in path:
        pt = Point(point[0] * .01, point[1] * .01, 0)
        points.append(pt)
    marker.points = points
    marker_arr.markers.append(marker)

    # Create points
    # points = []
    # pt1 = Point(1, 1, 1)
    # pt2 = Point(2, 2, 2)
    # points.append(pt1)
    # points.append(pt2)

    # marker.points = points

    # marker_arr.markers.append(marker)

    # Draw markers
    while not rospy.is_shutdown():
        pub_node.publish(marker_arr)
        rospy.Rate(30).sleep()
示例#24
0
from graph_adjacency_list import Graph as AdjacencyGraph
from graph_edge_list import Graph as EdgeGraph
from shortest_path import shortest_path
import sys

try:
    print("Testing with adjacency list graph...")
    adjacency_graph = AdjacencyGraph()
    adjacency_graph.add_edge('a', 'b', 1)
    adjacency_graph.add_edge('a', 'c', 2)
    adjacency_graph.add_edge('b', 'd', 3)
    adjacency_graph.add_edge('c', 'e', 5)
    adjacency_graph.add_edge('d', 'e', 2)
    adjacency_graph.add_edge('d', 'f', 4)
    adjacency_graph.add_edge('e', 'f', 1)
    if shortest_path(adjacency_graph, 'a', 'f') != (['a', 'b', 'd', 'e', 'f'
                                                     ], 7):
        print(
            "Your code ran, but did NOT output the shortest distance from 'a' to 'f' when your adjacency list graph had the edge ('e', 'f', 1) added."
        )
    else:
        print(
            "Your code ran, and it correctly output the shortest distance from 'a' to 'f' when your adjacency list graph had the edge ('e', 'f', 1) added."
        )
except:
    print(
        "Your code produced this error when adding edge ('a', 'b', 1) to the adjacency list graph or getting the shortest path from 'a' to 'b'."
    )
    print(sys.exc_info()[0])

try:
示例#25
0
文件: PTAS_2.py 项目: mengqwang2/SDN
	def run(self):
		epsilon=0.1
		beta=0.3
		alpha=self.__alpha
		d={}
		light_speed=3*math.pow(10,5)
		u=30000
		
		d_lower=1500
		d_upper=3000
		mu=30000

		self.__gi.graphParser()
		edge=self.__gi.getGraph()
		switch=self.__gi.getSwitch()
		controller=self.__gi.getController()
		ds=self.__ds

		adj={}

		for s1 in switch:
			adj[s1]={}
			d[s1]=0
			for s2 in switch:
				if s2!=s1:
					adj[s1][s2]=0

		#print adj

		d_node={}
		r_node={}

		count=0
		for node in adj:
			d_node[node]=0
			r_node[node]=0
			count=count+1

		x=math.pow(1+count*epsilon,(1-epsilon)/epsilon)
		x=1/x
		y=math.pow((1-epsilon)/(count*(count-1)),1/epsilon)

		gamma=x*y

		totalCost=4

		for s in switch:
			d[s]=d_lower+random.random()*(d_upper-d_lower)

		path={}
		
		while (totalCost<self.__B):
			print "Current cost is: {}".format(totalCost)

			u_edge={}
			phi={}
			flow={}
			cost={}

			ca=queuing.queuing(d,mu)

			for node in d_node:
				d_node[node]=d_node[node]+beta*d[node]

			for node,edge in adj.iteritems():
				if node not in u_edge:
					u_edge[node]={}
				if node not in flow:
					flow[node]={}
				for k,v in edge.iteritems():
					if k not in u_edge:
						u_edge[k]={}
					if k not in flow:
						flow[k]={}
					phi[k]=gamma/self.__B
					u_edge[node][k]=d_node[node]
					u_edge[k][k]=u
					flow[node][k]=0
					flow[k][k]=0
					cost[k]=0

			mg=MCFGraph.MCFGraph(adj,u_edge,phi,flow,cost)
			mg.graphUpdate(gamma)
			adj_mcf=mg.getGraph()
			path={}

			
			sp=shortest_path.shortest_path(switch,adj_mcf)
			#print adj_mcf
			
			  
			node_dist=priority_dict.priority_dict()

			for s in switch:
				print len(switch), totalCost
				cur_demand=d_node[s]
				u_edge=mg.getCapacity()
				flow=mg.getFlow()

				node_dist[s]=sp.shortestPath(s)
				#print node_dist[s]
				
				c_found=node_dist[s].smallest()

				while (flow[c_found][c_found]+cur_demand>u_edge[c_found][c_found]):
					node_dist[s].pop_smallest()

				c_found=node_dist[s].smallest()

				mg.updateFlow(s,c_found,cur_demand)
				mg.updateCost(c_found)

				path[s]=c_found

				
				dist=ds[s][c_found]

				#print s, c_found, node_dist[s][c_found]

				ca.updateAssignment(s,c_found)
				t=ca.queuingTime(s,c_found)
				
				rtt=dist/light_speed*2+t   
				r_node[s]=cur_demand/d[s]+alpha*(self.__theta-rtt)
				print rtt, self.__theta
				self.__sub.append(self.__theta-rtt)

				mg.relaxation(epsilon,self.__B,cur_demand,s,c_found)
				adj_mcf=mg.getGraph()
				sp=shortest_path.shortest_path(switch,adj_mcf)
				totalCost=mg.calculateCost()

			
			print len(switch), totalCost
			#print "Current path is: {}".format(path)

		i=0
		min_obj=0
		x=math.log((1+epsilon)/gamma,1+epsilon)
		for node in r_node:
			if (i==0):
				r_node[node]=r_node[node]/x
				min_obj=r_node[node]
			else:
				r_node[node]=r_node[node]/x
				if (r_node[node]<min_obj):
					min_obj=r_node[node]
			i=i+1

		self.__path=path
		return min_obj
示例#26
0
# This is a short test file, given to you to ensure that our grading scripts can grade your file.
# Please do not modify it.
# You should only submit "graph_adjacency_list.py", "graph_edge_list.py", and "shortest_path.py".

# This tests the simplest case: adding a single edge to the graph and checking the shortest path from one node to the other.

from graph_adjacency_list import Graph as AdjacencyGraph
from graph_edge_list import Graph as EdgeGraph
from shortest_path import shortest_path
import sys

try:
    print("Testing with adjacency list graph...")
    adjacency_graph = AdjacencyGraph()
    adjacency_graph.add_edge('a', 'b', 1)
    if shortest_path(adjacency_graph, 'a', 'b') != (['a', 'b'], 1):
        print(
            "Your code ran, but did NOT output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added."
        )
    else:
        print(
            "Your code ran, and it correctly output the shortest distance from 'a' to 'b' when your adjacency list graph had the edge ('a', 'b', 1) added."
        )
except:
    print(
        "Your code produced this error when adding edge ('a', 'b', 1) to the adjacency list graph or getting the shortest path from 'a' to 'b'."
    )
    print(sys.exc_info()[0])

try:
    print("Testing with edge list graph...")