コード例 #1
0
def main(n, m):
    global total_node_generated
    global Max_Boat_Capcity
    global children_avl

    children_avl = None  # Free the memory
    children_avl = atree.AVLTree()
    Max_Boat_Capcity = m
    total_node_generated = 1  # 1 to count for the first node

    start_time = time.time()

    result = dijkstra(n)

    end_time = (time.time() - start_time)

    if result != None:
        arr_1 = []
        cost = 0
        while result != None:
            arr_1.append(result.__str__())
            cost = cost + result.get_g_value()
            result = result.parent

        print "#" * 30 + " Missionries And Cannibals Result " + "#" * 30
        print '\n'
        print "Path: ", arr_1
        print "Cost: ", cost - 1  # The -1 because to get to the first node it costs 0, but the program has cost 1 by default for each edge
        print "Total Nodes: ", total_node_generated
        print("--- %.5f seconds ---" % end_time)
        print '\n'
コード例 #2
0
def dijkstra(n):

    initial_state = State(n, n, 'left', 0, 0)
    if initial_state.is_goal():
        return initial_state

    explored = atree.AVLTree()  # AVL Tree
    frontier = []

    hq.heappush(frontier, (initial_state.get_g_value(), initial_state))

    #debug_arr = []
    while frontier != []:

        state = hq.heappop(frontier)[1]

        if state.is_goal():
            return state
        explored.insert(state.__hash__(), state)
        children = successors(state)
        for item in children:
            # 1 --------------------------------
            # Helper place holders so we won't have to do the search more than once
            inExplored = explored.find(item.__hash__())
            inFrontier = [
                [True, item2] for item2 in frontier
                if item2.__hash__() == state.__hash__()
            ]  # inFrontier will hold if node found: [True, item], else: []

            # 2 --------------------------------
            # Calculate new_g_value
            new_g_value = state.get_g_value() + item.get_g_value()

            # 3 --------------------------------
            # case 1
            if inExplored == None and inFrontier == []:
                hq.heappush(frontier, (item.get_g_value(), item))
            # case 2
            elif inFrontier != []:
                # Edge Relaxation
                # Ex. frontier = [True, (3, <__main__.Node instance at 0x7f6045676d40>)]
                if new_g_value < inFrontier[0][1].get_g_value():
                    inFrontier[0][1].set_g_value(new_g_value)
                    hq.heappush(frontier, (new_g_value, inFrontier[0][1]))

            # case 3: ui in Explored
            elif inExplored != None:
                # Check that this edge is not connecting back to the parent of the current node
                if state.parent != None:
                    if state.parent.__hash__() != item.__hash__():
                        if new_g_value < inExplored.data.get_g_value():
                            inExplored.data.set_g_value(new_g_value)
                            inExplored.data.parent = state
                            # Add it to Frontier and remove it from Explored
                            hq.heappush(frontier,
                                        (new_g_value, inExplored.data))
                            explored.remove(item.__hash__())
    #return debug_arr
    return None
コード例 #3
0
def do_operations(init_arrangment, h=1):
    """ h0 = dijkstra, h1 = A*, h2 = manhattan distance """
    global total_node_generated
    global children_avl
    global frontier_avl
    global frontier_dict
    global children_dict

    children_avl = None  # Free the memory
    children_avl = atree.AVLTree()

    children_dict = None  # Free the memory
    children_dict = {}

    frontier_avl = None  # Free the memory
    frontier_avl = atree.AVLTree()

    frontier_dict = None  # Free the memory
    frontier_dict = {}

    huristic = huristic_helper(init_arrangment, h)
    total_node_generated = 0

    start_time = time.time()
    result = dijkstra_a_star(
        State(init_arrangment, 0, huristic, 0 + huristic, None), h)
    end_time = (time.time() - start_time)

    if result != None:
        arr_1 = []
        cost = 0
        while result != None:
            arr_1.append(result.arrangment)
            cost = cost + result.get_g_value()
            result = result.parent

        print "#" * 30 + " Misplaced 1D tiles " + "#" * 30
        print '\n'
        print "Path: ", arr_1
        print "Cost: ", cost
        print "Total Nodes: ", total_node_generated
        print "Effective Branching Factor: ", math.pow(
            float(total_node_generated), 1.0 / float(len(arr_1) - 1)
        )  # Formula: b=x^1/d, where x: total number of nodes searched, d: depth (-1: to remove the root node from the count since we are looking at the depth)
        print("--- %.5f seconds ---" % end_time)
        print '\n'
コード例 #4
0
ファイル: graph.py プロジェクト: SalN3t/heuristic
def dijkstra(graph, src, dist):
    total_node_generated = 0
    expolored = atree.AVLTree()  # AVL Tree
    frontier = []

    for item in graph:
        if item != src:
            hq.heappush(
                frontier,
                (float('inf'), Node(item, graph[item], None, float('inf'))))
            total_node_generated = total_node_generated + 1
    hq.heappush(frontier, (0, Node(src, graph[src], None, 0)))
    total_node_generated = total_node_generated + 1

    while frontier != []:
        u = hq.heappop(frontier)
        expolored.insert(u[1].key, u)

        all_succ = u[1].succ
        for item in all_succ:
            # 1 --------------------------------
            # Helper place holders so we won't have to do the search more than once
            inExplored = expolored.find(item)
            inFrontier = [
                [True, item2] for item2 in frontier if item2[1].key == u
            ]  # inFrontier will hold if node found: [True, item], else: []

            # 2 --------------------------------
            # Calculate new_g_value
            new_g_value = 0
            if u[1].key == float('inf'):
                new_g_value = 0 + all_succ[item]
            else:
                new_g_value = u[1].g_value + all_succ[item]
            # 3 --------------------------------
            # case 1
            if inExplored == None and inFrontier == []:
                hq.heappush(
                    frontier,
                    (new_g_value, Node(item, graph[item], u, new_g_value)))
                total_node_generated = total_node_generated + 1
            # case 2
            elif inFrontier != []:
                # Edge Relaxation
                # Ex. frontier = [True, (3, <__main__.Node instance at 0x7f6045676d40>)]
                if new_g_value < inFrontier[0][1][1].g_value:
                    frontier[0][1][1].update_g_value_and_parent(new_g_value, u)
                    inFrontier[0][1][1].g_value = new_g_value
                    inFrontier[0][1][1].parent_node = u
                    hq.heappush(frontier, (new_g_value, inFrontier[0][1][1]))
            # case 3: ui in Explored, Handling minus edges
            elif inExplored != None:
                # Check that this edge is not connecting back to the parent of the current node
                if u[1].parent_node != None:
                    if u[1].parent_node[1].key != item:
                        if new_g_value < inExplored.data[1].g_value:

                            inExplored.data[1].g_value = new_g_value
                            inExplored.data[1].parent_node = u
                            # Add it to Frontier and remove it from Explored
                            hq.heappush(frontier,
                                        (new_g_value, inExplored.data))
                            expolored.remove(item)
        if u[1].key in dist:
            tmp = []
            total_cost = 0
            u[1].prent_node = u
            return u, total_node_generated

    return expolored, total_node_generated
コード例 #5
0
def dijkstra_a_star(initial_state, h):
    global frontier_avl
    global frontier_dict

    frontier_avl = None
    frontier_avl = atree.AVLTree()

    if is_goal(initial_state):
        return initial_state

# explored = atree.AVLTree() # AVL Tree
    explored_dict = {}

    frontier = []

    hq.heappush(frontier, (initial_state.f_value, initial_state))
    #frontier_avl.insert(initial_state.__hash__(), initial_state)
    frontier_dict[initial_state.__hash__()] = initial_state
    while frontier != []:
        #while frontier_avl.is_Empty() == False:
        # while frontier_dict != {}:

        state = hq.heappop(frontier)[1]

        #print state.__hash__()
        #print frontier_dict
        frontier_dict.pop(state.__hash__())
        # print dict(state_dict)
        #state = frontier_avl.pop_min_value_key().data
        #state = frontier_dict.pop
        #frontier_avl.remove(state.__hash__())

        if is_goal(state.arrangment):
            return state

        #explored.insert(state.__hash__(), state)
        explored_dict[state.__hash__()] = state
        children = successors(state, h)
        #children = re_order_states(children)
        for item in children:
            # 1 --------------------------------
            # Helper place holders so we won't have to do the search more than once
            # inExplored = explored.find(item.__hash__())
            # inFrontier = frontier_avl.find(item.__hash__())

            inExplored = dict_key_found(explored_dict, item.__hash__())
            inFrontier = dict_key_found(frontier_dict, item.__hash__())

            # 2 --------------------------------
            # Calculate new_g_value
            new_g_value = state.get_g_value() + item.get_g_value()

            # 3 --------------------------------
            # case 1
            if inExplored == None and inFrontier == None:

                hq.heappush(frontier, (item.f_value, item))
                frontier_dict[item.__hash__()] = item
            # frontier_avl.insert(item.__hash__(), item)

            # case 2
            elif inFrontier != None:
                # Edge Relaxation
                # Ex. frontier = [True, (3, <__main__.Node instance at 0x7f6045676d40>)]
                if new_g_value < inFrontier.get_g_value():
                    inFrontier.set_g_value(new_g_value)
                    hq.heappush(frontier, (inFrontier.f_value, inFrontier))
                    frontier_dict[item.__hash__()] = item

                # if new_g_value < inFrontier.date.get_g_value():
                #     inFrontier.data.set_g_value(new_g_value)

                #     hq.heappush(frontier,(inFrontier.data.f_value,inFrontier.data))
                #     frontier_dict[initial_state.__hash__()] = initial_state
                #    #frontier_avl.insert(item.__hash__(), item)

    return None
コード例 #6
0
import heapq as hq
import pyavltree as atree
import time
import math

total_node_generated = 0
Max_Boat_Capcity = 0
children_avl = atree.AVLTree()


class State():
    #def __init__(self, cannibalLeft, missionaryLeft, boat, cannibalRight, missionaryRight, g_value = 1 ):
    def __init__(self,
                 cannibalLeft,
                 missionaryLeft,
                 boat,
                 cannibalRight,
                 missionaryRight,
                 g_value=1):
        self.cannibalLeft = cannibalLeft
        self.missionaryLeft = missionaryLeft
        self.boat = boat
        self.cannibalRight = cannibalRight
        self.missionaryRight = missionaryRight
        self.parent = None
        self.g_value = g_value

    def __str__(self):
        return "(" + str(self.missionaryLeft) + "," + str(
            self.cannibalLeft) + "," + str(self.boat) + "," + str(
                self.missionaryRight) + "," + str(self.cannibalRight) + ")"