Esempio n. 1
0
/**
* @brief Initialise an autocoder
* @param autocoder Autocoder object
* @param no_of_inputs The number of inputs
* @param no_of_hiddens The number of hidden (encoder) units
* @param random_seed Random number generator seed
* @return zero on success
*/
int autocoder_init(ac * autocoder,
                   int no_of_inputs,
                   int no_of_hiddens,
                   unsigned int random_seed)
{
    autocoder->NoOfInputs = no_of_inputs;
    autocoder->NoOfHiddens = no_of_hiddens;
    autocoder->inputs =
        (float*)malloc(no_of_inputs*sizeof(float));
    if (!autocoder->inputs) return -1;
    autocoder->hiddens =
        (float*)malloc(no_of_hiddens*sizeof(float));
    if (!autocoder->hiddens) return -2;
    autocoder->bias =
        (float*)malloc(no_of_hiddens*sizeof(float));
    if (!autocoder->bias) return -3;
    autocoder->weights =
        (float*)malloc(no_of_hiddens*no_of_inputs*sizeof(float));
    if (!autocoder->weights) return -4;
    autocoder->lastWeightChange =
        (float*)malloc(no_of_hiddens*no_of_inputs*sizeof(float));
    if (!autocoder->lastWeightChange) return -5;
    autocoder->outputs =
        (float*)malloc(no_of_inputs*sizeof(float));
    if (!autocoder->outputs) return -6;
    autocoder->bperr =
        (float*)malloc(no_of_hiddens*sizeof(float));
    if (!autocoder->bperr) return -7;
    autocoder->lastBiasChange =
        (float*)malloc(no_of_hiddens*sizeof(float));
    if (!autocoder->lastBiasChange) return -8;
    memset((void*)autocoder->inputs,'\0',no_of_inputs*sizeof(float));
    memset((void*)autocoder->outputs,'\0',no_of_inputs*sizeof(float));
    memset((void*)autocoder->hiddens,'\0',
           no_of_hiddens*sizeof(float));
    memset((void*)autocoder->lastWeightChange,'\0',
           no_of_hiddens*no_of_inputs*sizeof(float));
    memset((void*)autocoder->bperr,'\0',
           autocoder->NoOfHiddens*sizeof(float));
    memset((void*)autocoder->lastBiasChange,'\0',
           autocoder->NoOfHiddens*sizeof(float));
    autocoder->BPerror = AUTOCODER_UNKNOWN;
    autocoder->BPerrorAverage = AUTOCODER_UNKNOWN;
    autocoder->learningRate = 0.2f;
    autocoder->noise = 0;
    autocoder->random_seed = random_seed;
    autocoder->itterations = 0;
    autocoder->DropoutPercent = 0.01f;

    /* initial small random values */
    for (int h = 0; h < no_of_hiddens; h++) {
        autocoder->bias[h] =
            (0.2f*(rand_num(&autocoder->random_seed)%10000/10000.0f))-0.1f;
        for (int i = 0; i < no_of_inputs; i++) {
            autocoder->weights[h*no_of_inputs + i] =
                (0.2f*(rand_num(&autocoder->random_seed)%10000/10000.0f))-0.1f;
        }
    }
    return 0;
}
Esempio n. 2
0
/**
* @brief Encodes the inputs to a given array
* @param autocoder Autocoder object
* @param encoded Array to store the encoded values
* @param use_dropouts If non-zero then allow dropouts in the returned results
*/
void autocoder_encode(ac * autocoder, float * encoded, unsigned char use_dropouts)
{
    for (int h = 0; h < autocoder->NoOfHiddens; h++) {
        if (use_dropouts != 0) {
            if (rand_num(&autocoder->random_seed)%10000 <
                autocoder->DropoutPercent*100) {
                autocoder->hiddens[h] = (int)AUTOCODER_DROPPED_OUT;
                continue;
            }
        }

        /* weighted sum of inputs */
        float adder = autocoder->bias[h];
        for (int i = 0; i < autocoder->NoOfInputs; i++) {
            adder +=
                autocoder->weights[h*autocoder->NoOfInputs + i] *
                autocoder->inputs[i];
        }

        /* add some random noise */
        if (autocoder->noise > 0) {
            adder = ((1.0f - autocoder->noise) * adder) +
                (autocoder->noise * ((rand_num(&autocoder->random_seed)%10000)/10000.0f));
        }

        /* activation function */
        encoded[h] = 1.0f / (1.0f + exp(-adder));
    }
}
void generate_colors()
{
    srand(time(NULL));
    int i;
    for(i=0; i<MAX*5; i++)
    {
        color[i].r = rand_num();
        color[i].g = rand_num();
        color[i].b = rand_num();
    }
}
Esempio n. 4
0
File: ebizzy.c Progetto: 1587/ltp
static unsigned int search_mem(void)
{
	record_t key, *found;
	record_t *src, *copy;
	unsigned int chunk;
	size_t copy_size = chunk_size;
	unsigned int i;
	unsigned int state = 0;

	for (i = 0; threads_go == 1; i++) {
		chunk = rand_num(chunks, &state);
		src = mem[chunk];
		/*
		 * If we're doing random sizes, we need a non-zero
		 * multiple of record size.
		 */
		if (random_size)
			copy_size = (rand_num(chunk_size / record_size, &state)
				     + 1) * record_size;
		copy = alloc_mem(copy_size);

		if (touch_pages) {
			touch_mem((char *)copy, copy_size);
		} else {

			if (no_lib_memcpy)
				my_memcpy(copy, src, copy_size);
			else
				memcpy(copy, src, copy_size);

			key = rand_num(copy_size / record_size, &state);

			if (verbose > 2)
				printf("Search key %zu, copy size %zu\n", key,
				       copy_size);
			if (linear)
				found = linear_search(key, copy, copy_size);
			else
				found =
				    bsearch(&key, copy, copy_size / record_size,
					    record_size, compare);

			/* Below check is mainly for memory corruption or other bug */
			if (found == NULL) {
				fprintf(stderr, "Couldn't find key %zd\n", key);
				exit(1);
			}
		}		/* end if ! touch_pages */

		free_mem(copy, copy_size);
	}

	return (i);
}
Esempio n. 5
0
void bubbles()
{
     int r, c, b;
     int size;
     int centerx, centery;
     int outradius, inradius, midradius;
     int bubblesx, bubblesy; /* number of bubbles in a row or column */
     int numbubbles;

     clear_invert_map();

     /*
     * outer is the main bubble
     * inner is the black dot in the bubble
     * what's the middle??
     */

     size = (map.sec_width > map.sec_height ? map.sec_width : map.sec_height);
     outradius = rand_num(size/3, size);
     inradius  = rand_num(outradius/1.5, outradius*(7.0/8.0));
     midradius = (outradius + inradius) / 2;

     midradius = (midradius == 0 ? 1 : midradius);


     bubblesx = map.sec_width  / midradius;
     bubblesy = map.sec_height / midradius;
     numbubbles = (bubblesx * bubblesy);

     numbubbles = (numbubbles == 0 ? 1 : numbubbles);


     for( r = 0; r < map.num_row; r++ )
     {
          for( c = 0; c < map.num_col; c++ )
          {
               for( b = 0; b < numbubbles; b++ )
               {
                    rand_point_section_offset(&centerx, &centery, r, c, 0);

                    /*
                    *centerx *= (centerx / bubblesx);
                    *centery *= (centery / bubblesy);
                    */

                    circlefill(map.map, centerx, centery, outradius, 255);
                    circlefill(map.map, centerx, centery, inradius, 0);
               }
          } /* for(c..) */
     } /* for(r..) */

return;
}
void draw_selected_line(line l)
{
    glEnable(GL_LINE_STIPPLE);
    glLineWidth(8);
    glLineStipple(1,0x00FF);
    glColor3f(rand_num(),rand_num(),rand_num());
    glBegin(GL_LINES);
    glVertex2f(l.p1.x,l.p1.y);
    glVertex2f(l.p2.x,l.p2.y);
    glEnd();
    glDisable(GL_LINE_STIPPLE);
    glLineWidth(2);
}
void draw_point(point p)
{
    /*glBegin(GL_POINTS);
    glColor3f(rand_num(),rand_num(),rand_num());
    glVertex2f(p.x,p.y);
    glEnd();*/
    int i;
    float rad = 1;
    glColor3f(rand_num(),rand_num(),rand_num());
    glBegin(GL_TRIANGLE_FAN);
    for(i=0 ; i<360 ; i++)
        glVertex2f(p.x + rad * cos(DEG2RAD(i)), p.y + rad * sin(DEG2RAD(i)));
    glEnd();
}
Esempio n. 8
0
int
main(int argc, char *argv[])
{
	int i, nloops;
	unsigned int max_num;
	Number x;
	float m1 = 0.0, m2 = 0.0;

	if (argc != 3) {
	   fprintf(stderr, "Usage: %s <max_num> <nloops>\n", argv[0]);
	   exit(1);
	}

	max_num = atoi(argv[1]);
	nloops = atoi(argv[2]);

	for (i = 0; i < nloops; i++) {
		x =  rand_num() % max_num;
		m1 += ((float)x) / nloops;
		m2 += ((float)x*x) / nloops;
	}

	printf("      Average: %lf\n", m1);
	printf("Std.deviation: %lf\n", sqrt(m2 - m1*m1));

	return 0;
}
Esempio n. 9
0
int main(void)
{
	// rand_num doesn't work until first world is initialized :(
	GpWorld * w = gp_world_new();

	for (int i = 0; i < TEST_SIZE; i++) {
		data[i].x = rand_num() * 10000;
		data[i].y = sqrt(data[i].x);
	}

	GpWorldConf default_conf = gp_world_conf_default();

	default_conf.constant_func      = &constant_func;
	default_conf.evaluator          = &eval;
	default_conf.population_size    = 50000;
	default_conf.num_inputs         = 1;
	default_conf.min_program_length = 5;
	default_conf.max_program_length = 30;
	default_conf.num_registers      = 2;
	default_conf.minimize_fitness   = 1;
	default_conf.mutate_rate        = 0.4;

	GpWorldConf confs[4];
	confs[0] = confs[1] = confs[2] = confs[3] = default_conf;

	confs[0].num_registers = 1;
	confs[1].num_registers = 2;
	confs[2].num_registers = 3;
	confs[3].num_registers = 4;

	gp_test_configurations_secs(confs, sizeof(confs)/sizeof(GpWorldConf), 60, 4);
}
Esempio n. 10
0
/*
 * pickup:
 *	pick up a mine or grenade, with some probability of it exploding
 */
static void
pickup(PLAYER *pp, int y, int x, int prob, int obj)
{
	int	req;

	/* Figure out how much ammo the player is trying to pick up: */
	switch (obj) {
	  case MINE:
		req = BULREQ;
		break;
	  case GMINE:
		req = GRENREQ;
		break;
	  default:
#ifdef DIAGNOSTIC
		abort();
#endif
		return;
	}

	/* Does it explode? */
	if (rand_num(100) < prob)
		/* Ooooh, unlucky: (Boom) */
		add_shot(obj, y, x, LEFTS, req, NULL, TRUE, pp->p_face);
	else {
		/* Safely picked it up. Add to player's ammo: */
		pp->p_ammo += req;
		ammo_update(pp);
	}
}
Esempio n. 11
0
/* create a test data set from the original data.
   The test data can be used to calculate a final fitness
   value, because it was not seen during training and so
   provides an indication of how well the system has generalised */
static int create_test_data(float * training_data,
							int * no_of_training_examples,
							int fields_per_example,
							float * test_data)
{
	int i,j,k,index;
	int no_of_test_examples = 0;
	unsigned int random_seed = (unsigned int)time(NULL);

	for (i = 0; i < MAX_TEST_EXAMPLES; i++) {
		/* pick an example from the loaded data set */
		index = rand_num(&random_seed)%(*no_of_training_examples);

		/* increase the number of test examples */
		for (j = 0; j < fields_per_example; j++) {
			test_data[no_of_test_examples*fields_per_example + j] =
				training_data[index*fields_per_example + j];
		}
		no_of_test_examples++;

		/* reshuffle the original data set */
		for (j = index+1; j < (*no_of_training_examples); j++) {
			for (k = 0; k < fields_per_example; k++) {
				training_data[(j-1)*fields_per_example + k] = 
					training_data[j*fields_per_example + k];
			}
		}
		/* decrease the number of training data examples */
		*no_of_training_examples = *no_of_training_examples - 1;
	}

	return no_of_test_examples;
}
Esempio n. 12
0
void Utility::random_string(string &random, unsigned length)
{
    CryptoPP::AutoSeededRandomPool RNG;
    CryptoPP::Integer rand_num(RNG, 32);

	for(unsigned i = 0; i < length; ++i)
	{
		unsigned num;

        if(!rand_num.IsConvertableToLong())
            num = std::numeric_limits<unsigned>::max() + static_cast<unsigned>(rand_num.AbsoluteValue().ConvertToLong());
        else
            num = static_cast<unsigned>(rand_num.AbsoluteValue().ConvertToLong());
        

        num = num % 122;
        if(48 > num)
			num += 48;
		
        if(57 < num && 65 > num)
            num += 7;
		
        if(90 < num && 97 > num)
            num += 6;
		
        random += static_cast<char>(num);
        rand_num.Randomize(RNG, 32);
	}
}
Esempio n. 13
0
/*
 * makeboots:
 *	Put the boots in the maze
 */
static void
makeboots(void)
{
	int	x, y;
	PLAYER	*pp;

	if (conf_boots) {
		do {
			x = rand_num(WIDTH - 1) + 1;
			y = rand_num(HEIGHT - 1) + 1;
		} while (Maze[y][x] != SPACE);
		Maze[y][x] = BOOT_PAIR;
	}

	for (pp = Boot; pp < &Boot[NBOOTS]; pp++)
		pp->p_flying = -1;
}
Esempio n. 14
0
/**
 * Returns a pointer to a newly allocated array of length len
 * containing random integer elements.
 */
int *rand_array(int len)
{
    int *int_arr = (int*) malloc(len * sizeof(int));

    for (int i = 0; i < len; i++) {
        int_arr[i] = rand_num();
    }
    return int_arr;
}
/* generates a ramdom grid for given 
   site vacancy probability */
void grid_create(grid *grd, double prob)
{
    int i, j;
    
    for (i = 0; i < grd->height; i++)
        for (j = 0; j < grd->width; j++)
             grd->cells[grd->width * i + j] = (rand_num() < prob) ? SITE_OPEN : SITE_BLOCK;
    
}
Esempio n. 16
0
/**
* @brief Randomly sets exclusion flags to cause units to drop out
* @param net Backprop neural net object
*/
static void bp_dropouts(bp * net)
{
    int l,i,no_of_dropouts,hidden_units,n;

    if (net->DropoutPercent==0) return;

    /* total number of hidden units */
    hidden_units = net->HiddenLayers * net->NoOfHiddens;

    /* total number of dropouts */
    no_of_dropouts = net->DropoutPercent*hidden_units/100;

    /* set the exclusion flags */
    for (n = 0; n < no_of_dropouts; n++) {
        l = rand_num(&net->random_seed)%net->HiddenLayers;
        i = rand_num(&net->random_seed)%net->NoOfHiddens;
        net->hiddens[l][i]->excluded = 1;
    }
}
Esempio n. 17
0
// DESC: modifies health of patient if machine happens to harm user
// PRE: patient must have modify_help member function
// POST: patient.condition will be modified to reflect damage, returns
//       nothing
void x_rayer::apply(patient & user)
{
  
  // halve patient condition randomly. odds are 1 in DAMAGE_CHANCE
  if (rand_num(0,X_RAYER_DAMAGE_CHANCE) == 0)
    user.modify_phys_health(-user.get_phys_health()/2);
  
  m_num_uses += 1;
  
  return;
}
Esempio n. 18
0
int*
gen_test_arr(int size) {
    int* arr = (int*)malloc(size * sizeof(int));
    assert(arr);

    int i;
    for (i = 0; i < size; ++i) {
        arr[i] = rand_num(0, size);
    }

    return arr;
}
Esempio n. 19
0
/**
* @brief Performs a single training step
* @param learner Deep learner object
* @returns 1=pretraining,2=final training,0=training complete,-1=no training data
*/
int deeplearndata_training(deeplearn * learner)
{
    if (learner->training_data_samples == 0) {
        return -1;
    }

    /* plot a graph showing training progress */
    if (learner->training_ctr > learner->history_plot_interval) {
        if (strlen(learner->history_plot_filename) > 0) {
            deeplearn_plot_history(learner,
                                   learner->history_plot_filename,
                                   learner->history_plot_title,
                                   1024, 480);
        }
        learner->training_ctr = 0;
    }
    learner->training_ctr++;

    if ((learner->net->HiddenLayers > 1) &&
        (learner->current_hidden_layer < learner->net->HiddenLayers)) {
        /* index number of a random training sample */
        int index = rand_num(&learner->net->random_seed)%learner->training_data_samples;
        /* get the sample */
        deeplearndata * sample = deeplearndata_get_training(learner, index);
        deeplearn_set_inputs(learner, sample);
        deeplearn_update(learner);
        return 1;
    }
    if (learner->training_complete == 0) {
        /* index number of a random training sample */
        int index = rand_num(&learner->net->random_seed)%learner->training_data_labeled_samples;
        /* get the sample */
        deeplearndata * sample = deeplearndata_get_training_labeled(learner, index);
        deeplearn_set_inputs(learner, sample);
        deeplearn_set_outputs(learner, sample);
        deeplearn_update(learner);
        return 2;
    }
    return 0;
}
Esempio n. 20
0
/*********************************************************
 ******************    Main Function    ******************
 *********************************************************/
int main(int agrc, char *agrv[])
{
    int rt = 0; /* return value of function main */
    
    srandom((unsigned int)time(NULL));
    printf("rand num: \n");
    while (rt++ < 100)
        printf("%d ", rand_num(10,50));
        //printf("rand num: %d\n", rand_num(10,50));
    printf("\n");

    return rt;
}
Esempio n. 21
0
double monte_carlo(MINTEGP ap)
{
  int m;
  double a,b,r,x,s;
  a=ap->a;b=ap->b;r=1.0;s=0.0;
  for(m=0;m<ap->m;m++)
  {
    x=a+(b-a)*rand_num(&r);
    s=s+(*ap->ptr)(x)/ap->m;
  }
  s=s*(b-a);
  return s;
}
Esempio n. 22
0
void test_matrix_rotate(void)
{
    Matrix3f m1, m2, diff;
    Vector3f r;

    m1.identity();
    m2.identity();
    r.x = rand_num();
    r.y = rand_num();
    r.z = rand_num();

    for (uint16_t i = 0; i<1000; i++) {
        // old method
        Matrix3f temp_matrix;
        temp_matrix.a.x = 0;
        temp_matrix.a.y = -r.z;
        temp_matrix.a.z =  r.y;
        temp_matrix.b.x =  r.z;
        temp_matrix.b.y = 0;
        temp_matrix.b.z = -r.x;
        temp_matrix.c.x = -r.y;
        temp_matrix.c.y =  r.x;
        temp_matrix.c.z = 0;
        temp_matrix = m1 * temp_matrix;
        m1 += temp_matrix;

        // new method
        m2.rotate(r);

        // check they behave in the same way
        diff = m1 - m2;
        float err = diff.a.length() + diff.b.length() + diff.c.length();

        if (err > 0) {
            hal.console->printf("ERROR: i=%u err=%f\n", (unsigned)i, err);
        }
    }
}
Esempio n. 23
0
/**
 * Return a random direction.
 * \return A random number representing a direction.
 */
int rand_dir() {
	switch (rand_num(4)) {
	case 0:
		return LEFTS;
	case 1:
		return RIGHT;
	case 2:
		return BELOW;
	case 3:
		return ABOVE;
	}
	/* NOTREACHED */
	return (-1);
}
Esempio n. 24
0
static float evaluate_features(int trials,
							   gprcm_population * population,
							   int individual_index,
							   int custom_command)
{
	int i,j,itt,n;
	float error,diff=0,v,reference,fitness;
	float dropout_rate = 0.2f;
	gprcm_function * f = &population->individual[individual_index];

	if (custom_command!=0) dropout_rate=0;

	for (i = 0; i < trials; i++) {
		/* clear the state */
		gprcm_clear_state(f,
						  population->rows, population->columns,
						  population->sensors, population->actuators);

		/* Randomly pick an example.
		   This discourages any ordering bias */
		n = rand_num(&f->program.random_seed)%trials;

		for (j=1;j<fields_per_example-3;j++) {
			gprcm_set_sensor(f,j-1,
							 current_data_set[n*fields_per_example+j]);
		}
		for (itt = 0; itt < RUN_STEPS; itt++) {
			/* run the program */
			gprcm_run(f, population, dropout_rate, 0, 0);
		}
		/* how close is the output to the actual slump? */
		for (j=0;j<3;j++) {
			reference =
				0.01f + fabs(current_data_set[n*fields_per_example+
											  fields_per_example-3+j]);
			v = 0.01f + fabs(gprcm_get_actuator(f,j,
												population->rows,
												population->columns,
												population->sensors));

			error = fabs(v - reference)/reference;
			diff += error*error;
		}
	}
	diff = (float)sqrt(diff/(float)(trials*3))*100;
	fitness = 100 - diff;
	if (fitness<0) fitness=0;
	return fitness;
}
//This function manages the game.
void play(void)
{

    int total = 8;
    int index = 0;
    int i = 0;
    int max = 0;
    char str[10];
    //create an array of strings
    char words[9][6] = {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};
    //create an array of numbers
    int nums[9] = {0,1,2,3,4,5,6,7,8};

    printf("\n\nWelcome to the Typing Speed Game!!\nType these words as fast as you can!");

    printf("\nReady??\nPress ENTER to start.");
    getchar();

    struct timeval before, after;
    gettimeofday(&before, NULL);  //get the time at the start of the game

    while (total > 0)  //randomize the array of integers by swapping the last for a random number within the array, this is repeated for all the numbers.
    {
        index = rand_num(total);

        max = nums[total];
        nums[total] = nums[index];  //shuffle the two numbers
        nums[index] = max;
        --total; //decriment the total to leave the numbers that have been shuffled alone.
    }

    for (i = 0; i < 9; ++i) //Print the word that corresponds to the number in the array. User must match the word exactly to proceed to the next.
    {
        do
        {
            printf("\nWord #%d is %s: ",i+1, words[nums[i]]); //print the word
            scanf("%9s", str);  //input a word from the user
            if (strcmp(str,words[nums[i]]) !=0)
                printf("Incorrect. Try again.\n");  //if not a match, try again
        } while(strcmp(str, words[nums[i]]) != 0);

    }
    gettimeofday(&after, NULL);  //get the time at the end of the game

    //Calculate the difference between the start and end time, then print it along with the time calculated in seconds.
    printf("\n\nCorrect!  Your time is: %.0lf sec, %.0lf usec\n" ,(time_diff(before, after) * 1.0e-6), time_diff(before, after));


}
void draw_line2(point p1,point p2)
{
    if(light_transport_mode)
    {
        int i = 0;
        float dist = distance_between_points(p1,p2);
        float d0 = dist/8;
        float d1 = rand_num()*d0;
        float theta = atan2((p2.y-p1.y),(p2.x-p1.x));
        float tot_dist = d1;
        float ctheta = cos(theta),stheta = sin(theta);
        p2.x = p1.x + d1*ctheta;
        p2.y = p1.y + d1*stheta;
        glBegin(GL_LINES);
        glVertex2f(p1.x,p1.y);
        glVertex2f(p2.x,p2.y);
        while(1)
        {
            p1 = p2;
            if(tot_dist+d0 > dist)
            {
                d0 = dist - tot_dist;
                p2.x = p1.x + d0*ctheta;
                p2.y = p1.y + d0*stheta;
                if(i%2)
                {
                    glVertex2f(p1.x,p1.y);
                    glVertex2f(p2.x,p2.y);
                }
                break;
            }
            p2.x = p1.x + d0*ctheta;
            p2.y = p1.y + d0*stheta;
            if(i%2)
            {
                glVertex2f(p1.x,p1.y);
                glVertex2f(p2.x,p2.y);
            }
            tot_dist += d0;
            i++;
        }
        glEnd();
        return;
    }
    glBegin(GL_LINES);
    glVertex2f(p1.x,p1.y);
    glVertex2f(p2.x,p2.y);
    glEnd();
}
Esempio n. 27
0
static float evaluate_features(int trials,
							   gprcm_population * population,
							   int individual_index,
							   int mode)
{
	int i,j,itt,n;
	float diff=0,v,crime_rate,error,fitness;
	float dropout_rate = 0.0f;
	gprcm_function * f = &population->individual[individual_index];

	for (i = 0; i < trials; i++) {
		/* clear the state */
		gprcm_clear_state(f,
						  population->rows, population->columns,
						  population->sensors, population->actuators);

		/* randomly choose and example */
		n = rand_num(&f->program.random_seed)%trials;

		/* set the sensor values */
		for (j=INITIAL_FIELDS;j<fields_per_example-1;j++) {
			gprcm_set_sensor(f,j-INITIAL_FIELDS,
							 current_data_set[n*fields_per_example+j]);
		}

		for (itt = 0; itt < RUN_STEPS; itt++) {
			/* run the program */
			gprcm_run(f, population, dropout_rate, 0, 0);
		}

		/* how close is the output to the actual crime level? */
		crime_rate =
			0.0001f +
			current_data_set[n*fields_per_example+fields_per_example-1];

		v = fabs(gprcm_get_actuator(f,0,population->rows,
									population->columns,
									population->sensors));

		error = (v - crime_rate)/crime_rate;
		diff += error*error;
	}
	diff = (float)sqrt(diff/trials)*100;
	fitness = 100 - diff;
	if (fitness < 0) fitness=0;
	return fitness;
}
Esempio n. 28
0
int main(void)
{
	GpWorld * world = gp_world_new();

	for (int i = 0; i < TEST_SIZE; i++) {
		data[i].x = rand_num() * 10000;
		data[i].y = sqrt(data[i].x);
	}

	GpWorldConf conf = gp_world_conf_default();
	conf.constant_func      = &constant_func;
	conf.evaluator          = &eval;
	conf.num_inputs         = 1;
	conf.minimize_fitness   = 1;

	gp_world_initialize(world, conf);

	uint loops = 0;
	uint total_steps = 0;
	float ips = 0.0;

	for (;;)
	{
		uint times = gp_world_evolve_secs(world, 1);
		ips = (ips * loops + times) / (loops + 1);
		total_steps += times;

		printf("Best: %-9.2f  Avg: %-9.2f  Gens: %-3u  Steps/sec: %-10.2f  Avg Len: %-5.2f\n",
			world->stats.best_fitness,
			world->stats.avg_fitness,
			world->stats.total_generations,
			ips,
			world->stats.avg_program_length);

		loops++;

		// Run for 60 seconds.
		if (loops > 60) {
			gp_program_export_python(stdout, world, &world->programs[0]);
			return 0;
		}
	}
}
Esempio n. 29
0
/* select the best individual to breed from */
void paintatron::select_best(int index)
{
    int i;

    for (i = 0; i < population; i++) {
        if (i != index) {
            if ((&sys.island[0])->fitness[i] > 20) {
                (&sys.island[0])->fitness[i] /= 2;
            }
            else {
                (&sys.island[0])->fitness[i] =
                    rand_num(&random_seed)%10000/100000.0f;
            }
        }
        else {
            (&sys.island[0])->fitness[i] = 99;
        }
    }
}
Esempio n. 30
0
//
// `gp_world_optimize_test` will set up a sample problem and record
// program outputs for many inputs, then run a whole-world optimization,
// and rerun all the programs making sure the outputs haven't changed
//
void gp_world_optimize_test()
{

	GpWorld * world = gp_world_new();

	for (int i = 0; i < TEST_SIZE; i++)
		_test_data[i] = rand_num() * 10000;

	GpWorldConf conf = gp_world_conf_default();
	conf.constant_func = &_test_constant_func;
	conf.evaluator = &_test_eval;
	conf.num_inputs = 1;

	gp_world_initialize(world, conf);

	uint i, j;

	for (i = 0; i < world->conf.population_size; i++)
	{
		for (j = 0; j < TEST_SIZE; j++)
		{
			GpState state = gp_program_run(world, &world->programs[i], _test_data + j);
			_test_out[j] = state.registers[0];
		}
		_remove_introns(world, &world->programs[i]);
		for (j = 0; j < TEST_SIZE; j++)
		{
			GpState state = gp_program_run(world, &world->programs[i], _test_data + j);
			if (state.registers[0] != _test_out[j])
				printf("ERROR! Intron removal changed program output: %f vs %f\n",
					state.registers[0], _test_out[j]);
		}
	}

	gp_world_delete(world);
}