;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: search/algorithms/genetic.lisp

;;;; Genetic Algorithms

;;; An individual is a list of genes, each taken from a gene pool.  The
;;; fitness function maps an individual to a non-negative number, higher
;;; meaning fitter.

(defun genetic-algorithm (population fitness-fn
			  &key (gene-pool '(0 1)) (f-thres nil) (ngen 1000)
			       (pmut 0.1))
  "Evolve POPULATION for NGEN generations: each child comes from two
  parents chosen with probability proportional to their fitness, by
  crossover, and is mutated with probability PMUT.  Stop as soon as an
  individual reaches fitness F-THRES (if given).  Return the fittest
  individual. [Fig. 4.7]"
  (dotimes (i ngen)
    (let ((weights (mapcar fitness-fn population)))
      (setf population
	    (loop repeat (length population)
		  collect (genetic-mutate
			   (genetic-reproduce
			    (genetic-weighted-choice population weights)
			    (genetic-weighted-choice population weights))
			   gene-pool pmut))))
    (when f-thres
      (let ((fittest (the-biggest fitness-fn population)))
	(when (>= (funcall fitness-fn fittest) f-thres)
	  (return-from genetic-algorithm fittest)))))
  (the-biggest fitness-fn population))

(defun genetic-init-population (n gene-pool length)
  "A list of N random individuals of the given LENGTH."
  (loop repeat n
	collect (loop repeat length collect (random-element gene-pool))))

(defun genetic-weighted-choice (population weights)
  "Choose an individual with probability proportional to its weight
  (uniformly when all the weights are zero)."
  (let ((total (reduce #'+ weights)))
    (if (<= total 0)
	(random-element population)
      (let ((r (random (float total 1.0d0))))
	(loop for individual in population
	      for w in weights
	      do (decf r w)
	      when (< r 0) do (return individual)
	      finally (return (last1 population)))))))

(defun genetic-reproduce (x y)
  "Single-point crossover: a random prefix of X followed by the rest of Y."
  (let ((c (random (length x))))
    (append (subseq x 0 c) (nthcdr c y))))

(defun genetic-mutate (x gene-pool pmut)
  "With probability PMUT, replace a random gene of X by one of GENE-POOL."
  (if (>= (random 1.0) pmut)
      x
    (let ((child (copy-list x)))
      (setf (nth (random (length child)) child) (random-element gene-pool))
      child)))

(defun genetic-queens-fitness (q)
  "The number of non-attacking pairs of queens, where the queen of column i
  is in row (nth i Q); 28 for a solution of the 8-queens problem."
  (let ((n (length q))
	(count 0))
    (dotimes (c1 n count)
      (loop for c2 from (+ c1 1) below n do
	    (let ((r1 (nth c1 q))
		  (r2 (nth c2 q)))
	      (unless (or (= r1 r2) (= (abs (- r1 r2)) (- c2 c1)))
		(incf count)))))))
