/* This is the code for the CPS 615 Spring Final project for "Ecological Computation". Authors: Steve Alexander Marjorie Quant */ #include #include #include #include #include "mpi.h" #define GENERATIONS 100 #define MUT_ENVIRONMENT 10 #define X_OVER 50 #define MUT_IND 50 #define NVARS 10 #define MAX_POP 10000 #define START_POP 50 #define TRUE 1 #define FALSE 0 typedef struct /* gtype, a member of the population */ { int gene[NVARS]; /* a string of variables */ } gtype; gtype population[MAX_POP]; /*population*/ gtype new_population[MAX_POP]; /*new populaiton, minus bad individuals*/ gtype environment; int popsize = 50; float avg_pop_fit = 0.0; int randval(int low, int high) { int val; /* return 0-9 */ val = (int)(((float)(rand()%1000)/1000.0) * (float)(high - low) + (float)low); return(val); } /* end randval */ void clear(gtype *one) { int i, j; for (i=0; igene[i] = 0; } } /* end of clear */ void init(gtype *one) { int i, j; for (i=0; i < NVARS; i++) { for (j=0; j < popsize; j++) /*initialize genes in population */ one->gene[i] = randval(0, 10); } } /* end of init */ /************************************************************* EVALUATE AND SELECT FUNCTION This function evaluates the fitness of each individual and the collective population. Each trait of each individual is compared with the environment. If there is more than an 80% differnce in any gene, the individual is selected to die. If the average differnce is more than 50%, that individual will be selected to die. Only individuals not selected to die will be copied into the new population. *************************************************************/ void evaluate() { int i, j, k; float ind_fit = 0.0; int gene_fit[NVARS]; float avg_ind_fit = 0.0; float pop_fit = 0.0; int num_survivors; int bad; for(i = 0; i < popsize; i++) { clear(&(new_population[i])); } num_survivors = 0; for (j=0; j < popsize; j++) { avg_ind_fit = 0.0; ind_fit = 0.0; for (i=0; i < NVARS; i++) { gene_fit[i] = (abs)(population[j].gene[i] - environment.gene[i]); ind_fit += (float) gene_fit[i]; } avg_ind_fit = ind_fit/(float) NVARS; pop_fit += avg_ind_fit; bad = FALSE; for (i=0; i 8 || avg_ind_fit > 5.0) { bad = TRUE; /*if gene fitness is less than 8 AND the average individual fitness is greater than 5, keep the individual, else don't copy the individual to the new population*/ } } if(bad == FALSE) { num_survivors++; for(k = 0; k < NVARS; k++) new_population[j].gene[k] = population[j].gene[k]; } } popsize = num_survivors; if(num_survivors != 0) avg_pop_fit = pop_fit/(float) popsize; else avg_pop_fit = 0.0; } /*end of evaluate */ /******************************************************************* MUTATION FOR ASEXUAL AND SEXUAL REPRODUCTION *******************************************************************/ void mutate() { int i, j, k; for (i=0; i 1) crossover(); /*only call for sexually reproducing*/ /*populations*/ for(j=0; j