;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: learning/agents/exploring-sarsa-learner.lisp

;;;; Exploratory reinforcement learning agent using SARSA (Section 22.3.3)

;;; Like the TD Q-learning agent of exploring-tdq-learner.lisp, but on-policy:
;;; the update uses the Q-value of the action a' actually chosen in the new
;;; state, Q(i,a) <- Q(i,a) + alpha (R(i) + Q(j,a') - Q(i,a)), instead of the
;;; best Q-value of that state.  The table Q may be passed in, to inspect it.

(defun make-exploring-sarsa-learner (actions &optional (Q (make-hash-table :test #'equal)))
  (let ((i nil)           ;;; the previous state visited
        (a nil)           ;;; the last action taken
        (N (make-hash-table :test #'equal))
        (Ri nil))         ;;; reward received in state i
    #'(lambda (e)
        (let ((terminalp (mdp-percept-terminalp e))
              (j (mdp-percept-state e))
              (reward (mdp-percept-reward e)))
          (unless (gethash j Q)
            (setf (gethash j Q)
                  (mapcar #'(lambda (a) (cons a reward)) actions))
            (setf (gethash j N)
                  (mapcar #'(lambda (a) (cons a 0)) actions)))
          (let ((next (exploration-q-choice j Q N)))
            (when i
              (incf (cdr (assoc a (gethash i N) :test #'eq)))
              (incf (cdr (assoc a (gethash i Q) :test #'eq))
                    (* (current-alpha (cdr (assoc a (gethash i N) :test #'eq)))
                       (+ Ri (- (q-entry Q next j) (q-entry Q a i))))))
            (cond (terminalp
                   (setq i nil)
                   (setf (gethash j Q)
                         (mapcar #'(lambda (a) (cons a reward)) actions)))
                  (t (setq i j Ri reward)))
            (setq a next))))))
