📄 gp.cc
字号:
// gp.cc File for common problem code, build with GPQUICK-2.1// W. Langdon cs.ucl.ac.uk 23 January 1995// based upon queue2.cc 20 Dec 1994 Revision: 1.57#define main_version "$Revision: 1.72 $"//Modifications (in reverse order)//WBL 31 Dec 96 If pTraceDupStats or pTracePStats or pTraceDStats// report every generation even if more than 50 //WBL 19 Dec 96 Add calling DisplayDupStats()//WBL 13 Apr 96 Use cout rather than sprint format best, works with float!//WBL 8 Apr 96 Add pSeeds//WBL 10 Dec 95 Undo r1.53 (remove ThisTest->write_stats() from do_gens//WBL 10 Dec 95 Quick and dirty fix for int scoretype after find_elite//WBL 20 Oct 95 BUG Notice save/restore does not use original test_seed//WBL 18 Oct 95 Support test_seed//WBL 10 Oct 95 Remove PRETTY_PARENS// Restore display of best every gen//WBL 22 Sep 95 Replace list.h by prob.h//WBL 29 Aug 95 mangle "calls" so can see fix to pareto.cc is in//WBL 6 Aug 95 Add saving of test.cc and list.cc globals in dumpfile//WBL 30 Jun 95 Add save_state and restart//WBL 20 Jun 95 Add calling gethostname//WBL 7 May 95 Add calling DisplayLPStats//WBL 1 May 95 Add support for DisplayPStats// Ensure no more than 50 intermediate reports are generated//WBL 19 Apr 95 Increase outputsize from 1000// in display_best_stats to 5000// in display_ellite and display_all_best to popsize//WBL 7 Apr 95 Add clearing pElitist before Load()//WBL 23 Mar 95 Add clearing pElitist before delete pop// Call either display_all_best or display_elite//WBL 12 Mar 95 Replace calling display_all_best by display_elite//WBL 12 Mar 95 In do_gens call new function display_best_stats inplace of// display_all_best. Do stats every gen rather than evry 5th//WBL 26 Feb 95 Use ThisPop//WBL 25 Feb 95 Bump output display_size of pareto front from 50 to 1000// hopefully temporaily!// Display stats etc only every 5 gens rather than every one//WBL 19 Feb 95 Replace all uses of BestMember by display_all_best// Add calling select_hits_write_stats//WBL 18 Feb 95 Add reporting number of duplicate chromes along pareto front//WBL 11 Feb 95 Get fitness() working//WBL 23 Jan 95 New file//requires MULTREE to be defined#include <sys/param.h>#include <unistd.h>//#include <procbuf.h> //located at /bham/pd/packages/gcc/lib/g++-include/#include <assert.h>#include "pch.h"#include "chrome.h"#include "primitiv.h"//pickup problem library#include "prob.h"//#include "Primitives.h"#include "gp.h"#include "test.h"//extern char scratch[100];#ifdef FASTEVAL// extern evalnode* IpGlobal;// extern Chrome* ChromeGlobal;#endifgp* ThisProblem;extern test* ThisTest;test* ThisTest;ChromeParams* ThisParams = new ChromeParams();float max_fitness = 0;Pop* ThisPop;//**************************************************************************///////////////////////// PROBLEM definitionvoid output_header(ostream& fout){ time_t start; fout << "\nGP ("<<main_version << flush; fout << ") to evolve a "<<ThisProblem->ProbVersion<<endl; time (&start); fout << ctime(&start) << flush;#ifdef MAXHOSTNAMELEN {char buffer[MAXHOSTNAMELEN]; fout << "Node " << flush; gethostname(buffer,sizeof(buffer)); fout << buffer << endl; }#else fout << "Node ?"<< endl;#endif}//end output_headervoid output_globals(ostream& fout){ fout<<current_phase<<endl; fout<<total_cpu<<endl; fout<<tests_run<<endl; fout<<tests_apparently_run<<endl; fout<<num_sol_found<<endl;}//end output globalsvoid delete_dumpfile(char* type){char dumpfile[2*(ChromeParams::param_str_size)+12];strcpy(dumpfile,ThisParams->params_str[pDumpfile1]);strcat(dumpfile,ThisParams->params_str[pDumpfile2]);strcat(dumpfile,type); //nb the other fileofstream fout(dumpfile); //Unix specificif(!fout) cerr <<"Failed to delete dumpfile "<<dumpfile<< flush;fout.close(); //well its of zero length, good enough}//end delete_dumpfileint save_state_count = 1;time_t last_save_time;void save_state(int phase_number) {time_t time_;time (&time_);if( ( (strlen(ThisParams->params_str[pDumpfile1])+ strlen(ThisParams->params_str[pDumpfile2]) )!=0) && ( ((time_ - last_save_time) > 3600 )|| //save once per hour// ( ((time_ - last_save_time) > 0 )|| //save once per sec (phase_number != 0 ) ) ) { char dumpfile[3*(ChromeParams::param_str_size)+12]; strcpy(dumpfile,ThisParams->params_str[pZipCmd]); strcat(dumpfile,ThisParams->params_str[pDumpfile1]); strcat(dumpfile,ThisParams->params_str[pDumpfile2]); if(phase_number != 0 ) { char buff [12]; sprintf(buff,".%d",phase_number); strcat(dumpfile,buff); } else if((++save_state_count&1) == 0) strcat(dumpfile,".A"); else strcat(dumpfile,".B"); BOOL ok = FALSE;#ifdef PROCBUF if(strlen(ThisParams->params_str[pZipCmd]) != 0) { procbuf popen_(dumpfile,ios::out); ostream fout( &popen_ ); if(!fout) cerr <<"Failed to open dumpfile "<<dumpfile <<" "<< ctime(&time_) << flush; else { cout <<"Writing dumpfile "<<dumpfile <<" "<< ctime(&time_) << flush; output_header(fout); fout<<ThisPop->gencount<<endl; ThisParams->params[pPopSeed] = gpquick_seed; //record seed used// cout << "gpquick_seed "<<gpquick_seed<<endl;//debug ThisParams->Save(fout); fout<<endl; //note end of params output_globals(fout); ThisPop->Write(fout,TRUE); //binary mode popen_.close(); ok = TRUE; } }else #endif //PROCBUF{ ofstream fout(dumpfile); if(!fout) cerr <<"Failed to open dumpfile "<<dumpfile <<" "<< ctime(&time_) << flush; else { cout <<"Writing dumpfile "<<dumpfile <<" "<< ctime(&time_) << flush; output_header(fout); fout<<ThisPop->gencount<<endl; ThisParams->params[pPopSeed] = gpquick_seed; //record seed used//cout << "gpquick_seed "<<gpquick_seed<<endl;//debug ThisParams->Save(fout); fout<<endl; //note end of params output_globals(fout); ThisPop->Write(fout,TRUE); //binary mode fout.close(); ok = TRUE; }} if(ok) { if(phase_number == 0) { //delete the other dump file if((save_state_count&1) != 0) delete_dumpfile(".A"); //nb the other file else delete_dumpfile(".B"); } else{ delete_dumpfile(".A"); //delete both files delete_dumpfile(".B"); //even if they dont exist! } time (&time_); cout <<" done "<< ctime(&time_) << endl; memcpy(&last_save_time,&time_,sizeof(time_)); }//endif fout ok}}//end save_statevoid skip_line(istream& fin, int num_lines){for(int l=0; l<num_lines;l++){ char c; for(c=fin.get(); (c != '\n') && (c != EOF); c=fin.get()) cout<<c;cout<<endl;};}//end skip_headerint load_save(istream& fin, int argc, char * argv[]){ skip_line(fin,4); int gencount_; fin>>gencount_; skip_line(fin,1); //discard rest of line ThisParams->Load(fin);// skip_line(fin,1);//restore paramters given on command line for(int i=0; i<argc;i++) { ThisParams->Load(argv[i]); } int c = fin.peek(); if( c == '-' || (c >= '0' && c <= '9')) { fin>>current_phase; fin>>total_cpu; fin>>tests_run; fin>>tests_apparently_run; fin>>num_sol_found; fin.get(); //discard eol } else cout << "Test global data missing from dumpfile\n"; if ((!fin) || (fin.peek()==EOF)) { cerr << "Format error on reading dumpfile\n"; exit(0); } gpquick_seed = ThisParams->params[pPopSeed]; int pop_size = ThisParams->params[pPopSize]; ThisPop = new Pop(ThisProblem,ThisParams,pop_size,&fin); cout << "Old pop -- loaded\n"; return gencount_;}int open_zipped(char* name, int argc, char * argv[]){ int gencount_ = -1;#ifdef PROCBUF BOOL loadfile; char dumpfile[3*(ChromeParams::param_str_size)+15]; strcpy(dumpfile,ThisParams->params_str[pDumpfile1]); strcat(dumpfile,ThisParams->params_str[pDumpfile2]); strcat(dumpfile,name); ifstream fin(dumpfile); loadfile = (fin && (fin.peek()!=EOF)); fin.close();if(loadfile){// cout<<dumpfile<<" ok"<<endl; strcpy(dumpfile,"cat "); strcat(dumpfile,ThisParams->params_str[pDumpfile1]); strcat(dumpfile,ThisParams->params_str[pDumpfile2]); strcat(dumpfile,name); strcat(dumpfile," | gunzip"); procbuf popen_(dumpfile,ios::in); istream fin( &popen_ ); if(!fin) cout<<"Failed to open loadfile "<<dumpfile<<endl; else { cout << "Loading old population from "<<dumpfile<<endl; gencount_ = load_save(fin, argc, argv); } popen_.close();}#else cout<<"gzip not supported"<<endl;#endifreturn gencount_;}//end open_zippedint open_dump (char* name, int argc, char * argv[]){ int gencount_ = -1; BOOL loadfile; char dumpfile[3*(ChromeParams::param_str_size)+15]; strcpy(dumpfile,ThisParams->params_str[pDumpfile1]); strcat(dumpfile,ThisParams->params_str[pDumpfile2]); strcat(dumpfile,name); ifstream fin(dumpfile); loadfile = (fin && (fin.peek()!=EOF)); if(loadfile){ cout << "Loading old population from "<<dumpfile<<endl; gencount_ = load_save(fin, argc, argv); } fin.close();return gencount_;}//end open_dumpint load_dumpfile(int argc, char * argv[]) //if possible{int gencount_;if(strlen(ThisParams->params_str[pZipCmd]) != 0) { gencount_ = open_zipped(".A", argc, argv ); if (gencount_ < 0 ) gencount_ = open_zipped(".B", argc, argv );}else { gencount_ = open_dump(".A", argc, argv ); if (gencount_ < 0 ) gencount_ = open_dump(".B", argc, argv );}return gencount_;}//end load_dumpfile//************************************************************#ifdef PARETOvoid display_best_stats(Pop* pop, int popsize){int i, dummy;#define outputsize_max 5000int outputsize = outputsize_max;int output[outputsize_max];int duplicates[outputsize_max];select_hits(pop->pop, popsize, 0, &dummy, TRUE, output, duplicates, &outputsize);cout<<"Best ("<<outputsize<<") in population "<<flush;int sum = 0;int sumsq = 0;for (i=0; i<outputsize; i++){ sum += duplicates[i]; sumsq += duplicates[i] * duplicates[i]; }float mean = float(sum)/float(outputsize);float variance = (float(sumsq)/float(outputsize))-mean*mean;float sd = (variance>0) ? sqrt(variance) : 0.0; //protect from rounderrscout <<sum <<"\tMean = "<<mean <<"\tSD = "<<sd
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -