| Path: | lib/charlie/list/list_crossover.rb |
| Last Update: | Fri May 09 14:21:11 +0200 2008 |
List crossovers: SinglePointCrossover, UniformCrossover, NPointCrossover
| TwoPointCrossover | = | NPointCrossover(2) |
| ThreePointCrossover | = | NPointCrossover(3) |
| BlendingCrossover | = | BlendingCrossover() |
Blending crossover, common in evolutionary strategies.
# File lib/charlie/list/list_crossover.rb, line 58
58: def BlendingCrossover(exploration_alpha=0.1,type=:cube)
59: sz_rand = 1 + 2 * exploration_alpha
60: Module.new{
61: self.name = "BlendingCrossover(#{exploration_alpha},#{type})"
62: if(type==:cube)
63: define_method(:cross){|parent1,parent2|
64: c1 = []; c2=[]; g1 = parent1.genes; g2 = parent2.genes
65: g1.each_with_index{|e,i|
66: y = rand*sz_rand - exploration_alpha
67: x2 = g2[i]
68: c1 << y*e + (1-y)*x2
69: c2 << y*x2 + (1-y)*e
70: }
71: [c1,c2].map{|x| from_genes(x) }
72: }
73: elsif(type==:line)
74: define_method(:cross){|parent1,parent2|
75: c1 = []; c2=[]; g1 = parent1.genes; g2 = parent2.genes
76: y = rand*sz_rand - exploration_alpha
77: g1.each_with_index{|e,i|
78: x2 = g2[i]
79: c1 << y*e + (1-y)*x2
80: c2 << y*x2 + (1-y)*e
81: }
82: [c1,c2].map{|x| from_genes(x) }
83: }
84: else
85: raise ArgumentError,"Invalid BlendingCrossover type #{type}"
86: end
87: }
88: end
n point crossover, returns two children.
# File lib/charlie/list/list_crossover.rb, line 14
14: def NPointCrossover(n=2)
15: Module.new{
16: self.name = "NPointCrossover(#{n})"
17: define_method(:cross){|parent1,parent2|
18: p1 = parent1.genes; p2 = parent2.genes
19: upper_bnd = p1.size + 1
20: cross_pts = (0...n).map{rand(upper_bnd)}.sort
21:
22: c1 = []; c2=[]
23: ([0] + cross_pts << upper_bnd).each_cons(2){|cp1,cp2|
24: c1 += p1[cp1...cp2]
25: c2 += p2[cp1...cp2]
26: p1,p2 = p2,p1
27: }
28: [c1,c2].map{|x| from_genes(x) }
29: }
30: }
31: end