;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: multiagent/algorithms/game-theory.lisp

;;;; Game Theory and Making Collective Decisions (Sections 18.2-18.4)

;;; A two-player game in normal form has two payoff matrices, as lists of
;;; rows: (payoff-entry payoff1 i j) is the payoff of the row player when it
;;; plays strategy i and the column player plays j, and payoff2 is that of
;;; the column player.  Strategies are 0-based indices.

(defun payoff-entry (matrix i j) (nth j (nth i matrix)))

(defun select-entries (row indices)
  (mapcar #'(lambda (j) (nth j row)) indices))

;;;; Non-Cooperative Game Theory (Section 18.2)

(defun dominates? (s-payoffs t-payoffs &optional (strongly t))
  "Does the strategy with payoffs S-PAYOFFS dominate the strategy with
  payoffs T-PAYOFFS, against the same strategies of the opponents?  Strong
  domination is better everywhere, weak domination never worse and better
  somewhere."
  (if strongly
      (every #'> s-payoffs t-payoffs)
    (and (every #'>= s-payoffs t-payoffs) (some #'> s-payoffs t-payoffs))))

(defun dominant-strategy (payoff &optional (strongly t))
  "The strategy (row) of the player with matrix PAYOFF that dominates all
  its other strategies, or NIL.  For the column player, pass the transpose
  of its matrix."
  (loop for s from 0 below (length payoff)
        when (loop for s2 from 0 below (length payoff)
                   always (or (= s s2)
                              (dominates? (nth s payoff) (nth s2 payoff) strongly)))
          return s))

(defun iterated-dominance (payoff1 payoff2 &optional (strongly t))
  "Iterated elimination of dominated strategies: delete, for either player,
  a strategy dominated among the strategies still in play, until there is
  none.  Returns the list of the surviving rows and the surviving columns."
  (let ((rows (iota (length payoff1)))
        (cols (iota (length (first payoff1))))
        (payoff2-by-column (transpose payoff2)))
    (flet ((dominated (matrix own opponent)
             (find-if #'(lambda (s)
                          (some #'(lambda (s2)
                                    (and (/= s s2)
                                         (dominates? (select-entries (nth s2 matrix) opponent)
                                                     (select-entries (nth s matrix) opponent)
                                                     strongly)))
                                own))
                      own)))
      (loop (let* ((row (dominated payoff1 rows cols))
                   (col (dominated payoff2-by-column cols
                                   (if row (remove row rows) rows))))
              (when row (setf rows (remove row rows)))
              (when col (setf cols (remove col cols)))
              (unless (or row col)
                (return (list rows cols))))))))

(defun pure-nash-equilibria (payoff1 payoff2)
  "The pure-strategy Nash equilibria (i j) of a two-player game: each
  player's strategy is a best response to the other's."
  (let ((m (length payoff1))
        (n (length (first payoff1))))
    (loop for i from 0 below m
          nconc (loop for j from 0 below n
                      when (and (>= (payoff-entry payoff1 i j)
                                    (loop for k from 0 below m
                                          maximize (payoff-entry payoff1 k j)))
                                (>= (payoff-entry payoff2 i j)
                                    (loop for k from 0 below n
                                          maximize (payoff-entry payoff2 i k))))
                        collect (list i j)))))

;;; A zero-sum game is solved by linear programming.  With the payoffs
;;; shifted to be positive, the column player's optimal strategy is q / sum q
;;; for the solution q of: maximize sum q_j subject to A q <= 1, q >= 0; the
;;; row player's is given by the dual variables, and the value of the
;;; shifted game is 1 / sum q.  The simplex method below works on exact
;;; rationals when the payoffs are rationals.

(defun simplex-maximize-packing (a)
  "Maximize sum_j x_j subject to A x <= 1 and x >= 0, for a matrix A of
  positive entries, by the simplex method with Bland's rule.  Returns the
  optimal x, the optimal dual variables y and the optimal value."
  (let* ((m (length a))
         (n (length (first a)))
         (rhs (+ n m))
         (tab (make-array (list (+ m 1) (+ n m 1)) :initial-element 0))
         (basis (make-array m)))
    ;; the constraint rows, with a slack variable each, and the objective row
    (loop for row in a
          for i from 0
          do (loop for x in row
                   for j from 0
                   do (setf (aref tab i j) x))
             (setf (aref tab i (+ n i)) 1
                   (aref tab i rhs) 1
                   (aref basis i) (+ n i)))
    (dotimes (j n) (setf (aref tab m j) -1))
    (loop
     (let ((enter (loop for j from 0 below (+ n m)
                        when (< (aref tab m j) -1e-12) return j))
           (leave nil))
       (unless enter (return))
       ;; the ratio test, ties broken by the smallest basic variable
       (dotimes (i m)
         (when (> (aref tab i enter) 1e-12)
           (when (or (null leave)
                     (< (/ (aref tab i rhs) (aref tab i enter))
                        (/ (aref tab leave rhs) (aref tab leave enter)))
                     (and (= (/ (aref tab i rhs) (aref tab i enter))
                             (/ (aref tab leave rhs) (aref tab leave enter)))
                          (< (aref basis i) (aref basis leave))))
             (setf leave i))))
       ;; pivot on (leave, enter)
       (let ((pivot (aref tab leave enter)))
         (dotimes (j (+ n m 1))
           (setf (aref tab leave j) (/ (aref tab leave j) pivot))))
       (dotimes (i (+ m 1))
         (unless (= i leave)
           (let ((factor (aref tab i enter)))
             (unless (zerop factor)
               (dotimes (j (+ n m 1))
                 (decf (aref tab i j) (* factor (aref tab leave j))))))))
       (setf (aref basis leave) enter)))
    (values (loop for j from 0 below n
                  collect (let ((i (position j basis)))
                            (if i (aref tab i rhs) 0)))
            (loop for i from 0 below m collect (aref tab m (+ n i)))
            (aref tab m rhs))))

(defun solve-zero-sum-game (payoff)
  "Solve the two-player zero-sum game in which the row player receives
  PAYOFF and the column player its negation.  Returns the value of the game
  for the row player, the row player's optimal mixed strategy (it maximizes
  the payoff it can guarantee) and the column player's (it minimizes the
  loss it can be forced to take)."
  (let* ((shift (- 1 (loop for row in payoff minimize (reduce #'min row))))
         (a (mapcar #'(lambda (row) (mapcar #'(lambda (x) (+ x shift)) row))
                    payoff)))
    (multiple-value-bind (q p total) (simplex-maximize-packing a)
      (values (- (/ 1 total) shift)
              (mapcar #'(lambda (pi-i) (/ pi-i total)) p)
              (mapcar #'(lambda (q-j) (/ q-j total)) q)))))

;;;; Cooperative Game Theory (Section 18.3)

;;; A cooperative game has a list of players and a characteristic function
;;; v, called with a coalition: a list of players, in the order of the list
;;; of all the players.

(defun coalitions (players)
  "All the subsets of the list PLAYERS, keeping their order."
  (if (null players)
      (list nil)
    (let ((rest (coalitions (rest players))))
      (append rest (mapcar #'(lambda (c) (cons (first players) c)) rest)))))

(defun count-factorial (n)
  (if (<= n 1) 1 (* n (count-factorial (- n 1)))))

(defun shapley-value (players v)
  "The Shapley value of the cooperative game (PLAYERS, V): each player gets
  its marginal contribution v(C + i) - v(C) averaged over all the orders in
  which the players can join the grand coalition, i.e., over the coalitions
  C without i, weighted by |C|! (n - |C| - 1)! / n!.  Returns an alist of
  (player . value)."
  (let ((n (length players)))
    (mapcar #'(lambda (i)
                (cons i
                      (loop for c in (coalitions (remove i players))
                            sum (* (/ (* (count-factorial (length c))
                                         (count-factorial (- n (length c) 1)))
                                      (count-factorial n))
                                   (- (funcall v (remove-if-not
                                                  #'(lambda (p) (or (eql p i) (member p c)))
                                                  players))
                                      (funcall v c))))))
            players)))

(defun in-core? (players v payoff &optional (tolerance 1e-9))
  "Is the alist PAYOFF of (player . share) in the core of the game
  (PLAYERS, V)?  It must share exactly v(N), and every coalition C must
  receive at least v(C), or C would be better off on its own."
  (flet ((share (c) (loop for i in c sum (cdr (assoc i payoff)))))
    (and (<= (abs (- (share players) (funcall v players))) tolerance)
         (every #'(lambda (c) (>= (share c) (- (funcall v c) tolerance)))
                (coalitions players)))))

;;;; Making Collective Decisions (Section 18.4)

(defun contract-net (tasks agents bid &key (better #'<))
  "The contract net protocol: for each task the manager announces it, every
  agent bids (BID agent task), a number or NIL when it does not bid, and
  the task is awarded to the best bid (the lowest cost, by default).
  Returns an alist of (task agent . bid), with NIL for a task without bids."
  (mapcar #'(lambda (task)
              (let ((best nil))
                (dolist (agent agents)
                  (let ((b (funcall bid agent task)))
                    (when (and b (or (null best) (funcall better b (cdr best))))
                      (setf best (cons agent b)))))
                (cons task best)))
          tasks))

(defun vickrey-auction (bids)
  "A sealed-bid second-price auction: the highest bidder of the alist BIDS
  of (bidder . bid) wins, and pays the second highest bid.  Returns the
  winner and the price."
  (let* ((ranked (sort (copy-list bids) #'> :key #'cdr))
         (winner (first ranked)))
    (values (car winner)
            (cdr (or (second ranked) winner)))))

;;; A ballot is a list of candidates, from the most to the least preferred.

(defun ballot-candidates (preferences)
  (remove-duplicates (apply #'append preferences) :from-end t))

(defun plurality-winner (preferences)
  "The candidate ranked first by the most voters."
  (the-biggest #'(lambda (c) (count c preferences :key #'first))
               (ballot-candidates preferences)))

(defun borda-winner (preferences)
  "The winner of the Borda count: with k candidates, a ballot gives k
  points to its first candidate, k - 1 to the second, down to 1."
  (the-biggest #'(lambda (c)
                   (loop for ballot in preferences
                         sum (- (length ballot) (position c ballot))))
               (ballot-candidates preferences)))

(defun condorcet-winner (preferences)
  "The candidate that beats every other in a pairwise majority vote, or
  NIL when majority preference is cyclic (Condorcet's paradox)."
  (let ((candidates (ballot-candidates preferences)))
    (flet ((beats (a b)
             (> (count-if #'(lambda (ballot)
                              (< (position a ballot) (position b ballot)))
                          preferences)
                (/ (length preferences) 2))))
      (find-if #'(lambda (a)
                   (every #'(lambda (b) (or (eql a b) (beats a b))) candidates))
               candidates))))

(defun alternating-offers-bargaining (discount-a discount-b)
  "The subgame-perfect equilibrium of the alternating-offers bargaining
  game over a pie of size 1, with discount factors DISCOUNT-A and
  DISCOUNT-B, when A makes the first offer: A keeps
  (1 - discount-b) / (1 - discount-a discount-b).  Returns the shares of
  A and of B."
  (let ((share-a (/ (- 1 discount-b) (- 1 (* discount-a discount-b)))))
    (values share-a (- 1 share-a))))
