def playGame(self): """ Executes the game """ ### Agent initialization ### for agent in xrange(len(self.agents)): initAgentFunc = util.TimeoutFunction( self.agents[agent].initState, self.options["timeoutStartup"]) try: start_time = time.time() initAgentFunc(self.game.gameState) elapsed_time = time.time() - start_time if elapsed_time > self.game.options["startupTime"]: raise util.TimeoutFunctionException() self.agentTotalTime[agent] += elapsed_time except util.TimeoutFunctionException: print 'Agent {agent} timed out on startup'.format(**locals()) return ### Run game simulation ### moveCount = 0 while self.game.isOver() == False: action = None agent_getAction = util.TimeoutFunction( self.agents[self.current_agent].getAction, self.options["timeoutGetAction"]) try: start_time = time.time() action = agent_getAction(self.game.gameState) elapsed_time = time.time() - start_time if elapsed_time > self.game.options["getActionTime"]: raise util.TimeoutFunctionException() self.agentTotalTime[agent] += elapsed_time except util.TimeoutFunctionException: print 'Agent {agent} timed out on getAction call'.format( **locals()) return if self.options.get("printActions", False) == True: print "Action taken : {action}".format(**locals()) self.game.gameState = self.game.gameState.result(action) moveCount += 1 if self.options.get("printEachMove", False) == True: print "After move {moveCount} by {self.current_agent}".format( **locals()) print "Rewards {lista}".format( lista=self.game.gameState.rewardPlayer[1:3]) print str(self.game.gameState) self.current_agent = (self.current_agent + 1) % (len(self.agents)) if self.options.get("printSummary", False) == True: print 'Total time taken : {self.agentTotalTime}'.format(**locals()) return self.game.gameState.rewardPlayer[1:3]
def grade(self, gradingModule, exceptionMap={}, bonusPic=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print '\nQuestion %s' % q print '=' * (9 + len(q)) print self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print \ """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 1200)( self) # Call the question's function #TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception, inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except:
def grade(self, gradingModule, exceptionMap={}, bonusPic=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print('\nQuestion %s' % q) print('=' * (9 + len(q))) print self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print(\ """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq)) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 1800)( self) # Call the question's function #TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q])) print('\nFinished at %d:%02d:%02d' % time.localtime()[3:6]) print("\nProvisional grades\n==================") for q in self.questions: print('Question %s: %d/%d' % (q, self.points[q], self.maxes[q])) print('------------------') print('Total: %d/%d' % (self.points.totalCount(), sum(self.maxes.values()))) print(""" Wish you have fun playing the game! Please remember to submit the required files to Moodle before the deadline. ***Kindly Reminder: please follow the submission requirements to avoid unnecessary mistakes*** """) if self.edxOutput: self.produceOutput() if self.gsOutput: self.produceGradeScopeOutput()
def execute(self, grades, moduleDict, solutionDict): random.seed(self.seed) lines = solutionDict['correctActions'].split('\n') moves = [] # Collect solutions for l in lines: m = re.match('(\d+) (\w+) (.*)', l) moves.append((m.group(1), m.group(2), eval(m.group(3)))) inferenceFunction = getattr(moduleDict['inference'], self.inference) ghosts = [ globals()[self.ghost](i) for i in range(1, self.numGhosts + 1) ] if self.inference == 'MarginalInference': moduleDict['inference'].jointInference = moduleDict[ 'inference'].JointParticleFilter() disp = self.question.getDisplay() pac = DoubleInferenceAgent(inferenceFunction, moves, ghosts, grades, self.seed, disp, self.inference, elapse=self.elapse, observe=self.observe, L2Tolerance=self.L2Tolerance, checkUniform=self.checkUniform) if self.inference == "ParticleFilter": for pfilter in pac.inferenceModules: pfilter.setNumParticles(5000) elif self.inference == "MarginalInference": moduleDict['inference'].jointInference.setNumParticles(5000) if self.timeout is not None: timed_run = util.TimeoutFunction(run, self.timeout) try: timed_run(self.layout_str, pac, ghosts, disp, maxMoves=self.maxMoves) except util.TimeoutFunctionException: grades.addMessage("Timed out after {} seconds".format( self.timeout)) return self.testFail(grades) else: run(self.layout_str, pac, ghosts, disp, maxMoves=self.maxMoves) msg = self.errorMsg % pac.errors grades.addMessage(("%s) " % (grades.currentQuestion)) + msg) if pac.errors == 0: grades.addPoints(2) return self.testPass(grades) else: return self.testFail(grades)
def grade(self, gradingModule, exceptionMap={}, bonusPic=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print('\nQuestion %s' % q) print('=' * (9 + len(q))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print( "*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. " % (prereq, q, q, prereq)) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 300)(self) # Call the question's function #TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q])) print('\nFinished at %d:%02d:%02d' % time.localtime()[3:6]) print("\nProvisional grades\n==================") for q in self.questions: print('Question %s: %d/%d' % (q, self.points[q], self.maxes[q])) print('------------------') print('Total: %d/%d' % (self.points.totalCount(), sum(self.maxes.values()))) if bonusPic and self.points.totalCount() == 25: print("Well Done!!") print( "*** Your grades are NOT yet registered. To register your grades, make sure to follow your instructor's guidelines to receive credit on your project.***" ) if self.edxOutput: self.produceOutput()
def evalCode(self, moduleDict): module = moduleDict[self.moduleStr] function = getattr(module, self.functionStr) timeout = 300 timed_function = util.TimeoutFunction(function, timeout) try: result = timed_function(self.truck_limit, self.W, self.C, self.T) except util.TimeoutFunctionException: result = "Timed out after {} seconds".format(timeout) return result
def solve_with_timeout(maxSeconds): try: util.TimeoutFunction(solve_now, maxSeconds)() except KeyboardInterrupt: raise except MemoryError as e: signal.alarm(0) gc.collect() print('Memory limit exceeded.') except util.TimeoutFunctionException as e: signal.alarm(0) print('Time limit (%s seconds) exceeded.' % maxSeconds)
def execute(self, grades, moduleDict, solutionDict): ghosts = [ SeededRandomGhostAgent(i) for i in range(1, self.numGhosts + 1) ] print(self.inference) pac = bustersAgents.GreedyBustersAgent( 0, inference=self.inference, ghostAgents=ghosts, observeEnable=self.observe_enable, elapseTimeEnable=self.elapse_enable) #if self.inference == "ExactInference": # pac.inferenceModules = [moduleDict['inference'].ExactInference(a) for a in ghosts] #else: # print "Error inference type %s -- not implemented" % self.inference # return if self.timeout is not None: timed_run = util.TimeoutFunction(run, self.timeout) try: stats = timed_run(self.layout_str, pac, ghosts, self.question.getDisplay(), nGames=self.numRuns, maxMoves=self.maxMoves, quiet=False) except util.TimeoutFunctionException: grades.addMessage("Timed out after {} seconds".format( self.timeout)) return self.testFail(grades) else: stats = run(self.layout_str, pac, ghosts, self.question.getDisplay(), nGames=self.numRuns, maxMoves=self.maxMoves, quiet=False) aboveCount = [s >= self.min_score for s in stats['scores']].count(True) msg = "%s) Games won on %s with score above %d: %d/%d" % ( self.layout_name, grades.currentQuestion, self.min_score, aboveCount, self.numRuns) grades.addMessage(msg) if aboveCount >= self.numWinsForCredit: grades.assignFullCredit() return self.testPass(grades) else: return self.testFail(grades)
def getAction(self, gameState, gameRules): #both players are trying to make themselves the winning player so only one function is needed def playerValue(gameState, gameRules, player): actions = gameState.getLegalActions(gameRules) tempAction = actions[0] #randomise action list so that each test iteration produces a different result for action in random.sample(actions, len(actions)): newGameState = gameState.generateSuccessor(action) evalNumber = self.evalGame(newGameState, gameRules, True) #don't explore an action that loses the game if gameRules.isGameOver(newGameState.boards): continue #don't explore an action that previously lost if evalNumber in self.loserSet: continue #use any action that previously won if evalNumber in self.winnerSet: return (player, action) #change player with new board #winnerPlayer, winnerAction = minimaxDecision(newGameState, gameRules, not player) winnerPlayer, winnerAction = playerValue( newGameState, gameRules, not player) #only accept a sure thing win if winnerPlayer == player: #add state to explored winner set if evalNumber not in self.winnerSet: self.winnerSet.append(evalNumber) return (player, action) #add state to explored loser set elif evalNumber not in self.loserSet: self.loserSet.append(evalNumber) return (not player, tempAction) start_time = time.time() timed_func = util.TimeoutFunction(playerValue, int(self.maxTimeOut)) try: winnerPlayer, winnerAction = timed_func(gameState, gameRules, True) except util.TimeoutFunctionException: print("Move Timeout!") winnerAction = random.choice(gameState.getLegalActions(gameRules)) return winnerAction util.raiseNotDefined()
def evalCode(self, moduleDict): module = moduleDict[self.moduleStr] function = getattr(module, self.functionStr) timeout = 180 timed_function = util.TimeoutFunction(function, timeout) try: if self.constraints is None or self.cost is None: result = timed_function() else: result = timed_function(self.constraints, self.cost) except util.TimeoutFunctionException: result = "Timed out after {} seconds".format(timeout) return result
def run(self): """ Run a certain number of games, and count the number of wins The max timeout for a single move for the first player (your AI) is 30 seconds. If your AI exceed this time limit, this function will throw an error prompt and return. """ numOfWins = 0 for i in range(self.numOfGames): gameState = GameState() agentIndex = 0 # 0 for First Player (AI), 1 for Second Player (Human) while True: if agentIndex == 0: timed_func = util.TimeoutFunction(self.AIPlayer.getAction, int(self.maxTimeOut)) try: start_time = time.time() action = timed_func(gameState, self.gameRules) except util.TimeoutFunctionException: print( "ERROR: Player %d timed out on a single move, Max %d Seconds!" % (agentIndex, self.maxTimeOut)) return False if not self.muteOutput: print("Player 1 (AI): %s" % action) else: action = self.HumanAgent.getAction(gameState, self.gameRules) if not self.muteOutput: print("Player 2 (Human): %s" % action) gameState = gameState.generateSuccessor(action) if self.gameRules.isGameOver(gameState.boards): break if not self.muteOutput: gameState.printBoards(self.gameRules) agentIndex = (agentIndex + 1) % 2 if agentIndex == 0: pdb.set_trace() print("****player 2 wins game %d!!****" % (i + 1)) else: numOfWins += 1 print("****Player 1 wins game %d!!****" % (i + 1)) print("\n****Player 1 wins %d/%d games.**** \n" % (numOfWins, self.numOfGames))
def execute(self, grades, moduleDict, solutionDict): random.seed(self.seed) inferenceFunction = getattr(moduleDict['inference'], self.inference) ghosts = [ globals()[self.ghost](i) for i in range(1, self.numGhosts + 1) ] if self.inference == 'MarginalInference': moduleDict['inference'].jointInference = moduleDict[ 'inference'].JointParticleFilter() disp = self.question.getDisplay() pac = ZeroWeightAgent(inferenceFunction, ghosts, grades, self.seed, disp, elapse=self.elapse_enable, observe=self.observe_enable) if self.inference == "ParticleFilter": for pfilter in pac.inferenceModules: pfilter.setNumParticles(5000) elif self.inference == "MarginalInference": moduleDict['inference'].jointInference.setNumParticles(5000) if self.timeout is not None: timed_run = util.TimeoutFunction(run, self.timeout) try: timed_run(self.layout_str, pac, ghosts, disp, maxMoves=self.maxMoves) except util.TimeoutFunctionException: grades.addMessage("Timed out after {} seconds".format( self.timeout)) return self.testFail(grades) else: run(self.layout_str, pac, ghosts, disp, maxMoves=self.maxMoves) if pac.getReset(): grades.addMessage('%s) successfully handled all weights = 0' % grades.currentQuestion) return self.testPass(grades) else: grades.addMessage('%s) error handling all weights = 0' % grades.currentQuestion) return self.testFail(grades)
def grade(self, gradingModule, exceptionMap={}, bonusPic=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print('\%s' % q) print('=' * (9 + len(q))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print("""*** NOTE: Make sure to complete %s before working on %s, *** because %s builds upon your answer for %s. """ % (prereq, q, q, prereq)) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 1800)( self) # Call the question's function # TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) if self.edxOutput: self.produceOutput() if self.gsOutput: self.produceGradeScopeOutput()
def grade(self, gradingModule, exceptionMap = {}, bonusPic = False): completedQuestions = set([]) for q in self.questions: print '\nQuestion %s' % q print '=' * (9 + len(q)) print self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print \ % (prereq, q, q, prereq) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q),1800)(self) except Exception, inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except:
def grade(self, gradingModule, exceptionMap={}, bonusPic=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print('\nQuestion %s' % q) print('=' * (9 + len(q))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print( """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq)) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 1800)( self) # Call the question's function # TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q])) print('\nFinished at %d:%02d:%02d' % time.localtime()[3:6]) print("\nProvisional grades\n==================") for q in self.questions: print('Question %s: %d/%d' % (q, self.points[q], self.maxes[q])) print('------------------') print('Total: %d/%d' % (self.points.totalCount(), sum(self.maxes.values()))) if bonusPic and self.points.totalCount() == 25: print(""" ALL HAIL GRANDPAC. LONG LIVE THE GHOSTBUSTING KING. --- ---- --- | \ / + \ / | | + \--/ \--/ + | | + + | | + + + | @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@ V @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ /\ @@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@ /\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ """) print(""" Your grades are NOT yet registered. To register your grades, you must submit to moodle. Submission will be available from February 27th. """) if self.edxOutput: self.produceOutput() if self.gsOutput: self.produceGradeScopeOutput()
def grade(self, gradingModule, exceptionMap={}, bonusPic=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print("\nQuestion %s" % q) print("=" * (9 + len(q))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print( """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq)) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 300)(self) # Call the question's function # TimeoutFunction(getattr(gradingModule, q),1200)(self) # # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: # noqa self.fail("FAIL: Terminated with a string exception.") finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print("\n### Question %s: %d/%d ###\n" % (q, self.points[q], self.maxes[q])) print("\nFinished at %d:%02d:%02d" % time.localtime()[3:6]) print("\nProvisional grades\n==================") for q in self.questions: print("Question %s: %d/%d" % (q, self.points[q], self.maxes[q])) print("------------------") print("Total: %d/%d" % (self.points.totalCount(), sum(self.maxes.values()))) if bonusPic and self.points.totalCount() == 25: print(r""" ALL HAIL GRANDPAC. LONG LIVE THE GHOSTBUSTING KING. --- ---- --- | \ / + \ / | | + \--/ \--/ + | | + + | | + + + | @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@ V @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ /\ @@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@ /\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ """) print(""" TO OBTAIN MARKS YOU MUST SUBMIT YOUR CODE USING MarkUs. """) if self.edxOutput: self.produceOutput()
def run(self): """Run main control loop for game play.""" self.display.initialize(self.state.data) self.num_moves = 0 # self.display.initialize(self.state.make_observation(1).data) # inform learning agents of the game start for i in range(len(self.agents)): agent = self.agents[i] if not agent: self.mute(i) # this is a null agent, meaning it failed to load # the other team wins print("Agent %d failed to load" % i, file=sys.stderr) self.unmute() self._agent_crash(i, quiet=True) return if ("register_initial_state" in dir(agent)): self.mute(i) if self.catch_exceptions: try: timed_func = util.TimeoutFunction( agent.register_initial_state, int(self.rules.get_max_startup_time(i))) try: start_time = time.time() timed_func(self.state.deep_copy()) time_taken = time.time() - start_time self.total_agent_times[i] += time_taken except util.TimeoutFunctionException: print("Agent %d ran out of time on startup!" % i, file=sys.stderr) self.unmute() self.agent_timeout = True self._agent_crash(i, quiet=True) return except Exception as data: self._agent_crash(i, quiet=False) self.unmute() return else: agent.register_initial_state(self.state.deep_copy()) # TODO: could this exceed the total time self.unmute() agent_index = self.starting_index num_agents = len(self.agents) while not self.game_over: # Fetch the next agent agent = self.agents[agent_index] move_time = 0 skip_action = False # Generate an observation of the state if 'observation_function' in dir(agent): self.mute(agent_index) if self.catch_exceptions: try: timed_func = util.TimeoutFunction( agent.observation_function, int(self.rules.get_move_timeout(agent_index))) try: start_time = time.time() observation = timed_func(self.state.deep_copy()) except util.TimeoutFunctionException: skip_action = True move_time += time.time() - start_time self.unmute() except Exception as data: self._agent_crash(agent_index, quiet=False) self.unmute() return else: observation = agent.observation_function( self.state.deep_copy()) self.unmute() else: observation = self.state.deep_copy() # Solicit an action action = None self.mute(agent_index) if self.catch_exceptions: try: timed_func = util.TimeoutFunction( agent.get_action, int(self.rules.get_move_timeout(agent_index)) - int(move_time)) try: start_time = time.time() if skip_action: raise util.TimeoutFunctionException() action = timed_func(observation) except util.TimeoutFunctionException: print("Agent %d timed out on a single move!" % agent_index, file=sys.stderr) self.agent_timeout = True self._agent_crash(agent_index, quiet=True) self.unmute() return move_time += time.time() - start_time if (move_time > self.rules.get_move_warning_time(agent_index)): self.total_agent_time_warnings[agent_index] += 1 print(("Agent %d took too long to make a move! " + "This is warning %d") % (agent_index, self.total_agent_time_warnings[agent_index]), file=sys.stderr) if (self.total_agent_time_warnings[agent_index] > self.rules.get_max_time_warnings(agent_index)): print( ("Agent %d exceeded the maximum number of " + "warnings: %d") % (agent_index, self.total_agent_time_warnings[agent_index]), file=sys.stderr) self.agent_timeout = True self._agent_crash(agent_index, quiet=True) self.unmute() return self.total_agent_times[agent_index] += move_time if (self.total_agent_times[agent_index] > self.rules.get_max_total_time(agent_index)): print( "Agent %d ran out of time! (time: %1.2f)" % (agent_index, self.total_agent_times[agent_index]), file=sys.stderr) self.agent_timeout = True self._agent_crash(agent_index, quiet=True) self.unmute() return self.unmute() except Exception as data: self._agent_crash(agent_index) self.unmute() return else: action = agent.get_action(observation) self.unmute() # Execute the action self.move_history.append((agent_index, action)) if self.catch_exceptions: try: self.state = self.state.generate_successor( agent_index, action) except Exception as data: self.mute(agent_index) self._agent_crash(agent_index) self.unmute() return else: self.state = self.state.generate_successor(agent_index, action) # Change the display self.display.update(self.state.data) # idx = agent_index - agent_index % 2 + 1 # self.display.update( self.state.make_observation(idx).data ) # Allow for game specific conditions (winning, losing, etc.) self.rules.process(self.state, self) # Track progress if agent_index == num_agents + 1: self.num_moves += 1 # Next agent agent_index = (agent_index + 1) % num_agents if _BOINC_ENABLED: boinc.set_fraction_done(self.get_progress()) # inform a learning agent of the game result for agent_index, agent in enumerate(self.agents): if "final" in dir(agent): try: self.mute(agent_index) agent.final(self.state) self.unmute() except Exception as data: if not self.catch_exceptions: raise self._agent_crash(agent_index) self.unmute() return self.display.finish()
def grade(self, gradingModule, exceptionMap={}): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print(("\nQuestion %s" % q)) print(("=" * (9 + len(q)))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print(( """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq))) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 300)(self) # Call the question's function # TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail("FAIL: Terminated with a string exception.") finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print(("\n### Question %s: %d/%d ###\n" % (q, self.points[q], self.maxes[q]))) print(("\nFinished at %d:%02d:%02d" % time.localtime()[3:6])) print("\nProvisional grades\n==================") for q in self.questions: print(("Question %s: %d/%d" % (q, self.points[q], self.maxes[q]))) print("------------------") print(("Total: %d/%d" % (self.points.totalCount(), sum(self.maxes.values())))) print(""" Your grades are NOT yet registered. To register your grades you must submit your files to the edX website. The grades obtained through the edX website are your final grades unless your submission was not in the spirit of the course, such as if your submission simply hardcoded the answers to the tests. We will screen for this after the deadline. *If you worked with a partner, you must both submit separately.* """) if self.edxOutput: self.produceOutput()
def run(self): """ Main control loop for game play. """ self.display.initialize(self.state.data) self.numMoves = 0 # self.display.initialize(self.state.makeObservation(1).data) # inform learning agents of the game start for i in range(len(self.agents)): agent = self.agents[i] if not agent: # this is a null agent, meaning it failed to load # the other team wins self._agentCrash(i, quiet=True) return if ("registerInitialState" in dir(agent)): self.mute() if self.catchExceptions: try: timed_func = ut.TimeoutFunction( agent.registerInitialState, int(self.rules.getMaxStartupTime(i))) try: start_time = time.time() timed_func(self.state.deepCopy()) time_taken = time.time() - start_time self.totalAgentTimes[i] += time_taken except ut.TimeoutFunctionException: print(("Agent %d ran out of time on startup!" % i)) self.unmute() self.agentTimeout = True self._agentCrash(i, quiet=True) return except Exception as data: self.unmute() self._agentCrash(i, quiet=True) return else: agent.registerInitialState(self.state.deepCopy()) # TODO: could this exceed the total time self.unmute() agentIndex = self.startingIndex numAgents = len(self.agents) while not self.gameOver: # Fetch the next agent agent = self.agents[agentIndex] move_time = 0 skip_action = False # Generate an observation of the state if 'observationFunction' in dir(agent): self.mute() if self.catchExceptions: try: timed_func = ut.TimeoutFunction( agent.observationFunction, int(self.rules.getMoveTimeout(agentIndex))) try: start_time = time.time() observation = timed_func(self.state.deepCopy()) except ut.TimeoutFunctionException: skip_action = True move_time += time.time() - start_time self.unmute() except Exception as data: self.unmute() self._agentCrash(agentIndex, quiet=True) return else: observation = agent.observationFunction( self.state.deepCopy()) self.unmute() else: observation = self.state.deepCopy() # Solicit an action action = None self.mute() if self.catchExceptions: try: timed_func = ut.TimeoutFunction( agent.getAction, int(self.rules.getMoveTimeout(agentIndex)) - int(move_time)) try: start_time = time.time() if skip_action: raise ut.TimeoutFunctionException() action = timed_func(observation) except ut.TimeoutFunctionException: print(("Agent %d timed out on a single move!" % agentIndex)) self.agentTimeout = True self.unmute() self._agentCrash(agentIndex, quiet=True) return move_time += time.time() - start_time if move_time > self.rules.getMoveWarningTime(agentIndex): self.totalAgentTimeWarnings[agentIndex] += 1 print(("Agent %d took too long to make a move!\ This is warning %d" % (agentIndex, self.totalAgentTimeWarnings[agentIndex]))) if self.totalAgentTimeWarnings[agentIndex] >\ self.rules.getMaxTimeWarnings(agentIndex): print(("Agent %d exceeded the maximum number of\ warnings: %d" % (agentIndex, self.totalAgentTimeWarnings[agentIndex]))) self.agentTimeout = True self.unmute() self._agentCrash(agentIndex, quiet=True) self.totalAgentTimes[agentIndex] += move_time """ print("Agent: %d, time: %f, total: %f" %) (agentIndex, move_time, self.totalAgentTimes[agentIndex]) """ if self.totalAgentTimes[agentIndex] >\ self.rules.getMaxTotalTime(agentIndex): print(("Agent %d ran out of time! (time: %1.2f)" % (agentIndex, self.totalAgentTimes[agentIndex]))) self.agentTimeout = True self.unmute() self._agentCrash(agentIndex, quiet=True) return self.unmute() except Exception as data: self.unmute() self._agentCrash(agentIndex) return else: action = agent.getAction(observation) self.unmute() # Execute the action self.moveHistory.append((agentIndex, action)) if self.catchExceptions: try: self.state =\ self.state.generateSuccessor(agentIndex, action) except Exception as data: self._agentCrash(agentIndex) return else: self.state = self.state.generateSuccessor(agentIndex, action) # Change the display self.display.update(self.state.data) # idx = agentIndex - agentIndex % 2 + 1 # self.display.update( self.state.makeObservation(idx).data ) # Allow for game specific conditions (winning, losing, etc.) self.rules.process(self.state, self) # Track progress if agentIndex == numAgents + 1: self.numMoves += 1 # Next agent agentIndex = (agentIndex + 1) % numAgents if _BOINC_ENABLED: boinc.set_fraction_done(self.getProgress()) # inform a learning agent of the game result for agent in self.agents: if "final" in dir(agent): try: self.mute() agent.final(self.state) self.unmute() except Exception as data: if not self.catchExceptions: raise self.unmute() print(("Exception", data)) self._agentCrash(agent.index) return self.display.finish()
def grade(self, gradingModule, exceptionMap={}, bonusPic=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print('\nQuestion %s' % q) print('=' * (9 + len(q))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print( """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq)) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 1800)( self) # Call the question's function #TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q])) print('\nFinished at %d:%02d:%02d' % time.localtime()[3:6]) print("\nTest Summary\n==================") for q in self.questions: print('Question %s: %d/%d' % (q, self.points[q], self.maxes[q])) print('------------------') print('Total: %d/%d' % (self.points.totalCount(), sum(self.maxes.values()))) if bonusPic and self.points.totalCount() == 25: print(""" ALL HAIL GRANDPAC. LONG LIVE THE GHOSTBUSTING KING. --- ---- --- | \ / + \ / | | + \--/ \--/ + | | + + | | + + + | @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@ V @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ /\ @@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@ /\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ """) print(""" These numbers are NOT your grades, these numbers just tell you how many of the tests that you have passed. Your grade depends on a number of other factors, including your screenshots, your git log (PLEASE make regular commits with meaningful descriptions!!!), following the directions for elvis and canvas submission, etc. """) if self.edxOutput: self.produceOutput() if self.gsOutput: self.produceGradeScopeOutput()
def grade(self, grading_module, exception_map={}, bonus_pic=False): """ Grades each question grading_module: the module with all the grading functions (pass in with sys.modules[__name__]) """ completed_questions = set([]) for q in self.questions: print '\nQuestion %s' % q print '=' * (9 + len(q)) print self.current_question = q incompleted = self.prereqs[q].difference(completed_questions) if len(incompleted) > 0: prereq = incompleted.pop() print \ """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq) continue if self.mute: util.mute_print() try: util.TimeoutFunction(getattr(grading_module, q), 1800)( self) # Call the question's function # TimeoutFunction(getattr(grading_module, q),1200)(self) # Call # the question's function except Exception as inst: self.add_exception_message(q, inst, traceback) self.add_error_hints(exception_map, inst, q[1]) except BaseException: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmute_print() if self.points[q] >= self.maxes[q]: completed_questions.add(q) print '\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q]) print '\nFinished at %d:%02d:%02d' % time.localtime()[3:6] print "\nProvisional grades\n==================" for q in self.questions: print 'Question %s: %d/%d' % (q, self.points[q], self.maxes[q]) print '------------------' print 'Total: %d/%d' % (self.points.total_count(), sum(self.maxes.values())) if bonus_pic and self.points.total_count() == 25: print """ ALL HAIL GRANDPAC. LONG LIVE THE GHOSTBUSTING KING. --- ---- --- | \ / + \ / | | + \--/ \--/ + | | + + | | + + + | @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@ V @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ /\ @@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@ /\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ """ print """ Your grades are NOT yet registered. To register your grades, make sure\n\n (a) You have PROPER HEADER AND AUTHENTICITY STATEMENT on all source files you are submitting, \n (b) Create a single zip file containing just the files you were instructed to modify, and\n (c) Upload your zip file to canvas. """ if self.edx_output: self.produce_output() if self.gs_output: self.produce_grade_scope_output()
def grade(self, gradingModule, exceptionMap={}, bonusPic=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print('\nQuestion %s' % q) print('=' * (9 + len(q))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print( """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq)) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 1800)( self) # Call the question's function # TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q])) print('\nFinished at %d:%02d:%02d' % time.localtime()[3:6]) print("\nProvisional grades\n==================") CSPValues = [] for q in self.questions: print('Question %s: %d/%d' % (q, self.points[q], self.maxes[q])) if self.runQ6: with open("./test_cases/q6/cspScore.txt") as infile: for line in infile: CSPValues = line.split("/") print('Question q6: ' + line) self.q6_points = int(CSPValues[0]) self.q6_max = int(CSPValues[1]) totalPoints = self.points.totalCount() + self.q6_points maxPoints = sum(self.maxes.values()) + self.q6_max else: totalPoints = self.points.totalCount() maxPoints = sum(self.maxes.values()) print('------------------') print('Total: %d/%d' % (totalPoints, maxPoints)) if bonusPic and self.points.totalCount() == 25: print(""" ALL HAIL GRANDPAC. LONG LIVE THE GHOSTBUSTING KING. --- ---- --- | \ / + \ / | | + \--/ \--/ + | | + + | | + + + | @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@ V @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ /\ @@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@ /\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ """) print(""" Your grades are NOT yet registered. To register your grades, make sure to follow your instructor's guidelines to receive credit on your project. """) if self.edxOutput: self.produceOutput() if self.gsOutput: self.produceGradeScopeOutput()
print ('=' * (9 + len(q))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print ("\\") """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q),1800)(self) # Call the question's function #TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception, inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print ('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q]))
def grade(self, gradingModule, exceptionMap={}, bonusPic=False, forSubmission=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print('\nQuestion %s' % q) print('=' * (9 + len(q))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print( """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq)) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 1800)( self) # Call the question's function # TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q])) print('\nFinished at %d:%02d:%02d' % time.localtime()[3:6]) print("\nProvisional grades\n==================") for q in self.questions: print('Question %s: %d/%d' % (q, self.points[q], self.maxes[q])) print('------------------') print('Total: %d/%d' % (self.points.totalCount(), sum(self.maxes.values()))) if bonusPic and self.points.totalCount() == 25: print(""" ALL HAIL GRANDPAC. LONG LIVE THE GHOSTBUSTING KING. --- ---- --- | \ / + \ / | | + \--/ \--/ + | | + + | | + + + | @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@ V @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ /\ @@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@ /\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ """) if forSubmission: print( '\nToken for submission has been created! Submit submit.token, multiagent.py, and report.pdf to Blackboard.' ) else: print( "\nHow did you do? If you're ready to submit, run python submission_autograder.py" ) print(""" Your grades are NOT yet registered. To register your grades, make sure to follow your instructor's guidelines to receive credit on your project. """) if self.edxOutput: self.produceOutput() if self.gsOutput: self.produceGradeScopeOutput()
def grade(self, gradingModule, exceptionMap = {}, bonusPic = False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print('\nQuestion %s' % q) print('=' * (9 + len(q))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print("""*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq)) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q),7)(self) # Call the question's function #TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q])) print('\nFinished at %d:%02d:%02d' % time.localtime()[3:6]) print("\nProvisional grades\n==================") sumMax = 0 for q in self.questions[:-1]: print('Question %s: %d/%d' % (q, self.points[q], self.maxes[q])) sumMax += self.maxes[q] lq = self.questions[-1] print('Extra Credit Question %s: %d/%d' % (lq, self.points[lq], self.maxes[lq])) print('------------------') print('Total: %d/%d' % (self.points.totalCount(), sumMax)) posBonus1 = 6 posBonus2 = 4 print("Q1-Q4 Style Points: ?/%d" % (posBonus1)) print("Q5-Q7 Style Points: ?/%d" % (posBonus2)) print('------------------') print('Total: %d/%d (%d/%d excluding style)' % (self.points.totalCount(), sumMax+posBonus1+posBonus2,self.points.totalCount(), sumMax)) if bonusPic and self.points.totalCount() == 25: print(""" ALL HAIL GRANDPAC. LONG LIVE THE GHOSTBUSTING KING. --- ---- --- | \ / + \ / | | + \--/ \--/ + | | + + | | + + + | @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@ V @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ /\ @@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@ /\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ """) print(""" Your grades are NOT yet registered. To register your grades, make sure to follow your instructor's guidelines to receive credit on your project. """) if self.edxOutput: self.produceOutput()
def grade(self, gradingModule, exceptionMap={}, bonusPic=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print('\nQuestion %s' % q) print('=' * (9 + len(q))) print() self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print (\ """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq)) continue if self.mute: util.mutePrint() try: util.TimeoutFunction(getattr(gradingModule, q), 1800)( self) # Call the question's function #TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q])) print('\nFinished at %d:%02d:%02d' % time.localtime()[3:6]) print("\nProvisional grades\n==================") for q in self.questions: print('Question %s: %d/%d' % (q, self.points[q], self.maxes[q])) print('------------------') print('Total: %d/%d' % (self.points.totalCount(), sum(self.maxes.values()))) if bonusPic and self.points.totalCount() == 25: print(""" ALL HAIL GRANDPAC. LONG LIVE THE GHOSTBUSTING KING. --- ---- --- | \ / + \ / | | + \--/ \--/ + | | + + | | + + + | @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@ V @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ /\ @@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@ /\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ """) if self.points.totalCount() == sum(self.maxes.values()): print(""" ^_^ Congratulations! You have finished Bayes Net project. Please run the following command to generate the .tar file: tar cvf submit.tar factorOperations.py inference.py bayesAgents.py then submit to autolab. Have fun in CS181! """) if self.edxOutput: self.produceOutput() if self.gsOutput: self.produceGradeScopeOutput()
def grade(self, grading_module, exception_map={}, bonus_pic=False): """Grade each question. Args: grading_module: the module with all the grading functions (pass in with sys.modules[__name__]) """ completed_questions = set([]) for q in self.questions: print('\nQuestion %s' % q) print('=' * (9 + len(q))) print() self.current_question = q incompleted = self.prereqs[q].difference(completed_questions) if len(incompleted) > 0: prereq = incompleted.pop() print("*** NOTE: Make sure to complete Question %s before \ working on Question %s,\n\ *** because Question %s builds upon your answer for Question %s." % (prereq, q, q, prereq)) continue if self.mute: util.mute_print() try: # Call the question's function util.TimeoutFunction(getattr(grading_module, q), 300)(self) except Exception as inst: self.add_exception_message(q, inst, traceback) self.add_error_hints(exception_map, inst, q[1]) finally: if self.mute: util.unmute_print() if self.points[q] >= self.maxes[q]: completed_questions.add(q) print('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q])) # if self.student_code comes in then we lint if self.student_code is not None: try: from flake8.api import legacy as flake8 # noqa on the following since just importing to test installed import pep8ext_naming # noqa import flake8_docstrings # noqa print("\nLinting Code...\n" + "=" * 15) self.current_question = "linting" style_guide = flake8.get_style_guide() report = style_guide.check_files(self.student_code.split(",")) self.maxes["linting"] = self.linting_value self.points["linting"] = self.linting_value if report.total_errors > 0: self.fail("FAIL: You should fix all linting errors " + "before submission in order to receive full " + "credit!") self.add_message("") for module in self.student_code.split(","): self.check_header(module) if (("project_test_classes" in dir(grading_module) and "extra_lint" in dir(grading_module.project_test_classes) )): grading_module.project_test_classes.extra_lint(self) if self.points["linting"] == self.linting_value: self.add_message("PASS: no linting errors.") print('\n### Linter: %d/%d ###\n' % (self.points['linting'], self.maxes['linting'])) except ImportError: print(""" ### WARNING: Unable to import flake8 and/or extensions, so cannot \ properly lint your code. ### Please install flake8, pep8-naming, and flake8-docstrings to auto-check \ whether you are adhering to proper style and docstring conventions. To install, run: pip install flake8 pep8-naming flake8-docstrings """) print('\nFinished at %d:%02d:%02d' % time.localtime()[3:6]) print("\nProvisional grades\n==================") for q in self.questions: print('Question %s: %d/%d' % (q, self.points[q], self.maxes[q])) if "linting" in self.maxes: print('Linter: %d/%d' % (self.points["linting"], self.maxes["linting"])) print('------------------') print('Total: %d/%d' % (self.points.total_count(), sum(self.maxes.values()))) if bonus_pic and self.points.total_count() == 25: print(""" ALL HAIL GRANDPAC. LONG LIVE THE GHOSTBUSTING KING. --- ---- --- | \ / + \ / | | + \--/ \--/ + | | + + | | + + + | @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@ V @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ /\ @@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@ /\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ """) print(""" Your grades are NOT yet registered. To register your grades, make sure (a) You have PROPER HEADER AND AUTHENTICITY STATEMENT on all source files \ you are submitting, (b) Create a single zip file containing just the files you were instructed to \ modify, and (c) Upload your zip file to canvas. """) if self.edx_output: self.produce_edx_output() if self.gs_output: self.produce_grade_scope_output()
def grade(self, gradingModule, exceptionMap={}, bonusPic=False): """ Grades each question gradingModule: the module with all the grading functions (pass in with sys.modules[__name__]) """ completedQuestions = set([]) for q in self.questions: print '\nQuestion %s' % q print '=' * (9 + len(q)) print self.currentQuestion = q incompleted = self.prereqs[q].difference(completedQuestions) if len(incompleted) > 0: prereq = incompleted.pop() print \ """*** NOTE: Make sure to complete Question %s before working on Question %s, *** because Question %s builds upon your answer for Question %s. """ % (prereq, q, q, prereq) continue if self.mute: util.mutePrint() try: # Call the question's function util.TimeoutFunction(getattr(gradingModule, q), 300)(self) # TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call # the question's function except Exception as inst: self.addExceptionMessage(q, inst, traceback) self.addErrorHints(exceptionMap, inst, q[1]) except: self.fail('FAIL: Terminated with a string exception.') finally: if self.mute: util.unmutePrint() if self.points[q] >= self.maxes[q]: completedQuestions.add(q) print '\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q]) print '\nFinished at %d:%02d:%02d' % time.localtime()[3:6] print "\nProvisional grades\n==================" for q in self.questions: print 'Question %s: %d/%d' % (q, self.points[q], self.maxes[q]) print '------------------' print 'Total: %d/%d' % (self.points.totalCount(), sum(self.maxes.values())) if bonusPic and self.points.totalCount() == 25: print """ ALL HAIL GRANDPAC. LONG LIVE THE GHOSTBUSTING KING. --- ---- --- | \ / + \ / | | + \--/ \--/ + | | + + | | + + + | @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ / @@@@@@@@@@@@@@@@@@@@@@@@@@ V @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ /\ @@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@ /\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@ / \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ """ print """ Your grades are NOT yet registered. To register your grades you must submit your files to the edX website. The grades obtained through the edX website are your final grades unless your submission was not in the spirit of the course, such as if your submission simply hardcoded the answers to the tests. We will screen for this after the deadline. """ if self.edxOutput: self.produceOutput()