-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopulation.rb
More file actions
130 lines (66 loc) · 1.9 KB
/
population.rb
File metadata and controls
130 lines (66 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
class Population
def initialize first_gen_, pop_size_, score_func_, mutate_func_
@generation = first_gen_
@pop_size = pop_size_ == nil ? first_gen.size : pop_size_
@score_func = score_func_
@mutate_func = mutate_func_
@iteration_count = 0
end
def mutate cur_gen
mutated = []
cur_gen.each{|individual|
mutated << @mutate_func.call(individual)
}
mutated.flatten!
mutated
end
def filtrate gen
gen = gen + @generation
gen.sort! {|x ,y| @score_func.call(y) <=> @score_func.call(x)}
gen[0..(@pop_size - 1)]
end
def fit
mutated_gen = mutate @generation
filtrated_gen = filtrate mutated_gen
until stable? filtrated_gen
@iteration_count += 1
@generation = filtrated_gen
mutated_gen = mutate @generation
filtrated_gen = filtrate mutated_gen
end
return filtrated_gen, @iteration_count
end
def stable? filtrated_gen
fit_count = 0
0.upto(@pop_size - 1){|idx|
if (@generation[idx] - filtrated_gen[idx]).abs <= 0.001 and
(@score_func.call(@generation[idx]) - @score_func.call(filtrated_gen[idx]).abs <= 0.001)
fit_count += 1
end
}
fit_count >= (0.1 * @pop_size).to_i
end
end
set_mutate_func = Proc.new {|individual|
prng = Random.new
probability = []
1.upto(10) {
gened = individual + prng.rand(-200000.0..200000.0)
if 1.0 <= gened and gened <= 200000.0
probability << gened
end
}
probability
}
score_fun = Proc.new {|x| x * Math.cos(x) + 2}
first_gen = []
prng = Random.new
1.upto(10000) {first_gen << prng.rand(-200000.0..200000.0)}
pop = Population.new first_gen, 10000, score_fun, set_mutate_func
puts 'Start evolving.'
final_pop, iteration_count = pop.fit
# puts final_pop
puts iteration_count
1.upto(10) {|idx|
print "Individual: #{final_pop[idx]}, Score: #{score_fun.call(final_pop[idx])}.\n"
}