/* *alloc_pool *allocatesmemoryforGApool
*/
Pool *
alloc_pool(PlannerInfo *root, int pool_size, int string_length)
{
Pool *new_pool;
Chromosome *chromo; int i;
/* all gene */
chromo = (Chromosome *) new_pool->data; /* vector of all chromos */ for (i = 0; i < pool_size; i++)
chromo[i].string = palloc((string_length + 1) * sizeof(Gene));
return new_pool;
}
/* *free_pool *deallocatesmemoryforGApool
*/ void
free_pool(PlannerInfo *root, Pool *pool)
{
Chromosome *chromo; int i;
/* all gene */
chromo = (Chromosome *) pool->data; /* vector of all chromos */ for (i = 0; i < pool->size; i++)
pfree(chromo[i].string);
/* all chromosome */
pfree(pool->data);
/* pool */
pfree(pool);
}
/* *random_init_pool *initializegeneticpool
*/ void
random_init_pool(PlannerInfo *root, Pool *pool)
{
Chromosome *chromo = (Chromosome *) pool->data; int i; int bad = 0;
/* *Weimmediatelydiscardanyinvalidindividuals(thosethatgeqo_eval *returnsDBL_MAXfor),therebynotwastingpoolspaceonthem. * *Ifwefailtomakeanyvalidindividualsafter10000tries,giveup; *thisprobablymeanssomethingisbroken,andweshouldn'tjustlet *ourselvesgetstuckinaninfiniteloop.
*/
i = 0; while (i < pool->size)
{
init_tour(root, chromo[i].string, pool->string_length);
pool->data[i].worth = geqo_eval(root, chromo[i].string,
pool->string_length); if (pool->data[i].worth < DBL_MAX)
i++; else
{
bad++; if (i == 0 && bad >= 10000)
elog(ERROR, "geqo failed to make a valid plan");
}
}
#ifdef GEQO_DEBUG if (bad > 0)
elog(DEBUG1, "%d invalid tours found while selecting %d pool entries",
bad, pool->size); #endif
}
/* spread_chromo *insertsanewchromosomeintothepool,displacingworstgeneinpool *assumesbest->worst=smallest->largest
*/ void
spread_chromo(PlannerInfo *root, Chromosome *chromo, Pool *pool)
{ int top,
mid,
bot; int i,
index;
Chromosome swap_chromo,
tmp_chromo;
/* new chromo is so bad we can't use it */ if (chromo->worth > pool->data[pool->size - 1].worth) return;
/* do a binary search to find the index of the new chromo */
top = 0;
mid = pool->size / 2;
bot = pool->size - 1;
index = -1;
while (index == -1)
{ /* these 4 cases find a new location */
if (chromo->worth <= pool->data[top].worth)
index = top; elseif (chromo->worth == pool->data[mid].worth)
index = mid; elseif (chromo->worth == pool->data[bot].worth)
index = bot; elseif (bot - top <= 1)
index = bot;