コード例 #1
0
ファイル: fitness.c プロジェクト: emkev/genetic
int main(int argc , char **argv)
{
  int i , j , t , targetlen , parent_a , parent_b ;
  int *numcorrect; 
  char **newpop , **oldpop , **swap;
  double *normfit;

  //srandom(seed);
  srand((unsigned)time(NULL));

  // whether to consider forcing the size to be even . 

  targetlen = 10;
  printf("hello! \n");
  newpop = malloc(sizeof(char *) * size);
  oldpop = malloc(sizeof(char *) * size);
  printf("hello 1-1 \n");
  numcorrect = malloc(sizeof(int) * size);
  normfit = malloc(sizeof(double) * size);
  printf("hello2 \n");
  for(i = 0 ; i < size ; i++)
  {
    newpop[i] = malloc(sizeof(char) * targetlen + 1);
    oldpop[i] = malloc(sizeof(char) * targetlen + 1);
    for(j = 0 ; j < targetlen ; j++)
    {
      oldpop[i][j] = random_letter_or_space();
    }
    newpop[i][targetlen] = 0;
    oldpop[i][targetlen] = 0;
  }

  for(t = 0 ; t < steps ; t++)
  {
    compute_fitness(oldpop , numcorrect , normfit);
    dump_stats(numcorrect , oldpop , t + 1 , targetlen);
    for(i = 0 ; i < size ; i += 2)
    {
      parent_a = select_one(normfit);
      parent_b = select_one(normfit);
      // whether to add parent_a can not be equal to parent_b .  
      //printf("p_a = %d , p_b = %d \n" , parent_a , parent_b);
      reproduce(oldpop , newpop , parent_a , parent_b , targetlen , i);
    }
    
    swap = oldpop;
    oldpop = newpop;
    newpop = swap; 
    /*
    swap = newpop;
    newpop = oldpop;
    oldpop = swap;
    */
  }
  exit(0);
}
コード例 #2
0
int main(int argc, char *args[]) {
	char buffer[255];	// Buffer for sending data
	int i;			// Index
  
	if (argc == 4) { // Get parameters
		offset = atoi(args[1]);
		migrx = atof(args[2]);
		migrz = atof(args[3]);
		//migration goal point comes from the controller arguments. It is defined in the world-file, under "controllerArgs" of the supervisor.
		printf("Migratory instinct : (%f, %f)\n", migrx, migrz);
	} else {
		printf("Missing argument\n");
		return 1;
	}
	
	orient_migr = -atan2f(migrx,migrz);
	if (orient_migr<0) {
		orient_migr+=2*M_PI; // Keep value within 0, 2pi
	}

	reset();

         send_init_poses();
	
	// Compute reference fitness values
	
	float fit_cluster;			// Performance metric for aggregation
	float fit_orient;			// Performance metric for orientation
		
	for(;;) {
		wb_robot_step(TIME_STEP);
		
		if (t % 10 == 0) {
			for (i=0;i<FLOCK_SIZE;i++) {
				// Get data
				loc[i][0] = wb_supervisor_field_get_sf_vec3f(robs_trans[i])[0]; // X
				loc[i][1] = wb_supervisor_field_get_sf_vec3f(robs_trans[i])[2]; // Z
				loc[i][2] = wb_supervisor_field_get_sf_rotation(robs_rotation[i])[3]; // THETA
				
                    		// Sending positions to the robots, comment the following two lines if you don't want the supervisor sending it                   		
                  		sprintf(buffer,"%1d#%f#%f#%f##%f#%f",i+offset,loc[i][0],loc[i][1],loc[i][2], migrx, migrz);
                  		wb_emitter_send(emitter,buffer,strlen(buffer));				
    			}
			//Compute and normalize fitness values
			compute_fitness(&fit_cluster, &fit_orient);
			fit_cluster = fit_cluster_ref/fit_cluster;
			fit_orient = 1-fit_orient/M_PI;
			printf("time:%d, Topology Performance: %f\n", t, fit_cluster);			
			
		}
		
		t += TIME_STEP;
	}

}
コード例 #3
0
ファイル: e-puck_drive.c プロジェクト: daydin/maze
//
// Trial to test the robot's behavior (according to NN) in the environment
//
double run_trial() {

  double inputs[NB_INPUTS];
  double outputs[NB_OUTPUTS];
  
  //Get position of the e-puck
  static double position[3]={0.0,0.0,0.0};
  const double *gps_matrix = wb_gps_get_values(gps);
  position[0] = gps_matrix[0];//gps_position_x(gps_matrix);
  position[1] = gps_matrix[2];//gps_position_z(gps_matrix);
  position[2] = gps_matrix[1];//gps_position_y(gps_matrix);
  
  //Speed of the robot's wheels within the +SPEED_RANGE and -SPEED_RANGE values
  int speed[2]={0,0};
  //Maximum activation of all IR proximity sensors [0,1]
  double maxIRActivation = 0;

  //get sensor data, i.e., NN inputs
  int i, j;
  for(j=0;j<NB_INPUTS;j++) {
    inputs[j]=(((double)wb_distance_sensor_get_value(ps[j])-ps_offset[j])<0)?0:((double)wb_distance_sensor_get_value(ps[j])-ps_offset[j])/((double)PS_RANGE);
    //get max IR activation
    if(inputs[j]>maxIRActivation) maxIRActivation=inputs[j];
    printf("sensor #: %d, sensor read: %g, maxIR: %g\n", j, inputs[j], maxIRActivation);
  }
  //printf("max IR activation: %f\n", maxIRActivation);

  // Run the neural network and computes the output speed of the robot
  run_neural_network(inputs, outputs); 
  
  speed[LEFT]  = SPEED_RANGE*outputs[0];
  speed[RIGHT] = SPEED_RANGE*outputs[1];
  
  // If you are running against an obstacle, stop the wheels
  if ( maxIRActivation > 0.9 ) {
    speed[LEFT]=0;
    speed[RIGHT]=0;
  }
  // Set wheel speeds to output values
  wb_differential_wheels_set_speed(speed[LEFT], speed[RIGHT]); //left, right
  
  // Stop the robot if it is against an obstacle
  for (i=0;i<NB_DIST_SENS;i++) {
    int tmpps=(((double)wb_distance_sensor_get_value(ps[i])-ps_offset[i])<0)?0:((double)wb_distance_sensor_get_value(ps[i])-ps_offset[i]);
    
    if(OBSTACLE_THRESHOLD<tmpps ) {// proximity sensors 
      //printf("%d \n",tmpps);
      speed[LEFT]  = 0;
      speed[RIGHT] = 0;
      break;
    }
  }
  
  return compute_fitness(speed, position, maxIRActivation);
}
コード例 #4
0
ファイル: drive2.c プロジェクト: daydin/maze
double run_trial() {

	int speed[2]={0,0};


	//Maximum activation of all IR proximity sensors [0,1]
	//double maxIRActivation = 0;

	//get sensor data, i.e., NN inputs
	int j;
	for(j=0;j<NB_DIST_SENS;j++) {
		//printf("sensor %d reads %g\n",j,wb_distance_sensor_get_value(ps[j]));
		temp[j]=(((double)wb_distance_sensor_get_value(ps[j])-ps_offset[j])<0)?0:(((double)wb_distance_sensor_get_value(ps[j])-ps_offset[j])/((double)PS_RANGE));
	}

	for(j=0;j<NB_PS;j++) {
		//printf("sensor %d reads %g\n",j,wb_distance_sensor_get_value(ps[j]));
		inputs[j]=(temp[2*j]+temp[(2*j)+1])/2.0;

	}
            inputs[4]= wb_distance_sensor_get_value(fs[0])-fs_offset[0];
            //printf("floor sensor:%g\n",inputs[4]);
            
          
	// Run the neural network and computes the output speed of the robot
	run_neural_network(inputs, outputs);

	speed[LEFT]  =  clip_value(outputs[0],max_speed); //scale  outputs between 0 and 1
	speed[RIGHT] =  clip_value(outputs[1],max_speed);
	//printf("L: %d; R: %d\n",speed[LEFT],speed[RIGHT]);

	// Set wheel speeds to output values
	wb_differential_wheels_set_speed(speed[LEFT], speed[RIGHT]); //left, right
	//printf("Set wheels to outputs.\n");

	return compute_fitness(inputs[4]);
	return compute_fitness(inputs[4]);
}
コード例 #5
0
ファイル: gabump.c プロジェクト: Stray/CBofN
int main(int argc, char **argv)
{
  int i, j, t, parent_a, parent_b;
  char **swap, **newpop, **oldpop;
  double *fit, *normfit;
  
  get_options(argc, argv, options, help_string);

  srandom(seed);

  /* Force the size to be even. */
  size += (size / 2 * 2 != size);

  /* Initialize the population. */
  newpop = xmalloc(sizeof(char *) * size);
  oldpop = xmalloc(sizeof(char *) * size);
  fit = xmalloc(sizeof(double) * size);
  normfit = xmalloc(sizeof(double) * size);
  for(i = 0; i < size; i++) {
    newpop[i] = xmalloc(sizeof(char) * len + 1);
    oldpop[i] = xmalloc(sizeof(char) * len + 1);
    for(j = 0; j < len; j++)
      oldpop[i][j] = random() % 2 + '0';
    oldpop[i][len] = 0;
    newpop[i][len] = 0;
  }

  /* For each time step... */
  for(t = 0; t < gens; t++) {
    compute_fitness(oldpop, fit, normfit);
    dump_stats(t, oldpop, fit);

    /* Pick two parents by fitness and mate them until the
     * next generation has been made.
     */
    for(i = 0; i < size; i += 2) {
      parent_a = select_one(normfit);
      parent_b = select_one(normfit);
      reproduce(oldpop, newpop, parent_a, parent_b, i);
    }
    /* Make everything old new again. */
    swap = newpop; newpop = oldpop; oldpop = swap;
  }

  exit(0);
}
コード例 #6
0
void EXP_Class::adv ( void ){
 //cout << "enter advance" << endl;
  if( viewing ) stop_iterations_loop( );
  
  update_sensors( );//here you compute the input vector
  
  update_controllers ( ); //here you update the controllers and you generate a new output vector
  
  if( viewing ) param->eye->view_eye_movement();
  
  update_world(); //Here you call the set eye fucntion to upadte the eye position given the output vector

  //manage_collisions ( );

  compute_fitness();
  
  iter++;
  //cout << "leave advance" << endl;
}
コード例 #7
0
//---------------------------------------------------------------------------
void start_steady_state(t_parameters &params, t_graph *training_graphs, int num_training_graphs, t_graph *validation_graphs, int num_validation_graphs, int num_variables, int num_procs, int current_proc_id)
{

	int size_to_send = params.code_length * sizeof(t_code3) + params.num_constants * 20 + 20;
	char *s_source = new char[size_to_send];
	char *s_dest = new char[size_to_send];

	t_chromosome receive_chromosome;
	allocate_chromosome(receive_chromosome, params);


	// a steady state model - 
	// Newly created inviduals replace the worst ones (if the offspring are better) in the same (sub) population.

	// allocate memory for all sub populations
	t_chromosome **sub_populations; // an array of sub populations
	sub_populations = new t_chromosome*[params.num_sub_populations];
	for (int p = 0; p < params.num_sub_populations; p++) {
		sub_populations[p] = new t_chromosome[params.sub_population_size];
		for (int i = 0; i < params.sub_population_size; i++)
			allocate_chromosome(sub_populations[p][i], params); // allocate each individual in the subpopulation 
	}
#ifdef USE_THREADS
	// allocate memory
	double** vars_values = new double*[params.num_threads];
	for (int t = 0; t < params.num_threads; t++)
		vars_values[t] = new double[num_variables];

	// an array of threads. Each sub population is evolved by a thread
	std::thread **mep_threads = new std::thread*[params.num_threads];
	// we create a fixed number of threads and each thread will take and evolve one subpopulation, then it will take another one
	std::mutex mutex;
	// we need a mutex to make sure that the same subpopulation will not be evolved twice by different threads
#else
	double* vars_values = new double[num_variables];
#endif

	t_chromosome best_validation;
	allocate_chromosome(best_validation, params);
	double best_validation_fitness = DBL_MAX;

	// evolve for a fixed number of generations
	for (int generation = 0; generation < params.num_generations; generation++) { // for each generation

#ifdef USE_THREADS
		int current_subpop_index = 0;
		for (int t = 0; t < params.num_threads; t++)
			mep_threads[t] = new std::thread(evolve_one_subpopulation, &current_subpop_index, &mutex, sub_populations, generation, &params, training_graphs, num_training_graphs, num_variables, vars_values[t]);

		for (int t = 0; t < params.num_threads; t++) {
			mep_threads[t]->join();
			delete mep_threads[t];
		}
#else
		//for (int p = 0; p < params.num_sub_populations; p++)
		int p = 0;
		evolve_one_subpopulation(&p, sub_populations, generation, &params, training_graphs, num_training_graphs, num_variables, vars_values);
#endif
		// find the best individual
		int best_individual_subpop_index = 0; // the index of the subpopulation containing the best invidual

		for (int p = 1; p < params.num_sub_populations; p++)
			if (sub_populations[p][0].fitness < sub_populations[best_individual_subpop_index][0].fitness)
				best_individual_subpop_index = p;

		double *partial_values_array = new double[params.code_length];

		sub_populations[best_individual_subpop_index][0].simplify(params.code_length);
		double current_validation_fitness = compute_fitness(sub_populations[best_individual_subpop_index][0], validation_graphs, num_validation_graphs, num_variables, vars_values, partial_values_array);

		if (!generation || generation && current_validation_fitness < best_validation_fitness) {
			best_validation_fitness = current_validation_fitness;
			copy_individual(best_validation, sub_populations[best_individual_subpop_index][0], params);
		}
		delete[] partial_values_array;

		printf("proc_id=%d, generation=%d, best training =%lf best validation =%lf\n", current_proc_id, generation, sub_populations[best_individual_subpop_index][0].fitness, best_validation_fitness);

		if (current_proc_id == 0) {
			FILE* f = fopen("tst_log.txt", "a");
			fprintf(f, "proc_id=%d, generation=%d, best=%lf\n", current_proc_id, generation, sub_populations[best_individual_subpop_index][0].fitness);
			fclose(f);
		}

		// now copy one individual from one population to the next one.
		// the copied invidual will replace the worst in the next one (if is better)

		for (int p = 0; p < params.num_sub_populations; p++) {
			int  k = rand() % params.sub_population_size;// the individual to be copied
			// replace the worst in the next population (p + 1) - only if is better
			int index_next_pop = (p + 1) % params.num_sub_populations; // index of the next subpopulation (taken in circular order)
			if (sub_populations[p][k].fitness < sub_populations[index_next_pop][params.sub_population_size - 1].fitness) {
				copy_individual(sub_populations[index_next_pop][params.sub_population_size - 1], sub_populations[p][k], params);
				qsort((void *)sub_populations[index_next_pop], params.sub_population_size, sizeof(sub_populations[0][0]), sort_function);
			}
		}

#ifdef USE_MPI
		// here I have to copy few individuals from one process to another process
		for (int i = 0; i < 1; i++) {
			int source_sub_population_index = rand() % params.num_sub_populations;
			int chromosome_index = rand() % params.sub_population_size;
			int tag = 0;

			sub_populations[source_sub_population_index][chromosome_index].to_string(s_dest, params.code_length, params.num_constants);
			MPI_Send((void*)s_dest, size_to_send, MPI_CHAR, (current_proc_id + 1) % num_procs, tag, MPI_COMM_WORLD);

			MPI_Status status;
			int flag;
			MPI_Iprobe(!current_proc_id ? num_procs - 1 : current_proc_id - 1, tag, MPI_COMM_WORLD, &flag, &status);
			if (flag) {
				MPI_Recv(s_source, size_to_send, MPI_CHAR, !current_proc_id ? num_procs - 1 : current_proc_id - 1, tag, MPI_COMM_WORLD, &status);
				receive_chromosome.from_string(s_source, params.code_length, params.num_constants);

				int dest_sub_population_index = rand() % params.num_sub_populations;
				if (receive_chromosome.fitness < sub_populations[dest_sub_population_index][params.sub_population_size - 1].fitness) {
					copy_individual(sub_populations[dest_sub_population_index][params.sub_population_size - 1], receive_chromosome, params);
					qsort((void *)sub_populations[dest_sub_population_index], params.sub_population_size, sizeof(sub_populations[0][0]), sort_function);
				}
			}
		}


#endif
	}

#ifdef USE_THREADS
	delete[] mep_threads;
#endif
	// print best t_chromosome
	// any of them can be printed because if we allow enough generations, the populations will become identical
	print_chromosome(best_validation, params, num_variables);
	best_validation.to_file_simplified("best.txt", params.code_length, params.num_constants);

	// free memory

	for (int p = 0; p < params.num_sub_populations; p++) {
		for (int i = 0; i < params.sub_population_size; i++)
			delete_chromosome(sub_populations[p][i]);
		delete[] sub_populations[p];
	}
	delete[] sub_populations;

#ifdef USE_THREADS
	for (int t = 0; t < params.num_threads; t++)
		delete[] vars_values[t];
	delete[] vars_values;
#endif

	delete[] s_dest;
	delete[] s_source;

	delete_chromosome(receive_chromosome);
	delete_chromosome(best_validation);
}
コード例 #8
0
void evolve_one_subpopulation(int *current_subpop_index, t_chromosome ** sub_populations, int generation_index, t_parameters *params, t_graph *training_graphs, int num_training_graphs, int num_variables, double* vars_values)
#endif
{
	int pop_index = 0;
	while (*current_subpop_index < params->num_sub_populations) {// still more subpopulations to evolve?
#ifdef USE_THREADS
		while (!mutex->try_lock()) {}// create a lock so that multiple threads will not evolve the same sub population
		pop_index = *current_subpop_index;
		(*current_subpop_index)++;
		mutex->unlock();
#else
		pop_index = *current_subpop_index;
		(*current_subpop_index)++;
#endif

		// pop_index is the index of the subpopulation evolved by the current thread
		if (pop_index < params->num_sub_populations) {
			t_chromosome *a_sub_population = sub_populations[pop_index];

			t_chromosome offspring1, offspring2;
			allocate_chromosome(offspring1, *params);
			allocate_chromosome(offspring2, *params);

			double *partial_values_array = new double[params->code_length];

			if (generation_index == 0) {
				for (int i = 0; i < params->sub_population_size; i++) {
					generate_random_chromosome(a_sub_population[i], *params, num_variables);

					a_sub_population[i].fitness = compute_fitness(a_sub_population[i], training_graphs, num_training_graphs, num_variables, vars_values, partial_values_array);

				}
				// sort ascendingly by fitness inside this population
				qsort((void *)a_sub_population, params->sub_population_size, sizeof(a_sub_population[0]), sort_function);
			}
			else // next generations
				for (int k = 0; k < params->sub_population_size; k += 2) {
					// we increase by 2 because at each step we create 2 offspring

					// choose the parents using binary tournament
					int r1 = tournament_selection(a_sub_population, params->sub_population_size, 2);
					int r2 = tournament_selection(a_sub_population, params->sub_population_size, 2);
					// crossover
					double p_0_1 = rand() / double(RAND_MAX); // a random number between 0 and 1
					if (p_0_1 < params->crossover_probability)
						one_cut_point_crossover(a_sub_population[r1], a_sub_population[r2], *params, offspring1, offspring2);
					else {// no crossover so the offspring are a copy of the parents
						copy_individual(offspring1, a_sub_population[r1], *params);
						copy_individual(offspring2, a_sub_population[r2], *params);
					}
					// mutate the result and compute fitness
					mutation(offspring1, *params, num_variables);
					offspring1.fitness = compute_fitness(offspring1, training_graphs, num_training_graphs, num_variables, vars_values, partial_values_array);

					// mutate the other offspring too
					mutation(offspring2, *params, num_variables);
					offspring2.fitness = compute_fitness(offspring2, training_graphs, num_training_graphs, num_variables, vars_values, partial_values_array);

					// replace the worst in the population
					if (offspring1.fitness < a_sub_population[params->sub_population_size - 1].fitness) {
						copy_individual(a_sub_population[params->sub_population_size - 1], offspring1, *params);
						qsort((void *)a_sub_population, params->sub_population_size, sizeof(a_sub_population[0]), sort_function);
					}
					if (offspring2.fitness < a_sub_population[params->sub_population_size - 1].fitness) {
						copy_individual(a_sub_population[params->sub_population_size - 1], offspring2, *params);
						qsort((void *)a_sub_population, params->sub_population_size, sizeof(a_sub_population[0]), sort_function);
					}
				}

			delete_chromosome(offspring1);
			delete_chromosome(offspring2);

			delete[] partial_values_array;
		}
	}
}
コード例 #9
0
ファイル: formation_super.c プロジェクト: hubifant/disProject
/*
 * Main function.
 */
int main(int argc, char *args[]) {

    float fitness;

    // The type of formation is decided by the user through the world
    char* formation = DEFAULT_FORMATION; 
    if(argc == 2) {
        formation_type = atoi(args[1]); 
    }
    
    if(formation_type == 0)
          formation = "line";
    else if(formation_type == 1)
          formation = "column";
    else if(formation_type == 2)
          formation = "wedge";
    else if(formation_type == 3)
          formation = "diamond";
    printf("Chosen formation: %s.\n", formation);
    
    
////////////////////////////////////////////////////////////////////////////////////////////////////
//                                              PSO                                               //
////////////////////////////////////////////////////////////////////////////////////////////////////

    // The paramethers that we don't optimise are commented. 
    // To add them to the simulation you should uncomment it here, in pso_ocba and change DIMENSIONALITY
    
    // each motorschema's weight
    parameter_ranges[0][0] =  0;
    parameter_ranges[0][1] = 10;
    parameter_ranges[1][0] =  0;
    parameter_ranges[1][1] = 10;
    parameter_ranges[2][0] =  0;
    parameter_ranges[2][1] = 10;
    parameter_ranges[3][0] =  0;
    parameter_ranges[3][1] = 10; /*
    parameter_ranges[4][0] =  0;
    parameter_ranges[4][1] =  4;*/


    /*
    // thresholds
    parameter_ranges[ 5][0] =   0.001;      // obstacle avoidance min
    parameter_ranges[ 5][1] =   0.5;
    parameter_ranges[ 6][0] =   0.001;      // obstacle avoidance min + range
    parameter_ranges[ 6][1] =   1;
    parameter_ranges[ 7][0] =   0.001;  // move_to_goal min
    parameter_ranges[ 7][1] =   0.5;
    parameter_ranges[ 8][0] =   0.001;  // move_to_goal min + range
    parameter_ranges[ 8][1] =   1;
    parameter_ranges[ 9][0] =   0.001;  // avoid_robot min
    parameter_ranges[ 9][1] =   0.2;
    parameter_ranges[10][0] =   0.001;  // avoid_robot min + range
    parameter_ranges[10][1] =   1;
    parameter_ranges[11][0] =   0.001;  // keep_formation min
    parameter_ranges[11][1] =   0.3;
    parameter_ranges[12][0] =   0.001;  // keep_formation min + range
    parameter_ranges[12][1] =   1;
    
    // noise
    parameter_ranges[13][0] =   1;      // noise_gen frequency
    parameter_ranges[13][1] =  20;
    parameter_ranges[14][0] =   0;      // fade or not
    parameter_ranges[14][1] =   1;
    */


    float optimal_params[DIMENSIONALITY];
    initialize();
    reset();
    

    pso_ocba(optimal_params);

    // each motorschema's weight
    w_goal            = optimal_params[0];
    w_keep_formation  = optimal_params[1];
    w_avoid_robot     = optimal_params[2];
    w_avoid_obstacles = optimal_params[3];/*
    w_noise           = optimal_params[4];

    
    // thresholds
    avoid_obst_min_threshold     = optimal_params[5];
    avoid_obst_max_threshold     = optimal_params[5] + optimal_params[6];
    move_to_goal_min_threshold   = optimal_params[7];
    move_to_goal_max_threshold   = optimal_params[7] + optimal_params[8];
    avoid_robot_min_threshold    = optimal_params[9];
    avoid_robot_max_threshold    = optimal_params[9] + optimal_params[10];
    keep_formation_min_threshold = optimal_params[11];
    keep_formation_max_threshold = optimal_params[11] + optimal_params[12];

    // noise parameters
    noise_gen_frequency = optimal_params[13];
    fading              = round(optimal_params[14]); // = 0 or 1
    */

    printf("\n\n\nThe optimal parameters are: \n");
    printf("___________ w_goal...................... = %f\n", w_goal);
    printf("___________ w_keep_formation............ = %f\n", w_keep_formation);
    printf("___________ w_avoid_robo................ = %f\n", w_avoid_robot);
    printf("___________ w_avoid_obstacles........... = %f\n", w_avoid_obstacles);
    printf("___________ w_noise..................... = %f\n", w_noise);
    printf("___________ noise_gen_frequency......... = %d\n", noise_gen_frequency);
    printf("___________ fading...................... = %d\n", fading);
    printf("___________ avoid_obst_min_threshold.... = %f\n", avoid_obst_min_threshold);
    printf("___________ avoid_obst_max_threshold.... = %f\n", avoid_obst_max_threshold);
    printf("___________ move_to_goal_min_threshold.. = %f\n", move_to_goal_min_threshold);
    printf("___________ move_to_goal_max_threshold.. = %f\n", move_to_goal_max_threshold);
    printf("___________ avoid_robot_min_threshold... = %f\n", avoid_robot_min_threshold);
    printf("___________ avoid_robot_max_threshold... = %f\n", avoid_robot_max_threshold);
    printf("___________ keep_formation_min_threshold = %f\n", keep_formation_min_threshold);
    printf("___________ keep_formation_max_threshold = %f\n", keep_formation_max_threshold);
    printf("\n\n");
    
    
////////////////////////////////////////////////////////////////////////////////////////////////////
//                                         REAL RUN                                               //
////////////////////////////////////////////////////////////////////////////////////////////////////



    // Real simulation with optimized parameters:
    initialize();
    // reset and communication part
    printf("Beginning of the real simulation\n");
    reset_to_initial_values();
    printf("Supervisor reset.\n");
    send_real_run_init_poses();
    printf("Init poses sent.\n Chosen formation: %s.\n", formation);
    
    // sending weights
    send_weights();
    printf("Weights sent\n");
    
    bool is_goal_reached=false;
    // infinite loop
    for(;;) {
        wb_robot_step(TIME_STEP);

        // every 10 TIME_STEP (640ms)
        if (simulation_duration % 10 == 0) {
            send_current_poses();

            update_fitness();
        }
        simulation_duration += TIME_STEP;
        if (simulation_has_ended()) {
            is_goal_reached=true;
            printf("\n\n\n\n______________________________________GOAL REACHED!______________________________________\n\n");

            // stop the robots
            w_goal            = 0;
            w_keep_formation  = 0;
            w_avoid_robot     = 0;
            w_avoid_obstacles = 0;
            w_noise           = 0;
            send_weights();
            break;
        }
    }
    
    if (is_goal_reached){
        fitness = compute_fitness(FORMATION_SIZE,loc);
    } else {
        fitness = compute_fitness(FORMATION_SIZE,loc);
    }
    printf("fitness = %f\n",fitness);
    
    while (1) wb_robot_step(TIME_STEP); //wait forever
    
    return 0;
}
コード例 #10
0
ファイル: scatter.c プロジェクト: DanielKowalczyk1984/WCTimpl
int SSrun_scatter_search(SS *scatter_search, CCutil_timer *timer) {
    guint i;
    REFSET *refset = scatter_search->rs;
    int flag, val = 0;
    int nbnew_sol = 0;
    int nbjobs = scatter_search->njobs;
    int nmachines = scatter_search->nmachines;
    int nb_noimprovements = 0;
    int *totsubset = (int *) NULL;
    double limit = scatter_search->timelimit;
    totsubset = CC_SAFE_MALLOC(scatter_search->b1 + 1, int);
    CCcheck_NULL_2(totsubset, "Failed tot allocate memory to tot subset");

    if (refset->list1->len == 0) {
        printf("We can't run scatter search, refset is empty\n");
        val = 1;
        goto CLEAN;
    }

    printf("PMCombination method\n");
    CCutil_suspend_timer(timer);
    CCutil_resume_timer(timer);

    while (refset->newsol && scatter_search->status != opt &&
            timer->cum_zeit < limit) {
        GPtrArray *list = g_ptr_array_new();

        for (i = 0; i < refset->list1->len; ++i) {
            g_ptr_array_add(list, g_ptr_array_index(refset->list1, i));
        }

        for (i = 0; i < refset->list2->len; ++i) {
            g_ptr_array_add(list, g_ptr_array_index(refset->list2, i));
        }

        compute_fitness(scatter_search);
        refset->newsol = 0;

        if (scatter_search->iter > 0) {
            int best = scatter_search->upperbound;
            CCutil_suspend_timer(timer);
            CCutil_resume_timer(timer);
            double rel_error = ((double)best - (double)scatter_search->lowerbound) /
                               (double)scatter_search->lowerbound;
            printf("iteration %d with best wct %d and rel error %f, number of new solutions %d, time = %f\n",
                   scatter_search->iter, best, rel_error, nbnew_sol, timer->cum_zeit);
        }

        nbnew_sol = 0;
        k_subset_init(list->len, 2, totsubset, &flag);

        while (flag && scatter_search->status != opt) {
            solution *new_sol = CC_SAFE_MALLOC(1, solution);
            solution_init(new_sol);
            solution_alloc(new_sol, nmachines, nbjobs);
            int rval = 1;
            rval = combine_PM(scatter_search, list, totsubset, 2, new_sol);

            if (!rval) {
                solution_calc(new_sol, *(scatter_search->jobarray));
                new_sol->iter = scatter_search->iter + 1;
                localsearch_random_k(new_sol, scatter_search->lowerbound, 2);
                solution_unique(new_sol);

                if (!dynamic_update(scatter_search, list, new_sol)) {
                    if (new_sol->totalweightcomptime < scatter_search->upperbound) {
                        scatter_search->upperbound = new_sol->totalweightcomptime;
                    }

                    if (new_sol->totalweightcomptime == scatter_search->lowerbound) {
                        scatter_search->status = opt;
                        printf("Found optimal with SS with subset generation 1\n");
                    }

                    nbnew_sol++;
                } else {
                    solution_free(new_sol);
                    CC_IFFREE(new_sol, solution);
                }
            } else {
                solution_free(new_sol);
                CC_IFFREE(new_sol, solution);
            }

            k_subset_lex_successor(list->len, 2, totsubset, &flag);
        }

        k_subset_init(list->len, 3, totsubset, &flag);
        solution *sol = (solution *)NULL;
        sol = (solution *) g_ptr_array_index(list, 0);

        while (flag && scatter_search->status != opt) {
            solution *new_sol = CC_SAFE_MALLOC(1, solution);
            solution_init(new_sol);
            solution_alloc(new_sol, nmachines, nbjobs);
            int rval = 1;
            rval = combine_PM(scatter_search, list, totsubset, 3,
                              new_sol);  //Dell'Amico et al.

            if (!rval) {
                solution_calc(new_sol, *(scatter_search->jobarray));
                new_sol->iter = scatter_search->iter + 1;
                localsearch_random_k(new_sol, scatter_search->lowerbound, 2);
                solution_unique(new_sol);

                if (!dynamic_update(scatter_search, list, new_sol)) {
                    if (new_sol->totalweightcomptime < scatter_search->upperbound) {
                        scatter_search->upperbound = new_sol->totalweightcomptime;
                    }

                    if (new_sol->totalweightcomptime == scatter_search->lowerbound) {
                        scatter_search->status = opt;
                        printf("Found optimal with SS\n");
                    }

                    nbnew_sol++;
                } else {
                    solution_free(new_sol);
                    CC_IFFREE(new_sol, solution);
                }
            } else {
                solution_free(new_sol);
                CC_IFFREE(new_sol, solution);
            }

            k_subset_lex_successor(list->len, 3, totsubset, &flag);
            sol = (solution *) g_ptr_array_index(list, totsubset[1] - 1);
        }

        k_subset_init(list->len, 4, totsubset, &flag);
        sol = (solution *) g_ptr_array_index(list, 0);
        solution *temp_sol = (solution *) g_ptr_array_index(list, 1);

        while (flag && scatter_search->status != opt
                && sol->totalweightcomptime <= scatter_search->upperbound
                && temp_sol->totalweightcomptime <= scatter_search->upperbound) {
            solution *new_sol = CC_SAFE_MALLOC(1, solution);
            solution_init(new_sol);
            solution_alloc(new_sol, nmachines, nbjobs);
            int rval = 1;
            rval = combine_PM(scatter_search, list, totsubset, 4, new_sol);

            if (!rval) {
                solution_calc(new_sol, *(scatter_search->jobarray));
                new_sol->iter = scatter_search->iter + 1;
                localsearch_random_k(new_sol, scatter_search->lowerbound, 2);
                solution_unique(new_sol);

                if (!dynamic_update(scatter_search, list, new_sol)) {
                    if (new_sol->totalweightcomptime < scatter_search->upperbound) {
                        scatter_search->upperbound = new_sol->totalweightcomptime;
                    }

                    if (new_sol->totalweightcomptime == scatter_search->lowerbound) {
                        scatter_search->status = opt;
                        printf("Found optimal with SS\n");
                    }

                    nbnew_sol++;
                } else {
                    solution_free(new_sol);
                    CC_IFFREE(new_sol, solution);
                }
            } else {
                solution_free(new_sol);
                CC_IFFREE(new_sol, solution);
            }

            k_subset_lex_successor(list->len, 4, totsubset, &flag);
            sol = (solution *) g_ptr_array_index(list, totsubset[1] - 1);
            temp_sol = (solution *)g_ptr_array_index(list, totsubset[2] - 1);
        }

        for (i = 0; i < refset->list2->len + 1; ++i) {
            totsubset[i] = i;
        }

        for (i = 5; i < refset->list2->len + 1
                && scatter_search->status != opt; i++) {
            solution *new_sol = CC_SAFE_MALLOC(1, solution);
            solution_init(new_sol);
            solution_alloc(new_sol, nmachines, nbjobs);
            int rval = 1;
            rval = combine_PM(scatter_search, list, totsubset, i, new_sol);

            if (!rval) {
                solution_calc(new_sol, *(scatter_search->jobarray));
                new_sol->iter = scatter_search->iter + 1;
                localsearch_random_k(new_sol, scatter_search->lowerbound, 2);
                solution_unique(new_sol);

                if (!dynamic_update(scatter_search, list, new_sol)) {
                    if (new_sol->totalweightcomptime < scatter_search->upperbound) {
                        scatter_search->upperbound = new_sol->totalweightcomptime;
                    }

                    if (new_sol->totalweightcomptime == scatter_search->lowerbound) {
                        scatter_search->status = opt;
                        printf("Found optimal with SS\n");
                    }

                    nbnew_sol++;
                } else {
                    solution_free(new_sol);
                    CC_IFFREE(new_sol, solution);
                }
            } else {
                solution_free(new_sol);
                CC_IFFREE(new_sol, solution);
            }
        }

        scatter_search->iter++;

        if (nbnew_sol == 0) {
            nb_noimprovements++;
        }

        if (refset->newsol == 0 && scatter_search->iter < 10
                && nb_noimprovements < 5) {
            add_solution_refset(scatter_search);
            refset->newsol = 1;
        }

        g_ptr_array_free(list, TRUE);
    }

CLEAN:
    CC_IFFREE(totsubset, int);
    return val;
}
コード例 #11
0
//--------------------------------------------------------------------
void start_steady_state_ga(int pop_size, int num_gens, int num_dims, int num_bits_per_dimension, double pcross, double pm, double min_x, double max_x)
// Steady-State genetic algorithm
// each step:
// pick 2 parents, mate them, 
// mutate the offspring
// and replace the worst in the population
// (only if offspring are better)
{
	// allocate memory
	b_chromosome *population;
	population = (b_chromosome*)malloc(pop_size * sizeof(b_chromosome));
	for (int i = 0; i < pop_size; i++)
		population[i].x = (char*)malloc(num_dims * num_bits_per_dimension);

	b_chromosome offspring1, offspring2;
	offspring1.x = (char*)malloc(num_dims * num_bits_per_dimension);
	offspring2.x = (char*)malloc(num_dims * num_bits_per_dimension);

	// initialize
	for (int i = 0; i < pop_size; i++) {
		generate_random(population[i], num_dims, num_bits_per_dimension);
		compute_fitness(&population[i], num_dims, num_bits_per_dimension, min_x, max_x);
	}

	qsort((void *)population, pop_size, sizeof(population[0]), sort_function);

	printf("generation 0\n");
	// print the best from generation 0
	print_chromosome(&population[0], num_dims, num_bits_per_dimension, min_x, max_x);

	for (int g = 1; g < num_gens; g++) {
		for (int k = 0; k < pop_size; k += 2) {
			// choose the parents using binary tournament
			int r1 = tournament_selection(2, population, pop_size);
			int r2 = tournament_selection(2, population, pop_size);
			// crossover
			double p = rand() / double(RAND_MAX);
			if (p < pcross)
				one_cut_point_crossover(population[r1], population[r2], offspring1, offspring2, num_dims, num_bits_per_dimension);
			else {
				copy_individual(&offspring1, population[r1], num_dims, num_bits_per_dimension);
				copy_individual(&offspring2, population[r2], num_dims, num_bits_per_dimension);
			}
			// mutate the result and compute its fitness
			mutation(offspring1, num_dims, num_bits_per_dimension, pm);
			compute_fitness(&offspring1, num_dims, num_bits_per_dimension, min_x, max_x);
			mutation(offspring2, num_dims, num_bits_per_dimension, pm);
			compute_fitness(&offspring2, num_dims, num_bits_per_dimension, min_x, max_x);

			// are offspring better than the worst ?
			if (offspring1.fitness < population[pop_size - 1].fitness) {

				copy_individual(&population[pop_size - 1], offspring1, num_dims, num_bits_per_dimension);
				qsort((void *)population, pop_size, sizeof(population[0]), sort_function);
			}
			if (offspring2.fitness < population[pop_size - 1].fitness) {
				copy_individual(&population[pop_size - 1], offspring2, num_dims, num_bits_per_dimension);
				qsort((void *)population, pop_size, sizeof(population[0]), sort_function);
			}
		}
		printf("generation %d\n", g);
		print_chromosome(&population[0], num_dims, num_bits_per_dimension, min_x, max_x);
	}
	// free memory
	free(offspring1.x);
	free(offspring2.x);

	for (int i = 0; i < pop_size; i++)
		free(population[i].x);
	free(population);
}
コード例 #12
0
bool RRSchedule::add_week()
// Add a full set of timeslots to the week
{
    // Guarantee everyone played a sufficient number of times
    bool mincheck = (min_per_night <= VectMin(this_week_played));
    if (week0)
    {
        int temp_min_per_night = (max_courts * (max_times - skip_first) * 2) / max_teams;
        mincheck = temp_min_per_night <= VectMin(this_week_played);
    }
    
    bool goodSort = false;
    bool acceptableWait = false;
    if (mincheck)
    {
        // Check to ensure sorting is acceptable?
        goodSort = sort_times_new(timeslots);
        
        if (goodSort)
        {
            Vector temp_team_waits = total_waiting_by_team;
            VectDotSum(temp_team_waits, compute_team_waits_for_week(timeslots));
            
            acceptableWait = ( VectMax(temp_team_waits) - VectMin(temp_team_waits) <= MAX_WAIT_GAP);
            if (acceptableWait)
            {
                // Roll up timeslot information into the week and log
                weeks.push_back(timeslots);
                store_timeslot();
                
                // No longer first week after successful addition of timeslot
                week0 = false;
                
                // Reset the timeslots and matchups for this week
                allocate2D(timeslots, max_times, max_courts*2);
                init2D(this_week_matchups, max_teams, max_teams);
                
                total_this_week_played.push_back(this_week_played);
                
                init1D(this_week_played,max_teams);
                
                compute_total_team_waits();
                compute_fitness();
                
                // Note progress for user
                printf ("Current Size: %d weeks (Max Weeks: %d).  Total Wait Time: %d   Fitness Level: %d (Scaled Fitness: %.2f) Printed Solutions: %d\n", int(weeks.size()), max_weeks, total_wait_time, fitness_level, scaled_fitness_level, PRINTED_SOLUTIONS);
                
                std::cout << weeks.size() << std::endl;
                
                if (weeks.size() == max_weeks)
                {
                    printf("Full Solution?\n");
                    fullSolution = true;
                }
                else{
                    printf ("Not full Solution\n");
                    
                }
            }
        }
    }
    return mincheck and goodSort and acceptableWait;
}