Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ns gen.core)
- (def conf
- {:w1 0.7
- :w2 0.3
- :num-of-gen 5
- :chs-num 6
- :sel-num 4
- :vec-len 5
- :prob-of-cross 0.7
- :prob-of-mut 0.3
- :count-of-pairs 2})
- (letfn [(f [x j]
- (->> (* 6 Math/PI (first x))
- (+ (/ (* j Math/PI) (count x)))
- (Math/sin)
- (- (nth x j))
- (#(Math/pow % 2))))]
- (defn f1 [x]
- (let [j1 (range 1 (count x) 2)]
- (->> (map (partial f x) j1)
- (reduce +)
- (* (/ 2 (count j1)))
- (+ (first x)))))
- (defn f2 [x]
- (let [j2 (range 2 (count x) 2)]
- (->> (map (partial f x) j2)
- (reduce +)
- (* (/ 2 (count j2)))
- (+ (- 1 (-> x first Math/sqrt)))))))
- (defn fit-fn [x]
- (+ (* (:w1 conf) (f1 x))
- (* (:w2 conf) (f2 x))))
- (defn init-generation [vec-len n]
- (repeatedly n #(->> (fn [] (dec (rand 2)))
- (repeatedly (dec vec-len))
- ((fn [v] (conj v (rand)))))))
- (defn select-population [gen n]
- (->> (sort-by fit-fn gen)
- (reverse)
- (take n)))
- (defn mutate [ch]
- (-> (map #(+ % (* (dec (rand 2)) (rand 0.1))) (rest ch))
- (conj (+ (first ch) (* (rand) (rand 0.1))))))
- (defn crossing-over [[ch1 ch2]]
- (map #(map + (map * ch1 (repeat %))
- (map * ch2 (repeat (- 1 %))))
- (repeatedly (:vec-len conf) rand)))
- (defn handle-pair [pair]
- (if (< (rand) (:prob-of-cross conf))
- (if (< (rand) (:prob-of-mut conf))
- (map mutate (crossing-over pair))
- (crossing-over pair))
- pair))
- (defn new-generation
- ([] (new-generation (init-generation (:vec-len conf) (:chs-num conf))))
- ([gen] (->> (select-population gen (:sel-num conf))
- ((fn [sel] (map (fn [el] [(rand-nth sel) (rand-nth sel)]) sel)))
- (map handle-pair))))
- (loop [n (:num-of-gen conf)
- gen (new-generation)]
- (if (zero? n) gen (recur (dec n) (new-generation gen))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement