#include #include #include "gp.h" static int cmp_fitness(const void *d1, const void *d2) { const gp_indiv_t *i1 = d1, *i2 = d2; return i1->fitness > i2->fitness; } static void gp_sort(gp_pop_t *pop) { qsort(pop->indiv, pop->len, sizeof(gp_indiv_t), cmp_fitness); } void gp_setup(gp_pop_t *pop) { int n; pop->indiv = malloc(sizeof(gp_indiv_t) * pop->len); for(n = 0; n < pop->len; n++) { pop->indiv[n].data = pop->create(); pop->indiv[n].fitness = pop->score(pop->indiv[n].data); } pop->pop_cnt = 0; gp_sort(pop); } void gp_iterate(gp_pop_t *pop) { int n, s, delay; pop->pop_cnt++; /* kill the weakest few and replace them with the strongests */ for(delay = s = 0, n = pop->len - pop->weak_kill - 1; n < pop->len; n++) { pop->clone(pop->indiv[n].data, pop->indiv[s].data); pop->mutate(pop->indiv[n].data); if (delay > pop->clone_times) { delay = 0; s++; } } /* score and sort */ for(n = s; n < pop->len; n++) pop->indiv[n].fitness = pop->score(pop->indiv[n].data); gp_sort(pop); } void gp_dump(FILE *f, gp_pop_t *pop, int max_dump) { int n; for(n = 0; n < pop->len; n++) { const char *dmp = NULL; if ((pop->dump != NULL) && (n < max_dump)) dmp = pop->dump(pop->indiv[n].data, pop->pop_cnt, n); if (dmp == NULL) dmp = "n/a"; fprintf(f, " #%03d %f %s\n", n, pop->indiv[n].fitness, dmp); } }