예제 #1
0
	def shortestPath(self,n):

		wl=priority_dict.priority_dict()

		found=priority_dict.priority_dict()

		for ele in self.__node:
			if ele!=n:
				wl[ele]=999999999999

		found[n]=0

		#initialize: relaxation
		for ele in found:
			if ele in self.__edge:
				for key,value in self.__edge[ele].iteritems():
					wl[key]=value


		while wl:
			# dequeue the cloest node
			found[wl.smallest()]=wl[wl.smallest()]
			#print wl.smallest(), wl[wl.smallest()]
			wl.pop_smallest()

			# relaxation
			for k1,v1 in wl.iteritems():
				for k2,v2 in found.iteritems():
					if k2 in self.__edge:
						if k1 in self.__edge[k2]:
							if found[k2]+self.__edge[k2][k1]<wl[k1]:
								wl[k1]=found[k2]+self.__edge[k2][k1]

		return found
def dijkstras_search(origin_key, goal_key, graph):
    open_queue = priority_dict.priority_dict({})
    open_queue[origin_key] = 0.0
    closed_dict = {}
    predecessors = {}
    goal_found = False

    while (open_queue):
        u, u_length = open_queue.pop_smallest()

        if u == goal_key:
            goal_found = True
            break
        for edge_dict in graph.out_edges([u], data=True):
            v = edge_dict[1]
            if v in closed_dict:
                continue
            uv_length = edge_dict[2]['length']

            if v not in open_queue:
                open_queue[v] = u_length + uv_length
                predecessors[v] = u
            else:
                v_length = open_queue[v]
                if u_length + uv_length < v_length:
                    open_queue[v] = u_length + uv_length
                    predecessors[v] = u

        closed_dict[u] = 1

    if not goal_found:
        raise ValueError("Goal not found in search.")

    return get_path(origin_key, goal_key, predecessors)
예제 #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 set_priority_queue(
     V
 ):  # retourne un dictionnaire de priorité dont les clés sont les éléménts de la liste V
     F = priority_dict()
     for v in V:
         F[v] = float('inf')
     return F
예제 #5
0
def spanning_tree(graph, source):
    distance_table = {}
    for i in range(graph.numVertices):
        distance_table[i] = (None, None)
    distance_table[source] = (0, source)

    priority_queue = priority_dict.priority_dict()
    priority_queue[source] = 0

    visited_vertices = set()
    spanning_tree = set()

    while len(priority_queue.keys()) > 0:
        current_vertex = priority_queue.pop_smallest()
        if current_vertex in visited_vertices:
            continue

        visited_vertices.add(current_vertex)

        if current_vertex != source:
            last_vertex = distance_table[current_vertex][1]
            edge = str(last_vertex) + "--->" + str(current_vertex)
            if edge not in spanning_tree:
                spanning_tree.add(edge)

        for neighbour in graph.get_adjacent_vertices(current_vertex):
            distance = graph.get_edge_weight(current_vertex, neighbour)
            neighbour_distance = distance_table[neighbour][0]

            if neighbour_distance is None or neighbour_distance > distance:
                distance_table[neighbour] = (distance, current_vertex)
                priority_queue[neighbour] = distance

    for edge in spanning_tree:
        print(edge)
예제 #6
0
파일: verk3.py 프로젝트: gudmundurmar/SKSKG
def MSTPRIM(G,w,r):
    r[0] = 0
    
    Q =  priority_dict(G);
    while Q:
        Q._rebuild_heap()
        #print Q
        
        u = Q.smallest()
        #print u
        global b
        if not b:
            if not u[0]==None:
                if int(u[0])<int(u[1]):
                    listi.append(u)
                else:
                    v = [u[1],u[0]]
                    listi.append(v)
        w += int(Q[u[1]][0])
        u = Q.pop_smallest()

        #print u

        for v in G[u]:
            if isinstance(v, list):
                stri = str(v[0])
                if v[0] in Q:
                    if float(v[1]) < float(Q[v[0]][0]):
                        Q[v[0]][1] = u
                        Q[v[0]][0] = float(v[1])
                        
    b = True               
    return w    
예제 #7
0
파일: spanning.py 프로젝트: Ceasar/gadgets
def prim(graph):
    '''
    >>> graph = {'a': {'b': 7, 'd': 5},
            'b': {'a': 7, 'c': 8, 'd': 9, 'e': 7},
            'c': {'b': 8, 'e': 5},
            'd': {'a': 5, 'e': 15, 'f': 6},
            'e': {'b': 7, 'c': 5, 'd': 15, 'f': 8, 'g': 9},
            'f': {'d': 6, 'e': 8, 'g': 11},
            'g': {'e': 9, 'f': 11}}
    >>> prim(graph)
    {'d': {'a': 5, 'f': 6},
    'a': {'b': 7},
    'b': {'e': 7},
    'e': {'c': 5, 'g': 9}}
    '''
    if not connected(graph): raise NotConnectedError('graph is not connected')

    predecessor = {}
    frontier = priority_dict({iter(graph).next(): 0})
    explored = set()

    for nearest in frontier.sorted_iter():
        for neighbor in graph[nearest]:
            if neighbor in explored: continue
            displacement = graph[nearest][neighbor]
            if neighbor in frontier and displacement > frontier[neighbor]:
                continue
            else:
                frontier[neighbor] = displacement
                predecessor[neighbor] = nearest
        explored.add(nearest)
    return reconstruct_tree(graph, predecessor)
예제 #8
0
def ACM_Prim():
    """ calcule un ACM du graphe stocké sur le serveur en utilisant l'algorithme de Prim """
    F = priority_dict()
    r = getAVertex()
    sommets = set()
    sommets.add(r)
    F[r] = 0
    pere = dict()
    pere[r] = None
    while F:
        u = F.pop_smallest()
        for v in getNeighbors(u):
            if v not in sommets:
                sommets.add(v)
                F[v] = float('+infinity')
            if v in F and getWeight(u, v) < F[v]:
                pere[v] = u
                F[v] = getWeight(u, v)

    #Calcul du poids w de l'arbre couvrant
    w = 0
    for v in sommets:
        if v != r:
            w += getWeight(pere[v], v)
    SpanningTreeWeight(w)
def build_distance_table(graph, source):
    distance_table = {}

    for i in range(graph.numVertices):
        distance_table[i] = (None, None)

    distance_table[source] = (0, source)

    priority_queue = priority_dict.priority_dict()

    priority_queue[source] = 0

    while len(priority_queue.keys()) > 0:
        current_vertex = priority_queue.pop_smallest()

        current_distance = distance_table[current_vertex][0]

        for neighbor in graph.get_adjacent_vertices(current_vertex):
            distance = current_distance + g.get_edge_weight(current_vertex, neighbor)

            neighbor_distance = distance_table[neighbor][0]

            if neighbor_distance is None or neighbor_distance > distance:
                distance_table[neighbor] = (distance, current_vertex)
                priority_queue[neighbor] = distance

    
    return distance_table
예제 #10
0
def dijkstras_search(origin_key, goal_key, graph):
    open_queue = priority_dict.priority_dict({})
    closed_dict = {}
    predecessors = {}
    open_queue[origin_key] = 0.0
    goal_found = False
    while (open_queue):
        u, ucost = open_queue.pop_smallest()
        if u == goal_key:
            goal_found = True
            break
        for edge in graph.out_edges([u], data=True):
            v = edge[1]
            if v in closed_dict:
                continue
            uvcost = edge[2]['length']
            if v in open_queue.keys():
                if ucost + uvcost < open_queue[v]:
                    open_queue[v] = ucost + uvcost
                    predecessors[v] = u
            else:
                open_queue[v] = ucost + uvcost
                predecessors[v] = u
        closed_dict[u] = 1

    if not goal_found:
        raise ValueError("Goal not found in search.")

    return get_path(origin_key, goal_key, predecessors)
예제 #11
0
def build_distance_table(graph, source):
    distance_table = {}

    for i in range(graph.numVertices):
        distance_table[i] = (None, None)

    distance_table[source] = (0, source)
    # Holding mapping of vertex id to distance from source
    # Access the highest priority (lowest distance) item
    # first
    priority_queue = priority_dict()
    priority_queue[source] = 0
    while len(priority_queue.keys()) > 0:
        current_vertex = priority_queue.pop_smallest(
        )  # vertex with smallest distance value
        # the distance of current node
        current_distance = distance_table[current_vertex][0]
        for neighbor in graph.get_adjacent_vertices(current_vertex):
            distance = current_distance + graph.get_edge_weight(
                current_vertex, neighbor)
            neighbor_distance = distance_table[neighbor][0]
            if neighbor_distance is None or neighbor_distance > distance:
                distance_table[neighbor] = (distance, current_vertex)
                priority_queue[neighbor] = distance

    return distance_table
예제 #12
0
def build_distance_table(graph, source):

    distance_table = {}  # vertex and tuple (distance and last preceding node)

    for i in range(graph.numVertices):
        distance_table[i] = (None, None)
    distance_table[source] = (0, source)

    priority_queue = priority_dict.priority_dict()
    priority_queue[source] = 0

    while len(priority_queue.keys()) > 0:
        current_vertex = priority_queue.pop_smallest()
        current_distance = distance_table[current_vertex][0]

        for neighbour in graph.get_adjacent_vertices(current_vertex):
            if distance_table[neighbour][0] is None:
                distance = (g.get_edge_weight(current_vertex, neighbour) +
                            current_distance)

                neighbour_distance = distance_table[neighbour][0]

                if neighbour_distance is None or neighbour_distance > distance > 0:
                    distance_table[neighbour] = (distance, current_vertex)
                    priority_queue[neighbour] = distance

    return distance_table
예제 #13
0
파일: dijkstra.py 프로젝트: qqrs/mta-routes
def dijkstra(graph, start, end=None):
    """ Dijkstra's algorithm for finding shortest paths.

    Finds shortest paths from a start node in a graph of Node objects with
    graph edges represented as an adjacency list in Node.neighbors. If end is
    not None, the algorithm stops when a path to the end node is found.
    Otherwise, it continues until a path to all nodes is found.

    graph: dict of dicts -- graph[v][k] is weight of edge from nodes v to k
    start: start node
    end: end node -- if None, paths will be calculated to all reachable nodes
    """
    predecessors = {}
    distances = {}

    queue = priority_dict()
    queue[start] = 0

    for (dist, node) in queue.sorted_iter():
        distances[node] = dist
        if node == end:
            break
        for neigh in graph[node]:
            new_dist = dist + graph[node][neigh]
            if (neigh not in distances
               and (neigh not in queue or new_dist < queue[neigh])):
                queue[neigh] = new_dist
                predecessors[neigh] = node

    return (distances, predecessors)
예제 #14
0
파일: PathFinder.py 프로젝트: rytai/ReStart
    def find_path_between_points(self, start_tile, end_tile, pathfinder_screen_s):
        """


        :param point_a: Tuple(int, int)
        :param point_b: Tuple(int, int)
        :rtype : List(Tuple)
        :rtype time_module: pygame.time
        """

        assert isinstance(start_tile, tuple)
        assert isinstance(end_tile, tuple)

        method_init_time = time.get_ticks()
        counter = 0

        # Create start and end nodes.
        start_node = self.grid.nodes[start_tile]
        target_node = self.grid.nodes[end_tile]

        # Keep track of the open and closed nodes.
        # Add the start node as the first node to start the flood from.
        open_nodes = priority_dict()
        open_nodes[start_node] = 0
        closed_nodes = set()

        # start looping
        while open_nodes.__len__() > 0:

            current_node = open_nodes.pop_smallest()


            # Remove the current node from open set and add it to closed set.
            #open_nodes.remove(current_node)
            closed_nodes.add(current_node)
            # Found the end tile.
            if current_node == target_node:
                complete_path = self.retrace_path(start_node, target_node)

                method_run_time = time.get_ticks() - method_init_time
                print 'Pathfinding completed in {}ms'.format(method_run_time)
                return complete_path

            for neighbour_node in self.get_neighbours(current_node):
                if neighbour_node in closed_nodes:
                    continue

                assert isinstance(current_node, PathFinder.Node)
                assert isinstance(neighbour_node, PathFinder.Node)
                new_movement_cost_to_neighbor = current_node.g_cost + 10
                # Try to find a lower cost for neighbor, or calculate if it doesn't have one.
                if new_movement_cost_to_neighbor < neighbour_node.g_cost or neighbour_node not in open_nodes.keys():

                    # Calculate the costs for the neighbor
                    neighbour_node.g_cost = new_movement_cost_to_neighbor
                    neighbour_node.h_cost = self.get_distance(neighbour_node, target_node)
                    neighbour_node.parent = current_node

                    open_nodes[neighbour_node] = neighbour_node.f_cost
예제 #15
0
def prim(G):
    """ calcule un ACM du graphe stocké sur le serveur en utilisant l'algorithme de Prim """

    F = priority_dict()  # init file priorite

    # sommet racine choisit arbitrairement
    r = next(iter(G))  # recupere le premier sommet dans le graphe G

    F[r] = 0

    sommet_atteint = set()  # init sommets decouvert
    sommet_atteint.add(r)  # ajout de r a l ensemble des sommets atteint

    pere = dict()  # init pere
    pere[r] = None  # pere du premier = rien

    weight = dict(
    )  # init pour stocker le poids entre 2 sommets, cela evite de le redemander au serveur a la fin pour calculer le poids w de l arbre couvrant

    list_sommet_extrait = []  # init liste des sommets extrait

    while F:
        u = F.pop_smallest()
        list_sommet_extrait.append(
            u)  # ajout de u a la fin de la liste des sommets extrait

        for v in getNeighbors(G, u):
            if v not in sommet_atteint:
                sommet_atteint.add(
                    v)  # si pas atteint alors on l ajoute a l essemble atteint
                F[v] = float(
                    '+infinity'
                )  # on l ajoute dans la file de prioriter avec comme valeur : +oo

            weight_u_v = getWeight(
                G, u, v)  # stocke dans une var le poids entre u et v
            if v in F and weight_u_v < F[v]:
                pere[
                    v] = u  # ajoute(ou modifie si deja existant) au dictionaire pere, le pere du sommet v
                F[v] = weight_u_v  # modifie le poids de v
                weight[(u, v)] = weight_u_v  # stocker le poids entre u et v

    list_pere_sommet = list()  # init liste pere sommet
    for sommet in list_sommet_extrait:
        list_pere_sommet.append(
            [pere[sommet], sommet]
        )  # on ajoute a la fin de la lite une liste tel que : le premier element est le pere et le second est le sommet


#test
#print("algo prim = ", list_sommet_extrait)
#print("\nlist pere sommet = ", list_pere_sommet)

    return [
        list_sommet_extrait, list_pere_sommet
    ]  # return liste chronologique des sommets atteint, la liste des [pere[sommet], sommet]
 def __init__(self, k, t, b):
     self.A = priority_dict()  # heap of top k elemenets so far
     self.k = k
     self.t = t
     self.b = b
     # h_hashes is a family of t hashes from an item to {1,...,b}
     self.h_hashes = HashFamily(self.t, self.b)
     # s_hashes is a family of t hashes from an item to {+1,-1}
     self.s_hashes = HashFamily(self.t, 2)
     self.count_sketch = [[0 for i in range(self.b)] for j in range(self.t)]
예제 #17
0
 def find_port(self, router_src, router_dest):
     ports = priority_dict()
     print "FIND PORT:",router_src.dpid, router_dest.dpid
     for edge in self.edges:
         print "EDGE: ",edge[0].router.dpid, edge[1].router.dpid
         if router_src == edge[0].router and router_dest == edge[1].router:
             ports[edge[0]] = self.edges[edge]
         if router_src == edge[1].router and router_dest == edge[0].router:
             ports[edge[1]] = self.edges[edge]
     print ports
     return ports.pop_smallest()
    def find_port(self, router_src, router_dest):
        ports = priority_dict()

        for edge in self.edges:

            if router_src == edge[0].router and router_dest == edge[1].router:
                ports[edge[0]] = self.edges[edge]
            if router_src == edge[1].router and router_dest == edge[0].router:
                ports[edge[1]] = self.edges[edge]

        return ports.pop_smallest()
예제 #19
0
파일: host.py 프로젝트: eaas-framework/wire
 def __init__(self, information, seq, expSeq):
     super(TCPHost, self).__init__(information)
     self.seq = seq
     self.ack = seq
     self.expectACK = seq
     self.expectSEQ = expSeq
     self.retransqueue = priority_dict.priority_dict()
     self.winsize = 0
     self.status = 1
     # This is the default value if there is no specific MSS given.
     self.mss = 512
예제 #20
0
def spanning_tree(graph):

	# Holds a mapping from a pair of edges to the edge weight
	# The edge weight is the priority of the edge	
	priority_queue = priority_dict.priority_dict()

	for v in range(graph.numVertices):
		for neighbor in graph.get_adjacent_vertices(v):
			priority_queue[(v, neighbor)] = graph.get_edge_weight(v, neighbor)

	visited_vertices = set()

	# Maps a node to all its adjacent nodes which are in the
	# minimum spanning tree
	spanning_tree = {}
	for v in range(graph.numVertices):
		spanning_tree[v] = set()	

	# Number of edges we have got so far	
	num_edges = 0

	while len(priority_queue.keys()) > 0 and num_edges < graph.numVertices - 1:
		v1, v2 = priority_queue.pop_smallest()

		if v1 in spanning_tree[v2]:
			continue


		# Arrange the spanning tree so the node with the smaller
		# vertex id is always first. This greatly simplifies the
		# code to find cycles in this tree
		vertex_pair = sorted([v1, v2])
		spanning_tree[vertex_pair[0]].add(vertex_pair[1])

		# Check if adding the current edge causes a cycle
		if has_cycle(spanning_tree):
			spanning_tree[vertex_pair[0]].remove(vertex_pair[1])
			continue

		num_edges = num_edges + 1

		visited_vertices.add(v1)
		visited_vertices.add(v2)

	print("Visited vertices: ", visited_vertices)

	if len(visited_vertices) != graph.numVertices:
		print("Minimum spanning tree not found")
	else:
		print("Minimum spanning tree:")
		for key in spanning_tree:
			for value in spanning_tree[key]:
				print(key, "-->", value)		
def a_star_search(origin_key, goal_key, graph):
    node_data = graph.nodes(True)

    open_queue = priority_dict.priority_dict({})
    open_queue[origin_key] = distance_heuristic(origin_key, goal_key,
                                                node_data)

    closed_dict = {}
    predecessors = {}

    costs = {}
    costs[origin_key] = 0.0

    goal_found = False

    while open_queue:
        u, u_heuristic = open_queue.pop_smallest()
        u_length = costs[u]
        if u == goal_key:
            goal_found = True
            break

        for edge_dict in graph.out_edges([u], data=True):
            v = edge_dict[1]

            if v in closed_dict:
                continue

            uv_length = edge_dict[2]['length']

            if v not in open_queue:
                costs[v] = u_length + uv_length
                open_queue[v] = u_length + uv_length + distance_heuristic(
                    v, goal_key, node_data)
                predecessors[v] = u
            else:
                v_length = costs[v]
                if u_length + uv_length < v_length:
                    costs[v] = u_length + uv_length
                    open_queue[v] = u_length + uv_length + distance_heuristic(
                        v, goal_key, node_data)
                    predecessors[v] = u

        closed_dict[u] = 1

    if not goal_found:
        raise ValueError("Goal not found in search.")

    return get_path(origin_key, goal_key, predecessors)
예제 #22
0
파일: NodeCover.py 프로젝트: mengqwang2/SDN
	def calculateNodeFreq(self):
		self.ctrCover()
		nodefreqpair=priority_dict.priority_dict()

		for ele in self.__switch:
			nodefreqpair[ele]=0

		maxFreq=0
		for k,v in self.__ctrCover.iteritems():
			countNode=0
			for ele in self.__switch:
				if ele in v:
					nodefreqpair[ele]=nodefreqpair[ele]+1
		
		self.__nf=nodefreqpair
예제 #23
0
def spanning_tree(graph):

    priority_queue = priority_dict.priority_dict()

    for v in range(graph.numVertices):
        for neighbor in graph.get_adjacent_vertices(v):
            print(neighbor)
            priority_queue[(v, neighbor)] = graph.get_edge_weight(v, neighbor)

    visited_vertices = set()

    spanning_tree = {}

    for v in range(graph.numVertices):
        spanning_tree[v] = set()

    num_edges = 0

    while len(priority_queue.keys()) > 0 and num_edges < graph.numVertices - 1:
        v1, v2 = priority_queue.pop_smallest()
        print(v1, v2)
        if v1 in spanning_tree[v2]:
            continue

        vertex_pair = sorted([v1, v2])

        spanning_tree[vertex_pair[0]].add(vertex_pair[1])

        if has_cycle(spanning_tree):
            spanning_tree[vertex_pair[0]].remove(vertex_pair[1])
            continue
        
        num_edges = num_edges + 1

        visited_vertices.add(v1)
        visited_vertices.add(v2)

    print("Visited vertices: ", visited_vertices)

    if len(visited_vertices) != graph.numVertices:
        print("Minimum spanning tree not found")
    else:
        print("Minimum spanning tree:")
        for key in spanning_tree:
            for value in spanning_tree[key]:
                print(key, "-->", value)
def dijkstras_search(origin_key, goal_key, graph):

    # The priority queue of open vertices we've reached.
    # Keys are the vertex keys, vals are the distances.
    open_queue = priority_dict.priority_dict({})

    # The dictionary of closed vertices we've processed.
    closed_dict = {}

    # The dictionary of predecessors for each vertex.
    predecessors = {}

    # Add the origin to the open queue.
    open_queue[origin_key] = 0.0

    # Iterate through the open queue, until we find the goal.
    # Each time, perform a Dijkstra's update on the queue.
    # TODO(done): Implement the Dijstra update loop.
    goal_found = False
    while (open_queue):
        vtx, dis = open_queue.pop_smallest()
        if (vtx == goal_key):
            goal_found = True
            break
        for edge in graph.out_edges([vtx], data=True):
            next_vtx = edge[1]
            if next_vtx in closed_dict:
                continue
            weight = edge[2]['length']
            if next_vtx in open_queue:
                if dis + weight < open_queue[next_vtx]:
                    open_queue[next_vtx] = dis + weight
                    predecessors[next_vtx] = vtx
            else:
                open_queue.update({next_vtx: dis + weight})
                predecessors.update({next_vtx: vtx})
        closed_dict.update({vtx: dis})

    # If we get through entire priority queue without finding the goal,
    # something is wrong.
    if not goal_found:
        raise ValueError("Goal not found in search.")

    # Construct the path from the predecessors dictionary.
    return get_path(origin_key, goal_key, predecessors)
예제 #25
0
파일: NodeCover.py 프로젝트: mengqwang2/SDN
	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
예제 #26
0
def tsp(
    n, edges
):  # Dijkstra, bit, heap-dict from from https://gist.github.com/matteodellamico/4451520
    import priority_dict

    def solution(nodeset, v):
        if nodeset == 1: return [0]
        u = back[nodeset, v]
        return solution(nodeset - (1 << v), u) + [v % n]

    t0 = time.time()
    edge = defaultdict(lambda: defaultdict(lambda: float('inf')))
    for u, v, w in edges:
        edge[u][v] = min(edge[u][v], w)  # possible duplicate edges
        edge[v][u] = min(edge[v][u], w)  # undirected
    for u in range(1, n):
        edge[u][n] = edge[u][0]  # clone a dummy sink n, which is 0
    d = priority_dict.priority_dict()
    d[1, 0] = (
        0, None
    )  # d[nodeset,last] = (dist,prev), the best dist for 0->nodeset->last is dist, and we have the prev of last
    back = {}
    npop = npush = 0
    fullset, fullsetplus = (1 << n) - 1, (
        1 << n + 1) - 1  # + has high priority than <<
    while d:
        (nodeset, u), (dist, prev) = d.pop_smallest()
        npop += 1
        if (nodeset, u) in back: continue
        back[nodeset, u] = prev
        if nodeset == fullsetplus:
            print('Dijkstra, heapdict, time: {0:.3f}, push: {1}, pop: {2}'.
                  format(time.time() - t0, npush, npop))
            return dist, solution(nodeset, u)

        for v in range(1, n) if nodeset < fullset else [n]:
            if v in edge[u] and not (1 << v & nodeset):
                newset = 1 << v | nodeset
                if (newset, v) in back: continue
                newdis = dist + edge[u][v]
                if (newset, v) in d and newdis >= d[newset, v][0]: continue
                d[newset, v] = newdis, u
                npush += 1
예제 #27
0
def tsp_dijk_bit_pqdict(n, _edges):  # the Dijkstra implementation
    def backtrace(nodeset, j):
        if nodeset == 1:
            return [0]
        last = fixed[nodeset, j]
        return backtrace(nodeset - (1 << j), last) + [j % n]

    start_time = time.time()

    edges = defaultdict(lambda: defaultdict(lambda: float("inf")))
    for (u, v, c) in _edges:
        edges[u][v] = min(edges[u][v], c)  # possible duplicate edges
        edges[v][u] = min(edges[v][u], c)  # undirected
    for u in range(1,
                   n):  # Matthew's suggestion: clone a special sink n from 0
        edges[u][n] = edges[u][0]

    queue = priority_dict()  #heapdict()
    queue[1, 0] = (0, -1)
    fixed = {}

    pushes = pops = 0
    full, fullplus = 2**n - 1, 2**(n + 1) - 1
    while queue:
        (nodeset, last), (value, back) = queue.popitem()
        pops += 1
        fixed[nodeset, last] = back
        if nodeset == fullplus:  # full set + [0]
            print(
                "Dijkstra, bit, pqdict, time: %.2f" %
                (time.time() - start_time), "pushes:", pushes, "pops:", pops)
            return (value, backtrace(nodeset, last))

        for j in range(1, n) if nodeset < full else [n]:
            if j in edges[last] and not (1 << j & nodeset):
                newvalue = value + edges[last][j]
                newset = nodeset | (1 << j)
                if (newset, j) not in fixed and \
                   ((newset, j) not in queue or newvalue < queue[newset, j][0]):
                    #print("push", newvalue, newset, j)
                    queue[newset, j] = (newvalue, last)
                    pushes += 1
def dijkstra(S, A, sdeb):
    edges = set(A.keys())
    distances = {x: float("inf") for x in S}
    distances[sdeb] = 0
    distances = priority_dict(distances)
    final_distance = {}
    predecessors = {x: None for x in S}
    while len(distances) != 0:
        a = distances.smallest()
        min_dist = distances[a]
        distances.pop_smallest()
        final_distance[a] = min_dist
        voisins = [b for b in distances.keys() if (a, b) in edges]
        for b in voisins:
            distance_through_a = final_distance[a] + A[(a, b)]
            if distances[b] > distance_through_a:
                distances[b] = distance_through_a
                predecessors[b] = a

    return final_distance, predecessors
예제 #29
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))
예제 #30
0
def a_star_search(origin_key, goal_key, graph):

    open_queue = priority_dict.priority_dict({})
    closed_dict = {}
    predecessors = {}
    costs = {}
    node_data = graph.nodes(True)
    costs[origin_key] = 0.0
    open_queue[origin_key] = distance_heuristic(origin_key, goal_key,
                                                node_data)
    goal_found = False

    while (open_queue):
        u, u_h = open_queue.pop_smallest()
        ucost = costs[u]
        if u == goal_key:
            goal_found = True
            break
        for edge in graph.out_edges([u], data=True):
            v = edge[1]
            if v in closed_dict:
                continue
            uvcost = edge[2]['length']
            if v in open_queue.keys():
                if ucost + uvcost + distance_heuristic(
                        v, goal_key, node_data) < open_queue[v]:
                    open_queue[v] = ucost + uvcost + distance_heuristic(
                        v, goal_key, node_data)
                    costs[v] = ucost + uvcost
                    predecessors[v] = u
            else:
                open_queue[v] = ucost + uvcost + distance_heuristic(
                    v, goal_key, node_data)
                costs[v] = ucost + uvcost
                predecessors[v] = u
        closed_dict[u] = 1

    if not goal_found:
        raise ValueError("Goal not found in search.")
    return get_path(origin_key, goal_key, predecessors)
    def compute_dijkstra(self, src_router_id):
        src_router = self.get_router_by_id(src_router_id)
        q = priority_dict()
        prev = {}
        for r_id, r in self.routers.iteritems():
            q[r] = float("inf")
        q[src_router] = 0
        while q:
            dist = q[q.smallest()]
            u = q.pop_smallest()

            # v[0] = Router-neighbor, v[1] = cost
            for v in self.get_neighbors(u):
                if v[0] in q:
                    alt = dist + v[1]
                    if alt < q[v[0]]:
                        q[v[0]] = alt
                        prev[v[0]] = u

        next_hop = self.get_next_hop(src_router, prev)

        return next_hop
예제 #32
0
def MSTPRIM(G,w,r):
    r[0] = 0
    Q =  priority_dict(G);
    print Q
    while Q:
        u = Q.smallest()
        if 0 in Q:
            print "yeah"
        w += Q[u][0]
        u = Q.pop_smallest()

        for v in G[u]:
            if isinstance(v, list):
                print "ok"
                stri = str(v[0])
                print ''+stri
                if stri in Q and v[1] < Q[v[0]][0]:
                    print "common"
                    Q[v[0]][1] = u
                    Q[v[0]][0] = v[1]

    return w    
예제 #33
0
def build_distance_table(graph, source):
    # A dictionary mapping from the vertex number to a tuple of
    # (distance from source, last vertex on path from source)
    distance_table = {}

    for i in range(graph.numVertices):
        distance_table[i] = (None, None)

    # The distance to the source from itself is 0
    distance_table[source] = (0, source)

    # Holds mapping of vertex id to distance from source
    # Access the highest priority (lowest distance) item
    # first
    priority_queue = priority_dict.priority_dict()
    priority_queue[source] = 0

    while len(priority_queue.keys()) > 0:
        current_vertex = priority_queue.pop_smallest()

        # The distance of the current node from the source
        current_distance = distance_table[current_vertex][0]

        for neighbor in graph.get_adjacent_vertices(current_vertex):
            distance = current_distance + g.get_edge_weight(
                current_vertex, neighbor)

            # The last recorded distance of this neighbor from the source
            neighbor_distance = distance_table[neighbor][0]

            # If there is a currently recorded distance from the source and this is
            # greater than the distance of the new path found, update the current
            # distance from the source in the distance table
            if neighbor_distance is None or neighbor_distance > distance:
                distance_table[neighbor] = (distance, current_vertex)

                priority_queue[neighbor] = distance

    return distance_table
예제 #34
0
def dijkstra(graph, start, goal, heuristic=lambda x, y: 0):
    '''
    Find the shortest path from start to goal.

    >>> graph = {'a': {'w': 14, 'x': 7, 'y': 9},
            'b': {'w': 9, 'z': 6},
            'w': {'a': 14, 'b': 9, 'y': 2},
            'x': {'a': 7, 'y': 10, 'z': 15},
            'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11},
            'z': {'b': 6, 'x': 15, 'y': 11}}
    >>> dijkstra(graph,'a','b')
    ['a', 'y', 'w', 'b']

    By supplying a heuristic, you can transform the algorithm into the
    a* search algorithm.
    '''
    predecessor = {}
    frontier = priority_dict({start: 0})
    explored = set()
    
    traveled = {start: 0}
    remaining = {start: heuristic(start, goal)} #cached for speed

    for nearest in frontier.sorted_iter():
        if nearest == goal: break
        explored.add(nearest)
        for neighbor in graph[nearest]:
            if neighbor in explored: continue
            displacement = traveled[nearest] + graph[nearest][neighbor]
            if neighbor in frontier and displacement > traveled[neighbor]:
                continue
            traveled[neighbor] = displacement
            if not neighbor in remaining:
                remaining[neighbor] = heuristic(neighbor, goal)
            frontier[neighbor] = displacement + remaining[neighbor]
            predecessor[neighbor] = nearest
        del traveled[nearest]
    return reconstruct_path(predecessor, goal, start)
	def shortestPaths(self, src, it_edges):
		distances = {}
		queue = pd.priority_dict({})
		queue[src.id] = 0
		## priority_dict requires __lt__ operator
		## which is undefined for tlp.node
		ancestors = {src : []}
		stack = []
		nb_paths = tlp.DoubleProperty(self.graph)
		nb_paths.setAllNodeValue(1)
		nb_paths[src] = 1

		while len(queue) > 0:
			v_id = queue.smallest()
			d = queue[v_id]
			v = tlp.node(v_id)
			queue.pop_smallest()
			
			stack.append(v)
			distances[v] = d
			for e in it_edges(v):
				val = 1.
				if self.cost is not None:
					val = self.cost[e]
				w = self.graph.opposite(e, v)
				alt = d + val
				if w in distances:
					if alt < distances[w]:
						self.pluginProgress.setError("Dijkstra: found better path to already-final vertex")
				else:
					if (w.id not in queue) or (alt < queue[w.id]):
						queue[w.id] = alt
						ancestors[w] = [v]
						nb_paths[w] = nb_paths[v]
					elif (alt == queue[w.id]) :
						ancestors[w].append(v)
						nb_paths[w] = nb_paths[w] + nb_paths[v]
		return ancestors, stack, nb_paths
예제 #36
0
def dijkstra(G,posInit):


	attribut=dict()
	for v in G:
		attribut[v]= [ float('+infinity'), None] #[dsitance,pere]
	attribut[posInit][DIST]=0

	F= priority_dict() #cree file prioriter

	# on peuple la file de prioriter avec las sommet et leur distance
	for v in G:
		F[v]=attribut[v][DIST]	

	while F:
		u=F.pop_smallest() #extraire le sommet de plus petit distance
		for v in G[u]:
			#relacher
			if attribut[v][DIST] > (attribut[u][DIST] + G[u][v]) :
				attribut[v][DIST]=attribut[u][DIST] + G[u][v]
				F[v]=attribut[v][DIST]	 # mise a jour des poids dans la file			
				attribut[v][PERE]=u
	return attribut
예제 #37
0
def dijkstra(G, pos_init):
    ''' retourne un dictionaire avec la plus petite distance a partir de la position inital jusqu'a chaque sommet du graphe G '''

    POID = 0  # init constante poid ~ l[0]
    PERE = 1  # init constante pere ~ l[1]

    attribut = dict(
    )  # init du dict attribut pour y stocker le poid et le pere

    for v in G:
        attribut[v] = [
            float('+infinity'), None
        ]  # on fixe pour chaque sommet une POIDante a +oo et un pere a None

    attribut[pos_init][
        POID] = 0  # fixe le premier poid a partir de la position initiale a 0

    F = priority_dict()  # cree file prioriter

    # on peuple la file de prioriter avec les sommets et leurs poid respectifs
    for v in G:
        F[v] = attribut[v][POID]

    while F:

        u = F.pop_smallest()  # extrai le sommet avec le plus petit poid

        for v in G[u]:

            #relacher
            if attribut[v][POID] > (attribut[u][POID] + G[u][v]):
                attribut[v][POID] = attribut[u][POID] + G[u][
                    v]  # on modifie la poid du sommet v car on a trouver une arete qui reduit la poid pour atteindre v depuis u
                F[v] = attribut[v][
                    POID]  # on met a jour les poids dans la file
                attribut[v][PERE] = u  # change le pere de v par u
    return attribut
예제 #38
0
def ACM_Prim():
    """ calcule un ACM du graphe stocké sur le serveur en utilisant l'algorithme de Prim """

    F = priority_dict() #init file priorite
    r = getAVertex() # recupere un somet au hazard
    F[r] = 0 

    sommet_atteint = set() # init sommets decouvert 
    sommet_atteint.add(r) # ajout de r a l ensemble des sommets atteint

    pere = dict() # init pere
    pere[r] = None # pere du premier = rien

    weight = dict() # init pour stocker le poids entre 2 sommets, cela evite de le redemander au serveur a la fin pour calculer le poids w de l arbre couvrant

    while F :
        u = F.pop_smallest()
        for v in getNeighbors(u):
            if v not in sommet_atteint:
                sommet_atteint.add(v) # si pas atteint alors on l ajoute a l essemble atteint
                F[v]=float('+infinity') # on l ajoute dans la file de prioriter avec comme valeur : +oo

            weight_u_v = getWeight(u,v) # stocke dans une var le poids entre u et v
            if v in F and weight_u_v<F[v] :
                pere[v]=u # ajoute(ou modifie si deja existant) au dictionaire pere, le pere du sommet v
                F[v]=weight_u_v # modifie le poids de v 
                weight[(u,v)] = weight_u_v # stocker le poids entre u et v

    # Calcul du poids w de l arbre couvrant
    w=0 # init du poids a 0
    for s in sommet_atteint:
        if s != r:
            w += weight[(pere[s],s)] # somme des poids des arrets 
    
    # test si le poid de l arbre couvrant est bien le min
    SpanningTreeWeight(w) 
예제 #39
0
def spanning_tree(graph, source):
	# A dictionary mapping from the vertex number to a tuple of
	# (distance from source, last vertex on path from source)
	distance_table = {}

	for i in range(graph.numVertices):
		distance_table[i] = (None, None)

	# The distance to the source from itself is 0
	distance_table[source] = (0, source)

	# Holds mapping of vertex id to distance from source
	# Access the highest priority (lowest distance) item
	# first 
	priority_queue = priority_dict.priority_dict()
	priority_queue[source] = 0

	visited_vertices = set()

	# Set of edges where each edge is represented as a string
	# "1->2": is an edge between vertices 1 and 2 
	spanning_tree = set()

	while len(priority_queue.keys()) > 0:
		current_vertex = priority_queue.pop_smallest()

		# If we've visited a vertex earlier then we have all
		# outbound edges from it, we do not process it again
		if current_vertex in visited_vertices:
			continue

		visited_vertices.add(current_vertex)

		# If the current vertex is the source, we haven't traversed an
		# edge yet, no edge to add to our spanning tree
		if current_vertex != source:	
			# The current vertex is connected by the lowest weighted edge
			last_vertex = distance_table[current_vertex][1]	

			edge = str(last_vertex) + "-->" + str(current_vertex)
			if edge not in spanning_tree:
				spanning_tree.add(edge)		

		for neighbor in graph.get_adjacent_vertices(current_vertex):
			# The distance to the neighbor is only the weight of the edge
			# connecting the neighbor
			distance = g.get_edge_weight(current_vertex, neighbor)

			# The last recorded distance of this neighbor
			neighbor_distance = distance_table[neighbor][0]

			# If this neigbor has been seen for the first time or the new edge
			# connecting this neighbor is of a lower weight than the last
			if  neighbor_distance is None or neighbor_distance > distance:
				distance_table[neighbor] = (distance, current_vertex)

				priority_queue[neighbor] = distance


	for edge in spanning_tree:
		print(edge)			
예제 #40
0
 def __init__(self, duration=DEFAULT_DURATION):
     self.duration = duration
     self.latest_ts = int(time.time())
     self.counts = priority_dict()
     self.count = 0
     self.history = {}
예제 #41
0
G = {
    "a": {"b": 1, "c": 2},
    "b": {"a": 1, "f": 5, "c": 10},
    "c": {"a": 2, "b": 10, "f": 2, "e": 4},
    "d": {"f": 8, "e": 3},
    "e": {"c": 4, "d": 3},
    "f": {"b": 5, "c": 2, "d": 8}
}

for u in G:
    for v in G[u]:
        print("L'arête (%s,%s) a pour poids %d" % (u, v, G[u][v]))

print("################################################\n\n\n")

from priority_dict import priority_dict

F = priority_dict() # F est maintenant définie comme une file de priorité

F['x'] = 30 # l'élément x a pour clé 30
F['y'] = 10
F['z'] = 20

while F:
	u = F.pop_smallest()
	print(u)
	if u=='y':
		F['x'] = 5
예제 #42
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
예제 #43
0
import sys
from priority_dict import priority_dict
import matplotlib as mpl
from matplotlib import rc
import matplotlib.pyplot as plt
import numpy as np

mpl.rcParams.update({'font.size': 22})
#Will open and read the results for find_halos.py
#note that find_halos.py ouputs three lists, the first is true, second mg, third cs
#list is [(item, freq_est), (),...()] sorted worst too best (lowest freq first)

true_items = set()
true_counts = priority_dict()
#mg_freq = []
#cs_items = set()
#cs_freq = []
curr = ""
#First retrieve top 1000 elements of true most frequent
c = 0
for line in list(open("true_freqs.txt")):
    if c == 1000:
        break
    data = line.strip().split(',')
    true_items.add(data[0])
    true_counts[data[0]] = data[1]
    c += 1

k_vals = []
recall_points = []
false_pos_points = []
예제 #44
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
예제 #45
0
파일: A4.py 프로젝트: mengqwang2/SDN
				fo=open(demandPath+".txt","r+")
				for s in switch:
					line=fo.readline()
					d[str(s)]=float(line[:-2])

				fo.close()

				c=ng.getController()
				
				ca=queuing.queuing(mu)
				nc=NodeCover.NodeCover(ng,ca,d,theta,c,mu)
				nc.ctrCover()
				nc.calculateNodeFreq()

				freq_pq=priority_dict.priority_dict()
				freq_pq=nc.getNodeFreqPair()
				ctrCover=nc.getCtrCover()
				cost=dict()
				for s in switch:
					cost[s]=0

				ctrList=[]
				ctrCand=[]
				uncovered=list(switch)
				ns=dict()
				for c in ctrCover:
					ctrCand.append(c)

				while (freq_pq):
					#print freq_pq.smallest()
예제 #46
0
				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)

						for n,dist in node_dist[ele].iteritems():
							if n!=ele:
								#ca.updateAssignment(n,ele,d)
								t=2*dist/300000000+ca.queuingTime(n,ele,d)
								
								if t<=theta:
									ca.updateAssignment(n,ele,d)
									neighbour.append(n)
예제 #47
0
def A_star(origin_key, goal_key, graph):

    # min heap for open vertices
    open_queue = priority_dict.priority_dict({})
    #closed dictionary
    closed_dict = {}
    #predecessor dictionary
    predecessors = {}
    #best cost of each vertices
    costs = {}

    #get spatial data of nodes
    node_data = graph.nodes(True)

    costs[origin_key] = 0.0
    open_queue[origin_key] = distance_heuristic(origin_key, goal_key,
                                                node_data)

    #iterate through open_queue through all nodes till goal is found
    goal_found = False
    while (open_queue):
        # pop the initial vertex
        u, u_heu = open_queue.pop_smallest()
        u_cost = costs[u]
        # check condition if the start vertex is goal
        if u == goal_key:
            goal_found = True
            break

        for edge in graph.out_edges([u], data=True):
            # out_edges provide information about the edges.
            #The return value of this is a list of tuples, each of which represent an outgoing edge.
            #The second element of each tuple is the outgoing vertex at the other end of the edge.

            v = edge[1]

            if v in closed_dict:
                continue

            uv_cost = edge[2]['length']

            if v not in open_queue:
                costs[v] = u_cost + uv_cost
                open_queue[v] = u_cost + uv_cost + distance_heuristic(
                    v, goal_key, node_data)
                predecessors[v] = u
            else:
                v_cost = costs[v]
                if u_cost + uv_cost + distance_heuristic(
                        v, goal_key, node_data) < v_cost:
                    open_queue[v] = u_cost + uv_cost + distance_heuristic(
                        v, goal_key, node_data)
                    costs[v] = u_cost + uv_cost
                    predecessors[v] = u

            closed_dict[v] = -1

    # If we get through entire priority queue without finding the goal,
    # something is wrong.
    if not goal_found:
        raise ValueError("Goal not found in search.")

    # Construct the path from the predecessors dictionary.
    return get_path(origin_key, goal_key, predecessors)
예제 #48
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."