예제 #1
0
 def execute(self, grades, moduleDict, solutionDict):
     search = moduleDict['search']
     searchAgents = moduleDict['searchAgents']
     game_state = pacman.GameState()
     lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
     game_state.initialize(lay, 0)
     problem = searchAgents.CornersProblem(game_state)
     start_state = problem.getStartState()
     h0 = searchAgents.cornersHeuristic(start_state, problem)
     succs = problem.getSuccessors(start_state)
     # cornerConsistencyA
     for succ in succs:
         h1 = searchAgents.cornersHeuristic(succ[0], problem)
         if h0 - h1 > 1:
             grades.addMessage('FAIL: inconsistent heuristic')
             return False
     heuristic_cost = searchAgents.cornersHeuristic(start_state, problem)
     true_cost = float(solutionDict['cost'])
     # cornerNontrivial
     if heuristic_cost == 0:
         grades.addMessage('FAIL: must use non-trivial heuristic')
         return False
     # cornerAdmissible
     if heuristic_cost > true_cost:
         grades.addMessage('FAIL: Inadmissible heuristic')
         return False
     path = solutionDict['path'].split()
     states = followPath(path, problem)
     heuristics = []
     for state in states:
         heuristics.append(searchAgents.cornersHeuristic(state, problem))
     for i in range(0, len(heuristics) - 1):
         h0 = heuristics[i]
         h1 = heuristics[i + 1]
         # cornerConsistencyB
         if h0 - h1 > 1:
             grades.addMessage('FAIL: inconsistent heuristic')
             return False
         # cornerPosH
         if h0 < 0 or h1 < 0:
             grades.addMessage('FAIL: non-positive heuristic')
             return False
     # cornerGoalH
     if heuristics[len(heuristics) - 1] != 0:
         grades.addMessage('FAIL: heuristic non-zero at goal')
         return False
     grades.addMessage(
         'PASS: heuristic value less than true cost at start state')
     return True
    def execute(self, grades, module_dict, solution_dict):
        """Run student code.

        Overrides test_classes.TestCase.execute

        If an error message is returned, print error and return false.
        If a good solution is returned, print the solution and return true.
        Otherwise, print both the correct and student's solution and return
        false.
        """
        search = module_dict['search']
        search_agents = module_dict['search_agents']
        # total = 0
        true_cost = float(solution_dict['cost'])
        thresholds = list(map(int, solution_dict['thresholds'].split()))
        points_per_threshold = 1
        if 'points_per_threshold' in solution_dict:
            points_per_threshold = int(solution_dict['points_per_threshold'])
        game_state = pacman.GameState()
        lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
        game_state.initialize(lay, 0)
        problem = search_agents.CornersProblem(game_state)
        start_state = problem.get_start_state()
        if search_agents.corners_heuristic(start_state, problem) > true_cost:
            grades.add_message('FAIL: Inadmissible heuristic')
            return False
        path = search.a_star(problem, search_agents.corners_heuristic)
        print("path:", path)
        print("path length:", len(path))
        cost = problem.get_cost_of_actions(path)
        if cost > true_cost:
            grades.add_message('FAIL: Inconsistent heuristic')
            return False
        expanded = problem._expanded
        points = 0
        for threshold in thresholds:
            if expanded <= threshold:
                points += points_per_threshold
        grades.add_points(points)
        if points >= len(thresholds):
            grades.add_message('PASS: Heuristic resulted in expansion of ' +
                               '%d nodes' % expanded)
        else:
            grades.add_message('FAIL: Heuristic resulted in expansion of ' +
                               '%d nodes' % expanded)
        return True
    def execute(self, grades, moduleDict, solutionDict, result=[]):
        search = moduleDict['search']
        searchAgents = moduleDict['searchAgents']
        searchAgents_ta = moduleDict['searchAgents-TA']

        total = 0
        true_cost = float(solutionDict['cost'])
        thresholds = [int(x) for x in solutionDict['thresholds'].split()]
        game_state = pacman.GameState()
        lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
        game_state.initialize(lay, 0)
        problem = searchAgents.CornersProblem(game_state)
        problem_ta = searchAgents_ta.CornersProblem(game_state)

        start_state = problem.getStartState()
        if searchAgents.cornersHeuristic(start_state, problem) > true_cost:
            grades.addMessage('FAIL: Inadmissible heuristic')
            result.extend(
                ["FAIL: Inadmissible heuristic", False, None, tok - tik])
            return False
        tik = time.time()
        path = search.astar(problem, searchAgents.cornersHeuristic)
        tok = time.time()
        print("path:", path)
        print("path length:", len(path))
        cost = problem_ta.getCostOfActions(path)
        if cost > true_cost:
            grades.addMessage('FAIL: Inconsistent heuristic')
            result.extend(
                ["FAIL: Inconsistent heuristic", False, None, tok - tik])
            return False
        expanded = problem.get_expanded()
        # points = 0
        # for threshold in thresholds:
        #     if expanded <= threshold:
        #         points += 1
        # grades.addPoints(points)
        # if points >= len(thresholds):
        #     grades.addMessage('PASS: Heuristic resulted in expansion of %d nodes' % expanded)
        # else:
        #     grades.addMessage('FAIL: Heuristic resulted in expansion of %d nodes' % expanded)
        grades.addMessage('PASS: Heuristic resulted in expansion of %d nodes' %
                          expanded)
        result.extend(["PASS", True, expanded, tok - tik])
        return True
    def execute(self, grades, moduleDict, solutionDict):
        search = moduleDict['search']
        searchAgents = moduleDict['searchAgents']
        total = 0
        true_cost = float(solutionDict['cost'])
        thresholds = [int(x) for x in solutionDict['thresholds'].split()]
        #EXTRA, USED TO CONFIGURE DYNAMIC THRESHOLD VALUES
        thresholdPoints = [
            int(x) for x in solutionDict['thresholdPoints'].split()
        ]
        game_state = pacman.GameState()
        lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
        game_state.initialize(lay, 0)
        problem = searchAgents.CornersProblem(game_state)
        start_state = problem.getStartState()
        if searchAgents.cornersHeuristic(start_state, problem) > true_cost:
            grades.addMessage('FAIL: Inadmissible heuristic')
            return False
        path = search.astar(problem, searchAgents.cornersHeuristic)
        print("path:", path)
        print("path length:", len(path))
        cost = problem.getCostOfActions(path)
        if cost > true_cost:
            grades.addMessage('FAIL: Inconsistent heuristic')
            return False
        expanded = problem._expanded
        points = 0
        #Original
        #        for threshold in thresholds:
        #            if expanded <= threshold:
        #                points += 1
        #Extra
        for z in range(len(thresholds)):
            if expanded <= thresholds[z]:
                points += thresholdPoints[z]
#Extra Ends
        grades.addPoints(points)
        if points >= len(thresholds):
            grades.addMessage(
                'PASS: Heuristic resulted in expansion of %d nodes' % expanded)
        else:
            grades.addMessage(
                'FAIL: Heuristic resulted in expansion of %d nodes' % expanded)
        return True
예제 #5
0
    def writeSolution(self, moduleDict, filePath):
        search = moduleDict['search']
        searchAgents = moduleDict['searchAgents']
        # write comment
        handle = open(filePath, 'w')
        handle.write('# In order for a heuristic to be admissible, the value\n')
        handle.write('# of the heuristic must be less at each state than the\n')
        handle.write('# true cost of the optimal path from that state to a goal.\n')

        # solve problem and write solution
        lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
        start_state = pacman.GameState()
        start_state.initialize(lay, 0)
        problem = searchAgents.CornersProblem(start_state)
        solution = search.astar(problem, searchAgents.cornersHeuristic)
        handle.write('cost: "%d"\n' % len(solution))
        handle.write('path: """\n%s\n"""\n' % wrap_solution(solution))
        handle.close()
        return True
예제 #6
0
    def execute(self, grades, moduleDict, solutionDict):
        search = moduleDict['search']
        searchAgents = moduleDict['searchAgents']
        total = 0
        true_cost = float(solutionDict['cost'])
        thresholds = map(int, solutionDict['thresholds'].split())
        basePoints = int(solutionDict['basePoints'])
        game_state = pacman.GameState()
        lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
        game_state.initialize(lay, 0)
        problem = searchAgents.CornersProblem(game_state)
        # BEGIN SOLUTION NO PROMPT
        patchExpansionExploit(problem)
        # END SOLUTION NO PROMPT
        start_state = problem.getStartState()
        if searchAgents.cornersHeuristic(start_state, problem) > true_cost:
            grades.addMessage('FAIL: Inadmissible heuristic')
            return False
        path = search.astar(problem, searchAgents.cornersHeuristic)
        print "path:", path
        print "path length:", len(path)
        cost = problem.getCostOfActions(path)
        if cost > true_cost:
            grades.addMessage('FAIL: Inconsistent heuristic')
            return False
        expanded = problem._expanded
        # BEGIN SOLUTION NO PROMPT
        expanded = problem._secretKeyLol
        # END SOLUTION NO PROMPT

        grades.addPoints(basePoints)
        points = 0
        for threshold in thresholds:
            if expanded <= threshold:
                points += 3
        grades.addPoints(points)
        if points >= len(thresholds):
            grades.addMessage(
                'PASS: Heuristic resulted in expansion of %d nodes' % expanded)
        else:
            grades.addMessage(
                'FAIL: Heuristic resulted in expansion of %d nodes' % expanded)
        return True
예제 #7
0
    def getSolInfo(self, search, searchAgents):
        alg = getattr(search, self.alg)
        lay = layout.Layout([l.strip() for l in self.layout_text.split("\n")])
        start_state = pacman.GameState()
        start_state.initialize(lay, 0)

        problemClass = getattr(searchAgents, self.searchProblemClassName)
        problemOptions = {}
        if self.costFn != None:
            problemOptions["costFn"] = self.costFn
        problem = problemClass(start_state, **problemOptions)
        heuristic = (
            getattr(searchAgents, self.heuristicName)
            if self.heuristicName != None
            else None
        )

        if heuristic != None:
            solution = alg(problem, heuristic)
        else:
            solution = alg(problem)

        if type(solution) != type([]):
            return (
                None,
                None,
                "The result of %s must be a list. (Instead, it is %s)"
                % (self.alg, type(solution)),
            )

        from game import Directions

        dirs = Directions.LEFT.keys()
        if [el in dirs for el in solution].count(False) != 0:
            return (
                None,
                None,
                "Output of %s must be a list of actions from game.Directions"
                % self.alg,
            )

        expanded = problem._expanded
        return solution, expanded, None
예제 #8
0
 def writeSolution(self, moduleDict, filePath):
     search = moduleDict['search']
     searchAgents = moduleDict['searchAgents']
     handle = open(filePath, 'w')
     handle.write(
         '# This solution file specifies the length of the optimal path\n')
     handle.write(
         '# as well as the thresholds on number of nodes expanded to be\n')
     handle.write('# used in scoring.\n')
     lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
     start_state = pacman.GameState()
     start_state.initialize(lay, 0)
     problem = searchAgents.CornersProblem(start_state)
     solution = search.astar(problem, searchAgents.cornersHeuristic)
     handle.write('cost: "%d"\n' % len(solution))
     handle.write('path: """\n%s\n"""\n' % wrap_solution(solution))
     handle.write('thresholds: "2000 1600 1200"\n')
     handle.close()
     return True
 def execute(self, grades, moduleDict, solutionDict):
     search = moduleDict['search']
     searchAgents = moduleDict['searchAgents']
     total = 0
     true_cost = float(solutionDict['cost'])
     thresholds = [int(x) for x in solutionDict['thresholds'].split()]
     game_state = pacman.GameState()
     lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
     game_state.initialize(lay, 0)
     problem = searchAgents.CornersProblem(game_state)
     start_state = problem.getStartState()
     if searchAgents.cornersHeuristic(start_state, problem) > true_cost:
         grades.addMessage('FAIL: Inadmissible heuristic')
         return False
     path = search.astar(problem, searchAgents.cornersHeuristic)
     print("path:", path)
     print("path length:", len(path))
     cost = problem.getCostOfActions(path)
     if cost > true_cost:
         grades.addMessage(
             'FAIL: non-optimal solution returned (inadmissible heuristic, cycle checking error, or other search error'
         )
         return False
     expanded = problem._expanded
     points = 0
     for threshold in thresholds:
         if expanded <= threshold:
             points += 1
     grades.addPoints(points)
     if points >= len(thresholds):
         grades.addMessage(
             'PASS: Heuristic resulted in expansion of %d nodes' % expanded)
     else:
         if (points > 0):
             grades.addMessage(
                 'REDUCED MARK: Heuristic resulted in expansion of %d nodes'
                 % expanded)
         if (points == 0):
             grades.addMessage(
                 'FAIL: Heuristic resulted in expansion of %d nodes more than maximum allowed'
                 % expanded)
     return True
예제 #10
0
    def getSolInfo(self, search, searchAgents):
        alg = getattr(search, self.alg)
        lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
        start_state = pacman.GameState()
        start_state.initialize(lay, 0)

        problemClass = getattr(searchAgents, self.searchProblemClassName)
        problemOptions = {}
        if self.costFn != None:
            problemOptions['costFn'] = self.costFn
        problem = problemClass(start_state, **problemOptions)
        # BEGIN SOLUTION NO PROMPT
        patchExpansionExploit(problem)
        # END SOLUTION NO PROMPT
        heuristic = getattr(
            searchAgents,
            self.heuristicName) if self.heuristicName != None else None

        if heuristic != None:
            solution = alg(problem, heuristic)
        else:
            solution = alg(problem)

        if type(solution) != type([]):
            return None, None, 'The result of %s must be a list. (Instead, it is %s)' % (
                self.alg, type(solution))

        from game import Directions
        dirs = Directions.LEFT.keys()
        if [el in dirs for el in solution].count(False) != 0:
            return None, None, 'Output of %s must be a list of actions from game.Directions' % self.alg

        expanded = problem._expanded
        # BEGIN SOLUTION NO PROMPT
        expanded = problem._secretKeyLol
        # END SOLUTION NO PROMPT
        return solution, expanded, None
예제 #11
0
 def execute(self, grades, moduleDict, solutionDict):
     search = moduleDict["search"]
     searchAgents = moduleDict["searchAgents"]
     total = 0
     true_cost = float(solutionDict["cost"])
     thresholds = [int(x) for x in solutionDict["thresholds"].split()]
     game_state = pacman.GameState()
     lay = layout.Layout([l.strip() for l in self.layout_text.split("\n")])
     game_state.initialize(lay, 0)
     problem = searchAgents.CornersProblem(game_state)
     start_state = problem.getStartState()
     if searchAgents.cornersHeuristic(start_state, problem) > true_cost:
         grades.addMessage("FAIL: Inadmissible heuristic")
         return False
     path = search.astar(problem, searchAgents.cornersHeuristic)
     print("path:", path)
     print("path length:", len(path))
     cost = problem.getCostOfActions(path)
     if cost > true_cost:
         grades.addMessage("FAIL: Inconsistent heuristic")
         return False
     expanded = problem._expanded
     points = 0
     for threshold in thresholds:
         if expanded <= threshold:
             points += 1
     grades.addPoints(points)
     if points >= len(thresholds):
         grades.addMessage(
             "PASS: Heuristic resulted in expansion of %d nodes" % expanded
         )
     else:
         grades.addMessage(
             "FAIL: Heuristic resulted in expansion of %d nodes" % expanded
         )
     return True
    def get_solution_info(self, search, search_agents):
        """Return solution info: (solution, expanded states, error message)."""
        alg = getattr(search, self.alg)
        lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
        start_state = pacman.GameState()
        start_state.initialize(lay, 0)

        problem_class = getattr(search_agents, self.search_problem_class_name)
        problem_options = {}
        if self.cost_fn is not None:
            problem_options['cost_fn'] = self.cost_fn
        problem = problem_class(start_state, **problem_options)
        if self.heuristic_name is not None:
            heuristic = getattr(search_agents, self.heuristic_name)
        else:
            heuristic = None

        if heuristic is not None:
            solution = alg(problem, heuristic)
        else:
            solution = alg(problem)

        if not isinstance(solution, list):
            return (None, None,
                    'The result of %s must be a list. (Instead, it is %s)' %
                    (self.alg, type(solution)))

        from game import Directions
        dirs = list(Directions.LEFT.keys())
        if [el in dirs for el in solution].count(False) != 0:
            return (None, None,
                    ('Output of %s must be a list of actions ' % self.alg) +
                    'from game.Directions')

        expanded = problem._expanded
        return solution, expanded, None
예제 #13
0
 def solution(self, searchAgents):
     lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')])
     gameState = pacman.GameState()
     gameState.initialize(lay, 0)
     path = searchAgents.ClosestDotSearchAgent().findPathToClosestDot(gameState)
     return path
예제 #14
0
def getStartState(layoutName):
    s = pacman.GameState()
    lay1 = layout.getLayout(layoutName, 3)
    s.initialize(lay1, 0)
    return s