Advertisement
_eremec_

Untitled

Jun 17th, 2019
3,386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns gen.core)
  2.  
  3. (def conf
  4.   {:w1 0.7
  5.    :w2 0.3
  6.    :num-of-gen 5
  7.    :chs-num 6
  8.    :sel-num 4
  9.    :vec-len 5
  10.    :prob-of-cross 0.7
  11.    :prob-of-mut 0.3
  12.    :count-of-pairs 2})
  13.  
  14. (letfn [(f [x j]
  15.           (->> (* 6 Math/PI (first x))
  16.                (+ (/ (* j Math/PI) (count x)))
  17.                (Math/sin)
  18.                (- (nth x j))
  19.                (#(Math/pow % 2))))]
  20.   (defn f1 [x]
  21.     (let [j1 (range 1 (count x) 2)]
  22.       (->> (map (partial f x) j1)
  23.            (reduce +)
  24.            (* (/ 2 (count j1)))
  25.            (+ (first x)))))
  26.   (defn f2 [x]
  27.     (let [j2 (range 2 (count x) 2)]
  28.       (->> (map (partial f x) j2)
  29.            (reduce +)
  30.            (* (/ 2 (count j2)))
  31.            (+ (- 1 (-> x first Math/sqrt)))))))
  32.  
  33. (defn fit-fn [x]
  34.   (+ (* (:w1 conf) (f1 x))
  35.      (* (:w2 conf) (f2 x))))
  36.  
  37. (defn init-generation [vec-len n]
  38.   (repeatedly n #(->> (fn [] (dec (rand 2)))
  39.                       (repeatedly (dec vec-len))
  40.                       ((fn [v] (conj v (rand)))))))
  41.  
  42. (defn select-population [gen n]
  43.   (->> (sort-by fit-fn gen)
  44.        (reverse)
  45.        (take n)))
  46.  
  47. (defn mutate [ch]
  48.   (-> (map #(+ % (* (dec (rand 2)) (rand 0.1))) (rest ch))
  49.       (conj (+ (first ch) (* (rand) (rand 0.1))))))
  50.  
  51. (defn crossing-over [[ch1 ch2]]
  52.   (map #(map + (map * ch1 (repeat %))
  53.                (map * ch2 (repeat (- 1 %))))
  54.        (repeatedly (:vec-len conf) rand)))
  55.  
  56. (defn handle-pair [pair]
  57.   (if (< (rand) (:prob-of-cross conf))
  58.       (if (< (rand) (:prob-of-mut conf))
  59.           (map mutate (crossing-over pair))
  60.           (crossing-over pair))
  61.       pair))
  62.  
  63. (defn new-generation
  64.   ([] (new-generation (init-generation (:vec-len conf) (:chs-num conf))))
  65.   ([gen] (->> (select-population gen (:sel-num conf))
  66.               ((fn [sel] (map (fn [el] [(rand-nth sel) (rand-nth sel)]) sel)))
  67.               (map handle-pair))))
  68.  
  69. (loop [n (:num-of-gen conf)
  70.        gen (new-generation)]
  71.   (if (zero? n) gen (recur (dec n) (new-generation gen))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement