def driver():
    # raise NotImplemented
    puzzle_size = 8
    puzzle = NPuzzle(puzzle_size, force_state=[1, 3, 5, 4, 2, None, 6, 7, 8], g=BreadthFirst.g, h=BreadthFirst.h)
    (solution, nodesexpanded) = graph_search(puzzle)
    print("solution is " + str(solution))

    '''
Пример #2
0
def driver():

    p_size = dict()
    n_size = dict()
    t = dict()

    for method in SEARCH_METHODS:
        t[method] = list()
        n_size[method] = list()
        p_size[method] = list()
        
       

    for i in range(TRIAL):

        board_layout = TileBoard(BOARD_SIZE).state_tuple()

        for method in SEARCH_METHODS:

            p = NPuzzle(BOARD_SIZE, g=method.g,h=method.h, force_state=board_layout)

            start_time = time.perf_counter()
                                      
            path, nodes_explored = graph_search(p)
                        
            dur = time.perf_counter() - start_time
            
            n_size[method].append(nodes_explored)
            
            t[method].append(dur)
            
            p_size[method].append(len(path))
            
            print('Trial %d via %s - plan %d node %d in %d seconds' %((i+1), method.__name__, len(path), nodes_explored, dur))



    for method in SEARCH_METHODS:
        
        print('Plan Method %s Mean %f Std %f' %(method.__name__, mean(p_size[method]), stdev(p_size[method])))
        print('Nodes Method %s Mean %f Std %f' %(method.__name__, mean(n_size[method]), stdev(n_size[method])))
        print('Time Method %s Mean %f Std %f' %(method.__name__, mean(t[method]), stdev(t[method])))
Пример #3
0
def driver() :
    stepsList = []
    nodesList = []
    timeList = []
    
    i = 0
    trials = 1
    while i < trials:
        start = tic()
        puzzle = NPuzzle(8, g = Manhattan.g, h = Manhattan.h)
        (solution, nodesExpanded) = graph_search(puzzle, True, True)
    
        stepsList.append(solution.__len__())
        nodesList.append(nodesExpanded)
        timeList.append(tock(start))
        print("Trial ", i, " Complete")
        i += 1
    
    print("DFC")
    print("Mean Steps: ", mean(stepsList), " Std Dev Steps: ", stdev(stepsList))
    print("Mean Nodes Expanded: ", mean(nodesList), " Std Dev Nodes Expanded: ", stdev(nodesList))
    print("Mean Time: ", mean(timeList), " Std Dev Time: ", stdev(timeList))

    return
Пример #4
0
def driver():
    manTime = [] 
    manLength = []
    manNodes = []
    depTime = []
    depLength = []
    depNodes = []
    breadTime = []
    breadLength = []
    breadNodes = []
    
    for i in range(0,31):
        tb = TileBoard(8)
        #starting with manhattan
        manprobs = NPuzzle(8,tb.state_tuple(),g=Manhattan.g,h=Manhattan.h)
        curTime = tic() #current time
        manList = graph_search(manprobs) #CONSIDER OTHER PARAMETERS LATER
        manTime.append(tock(curTime))
        manLength.append(len(manList[0]))
        manNodes.append(manList[1])
        
        #depth_first search
        depprobs = NPuzzle(8,tb.state_tuple(),g=DepthFirst.g,h=DepthFirst.h)
        curTime = tic() #current time
        depList = graph_search(depprobs) #CONSIDER OTHER PARAMETERS LATER
        depTime.append(tock(curTime))
        depLength.append(len(depList[0]))
        depNodes.append(depList[1])
        
        #breadth_first search
        breadprobs = NPuzzle(8,tb.state_tuple(),g=BreadthFirst.g,h=BreadthFirst.h)
        curTime = tic() #current time
        breadList = graph_search(breadprobs) #CONSIDER OTHER PARAMETERS LATER
        breadTime.append(tock(curTime))
        breadLength.append(len(breadList[0]))
        breadNodes.append(breadList[1])
    #calculate mean and stdevs for each list generated at beginning
    
    #manhattan statistics
    meanmantime = mean(manTime)
    stdmantime = stdev(manTime,meanmantime)
    meanmanlength = mean(manLength)
    stdmanlength = stdev(manLength,meanmanlength)
    meanmannodes = mean(manNodes)
    stdmannodes = stdev(manNodes,meanmannodes)

    #depth-first statistics
    meandeptime = mean(depTime)
    stddeptime = stdev(depTime)
    meandeplength = mean(depLength)
    stddeplength = stdev(depLength)
    meandepnodes = mean(depNodes)
    stddepnodes = stdev(depNodes)
    
    #breadth-first statistics
    meanbreadtime = mean(breadTime)
    stdbreadtime = stdev(breadTime)
    meanbreadlength = mean(breadLength)
    stdbreadlength = stdev(breadLength)
    meanbreadnodes = mean(breadNodes)
    stdbreadnodes = stdev(breadNodes)
    
    print("Manhattan Statistics - Mean Time: ", meanmantime, "StDev Time: ", stdmantime)
    print("Manhattan Statistics - Mean Length: ", meanmanlength, "StDev Length: ", stdmanlength)
    print("Manhattan Statistics - Mean Nodes: ", meanmannodes, "StDev Nodes: ", stdmannodes)

    print("Depth-First Statistics - Mean Time: ", meandeptime, "StDev Time: ", stddeptime)
    print("Depth-First Statistics - Mean Length: ", meandeplength, "StDev Length: ", stddeplength)
    print("Depth-First Statistics - Mean Nodes: ", meandepnodes, "StDev Nodes: ", stddepnodes)
    
    print("Breadth-First Statistics - Mean Time: ", meanbreadtime, "StDev Time: ", stdbreadtime)
    print("Breadth-First Statistics - Mean Length: ", meanbreadlength, "StDev Length: ", stdbreadlength)
    print("Breadth-First Statistics - Mean Nodes: ", meanbreadnodes, "StDev Nodes: ", stdbreadnodes)    
Пример #5
0
def solve(puzzle):
    start_time = tic()
    (solved_path, number_of_nodes_explored) = graph_search(puzzle)
    elapsed_time = tock(start_time)
    return (solved_path, number_of_nodes_explored, elapsed_time)
Пример #6
0
def driver():
    timer = Timer()
    # result dictionary will contain the result for all strategies
    results = {
        'BFS': {
            'Total_steps': [],
            'Total_explored_nodes': [],
            'Time_in_seconds': []
        },
        'DFS': {
            'Total_steps': [],
            'Total_explored_nodes': [],
            'Time_in_seconds': []
        },
        'AS': {
            'Total_steps': [],
            'Total_explored_nodes': [],
            'Time_in_seconds': []
        }
    }

    # Strategies
    strategies = {'BFS': BreadthFirst, 'DFS': DepthFirst, 'AS': Manhattan}

    # Create a puzzle 31 times
    for t in range(31):

        # Create an 8-puzzle (3x3) and perform the search
        for i in range(3, 4):
            problem = NPuzzle(i * i - 1)
            print(f'\t<Problem number {t + 1}>')
            print('Init State')
            print(problem.initial)
            print('Goal States', problem.goals)
            print('___________________________________\n')

            # Test each strategies on the same puzzle:
            for key in strategies:
                # Assign the g and h method corresponding to the current strategie
                problem.g = strategies[key].g
                problem.h = strategies[key].h

                # Execute the search using the current strategie
                # Set verbose to True if we want to see each move
                moves, exploredNodes, time = graph_search(problem,
                                                          verbose=False)

                results[key]['Total_steps'].append(len(moves))
                results[key]['Total_explored_nodes'].append(exploredNodes)
                results[key]['Time_in_seconds'].append(time)

    # Print out the Mean and STDev for all strategies used
    print('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    print('~~~~~~~~~~~~~SUMMARY TABLE~~~~~~~~~~~~~~~~~\n')
    for strategie_key in results:
        items = results[strategie_key]
        print(f'* Result for strategie: | {strategie_key} | *\n')
        for item_key in items:
            print(f'- {item_key}: ')
            print(f'\t+ Mean: {mean(items[item_key])}')
            print(f'\t+ STDev: {stdev(items[item_key])}')
        print('___________________________________________')
    print(f'\nTotal time to run 31 trials: {timer.elapsed()}')
def driver():
    # Assign number of trials, size of tileboards, and set verbose / debug flags, and force_states
    ntrials = 31
    n = 8
    verbose, debug = False, True

    f_state = []

    # Create puzzle states for ntrials, dummy board to check if solvable
    for f in range(0, ntrials):
        dummy = TileBoard(n)
        done = False
        while not done:
            made = False
            # Create temporary state and check if solvable
            tmp_state = list(range(1, n + 1))
            tmp_state.append(None)
            random.shuffle(tmp_state)
            if dummy.solvable(tmp_state):
                made = done = True
            else:
                # Reshuffle temporary state if not solvable
                random.shuffle(tmp_state)
            if made:
                # If solvable, append to f_state list
                f_state.append(tmp_state)

    # Initialize empty arrays to hold stat values
    btime, dtime, atime = [], [], []
    bnodes, dnodes, anodes = [], [], []
    bsteps, dsteps, asteps = [], [], []
    """ Run ntrials: each loop runs a breadth search, 
        depth search, and A* search for each force_state"""
    for state in f_state:
        # Initialize timer before each search
        # Create puzzle with same initial state & costs specific to search type
        # Run graph search on created puzzle
        # Add stats to stat arrays

        bt = Timer()
        breadthpuzzle = NPuzzle(n,
                                force_state=state,
                                g=BreadthFirst.g,
                                h=BreadthFirst.h)
        bsearch = graph_search(breadthpuzzle, verbose, debug)
        bsteps.append(len(bsearch[0]))
        bnodes.append(bsearch[1])
        btime.append(bt.elapsed_s())

        dt = Timer()
        depthpuzzle = NPuzzle(n,
                              force_state=state,
                              g=DepthFirst.h,
                              h=DepthFirst.g)
        dsearch = graph_search(depthpuzzle, verbose, debug)
        dsteps.append(len(dsearch[0]))
        dnodes.append(dsearch[1])
        dtime.append(dt.elapsed_s())

        at = Timer()
        astarpuzzle = NPuzzle(n,
                              force_state=state,
                              g=Manhattan.g,
                              h=Manhattan.h)
        asearch = graph_search(astarpuzzle, verbose, debug)
        asteps.append(len(asearch[0]))
        anodes.append(asearch[1])
        atime.append(at.elapsed_s())

    # Merge each stat array into an array for each search
    bdata, ddata, adata = [], [], []
    """ Compile stats and create table """
    if ntrials > 1:
        # Find mean and standard deviation for each stat of each search
        bdata = [
            mean(bsteps),
            stdev(bsteps, mean(bsteps)),
            mean(bnodes),
            stdev(bnodes, mean(bnodes)),
            mean(btime),
            stdev(btime, mean(btime))
        ]

        ddata = [
            mean(dsteps),
            stdev(dsteps, mean(dsteps)),
            mean(dnodes),
            stdev(dnodes, mean(dnodes)),
            mean(dtime),
            stdev(dtime, mean(dtime))
        ]

        adata = [
            mean(asteps),
            stdev(asteps, mean(asteps)),
            mean(anodes),
            stdev(anodes, mean(anodes)),
            mean(atime),
            stdev(atime, mean(atime))
        ]

        # Combine all data into one list and round as necessary
        data = [bdata, ddata, adata]
        data = [[round(elem, 6) for elem in lis] for lis in data]

        # Create lists for table labels
        searches = ["Breadth Search", "Depth Search", "A* Search"]
        stats = [
            "Mean Steps", "Std Steps", "Mean Nodes", "Std Nodes", "Mean Time",
            "Std Time"
        ]

        # Create table using formatted strings and for loop
        i = 0
        row_format = ("{:>14}" * (len(stats) + 1))
        print(row_format.format("", *stats))
        for stat, row in zip(stats, data):
            print(row_format.format(searches[i], *row))
            i += 1
Пример #8
0
def driver() :
    lengthOfPath = dict() # number of steps to solution for each search type
    numOfNodes = dict() # number of nodes expanded, we can put lists inside of the dict indexes
    timeElapsedSec = dict() # time elapsed for each of the seach methods for each of the puzzles
    t = Timer() # time of entire run

    # initialize dictionaries with list for every seach method
    for search in searchType:
        lengthOfPath[search] = list()
        numOfNodes[search] = list()
        timeElapsedSec[search] = list()

    # PROCESSING SOLUTIONS FOR PUZZLES
    for i in range(1,numPuzzles+1):

        print("puzzle number",i)

        for search in searchType:

            # prints out the name of the search trategy used to solve the puzzle
            print("solving with", search.__name__)

            # create the puzzle
            npuzzle = NPuzzle(puzzleSize, g = search.g, h = search.h)

            # solving the npuzzle
            # graph_search will return 3 values, the path, nodes explored, and elapsed time in seconds
            path, nodes_explored, elapsedtime = graph_search(npuzzle, debug=False, verbose=False)

            print("puzzle solved in %dmin %dsec"
                % (int(elapsedtime/60), elapsedtime%60))

            # appending the lenth of the path to the list
            lengthOfPath[search].append(len(path))

            # appending number of nodes explored
            numOfNodes[search].append(nodes_explored)

            # appending the time it took to solve
            timeElapsedSec[search].append(elapsedtime)

    # SUMMARY PRINT OUT SECTION

    print("#####SUMMARY PRINT OUT#####\n")

    # print path length summary
    print("\t\tBreadthFirst\n"
            "path length\tmean %.2f, std %.2f\n"
            % (mean(lengthOfPath[BreadthFirst]), stdev(lengthOfPath[BreadthFirst]))+
            "num of nodes\tmean %.2f, std %.2f\n"
            % (mean(numOfNodes[BreadthFirst]), stdev(numOfNodes[BreadthFirst]))+
            "time elapsed\tmean %.2f, std %.2f\n"
            % (mean(timeElapsedSec[BreadthFirst]), stdev(timeElapsedSec[BreadthFirst])))
    
    print("\t\tDepthFirst\n"
            "path length\tmean %.2f, std %.2f\n"
            % (mean(lengthOfPath[DepthFirst]), stdev(lengthOfPath[DepthFirst]))+
            "num of nodes\tmean %.2f, std %.2f\n"
            % (mean(numOfNodes[DepthFirst]), stdev(numOfNodes[DepthFirst]))+
            "time elapsed\tmean %.2f, std %.2f\n"
            % (mean(timeElapsedSec[DepthFirst]), stdev(timeElapsedSec[DepthFirst])))
    
    print("\t\tA* - Manhattan\n"
            "path length\tmean %.2f, std %.2f\n"
            % (mean(lengthOfPath[Manhattan]), stdev(lengthOfPath[Manhattan]))+
            "num of nodes\tmean %.2f, std %.2f\n"
            % (mean(numOfNodes[Manhattan]), stdev(numOfNodes[Manhattan]))+
            "time elapsed\tmean %.2f, std %.2f\n"
            % (mean(timeElapsedSec[Manhattan]), stdev(timeElapsedSec[Manhattan])))
    
    print("\ntime elapsed to solve all puzzles %dmin %dsec" % (t.elapsed_s()/60, t.elapsed_s()%60))
Пример #9
0
def driver():
    print("============================= TileBoard Game ==============================")
    print("CS 550 Artificial Intelligence | Prof. Roch | Assignment 2 | kingofthenorth")
    print("======================== Going through searches... ========================")

    plan_size = dict()
    nodes_size = dict()
    time = dict()

    for method in SEARCH_METHODS:
        plan_size[method] = list()
        nodes_size[method] = list()
        time[method] = list()

    for i in range(TRIAL_SIZE):
        if INFO:
            print('Trial #%d commence...' % (i + 1))

        # Standard layout for the board
        board_layout = TileBoard(BOARD_SIZE).state_tuple()

        # Trying the methods
        for method in SEARCH_METHODS:
            if INFO:
                print('Solving puzzle via %s' % method.__name__)

            puzzle = NPuzzle(BOARD_SIZE, g=method.g,
                             h=method.h, force_state=board_layout)

            start_time = tic()
            path, nodes_explored = graph_search(
                puzzle, debug=DEBUG, verbose=VERBOSE)
            duration = tock(start_time)
            assert path is not None

            plan_size[method].append(len(path))
            nodes_size[method].append(nodes_explored)
            time[method].append(duration)

            if INFO:
                print('Solved puzzle via %s in %d seconds' %
                      (method.__name__, duration))

        print('Finished Trial #%d' % (i + 1))

    if INFO or DEBUG or VERBOSE:
        print("\n\n======================== Going through searches... ========================\n\n\n")

    header = ["Search / Result   ",
              "Plan Size (Mean/STDEV)",
              "Node Size (Mean/STDEV)",
              "Time (Mean/STDEV)"]
    rows = list()

    # Formatting
    rows.append(['-' * (len(header[i]) + 1) for i in range(len(header))])

    for method in SEARCH_METHODS:
        rows.append([' '.join(re.sub('(?!^)([A-Z][a-z]+)', r' \1', method.__name__).split()),
                     '{:.3f} / {:.3f}'.format(
                         mean(plan_size[method]), stdev(plan_size[method])),
                     '{:.3f} / {:.3f}'.format(
                         mean(nodes_size[method]), stdev(nodes_size[method])),
                     '{:.3f} / {:.3f}'.format(mean(time[method]), stdev(time[method]))])

    print_table(rows, header=header, sep="\t| ")
Пример #10
0
def driver() :
    bfsLengthList = []
    bfsNodesExpandedList = []
    bfsTimeList = []

    dfsLengthList = []
    dfsNodesExpandedList = []
    dfsTimeList = []

    manLengthList = []
    manNodesExpandedList = []
    manTimeList = []

    for i in range(2):      #change back to 31
        tempBoard = TileBoard(8)        #force_state=(1,2,3,4,5,6,7,8,None)

        #Breadth First Search
        bfs = NPuzzle(8,g=BreadthFirst.g,force_state=tempBoard.state_tuple())
        tempTimer = Timer()
        path,numNodes = graph_search(bfs, verbose=True)
        bfsTimeList.append(tempTimer.elapsed_s())
        bfsNodesExpandedList.append(numNodes)
        bfsLengthList.append(len(path))

        #Depth First Search
        dfs = NPuzzle(8,g=DepthFirst.g,force_state=tempBoard.state_tuple())
        tempTimer = Timer()
        path,numNodes = graph_search(dfs, verbose=True)
        dfsTimeList.append(tempTimer.elapsed_s())
        dfsNodesExpandedList.append(numNodes)
        dfsLengthList.append(len(path))

        #Manhattan Search
        manhattan = NPuzzle(8, h=Manhattan.h, force_state=tempBoard.state_tuple())
        tempTimer = Timer()
        path, numNodes = graph_search(manhattan, verbose=True)
        manTimeList.append(tempTimer.elapsed_s())
        manNodesExpandedList.append(numNodes)
        manLengthList.append(len(path))

    print("BFS Average Path Length:",mean(bfsLengthList))
    print("BFS Average Nodes Expanded:",mean(bfsNodesExpandedList))
    print("BFS Average Time Elapsed:",mean(bfsTimeList))

    print("DFS Average Path Length:", mean(dfsLengthList))
    print("DFS Average Nodes Expanded:",mean(dfsNodesExpandedList))
    print("DFS Average Time Elapsed:",mean(dfsTimeList))

    print("Manhattan Average Path Length:", mean(manLengthList))
    print("Manhattan Average Nodes Expanded:", mean(manNodesExpandedList))
    print("Manhattan Average Time Elapsed:", mean(manTimeList))

    print("BFS Standard Deviation Path Length:", stdev(bfsLengthList))
    print("BFS Standard Deviation Nodes Expanded:", stdev(bfsNodesExpandedList))
    print("BFS Standard Deviation Time Elapsed:", stdev(bfsTimeList))
  
    print("DFS Standard Deviation Path Length:", stdev(dfsLengthList))
    print("DFS Standard Deviation Nodes Expanded:", stdev(dfsNodesExpandedList))
    print("DFS Standard Deviation Time Elapsed:", stdev(dfsTimeList))

    print("Manhattan Standard Deviation Path Length:", stdev(manLengthList))
    print("Manhattan Standard Deviation Nodes Expanded:", stdev(manNodesExpandedList))
    print("Manhattan Standard Deviation Time Elapsed:", stdev(manTimeList))
Пример #11
0
import time

path_to_file = 'test_input_2.txt'

nodes = []
nodes.append(0)
with open(path_to_file) as input:
    for line in input:
        m = re.match(re.compile(r'(\d+) (-?\d+)'), line)
        if line != '\n':
            nodes.append(int(m.group(2)))
    input.close()

def tic():
    "Return current time representation"
    return time.time()

def tock(t):
    "Return time elapsed in sec since t where t is the output of tic()"
    return time.time() - t

start = tic()
test = HexGrid(nodes)
solution = graph_search(test)

output_file = open('output.txt', 'w+')
for node in reversed(solution[0]):
    output_file.write(str(node) + '\n')
output_file.write("MINIMAL-COST PATH COSTS: "+str(solution[1]) + '\n')
output_file.write(str(tock(start)))
Пример #12
0
def driver():

    #Define number of problems and get user input for search algorithm
    num_problems = 32
    num_steps = [[], [], []]
    num_nodes = [[], [], []]
    time = [[], [], []]

    #Begin timer and define problem state. Then begin BFS search
    for i in range(1, num_problems):
        np_BFS = NPuzzle(8, g=BreadthFirst.g, h=BreadthFirst.h)
        if (graph_search(np_BFS)):
            t = Timer()
            steps, nodes = graph_search(np_BFS)
            time[0].append(t.elapsed_s())
            num_steps[0].append(steps)
            num_nodes[0].append(nodes)
    #Display results
    print("\nBreadth First Search Results")
    print("Time(s) (AVG): ", mean(time[0]))
    print("Time(s) (STD): ", stdev(time[0]))
    print("Nodes expanded (AVG): ", mean(num_nodes[0]))
    print("Nodes expanded (STD): ", stdev(num_nodes[0]))
    print("Steps taken (AVG): ", mean(num_steps[0]))
    print("Steps taken (STD): ", stdev(num_steps[0]), "\n")

    #Begin timer and conduct DFS search and print results
    for i in range(1, num_problems):
        np_DFS = NPuzzle(8, g=DepthFirst.h, h=DepthFirst.g)
        if (graph_search(np_DFS)):
            t2 = Timer()
            steps, nodes = graph_search(np_DFS)
            time[1].append(t2.elapsed_s())
            num_steps[1].append(steps)
            num_nodes[1].append(nodes)
    #Display results
    print("\nDepth First Search Results for 31 Searches")
    print("Time(s) (AVG): ", mean(time[1]))
    print("Time(s) (STD): ", stdev(time[1]))
    print("Nodes expanded (AVG): ", mean(num_nodes[1]))
    print("Nodes expanded (STD): ", stdev(num_nodes[1]))
    print("Steps taken (AVG): ", mean(num_steps[1]))
    print("Steps taken (STD): ", stdev(num_steps[1]), "\n")

    #Begin timer and conduct A* search and print results
    for i in range(1, num_problems):
        np_A = NPuzzle(8, g=Manhattan.g, h=Manhattan.h)
        if (graph_search(np_A)):
            t3 = Timer()
            steps, nodes = graph_search(np_A)
            time[2].append(t3.elapsed_s())
            num_steps[2].append(steps)
            num_nodes[2].append(nodes)
    #Display results
    print("\nA* Search Results For 31 Searches")
    print("Time(s) (AVG): ", mean(time[2]))
    print("Time(s) (STD): ", stdev(time[2]))
    print("Nodes expanded (AVG): ", mean(num_nodes[2]))
    print("Nodes expanded (AVG): ", stdev(num_nodes[2]))
    print("Steps taken (AVG): ", mean(num_steps[2]))
    print("Steps taken (STD): ", stdev(num_steps[2]))
Пример #13
0
def driver():
    length_of_plan = dict()
    number_of_nodes = dict()
    elapsed_time = dict()

    for method in SOLUTION_METHODS:
        length_of_plan[method] = list()
        number_of_nodes[method] = list()
        elapsed_time[method] = list()

    for i in range(TRIAL_SIZE):
        if INFO:
            print('Starting Trial #%d' % (i + 1))

        # Standard Config
        board_layout = TileBoard(TRIAL_BOARD_SIZE).state_tuple()

        # Random Board - For testing
        # board_layout = TileBoard(TRIAL_BOARD_SIZE, force_state=[8, None, 6, 5, 4, 7, 2, 3, 1]).state_tuple()
        # board_layout = TileBoard(TRIAL_BOARD_SIZE, force_state=[7, 3, None, 5, 1, 2, 4, 8, 6]).state_tuple()

        # Solvable in 1 move
        # board_layout = TileBoard(TRIAL_BOARD_SIZE, force_state=[1, None, 3, 4, 2, 5, 6, 7, 8]).state_tuple()

        # Solvable in ~5 moves
        # board_layout = TileBoard(TRIAL_BOARD_SIZE, force_state=[4, 1, 2, None, 5, 3, 6, 7, 8]).state_tuple()
        # board_layout = TileBoard(TRIAL_BOARD_SIZE, force_state=[1, None, 3, 7, 2, 5, 4, 6, 8]).state_tuple()

        # Solvable in ~15 moves
        # board_layout = TileBoard(TRIAL_BOARD_SIZE, force_state=[5, 3, 7, None, 1, 2, 4, 6, 8]).state_tuple()

        for method in SOLUTION_METHODS:
            if INFO:
                print('Solving puzzle via %s' % method.__name__)

            puzzle = NPuzzle(TRIAL_BOARD_SIZE,
                             g=method.g,
                             h=method.h,
                             force_state=board_layout)

            start_time = tic()
            path, nodes_explored = graph_search(puzzle,
                                                debug=DEBUG,
                                                verbose=VERBOSE)
            duration = tock(start_time)
            assert path is not None

            length_of_plan[method].append(len(path))
            number_of_nodes[method].append(nodes_explored)
            elapsed_time[method].append(duration)

            if INFO:
                print('Solved puzzle via %s in %d seconds' %
                      (method.__name__, duration))

        print('Finished Trial #%d' % (i + 1))

    if INFO or DEBUG or VERBOSE:
        print("\n\n==================================================\n\n\n")

    header = [
        "Method / Result   ", "Length of Plan (Mean/STDEV)",
        "Number of Nodes (Mean/STDEV)", "Elapsed Time (Mean/STDEV)"
    ]
    rows = list()

    # Header Separator
    rows.append(['-' * (len(header[i]) + 1) for i in range(len(header))])

    # Table Values
    for method in SOLUTION_METHODS:
        rows.append([
            ' '.join(
                re.sub('(?!^)([A-Z][a-z]+)', r' \1', method.__name__).split()),
            '{:.3f} / {:.3f}'.format(mean(length_of_plan[method]),
                                     stdev(length_of_plan[method])),
            '{:.3f} / {:.3f}'.format(mean(number_of_nodes[method]),
                                     stdev(number_of_nodes[method])),
            '{:.3f} / {:.3f}'.format(mean(elapsed_time[method]),
                                     stdev(elapsed_time[method]))
        ])

    print_table(rows, header=header, sep="\t| ")
Пример #14
0
def driver():
    print(
        "-------------------------- TileBoard searching...-----------------------------------"
    )
    # declarations
    path_length = dict()
    num_nodes = dict()
    elapsed_sec = dict()
    elapsed_min = dict()

    for method in search_method:
        path_length[method] = list()
        num_nodes[method] = list()
        elapsed_sec[method] = list()
        elapsed_min[method] = list()

    for i in range(num_puzzle):
        print('\n###Puzzle %d###' % (i + 1))

        for method in search_method:
            if method.__name__ is 'Manhattan':
                name = 'A*'
            else:
                name = method.__name__
            print('Solving puzzle using %s' % name)

            # set the puzzle
            npuzzle = NPuzzle(board_size,
                              g=method.g,
                              h=method.h,
                              force_state=TileBoard(board_size).state_tuple())
            t = Timer()
            # (1,2,3,None,4,6,7,5,8) solve in 3 moves
            """--------------------One Path Demo using A---------------------------*  
            temp = False
            if method.__name__ is 'Manhattan':
                temp = True
            path, nodes_explored = graph_search(npuzzle, debug=False, verbose=temp)
            ----------------------------------------------------------------------"""
            path, nodes_explored = graph_search(npuzzle,
                                                debug=False,
                                                verbose=False)

            if method.__name__ is 'Manhattan':
                name = "A*"
            else:
                name = method.__name__
            print('Puzzle Solved in %d sec or  %d min' %
                  (t.elapsed_s(), t.elapsed_min()))

            assert path is not None
            path_length[method].append(len(path))
            num_nodes[method].append(nodes_explored)
            elapsed_sec[method].append(t.elapsed_s())
            elapsed_min[method].append(t.elapsed_min())

    # use pandas tabulate and print table pretty
    data = list()

    # round 2digit and formatting
    for method in search_method:
        if method.__name__ is 'Manhattan':
            name = 'A*'
        else:
            name = method.__name__
        # create list according to column names
        data.append([
            ' '.join(re.sub('(?!^)([A-Z][a-z]+)', r' \1', name).split()),
            '{:.2f} / {:.2f}'.format(mean(path_length[method]),
                                     stdev(path_length[method])),
            '{:.2f} / {:.2f}'.format(mean(num_nodes[method]),
                                     stdev(num_nodes[method])),
            '{:.2f} / {:.2f}'.format(mean(elapsed_sec[method]),
                                     stdev(elapsed_sec[method])),
            '{:.2f} / {:.2f}'.format(mean(elapsed_min[method]),
                                     stdev(elapsed_min[method]))
        ])

    df_data = pd.DataFrame(data)
    df_data.columns = [
        'Search Type', 'Path_Length (Mean/Stdev)',
        'Node_Explored (Mean/Stdev)', 'Time in Sec(Mean/Stdev)',
        'Time in Min(Mean/Stdev)'
    ]

    pd_tabulate = lambda df_data: tabulate(
        df_data, headers='keys', tablefmt='psql')
    print(pd_tabulate(df_data))