Advertisement
Guest User

Untitled

a guest
May 27th, 2015
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 20.93 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #undef YAFT_WIN
  4. #ifdef YAFT_WIN
  5. #include <conio.h>
  6. #endif
  7. #include <string.h>
  8. #include <time.h>
  9.  
  10. // undef SMILE for file output
  11. #define SMILE
  12.  
  13. //#define DBG_MUTATE
  14. //#define DBG_CROSSOVER
  15. //#define DBG_SELECT
  16. //#define DBG_GENERATIONS
  17. //#define DBG_CSVOUT
  18.  
  19. #define SELECT_DEFAULT
  20. //#define SELECT_UNREAL
  21. //#define SELECT_TOURNAMENT 3
  22. #define ELITE 5
  23. #define CROSSOVER_DEFAULT
  24. //#define CROSSOVER_UNIFORM // coin toss
  25. #define MUTATE_DEFAULT
  26. //#define MUTATE_INVERT
  27.  
  28. // Limits, may be changed to soft limits later
  29. #define MAX_POP 1500
  30. #define MAX_ITER 50
  31. #define MUTATION_RATE 1
  32. #define MUTATION_N 3
  33. #define CROSSOVER_RATE 25
  34. #define CROSSOVER_N 1
  35. #define FIT_MULT 10
  36. #define FIT_OFF vars->gene_len - 3
  37.  
  38. #ifndef CHAR_BIT
  39. #define CHAR_BIT 8
  40. #endif
  41.  
  42.  
  43. #define MIN(x,y) (y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)))) // min(x, y)
  44. #define MAX(x,y) (x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)))) // max(x, y)
  45.  
  46. //ERRORS
  47. #define MEMERR puts("out of memory error")
  48. #define COLERR puts("collision error")
  49.  
  50. //VALUES
  51. #define TLEFT 0x03
  52. #define TSTRAIGHT 0x00
  53. #define TRIGHT 0x01
  54. #define TEND 0x02
  55.  
  56. #define DNORTH 0x00
  57. #define DEAST 0x01
  58. #define DSOUTH 0x02
  59. #define DWEST 0x03
  60.  
  61. // MASKS
  62. #define MDIR 0x03
  63. #define MTYPE 0x04
  64. #define MHIGH 0x0C
  65.  
  66.  
  67. /* OUTSTRING FORMAT:
  68. .... 1tdd
  69. t:  type
  70. dd: direction
  71. 00: left
  72. 01: straight
  73. 10: right
  74. 11: end
  75. */
  76.  
  77. // dead
  78. // worst fitness = 0, otherwise keep the original values
  79. #define SET_WORST_IS_ZERO true
  80. // do not adjust fitnesses higher than that
  81. #define FITNESS_THRESHOLD -100
  82. // if fitness < FITNESS_THRESHOLD, set chance = 0%
  83. #define ELIMINATE_BROKEN false
  84.  
  85. typedef unsigned char gene;
  86. typedef struct { gene* genome; int fitness; double rel_fitness, sum_chance; } population;
  87. //typedef struct { gene* genome; int fitness; } elite;
  88. typedef struct { int gene_len,  pop_size, worst, pop_fitness, best, input_fitness;  
  89.                 population* elites; int elite_worst_index, elite_worst_fitness, elite_best;
  90.                 int rate_mut, rate_xover;
  91.                 bool silent;
  92. } g_vars;
  93.  
  94.  
  95. void printChain(const gene* chain, g_vars *vars) {
  96.     int size = vars->gene_len;
  97.     for (int i = 0; i < size; i++) {
  98.         gene tmpval = chain[i] & MTYPE;
  99.         gene tmpdir = chain[i] & MDIR;
  100.         char x = (tmpval == 0) ? '0': '1';
  101.         char y;
  102.         switch (tmpdir) {
  103.             case TSTRAIGHT : y = 's'; break;
  104.             case TLEFT : y = 'l'; break;
  105.             case TRIGHT : y = 'r'; break;
  106.             case TEND : y = '.';
  107.         }
  108.         putchar(x); putchar(y);
  109.     }
  110.     putchar('\n');
  111. }
  112.  
  113. char* getChain(const gene* chain, g_vars *vars) {
  114.     int size = vars->gene_len;
  115.     char* ret_chain = (char*) malloc(2*size*sizeof(char)+sizeof(char));
  116.     for (int i = 0; i < size; i++) {
  117.         gene tmpval = chain[i] & MTYPE;
  118.         gene tmpdir = chain[i] & MDIR;
  119.         char x = (tmpval == 0) ? '0': '1';
  120.         //x=' ';  // ?
  121.         char y;
  122.         switch (tmpdir) {
  123.             case TSTRAIGHT : y = 's'; break;
  124.             case TLEFT : y = 'l'; break;
  125.             case TRIGHT : y = 'r'; break;
  126.             case TEND : y = '.';
  127.         }
  128.         ret_chain[i*2]=x; ret_chain[i*2+1]=y;
  129.     }
  130.     ret_chain[size*2]='\0';
  131.     return (ret_chain);
  132. }
  133.  
  134. int evaluateMatrix(const gene* matrix, g_vars *vars) {
  135.     int xsize = vars->gene_len*2+1, ysize=xsize;
  136.     int curval = 0;
  137.     for (int y = 0; y < ysize; y++)
  138.         for(int x = 0; x < xsize; x++)
  139.         {
  140.             int tval = 0;
  141.  
  142.             gene tmp = matrix[x+xsize*y];
  143.             gene tmpval = (tmp & MTYPE) >> 2;
  144.             if (tmpval == 1) {
  145.                 //if ( y > 0)  tval = tval + ((matrix[(x)+ysize*(y-1)] & MTYPE) >> 2);
  146.                 //if ( x > 0)  tval = tval + ((matrix[(x-1)+ysize*(y)] & MTYPE) >> 2); 
  147.                 if ( y < ysize-1)  tval = tval + ((matrix[(x)+ysize*(y+1)] & MTYPE) >> 2); 
  148.                 if ( x < xsize-1)  tval = tval + ((matrix[(x+1)+ysize*(y)] & MTYPE) >> 2);
  149.             }
  150.             curval = curval + tval;
  151.         }
  152.         return curval; // 2
  153. }
  154.  
  155. gene* generateMatrixFromChain(const gene* chain, g_vars *vars, int* broken) {
  156.     *broken = 0;
  157.     const int yArr[4] = {-1,0,1,0};
  158.     const int xArr[4] = {0,1,0,-1};
  159.     int chainLen = vars->gene_len;
  160.     int curDir = DNORTH;
  161.     int matrixSize = 2*chainLen+1;
  162.     gene* matrix = (gene*)malloc(matrixSize*matrixSize*sizeof(gene));
  163.     if (matrix == NULL) {
  164.         MEMERR;
  165.         return 0;
  166.     }
  167.     gene emptyVal = 0x00;
  168.  
  169.     memset (matrix,emptyVal,matrixSize*matrixSize*sizeof(gene));
  170.     int x = chainLen;
  171.     int y = chainLen;
  172.     gene tmp;
  173.     gene tmpDir;
  174.     for (int i = 0; i < chainLen; i++) {
  175.         tmp = chain[i];
  176.         tmpDir = tmp & MDIR;
  177.         if (matrix[x+matrixSize*y] != emptyVal) {
  178.             *broken = *broken +1;
  179.         }
  180.             matrix[x+matrixSize*y] = tmp;
  181.         curDir = (curDir+tmpDir)& MDIR;
  182.         x = x+xArr[curDir];
  183.         y = y+yArr[curDir];
  184.     }
  185.     //*size = matrixSize;
  186.     return matrix;
  187. }
  188.  
  189. void printMatrixAlt(gene* chain, g_vars* vars) {
  190.     int gene_len = vars->gene_len;
  191.     int minmax[4]={0};
  192.     int axyDir[8]={0,-1 , 1,0 , 0,1 , -1,0 };   // my directions
  193.     int i=0, dir, xyDir=3;
  194.  
  195.     // reserve a huge space to draw in, just in case
  196.     char* display_matrix = (char*) calloc((gene_len+1)*2 * (gene_len+1)*2, sizeof(char));
  197.     int x=gene_len; int y=gene_len;
  198.  
  199.     while (true) {
  200. #ifdef SMILE
  201.         display_matrix[x+y*gene_len*2]=((chain[i]>>2) & 1)+1;
  202. #else
  203.         display_matrix[x+y*gene_len*2]=((chain[i]>>2) & 1)*('X'-'O') + 'O';
  204. #endif
  205.         //display_matrix[x+y*gene_len*2]='#';
  206.         dir = chain[i] & 3;
  207.         if (dir==0x02) break;
  208.         /*
  209.         #define TLEFT 0x03
  210.         #define TSTRAIGHT 0x00
  211.         #define TRIGHT 0x01
  212.         #define TEND 0x02
  213.         */
  214.         xyDir=(xyDir+dir)%4;
  215.         x+=axyDir[xyDir*2]; y+=axyDir[xyDir*2+1];
  216.         display_matrix[x+y*gene_len*2]=0x7c+(xyDir%2)*-79;
  217.         //display_matrix[x+y*gene_len*2]='-';
  218.         x+=axyDir[xyDir*2]; y+=axyDir[xyDir*2+1];
  219.         minmax[1]=MAX(x-gene_len,minmax[1]); minmax[2]=MAX(y-gene_len,minmax[2]);
  220.         minmax[3]=MIN(x-gene_len,minmax[3]); minmax[0]=MIN(y-gene_len,minmax[0]);
  221.         i++;
  222.     }
  223.     int top=minmax[0], bottom=minmax[2];
  224.     int left=minmax[3], right=minmax[1];
  225.     for(y=top+gene_len;y<=bottom+gene_len;y++) {
  226.         for(x=left+gene_len;x<=right+gene_len;x++) {
  227.             (display_matrix[x+y*gene_len*2] == 0) ? putchar(32) : putchar(display_matrix[x+y*gene_len*2]);
  228.         }
  229.         putchar('\n');
  230.     }
  231.     free(display_matrix);
  232.     return;
  233. }
  234.  
  235. int getFitness(gene* chain, g_vars *vars) {
  236.     int broken;
  237.     int bfsize = vars->gene_len;
  238.     int bfval = 0;
  239.     gene* matrix = generateMatrixFromChain(chain,vars,&broken);
  240.     if (matrix && !broken) {
  241.         bfval = evaluateMatrix(matrix,vars);           
  242.         //printMatrix(chain,count);
  243.         bfval = (bfval-vars->input_fitness)*FIT_MULT;
  244.     }
  245.     if (matrix && broken) bfval = broken*-1;
  246.     if (!matrix) MEMERR;
  247.     free(matrix);
  248.     //int offset = vars->gene_len-3;
  249.  
  250.     //if (ELIMINATE_BROKEN && bfval<FITNESS_THRESHOLD) return 0;
  251.     //if (SET_WORST_IS_ZERO) pop[i].fitness+=abs(worst)+1;
  252.  
  253.  
  254.     return bfval+FIT_OFF; //vars->gene_len-3;
  255. }
  256.  
  257. /** lol bruteforce
  258. int recBruteForce(gene* chain, int pos, const int* len, const gene* values, int* highScore, const int* inputEval, gene* scoreChain)
  259. {
  260.     gene* matrix = NULL;
  261.     int bfval;
  262.     //printf("pos: %i\n",pos);
  263.  
  264.     for (int i = 0; i < 3; i++) {
  265.         bfval = 0;
  266.         if ((chain[pos] & MDIR) != TEND) chain[pos] = (chain[pos] & MHIGH)|values[i];  
  267.         bfval = getFitness(chain,vars,inputEval);
  268.         if (bfval > *highScore) {
  269.             memcpy(scoreChain,chain,*len);
  270.             *highScore = bfval;
  271.         }
  272.         free(matrix);
  273.         if (pos < *len-1) recBruteForce(chain,pos+1,len,values,highScore,inputEval,scoreChain);
  274.     }
  275.     return 0;
  276. }
  277. */
  278.  
  279. void randomFold(gene* chain, g_vars* vars) {
  280.     int chain_len = vars->gene_len;
  281.     for (int i=0; i<chain_len-1; i++) {
  282.         // Remove lower 2 bits and add random direction
  283.         chain[i] = (chain[i] & 0xFC) | (0x03 >> rand()%3);
  284.     }
  285.     return;
  286. }
  287.  
  288. void calcPopFitness(population* pop, g_vars* vars) {
  289.     int pop_size=vars->pop_size, worst = vars->worst;
  290.     int pop_fitness=0; //vars->pop_fitness;
  291.     for (int i = 0; i < pop_size; i++) {
  292.         //if (ELIMINATE_BROKEN && pop[i].fitness<FITNESS_THRESHOLD) pop[i].fitness = 0;
  293.         //if (SET_WORST_IS_ZERO) pop[i].fitness+=abs(worst)+1;
  294.         pop_fitness+=pop[i].fitness;
  295.     }
  296.     double sum_chance=0.0f;
  297.     for (int i = 0; i < pop_size; i++) {
  298.         pop[i].rel_fitness = (double) pop[i].fitness / (double) pop_fitness;
  299.         sum_chance+=pop[i].rel_fitness;
  300.         pop[i].sum_chance=sum_chance;
  301.     }
  302.     vars->pop_fitness=pop_fitness;
  303. }
  304.  
  305. void selectNewPopulation(population* pop, g_vars* vars) {
  306.     int pop_size=vars->pop_size, pop_fitness=vars->pop_fitness, gene_len=vars->gene_len;
  307.     population* old_pop = (population*) malloc(pop_size * sizeof(population));
  308.     for (int i=0; i<pop_size; i++) {
  309.         old_pop[i].genome = (gene*) malloc(gene_len * sizeof(gene));
  310.         memcpy(old_pop[i].genome,pop[i].genome,sizeof(gene)*gene_len);
  311.         old_pop[i].sum_chance = pop[i].sum_chance;
  312.         old_pop[i].fitness = pop[i].fitness;
  313.     }
  314.     for (int i=0;i<pop_size;i++) {
  315. #ifdef SELECT_DEFAULT
  316.         double r = (double) rand() / (double) RAND_MAX; // das war dumm -> * pop_fitness;
  317.         int j=0;
  318.         while (old_pop[j].sum_chance<r && j<pop_size-1) j++;
  319.         memcpy(pop[i].genome,old_pop[j].genome,gene_len*sizeof(gene));
  320.         pop[i].fitness = 0; pop[i].rel_fitness=pop[i].sum_chance=0.0f;
  321.     #ifdef DBG_SELECT
  322.  
  323.         printf("r: %f => selected %i as new %i (%s)\n",r,j,i,getChain(pop[i].genome,gene_len));
  324.     #endif
  325. #endif
  326. #ifdef SELECT_TOURNAMENT
  327.         int* candidate = (int*) malloc(SELECT_TOURNAMENT*sizeof(int));
  328.         int j;
  329.         for (j=0; j<SELECT_TOURNAMENT;j++) {
  330.             candidate[j] = (double) rand() / (double) RAND_MAX * vars->pop_size;
  331.     #ifdef DBG_SELECT
  332.             printf("Candidate for tournament %i of %i: %i (fit: %i)\n",j+1,SELECT_TOURNAMENT,candidate[j],old_pop[candidate[j]].fitness);
  333.     #endif
  334.         }
  335.         int best_candidate = candidate[0];
  336.         for (j=1; j<SELECT_TOURNAMENT;j++) {
  337.             if (old_pop[candidate[j]].fitness>old_pop[best_candidate].fitness) best_candidate = candidate[j];
  338.         }
  339.         free(candidate);
  340. #ifdef DBG_SELECT
  341.         printf("Winner of tournament: %i\n",best_candidate);
  342. #endif
  343.         memcpy(pop[i].genome,old_pop[best_candidate].genome,gene_len*sizeof(gene));
  344. #endif
  345.         pop[i].fitness = 0; pop[i].rel_fitness=pop[i].sum_chance=0.0f;
  346.     }
  347.     for (int i=0;i<pop_size;i++) free(old_pop[i].genome);
  348.     free(old_pop);
  349.     return;
  350. }
  351.  
  352. void mutate(population* pop, g_vars* vars) {
  353.     int pop_size=vars->pop_size, gene_len=vars->gene_len;
  354.     for (int i=0; i<pop_size; i++) {
  355.         if (rand()%100 < vars->rate_mut) {
  356. #ifdef MUTATE_DEFAULT
  357.             int mmax = rand()%MUTATION_N+1;
  358.             for (int j=0; j<mmax; j++) {
  359.                 int pos = rand()%(gene_len-1);
  360.                 gene before = pop[i].genome[pos];
  361.                 while(pop[i].genome[pos] == before) pop[i].genome[pos] = (pop[i].genome[pos] & 0xFC) | (0x03 >> rand()%3);
  362. #ifdef DBG_MUTATE
  363.             printf("Mutation in %i at %i, before %x, after %x\n",i,pos,before&0x03,pop[i].genome[pos]&0x03);
  364. #endif
  365.             }
  366. #endif
  367. #ifdef MUTATE_INVERT
  368.             int pos1 = rand()%(gene_len-1);
  369.             int pos2 = rand()%(gene_len-1);
  370.             gene* temp_gene = (gene*) malloc(gene_len*sizeof(gene));
  371.             memcpy(temp_gene,pop[i].genome,gene_len);
  372.             for (int j = MIN(pos1,pos2); j <= MAX(pos1,pos2); j++) {
  373.                 pop[i].genome[j]=(pop[i].genome[j] & 0xFC) | (temp_gene[(MAX(pos1,pos2))-(j-(MIN(pos1,pos2)))] & 0x03);  // lol lisp
  374.             }
  375. #ifdef DBG_MUTATE
  376.             printf("Mutation in %i from %i to %i, before %s, after %s\n",i,pos1,pos2,getChain(temp_gene, vars),getChain(pop[i].genome, vars));
  377. #endif
  378.             free(temp_gene);
  379. #endif
  380.         }
  381.     }
  382.     return;
  383. }
  384.  
  385. void crossover(population* pop, g_vars* vars) {
  386.     int pop_size=vars->pop_size, gene_len=vars->gene_len;
  387.     for (int i=0; i<pop_size; i++) {
  388.         if (rand()%100 < vars->rate_xover) {
  389.             int partner = rand()%pop_size;
  390.             gene* temp_gene = (gene*) malloc(gene_len*sizeof(gene));
  391.             memcpy(temp_gene,pop[i].genome,gene_len);
  392. #ifdef CROSSOVER_DEFAULT
  393.             for (int k=0; k<CROSSOVER_N;k++) {
  394.                 int pos = rand()%(gene_len-1);  // we don't want crossover to happen at the terminator
  395.                 for (int j=pos;j<gene_len;j++) {
  396.                     pop[i].genome[j]=pop[partner].genome[j];
  397.                     pop[partner].genome[j]=temp_gene[j];
  398.                 }
  399. #ifdef DBG_CROSSOVER
  400.                 printf("Crossover between %i and %i at position %i\n",i,partner,pos);
  401. #endif
  402.             }
  403. #endif
  404. #ifdef CROSSOVER_UNIFORM
  405. #ifdef DBG_CROSSOVER
  406.             printf("Crossover between %i and %i: ",i,partner);
  407. #endif
  408.             for (int j=0;j<gene_len;j++) {
  409.                 if (rand()%2) {
  410.                     pop[i].genome[j]=pop[partner].genome[j];
  411.                     pop[partner].genome[j]=temp_gene[j];
  412. #ifdef DBG_CROSSOVER
  413.                     printf("%i ",j);
  414. #endif
  415.                 }
  416.             }
  417. #ifdef DBG_CROSSOVER
  418.             printf("\n");
  419. #endif
  420. #endif
  421.             free (temp_gene);
  422.  
  423.         }
  424.     }
  425.     return;
  426. }
  427.  
  428. void selectElite(population* pop, g_vars* vars, int index) {
  429.     //printf("HALLO\n");
  430.     if (pop[index].fitness > vars->elite_worst_fitness) {
  431.         vars->elites[vars->elite_worst_index].fitness = pop[index].fitness;
  432.         memcpy(vars->elites[vars->elite_worst_index].genome, pop[index].genome, vars->gene_len);
  433.         vars->elite_worst_fitness = pop[index].fitness;
  434.         // printf("index %i, ding %s\n",index,getChain(vars->elites[vars->elite_worst_index].genome,vars));
  435.         for (int j = 0; j < ELITE; j++) {
  436.             if (vars->elites[j].fitness <= vars->elite_worst_fitness) {
  437.                 vars->elite_worst_fitness = vars->elites[j].fitness;
  438.                 vars->elite_worst_index = j;
  439.             }
  440.         }
  441.     }
  442. }
  443.  
  444. int main(int argc, char** argv) {
  445.     srand(time(NULL));
  446.     //fillPrintArr();
  447.     g_vars* vars = (g_vars*) malloc (sizeof(g_vars));
  448.  
  449.     vars->rate_mut = MUTATION_RATE;
  450.     vars->rate_xover = CROSSOVER_RATE;
  451.     vars->silent = false;
  452.  
  453.     gene* input; int count;
  454.     if (argc > 1) {
  455.         input = (gene*) malloc (strlen(argv[1]) * sizeof(gene) + 1);
  456.         count = strlen(argv[1]);
  457.         for (int i=0; i<count; i++) {
  458.             input[i] = 0x08 | (argv[1][i]-'0')<<2;
  459.         }
  460.         input[count-1]= input[count-1]+0x02; // End
  461.         if (argc>3) {
  462.             vars->rate_mut=atoi(argv[2]);
  463.             vars->rate_xover=atoi(argv[3]);
  464.         }
  465.         if (argc>4) {
  466.             //printf ("Hallo %s",argv[4]);
  467.             if (strstr(argv[4],"-s")) vars->silent = true;
  468.         }
  469.     } else {
  470.         puts("String please [01] :");
  471.         int c;
  472.         count = 0;
  473.         int limit = 32;
  474.         input = (gene*)malloc(limit * sizeof(gene));
  475.         if (input == NULL) {
  476.             MEMERR;
  477.         } else {
  478.             while ((c = getchar()) != '\r') {
  479.                 if (count >= limit) {
  480.                     limit = limit * 2;
  481.                     input = (gene*)realloc(input,limit * sizeof(gene));
  482.                     if (input == NULL) {
  483.                         MEMERR;
  484.                         break;
  485.                     }
  486.                 }
  487.                 if (c == '0' || c == '1') {
  488.                     //input[count] = ( c == '0') ? 0x08 : 0x0C; // 0000 1100
  489.                     input[count] = 0x08 | (c-'0')<<2;
  490.                     putchar(c);
  491.                     count++;
  492.                 }
  493.             }
  494.             input[count-1]= input[count-1]+0x02; // End
  495.         }
  496.     }
  497.     if(count<=0) return 0xc0ffee;
  498.     vars->gene_len=count;
  499.     if (!vars->silent) putchar('\n');
  500.     //EVALUATE INPUT (Removes neighbors from fitness evaluation)
  501.     int t;
  502.     gene* input_matrix = generateMatrixFromChain(input,vars,&t);
  503.     vars->input_fitness = evaluateMatrix(input_matrix, vars);
  504.     free(input_matrix);
  505. #ifndef DBG_CSVOUT
  506.     if (!vars->silent) {
  507.         printf("Input Value: %i\n", vars->input_fitness);
  508.         // Prepare initial population
  509.         printf("Generating initial population (%i individuals)... ",MAX_POP);
  510.     }
  511. #endif
  512.     //int gene_len = count;
  513.     vars->pop_size = MAX_POP;
  514.     //int fitness_threshold = gene_len * -1;
  515.     vars->worst = RAND_MAX;
  516.     vars->best = 0;
  517.     vars->elite_best = 0;
  518.  
  519. #ifdef ELITE
  520.     vars->elites = (population*)malloc(ELITE * sizeof(population));
  521.     for (int i = 0; i < ELITE; i++) {
  522.         vars->elites[i].genome = (gene*)malloc(sizeof(gene)*vars->gene_len);
  523.         vars->elites[i].fitness = 0;
  524.     }
  525.  
  526.     vars->elite_worst_index = 0;
  527.     vars->elite_worst_fitness = 0;
  528. #endif
  529.     //int bla_worst = fitness_threshold*-1;
  530.     population* pop = (population*) malloc(vars->pop_size * sizeof(population));
  531.     for (int i = 0; i<vars->pop_size; i++) {
  532.         pop[i].rel_fitness = pop[i].sum_chance = 0.0f;
  533.         pop[i].genome = (gene*) malloc(vars->gene_len * sizeof(gene));
  534.         memcpy(pop[i].genome,input,vars->gene_len);
  535.         // generate random folding
  536.         randomFold(pop[i].genome,vars);
  537.  
  538.         // build a matrix from the string
  539.         int broken;
  540.         //int width = gene_len;
  541.         //int* size = &width;
  542.         gene* matrix = generateMatrixFromChain(pop[i].genome,vars,&broken);
  543.         // evaluate the matrix
  544.         int val = evaluateMatrix(matrix,vars);
  545.         pop[i].fitness = getFitness(pop[i].genome,vars);
  546.         vars->worst = MIN(vars->worst, pop[i].fitness);
  547. #ifdef ELITE
  548.         selectElite(pop,vars,i);
  549. #endif
  550.         //bla_worst = MIN(bla_worst, pop[i].fitness);
  551.         // and free it
  552.         free(matrix);
  553.     }
  554. #ifndef DBG_CSVOUT
  555.     if (!vars->silent) {
  556.         printf("done.\n");
  557.         // Now for the loop
  558.         printf ("Running %i iterations...\n",MAX_ITER);
  559.     }
  560. #endif
  561. #ifdef DBG_CSVOUT
  562.         printf("Generation, TotalFitness, Worst, Best,Population,Offset\n");
  563. #endif
  564.     for (int i=0; i<MAX_ITER; i++) {
  565. #ifdef DBG_GENERATIONS
  566.         printf("Generation %i\n------------------------\nWorst fitness: %i\n",i-1,worst_fitness);
  567. #endif
  568.         //int pop_fitness = calcPopFitness(pop,max_pop,worst_fitness);
  569.         calcPopFitness(pop,vars);
  570.        
  571. #ifdef DBG_GENERATIONS
  572.         for (int j=0; j<vars->pop_size; j++) {
  573.             printf("[%i] %s Fitness %i rel_fitness %f sum %f\n",j,getChain(pop[j].genome,vars),pop[j].fitness,pop[j].rel_fitness,pop[j].sum_chance);
  574.         }
  575. #endif 
  576.  
  577.        
  578.         //DBG printf("Selection of Generation %i\n",i);
  579.         selectNewPopulation(pop,vars);
  580.         // mutate and recombinate too!
  581.         mutate(pop, vars);
  582.         crossover(pop, vars);
  583.  
  584.         // evaluate our new population
  585.         vars->worst = RAND_MAX;
  586.         vars->best = 0;
  587.         vars->pop_fitness = 0;
  588.         for (int j=0; j<vars->pop_size; j++) {
  589.             // build a matrix from the string
  590.             int broken;
  591.             //int width = vars->gene_len;
  592.             //int* size = &width;
  593.             gene* matrix = generateMatrixFromChain(pop[j].genome,vars,&broken);
  594.             // evaluate the matrix
  595.             int val = evaluateMatrix(matrix,vars);
  596.             pop[j].fitness = getFitness(pop[j].genome,vars);
  597.             vars->pop_fitness += pop[j].fitness;
  598.             vars->worst = MIN(vars->worst,pop[j].fitness);
  599.             //bla_worst = MIN(bla_worst, pop[i].fitness);
  600.             vars->best = MAX(vars->best,pop[j].fitness);
  601.             // vars->elite_best = vars->best;
  602. #ifdef ELITE
  603.             selectElite(pop,vars,j);
  604. #endif
  605.             // and free it
  606.             free(matrix);
  607.         }
  608.         for (int j=0; j<ELITE; j++) {
  609.             vars->elite_best = MAX(vars->elite_best,vars->elites[j].fitness);
  610.         }
  611.         //calcPopFitness(pop,max_pop,worst_fitness);
  612. #ifdef DBG_GENERATIONS
  613.         printf("------------------------\n");
  614. #endif
  615. #ifndef DBG_CSVOUT
  616.         if (!vars->silent) {
  617.             printf("Generation %i, total fitness: %i, worst: %i, best: %i, e_best: %i\n",i,vars->pop_fitness,vars->worst,vars->best,vars->elite_best);
  618.             printf("------------------------\n");
  619.         }
  620. #endif
  621. #ifdef DBG_CSVOUT
  622.         printf("%i, %i, %i, %i,%i,%i\n",i,vars->pop_fitness,vars->worst,vars->best,vars->pop_size,FIT_OFF);
  623. #endif
  624.     }
  625. #ifndef DBG_CSVOUT
  626.     // now let's select the first and best candidate for output
  627.     int best_index=0;
  628.     pop = (population*) realloc(pop,(vars->pop_size+ELITE)*sizeof(population)); // <-- LOL Nullpointer
  629.     for (int i=vars->pop_size;i<vars->pop_size+ELITE;i++) memcpy(&pop[i], &vars->elites[i-vars->pop_size], sizeof(population)); //pop[i] = &vars->elites[i-vars->pop_size];
  630.     for (int i=0; i<vars->pop_size+ELITE; i++) {
  631.         // printf("%s\n",getChain(pop[i].genome,vars));
  632.         if (pop[i].fitness>pop[best_index].fitness) best_index=i;
  633.     }
  634.     if (!vars->silent) {
  635.         printMatrixAlt(pop[best_index].genome,vars);
  636.         printf("Fitness: %i, chain: %s",(pop[best_index].fitness-(FIT_OFF))/FIT_MULT,getChain(pop[best_index].genome,vars));
  637.         printf("\ndone.\n");
  638.     } else {
  639.         printf("%i",(pop[best_index].fitness-(FIT_OFF))/FIT_MULT);
  640.     }
  641. #endif
  642.     // clean up yer mess, matey
  643.     for (int i=0; i<vars->pop_size; i++) free(pop[i].genome);
  644.     free(pop);
  645.     free(input);
  646.     free(vars->elites);
  647. #ifdef YAFT_WIN
  648.     if (argc <= 1) while(!_kbhit());
  649. #endif
  650.     return 0;
  651.  
  652.  
  653.     /** Old stuff ~
  654.     //DEFINE HIGHSOCRE
  655.     int highScore = 0;
  656.  
  657.     //GENERATE FIRST MATRIX
  658.     int broken;
  659.     int width = count;
  660.     int*  size = &width;
  661.     gene* matrix = generateMatrixFromChain(input,size,&broken,false);
  662.  
  663.     //EVALUATE FIRST MATRIX
  664.     int val = evaluateMatrix(matrix,width,width);
  665.     printf("Value: %i\n", val);
  666.  
  667.     //FREE FIRST MATRIX
  668.     free(matrix);
  669.  
  670.     //GENERATE WORKING COPY OF INPUT
  671.     gene* chain = (gene*)malloc(count * sizeof(gene));
  672.     memcpy(chain,input,count);
  673.  
  674.     //GENERATE HIGHSCORE COPY OF CHAIN
  675.     gene* scoreChain = (gene*)malloc(count * sizeof(gene));
  676.     memcpy(scoreChain,input,count);
  677.  
  678.     //BRUTE FORCE
  679.     gene bfarr[3] = {TSTRAIGHT,TLEFT,TRIGHT};
  680.     recBruteForce(chain,0,&count,bfarr,&highScore,&inputEval,scoreChain);      
  681.     printf("Endwert: %i", highScore);
  682.  
  683.     //DEBUG OUTPUT
  684.     puts("\nString");
  685.     printChain(scoreChain,count);
  686.     puts("\nMatrix");
  687.     printMatrix(scoreChain,count);
  688.     free(chain);
  689.     free(scoreChain);
  690.     free(input);
  691.     printf("\ndone.\n");
  692.     while(!_kbhit());
  693.     return 0;
  694.  
  695.     */
  696. }
  697.  
  698.  
  699.  
  700.  
  701. // benchmark sequences for the 2d HP model
  702. // 0 = hydrophil, "white"
  703. // 1 = hydrophob, "black"
  704. // source: Ron Unger, John Moult: Genetic Algorithms for Protein Folding Simulations,
  705. //         Journal of Molecular Biology, Vol. 231, No. 1, May 1993
  706. /**
  707. public class Examples {
  708.  
  709. public static final String SEQ20 = "10100110100101100101";
  710. public static final String SEQ24 = "110010010010010010010011";
  711. public static final String SEQ25 = "0010011000011000011000011";
  712. public static final String SEQ36 = "000110011000001111111001100001100100";
  713. public static final String SEQ48 = "001001100110000011111111110000001100110010011111";
  714. public static final String SEQ50 = "11010101011110100010001000010001000101111010101011";
  715.  
  716. }
  717. **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement