# python standard library import random from datetime import datetime import logging # libraries import networkx as nx # this project # import questions # setup logger for this module logger = logging.getLogger(__name__) # ---------------------------------------------------------------------------- # kowledge state of each student....?? # Contains: # state - dict of topics with state of unlocked topics # deps - dependency graph # topic_sequence - list with the order of recommended topics # ---------------------------------------------------------------------------- class StudentKnowledge(object): # ======================================================================= # methods that update state # ======================================================================= def __init__(self, deps, state={}): self.deps = deps # dependency graph shared among students self.state = state # {'topic': {'level':0.5, 'date': datetime}, ...} self.update_topic_levels() # forgetting factor self.topic_sequence = self.recommend_topic_sequence() # ['a', 'b', ...] self.unlock_topics() self.current_topic = None self.MAX_QUESTIONS = 6 # FIXME get from configuration file?? # ------------------------------------------------------------------------ # Updates the proficiency levels of the topics, with forgetting factor # FIXME no dependencies are considered yet... # ------------------------------------------------------------------------ def update_topic_levels(self): now = datetime.now() for s in self.state.values(): dt = now - s['date'] s['level'] *= 0.95 ** dt.days # forgetting factor 0.95 # ------------------------------------------------------------------------ # Unlock topics whose dependencies are satisfied (> min_level) # ------------------------------------------------------------------------ def unlock_topics(self): # minimum level that the dependencies of a topic must have # for the topic to be unlocked. min_level = 0.01 for topic in self.topic_sequence: if topic not in self.state: # if locked pred = self.deps.predecessors(topic) if all(d in self.state and self.state[d]['level'] > min_level for d in pred): # and all dependencies are done self.state[topic] = { 'level': 0.0, # then unlock 'date': datetime.now() } logger.debug(f'Unlocked "{topic}".') # ------------------------------------------------------------------------ # Start a new topic. If not provided, gets a recommendation. # questions: list of generated questions to do in the topic # current_question: the current question to be presented # ------------------------------------------------------------------------ def init_topic(self, topic=''): logger.debug(f'StudentKnowledge.init_topic({topic})') if not topic: topic = self.get_recommended_topic() # check if it's unlocked if self.is_locked(topic): return False if self.current_topic is not None and topic == self.current_topic: return True self.current_topic = topic # generate question instances for current topic factory = self.deps.node[topic]['factory'] questionlist = self.deps.node[topic]['questions'] self.correct_answers = 0 self.wrong_answers = 0 size = min(self.MAX_QUESTIONS, len(questionlist)) # number of questions questionlist = random.sample(questionlist, k=size) logger.debug(f'Questions: {", ".join(questionlist)}') self.questions = [factory[qref].generate() for qref in questionlist] logger.debug(f'Total: {len(self.questions)} questions') try: self.current_question = self.questions.pop(0) # FIXME crash if empty except IndexError: # self.current_question = None self.finish_topic() # FIXME if no questions, what should be done? return False else: self.current_question['start_time'] = datetime.now() return True # ------------------------------------------------------------------------ # The topic has finished and there are no more questions. # The topic level is updated in state and unlocks are performed. # The current topic is unchanged. # ------------------------------------------------------------------------ def finish_topic(self): logger.debug(f'StudentKnowledge.finish_topic({self.current_topic})') self.current_question = None self.state[self.current_topic] = { 'date': datetime.now(), 'level': self.correct_answers / (self.correct_answers + self.wrong_answers) } self.unlock_topics() # ------------------------------------------------------------------------ # returns the current question with correction, time and comments updated # ------------------------------------------------------------------------ def check_answer(self, answer): logger.debug('StudentKnowledge.check_answer()') q = self.current_question q['answer'] = answer q['finish_time'] = datetime.now() grade = q.correct() logger.debug(f'Grade {grade:.2} ({q["ref"]})') # if answer is correct, get next question if grade > 0.999: self.correct_answers += 1 try: self.current_question = self.questions.pop(0) # FIXME empty? except IndexError: self.finish_topic() else: self.current_question['start_time'] = datetime.now() # if wrong, keep same question and append a similar one at the end else: self.wrong_answers += 1 factory = self.deps.node[self.current_topic]['factory'] self.questions.append(factory[q['ref']].generate()) # returns answered and corrected question return q # ======================================================================== # pure functions of the state (no side effects) # ======================================================================== # ------------------------------------------------------------------------ # compute recommended sequence of topics ['a', 'b', ...] # ------------------------------------------------------------------------ def recommend_topic_sequence(self): return list(nx.topological_sort(self.deps)) # ------------------------------------------------------------------------ def get_current_question(self): return self.current_question # ------------------------------------------------------------------------ def get_current_topic(self): return self.current_topic # ------------------------------------------------------------------------ def is_locked(self, topic): return topic not in self.state # ------------------------------------------------------------------------ # Return list of {ref: 'xpto', name: 'long name', leve: 0.5} # Levels are in the interval [0, 1] if unlocked or None if locked. # Topics unlocked but not yet done have level 0.0. # ------------------------------------------------------------------------ def get_knowledge_state(self): return [{ 'ref': ref, 'type': self.deps.nodes[ref]['type'], 'name': self.deps.nodes[ref]['name'], 'level': self.state[ref]['level'] if ref in self.state else None } for ref in self.topic_sequence ] # ------------------------------------------------------------------------ def get_topic_progress(self): return self.correct_answers / (1 + self.correct_answers + len(self.questions)) # ------------------------------------------------------------------------ def get_topic_level(self, topic): return self.state[topic]['level'] # ------------------------------------------------------------------------ def get_topic_date(self, topic): return self.state[topic]['date'] # ------------------------------------------------------------------------ # Recommends a topic to practice/learn from the state. # ------------------------------------------------------------------------ def get_recommended_topic(self): # FIXME untested return min(self.state.items(), key=lambda x: x[1]['level'])[0]