📄 gaview.c
字号:
/* ---------------------------------------------------------------------------- gaview.C mbwall 10apr96 Copyright (c) 1996 Massachusetts Institute of Technology Visual genetic algorithm example code. The program pops up a single windowwith a set of buttons that control the evolution. You can view an entirepopulation or a single individual. The program reads standard GAlib settingsfiles and understands the usual GAlib command-line options. Apologies for the mix of C and C++ coding styles here, but you get the idea. By the way, this thing looks WAY better when you plot the functions in 3D(using an OpenGL widget rather than the drawing area widget, for example). You can compile this using either motif widgets or the athena widgets, depending on which you have on your system.---------------------------------------------------------------------------- */#include <stdio.h>#include <iostream.h>#include <math.h>#include <ga/ga.h>#include <ga/GARealGenome.h>#include <ga/GARealGenome.C>// comment this line if you don't have MOTIF on your system//#define USE_MOTIF#ifdef USE_MOTIF#include <Xm/Xm.h>#include <Xm/Form.h>#include <Xm/PushB.h>#include <Xm/Label.h>#include <Xm/Protocols.h>#include <Xm/DrawingA.h>#include <Xm/Frame.h>#else#include <X11/Intrinsic.h>#include <X11/StringDefs.h>#include <X11/Shell.h>#include <X11/Xaw/Form.h>#include <X11/Xaw/Command.h>#include <X11/Xaw/Box.h>#endif#define APP_CLASS "GAView"#define SETTINGS_FILE "settings.txt"#define MAX_POPS 5typedef struct _AppData { Pixel bestcolor; Pixel popcolor[MAX_POPS]; int geninc; // how many generations in each step XtWorkProcId procid; XtAppContext appc; Widget canvas, counter; GC bestgc, dotgc[MAX_POPS]; GAGenome* genome; GAGeneticAlgorithm* ga; int whichGA; // which genetic algorithm to use int whichGenome; // which genome to use int whichFunction; // which function to use} AppData, *AppDataPtr, **AppDataHdl;static AppData theAppData; // global data for the programint done = 0; // is the program finished yet?#include "bitmaps/gaview.xbm"#ifdef USE_MOTIF#include "bitmaps/rew.xbm"#include "bitmaps/stop.xbm"#include "bitmaps/fwds.xbm"#include "bitmaps/ffst.xbm"#include "bitmaps/ffwd.xbm"typedef struct _BitmapInfo { int width, height; unsigned char *bits;} BitmapInfo;static BitmapInfo bm[] = { {stop_width, stop_height, (unsigned char *)stop_bits}, {rew_width, rew_height, (unsigned char *)rew_bits}, {fwds_width, fwds_height, (unsigned char *)fwds_bits}, {ffst_width, ffst_height, (unsigned char *)ffst_bits}, {ffwd_width, ffwd_height, (unsigned char *)ffwd_bits}};enum { bmStop, bmRewind, bmForwardStop, bmFastForwardStop, bmFastForward, nBitmaps};#endifWidget ConstructWidgets(Widget);void UpdateCounter(GAGeneticAlgorithm*);static Boolean Evolve(int);void QuitCB(Widget, XtPointer, XtPointer);void InitCB(Widget, XtPointer, XtPointer);void DrawCB(Widget, XtPointer, XtPointer);void ResetCB(Widget, XtPointer, XtPointer);void StopCB(Widget, XtPointer, XtPointer);void StepCB(Widget, XtPointer, XtPointer);void EvolveSomeCB(Widget, XtPointer, XtPointer);void EvolveCB(Widget, XtPointer, XtPointer);void DumpStatsCB(Widget, XtPointer, XtPointer);void DumpParamsCB(Widget, XtPointer, XtPointer);void DumpScoreCB(Widget, XtPointer, XtPointer);void DrawPopulation(Widget, const GAPopulation&, GC, GC);static char *fallbacks[] = { "*shell.title: gaview", "*background: thistle4", "*canvas.background: black", "*leftOffset: 3", "*rightOffset: 3", "*topOffset: 3", "*bottomOffset: 3", "*canvas.width: 400", "*canvas.height: 300", "*bestColor: green", "*populationColor1: yellow", "*populationColor2: blue", "*populationColor3: red", "*populationColor4: purple", "*populationColor5: cyan", "*ga: 2", "*genome: 0", "*function: 3", "*generationsPerStep: 10",// motif-specific fallbacks "*fontList: -*-helvetica-bold-r-*-*-*-140-*-*-*-*-*-*", "*score.labelString: score", "*stats.labelString: stats", "*params.labelString: params",// athena-specific fallbacks "*font: -*-helvetica-bold-r-*-*-*-140-*-*-*-*-*-*", "*rewind.label: reset", "*stop.label: stop", "*step.label: one", "*some.label: some", "*evolve.label: all", "*score.label: score", "*stats.label: stats", "*params.label: params", (char *)NULL};static XtResource resources[] = {#define Offset(field) (XtOffset(AppDataPtr, field)) {"bestColor", XtCForeground, XtRPixel, sizeof(Pixel), Offset(bestcolor), XtRString, XtDefaultForeground}, {"populationColor1", XtCForeground, XtRPixel, sizeof(Pixel), Offset(popcolor[0]), XtRString, XtDefaultForeground}, {"populationColor2", XtCForeground, XtRPixel, sizeof(Pixel), Offset(popcolor[1]), XtRString, XtDefaultForeground}, {"populationColor3", XtCForeground, XtRPixel, sizeof(Pixel), Offset(popcolor[2]), XtRString, XtDefaultForeground}, {"populationColor4", XtCForeground, XtRPixel, sizeof(Pixel), Offset(popcolor[3]), XtRString, XtDefaultForeground}, {"populationColor5", XtCForeground, XtRPixel, sizeof(Pixel), Offset(popcolor[4]), XtRString, XtDefaultForeground}, {"ga", "GA", XtRInt, sizeof(int), Offset(whichGA), XtRImmediate, (XtPointer)2}, {"genome", "Genome", XtRInt, sizeof(int), Offset(whichGenome), XtRImmediate, (XtPointer)0}, {"function", "Function", XtRInt, sizeof(int), Offset(whichFunction), XtRImmediate, (XtPointer)3}, {"generationsPerStep", "GenerationsPerStep", XtRInt, sizeof(int), Offset(geninc), XtRImmediate, (XtPointer)10}#undef Offset};static XrmOptionDescRec options[] = { {"ga", "ga", XrmoptionSepArg, 0}, {"genome", "genome", XrmoptionSepArg, 0}, {"function", "function", XrmoptionSepArg, 0}, {"geninc", "generationsPerStep", XrmoptionSepArg, 0}};float RealObjective(GAGenome&);float Bin2DecObjective(GAGenome&);typedef float (*Function)(float, float);float Function1(float x, float y);float Function2(float x, float y);float Function3(float x, float y);float Function4(float x, float y);Function obj[] = { Function1, Function2, Function3, Function4 };float minx[] = {-6, -60, -500, -10 };float maxx[] = { 6, 60, 500, 10 };float ai[25],bi[25];intmain(int argc, char** argv) { cout << "Graphic genetic algorithm demonstration program.\n\n"; cout << "This program understands the standard GAlib and Xt\n"; cout << "arguments plus the following:\n\n"; cout << " function which function to solve\n"; cout << " 0 loaf of bread with 4 smooth humps\n"; cout << " 1 Shekel's foxholes from DeJong\n"; cout << " 2 Schwefel's nasty function\n"; cout << " 3 concentric rings (ripple in a pond) (default)\n"; cout << " ga specify which genetic algorithm to use\n"; cout << " 0 incremental genetic algorithm\n"; cout << " 1 simple genetic algorithm\n"; cout << " 2 steady-state genetic algorithm (default)\n"; cout << " 3 deme genetic algorithm\n"; cout << " genome specify which genome to use\n"; cout << " 0 real number genome (default)\n"; cout << " 1 binary-to-decimal genome\n"; cout << "\n"; cout << endl;// make the application widget, grab resource, and parse command line Widget toplevel = XtAppInitialize(&theAppData.appc, APP_CLASS, options, XtNumber(options), &argc, argv, fallbacks, (ArgList)NULL, 0); XtGetApplicationResources(toplevel, (XtPointer) &theAppData, resources, XtNumber(resources), NULL, 0);// do some setup for one of the functions for (int j=0; j<25; j++) { ai[j] = 16 * ((j % 5) -2); bi[j] = 16 * ((j / 5) -2); }// Create the appropriate genome and genetic algorithm if(theAppData.whichGenome == 1) { GABin2DecPhenotype map; map.add(31, minx[theAppData.whichFunction], maxx[theAppData.whichFunction]); map.add(31, minx[theAppData.whichFunction], maxx[theAppData.whichFunction]); theAppData.genome = new GABin2DecGenome(map, Bin2DecObjective); } else { GARealAlleleSet alleleset(minx[theAppData.whichFunction], maxx[theAppData.whichFunction]); theAppData.genome = new GARealGenome(2, alleleset, RealObjective); } if(theAppData.whichGA == 0) theAppData.ga = new GAIncrementalGA(*theAppData.genome); else if(theAppData.whichGA == 1) theAppData.ga = new GASimpleGA(*theAppData.genome); else if(theAppData.whichGA == 3) theAppData.ga = new GADemeGA(*theAppData.genome); else theAppData.ga = new GASteadyStateGA(*theAppData.genome);// Now set up the genetic algorithm parameters theAppData.ga->parameters(SETTINGS_FILE); theAppData.ga->parameters(argc, argv); theAppData.ga->initialize();// we don't allow too many populations (due to our color limit) if(theAppData.whichGA == 3) { int val; theAppData.ga->get(gaNnPopulations, &val); if(val > MAX_POPS) { val = MAX_POPS; theAppData.ga->set(gaNnPopulations, val); cerr << "this demo limits the number of populations to "<<MAX_POPS<<"\n"; } }// Create and manage all of the widgets Widget shell = ConstructWidgets(toplevel);// report status cout << "The evolution will use the following:\n"; cout << " function: "; switch(theAppData.whichFunction) { case 0: cout << "loaf of bread"; break; case 1: cout << "foxholes"; break; case 2: cout << "nasty function"; break; case 3: cout << "concentric rings"; break; default: cout << "unrecognized function selected"; break; } cout << "\n"; cout << " genome: "; switch(theAppData.whichGenome) { case 1: cout << "binary-to-decimal"; break; default: cout << "real number"; break; } cout << "\n"; cout << " algorithm: "; switch(theAppData.whichGA) { case 0: cout << "incremental (immediate replacement)"; break; case 1: cout << "simple (non-overlapping population)"; break; case 3: cout << "deme (multiple populations)"; break; default: cout << "steady-state (overlapping population)"; break; } cout << "\n" << endl;// now realize all the widgets and pop 'em up XtRealizeWidget(shell); XtMapWidget(shell); static Atom wmDeleteWindow; wmDeleteWindow = XInternAtom(XtDisplay(toplevel), "WM_DELETE_WINDOW", False);#ifdef USE_MOTIF XmAddWMProtocolCallback(shell, wmDeleteWindow, QuitCB, (XtPointer)0);#else XSetWMProtocols(XtDisplay(toplevel), XtWindow(toplevel), &wmDeleteWindow, 1);#endif while(!done){ XEvent event; XtAppNextEvent(theAppData.appc, &event); XtDispatchEvent(&event); } XFreeGC(XtDisplay(toplevel), theAppData.bestgc); for(int qq=0; qq<MAX_POPS; qq++) XFreeGC(XtDisplay(toplevel), theAppData.dotgc[qq]); delete theAppData.genome; delete theAppData.ga; return 0;}voidUpdateCounter(GAGeneticAlgorithm* ga) {#ifdef USE_MOTIF XmString str; static char txt[62]; sprintf(txt, "%d", ga->generation()); str = XmStringLtoRCreate(txt, XmSTRING_DEFAULT_CHARSET); XtVaSetValues(theAppData.counter, XmNlabelString, str, NULL); XmStringFree(str);#else static char txt[62]; sprintf(txt, "%d", ga->generation()); XtVaSetValues(theAppData.counter, XtNlabel, txt, NULL);#endif}BooleanEvolve(int n){ if((n < 0 && theAppData.ga->done() == gaFalse) || theAppData.ga->generation() < n){ theAppData.ga->step(); DrawCB(theAppData.canvas, (XtPointer)&theAppData, 0); UpdateCounter(theAppData.ga); return False; } return True;}voidResetCB(Widget, XtPointer cd, XtPointer){ AppDataPtr data = (AppDataPtr)cd; if(data->procid){ XtRemoveWorkProc(data->procid); data->procid = 0; } data->ga->initialize(); DrawCB(data->canvas, data, 0); UpdateCounter(data->ga);}voidStopCB(Widget, XtPointer cd, XtPointer){ AppDataPtr data = (AppDataPtr)cd; if(data->procid){ XtRemoveWorkProc(data->procid); data->procid = 0; }}voidStepCB(Widget, XtPointer cd, XtPointer){ AppDataPtr data = (AppDataPtr)cd; Evolve(data->ga->generation() + 1);}voidEvolveSomeCB(Widget, XtPointer cd, XtPointer){ AppDataPtr data = (AppDataPtr)cd; data->procid = XtAppAddWorkProc(data->appc, (XtWorkProc)Evolve, (XtPointer)(data->ga->generation() + data->geninc));}voidEvolveCB(Widget, XtPointer cd, XtPointer){ AppDataPtr data = (AppDataPtr)cd; data->procid = XtAppAddWorkProc(data->appc, (XtWorkProc)Evolve,(XtPointer)(-1));}voidQuitCB(Widget, XtPointer, XtPointer){ done = 1;}voidDumpStatsCB(Widget, XtPointer cd, XtPointer){ cerr << "\nstatistics are:\n" << ((GAGeneticAlgorithm*)cd)->statistics() << "\n";}voidDumpParamsCB(Widget, XtPointer cd, XtPointer){ cerr << "\nparameters are:\n" << ((GAGeneticAlgorithm*)cd)->parameters() << "\n";}voidDumpScoreCB(Widget, XtPointer cd, XtPointer){ cerr << "\nbest individual score is: " << ((GAGeneticAlgorithm*)cd)->population().best().score() << "\n";}// This routine draws the entire population or a single individual depending
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -