Exemplo n.º 1
0
def UCS(initial_state):
    '''Uniform Cost Search. This is the actual algorithm.'''
    global g, COUNT, BACKLINKS, MAX_OPEN_LENGTH, CLOSED, TOTAL_COST
    CLOSED = []
    BACKLINKS[initial_state] = None
    # The "Step" comments below help relate UCS's implementation to
    # those of Depth-First Search and Breadth-First Search.

    # STEP 1a. Put the start state on a priority queue called OPEN
    OPEN = PriorityQueue()
    OPEN.insert(initial_state, 0)
    # STEP 1b. Assign g=0 to the start state.
    g[initial_state] = 0.0
    cost_so_far = g[initial_state]

    # STEP 2. If OPEN is empty, output “DONE” and stop.
    #   while False: # ***STUDENTS CHANGE THIS CONDITION***
    while OPEN != []:
        # LEAVE THE FOLLOWING CODE IN PLACE TO INSTRUMENT AND/OR DEBUG YOUR IMPLEMENTATION
        if VERBOSE: report(OPEN, CLOSED, COUNT)
        if len(OPEN) > MAX_OPEN_LENGTH: MAX_OPEN_LENGTH = len(OPEN)

        # STEP 3. Select the state on OPEN having lowest priority value and call it S.
        #         Delete S from OPEN.
        #         Put S on CLOSED.
        #         If S is a goal state, output its description
        (S, P) = OPEN.delete_min()
        cost_so_far += P
        g[S] = cost_so_far
        # print(f"currently at {S.name} ")
        # print(f"cost from {initial_state.name} to {S.name} = {cost_so_far}")
        # print("In Step 3, returned from OPEN.delete_min with results (S,P)= \n", (str(S), P))

        # print("BACKLINKS = ")
        # for state in BACKLINKS.keys():
        #   print("parent = " + str(BACKLINKS.get(state)) + ", child = " + str(state))

        CLOSED.append(S)

        if Problem.GOAL_TEST(S):
            print("\n" + Problem.GOAL_MESSAGE_FUNCTION(S) + "\n")

            # handling backtracing
            SOLUTION_PATH = [str(s)
                             for s in backtrace(S)]  # should return a list
            print(f"Solution path = {SOLUTION_PATH}")
            print('Length of solution path found: ' +
                  str(len(SOLUTION_PATH) - 1) + ' edges')

            # handling total cost
            TOTAL_COST = g[S]
            print("TOTAL_COST = " + str(TOTAL_COST))

            return
        COUNT += 1
        print("EXPANDING = ", S.name)

        # STEP 4. Generate each successor of S
        #         and if it is already on CLOSED, delete the new instance.
        successors = []
        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                priority = cost_so_far + new_state.edge_distance(S)

                # if successor is not on CLOSED and OPEN, add to successors
                if not (new_state in CLOSED) and not (new_state in OPEN):
                    successors.append((new_state, priority))
                    BACKLINKS[new_state] = S
                else:
                    if new_state in OPEN:
                        if OPEN[new_state] > priority:
                            OPEN.__delitem__(new_state)
                            OPEN.insert(new_state, priority)
                            # print(f"PREVIOUS BACKLINK FOR {new_state} = {BACKLINKS[new_state].name}")
                            BACKLINKS[new_state] = S
                            # print(f"UPDATING BACKLINK FOR {new_state} = {BACKLINKS[new_state].name}")
                            # print(f"UPDATING PRIORITY FOR {new_state} = {OPEN[new_state]}")
                    elif new_state in CLOSED:
                        # If sj occurs on CLOSED, and its new distance is smaller than its old distance,
                        # then it is taken off of CLOSED, put back on OPEN, but with the new, smaller distance.
                        for item in CLOSED:
                            if item == new_state:
                                old_distance = g[item]
                                if old_distance > priority:
                                    CLOSED.remove(item)
                                    # print(f"STATE {new_state} IS ON CLOSED.")
                                    # print(f"OLD DISTANCE = {old_distance} vs NEW DISTANCE = {new_distance}")
                                    # print(f"CURRENT CLOSED = {str(CLOSED)}")
                                    OPEN.insert(new_state, priority)
                                    BACKLINKS[new_state] = S

        for (s, p) in successors:
            OPEN.insert(s, p)

        print_state_queue("OPEN", OPEN)
        # print("CLOSED: [ ", end="")
        # for state in CLOSED:
        #     print(state.name, end=" ")
        # print("]")
        cost_so_far -= P  # reset cost_so_far to current shortest path
    # STEP 6. Go to Step 2.
    return None  # No more states on OPEN, and no goal reached.
Exemplo n.º 2
0
def AStar(initial_state):
  '''AStar Search. This is the actual algorithm.'''
  global g, COUNT, BACKLINKS, MAX_OPEN_LENGTH, CLOSED, TOTAL_COST
##CLOSED = []
  CLOSED = My_Priority_Queue()
  BACKLINKS[initial_state] = None
  # The "Step" comments below help relate AStar's implementation to
  # those of Depth-First Search and Breadth-First Search.

# STEP 1a. Put the start state on a priority queue called OPEN
  OPEN = My_Priority_Queue()
  OPEN.insert(initial_state, 0)
# STEP 1b. Assign g=0 to the start state.
  g[initial_state]=0.0

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

# STEP 3. Select the state on OPEN having lowest priority value and call it S.
#         Delete S from OPEN.
#         Put S on CLOSED.
#         If S is a goal state, output its description
    (S,P) = OPEN.delete_min()
    #print("In Step 3, returned from OPEN.delete_min with results (S,P)= ", (str(S), P))
#####CLOSED.append(S)
    #print("current S =" + str(S))


    #if(CLOSED.__contains__(S)):
    #  CLOSED.__delitem__(S)
    CLOSED.insert(S,P)
    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')
      TOTAL_COST = g[S]
      print('Total cost of solution path found: '+str(TOTAL_COST))
      return path
    COUNT += 1

# STEP 4. Generate each successors of S and delete 
#         if it is already on CLOSED, delete the new instance.
    gs = g[S] # Save the cost of getting to S in a variable.

    for op in Problem.OPERATORS:
      if op.precond(S):
        new_state = op.state_transf(S)
        edge_cost = S.edge_distance(new_state)
        new_gs = gs + edge_cost #dist of s + sucessor
        new_hs = h(new_state) #heuristic vallue of sucessor
        new_fs = new_gs + new_hs #priortiy value

        if (new_state in CLOSED):
          prev_new_state_fs = CLOSED[new_state] #return the P of state in CLOSED list
          # new state has lower cost
          if (new_fs < prev_new_state_fs):
            CLOSED.__delitem__(new_state)
            OPEN.insert(new_state, new_fs)
          # new state has greater cost so delete
          else:
            del new_state
            continue

        # If new_state already exists on OPEN:
        #   If its new priority is less than its old priority,
        #     update its priority on OPEN, and set its BACKLINK to S.
        #   Else: forget out this new state object... delete it.

        elif (new_state in OPEN):
          P = OPEN[new_state] #returns priority
          # new state has lower cost
          if (new_fs < P):
            #print("New priority value is lower, so del older one")
            OPEN.__delitem__(new_state)
            OPEN.insert(new_state, new_fs)
          # new state has greater cost
          else:
            #print("Older one is better, so del new_state")
            del new_state
            continue
        
            #print("new_state was not on OPEN at all, so just put it on.")
        else:
          OPEN.insert(new_state, new_fs)
          
        BACKLINKS[new_state] = S
        g[new_state] = new_gs

    #print_state_queue("OPEN", OPEN)
    #print_state_queue("CLOSED", CLOSED)
    #print("\n")
  # STEP 6. Go to Step 2.
  return None  # No more states on OPEN, and no goal reached.
Exemplo n.º 3
0
def UCS(initial_state):
    '''Uniform Cost Search. This is the actual algorithm.'''
    global g, COUNT, BACKLINKS, MAX_OPEN_LENGTH, CLOSED, TOTAL_COST
    CLOSED = []
    BACKLINKS[initial_state] = None
    # The "Step" comments below help relate UCS's implementation to
    # those of Depth-First Search and Breadth-First Search.

    # STEP 1a. Put the start state on a priority queue called OPEN
    OPEN = My_Priority_Queue()
    OPEN.insert(initial_state, 0)
    # STEP 1b. Assign g=0 to the start state.
    g[initial_state] = 0.0

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

        # STEP 3. Select the state on OPEN having lowest priority value and call it S.
        #         Delete S from OPEN.
        #         Put S on CLOSED.
        #         If S is a goal state, output its description
        (S, P) = OPEN.delete_min()
        # print("In Step 3, returned from OPEN.delete_min with results (S,P)= ", (str(S), P))
        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')
            TOTAL_COST = g[S]
            print('Total cost of solution path found: ' + str(TOTAL_COST))
            return path
        COUNT += 1

        # STEP 4. Generate each successors of S and delete
        #         and if it is already on CLOSED, delete the new instance.
        gs = g[S]  # Save the cost of getting to S in a variable.
        for op in Problem.OPERATORS:
            if op.precond(S):
                new_state = op.state_transf(S)
                if (new_state in CLOSED):
                    # print("Already have this state, in CLOSED. del ...")
                    del new_state
                    continue
                edge_cost = S.edge_distance(new_state)
                new_g = gs + edge_cost

                # If new_state already exists on OPEN:
                #   If its new priority is less than its old priority,
                #     update its priority on OPEN, and set its BACKLINK to S.
                #   Else: forget out this new state object... delete it.

                if new_state in OPEN:
                    # print("new_state is in OPEN already, so...")
                    P = OPEN[new_state]
                    if new_g < P:
                        # print("New priority value is lower, so del older one")
                        del OPEN[new_state]
                        OPEN.insert(new_state, new_g)
                    else:
                        # print("Older one is better, so del new_state")
                        del new_state
                        continue
                else:
                    # print("new_state was not on OPEN at all, so just put it on.")
                    OPEN.insert(new_state, new_g)
                BACKLINKS[new_state] = S
                g[new_state] = new_g

        # print_state_queue("OPEN", OPEN)
    # STEP 6. Go to Step 2.
    return None  # No more states on OPEN, and no goal reached.
Exemplo n.º 4
0
def UCS(initial_state):
    '''Uniform Cost Search. This is the actual algorithm.'''
    global g, COUNT, BACKLINKS, MAX_OPEN_LENGTH, CLOSED, TOTAL_COST
    CLOSED = []
    BACKLINKS[initial_state] = None
    # The "Step" comments below help relate UCS's implementation to
    # those of Depth-First Search and Breadth-First Search.

    # STEP 1a. Put the start state on a priority queue called OPEN
    OPEN = My_Priority_Queue()
    OPEN.insert(initial_state, 0)
    # STEP 1b. Assign g=0 to the start state.
    g[initial_state] = 0.0

    # STEP 2. If OPEN is empty, output “DONE” and stop.
    while OPEN != []:  # ***STUDENTS CHANGE THIS CONDITION***
        # LEAVE THE FOLLOWING CODE IN PLACE TO INSTRUMENT AND/OR DEBUG YOUR IMPLEMENTATION

        if VERBOSE: report(OPEN, CLOSED, COUNT)
        if len(OPEN) > MAX_OPEN_LENGTH: MAX_OPEN_LENGTH = len(OPEN)

        # STEP 3. Select the state on OPEN having lowest priority value and call it S.
        #         Delete S from OPEN.
        #         Put S on CLOSED.
        #         If S is a goal state, output its description
        (S, P) = OPEN.delete_min()
        #print("In Step 3, returned from OPEN.delete_min with results (S,P)= ", (str(S), P))
        distance = P
        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')
            print('The distance between start state and destination is:',
                  str(distance))
            return  # ***STUDENTS CHANGE THE BODY OF THIS IF.***
            #HANDLE THE BACKTRACING, RECORDING THE SOLUTION AND TOTAL COST,
            # AND RETURN THE SOLUTION PATH, TOO.
        COUNT += 1

        # STEP 4. Generate each successor of S
        #         and if it is already on CLOSED, delete the new instance.
        i = 0
        while True:  #find out the # of neighbors(i) for S
            if not S.ith_neighbor_exists(i):
                for j in range(i):
                    ne = S.move(j)  #get neighbor name
                    P = S.edge_distance(ne)  #get distance to neighbor

                    if ne not in CLOSED and ne not in OPEN:  #make sure neighbor not in CLOSED
                        BACKLINKS[ne] = S
                        g[ne] = g[S] + P
                        OPEN.insert(ne, g[ne])
                break
            i += 1
    #find links of s, and add them to open.
    #add backtrace
    # ***STUDENTS IMPLEMENT THE GENERATION AND HANDLING OF SUCCESSORS HERE,
    # USING THE GIVEN PRIORITY QUEUE FOR THE OPEN LIST, AND
    # DETERMINING THE SHORTEST DISTANCE KNOWN SO FAR FROM THE INITIAL STATE TO
    # EACH SUCCESSOR.***

    # STEP 6. Go to Step 2.
    return None  # No more states on OPEN, and no goal reached.