Loading...

Introduction to Artificial Intelligence (Computer Science ,Python)

Open Posted By: ahmad8858 Date: 19/02/2021 Graduate Case Study Writing

This should be worked using Python.  The code will be given and you edit some section and write the report.


There are .zip file and the word files what I attached below. 

.zip file is coded file. You should edit some section following instruction. 

The word file include the instruction for the work and  the form of report. 

Though the word file is 6 pages, the most of content is attached picture and the form of report and well- explained to do easily


You should give me code file as .zip and the report following the form. 

Category: Mathematics & Physics Subjects: Mathematics Deadline: 12 Hours Budget: $120 - $180 Pages: 2-3 Pages (Short Assignment)

Attachment 1

homework_1_search/autograder.py

# autograder.py # ------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). # imports from python standard library import grading import imp import optparse import os import re import sys import projectParams import random random.seed(0) try: from pacman import GameState except: pass # register arguments and set default values def readCommand(argv): parser = optparse.OptionParser(description = 'Run public tests on student code') parser.set_defaults(generateSolutions=False, edxOutput=False, gsOutput=False, muteOutput=False, printTestCase=False, noGraphics=False) parser.add_option('--test-directory', dest = 'testRoot', default = 'test_cases', help = 'Root test directory which contains subdirectories corresponding to each question') parser.add_option('--student-code', dest = 'studentCode', default = projectParams.STUDENT_CODE_DEFAULT, help = 'comma separated list of student code files') parser.add_option('--code-directory', dest = 'codeRoot', default = "", help = 'Root directory containing the student and testClass code') parser.add_option('--test-case-code', dest = 'testCaseCode', default = projectParams.PROJECT_TEST_CLASSES, help = 'class containing testClass classes for this project') parser.add_option('--generate-solutions', dest = 'generateSolutions', action = 'store_true', help = 'Write solutions generated to .solution file') parser.add_option('--edx-output', dest = 'edxOutput', action = 'store_true', help = 'Generate edX output files') parser.add_option('--gradescope-output', dest = 'gsOutput', action = 'store_true', help = 'Generate GradeScope output files') parser.add_option('--mute', dest = 'muteOutput', action = 'store_true', help = 'Mute output from executing tests') parser.add_option('--print-tests', '-p', dest = 'printTestCase', action = 'store_true', help = 'Print each test case before running them.') parser.add_option('--test', '-t', dest = 'runTest', default = None, help = 'Run one particular test. Relative to test root.') parser.add_option('--question', '-q', dest = 'gradeQuestion', default = None, help = 'Grade one particular question.') parser.add_option('--no-graphics', dest = 'noGraphics', action = 'store_true', help = 'No graphics display for pacman games.') (options, args) = parser.parse_args(argv) return options # confirm we should author solution files def confirmGenerate(): print('WARNING: this action will overwrite any solution files.') print('Are you sure you want to proceed? (yes/no)') while True: ans = sys.stdin.readline().strip() if ans == 'yes': break elif ans == 'no': sys.exit(0) else: print('please answer either "yes" or "no"') # TODO: Fix this so that it tracebacks work correctly # Looking at source of the traceback module, presuming it works # the same as the intepreters, it uses co_filename. This is, # however, a readonly attribute. def setModuleName(module, filename): functionType = type(confirmGenerate) classType = type(optparse.Option) for i in dir(module): o = getattr(module, i) if hasattr(o, '__file__'): continue if type(o) == functionType: setattr(o, '__file__', filename) elif type(o) == classType: setattr(o, '__file__', filename) # TODO: assign member __file__'s? #print(i, type(o)) #from cStringIO import StringIO def loadModuleString(moduleSource): # Below broken, imp doesn't believe its being passed a file: # ValueError: load_module arg#2 should be a file or None # #f = StringIO(moduleCodeDict[k]) #tmp = imp.load_module(k, f, k, (".py", "r", imp.PY_SOURCE)) tmp = imp.new_module(k) exec(moduleCodeDict[k] in tmp.__dict__) setModuleName(tmp, k) return tmp import py_compile def loadModuleFile(moduleName, filePath): with open(filePath, 'r') as f: return imp.load_module(moduleName, f, "%s.py" % moduleName, (".py", "r", imp.PY_SOURCE)) def readFile(path, root=""): "Read file from disk at specified path and return as string" with open(os.path.join(root, path), 'r') as handle: return handle.read() ####################################################################### # Error Hint Map ####################################################################### # TODO: use these ERROR_HINT_MAP = { 'q1': { "<type 'exceptions.IndexError'>": """ We noticed that your project threw an IndexError on q1. While many things may cause this, it may have been from assuming a certain number of successors from a state space or assuming a certain number of actions available from a given state. Try making your code more general (no hardcoded indices) and submit again! """ }, 'q3': { "<type 'exceptions.AttributeError'>": """ We noticed that your project threw an AttributeError on q3. While many things may cause this, it may have been from assuming a certain size or structure to the state space. For example, if you have a line of code assuming that the state is (x, y) and we run your code on a state space with (x, y, z), this error could be thrown. Try making your code more general and submit again! """ } } import pprint def splitStrings(d): d2 = dict(d) for k in d: if k[0:2] == "__": del d2[k] continue if d2[k].find("\n") >= 0: d2[k] = d2[k].split("\n") return d2 def printTest(testDict, solutionDict): pp = pprint.PrettyPrinter(indent=4) print("Test case:") for line in testDict["__raw_lines__"]: print(" |", line) print("Solution:") for line in solutionDict["__raw_lines__"]: print(" |", line) def runTest(testName, moduleDict, printTestCase=False, display=None): import testParser import testClasses for module in moduleDict: setattr(sys.modules[__name__], module, moduleDict[module]) testDict = testParser.TestParser(testName + ".test").parse() solutionDict = testParser.TestParser(testName + ".solution").parse() test_out_file = os.path.join('%s.test_output' % testName) testDict['test_out_file'] = test_out_file testClass = getattr(projectTestClasses, testDict['class']) questionClass = getattr(testClasses, 'Question') question = questionClass({'max_points': 0}, display) testCase = testClass(question, testDict) if printTestCase: printTest(testDict, solutionDict) # This is a fragile hack to create a stub grades object grades = grading.Grades(projectParams.PROJECT_NAME, [(None,0)]) testCase.execute(grades, moduleDict, solutionDict) # returns all the tests you need to run in order to run question def getDepends(testParser, testRoot, question): allDeps = [question] questionDict = testParser.TestParser(os.path.join(testRoot, question, 'CONFIG')).parse() if 'depends' in questionDict: depends = questionDict['depends'].split() for d in depends: # run dependencies first allDeps = getDepends(testParser, testRoot, d) + allDeps return allDeps # get list of questions to grade def getTestSubdirs(testParser, testRoot, questionToGrade): problemDict = testParser.TestParser(os.path.join(testRoot, 'CONFIG')).parse() if questionToGrade != None: questions = getDepends(testParser, testRoot, questionToGrade) if len(questions) > 1: print('Note: due to dependencies, the following tests will be run: %s' % ' '.join(questions)) return questions if 'order' in problemDict: return problemDict['order'].split() return sorted(os.listdir(testRoot)) # evaluate student code def evaluate(generateSolutions, testRoot, moduleDict, exceptionMap=ERROR_HINT_MAP, edxOutput=False, muteOutput=False, gsOutput=False, printTestCase=False, questionToGrade=None, display=None): # imports of testbench code. note that the testClasses import must follow # the import of student code due to dependencies import testParser import testClasses for module in moduleDict: setattr(sys.modules[__name__], module, moduleDict[module]) questions = [] questionDicts = {} test_subdirs = getTestSubdirs(testParser, testRoot, questionToGrade) for q in test_subdirs: subdir_path = os.path.join(testRoot, q) if not os.path.isdir(subdir_path) or q[0] == '.': continue # create a question object questionDict = testParser.TestParser(os.path.join(subdir_path, 'CONFIG')).parse() questionClass = getattr(testClasses, questionDict['class']) question = questionClass(questionDict, display) questionDicts[q] = questionDict # load test cases into question tests = filter(lambda t: re.match('[^#~.].*\.test\Z', t), os.listdir(subdir_path)) tests = map(lambda t: re.match('(.*)\.test\Z', t).group(1), tests) for t in sorted(tests): test_file = os.path.join(subdir_path, '%s.test' % t) solution_file = os.path.join(subdir_path, '%s.solution' % t) test_out_file = os.path.join(subdir_path, '%s.test_output' % t) testDict = testParser.TestParser(test_file).parse() if testDict.get("disabled", "false").lower() == "true": continue testDict['test_out_file'] = test_out_file testClass = getattr(projectTestClasses, testDict['class']) testCase = testClass(question, testDict) def makefun(testCase, solution_file): if generateSolutions: # write solution file to disk return lambda grades: testCase.writeSolution(moduleDict, solution_file) else: # read in solution dictionary and pass as an argument testDict = testParser.TestParser(test_file).parse() solutionDict = testParser.TestParser(solution_file).parse() if printTestCase: return lambda grades: printTest(testDict, solutionDict) or testCase.execute(grades, moduleDict, solutionDict) else: return lambda grades: testCase.execute(grades, moduleDict, solutionDict) question.addTestCase(testCase, makefun(testCase, solution_file)) # Note extra function is necessary for scoping reasons def makefun(question): return lambda grades: question.execute(grades) setattr(sys.modules[__name__], q, makefun(question)) questions.append((q, question.getMaxPoints())) grades = grading.Grades(projectParams.PROJECT_NAME, questions, gsOutput=gsOutput, edxOutput=edxOutput, muteOutput=muteOutput) if questionToGrade == None: for q in questionDicts: for prereq in questionDicts[q].get('depends', '').split(): grades.addPrereq(q, prereq) grades.grade(sys.modules[__name__], bonusPic = projectParams.BONUS_PIC) return grades.points def getDisplay(graphicsByDefault, options=None): graphics = graphicsByDefault if options is not None and options.noGraphics: graphics = False if graphics: try: import graphicsDisplay return graphicsDisplay.PacmanGraphics(1, frameTime=.05) except ImportError: pass import textDisplay return textDisplay.NullGraphics() if __name__ == '__main__': options = readCommand(sys.argv) if options.generateSolutions: confirmGenerate() codePaths = options.studentCode.split(',') # moduleCodeDict = {} # for cp in codePaths: # moduleName = re.match('.*?([^/]*)\.py', cp).group(1) # moduleCodeDict[moduleName] = readFile(cp, root=options.codeRoot) # moduleCodeDict['projectTestClasses'] = readFile(options.testCaseCode, root=options.codeRoot) # moduleDict = loadModuleDict(moduleCodeDict) moduleDict = {} for cp in codePaths: moduleName = re.match('.*?([^/]*)\.py', cp).group(1) moduleDict[moduleName] = loadModuleFile(moduleName, os.path.join(options.codeRoot, cp)) moduleName = re.match('.*?([^/]*)\.py', options.testCaseCode).group(1) moduleDict['projectTestClasses'] = loadModuleFile(moduleName, os.path.join(options.codeRoot, options.testCaseCode)) if options.runTest != None: runTest(options.runTest, moduleDict, printTestCase=options.printTestCase, display=getDisplay(True, options)) else: evaluate(options.generateSolutions, options.testRoot, moduleDict, gsOutput=options.gsOutput, edxOutput=options.edxOutput, muteOutput=options.muteOutput, printTestCase=options.printTestCase, questionToGrade=options.gradeQuestion, display=getDisplay(options.gradeQuestion!=None, options))

homework_1_search/commands.txt

python pacman.py python pacman.py --layout testMaze --pacman GoWestAgent python pacman.py --layout tinyMaze --pacman GoWestAgent python pacman.py -h python pacman.py -l tinyMaze -p SearchAgent -a fn=tinyMazeSearch python pacman.py -l tinyMaze -p SearchAgent python pacman.py -l mediumMaze -p SearchAgent python pacman.py -l bigMaze -z .5 -p SearchAgent python pacman.py -l mediumMaze -p SearchAgent -a fn=bfs python pacman.py -l bigMaze -p SearchAgent -a fn=bfs -z .5 python eightpuzzle.py python pacman.py -l mediumMaze -p SearchAgent -a fn=ucs python pacman.py -l mediumDottedMaze -p StayEastSearchAgent python pacman.py -l mediumScaryMaze -p StayWestSearchAgent python pacman.py -l bigMaze -z .5 -p SearchAgent -a fn=astar,heuristic=manhattanHeuristic python pacman.py -l tinyCorners -p SearchAgent -a fn=bfs,prob=CornersProblem python pacman.py -l mediumCorners -p SearchAgent -a fn=bfs,prob=CornersProblem python pacman.py -l mediumCorners -p AStarCornersAgent -z 0.5 python pacman.py -l testSearch -p AStarFoodSearchAgent python pacman.py -l trickySearch -p AStarFoodSearchAgent python pacman.py -l bigSearch -p ClosestDotSearchAgent -z .5

homework_1_search/eightpuzzle.py

# eightpuzzle.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). import search import random # Module Classes class EightPuzzleState: """ The Eight Puzzle is described in the course textbook on page 64. This class defines the mechanics of the puzzle itself. The task of recasting this puzzle as a search problem is left to the EightPuzzleSearchProblem class. """ def __init__( self, numbers ): """ Constructs a new eight puzzle from an ordering of numbers. numbers: a list of integers from 0 to 8 representing an instance of the eight puzzle. 0 represents the blank space. Thus, the list [1, 0, 2, 3, 4, 5, 6, 7, 8] represents the eight puzzle: ------------- | 1 | | 2 | ------------- | 3 | 4 | 5 | ------------- | 6 | 7 | 8 | ------------ The configuration of the puzzle is stored in a 2-dimensional list (a list of lists) 'cells'. """ self.cells = [] numbers = numbers[:] # Make a copy so as not to cause side-effects. numbers.reverse() for row in range( 3 ): self.cells.append( [] ) for col in range( 3 ): self.cells[row].append( numbers.pop() ) if self.cells[row][col] == 0: self.blankLocation = row, col def isGoal( self ): """ Checks to see if the puzzle is in its goal state. ------------- | | 1 | 2 | ------------- | 3 | 4 | 5 | ------------- | 6 | 7 | 8 | ------------- >>> EightPuzzleState([0, 1, 2, 3, 4, 5, 6, 7, 8]).isGoal() True >>> EightPuzzleState([1, 0, 2, 3, 4, 5, 6, 7, 8]).isGoal() False """ current = 0 for row in range( 3 ): for col in range( 3 ): if current != self.cells[row][col]: return False current += 1 return True def legalMoves( self ): """ Returns a list of legal moves from the current state. Moves consist of moving the blank space up, down, left or right. These are encoded as 'up', 'down', 'left' and 'right' respectively. >>> EightPuzzleState([0, 1, 2, 3, 4, 5, 6, 7, 8]).legalMoves() ['down', 'right'] """ moves = [] row, col = self.blankLocation if(row != 0): moves.append('up') if(row != 2): moves.append('down') if(col != 0): moves.append('left') if(col != 2): moves.append('right') return moves def result(self, move): """ Returns a new eightPuzzle with the current state and blankLocation updated based on the provided move. The move should be a string drawn from a list returned by legalMoves. Illegal moves will raise an exception, which may be an array bounds exception. NOTE: This function *does not* change the current object. Instead, it returns a new object. """ row, col = self.blankLocation if(move == 'up'): newrow = row - 1 newcol = col elif(move == 'down'): newrow = row + 1 newcol = col elif(move == 'left'): newrow = row newcol = col - 1 elif(move == 'right'): newrow = row newcol = col + 1 else: raise "Illegal Move" # Create a copy of the current eightPuzzle newPuzzle = EightPuzzleState([0, 0, 0, 0, 0, 0, 0, 0, 0]) newPuzzle.cells = [values[:] for values in self.cells] # And update it to reflect the move newPuzzle.cells[row][col] = self.cells[newrow][newcol] newPuzzle.cells[newrow][newcol] = self.cells[row][col] newPuzzle.blankLocation = newrow, newcol return newPuzzle # Utilities for comparison and display def __eq__(self, other): """ Overloads '==' such that two eightPuzzles with the same configuration are equal. >>> EightPuzzleState([0, 1, 2, 3, 4, 5, 6, 7, 8]) == \ EightPuzzleState([1, 0, 2, 3, 4, 5, 6, 7, 8]).result('left') True """ for row in range( 3 ): if self.cells[row] != other.cells[row]: return False return True def __hash__(self): return hash(str(self.cells)) def __getAsciiString(self): """ Returns a display string for the maze """ lines = [] horizontalLine = ('-' * (13)) lines.append(horizontalLine) for row in self.cells: rowLine = '|' for col in row: if col == 0: col = ' ' rowLine = rowLine + ' ' + col.__str__() + ' |' lines.append(rowLine) lines.append(horizontalLine) return '\n'.join(lines) def __str__(self): return self.__getAsciiString() # TODO: Implement The methods in this class class EightPuzzleSearchProblem(search.SearchProblem): """ Implementation of a SearchProblem for the Eight Puzzle domain Each state is represented by an instance of an eightPuzzle. """ def __init__(self,puzzle): "Creates a new EightPuzzleSearchProblem which stores search information." self.puzzle = puzzle def getStartState(self): return puzzle def isGoalState(self,state): return state.isGoal() def getSuccessors(self,state): """ Returns list of (successor, action, stepCost) pairs where each succesor is either left, right, up, or down from the original state and the cost is 1.0 for each """ succ = [] for a in state.legalMoves(): succ.append((state.result(a), a, 1)) return succ def getCostOfActions(self, actions): """ actions: A list of actions to take This method returns the total cost of a particular sequence of actions. The sequence must be composed of legal moves """ return len(actions) EIGHT_PUZZLE_DATA = [[1, 0, 2, 3, 4, 5, 6, 7, 8], [1, 7, 8, 2, 3, 4, 5, 6, 0], [4, 3, 2, 7, 0, 5, 1, 6, 8], [5, 1, 3, 4, 0, 2, 6, 7, 8], [1, 2, 5, 7, 6, 8, 0, 4, 3], [0, 3, 1, 6, 8, 2, 7, 5, 4]] def loadEightPuzzle(puzzleNumber): """ puzzleNumber: The number of the eight puzzle to load. Returns an eight puzzle object generated from one of the provided puzzles in EIGHT_PUZZLE_DATA. puzzleNumber can range from 0 to 5. >>> print(loadEightPuzzle(0)) ------------- | 1 | | 2 | ------------- | 3 | 4 | 5 | ------------- | 6 | 7 | 8 | ------------- """ return EightPuzzleState(EIGHT_PUZZLE_DATA[puzzleNumber]) def createRandomEightPuzzle(moves=100): """ moves: number of random moves to apply Creates a random eight puzzle by applying a series of 'moves' random moves to a solved puzzle. """ puzzle = EightPuzzleState([0,1,2,3,4,5,6,7,8]) for i in range(moves): # Execute a random legal move puzzle = puzzle.result(random.sample(puzzle.legalMoves(), 1)[0]) return puzzle if __name__ == '__main__': puzzle = createRandomEightPuzzle(25) print('A random puzzle:') print(puzzle) problem = EightPuzzleSearchProblem(puzzle) path = search.breadthFirstSearch(problem) print('BFS found a path of %d moves: %s' % (len(path), str(path))) curr = puzzle i = 1 for a in path: curr = curr.result(a) print('After %d move%s: %s' % (i, ("", "s")[i>1], a)) print(curr) input("Press return for the next state...") # wait for key stroke i += 1

homework_1_search/game.py

# game.py # ------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). # game.py # ------- # Licensing Information: Please do not distribute or publish solutions to this # project. You are free to use and extend these projects for educational # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by # John DeNero ([email protected]) and Dan Klein ([email protected]). # For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html from util import * import time, os import traceback import sys ####################### # Parts worth reading # ####################### class Agent: """ An agent must define a getAction method, but may also define the following methods which will be called if they exist: def registerInitialState(self, state): # inspects the starting state """ def __init__(self, index=0): self.index = index def getAction(self, state): """ The Agent will receive a GameState (from either {pacman, capture, sonar}.py) and must return an action from Directions.{North, South, East, West, Stop} """ raiseNotDefined() class Directions: NORTH = 'North' SOUTH = 'South' EAST = 'East' WEST = 'West' STOP = 'Stop' LEFT = {NORTH: WEST, SOUTH: EAST, EAST: NORTH, WEST: SOUTH, STOP: STOP} RIGHT = dict([(y,x) for x, y in LEFT.items()]) REVERSE = {NORTH: SOUTH, SOUTH: NORTH, EAST: WEST, WEST: EAST, STOP: STOP} class Configuration: """ A Configuration holds the (x,y) coordinate of a character, along with its traveling direction. The convention for positions, like a graph, is that (0,0) is the lower left corner, x increases horizontally and y increases vertically. Therefore, north is the direction of increasing y, or (0,1). """ def __init__(self, pos, direction): self.pos = pos self.direction = direction def getPosition(self): return (self.pos) def getDirection(self): return self.direction def isInteger(self): x,y = self.pos return x == int(x) and y == int(y) def __eq__(self, other): if other == None: return False return (self.pos == other.pos and self.direction == other.direction) def __hash__(self): x = hash(self.pos) y = hash(self.direction) return hash(x + 13 * y) def __str__(self): return "(x,y)="+str(self.pos)+", "+str(self.direction) def generateSuccessor(self, vector): """ Generates a new configuration reached by translating the current configuration by the action vector. This is a low-level call and does not attempt to respect the legality of the movement. Actions are movement vectors. """ x, y= self.pos dx, dy = vector direction = Actions.vectorToDirection(vector) if direction == Directions.STOP: direction = self.direction # There is no stop direction return Configuration((x + dx, y+dy), direction) class AgentState: """ AgentStates hold the state of an agent (configuration, speed, scared, etc). """ def __init__( self, startConfiguration, isPacman ): self.start = startConfiguration self.configuration = startConfiguration self.isPacman = isPacman self.scaredTimer = 0 self.numCarrying = 0 self.numReturned = 0 def __str__( self ): if self.isPacman: return "Pacman: " + str( self.configuration ) else: return "Ghost: " + str( self.configuration ) def __eq__( self, other ): if other == None: return False return self.configuration == other.configuration and self.scaredTimer == other.scaredTimer def __hash__(self): return hash(hash(self.configuration) + 13 * hash(self.scaredTimer)) def copy( self ): state = AgentState( self.start, self.isPacman ) state.configuration = self.configuration state.scaredTimer = self.scaredTimer state.numCarrying = self.numCarrying state.numReturned = self.numReturned return state def getPosition(self): if self.configuration == None: return None return self.configuration.getPosition() def getDirection(self): return self.configuration.getDirection() class Grid: """ A 2-dimensional array of objects backed by a list of lists. Data is accessed via grid[x][y] where (x,y) are positions on a Pacman map with x horizontal, y vertical and the origin (0,0) in the bottom left corner. The __str__ method constructs an output that is oriented like a pacman board. """ def __init__(self, width, height, initialValue=False, bitRepresentation=None): if initialValue not in …