コード例 #1
0
def AStar(initial_state):
    global COUNT, BACKLINKS
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQ()
    # inserts the initial state with a priority of 0 (priority for initial state is irrelevant to algorithm)
    OPEN.insert(initial_state, 0)
    CLOSED = []
    BACKLINKS[initial_state] = None

    while OPEN.__len__() > 0:
        # S = min-priority state (priority value gets discarded, only state is looked at)
        S = OPEN.deletemin()[0]
        while S in CLOSED:
            S = OPEN.deletemin()
        CLOSED.append(S)

        # DO NOT CHANGE THIS SECTION: beginning
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
            # DO NOT CHANGE THIS SECTION: end

        COUNT += 1
        # if (COUNT % 32)==0:
        if True:
            # print(".",end="")
            # if (COUNT % 128)==0:
            if True:
                print("COUNT = " + str(COUNT))
                print("len(OPEN)=" + str(len(OPEN)))
                print("len(CLOSED)=" + str(len(CLOSED)))

        L = []
        # looks at all possible new states from operations on S
        # if the new state has not already been put on CLOSED, append to L
        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                #print(new_state.__str__())
                if not occurs_in(new_state, CLOSED):
                    L.append(new_state)
                    BACKLINKS[new_state] = S

        # adds new states in L into OPEN with their priorities
        # if any state already occurs in OPEN...
        #   if L's state has a lower priority, change OPEN's state priority to L's
        #   otherwise, keep OPEN's state in OPEN, ignore L's
        for state in L:
            g_state = G(state)
            if OPEN.__contains__(state):
                if g_state < OPEN.getpriority(state):
                    OPEN.remove(state)
                else:
                    break
            OPEN.insert(state, g_state)
コード例 #2
0
ファイル: AStar.py プロジェクト: chiho828/State-Space-Search
def AStar(initial_state):
    global COUNT, BACKLINKS
    # TODO: initialze and put first state into
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = []
    CLOSED = []
    BACKLINKS[initial_state] = -1
    OPEN.append(initial_state)
    PRI.append(0)
    G = {}
    F = {}
    G[initial_state] = 0

    while len(OPEN) > 0:
        index = findMin()
        S = OPEN[index]
        del OPEN[index]
        del PRI[index]
        while S in CLOSED:
            index = findMin()
            S = OPEN[index]
            del OPEN[index]
            del PRI[index]
        CLOSED.append(S)

        # DO NOT CHANGE THIS SECTION: begining
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
        # DO NOT CHANGE THIS SECTION: end

        # TODO: finish A* implementation
        COUNT += 1
        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if not (new_state in OPEN) and not (new_state in CLOSED):
                    G[new_state] = G[S] + 1
                    F[new_state] = G[new_state] + heuristics(new_state)
                    BACKLINKS[new_state] = S
                    OPEN.append(new_state)
                    PRI.append(F[new_state])
                elif BACKLINKS[new_state] != -1:
                    other_parent = BACKLINKS[new_state]
                    temp = F[new_state] - G[other_parent] + G[S]
                    if temp < F[new_state]:
                        G[new_state] = G[new_state] - F[new_state] + temp
                        F[new_state] = temp
                        BACKLINKS[new_state] = S
                        if new_state in CLOSED:
                            OPEN.append(new_state)
                            PRI.append(F[new_state])
                            CLOSED.remove(new_state)
コード例 #3
0
ファイル: AStar.py プロジェクト: mmb1995/search-algorithms
def AStar(initial_state):
    global COUNT, BACKLINKS, MAX_OPEN_LENGTH

    # STEP 1. Put the start state on a list OPEN
    OPEN = PriorityQB()
    OPEN.insert(initial_state, heur(initial_state))
    x = OPEN.getpriority(initial_state)
    print(x)
    CLOSED = []
    BACKLINKS[initial_state] = None
    moves = {initial_state: 0}

    # STEP 2. If OPEN is empty, output “DONE” and stop.
    while len(OPEN) != 0:
        report(OPEN, CLOSED, COUNT)
        if len(OPEN) > MAX_OPEN_LENGTH: MAX_OPEN_LENGTH = len(OPEN)

        # STEP 3. Select the first state on OPEN and call it S.
        #         Delete S from OPEN.
        #         Put S on CLOSED.
        #         If S is a goal state, output its description
        S = OPEN.deletemin()
        S = S[0]
        CLOSED.append(S)

        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            print('Length of solution path found: ' + str(len(path) - 1) +
                  ' edges')
            return
        COUNT += 1

        # STEP 4. Generate the list L of successors of S and delete
        #         from L those states already appearing on CLOSED.
        L = []
        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if not (new_state in CLOSED):
                    priority = getPriority(new_state, moves[S] + 1)
                    if new_state in OPEN and priority < OPEN.getpriority(
                            new_state):
                        OPEN.remove(new_state)
                    if new_state not in OPEN:
                        BACKLINKS[new_state] = S
                        moves[new_state] = moves[S] + 1
                        OPEN.insert(new_state, priority)
コード例 #4
0
def IterativeAStar(initial_state):
    global COUNT, BACKLINKS

    OPEN = [initial_state]
    CLOSED = []
    BACKLINKS[Problem.HASHCODE(initial_state)] = -1
    g = {Problem.HASHCODE(initial_state): 0}

    while OPEN != []:
        S = OPEN[0]
        del OPEN[0]
        CLOSED.append(S)

        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            backtrace(S)
            return

        COUNT += 1
        if (COUNT % 32) == 0:
            print(".", end="")
            if (COUNT % 128) == 0:
                print("COUNT = " + str(COUNT))
                print("len(OPEN)=" + str(len(OPEN)))
                print("len(CLOSED)=" + str(len(CLOSED)))
        L = []
        for op in Problem.OPERATORS:
            #Optionally uncomment the following when debugging
            #a new problem formulation.
            #print("Trying operator: "+op.name)
            if op.precond(S):
                new_state = op.state_transf(S)
                if not occurs_in(new_state, CLOSED):
                    L.append(new_state)
                    BACKLINKS[Problem.HASHCODE(new_state)] = S
                    g[Problem.HASHCODE(new_state)] = g[Problem.HASHCODE(S)] + 1
                    #Uncomment for debugging:
                    #print(Problem.DESCRIBE_STATE(new_state))

        for s2 in L:
            for i in range(len(OPEN)):
                if Problem.DEEP_EQUALS(s2, OPEN[i]):
                    del OPEN[i]
                    break

        OPEN = L + OPEN
        OPEN = sorted(OPEN,
                      key=lambda s: g[Problem.HASHCODE(s)] + heuristics(s))
コード例 #5
0
def AStar(initial_state):
    global COUNT, BACKLINKS
    # TODO: initialze and put first state into
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQueue()
    OPEN.put((0,initial_state))
    SEEN = []
    CLOSED = []
    G_SCORE = {}
    G_SCORE[initial_state] = 0
    BACKLINKS[initial_state] = -1
    MAX_GSCORE = 0

    while not OPEN.empty():
        S = OPEN.get()[1]
        while S in CLOSED:
            S = OPEN.get()[1]
        CLOSED.append(S)

        # DO NOT CHANGE THIS SECTION: begining
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            # path = backtrace(S)
            print(len(BACKLINKS))
            return path, Problem.PROBLEM_NAME
        # DO NOT CHANGE THIS SECTION: end

        COUNT += 1
        # TODO: finish A* implementation
        for op in Problem.OPERATORS:
            if op.precond(S):
                next_state = op.state_transf(S)
                # This is a valid move so you need to calculate F(n) = G(n) + H(n)
                if next_state not in SEEN and next_state not in CLOSED:
                    if S in G_SCORE:
                        next_G_SCORE = 1 + G_SCORE[S]
                    else:
                        next_G_SCORE = MAX_GSCORE
                    G_SCORE[next_state] = next_G_SCORE
                    if next_G_SCORE > MAX_GSCORE:
                        MAX_GSCORE = next_G_SCORE
                    next_F_SCORE = next_G_SCORE + heuristics(next_state)
                    OPEN.put((next_F_SCORE, next_state))
                    SEEN.append(next_state)
                    BACKLINKS[next_state] = S
                    print(S)
コード例 #6
0
ファイル: AStar.py プロジェクト: kalo37/cse_415
def AStar(initial_state):
    global COUNT, BACKLINKS
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQ()
    CLOSED = []
    BACKLINKS[initial_state] = None
    g = {initial_state: 0}

    OPEN.insert(initial_state, heuristics(initial_state))

    while not len(OPEN) == 0:
        S, f = OPEN.deletemin()
        while S in CLOSED:
            S, f = OPEN.deletemin()
        CLOSED.append(S)

        # DO NOT CHANGE THIS SECTION: begining
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
        # DO NOT CHANGE THIS SECTION: end

        COUNT += 1
        print(COUNT)

        L = []
        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if not occurs_in(new_state, CLOSED):
                    L.append(new_state)
                    BACKLINKS[new_state] = S
                    if new_state not in g.keys():
                        g[new_state] = g[S] + 1

        for s2 in L:
            if s2 in OPEN:
                OPEN.remove(s2)

        for elt in L:
            OPEN.insert(elt, heuristics(elt) + g[elt])
コード例 #7
0
def AStar(initial_state):
    counter = count() # this breaks pq ties
    global COUNT, BACKLINKS
    # TODO: initialze and put first state into
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQueue()
    CLOSED = []
    OPEN.put((0, next(counter), initial_state))
    BACKLINKS[initial_state] = -1


    while not OPEN.empty():
        COUNT += 1
        S = OPEN.get()
        while S[2] in CLOSED:
            S = OPEN.get()
        cost = S[0]
        S = S[2]
        CLOSED.append(S)
        # DO NOT CHANGE THIS SECTION: begining
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
        # DO NOT CHANGE THIS SECTION: end

        # TODO: finish A* implementation
        for op in Problem.OPERATORS:
          #Optionally uncomment the following when debugging
          #a new problem formulation.
          # print("Trying operator: "+op.name)
          if op.precond(S):
            new_state = op.state_transf(S)
            if not (new_state in CLOSED):
                h = heuristics(new_state)
                h += cost
                new_pq_item = (h, next(counter), new_state)
                OPEN.put(new_pq_item)
                BACKLINKS[new_state] = S
コード例 #8
0
def AStar(initial_state):
    global COUNT, BACKLINKS
    # TODO: initialze and put first state into
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQ()
    CLOSED = []
    #define the g score which means
    #the cost of the move will increase by 1 at each depth
    g = {}
    g[initial_state] = 0
    BACKLINKS[initial_state] = None
    #in priority queue, the state is the element
    #and the F score is the priority
    #F socre is the heuristics score plus g scorce
    OPEN.insert(initial_state, g[initial_state] + 0)

    while not OPEN.isEmpty():
        COUNT += 1
        S = OPEN.deletemin()
        while S in CLOSED:
            S = OPEN.deletemin()
        CLOSED.append(S)
        # DO NOT CHANGE THIS SECTION: begining
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
            # DO NOT CHANGE THIS SECTION: end

            # TODO: finish A* implementation
        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if not (new_state in CLOSED):
                    h = heuristics(new_state)
                    g[new_state] = g[S] + 1
                    if new_state not in OPEN:
                        OPEN.insert(new_state, h + g[new_state])
                        BACKLINKS[new_state] = S
コード例 #9
0
def AStar(initial_state):
    global COUNT, BACKLINKS
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQueue()
    OPEN.put((heuristics(initial_state), initial_state))
    OPENlist = [initial_state]
    #OPEN.put(initial_state)
    CLOSED = []
    BACKLINKS[initial_state] = -1
    prioritycount = 0

    while not OPEN.empty():
        S = OPEN.get()[1]
        OPENlist.remove(S)
        while S in CLOSED:
            S = OPEN.get()[1]
        CLOSED.append(S)

        # DO NOT CHANGE THIS SECTION: begining
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
        # DO NOT CHANGE THIS SECTION: end

        COUNT += 1
        for op in Problem.OPERATORS:
            prioritycount += 2
            #print(prioritycount)
            #print("Trying operator: "+op.name)
            if op.precond(S):
                new_state = op.state_transf(S)
                if not (new_state in CLOSED) and not (new_state in OPENlist):
                    #print(heuristics(new_state) +prioritycount)
                    #print(new_state)
                    #print(OPEN.qsize())
                    OPEN.put((heuristics(new_state), new_state))
                    OPENlist.append(new_state)
                    BACKLINKS[new_state] = S
コード例 #10
0
def IterateAStar(initial_state):
    global COUNT, BACKLINKS

    OPEN = [[initial_state, heuristics(initial_state)]]
    CLOSED = []

    # print(initial_state)
    COST = {Problem.HASHCODE(initial_state): 0}

    BACKLINKS[Problem.HASHCODE(initial_state)] = -1

    while OPEN != []:
        S = OPEN[0]
        del OPEN[0]
        CLOSED.append(S)

        if Problem.GOAL_TEST(S[0]):
            print(Problem.GOAL_MESSAGE_FUNCTION(S[0]))
            backtrace(S[0])
            return

        COUNT += 1
        if (COUNT % 32)==0:
            print(".",end="")
            if (COUNT % 128)==0:
                print("COUNT = "+str(COUNT))
                print("len(OPEN)="+str(len(OPEN)))
                print("len(CLOSED)="+str(len(CLOSED)))
        L = []

        # for each possible child in S (state)
        for op in Problem.OPERATORS:
            # is a child
            if op.precond(S[0]):
                new_state = op.state_transf(S[0])

                # index of occurrence in CLOSED
                occur_closed = occurs_in(new_state, CLOSED)

                # index of occurence in OPEN
                occur_open = occurs_in(new_state, OPEN)

                # the moves made so far + 1
                new_cost = COST[Problem.HASHCODE(S[0])] + 1
                # place in neighbor if new state
                if occur_closed == -1 and occur_open == -1:
                    L.append([new_state, heuristics(new_state)])
                    BACKLINKS[Problem.HASHCODE(new_state)] = S[0]
                    COST[Problem.HASHCODE(new_state)] = new_cost

                elif occur_open > -1:
                    # check to see if this move is more efficient
                    if COST[Problem.HASHCODE(new_state)] > new_cost:
                        COST[Problem.HASHCODE(new_state)] = new_cost
                        OPEN[occur_open] = [new_state, new_cost]

        # for all neighbors found, if it equals to states in OPEN,
        # delete it, shouldn't occur but juuuuust in case...
        for s2 in L:
            for i in range(len(OPEN)):
                if Problem.DEEP_EQUALS(s2, OPEN[i][0]):
                    del OPEN[i]; break

        OPEN = L + OPEN
        OPEN.sort(key=lambda x: x[1])
コード例 #11
0
def AStar(initial_state):
    global COUNT, BACKLINKS
    OPEN = PriorityQ()  #currently discovered, not yet evaluated states
    CLOSED = []  #already evaluated states
    BACKLINKS[initial_state] = None  #Tracks most efficient previous step

    #Calculate F, G, H scores for Starting state
    initialize_scores(initial_state)

    #Only one state is known as of now
    OPEN.insert(initial_state, F_SCORE[initial_state])

    while OPEN.isEmpty() != True:
        S, priority = OPEN.deletemin()
        while S in CLOSED:
            S = OPEN.deletemin()
        CLOSED.append(S)

        # DO NOT CHANGE THIS SECTION: beginning
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
            # DO NOT CHANGE THIS SECTION: end

        COUNT += 1
        if (COUNT % 32) == 0:
            #        if True:
            # print(".",end="")
            #            if (COUNT % 128*128)==0:
            if True:
                print("COUNT = " + str(COUNT))
                #print("len(OPEN)=" + str(len(OPEN))) #PriorityQ OPEN doesn't have len()
                print("len(CLOSED)=" + str(len(CLOSED)))

        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if not occurs_in(new_state,
                                 CLOSED):  #ignore already evaluated neighbors

                    #find tentative score of neighbor
                    tentative_g_score = G_SCORE[S] + 1

                    if new_state not in G_SCORE:  #Default INFINITY
                        BACKLINKS[
                            new_state] = S  #First known path to new_state

                    elif tentative_g_score <= G_SCORE[new_state]:
                        BACKLINKS[
                            new_state] = S  # Found better path to new_State

                    else:
                        continue  #current path is not the best path to the neighbor

                    G_SCORE[new_state] = tentative_g_score
                    F_SCORE[new_state] = G_SCORE[new_state] + h_score_fn(
                        new_state)

                    # Delete previous F-score in PriorityQ if it exists
                    if OPEN.__contains__(new_state):
                        OPEN.remove(new_state)

                    #Update PriorityQ with new priority
                    OPEN.insert(new_state, F_SCORE[new_state])

                # print(Problem.DESCRIBE_STATE(new_state))
        #print(OPEN)

    #Failure, if goal_test has not succeeded until now
    print("COULD NOT FIND GOAL")
    return
コード例 #12
0
ファイル: AStar.py プロジェクト: dc8291/Sp17-CSE415-AI
def AStar(initial_state):
    global COUNT, BACKLINKS
    # TODO: initialze and put first state into 
    # priority queue with respective priority
    # add any auxiliary data structures as needed
    OPEN = PriorityQueue()
    OPEN.put(initial_state, 0)
    OpenList = [initial_state]
    CLOSED = []
    BACKLINKS[initial_state] = -1
    COST = {}
    COST[initial_state] = 0

    while not OPEN.empty():
        S = OPEN.get()
        while S in CLOSED:
            S = OPEN.get()
        CLOSED.append(S)
        
        # DO NOT CHANGE THIS SECTION: beginning
        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            path = backtrace(S)
            return path, Problem.PROBLEM_NAME
        # DO NOT CHANGE THIS SECTION: end

        COUNT += 1
        if (COUNT % 32) == 0:
            print(".", end="")
            if (COUNT % 128) == 0:
                print("COUNT = " + str(COUNT))
                print("len(OPEN)=" + str(OPEN.qsize()))
                print("len(CLOSED)=" + str(len(CLOSED)))
        for op in Problem.OPERATORS:  # For every successor:
            if op.precond(S):         # if the move is legal to make
                new_state = op.state_transf(S)  # set new_state
                new_cost = COST[S] + 1           # set new_state's cost
                if new_state not in OpenList or new_state not in CLOSED:  # if the new state has never been seen before
                    COST[new_state] = new_cost  # store the cost of the new_state
                    new_state.f = new_cost + heuristics(new_state)  # set new_state's f value
                    BACKLINKS[new_state] = S  # set new_state's parent
                    OPEN.put(new_state, new_state.f)  # put new_state into open
                    OpenList.append(new_state)  # just for existence
                else:  # if new_state has been seen before
                    if new_state in BACKLINKS: # if the parent exists
                        temp = new_state.f + COST[S]  # set temp to the new cost
                    else:
                        temp = new_state.f  # set temp to old f value
                    if temp < new_state.f:  # if the new cost is lower
                        COST[new_state] = COST[new_state] - new_state.f + temp  # store the new value
                        new_state.f = temp
                        if new_state in OpenList:  #
                            OPEN.remove(new_state)
                            heapq.heapify(OPEN)
                            OPEN.put(new_state, new_state.f)
                            OpenList.append(new_state)
                        if new_state in CLOSED:
                            OPEN.put(new_state, new_state.f)
                            CLOSED.remove(new_state)

    print("Error: No path found")
コード例 #13
0
ファイル: AStarOld.py プロジェクト: vaibhavi-r/CSE-415
def AStar(initial_state):
    # print("In RecDFS, with depth_limit="+str(depth_limit)+", current_state is ")
    # print(Problem.DESCRIBE_STATE(current_state))
    global COUNT, BACKLINKS

    #Tracks most efficient previous step
    BACKLINKS[initial_state] = None

    #already evaluated states
    CLOSED = []

    #currently discovered, not yet evaluated states
    OPEN = PriorityQ()

    #Calculate F, G, H scores
    initialize_scores(initial_state)

    #Only initial node is known as of now
    OPEN.insert(initial_state, F_SCORE[initial_state])

    while OPEN.isEmpty() != True:
        S = OPEN.deletemin()
        CLOSED.append(S)

        if Problem.GOAL_TEST(S):
            print(Problem.GOAL_MESSAGE_FUNCTION(S))
            backtrace(S)
            return  #FOUND GOAL

        COUNT += 1
        if (COUNT % 32) == 0:
            #        if True:
            # print(".",end="")
            #            if (COUNT % 128*128)==0:
            if True:
                print("COUNT = " + str(COUNT))
                #print("len(OPEN)=" + str(len(OPEN))) #PriorityQ OPEN doesn't have len()
                print("len(CLOSED)=" + str(len(CLOSED)))

        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if not occurs_in(new_state,
                                 CLOSED):  #ignore already evaluated neighbors

                    #find tentative score of neighbor
                    tentative_g_score = G_SCORE[S] + 1

                    if new_state not in G_SCORE:  #Default INFINITY
                        BACKLINKS[
                            new_state] = S  #First known path to new_state
                    elif tentative_g_score >= G_SCORE[new_state]:
                        continue  #current path is not the best path to the neighbor
                    else:
                        BACKLINKS[
                            new_state] = S  #Found better path to new_State

                    G_SCORE[new_state] = tentative_g_score
                    F_SCORE[new_state] = G_SCORE[new_state] + h_score_fn(
                        new_state)

                    # discovered a new State
                    if not OPEN.__contains__(new_state):
                        OPEN.insert(new_state, F_SCORE[new_state])

                    # print(Problem.DESCRIBE_STATE(new_state))
            #print(OPEN)

    #Failure, if goal_test has not succeeded until now
    print("COULD NOT FIND GOAL")
    return