simpleGA.rkt 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #lang typed/racket
  2. ;; A simple genetic algorithm
  3. ;; Computer Exercise #1 from Intro to GA by Mitchell
  4. ;;
  5. ;; Uses:
  6. ;; - fitness-proportionate selection
  7. ;; - routlette-wheel sampling
  8. ; The population is stored as a single list of popsize*chromlen elements
  9. (require math)
  10. ; population size and individual chromosome length
  11. (define popsize 100)
  12. (define chromlen 100)
  13. ; single-point crossover rate
  14. (define p-cross 0.7)
  15. ; bitwise mutation rate
  16. (define p-mutate 0.001)
  17. ; Fitness assessment is the number of 1's in the population member
  18. (: fitness (-> (Listof Integer) Real))
  19. (define (fitness member)
  20. (/ (sum member)
  21. (length member)))
  22. ; Flip a chromosome to its opposite
  23. (: flip-chrom (-> Integer Integer))
  24. (define (flip-chrom val)
  25. (if (eq? val 1) 0 1))
  26. ; mutate
  27. ; because of the way the population is stored and that mutations happen after
  28. ; offspring are produced, we can mutate the whole list together
  29. (: mutate (-> (Listof Integer) (Listof Integer)))
  30. (define (mutate pop)
  31. (for/list: : Listof Integer ([i : Index pop])
  32. ((λ (chrom)
  33. (if (<= (random) p-mutate)
  34. (flip-chrom i)
  35. i))
  36. i)))
  37. ; Initialize a random population.
  38. ;(: initpop (-> (Listof Integer)))
  39. ;(define initpop
  40. ; (for/list ([i (in-range (* popsize chromlen))])
  41. ; (random-integer 0 1)))