コード例 #1
0
ファイル: iTreeGenerator.py プロジェクト: kimbyeongjun/ATHENA
    def all_pairs_dijkstra(self, biGraph, weight='weight'):
        for node in biGraph.nodes():
            g = biGraph.copy()
            attributes = nx.get_edge_attributes(g, 'rname')
            dist = {}
            prev = {}
            last_attribute = {}
            Q = PriorityQueue()

            dist[node] = 0
            prev[node] = [node]
            last_attribute[node] = None

            for n in g.nodes():
                if n != node:
                    dist[n] = float('Inf')
                    prev[n] = []
                Q.insert(dist[n], n)

            while Q.size() > 0:
                p, u = Q.pop()

                for v in g.neighbors(u):
                    p_attribute = last_attribute[u]
                    attribute = attributes[(u, v)]
                    num = 100 if p_attribute == 'is-a' and attribute == 'is-a2' else 0

                    alt = dist[u] + g[u][v].get('weight', 1) + num
                    if alt < dist[v]:
                        dist[v] = alt
                        prev[v] = prev[u] + [v]
                        last_attribute[v] = attribute
                        Q.insert(dist[v], v)
            yield (node, (dist, prev))
コード例 #2
0
ファイル: search.py プロジェクト: Aliz-f/ui-ai991-python
def graph_search(problem, heuristics):
    node = nodeTree(problem.agent, None, None, heuristics[problem.agent])
    frontier = PriorityQueue()
    frontier.insert(node)
    explored = []
    while frontier:
        node = frontier.pop()
        if problem.goal_test(node):
            return soloution(node)
        explored.append(node)
        children = expand_tree(problem, node, heuristics)
        for child in children:
            if not frontier.has_item(child) and child not in explored:
                frontier.insert(child)
    return
コード例 #3
0
class TransactionPool:
    """Transaction pool for a miner"""

    def __init__(self, env, identifier, neighbourList, nodes, params):
        self.env = env
        self.identifier = identifier
        self.neighbourList = neighbourList
        self.params = params
        self.nodes = nodes
        self.transactionQueue = PriorityQueue()
        self.prevTransactions = []

    def getTransaction(self, transactionCount):
        """Returns transactionCount number of Transactions. Returns
		 top transactions based on miner reward"""
        return self.transactionQueue.get(transactionCount)

    def popTransaction(self, transactionCount):
        """Remove transactions from transaction pool. Called when transactions 
		are added by a received block or a block is mined."""
        poppedTransactions = self.transactionQueue.pop(transactionCount)
        self.prevTransactions.append(poppedTransactions)

    def putTransaction(self, transaction, sourceLocation):
        """Add received transaction to the transaction pool and broadcast further"""
        destLocation = self.nodes[self.identifier].location
        delay = getTransmissionDelay(sourceLocation, destLocation)
        yield self.env.timeout(delay)
        if (
            not self.transactionQueue.isPresent(transaction)
            and transaction not in self.prevTransactions
        ):
            self.transactionQueue.insert(transaction)
            broadcast(
                self.env,
                transaction,
                "Transaction",
                self.identifier,
                self.neighbourList,
                self.params,
                nodes=self.nodes,
            )
            if self.params["verbose"] == "vv":
                print(
                    "%7.4f : %s accepted by %s"
                    % (self.env.now, transaction.identifier, self.identifier)
                )
コード例 #4
0
def branch_n_price(n, demands, capacity, distances, MasterProb):

    queue = PriorityQueue()
    MasterProb.RelaxOptimize()
    obj_val = MasterProb.relax_modelo.ObjVal

    queue.insert(obj_val, MasterProb)
    best_int_obj = 1e3
    best_relax_obj = 1e3

    nodes_explored = 0
    best_model = None

    while not queue.isEmpty():
        obj_val, MP_branch = queue.delete()
        nodes_explored += 1
        MP_branch.RelaxOptimize()
        solution = MP_branch.getSolution()
        duals = MP_branch.getDuals()

        branch_cost = MP_branch.getCosts()
        branch_routes = MP_branch.modelo.getA().toarray()
        sol_is_int = all([float(round(s, 4)).is_integer() for s in solution])
        # sol_is_int = all([False if i > 0.3 and np.abs(i - 1.0) > 0.3 else True for i in solution ])

        if obj_val < best_int_obj and sol_is_int:
            print(f"Best Integer Obj: {obj_val}")
            print(f"Nodes explored: {nodes_explored}")
            best_int_obj = obj_val

            # print(f"best sol: {solution}")
            best_model = copy_model(branch_cost, branch_routes, MP_branch)

        if obj_val < best_relax_obj:
            print(f"Best Relaxed Obj: {obj_val}")
            print(f"Nodes explored: {nodes_explored}")
            best_relax_obj = obj_val

        # --- # --- # Column generation # --- # --- #
        new_MP = column_generation(n, demands, capacity, distances, duals,
                                   MP_branch)

        if new_MP != None:
            new_MP.RelaxOptimize()
            branch_cost = new_MP.getCosts()
            branch_routes = new_MP.modelo.getA().toarray()
            if new_MP.relax_modelo.ObjVal <= best_relax_obj:
                queue.insert(new_MP.relax_modelo.ObjVal,
                             copy_model(branch_cost, branch_routes, new_MP))

        else:
            # --- # If stopped col generation then branch if solution is not integer # --- #

            if not sol_is_int:

                # print("#--#--#--# Not integer solution  ........Branching")
                queue = branch(branch_cost, branch_routes, n, demands,
                               capacity, distances, duals, solution, MP_branch,
                               queue, best_relax_obj)
            else:
                # print(f"best sol: {solution}")
                best_model = MP_branch

    return best_model
コード例 #5
0
ファイル: _new.py プロジェクト: Naraharirahul/MotionPlanning
def compute_path(grid,start,goal,cost,heuristic):
   
    # Use the OrderedSet for your closed list
    closed_set = OrderedSet()
    
    # Use thePriorityQueue for the open list
    open_set = PriorityQueue(order=min, f=lambda v: v.f)      

    # Keep track of the parent of each node. Since the car can take 4 distinct orientations, 
    # for each orientation we can store a 2D array indicating the grid cells. 
    # E.g. parent[0][2][3] will denote the parent when the car is at (2,3) facing up    
    parent = [[[' ' for row in range(len(grid[0]))] for col in range(len(grid))], 
             [[' ' for row in range(len(grid[0]))] for col in range(len(grid))],
             [[' ' for row in range(len(grid[0]))] for col in range(len(grid))],
             [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]]

    # The path of the car
    path =[['-' for row in range(len(grid[0]))] for col in range(len(grid))]
    dist =[]
    P =[]
    x = start[0]
    y = start[1]
    theta = start[2]
    h = heuristic[x][y]
    g = 0
    f = g+h
    open_set.put(start, Value(f=f,g=g))
    for i in range(0,6):
        for j in range(0,5):
            if grid[i][j] == 0:
                dist = 10000000
                x = P(i)
                y = P(j
        c dfd #cIm just)

                open_set.put([i][j], dist)
    open_set.insert(goal,0)

    while not open_set.empty():
        x,y = open_set.pop()


    # your code: implement A*

    # Initially you may want to ignore theta, that is, plan in 2D.
    # To do so, set actions=forward, cost = [1, 1, 1, 1], and action_name = ['U', 'L', 'R', 'D']
    # Similarly, set parent=[[' ' for row in range(len(grid[0]))] for col in range(len(grid))]

    return path, closed_set


if __name__ == "__main__":
    path,closed=compute_path(grid, init, goal, cost, heuristic)

    for i in range(len(path)):
        print(path[i])

    print("\nExpanded Nodes")    
    for node in closed:
        print(node)

"""