예제 #1
0
    def __init__(self, game, ai_information):
        self.game = game

        # Capture AI settings that the user specified
        search_type = ai_information[0]
        search_strategy = ai_information[1]

        # Set the strategy to use to search with
        if search_strategy == "bfs":
            search_strategy = BFS()
        elif search_strategy == "dfs":
            search_strategy = DFS()
        elif search_strategy == "astar":
            search_strategy = AStar(ai_information[2])
        elif search_strategy == "idastar":
            self.search_strategy = IDAStar(game.board, ai_information[2])
        else:
            raise Exception('Invalid search stategy')

        if search_strategy == "idastar":
            pass
        elif (search_type == "tree-search"):
            self.search_strategy = TreeSearch(game.board, search_strategy)
        elif (search_type == "graph-search"):
            self.search_strategy = GraphSearch(game.board, search_strategy)
        else:
            raise Exception('Invalid search type')
예제 #2
0
파일: geography.py 프로젝트: pawlactb/CS451
def main():
    test_case_1 = ["CDE", "CFG", "EHE", "EIJ", "GHK", "GLC"]
    test_case_2 = ["CDE", "CFG", "EHI", "GJC", "GKG"]

    root_node_1 = geography_node(test_case_1, words_added=["ABC"], name="root")

    print("BFS of Test Case 1:")
    print("Result of BFS on Test Case 1: %s, nodes visited: %d\n" %
          (BFS(root_node_1, node_count_max=128)))
    print("DFS of Test Case 1:")
    print("Result of DFS on Test Case 1: %s, nodes visited: %d\n" %
          (DFS(root_node_1, node_count_max=128)))

    root_node_2 = geography_node(test_case_2, words_added=["ABC"], name="root")

    print("BFS of Test Case 2:")
    print("Result of BFS on Test Case 2: %s, nodes visited: %d\n" %
          (BFS(root_node_2, node_count_max=128)))
    print("DFS of Test Case 2:")
    print("Result of DFS on Test Case 2: %s, nodes visited: %d\n" %
          (DFS(root_node_2, node_count_max=128)))
예제 #3
0
    def get_search(self):
        print "================================"
        print "Choose a Search Method:"
        print "================================"
        print "1. Depth First Search"
        print "2. Breadth First Search"
        print "3. A* Heuristic Search"

        search_input = int(raw_input("Enter search choice: =>  "))

        if search_input is -1:
            return
        elif search_input is 1:
            self.search = DFS()
        elif search_input is 2:
            self.search = BFS()
        elif search_input is 3:
            self.search = AS()
예제 #4
0
import os, sys
sys.path.append('search.py')
sys.path.append('heuristics.py')
from search import DFS, AStar, BestFirst
import heuristics as h
import numpy as np

if __name__ == '__main__':

	puzzle = np.array([int(val) for val in sys.argv[1:13]])

	if(len(puzzle) != 12):
		print('INVALID PUZZLE - LENGTH MUST BE 12')
		sys.exit()

	bfs = DFS(h.h1, max_depth=int(sys.argv[13]) if len(sys.argv) >= 13 else None,
			  iter_deep=int(sys.argv[14]) if len(sys.argv) >= 14 else None,
			  outfile='Data/Results/puzzleDFS.txt')
	bfs.traversal(puzzle, verbose=0)

	for heur_str, func in zip(['h1', 'h2'], [h.h1, h.h2]):

		bf = BestFirst(outfile='Data/Results/puzzleBFS-%s.txt' % heur_str)
		bf.traversal(puzzle, func, verbose=0)

		aS = AStar(outfile='Data/Results/puzzleAs-%s.txt' % heur_str)
		aS.traversal(puzzle, func, verbose=0)
예제 #5
0
        initState = State(initState)
        puzzle.setInitialState(initState)
        puzzleValued.setInitialState(initState)

        start = timeit.default_timer()
        BFS(puzzle, puzzle.initialState)
        end = timeit.default_timer()
        sumBFS += end - start

        start = timeit.default_timer()
        UCS(puzzleValued, puzzleValued.initialState)
        end = timeit.default_timer()
        sumUCS += end - start

        start = timeit.default_timer()
        DFS(puzzle, puzzle.initialState)
        end = timeit.default_timer()
        sumDFS += end - start

        start = timeit.default_timer()
        DLS(puzzle, puzzle.initialState, DEPTHLIMIT)
        end = timeit.default_timer()
        sumDLS += end - start

        start = timeit.default_timer()
        IDS(puzzle, puzzle.initialState)
        end = timeit.default_timer()
        sumIDS += end - start

        start = timeit.default_timer()
        A_star(puzzleValued, puzzleValued.initialState, heuristicPuzzle)
예제 #6
0
def main():
    """Main method that is run.

    Main method that takes command line arguments and performs given
    operation/s.
    
    """
    from argparse import ArgumentParser
    from data_loader import get_state_space, get_heuristic
    from search import BFS, UCS, DFS, lDFS, IDS, GBFS, HCS, AStar
    from heuristic_check import is_optimistic, is_consistent
    from puzzle_heuristic import manhattan_distance

    parser = ArgumentParser(
        'run specified search algorithm on a given state space')
    parser.add_argument('ss', type=str, help='path to a state space to use')
    parser.add_argument(
        '-a',
        '--algorithm',
        type=str,
        choices=['bfs', 'ucs', 'dfs', 'ldfs', 'ids', 'gbfs', 'hcs', 'astar'],
        help='state space search algoritm to use')
    parser.add_argument('-d',
                        '--depth',
                        type=int,
                        help='maximum depth for the limited DFS')
    parser.add_argument('-e',
                        '--heuristic',
                        type=str,
                        help='heuristic to use: [path, \'l1\']')
    parser.add_argument('-c',
                        '--check',
                        action='store_true',
                        help="run checks on heuristic")

    args = parser.parse_args()

    s0, transitions, goal = get_state_space(args.ss)

    heuristic = None
    if args.heuristic:
        if args.heuristic == 'l1':
            heuristic = manhattan_distance(goal)
        else:
            heuristic = get_heuristic(args.heuristic)

    if args.algorithm:
        if args.algorithm == 'bfs':
            BFS(s0, transitions, goal)
        elif args.algorithm == 'ucs':
            UCS(s0, transitions, goal)
        elif args.algorithm == 'dfs':
            DFS(s0, transitions, goal)
        elif args.algorithm == 'ldfs':
            if args.depth:
                lDFS(s0, transitions, goal, args.depth)
            else:
                print('Maximum depth not provided.')
        elif args.algorithm == 'ids':
            IDS(s0, transitions, goal)
        elif heuristic:
            if args.algorithm == 'gbfs':
                GBFS(s0, transitions, goal, heuristic)
            elif args.algorithm == 'hcs':
                HCS(s0, transitions, heuristic)
            elif args.algorithm == 'astar':
                AStar(s0, transitions, goal, heuristic)
            else:
                print('Invalid algorithm.')
        else:
            print('No heuristic provided.')

    if args.check:
        if heuristic:
            print('Checking heuristic')
            is_optimistic(heuristic, transitions, goal)
            is_consistent(heuristic, transitions)
        else:
            print('No heuristic provided.')
예제 #7
0
def dfs(ex):
    return search(ex, DFS(ex.add_waypoints, ex.routes_completed))
예제 #8
0
def heuristicGraph(state):
    if state == 0: return 5
    if state == 1: return 4
    if state == 2: return 4
    if state == 3: return 2
    if state == 4: return 2
    if state == 5: return 0

graph = SimpleGraph()
graphValued = SimpleValuedGraph()

print('---------Graph----------')

print('BFS:', BFS(graph, 0))
print('DFS:', DFS(graph, 0))
print('IDS:', IDS(graph, 0))
print('DLS:', DLS(graph, 0, 3))

print('UCS:', UCS(graphValued, 0))

print('Astar:', A_star(graphValued, 0, heuristicGraph))

#MCTS(graphValued,0,100)



def heuristicPuzzle(state):
    heuristic = 0
    goalState = [1,2,3,4,5,6,7,8,0]
    for x in list(range(0,3)):
예제 #9
0
                #Not the end of the txt
                if x[j] is not "\n":
                    #Fill the board map
                    if x[j] == "X":
                        board[(i, j)] = x[j]
                        goalsPos[(i, j)] = x[j]
                        numGoals += 1
                        j += 1
                    else:
                        board[(i, j)] = x[j]
                        j += 1
                    #Next character
                else:
                    j += 1
        #Not the end of the txt
        else:
            if x is not "\n" and boxFlg == False:
                player.append(int(x[0]))
                player.append(int(x[2]))
                boxFlg = True
            elif x is not "\n" and boxFlg == True:
                boxesPos.append([int(x[0]), int(x[2])])
        #next line
        i += 1


read_level(sys.argv[1])

print(DFS(board, player, goalsPos, boxesPos))
print(BFS(board, player, goalsPos, boxesPos))
print(IDFS(board, player, goalsPos, boxesPos))
예제 #10
0
sys.path.append('search.py')
from search import DFS, BestFirst, AStar
sys.path.append('heuristics.py')
import heuristics as h

if __name__ == '__main__':

    if (True):

        states = np.load('Data/states_bfs.npy')
        diffs = np.load('Data/diffs_bfs.npy')
        max_searches = 10000000

        for i, state in enumerate(states):
            ## BFS ##
            dfs = DFS(max_searches=max_searches, iter_deep=2, max_depth=3)
            dfs.traversal(state, func=None, verbose=0)
            df = pd.DataFrame(dfs.iter_deep_stats,
                              columns=['NumNodes', 'Depth', 'Searches'])
            df['Time'] = [dfs.overall_time] * len(df)
            df['Searches'] = [dfs.searches] * len(df)
            df['Difficulty'] = [diffs[i % len(diffs)]] * len(df)
            df['SolutionLength'] = [dfs.solution_path_length] * len(df)
            df.to_pickle('Data/Stats/bfs/state_%d.pkl' % i)
            ##
    else:

        states = np.load('Data/states.npy')
        diffs = np.load('Data/diffs.npy')
        max_searches = 15000