student.py 11.2 KB

# python standard library
from datetime import datetime
import logging
import random
from typing import Dict, List, Optional, Tuple

# third party libraries
import networkx as nx

# this project
from .questions import Question


# setup logger for this module
logger = logging.getLogger(__name__)


# ----------------------------------------------------------------------------
# kowledge state of a student
# Contains:
#   state - dict of unlocked topics and their levels
#   deps  - access to dependency graph shared between students
#   topic_sequence - list with the recommended topic sequence
#   current_topic - nameref of the current topic
# ----------------------------------------------------------------------------
class StudentState(object):
    # =======================================================================
    # methods that update state
    # =======================================================================
    def __init__(self, uid, state, courses, deps, factory) -> None:
        # shared application data between all students
        self.deps = deps        # dependency graph
        self.factory = factory  # question factory
        self.courses = courses  # {'course': ['topic_id1', 'topic_id2',...]}

        # data of this student
        self.uid = uid      # user id '12345'
        self.state = state  # {'topic': {'level': 0.5, 'date': datetime}, ...}

        # prepare for running
        self.update_topic_levels()  # applies forgetting factor
        self.unlock_topics()        # whose dependencies have been completed
        self.start_course(None)

    # ------------------------------------------------------------------------
    def start_course(self, course: Optional[str]) -> None:
        if course is None:
            logger.debug('no active course')
            self.current_course: Optional[str] = None
            self.topic_sequence: List[str] = []
            self.current_topic: Optional[str] = None
        else:
            logger.debug(f'starting course {course}')
            self.current_course = course
            topics = self.courses[course]['topics']
            self.topic_sequence = self.recommend_topic_sequence(topics)

    # ------------------------------------------------------------------------
    # Start a new topic.
    #    questions: list of generated questions to do in the topic
    #    current_question: the current question to be presented
    # ------------------------------------------------------------------------
    async def start_topic(self, topic: str) -> None:
        logger.debug(f'start topic "{topic}"')

        # avoid regenerating questions in the middle of the current topic
        if self.current_topic == topic:
            logger.info('Restarting current topic is not allowed.')
            return

        # do not allow locked topics
        if self.is_locked(topic):
            logger.debug(f'is locked "{topic}"')
            return

        # starting new topic
        self.current_topic = topic
        self.correct_answers = 0
        self.wrong_answers = 0

        t = self.deps.node[topic]
        k = t['choose']
        if t['shuffle_questions']:
            questions = random.sample(t['questions'], k=k)
        else:
            questions = t['questions'][:k]
        logger.debug(f'selected questions:  {", ".join(questions)}')

        self.questions: List[Question] = [await self.factory[ref].gen_async()
                                          for ref in questions]

        n = len(self.questions)
        logger.debug(f'generated {n} questions')

        # get first question
        self.next_question()

    # ------------------------------------------------------------------------
    # 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) -> None:
        logger.debug(f'finished {self.current_topic}')

        self.state[self.current_topic] = {
            'date': datetime.now(),
            'level': self.correct_answers / (self.correct_answers +
                                             self.wrong_answers)
            }
        self.current_topic = None
        self.unlock_topics()

    # ------------------------------------------------------------------------
    # corrects current question with provided answer.
    # implements the logic:
    #   - if answer ok, goes to next question
    #   - if wrong, counts number of tries. If exceeded, moves on.
    # ------------------------------------------------------------------------
    async def check_answer(self, answer) -> Tuple[Question, str]:
        q: Question = self.current_question
        q['answer'] = answer
        q['finish_time'] = datetime.now()
        logger.debug(f'checking answer of {q["ref"]}...')
        await q.correct_async()
        logger.debug(f'grade = {q["grade"]:.2}')

        if q['grade'] > 0.999:
            self.correct_answers += 1
            self.next_question()
            action = 'right'

        else:
            self.wrong_answers += 1
            self.current_question['tries'] -= 1

            if self.current_question['tries'] > 0:
                action = 'try_again'
            else:
                action = 'wrong'
                if self.current_question['append_wrong']:
                    logger.debug('wrong answer, append new question')
                    # self.questions.append(self.factory[q['ref']].generate())
                    new_question = await self.factory[q['ref']].gen_async()
                    self.questions.append(new_question)
                self.next_question()

        # returns corrected question (not new one) which might include comments
        return q, action

    # ------------------------------------------------------------------------
    # Move to next question, or None
    # ------------------------------------------------------------------------
    def next_question(self) -> Optional[Question]:
        try:
            self.current_question = self.questions.pop(0)
        except IndexError:
            self.current_question = None
            self.finish_topic()
        else:
            self.current_question['start_time'] = datetime.now()
            default_maxtries = self.deps.nodes[self.current_topic]['max_tries']
            maxtries = self.current_question.get('max_tries', default_maxtries)
            self.current_question['tries'] = maxtries
            logger.debug(f'current_question = {self.current_question["ref"]}')

        return self.current_question  # question or None

    # ------------------------------------------------------------------------
    # Update proficiency level of the topics using a forgetting factor
    # ------------------------------------------------------------------------
    def update_topic_levels(self) -> None:
        now = datetime.now()
        for tref, s in self.state.items():
            dt = now - s['date']
            forgetting_factor = self.deps.node[tref]['forgetting_factor']
            s['level'] *= forgetting_factor ** dt.days   # forgetting factor

    # ------------------------------------------------------------------------
    # Unlock topics whose dependencies are satisfied (> min_level)
    # ------------------------------------------------------------------------
    def unlock_topics(self) -> None:
        for topic in self.deps.nodes():
            if topic not in self.state:  # if locked
                pred = self.deps.predecessors(topic)
                min_level = self.deps.node[topic]['min_level']
                if all(d in self.state and self.state[d]['level'] > min_level
                       for d in pred):  # all deps are greater than min_level

                    self.state[topic] = {
                        'level': 0.0,           # unlock
                        'date': datetime.now()
                        }
                    logger.debug(f'unlocked "{topic}"')
                # else:  # lock this topic if deps do not satisfy min_level
                #     del self.state[topic]

    # ========================================================================
    # pure functions of the state (no side effects)
    # ========================================================================

    def topic_has_finished(self) -> bool:
        return self.current_topic is None

    # ------------------------------------------------------------------------
    # compute recommended sequence of topics  ['a', 'b', ...]
    # ------------------------------------------------------------------------
    def recommend_topic_sequence(self, targets: List[str] = []) -> List[str]:
        G = self.deps
        ts = set(targets)
        for t in targets:
            ts.update(nx.ancestors(G, t))

        tl = list(nx.topological_sort(G.subgraph(ts)))

        # sort with unlocked first
        unlocked = [t for t in tl if t in self.state]
        locked = [t for t in tl if t not in unlocked]
        return unlocked + locked

    # ------------------------------------------------------------------------
    def get_current_question(self) -> Optional[Question]:
        return self.current_question

    # ------------------------------------------------------------------------
    def get_current_topic(self) -> Optional[str]:
        return self.current_topic

    # ------------------------------------------------------------------------
    def get_current_course_title(self) -> Optional[str]:
        return self.courses[self.current_course]['title']

    # ------------------------------------------------------------------------
    def is_locked(self, topic: str) -> bool:
        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) -> float:
        return self.correct_answers / (1 + self.correct_answers +
                                       len(self.questions))

    # ------------------------------------------------------------------------
    def get_topic_level(self, topic: str) -> float:
        return self.state[topic]['level']

    # ------------------------------------------------------------------------
    def get_topic_date(self, topic: str):
        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]