-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenetics.c
64 lines (55 loc) · 1.92 KB
/
genetics.c
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
#include "genetics.h"
int uniform_select(int n)
{
return (int)((float)n * ((float)random() / (float)RAND_MAX));
}
int roulette_select(float *weights, int n_weights)
{
float rnd = random() / (float)RAND_MAX;
float total = weights[0];
int w = 0;
while(total < rnd && w < n_weights - 1) total += weights[++w];
return w;
}
void invert_weights(float *weights, int nweights, float *inverted_weights)
{
int i;
float total = 0.0f;
for(i = 0; i < nweights; ++i)
total += inverted_weights[i] = 1.0f - weights[i];
for(i = 0; i < nweights; ++i)
inverted_weights[i] /= total;
}
void generate_weights(struct tree *trees, int n_trees, float *weights)
{
int i;
float total = 0.0;
for(i = 0; i < n_trees; ++i) total += MAX(0.01, trees[i].score);
for(i = 0; i < n_trees; ++i) {
weights[i] = MAX(0.01, (float)trees[i].score) / total;
/* printf("score[%i] = %i : %f\n", i, trees[i].score, weights[i]); */
}
}
void crossover(struct tree *tree1, struct tree *tree2, struct tree *offspring)
{
int length1 = tree1->seed.rule_size * tree1->seed.num_rules;
int length2 = tree2->seed.rule_size * tree2->seed.num_rules;
int length_off = offspring->seed.rule_size * offspring->seed.num_rules;
int cross_point;
/* check that the trees are compatible */
if(length1 != length2) return;
if(length1 != length_off) {
/* Copy the structure from the first parent */
offspring->seed.rule_size = tree1->seed.rule_size;
offspring->seed.num_rules = tree1->seed.num_rules;
free_rule_set(&offspring->seed);
init_rule_set(&offspring->seed);
}
/* crossover - pick a point at the start/end of a rule */
cross_point = tree1->seed.rule_size *
(int)(tree1->seed.num_rules * (rand() / (float)RAND_MAX));
/* printf("Crossover at %i\n", cross_point); */
memcpy(offspring->seed.rules, tree1->seed.rules, cross_point);
memcpy(offspring->seed.rules + cross_point, tree2->seed.rules + cross_point,
length1 - cross_point);
}