(ns clojure-genetic-algorithms.core)



;yogthos: Dmitri Sotnikov (2013)
;Example of a simple GA using Clojure.
;A target phrase must be matched by evolution.
;https://github.com/yogthos/genetic-algorithm-example

(defn rand-in-range
  "generates a random value within the given range"
  [min max]
  (int (+ (* (Math/random) (inc (- max min))) min))); Math/random * (max - min + 1) + min

(comment  
  (Math/random);0.44281132755633723; 0.9376301916973543
  (int 3.4); 3
  (int 3.9); 3  
)


(defn mutator [c] 
  (if c
    (let [new-val ((if (> (rand) 0.5) + -)
                    (rand-int 5) (int c))]
      (char (cond 
              (> new-val 126) 126
              (< new-val 32) 32
              :else new-val)))
    (char (rand-in-range 32 126))))


(comment 
  
  (char? \a);true
  (int \1);49
  (int \9);57
  (int \a);97
  
  (if \c 6);6;; Everything except `false' and `nil' is true in boolean context.

  ((if (> (rand) 0.5) + -)
         (rand-int 5) (int 6));9 -6 9 8 10 9 9 7 -5

  ((if (> (rand) 0.5) + -); this boils down to + else -
            (rand-int 5) (int \r));-113

  (char 67);\C
  (char 33);\!
  (char 126);\~
  
  (char (rand-in-range 32 126));\; \& \> \m \L \h
   
  (mutator \v)
	\y
	(mutator \v)
	\z
	(mutator \v)
	\w
	(mutator \v)
	\space
	(mutator \v)
	\space
	(mutator \v)	
	\z
);end of comment;end of comment;end of comment



(defn- rank
  "ranks the population by fitness"
  [population]
  (reverse (sort-by :fitness population)))

(comment
  (rank (init-population 30 mutator fitness "$$$"))
  ; ({:value (\$ \( \n), :fitness -2}
  ;  {:value (\# \V \$), :fitness -2}
  ;  {:value (\s \b \>), :fitness -3})
  
);end of comment;end of comment;end of comment




(defn fitness [value target]
  (reduce 
    ;rank  is decremented when two symbols ( a and b) are different.
    (fn [rank [a b]] (if (= a b) rank (dec rank)))
    ;fn is applied by pairing the symbols of value and target
    0 (map vector value target))); rank starts at 0

(comment  
  
  (map inc [1 2 3 4 5]); (2 3 4 5 6)
   (map vector "abc" "123");([\a \1] [\b \2] [\c \3])

  (fitness "$$$" "45$");-2
  (fitness "$$$" "456");-3
  
);end of comment;end of comment;end of comment



(defn- mutate ;defn- same as defn, yielding non-public def
  "randomly mutates values in members of the population 
   using the mutator function"
  [population mutator threshold fitness target]
  (for [member population]
    ;threshold = mutation rate per individual per generation
    (if (< (rand) threshold)
      (let [value (map mutator (:value member))]
        {:value value
         :fitness (fitness value target)})
      member)))



(comment
  
  ;; prepare a seq of the even values 
  ;; from the first six multiples of three
  (for [x [0 1 2 3 4 5]
        :let [y (* x 3)]
        :when (even? y)]
    y);(0 6 12)
  
  (map mutator [\a\b\c]);((\d \space \g))
  
  (mutate (init-population 3 mutator fitness "$$$") 
           mutator 0.01 fitness "$$$")
	 ; ({:value (\E \^ \G), :fitness -3}
	 ; {:value (\: \O \g), :fitness -3}
	 ; {:value (\) \5 \s), :fitness -3})
);end of comment;end of comment;end of comment



(defn- update-vals; recombination of two members
  "randomly selects a value from either the first or the second member
  for each position,  preferring the first member, 
  as the front of the population is more fit"
  [fitness target {v1 :value} {v2 :value}]  
  (let [value (map #(if (> (rand) 0.3) %1 %2) v1 v2)]
    {:value value :fitness (fitness value target)}))

(comment  
  (map #(if (> (rand) 0.3) %1 %2) [\a\b\c] [\1\2\3]);(\a \2 \c)
);end of comment;end of comment;end of comment



(defn- mate; the populationis recombined
  "splits the population in half and mates all the members"
  [population fitness target]
  (apply map 
         (partial update-vals fitness target) 
         (split-at (/ (count population) 2) population)))

(comment
  
  (mate (rank (mutate (init-population 6 mutator fitness "RRRR")
               mutator 0.01 fitness "RRRR"))
   fitness "RRRR")
   ;({:value (\p \* \7 \S), :fitness -4}
   ;{:value (\z \u \u \L), :fitness -4}
   ;{:value (\2 \F \i \l), :fitness -4})
  
  );end of comment;end of comment;end of comment




(defn- evolve-step
  "mutate the population, then promote top members and 
   add mated members to the end"
  [size population mutator threshold fitness target]
  (let [mutated (rank (mutate population mutator threshold fitness target))        
        promote-size (/ size 5)
        keep-size (- (/ size 2) promote-size)
        [xs ys] (split-at keep-size mutated)]
    (println (first population))
    (concat xs (take promote-size ys) (mate mutated fitness target))))


(comment
  (evolve-step 3 (init-population 3 mutator fitness "$$$") 
               mutator 0.01 fitness "$$$")
  ; {:value (F i W), :fitness -3}
  ; ({:value (\' \q \L), :fitness -3}
  ; {:value (\L \A \O), :fitness -3}
  ; {:value (\' \q \L), :fitness -3})
  
);end of comment;end of comment;end of comment




(defn- gen-member; structure with 2 entries: value (seq)  and fitness (int)
  "generates a new member for the population"
  [mutator fitness target]
  (let [value (take (count target) (repeatedly #(mutator nil)))] 
    {:value value :fitness (fitness value target)}))

(comment
  (take 5 (repeatedly #(rand-int 11)))
  ;;=> (6 6 3 9 8)

  (repeat 5 (rand-int 100))
  ;(94 94 94 94 94)
  
  (take (count "$$$") (repeatedly #(mutator nil)))
  ;(\s \r \o)
  
  (gen-member mutator fitness "$$$")
  ;{:value (\i \space \x), :fitness -3}
  
);end of comment;end of comment;end of comment





(defn- init-population
  "creates a new population"
  [size mutator fitness target]
  (rank (take size (repeatedly #(gen-member mutator fitness target)))))

(comment 
  (take 3 (repeatedly #(gen-member mutator fitness "$$$")))
	({:value (\V \% \9), :fitness -3}
	 {:value (\! \H \J), :fitness -3}
	 {:value (\; \m \$), :fitness -2})

 
 (rank (take 30 (repeatedly #(gen-member mutator fitness "$$$"))))
 ({:value (\$ \+ \N), :fitness -2}
  {:value (\+ \L \,), :fitness -3}
  {:value (\G \6 \-), :fitness -3})
  
  (init-population 3  mutator fitness "$$$$")
	({:value (\R \a \U \l), :fitness -4}
	 {:value (\y \v \L \s), :fitness -4}
	 {:value (\c \] \l \C), :fitness -4})
);end of comment;end of comment;end of comment


(defn evolve
  "evolves the population until at least one member is fit"
  [size threshold mutator fitness target]
  (loop [population (init-population size mutator fitness target)]; initialization   
    (if (zero? (:fitness (first population))); fitness = 0 means end of loop
      population 
      (recur (evolve-step size population mutator threshold fitness target)))))


(comment  
  (evolve 100 0.01 mutator fitness "$$$$");long computing
  (evolve 1000 0.01 mutator fitness "Hello World!");long computing
);end of comment;end of comment;end of comment



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


(ns clojure-genetic-algorithms.core-test
(:use clojure.test clojure-genetic-algorithms.core))

(comment; moved to core
(defn mutator [c] 
  (if c
    (let [new-val ((if (> (rand) 0.5) + -)
                    (rand-int 5) (int c))]
      (char (cond 
              (> new-val 126) 126
              (< new-val 32) 32
              :else new-val)))
    (char (rand-in-range 32 126))))



(defn fitness [value target]
  (reduce 
    (fn [rank [a b]] (if (= a b) rank (dec rank)))
    0 (map vector value target)))
);end of comment


(deftest evolve-string
  (is 
    (= "Hello World!"
     (->> (evolve 1000 0.01 mutator fitness "Hello World!")
       time
       first
       :value
       (apply str)))))

(comment
  
  (time (Thread/sleep 100)); "Elapsed time: 100.208438 msecs"
  
  (def my-strings ["str1" "str2" "str3"])
      (apply str my-strings);str1str2str3
      
   (evolve-string);full computing
  )

  
  