simpleGA.rkt 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #lang 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. (define (fitness member)
  19. (/ (sum member)
  20. (length member)))
  21. ; Flip a chromosome to its opposite
  22. (define (flip-chrom val)
  23. (if (eq? val 1) 0 1))
  24. ; mutate
  25. ; because of the way the population is stored and that mutations happen after
  26. ; offspring are produced, we can mutate the whole list together
  27. (define (mutate pop)
  28. (for/list ([i pop])
  29. ((λ (chrom)
  30. (if (<= (random) p-mutate)
  31. (flip-chrom i)
  32. i))
  33. i)))
  34. ; Initialize a random population.
  35. (define (initpop)
  36. (for/list ([i (in-range (* popsize chromlen))])
  37. (random-integer 0 2)))
  38. ; check mutation rate
  39. ; return the number of members that are different between pop1 and pop2
  40. (define (mcheck pop1 pop2)
  41. (for/list ([i (length pop1)])
  42. (if (eq? (list-ref pop1 i) (list-ref pop2 i))
  43. 0
  44. 1)))
  45. ; testing/debugging code below
  46. (define pop (initpop))
  47. (define mutated (mutate pop))
  48. (define (actualmutrate pop mutated)
  49. (/ (sum (mcheck pop mutated)) (* popsize chromlen)))
  50. (write-string (string-append (real->decimal-string (actualmutrate pop mutated))
  51. "\n"))