gamete_pointer method3( gamete_pointer base_gamete, gamete_pointer other_gamete, unsigned int gen ) { unsigned int nMut = m_rng->nextPoisson(m_mu); unsigned int nRec = 0; if( base_gamete != other_gamete ) { nRec = m_rng->nextPoisson( m_rho ); if( m_rng->nextBool() ) std::swap( base_gamete, other_gamete); } if( nMut == 0 && nRec == 0) { // no recombination or mutation // therefore randomly copy one of them return base_gamete->copy(); } gamete_pointer res = NULL; if( nRec ) { if( nMut ) { res = new gamete_type( base_gamete->getAlphabet() ); typename recombination_method_type::result_type status; recombine( base_gamete, other_gamete, res->getBits(), nRec, status ); mutate( res, nMut ); } else { // recombination only typename gamete_type::bitset_type recombined_set; typename recombination_method_type::result_type status; recombine( base_gamete, other_gamete, &recombined_set, nRec, status ); if( status.is_empty ) { res = gamete_type::EMPTY.copy(); } else if( status.match_base ) { res = base_gamete->copy(); } else if( status.match_alt ) { res = other_gamete->copy(); } else { // this does not guarantee that the gamete will be unique in the population // there is a rare(?) scenario under which this new gamete will be identical // to another gamete in the population. // // Under the infinite site model, two identical child gametes can be produced // when a pair of parents produce multiple children, but recombination events // occur such at locations which result in the same output sequence. This is // rare because a) both parents must use the same "base" gamete for each // child (.5^C), and b) all of the randomly generated recombination events // need to occur in the same regions relative to the parent's mutations. res = new gamete_type( recombined_set, base_gamete->getAlphabet() ); } } } else { // mutation only res = base_gamete->clone(); mutate( res, nMut ); } assert( res != NULL ); return res; }
std::vector<sensor_msgs::Image::Ptr> Recombiner::operator() (const stdr_msgs::LadybugImages & raw_images) { std::vector<sensor_msgs::Image::Ptr> bayer_images; recombine(raw_images, bayer_images); return bayer_images; }
static ERL_NIF_TERM recombine_solutions(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]){ // long diff; // struct timespec start, end; // clock_gettime(CLOCK_MONOTONIC, &start); ERL_NIF_TERM terms[2]; ErlNifResourceType* sol_type; Solution *sols[2], *new_sols[2]; // arrays of two pointers of type Solution* unsigned int i; unsigned int len; CHECK(env, argc == 2) sol_type = (ErlNifResourceType*) enif_priv_data(env); CHECK(env, sol_type) // read parent solutions for (i=0; i<2; i++){ CHECK(env, enif_get_resource(env, argv[i], sol_type, (void**) &sols[i])) } #ifdef DEBUG print_solution(sols[0],"Genotype1"); print_solution(sols[1],"Genotype2"); #endif // allocate 2 child solution structures len = sols[0]->len; for (i=0; i<2; i++){ new_sols[i] = (Solution*) enif_alloc_resource(sol_type, sizeof(Solution)); CHECK(env, new_sols[i]) terms[i] = enif_make_resource(env, new_sols[i]); CHECK(env,terms[i]) enif_release_resource(new_sols[i]); new_sols[i]->len = len; new_sols[i]->genotype = (double*) malloc(sizeof(double)*len); } recombine(sols, new_sols); #ifdef DEBUG print_solution(new_sols[0],"RecombinedGenotype1"); print_solution(new_sols[1],"RecombinedGenotype2"); #endif // clock_gettime(CLOCK_MONOTONIC, &end); // diff = CLOCKS_PER_SEC * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec; // printf("reco=%llu\n", (long long unsigned int) diff); return enif_make_tuple2(env, terms[0], terms[1]); }
gamete_pointer recombine( gamete_pointer base_gamete, gamete_pointer other_gamete, unsigned int nRec, unsigned int gen = 0 ) { typename gamete_type::bitset_type symm_diff; #ifdef LOGGING typename recombination_method_type::result_type status(gen); #else typename recombination_method_type::result_type status; #endif recombine( base_gamete, other_gamete, &symm_diff, nRec, status ); gamete_pointer res = new gamete_type( symm_diff, base_gamete->getAlphabet() ); return res; }
gamete_pointer method2( gamete_pointer base_gamete, gamete_pointer other_gamete, unsigned int gen ) { #ifdef LOGGING static unsigned int nCalls = 0; std::ostringstream oss; oss << gen << "." << nCalls++; std::string log_key = oss.str(); #endif unsigned int nMut = m_rng->nextPoisson( m_mu ); unsigned int nRec = (( base_gamete == other_gamete) ? 0 : m_rng->nextPoisson(m_rho)); if( base_gamete != other_gamete && m_rng->nextBool() ) { // have different gametes; therefore should randomly swap them std::swap( base_gamete, other_gamete ); } if( nMut == 0 && nRec == 0) { // no recombination or mutation // therefore randomly copy one of them return base_gamete->copy(); } gamete_pointer res = NULL; if( nRec > 0 ) { #ifdef LOGGING global_log.put( log_key + ".recombine", true); #endif res = recombine( base_gamete, other_gamete, nRec, gen ); if( nMut ) { #ifdef LOGGING global_log.put( log_key + ".mutate", true); #endif mutate(res, nMut); } } else { #ifdef LOGGING global_log.put( log_key + ".mutate", true); #endif res = base_gamete->clone(); mutate(res, nMut); } #ifdef LOGGING oss.str(""); oss.clear(); oss << *res->getBits(); global_log.put( log_key + ".new_gamete.sequence", oss.str()); global_log.put( log_key + ".new_gamete.size", res->getBits()->size() ); global_log.put( log_key + ".new_gamete.count", res->getBits()->count() ); if( base_gamete->getBits()->count() > 0 && other_gamete->getBits()->count() > 0) { oss.str(""); oss.clear(); oss << *base_gamete->getBits(); global_log.put( log_key + ".base_gamete.sequence", oss.str()); global_log.put( log_key + ".base_gamete.size", base_gamete->getBits()->size() ); global_log.put( log_key + ".base_gamete.count", base_gamete->getBits()->count() ); oss.str(""); oss.clear(); oss << *other_gamete->getBits(); global_log.put( log_key + ".other_gamete.sequence", oss.str()); global_log.put( log_key + ".other_gamete.size", other_gamete->getBits()->size() ); global_log.put( log_key + ".other_gamete.count", other_gamete->getBits()->count() ); } #endif return res; }
/** * Main optimization loop * @param essProblem Contains all the variables needed by eSS * @param inp Objective function `inp` struct * @param out Objective function `out` struct */ void run_eSS(eSSType *eSSParams, void *inp, void *out){ int label[eSSParams->n_refSet]; /*!< Uses to store the index of Individuals that should be replaced with their children. */ memset(label, 0, eSSParams->n_refSet * sizeof(int)); int candidate_index; /*!< Store the index of candidate for replacement after recombination. */ int n_currentUpdated; /*!< Counter for all updated solutions either from recombination or goBeyond procedure. */ int archive_index = 0; /*!< Track the index of `archiveSet` for storing the best solutions found. */ /** * It sets to 0 at first, and then increments until it hits the 100. Because we don't wanted * to spend time and checking archive members that are not already assigned! */ eSSParams->archiveSet->size = 0; for (eSSParams->iter = 1; eSSParams->iter < eSSParams->max_iter; ++eSSParams->iter) { n_currentUpdated = 0; // int i_lCandidate = 0; for (int i = 0; i < eSSParams->n_refSet; ++i) { /** * Generate a candidate set by combining the `i`th member of the refSet and returning * the best candidate with respect to it's cost. */ candidate_index = recombine(eSSParams, &(eSSParams->refSet->members[i]), i, inp, out); if (-1 != candidate_index){ eSSParams->stats->n_successful_recombination++; label[i] = 1; n_currentUpdated++; /** * Copy the selected candidate into the childSet */ copy_Ind(eSSParams, &(eSSParams->childsSet->members[i]), &(eSSParams->candidateSet->members[candidate_index])); /** * goBeyond for already selected candidate from recombinedSet which is copied to * the childsSet too. Note that the goBeyond function works with childsSet so it * need the `i` as a index not the `candidate_index` */ if (eSSParams->goBeyond_freqs != 0 && (eSSParams->iter % eSSParams->goBeyond_freqs == 0)) goBeyond(eSSParams, i, inp, out); /** * TODO: Implement the local search selection routine as described in the paper */ // copy_Ind(eSSParams, &(eSSParams->localSearchCandidateSet->members[i_lCandidate]), &(eSSParams->childsSet->members[i])); // i_lCandidate++; // eSSParams->localSearchCandidateSet->size = i_lCandidate; /** * Check if the local search is activated and it is not activated only for best * sol, if so, then check if it's a right moment to run the local search based on * n1, and n2 values. * Note that the local search won't apply here if it meant to apply only on best * sol. */ if ( (eSSParams->perform_local_search && !eSSParams->local_onBest_Only) && ( (eSSParams->iter > eSSParams->local_N1) || ( eSSParams->iter % eSSParams->local_N2 == 0 ) ) ) { /** * This check will prevent the local search operation if the cost of the Individual * is greater than some value. */ if (eSSParams->childsSet->members[i].cost < eSSParams->local_minCostCriteria ){ /** * Check if the selected child is close to the area that already the * local search applied on it or not */ /////////////////////////////////////// /// Flatzone Detection /// /////////////////////////////////////// if (eSSParams->perform_flatzone_check){ if ( !is_in_flatzone(eSSParams, eSSParams->refSet, &(eSSParams->childsSet->members[i])) ){ goto local_search; local_search: if ( -1 == is_exist(eSSParams, eSSParams->archiveSet, &(eSSParams->childsSet->members[i])) ) { if (eSSParams->local_SolverMethod == 'n'){ neldermead_localSearch(eSSParams, &(eSSParams->childsSet->members[i]), inp, out); eSSParams->stats->n_local_search_performed++; }else if (eSSParams->local_SolverMethod == 'l'){ levmer_localSearch(eSSParams, &(eSSParams->childsSet->members[i]), inp, out); eSSParams->stats->n_local_search_performed++; } }else{ eSSParams->stats->n_duplicate_found++; } } }else{ goto local_search; } } } } } /** * Update the refSet Individual based on the indexes flagged in `label`, if the n_stuck is * greater than the max_stuck then the Individual will add to the archiveSet and then randomizes and n_not_randomized and all it's statistics will set to zero. */ for (int i = 0; i < eSSParams->n_refSet; ++i) { /** * If an Individual marked, it will replace by its improved child */ if (label[i] == 1){ /** * Check if the candidate is very close to a member of a refSet, if so, then randomize the * duplicated members in refSet. */ int duplicate_index = is_exist(eSSParams, eSSParams->refSet, &(eSSParams->childsSet->members[i])); if ((duplicate_index != -1) && (duplicate_index != i) && (duplicate_index != 0)){ eSSParams->stats->n_duplicate_found++; // TODO: I can do this better by picking a random value based on the frequency matrix; then I can promote areas that are not discovered enough yet. random_Ind(eSSParams, &(eSSParams->refSet->members[duplicate_index]), eSSParams->min_real_var, eSSParams->max_real_var); evaluate_Individual(eSSParams, &(eSSParams->refSet->members[duplicate_index]), inp, out); } /** * Replace the parent with its better child! If it does pass the flatzone_detection_test */ if (eSSParams->perform_flatzone_check){ // todo: maybe i dont need to check this again since i already did it above then i wanted to perform the local search but if the local search is not active the i have to do it. if (!is_in_flatzone(eSSParams, eSSParams->refSet, &(eSSParams->childsSet->members[i]))) { goto replace; replace: eSSParams->refSet->members[i].n_not_randomized++; copy_Ind(eSSParams, &(eSSParams->refSet->members[i]), &(eSSParams->childsSet->members[i])); eSSParams->refSet->members[i].n_stuck = 0; } }else{ goto replace; } label[i] = 0; }else{ /** * Otherwise, the Individual randomzies and all of it's stats and counters set * to 0. If the flag `perform_elite_presevation` is set true then the first `mac_preserve_elite` will * be preserved in the refSet. */ eSSParams->refSet->members[i].n_stuck++; if (eSSParams->refSet->members[i].n_stuck > eSSParams->max_stuck && (eSSParams->iter % eSSParams->n_randomization_Freqs == 0 ) && !( eSSParams->perform_elite_preservation && !(i > eSSParams->max_preserve_elite)) ) { /* Add the stuck Individual to the archiveSet */ if (archive_index == eSSParams->n_archiveSet) archive_index = 0; if ((archive_index < eSSParams->n_archiveSet) && (eSSParams->archiveSet->size < eSSParams->n_archiveSet)) eSSParams->archiveSet->size++; copy_Ind(eSSParams, &(eSSParams->archiveSet->members[archive_index]), &(eSSParams->refSet->members[i])); archive_index++; /** * Randomize the stuck refSet member. */ random_Ind(eSSParams, &(eSSParams->refSet->members[i]), eSSParams->min_real_var, eSSParams->max_real_var); evaluate_Individual(eSSParams, &(eSSParams->refSet->members[i]), inp, out); /* Store number of all the stuck parameters. */ eSSParams->stats->n_total_stuck++; eSSParams->refSet->members[i].n_not_randomized = 0; eSSParams->refSet->members[i].n_stuck = 0; } label[i] = 0; } } quickSort_Set(eSSParams, eSSParams->refSet, 0, eSSParams->n_refSet - 1, 'c'); /** * Apply the local search on the best solution * The last condition avoid performing local search on solutions that are stuck, since * the local search algorithm couldn't keep the parameters in boundary so, we have to stop * over-applying it on solutions before make them really far from defined box constratins. */ if (eSSParams->perform_local_search && eSSParams->local_onBest_Only && (eSSParams->best->cost < eSSParams->local_minCostCriteria) && eSSParams->best->n_stuck < eSSParams->max_stuck) // avoid performing local search on the best solution which is stuck for a long time { neldermead_localSearch(eSSParams, eSSParams->best, inp, out); eSSParams->stats->n_local_search_performed++; } if (eSSParams->iter % eSSParams->save_freqs == 0){ write_Set(eSSParams, eSSParams->refSet, refSet_history_file, eSSParams->iter); write_Ind(eSSParams, eSSParams->best, best_sols_history_file, eSSParams->iter); } /** * Check if the best solution found is enough to the predicted solution. Usually this is * not a good way to check the convergence of stochastic method but it the problem wasn't * a multi-models problem then it saves a lot of unnecessary iterations. */ if (eSSParams->perform_cost_tol_stopping && fabs( eSSParams->best->cost - eSSParams->sol ) < eSSParams->cost_tol ){ printf("%s\n", KRED); printf("Best Solutions converged after %d iterations\n", eSSParams->iter); printf("%s\n", KNRM); break; } /** * Check the difference between the cost of best solution and worst solution in the * refSet. This might not always be the indication of the convergence but it might be * the indication of saturated referenceSet. */ // if ( eSSParams->perform_refSet_convergence_stopping && // fabs( eSSParams->refSet->members[0].cost - fabs(eSSParams->refSet->members[eSSParams->n_refSet - 1].cost)) < eSSParams->refSet_convergence_tol ){ // printf("Converged or Stuck after %d iteration!\n", eSSParams->iter); // break; // } /** * Compute the mean and standard deviation of the set in order to decide if the * randomization should be applied or not. */ if (eSSParams->compute_Set_Stats){ compute_SetStats(eSSParams, eSSParams->refSet); fprintf(ref_set_stats_history_file, "%lf\t%lf\n", eSSParams->refSet->mean_cost, eSSParams->refSet->std_cost); /** * Check if the standard deviation of the set is small and the number of * updatedMembers is less than 1/4 of the n_refSet then randomize the refSet. * After randomization all the n_not_randomized values of refSet Individual will * set to 0. */ if (eSSParams->perform_refSet_randomization && eSSParams->refSet->std_cost < eSSParams->refSet_std_tol && n_currentUpdated < (eSSParams->n_refSet / 4)){ /** * Replace the last max_delete members of the refSet with the newly * randomized solutions in and sort the refSet at the end of the replacement. */ for (int i = eSSParams->refSet->size - 1; i > eSSParams->refSet->size - eSSParams->max_delete; --i) { random_Ind(eSSParams, &(eSSParams->refSet->members[i]), eSSParams->min_real_var, eSSParams->max_real_var); evaluate_Individual(eSSParams, &(eSSParams->refSet->members[i]), inp, out); } quickSort_Set(eSSParams, eSSParams->refSet, 0, eSSParams->refSet->size - 1, 'c'); eSSParams->stats->n_refSet_randomized++; } // update_IndsStats(eSSParams, eSSParams->refSet); // todo: i can remove this, i dont do anything with it. } if (eSSParams->iter % eSSParams->print_freqs == 0){ print_Stats(eSSParams); } write_Stats(eSSParams, stats_file); } printf("Final refSet: \n"); print_Set(eSSParams, eSSParams->refSet); printf("bestSol: \n"); print_Ind(eSSParams, eSSParams->best); print_Stats(eSSParams); /** * Performing the local search on the bestSol. */ if (eSSParams->perform_local_search && eSSParams->local_atEnd && !eSSParams->local_onBest_Only) { printf("Perforimg the last local search\n"); if (eSSParams->local_SolverMethod == 'n') neldermead_localSearch(eSSParams, eSSParams->best, inp, out); else levmer_localSearch(eSSParams, eSSParams->best, inp, out); printf("Final Result: \n"); print_Ind(eSSParams, eSSParams->best); } refSet_final_file = fopen("ref_set_final.csv", "w"); write_Set(eSSParams, eSSParams->refSet, refSet_final_file, -1); write_Set(eSSParams, eSSParams->archiveSet, archive_set_file, -1); write_Ind(eSSParams, eSSParams->best, best_sols_history_file, eSSParams->max_iter); printf("ref_set_final.csv, ref_set_history_file.out, best_sols_history_file.out, and stats_file is generated. \n"); fclose(refSet_final_file); fclose(best_sols_history_file); fclose(stats_file); // fclose(file) }
void proptrj(char *fngro,char *fndat,t_topology *top,t_pinp *p) { static char *ppp[efhNR] = { "RAD", "TWIST", "RISE", "LEN", "NHX", "DIP", "RMS", "CPHI", "RMSA", "PHI", "PSI", "HB3", "HB4", "HB5" }; FILE *out; rvec **EV; real **evprj; atom_id *index; int natoms,nca,nSel,nframes,nev; rvec *xav,*vav; atom_id *ca_index,*bb_index; matrix box; char buf[256],*prop; double x; int i,j,d; nframes = p->nframes; nSel = p->nSel; nev = p->nev; prop=ppp[nSel]; evprj=read_proj(nev,nframes,p->base); get_coordnum(fngro,&natoms); snew(xav,natoms); snew(vav,natoms); read_conf(fngro,buf,&natoms,xav,vav,box); fprintf(stderr,"Successfully read average positions (%s)\n",buf); EV=read_ev(fndat,natoms); fprintf(stderr,"Successfully read eigenvectors\n"); snew(index,nev); for(i=0; (i<nev); i++) index[i]=i; snew(bb_index,natoms); for(i=0; (i<natoms); i++) bb_index[i]=i; snew(ca_index,natoms); for(i=nca=0; (i<natoms); i++) if ((strcmp("CA",*(top->atoms.atomname[i])) == 0)) ca_index[nca++]=i; switch (p->funct) { case ptMC: switch(nSel) { case efhRAD: optim_radius(nev,xav,EV,evprj,natoms,nca,ca_index,p); break; case efhRISE: optim_rise(nev,xav,EV,evprj,natoms,nca,ca_index,p); break; default: break; } break; case ptREC: recombine(p->recomb,p->gamma,p->nskip,nframes,nev,natoms, EV,evprj,xav,bb_index); break; case ptPTRJ: mkptrj(prop,nSel,natoms,xav,nframes, nev,EV,evprj,nca,ca_index,bb_index, top->atoms.atom,box); break; default: gmx_fatal(FARGS,"I Don't Know What to Do"); } }