// iterate over one evolution of the search algorithm void gasearch_evolve(gasearch _g) { // Inject random chromosome at end chromosome_init_random(_g->population[_g->population_size-1]); // Crossover gasearch_crossover(_g); // Mutation gasearch_mutate(_g); // Evaluation gasearch_evaluate(_g); // Rank gasearch_rank(_g); if ( optim_threshold_switch(_g->utility_opt, _g->utility[0], _g->minimize) ) { // update optimum _g->utility_opt = _g->utility[0]; // copy optimum chromosome chromosome_copy(_g->population[0], _g->c); #if LIQUID_DEBUG_GA_SEARCH printf(" utility: %0.2E", _g->utility_opt); chromosome_printf(_g->c); #endif } }
// Execute the search // _g : ga search object // _max_iterations : maximum number of iterations to run before bailing // _tarutility : target utility float gasearch_run(gasearch _g, unsigned int _max_iterations, float _tarutility) { unsigned int i=0; do { i++; gasearch_evolve(_g); } while ( optim_threshold_switch(_g->utility[0], _tarutility, _g->minimize) && i < _max_iterations); // return optimum utility return _g->utility_opt; }
float qnsearch_run(qnsearch _q, unsigned int _max_iterations, float _target_utility) { unsigned int i=0; do { i++; qnsearch_step(_q); _q->utility = _q->get_utility(_q->userdata, _q->v, _q->num_parameters); } while ( optim_threshold_switch(_q->utility, _target_utility, _q->minimize) && i < _max_iterations); return _q->utility; }
// rank population by fitness void gasearch_rank(gasearch _g) { unsigned int i, j; float u_tmp; // temporary utility placeholder chromosome c_tmp; // temporary chromosome placeholder (pointer) for (i=0; i<_g->population_size; i++) { for (j=_g->population_size-1; j>i; j--) { if ( optim_threshold_switch(_g->utility[j], _g->utility[j-1], !(_g->minimize)) ) { // swap chromosome pointers c_tmp = _g->population[j]; _g->population[j] = _g->population[j-1]; _g->population[j-1] = c_tmp; // swap utility values u_tmp = _g->utility[j]; _g->utility[j] = _g->utility[j-1]; _g->utility[j-1] = u_tmp; } } } }
// sort values by index // _v : input values [size: _len x 1] // _rank : output rank array (indices) [size: _len x 1] // _len : length of input array // _descending : descending/ascending void optim_sort(float *_v, unsigned int * _rank, unsigned int _len, int _descending) { unsigned int i, j, tmp_index; for (i=0; i<_len; i++) _rank[i] = i; for (i=0; i<_len; i++) { for (j=_len-1; j>i; j--) { //if (_v[_rank[j]]>_v[_rank[j-1]]) { if ( optim_threshold_switch(_v[_rank[j]], _v[_rank[j-1]], _descending) ) { // swap elements tmp_index = _rank[j]; _rank[j] = _rank[j-1]; _rank[j-1] = tmp_index; } } } }