NB. Simple genetic algorithm
NB. by Tracy B. Harms, March 2008
NB. Thanks to Forrest H Bennett for design guidance.
 
N =:  50    NB. population size
G =:  20    NB. number of genes in a genome
M =:   0.01 NB. mutation rate
S =:   3    NB. selection size
R =:   2    NB. range of gene variation
D =:1000    NB. default limit on number of generations
 
X =: ((G-1), 2*G) $ 1,(G$0),G$1   NB. crossover masks
 
ga=: verb define
D ga y
:
ThisGen=. 0
Pf=. judge Population=. ? (N,G) $ R
while. (-. 0 e. Pf) *. x>ThisGen do.
  ThisGen=. >:ThisGen
  Population=. mutate Population breed select Pf
  Pf=. judge Population   
end.
ThisGen, (<./Pf), (+/ % #) Pf     NB. report results
)
 
judge=: G - +/"1    NB. fitness function
NB. one max -- perfect where *./"1
 
select=: verb define
Rivals=. ? (2,N,S) $ N
Best  =. (= <./)"1 Rivals { y
>./"1 Best #"1 Rivals
)
 
breed=: dyad define
ParentGenomes=. ((0{y){x),.(1{y){x
Crossovers=. X {~ ? N $ G-1
Crossovers #"1 1 ParentGenomes
)
 
mutate=: verb define
Mt=.# Mi=. I. M >: ? N $ 0
Mm=. <"1(Mi ,. (? Mt $ G))
if. 0=$Mm do.  y  else.  (? Mt $ R) Mm} y  end.
)
 
Note 'elaboration on short variable names'
Pf  -- evaluated fitness of current population
Mi  -- indexes of mutants in new generation
Mt  -- tally of mutants
Mm  -- index/gene-location pairs
)

TracyHarms/GA1 (last edited 2011-02-09 14:42:55 by TracyHarms)