示例#1
0
    def _compute_path(self, source, goal):
        """
        Calculates the path connecting two given nodes with the least
        possible weight using the A*-algorithm.

        :param source:
            The node the path is supposed to start on.

        :param goal:
            The node where the path is supposed to end on.

        :return:
            Dictionary with parent for each node where the parent is the node
            which provides the shortest path to a given node.
        """
        parent = {source: None}
        shortest = defaultdict(lambda: float('inf'))
        shortest[source] = 0

        node_pq = pq.PriorityQueue((source, 0))

        while node_pq:
            node = node_pq.pop_task()
            if node == goal:
                return self._restore_path(parent, source, goal)

            for adj_node in self.adj(node):
                cost = shortest[node] + self.weight(node, adj_node)
                if shortest[adj_node] > cost:
                    shortest[adj_node] = cost
                    parent[adj_node] = node
                    node_pq.add_task(adj_node,
                                     cost + self.heuristic(adj_node, goal))
        return []
示例#2
0
def computeMST(G):

    #New Graph
    MST = {}
    pq = priorityqueue.PriorityQueue('min')

    #Create Edge List From Graph
    for g in G:
        for v in G[g]:
            mytuple = G[g][v], (g, v)
            pq.push(mytuple)

    while (not pq.isempty()):
        d, edge = pq.pop()
        v, w = edge
        marked[:] = []
        DFS(MST, v)
        if w not in marked:
            edge1 = {w: d}
            edge2 = {v: d}
            if (MST.has_key(v)):
                MST[v].update(edge1)
            else:
                MST[v] = edge1

            if (MST.has_key(w)):
                MST[w].update(edge2)
            else:
                MST[w] = edge2

    #Return
    return MST
示例#3
0
文件: astar.py 项目: nag92/RBE550
    def __init__(self, env, robot, connected=8, heuristic="eucledian"):

        # Set the variables
        self._env = env
        self._robot = robot

        # which cells to check
        if not (connected == 8 or connected == 4):
            self._connected = 8
        else:
            self._connected = connected

        # how to calculate heuristics
        if not (heuristic is "eucledian" or heuristic is "manhattan"):
            self._heuristic = "eucledian"
        else:
            self._heuristic = heuristic

        # steps for pose
        self._step = 0.1
        self._angle_step = 0.25 * math.pi

        # set up the Queue
        self._fringe = priorityqueue.PriorityQueue()
        self._close_set = []
示例#4
0
def find_shortest_paths(start_node, nodes, edges):
    '''
	Takes in a graph and starting node and returns a dictionary that can be used to
	construct the shortest path to each other node.
	'''
    shortest_distances = dict()
    unvisited = priorityqueue.PriorityQueue()
    shortest_distances[start_node] = NodeInfo(0, None)
    for node in (nodes - {start_node}):
        shortest_distances[node] = NodeInfo(numpy.inf, None)
    for node in nodes:
        # print(type(shortest_distances[node].previous_weight))
        # print(shortest_distances[node].previous_weight)
        #
        unvisited.add(node, shortest_distances[node].previous_weight)
    while not unvisited.is_empty():
        current_node = unvisited.pop()
        for unvisited_node in (unvisited.keys()
                               & adjacent(current_node, edges)):
            new_distance = shortest_distances[
                current_node].previous_weight + get_weight(
                    current_node, unvisited_node, edges)
            if new_distance < shortest_distances[
                    unvisited_node].previous_weight:
                shortest_distances[
                    unvisited_node].previous_weight = new_distance
                shortest_distances[unvisited_node].previous_node = current_node
                unvisited.add(
                    unvisited_node,
                    shortest_distances[unvisited_node].previous_weight)
    return shortest_distances
def weightedsetcover(S, w):
    '''Weighted set cover greedy algorithm:
    pick the set which is the most cost-effective: min(w[s]/|s-C|),
    where C is the current covered elements set.
    The complexity of the algorithm: O(|U| * log|S|) .
    Finding the most cost-effective set is done by a priority queue.
    The operation has time complexity of O(log|S|).
    Input:
    udict - universe U, which contains the <elem, setlist>. (dict)
    S - a collection of sets. (list)
    w - corresponding weight to each set in S. (list)
    Output:
    selected: the selected set ids in order. (list)
    cost: the total cost of the selected sets.
    '''

    udict = {}
    selected = list()
    scopy = []  # During the process, S will be modified. Make a copy for S.
    for index, item in enumerate(S):
        scopy.append(set(item))
        for j in item:
            if j not in udict:
                udict[j] = set()
            udict[j].add(index)

    pq = priorityqueue.PriorityQueue()
    cost = 0
    coverednum = 0
    for index, item in enumerate(scopy):  # add all sets to the priorityqueue
        if len(item) == 0:
            pq.addtask(index, MAXPRIORITY)
        else:
            pq.addtask(index, float(w[index]) / len(item))
    print(len(udict))
    while coverednum < len(udict):
        a = pq.poptask()  # get the most cost-effective set
        #print("a ", a)
        selected.append(a)  # a: set id
        cost += w[a]
        #print("scopy[a] = ", len(scopy[a]))
        coverednum += len(scopy[a])
        # Update the sets that contains the new covered elements
        for m in scopy[a]:  # m: element
            for n in udict[m]:  # n: set id
                if n != a:
                    scopy[n].discard(m)
                    if len(scopy[n]) == 0:
                        pq.addtask(n, MAXPRIORITY)
                    else:
                        pq.addtask(n, float(w[n]) / len(scopy[n]))
        #print("here set cover, length = ", coverednum)
        scopy[a].clear()
        pq.addtask(a, MAXPRIORITY)

    return selected, cost
示例#6
0
def project_end_state(game):
    order = pq.PriorityQueue()
    
    for hero in game.heroes:
        riches = project_end_gold(hero, game)
        order.insert(hero.id, -riches)
    final = []
    while not order.is_empty():
        final.append(order.remove())
    return final
示例#7
0
def sort_by_highest_value(locs, game):
    q = pq.PriorityQueue()
    
    for loc in locs:
        q.insert(loc, -gold_value(loc, game))
    
    locs = []
    while not q.is_empty():
        locs.append(q.remove())
    
    return locs
def submodularsetcover(Q, w, T):
    if len(Q) == 0 or len(T) == 0:
        return [], 0

    C = set()  #elements of T covered so far
    A = list()  #sets added to solution
    A_id = set()  #set ids added to solution

    Q1 = []  #a copy of Q

    for index, item in enumerate(Q):
        Q1.append(set(item))

    alpha = priorityqueue.PriorityQueue()

    for i in range(len(Q)):
        a = w[i]
        b = len(T.intersection(Q[i]))

        if b == 0:
            alpha.addtask(i, MAXPRIORITY)
        else:
            val = a / float(b)
            alpha.addtask(i, val)

    cost = 0
    #print(T)
    while (len(T) > 0):
        #print(len(T))
        #print("stuck up here in submodular")
        choice = alpha.poptask()
        A.append(Q[choice])
        A_id.add(choice)

        cost = cost + w[choice]
        C = C.union(Q[choice])

        T = T - C
        for i in range(0, len(Q)):
            a = w[i]
            Q1[i] = Q1[i] - C
            b = len(T.intersection(Q1[i]))
            if b == 0:
                alpha.addtask(i, MAXPRIORITY)
            else:
                val = a / float(b)
                alpha.addtask(i, val)
        #print("target "+str(T))
        #print("Q1 "+str(Q1))
        #print("I'm here")
    return A, A_id
示例#9
0
#priorityqueue test

import priorityqueue

# test basic pop function
a = priorityqueue.PriorityQueue()
a.add('alpha', 1)
a.add('charlie', 3)
a.add('delta', 4)
assert a.pop() == 'alpha'
assert a.pop() == 'charlie'
assert a.pop() == 'delta'

# test basic update function
a.add('alpha', 1)
a.add('charlie', 3)
a.add('delta', 4)
a.add('alpha', 5)
assert a.pop() == 'charlie'
assert a.pop() == 'delta'
assert a.pop() == 'alpha'

# test for stable pop
a.add('alpha', 1)
a.add('charlie', 3)
a.add('delta', 4)
a.add('alpha2', 1)
assert a.pop() == 'alpha'
assert a.pop() == 'alpha2'
assert a.pop() == 'charlie'
assert a.pop() == 'delta'
示例#10
0
def weightedsetcover(G, S, costs, start_node, shortest_paths, pred, weight, heuristic_value, randomness):
    '''Weighted set cover greedy algorithm:
    pick the set which is the most cost-effective: min(w[s]/|s-C|),
    where C is the current covered elements set.
    The complexity of the algorithm: O(|U| * log|S|) .
    Finding the most cost-effective set is done by a priority queue.
    The operation has time complexity of O(log|S|).
    Input:
    udict - universe U, which contains the <elem, setlist>. (dict)
    S - a collection of sets. (list)
    w - corresponding weight to each set in S. (list)
    Output:
    selected: the selected set ids in order. (list)
    cost: the total cost of the selected sets.
    '''
    w = weight
    K = len(S)
    udict = {}
    selected = list()
    adj = [] # During the process, S will be modified. Make a copy for S.

    conquer_path = [start_node]

    for index, item in enumerate(S):
        adj.append(set(item))
        for j in item:
            if j not in udict:
                udict[j] = set()
            udict[j].add(index)

    conquered_kingdoms = set()
    unconquered_kingdoms = set([i for i in range(K)])
    current_node = start_node

    # print("PQ INITIALIZATION")
    # print("-----------------")

    pq = priorityqueue.PriorityQueue()
    cost = 0
    coverednum = 0
    for index, node in enumerate(adj): # add all sets to the priorityqueue
        if len(node) == 0:
            pq.addtask(index, MAXPRIORITY)
            # print("Added node", index, "with priority", MAXPRIORITY)
        else:
            priority = float(costs[index]) / value(G, start_node, index, unconquered_kingdoms, conquered_kingdoms, start_node, w, heuristic_value, randomness)
            pq.addtask(index, priority)
            # print("Added node", index, "with priority", priority, "(cost:", float(costs[index]), ", value:", value(G, start_node, index, unconquered_kingdoms, conquered_kingdoms, start_node), ")")

    # print(adj)

    while len(conquered_kingdoms) < K:
        target_node = pq.poptask() # get the most cost-effective set
        # print("Conquering node: ", target_node)
        path_to_add = path(current_node, target_node, pred)[1:]
        conquer_path.extend(path_to_add)

        current_node = target_node
        selected.append(target_node) # a: set id
        cost += costs[target_node]
        coverednum += len(adj[target_node])
        conquered_kingdoms.add(target_node)
        if target_node in unconquered_kingdoms:
            unconquered_kingdoms.remove(target_node)

        # pdb.set_trace()

        for adjacent_vertex in [node for node in adj[target_node] if node != target_node]:
            conquered_kingdoms.add(adjacent_vertex)
            if adjacent_vertex in unconquered_kingdoms:
                unconquered_kingdoms.remove(adjacent_vertex)
            pq.addtask(adjacent_vertex, MAXPRIORITY)
            #print("Adding task", adjacent_vertex, "with priority", MAXPRIORITY)
            for n in udict[adjacent_vertex]:
                if n != target_node:
                    adj[n].discard(adjacent_vertex)
                    # if len(adj[n]) == 0:
                    #     pq.addtask(n, MAXPRIORITY)

                    # else:
                    #     costs[n] = acquire_cost(G, target_node, n, shortest_paths)
                    #     #pdb.set_trace()
                    #     pq.addtask(n, costs[n] / value(G, target_node, n, unconquered_kingdoms, conquered_kingdoms))

        # Update the sets that contains the new covered elements
        # Commented out: only updates nodes that touched adjacent nodes that were removed
        # for m in adj[target_node]: # m: element
        #     for n in udict[m]:  # n: set id
        #         if n != target_node:
        #             adj[n].discard(m)
        #             if len(adj[n]) == 0:
        #                 pq.addtask(n, MAXPRIORITY)
        #             else:
        #                 pq.addtask(n, float(costs[n]) / len(adj[n]))

        # Update the acquire cost of each unacquired vertex
        for vertex in unconquered_kingdoms:
            cost = acquire_cost(G, target_node, vertex, shortest_paths)
            pq.addtask(vertex, cost / value(G, target_node, vertex, unconquered_kingdoms, conquered_kingdoms, start_node, w, heuristic_value, randomness))


        adj[target_node].clear()
        pq.addtask(target_node, MAXPRIORITY)

    path_to_add = path(current_node, start_node, pred)[1:]
    conquer_path.extend(path_to_add)
                        
    return selected, cost, conquer_path
示例#11
0
# -*- coding: utf-8 -*-
"""
Created on Sat Feb  6 18:05:18 2016

Test the priority queue

@author: dflemin3
"""

from __future__ import print_function

import numpy as np
import priorityqueue as priq

pq = priq.PriorityQueue()

print("Add 20 random ints to the priority queue.\n")
rand_ints = np.random.randint(0, 100, size=20)

for i in range(0, len(rand_ints)):
    print("Inserting into pq:", rand_ints[i])
    pq.insert(rand_ints[i])

print("\nCall delMin() 20 times.\n")
for i in range(0, len(rand_ints)):
    print("delMin():", pq.delMin())