Пример #1
0
	inline virtual std::string run(const Dataset& train, const Dataset& test)
	{
		srand(time(NULL));
		initialize_pop(train, test);
		
		std::pair<unsigned int, double> best_at_train;
		for (unsigned int i = 0; i < num_iter; ++i)
		{
			std::cout << "--- ITERATION " << i + 1 << " ---" << std::endl;
			iteration(train, test);

			best_at_train = cur_pop->best(train);
			std::vector<Statistics> fitness_train = cur_pop->evaluate(train);
			std::cout << "RMSE (train): " << fitness_train[best_at_train.first].rmse << std::endl;
			std::cout << "MSE (train): " << fitness_train[best_at_train.first].mse << std::endl;
			std::cout << "MAE (train): " << fitness_train[best_at_train.first].mae << std::endl;
			std::cout << "Total error (train): " << fitness_train[best_at_train.first].total_error << std::endl;

			std::vector<Statistics> fitness_test = cur_pop->evaluate(test, false);
			std::cout << "RMSE (test): " << fitness_test[best_at_train.first].rmse << std::endl;
			std::cout << "MSE (test): " << fitness_test[best_at_train.first].mse << std::endl;
			std::cout << "MAE (test): " << fitness_test[best_at_train.first].mae << std::endl;
			std::cout << "Total error (test): " << fitness_test[best_at_train.first].total_error << std::endl;

			std::cout << "Size: " << (*cur_pop)[best_at_train.first].size() << std::endl;
		}

		return graph->print_expression((*cur_pop)[best_at_train.first].get_index());
	}
Пример #2
0
/*Algoritmo Principal*/
int main(int argc, char *argv[])
{
    char name[20];// = "_kita_1";
    char archiveName[20] = "archive";
	char fitputName[20] = "fitput";
	char varputName[20] = "varput";
	char hvName[20]= "hv";
	unsigned int i, j, t;
	unsigned int fun, gen;
	clock_t  startTime, endTime;
	double duration, clocktime;
	FILE *fitfile,*varfile;
/*Parametros iniciales*/

    strcpy(name,argv[1]);
    fun = atoi(argv[2]);
    gen = atoi(argv[3]);

    printf("%s %d %d \n",name,fun,gen);

    initialize_data(fun,gen);
/*Iniciar variables*/
	initialize_memory();

	/*
	sprintf(name,"kita_1_");
	sprintf(archiveName,strcat(name,"archive.out"));
	sprintf(fitputName, strcat(name,"fitput.out"));
	sprintf(varputName, strcat(name,"varput.out"));
	sprintf(hvName,strcat(name,"hv.out"));
*/
	//fitfile = fopen(strcat(strcat(fitputName,name),".out"),"w");
	//varfile = fopen(strcat(strcat(varputName,name),".out"),"w");
	//hv = fopen(strcat(strcat(hvName,name),".out"),"w");
/* Iniciar generador de aleatorios*/
	initialize_rand();
	startTime = clock();
/* Iniciar contador de generaciones*/
	t = 0;
/* Iniciar valores de la poblacion de manera aleatoria*/
	initialize_pop();
/* Calcular velocidad inicial*/
	initialize_vel();
/* Evaluar las particulas de la poblacion*/
	evaluate();
/* Almacenar el pBest inicial (variables and valor de aptitud) de las particulas*/
	store_pbests();
/* Insertar las particulas no domindas de la poblacion en el archivo*/

	insert_nondom();
	//printf("\n%d",nondomCtr);
/*Ciclo Principal*/
	while(t <= maxgen)
	{
		//clocktime = (clock() - startTime)/(double)CLOCKS_PER_SEC;
		/*if(verbose > 0 && t%printevery==0 || t == maxgen)
		{
			fprintf(stdout,"Generation %d Time: %.2f sec\n",t,clocktime);
			fflush(stdout);
		}*/
		/*if(t%printevery==0 || t == maxgen)
		{
			fprintf(outfile,"Generation %d Time: %.2f sec\n",t,clocktime);
		}*/
    /* Calcular la nueva velocidad de cada particula en la pooblacion*/
		//printf("\n 1");
		compute_velocity();

    /* Calcular la nueva posicion de cada particula en la poblacion*/
        //printf("\n 2");
        compute_position();
    /* Mantener las particulas en la poblacion de la poblacion en el espacio de busqueda*/
		//printf("\n 3");
		maintain_particles();
    /* Pertubar las particulas en la poblacion*/
		if(t < maxgen * pMut)
			mutate(t);

    /* Evaluar las particulas en la poblacion*/
		//printf("\n 4");
		evaluate();
    /* Insertar nuevas particulas no domindas en el archivo*/
		//printf("\n 5");
		update_archive();
    /* Actualizar el pBest de las particulas en la poblacion*/
		//printf("\n 6");
		update_pbests();
    /* Escribir resultados del mejor hasta ahora*/
    //verbose > 0 && t%printevery==0 || t == maxgen
		/*if(t%printevery==0 || t == maxgen)
		{
			//fprintf(outfile, "Size of Pareto Set: %d\n", nondomCtr);
			fprintf(fitfile, "%d\n",t);
			fprintf(varfile, "%d\n",t);
			for(i = 0; i < nondomCtr; i++)
			{
			    for(j = 0; j < maxfun; j++)
                    fprintf(fitfile, "%f ", archiveFit[i][j]);
                fprintf(fitfile, "\n");
			}
			fprintf(fitfile, "\n\n");
			fflush(fitfile);
			for(i = 0; i < nondomCtr; i++)
			{
			    for(j = 0; j < maxfun; j++)
                    fprintf(varfile, "%f ", archiveVar[i][j]);
                fprintf(varfile, "\n");
			}
			fprintf(varfile, "\n\n");
			fflush(varfile);
		}*/
    /* Incrementar contador de generaciones*/
        t++;
        //printf("%d\n",t);
	}
 /* Escribir resultados en el archivo */
	save_results(strcat(strcat(archiveName,name),".out"));
	endTime = clock();
	duration = ( endTime - startTime ) / (double)CLOCKS_PER_SEC;
	fprintf(stdout, "%lf sec\n", duration);
	//fclose(fitfile);
	//fclose(varfile);
	free_memory();
	return EXIT_SUCCESS;
}
Пример #3
0
main(int argc, char *argv[]) 
{

    /* Declare vars : */
    /* - these for the getopt stuff... */
    int            c;
    int            lflg = 0, mflg = 0, errflg = 0;
    extern char    *optarg;
    extern int        optind, optopt;
    /* - and these for the main program... */
    int            i     , code_length, pop_size = 200, generations = 10, rand_seed = 123;
    pop_member     *head_of_pop;

    /* figure out all the cmd line requests... */
    while ((c = getopt(argc, argv, ":l:p:g:r:m")) != -1)
    switch (c) {
    case 'l':
        lflg++;
        code_length = atoi(optarg);
        break;
    case 'p':
        pop_size = atoi(optarg);
        break;
    case 'g':
        generations = atoi(optarg);
        break;
    case 'r':
        rand_seed = atoi(optarg);
        break;
    case 'm':
        mflg++;
        break;
    case ':':        /* -l, -p, -g, or -r without arguments */
        fprintf(stderr, "Option -%c requires an argument!\n", optopt);
        errflg++;
        break;
    case '?':
        fprintf(stderr, "Unrecognized option: -%c\n", optopt);
        errflg++;
    }

    if (!lflg) errflg++;

    if (errflg || argc == 1) {
    fprintf(stderr, "usage: \n");
    fprintf(stderr, "  ga_codes  -l <code_length>  ");
    fprintf(stderr, "[ -p <no. of pop members, default=200> ]  \\ \n");
    fprintf(stderr, "      [ -g <no. of generations, default=10> ] \\ \n");
    fprintf(stderr, "      [ -r <integer random no. seed, default=123> ]  \\ \n");
    fprintf(stderr, "      [ -m [for matlab compatible output] ]\n\n");
    exit(2);
    }
    /* use random seed to initiate random number generator */
    srand48(rand_seed);

    /* initialize population with randomly generated codes */
    head_of_pop = initialize_pop(pop_size, code_length);

    /* evaluate population */
    head_of_pop = apply_evals_to_pop(head_of_pop, code_length);

    /* sort population by evals */
    head_of_pop = sort_pop_by_evals(head_of_pop, code_length);

    /* print out all codes and evals in pop for diagnostic use... */
    /* printout_pop(head_of_pop, code_length); printf("\n"); */

    /* loop thru iterations of reproduction and replacing pop members that
     * have poor evals... */
    for (i = 1; i <= generations; i++) {
    /* run a reproduction cycle */
    head_of_pop = next_generation(head_of_pop, pop_size, code_length);

    /* evaluate population */
    head_of_pop = apply_evals_to_pop(head_of_pop, code_length);

    /* sort population by evals */
    head_of_pop = sort_pop_by_evals(head_of_pop, code_length);

    /* print out all codes and evals in pop for diagnostic use...
     * printout_pop(head_of_pop, code_length); printf("\n"); */
    }

    /* print output info... */
    printout_info(mflg, code_length, pop_size, generations, rand_seed,
          head_of_pop->code, head_of_pop->eval,
          head_of_pop->max_sl_height);

}  /* end main */
Пример #4
0
int maintest (int argc, char **argv)
{
    int i;
    FILE *fpt1;
    FILE *fpt2;
    FILE *fpt3;
    FILE *fpt4;
    FILE *fpt5;
    population *parent_pop;
    population *child_pop;
    population *mixed_pop;
	int gnuplt= 1;
    if (argc<2)
    {
        printf("\n Usage ./nsga2r random_seed \n");
        exit(1);
    }
    seed = (double)atof(argv[1]);
    if (seed<=0.0 || seed>=1.0)
    {
        printf("\n Entered seed value is wrong, seed value must be in (0,1) \n");
        exit(1);
    }
    fpt1 = fopen("initial_pop.out","w");
    fpt2 = fopen("final_pop.out","w");
    fpt3 = fopen("best_pop.out","w");
    fpt4 = fopen("all_pop.out","w");
    fpt5 = fopen("params.out","w");
    fprintf(fpt1,"# This file contains the data of initial population\n");
    fprintf(fpt2,"# This file contains the data of final population\n");
    fprintf(fpt3,"# This file contains the data of final feasible population (if found)\n");
    fprintf(fpt4,"# This file contains the data of all generations\n");
    fprintf(fpt5,"# This file contains information about inputs as read by the program\n");

	if(argc > 2) { 
		char *in_file_name = argv[2];
		if (read_inputParam_from_file(in_file_name) < 0) exit(1);
		gnuplt = 0;
	}
	else 
		if (read_inputParam() < 0) exit(1);

    printf("\n Input data successfully entered, now performing initialization \n");
    fprintf(fpt5,"\n Population size = %d",popsize);
    fprintf(fpt5,"\n Number of generations = %d",ngen);
    fprintf(fpt5,"\n Number of objective functions = %d",nobj);
    fprintf(fpt5,"\n Number of constraints = %d",ncon);
    fprintf(fpt5,"\n Number of real variables = %d",nreal);
    if (nreal!=0)
    {
        for (i=0; i<nreal; i++)
        {
            fprintf(fpt5,"\n Lower limit of real variable %d = %e",i+1,min_realvar[i]);
            fprintf(fpt5,"\n Upper limit of real variable %d = %e",i+1,max_realvar[i]);
        }
        fprintf(fpt5,"\n Probability of crossover of real variable = %e",pcross_real);
        fprintf(fpt5,"\n Probability of mutation of real variable = %e",pmut_real);
        fprintf(fpt5,"\n Distribution index for crossover = %e",eta_c);
        fprintf(fpt5,"\n Distribution index for mutation = %e",eta_m);
    }
    fprintf(fpt5,"\n Number of binary variables = %d",nbin);
    if (nbin!=0)
    {
        for (i=0; i<nbin; i++)
        {
            fprintf(fpt5,"\n Number of bits for binary variable %d = %d",i+1,nbits[i]);
            fprintf(fpt5,"\n Lower limit of binary variable %d = %e",i+1,min_binvar[i]);
            fprintf(fpt5,"\n Upper limit of binary variable %d = %e",i+1,max_binvar[i]);
        }
        fprintf(fpt5,"\n Probability of crossover of binary variable = %e",pcross_bin);
        fprintf(fpt5,"\n Probability of mutation of binary variable = %e",pmut_bin);
    }
    fprintf(fpt5,"\n Seed for random number generator = %e",seed);
    bitlength = 0;
    if (nbin!=0)
    {
        for (i=0; i<nbin; i++)
        {
            bitlength += nbits[i];
        }
    }
    fprintf(fpt1,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt2,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt3,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt4,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
    nbinmut = 0;
    nrealmut = 0;
    nbincross = 0;
    nrealcross = 0;
    parent_pop = (population *)malloc(sizeof(population));
    child_pop = (population *)malloc(sizeof(population));
    mixed_pop = (population *)malloc(sizeof(population));
    allocate_memory_pop (parent_pop, popsize);
    allocate_memory_pop (child_pop, popsize);
    allocate_memory_pop (mixed_pop, 2*popsize);
    randomize();
    initialize_pop (parent_pop);
    printf("\n Initialization done, now performing first generation");
    decode_pop(parent_pop);
    evaluate_pop (parent_pop);
    assign_rank_and_crowding_distance (parent_pop);
    report_pop (parent_pop, fpt1);
    fprintf(fpt4,"# gen = 1\n");
    report_pop(parent_pop,fpt4);
    printf("\n gen = 1");
    fflush(stdout);
    if (choice!=0) {    
		if(gnuplt) onthefly_display (parent_pop,gp,1);
		else display (parent_pop,1);
	}
    fflush(fpt1);
    fflush(fpt2);
    fflush(fpt3);
    fflush(fpt4);
    fflush(fpt5);
    _sleep(1);
    for (i=2; i<=ngen; i++)
    {
        selection (parent_pop, child_pop);
        mutation_pop (child_pop);
        decode_pop(child_pop);
        evaluate_pop(child_pop);
        merge (parent_pop, child_pop, mixed_pop);
        fill_nondominated_sort (mixed_pop, parent_pop);
        /* Comment following four lines if information for all
        generations is not desired, it will speed up the execution */
        fprintf(fpt4,"# gen = %d\n",i);
        report_pop(parent_pop,fpt4);
        fflush(fpt4);
        if (choice!=0) {
			if(gnuplt) onthefly_display (parent_pop,gp,i);
			else display (parent_pop,i);
		}
        printf("\n gen = %d",i);
    }
    printf("\n Generations finished, now reporting solutions");
    report_pop(parent_pop,fpt2);
    report_feasible(parent_pop,fpt3);
    if (nreal!=0)
    {
        fprintf(fpt5,"\n Number of crossover of real variable = %d",nrealcross);
        fprintf(fpt5,"\n Number of mutation of real variable = %d",nrealmut);
    }
    if (nbin!=0)
    {
        fprintf(fpt5,"\n Number of crossover of binary variable = %d",nbincross);
        fprintf(fpt5,"\n Number of mutation of binary variable = %d",nbinmut);
    }
    fflush(stdout);
    fflush(fpt1);
    fflush(fpt2);
    fflush(fpt3);
    fflush(fpt4);
    fflush(fpt5);
    fclose(fpt1);
    fclose(fpt2);
    fclose(fpt3);
    fclose(fpt4);
    fclose(fpt5);
    if (choice!=0 && gnuplt)
    {
        _pclose(gp);
    }
    if (nreal!=0)
    {
        free (min_realvar);
        free (max_realvar);
    }
    if (nbin!=0)
    {
        free (min_binvar);
        free (max_binvar);
        free (nbits);
    }
    deallocate_memory_pop (parent_pop, popsize);
    deallocate_memory_pop (child_pop, popsize);
    deallocate_memory_pop (mixed_pop, 2*popsize);
    free (parent_pop);
    free (child_pop);
    free (mixed_pop);
    printf("\n Routine successfully exited \n");
    return (0);
}
Пример #5
0
/* -------------------------------------------------------------------------------
 * NSGA2                                                       
 * ---------------------------------------------------------------------------- */
int nsga2(int nvar, int ncon, int nobj, double f[], double x[], double g[],
    int nfeval, double xl[], double xu[],	int popsize, int ngen, 
    double pcross_real, double pmut_real, double eta_c, double eta_m, 
    double pcross_bin, double pmut_bin, int printout, double seed)
{
	/* declaration of local variables and structures */
    int i, j;
    int nreal, nbin, *nbits, bitlength; 
    double *min_realvar, *max_realvar;
	double *min_binvar, *max_binvar;
	int *nbinmut, *nrealmut, *nbincross, *nrealcross;
    
    Global global;
    
    population *parent_pop;
    population *child_pop;
    population *mixed_pop;
    
    // "random" numbers seed
    if (seed==0) 
    {  
        // use of clock to generate "random" seed
        time_t seconds;
        seconds=time(NULL);
        seed=seconds;
    }
    
    // Files
	FILE *fpt1;
	FILE *fpt2;
	FILE *fpt3;
	FILE *fpt4;
	FILE *fpt5;
	FILE *fpt6;
    if (printout >= 1)
    {
		fpt1 = fopen("nsga2_initial_pop.out","w");
		fpt2 = fopen("nsga2_final_pop.out","w");
		fpt3 = fopen("nsga2_best_pop.out","w");
		if (printout == 2)
		{
			fpt4 = fopen("nsga2_all_pop.out","w");
		}
		fpt5 = fopen("nsga2_params.out","w");
		fpt6 = fopen("nsga2_run.out","w");
		fprintf(fpt1,"# This file contains the data of initial population\n");
		fprintf(fpt2,"# This file contains the data of final population\n");
		fprintf(fpt3,"# This file contains the data of final feasible population (if found)\n");
		if (printout == 2)
		{
			fprintf(fpt4,"# This file contains the data of all generations\n");
		}
		fprintf(fpt5,"# This file contains information about inputs as read by the program\n");
		fprintf(fpt6,"# This file contains runtime information\n");
	}
    
	// Input Handling
	nreal = nvar;	// number of real variables
	nbin = 0;  	    // number of binary variables
	
    min_realvar = (double *)malloc(nreal*sizeof(double));
    max_realvar = (double *)malloc(nreal*sizeof(double));
    
    j = 0;
    for (i=0; i<nvar; i++)
    {
        min_realvar[j] = xl[i];
        max_realvar[j] = xu[i];
        j += 1;
	}
	
	if (nbin != 0)
	{
        nbits = (int *)malloc(nbin*sizeof(int));
        min_binvar = (double *)malloc(nbin*sizeof(double));
        max_binvar = (double *)malloc(nbin*sizeof(double));
    }
    
    bitlength = 0;
    if (nbin!=0)
    {
        for (i=0; i<nbin; i++)
        {
            bitlength += nbits[i];
        }
    }
    
    // Performing Initialization
    if (printout >= 1)
    {
		fprintf(fpt5,"\n Population size = %d",popsize);
		fprintf(fpt5,"\n Number of generations = %d",ngen);
		fprintf(fpt5,"\n Number of objective functions = %d",nobj);
		fprintf(fpt5,"\n Number of constraints = %d",ncon);
		fprintf(fpt5,"\n Number of variables = %d",nvar);
		fprintf(fpt5,"\n Number of real variables = %d",nreal);
		if (nreal!=0)
		{
			for (i=0; i<nreal; i++)
			{
				fprintf(fpt5,"\n Lower limit of real variable %d = %e",i+1,min_realvar[i]);
				fprintf(fpt5,"\n Upper limit of real variable %d = %e",i+1,max_realvar[i]);
			}
			fprintf(fpt5,"\n Probability of crossover of real variable = %e",pcross_real);
			fprintf(fpt5,"\n Probability of mutation of real variable = %e",pmut_real);
			fprintf(fpt5,"\n Distribution index for crossover = %e",eta_c);
			fprintf(fpt5,"\n Distribution index for mutation = %e",eta_m);
		}
		fprintf(fpt5,"\n Number of binary variables = %d",nbin);
		if (nbin!=0)
		{
			for (i=0; i<nbin; i++)
			{
				fprintf(fpt5,"\n Number of bits for binary variable %d = %d",i+1,nbits[i]);
				fprintf(fpt5,"\n Lower limit of binary variable %d = %e",i+1,min_binvar[i]);
				fprintf(fpt5,"\n Upper limit of binary variable %d = %e",i+1,max_binvar[i]);
			}
			fprintf(fpt5,"\n Probability of crossover of binary variable = %e",pcross_bin);
			fprintf(fpt5,"\n Probability of mutation of binary variable = %e",pmut_bin);
		}
		fprintf(fpt5,"\n Seed for random number generator = %e",seed);
		
		fprintf(fpt1,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
		fprintf(fpt2,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
		fprintf(fpt3,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
		if (printout == 2)
		{
			fprintf(fpt4,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
		}
    }
    
    // 
    global.nreal = nreal;
    global.nbin = nbin;
    global.nobj = nobj;
    global.ncon = ncon;
    global.popsize = popsize;
    global.pcross_real = pcross_real;
    global.pcross_bin = pcross_bin;
    global.pmut_real = pmut_real;
    global.pmut_bin = pmut_bin;
    global.eta_c = eta_c;
    global.eta_m = eta_m;
    global.ngen = ngen;
    global.nbits = nbits;
    global.min_realvar = min_realvar;
    global.max_realvar = max_realvar;
    global.min_binvar = min_binvar;
    global.max_binvar = max_binvar;
    global.bitlength = bitlength;  
    
    //
    nbinmut = 0;
    nrealmut = 0;
    nbincross = 0;
    nrealcross = 0;
    parent_pop = (population *)malloc(sizeof(population));
    child_pop = (population *)malloc(sizeof(population));
    mixed_pop = (population *)malloc(sizeof(population));
    allocate_memory_pop (parent_pop, popsize, global);
    allocate_memory_pop (child_pop, popsize, global);
    allocate_memory_pop (mixed_pop, 2*popsize, global);
    randomize();
    initialize_pop (parent_pop, global);
    
    // First Generation
    if (printout >= 1)
    {
		fprintf(fpt6,"\n\n Initialization done, now performing first generation");
    }
    decode_pop(parent_pop, global);
    evaluate_pop(parent_pop, global);
    assign_rank_and_crowding_distance (parent_pop, global);
    if (printout >= 1)
    {
		report_pop (parent_pop, fpt1, global);
		if (printout == 2)
		{
			fprintf(fpt4,"# gen = 1\n");
			report_pop(parent_pop,fpt4, global);
		}
		
		fprintf(fpt6,"\n gen = 1");
		
		fflush(fpt1);
		fflush(fpt2);
		fflush(fpt3);
		if (printout == 2)
		{
			fflush(fpt4);
		}
		fflush(fpt5);
		fflush(fpt6);
	}
    fflush(stdout);
    
    // Iterate Generations
    for (i=2; i<=ngen; i++)
    {
        selection(parent_pop, child_pop, global, nrealcross, nbincross);
        mutation_pop(child_pop, global, nrealmut, nbinmut);
        decode_pop(child_pop, global);
        evaluate_pop(child_pop, global);
        merge (parent_pop, child_pop, mixed_pop, global);
        fill_nondominated_sort (mixed_pop, parent_pop, global);
        
        /* Comment following three lines if information for all
        generations is not desired, it will speed up the execution */
        if (printout >= 1)
		{
			if (printout == 2)
			{
				fprintf(fpt4,"# gen = %i\n",i);
				report_pop(parent_pop,fpt4, global);
				fflush(fpt4);
			}
			fprintf(fpt6,"\n gen = %i",i);
			fflush(fpt6);
		}
    }
    
    // Output
	if (printout >= 1)
	{
		fprintf(fpt6,"\n Generations finished");
		report_pop(parent_pop,fpt2, global);
		report_feasible(parent_pop,fpt3, global);
		
		if (nreal!=0)
		{
			fprintf(fpt5,"\n Number of crossover of real variable = %i",nrealcross);
			fprintf(fpt5,"\n Number of mutation of real variable = %i",nrealmut);
		}
		if (nbin!=0)
		{
			fprintf(fpt5,"\n Number of crossover of binary variable = %i",nbincross);
			fprintf(fpt5,"\n Number of mutation of binary variable = %i",nbinmut);
		}
		fflush(stdout);
		fflush(fpt1);
		fflush(fpt2);
		fflush(fpt3);
		if (printout == 2)
		{
			fflush(fpt4);
		}
		fflush(fpt5);
		fflush(fpt6);
		fclose(fpt1);
		fclose(fpt2);
		fclose(fpt3);
		if (printout == 2)
		{
			fclose(fpt4);
		}
		fclose(fpt5);
			
	}
	
	// 
    for (i=0; i<popsize; i++)
    {
		if (parent_pop->ind[i].constr_violation == 0.0 && parent_pop->ind[i].rank==1)
        {
			for (j=0; j<nobj; j++)
            {
                f[j] = parent_pop->ind[i].obj[j];
            }
            if (ncon!=0)
            {
                for (j=0; j<ncon; j++)
                {
                    g[j] = parent_pop->ind[i].constr[j];
                }
            }
            if (nreal!=0)
            {
                for (j=0; j<nreal; j++)
                {
                    x[j] = parent_pop->ind[i].xreal[j];
                }
            }
			break;
		}
	}
	
	// 
    if (nreal!=0)
    {
        free (min_realvar);
        free (max_realvar);
    }
    if (nbin!=0)
    {
        free (min_binvar);
        free (max_binvar);
        free (nbits);
    }
    deallocate_memory_pop (parent_pop, popsize, global);
    deallocate_memory_pop (child_pop, popsize, global);
    deallocate_memory_pop (mixed_pop, 2*popsize, global);
    free (parent_pop);
    free (child_pop);
    free (mixed_pop);
    
	// 
	if (printout >= 1)
	{
		fprintf(fpt6,"\n Routine successfully exited \n");
		fflush(fpt6);
		fclose(fpt6);
	}
    
    return (0);
}
Пример #6
0
int main (int argc, char **argv)
{
    int i;
    FILE *fpt1;
    FILE *fpt2;
    FILE *fpt3;
    FILE *fpt4;
    FILE *fpt5;
    population *parent_pop;
    population *child_pop;
    population *mixed_pop;
    fpt1 = fopen("output/initial_pop.out","w");
    fpt2 = fopen("output/final_pop.out","w");
    fpt3 = fopen("output/best_pop.out","w");
    fpt4 = fopen("output/all_pop.out","w");
    fpt5 = fopen("output/params.out","w");
    fprintf(fpt1,"# This file contains the data of initial population\n");
    fprintf(fpt2,"# This file contains the data of final population\n");
    fprintf(fpt3,"# This file contains the data of final feasible population (if found)\n");
    fprintf(fpt4,"# This file contains the data of all generations\n");
    fprintf(fpt5,"# This file contains information about inputs as read by the program\n");
    // 读取执行参数
    read_run_param();
    if (seed<=0.0 || seed>=1.0)
    {
        printf("\n Entered seed value is wrong, seed value must be in (0,1) \n");
        exit(1);
    }
//    printf("\n Enter the problem relevant and algorithm relevant parameters ... ");
//    printf("\n Enter the population size (a multiple of 4) : ");
//    scanf("%d",&popsize);
    if (popsize<4 || (popsize%4)!= 0)
    {
        printf("\n population size read is : %d",popsize);
        printf("\n Wrong population size entered, hence exiting \n");
        exit (1);
    }
//    printf("\n Enter the number of generations : ");
//    scanf("%d",&ngen);
    if (ngen<1)
    {
        printf("\n number of generations read is : %d",ngen);
        printf("\n Wrong nuber of generations entered, hence exiting \n");
        exit (1);
    }
//    printf("\n Enter the number of objectives : ");
//    scanf("%d",&nobj);
    if (nobj<1)
    {
        printf("\n number of objectives entered is : %d",nobj);
        printf("\n Wrong number of objectives entered, hence exiting \n");
        exit (1);
    }
//    printf("\n Enter the number of constraints : ");
//    scanf("%d",&ncon);
    if (ncon<0)
    {
        printf("\n number of constraints entered is : %d",ncon);
        printf("\n Wrong number of constraints enetered, hence exiting \n");
        exit (1);
    }
//    printf("\n Enter the number of real variables : ");
//    scanf("%d",&nreal);
    if (nreal<0)
    {
        printf("\n number of real variables entered is : %d",nreal);
        printf("\n Wrong number of variables entered, hence exiting \n");
        exit (1);
    }
    if (nreal != 0)
    {
        min_realvar = (double *)malloc(nreal*sizeof(double));
        max_realvar = (double *)malloc(nreal*sizeof(double));
        for (i=0; i<nreal; i++)
        {
//            printf ("\n Enter the lower limit of real variable %d : ",i+1);
//            scanf ("%lf",&min_realvar[i]);
//            printf ("\n Enter the upper limit of real variable %d : ",i+1);
//            scanf ("%lf",&max_realvar[i]);
            max_realvar[i] = 1;
            min_realvar[i] = 0;
            if (max_realvar[i] <= min_realvar[i])
            {
                printf("\n Wrong limits entered for the min and max bounds of real variable, hence exiting \n");
                exit(1);
            }
        }
//        printf ("\n Enter the probability of crossover of real variable (0.6-1.0) : ");
//        scanf ("%lf",&pcross_real);
        if (pcross_real<0.0 || pcross_real>1.0)
        {
            printf("\n Probability of crossover entered is : %e",pcross_real);
            printf("\n Entered value of probability of crossover of real variables is out of bounds, hence exiting \n");
            exit (1);
        }
//        printf ("\n Enter the probablity of mutation of real variables (1/nreal) : ");
//        scanf ("%lf",&pmut_real);
        if (pmut_real<0.0 || pmut_real>1.0)
        {
            printf("\n Probability of mutation entered is : %e",pmut_real);
            printf("\n Entered value of probability of mutation of real variables is out of bounds, hence exiting \n");
            exit (1);
        }
//        printf ("\n Enter the value of distribution index for crossover (5-20): ");
//        scanf ("%lf",&eta_c);
        if (eta_c<=0)
        {
            printf("\n The value entered is : %e",eta_c);
            printf("\n Wrong value of distribution index for crossover entered, hence exiting \n");
            exit (1);
        }
//        printf ("\n Enter the value of distribution index for mutation (5-50): ");
//        scanf ("%lf",&eta_m);
        if (eta_m<=0)
        {
            printf("\n The value entered is : %e",eta_m);
            printf("\n Wrong value of distribution index for mutation entered, hence exiting \n");
            exit (1);
        }
    }
//    printf("\n Enter the number of binary variables : ");
//    scanf("%d",&nbin);
    if (nbin<0)
    {
        printf ("\n number of binary variables entered is : %d",nbin);
        printf ("\n Wrong number of binary variables entered, hence exiting \n");
        exit(1);
    }
    if (nbin != 0)
    {
        nbits = (int *)malloc(nbin*sizeof(int));
        min_binvar = (double *)malloc(nbin*sizeof(double));
        max_binvar = (double *)malloc(nbin*sizeof(double));
        for (i=0; i<nbin; i++)
        {
//            printf ("\n Enter the number of bits for binary variable %d : ",i+1);
//            scanf ("%d",&nbits[i]);
            if (nbits[i] < 1)
            {
                printf("\n Wrong number of bits for binary variable entered, hence exiting");
                exit(1);
            }
//            printf ("\n Enter the lower limit of binary variable %d : ",i+1);
//            scanf ("%lf",&min_binvar[i]);
//            printf ("\n Enter the upper limit of binary variable %d : ",i+1);
//            scanf ("%lf",&max_binvar[i]);
            max_binvar[i] = 1;
            min_binvar[i] = 0;
            if (max_binvar[i] <= min_binvar[i])
            {
                printf("\n Wrong limits entered for the min and max bounds of binary variable entered, hence exiting \n");
                exit(1);
            }
        }
//        printf ("\n Enter the probability of crossover of binary variable (0.6-1.0): ");
//        scanf ("%lf",&pcross_bin);
        pcross_bin = 0.8;
        if (pcross_bin<0.0 || pcross_bin>1.0)
        {
            printf("\n Probability of crossover entered is : %e",pcross_bin);
            printf("\n Entered value of probability of crossover of binary variables is out of bounds, hence exiting \n");
            exit (1);
        }
//        printf ("\n Enter the probability of mutation of binary variables (1/nbits): ");
//        scanf ("%lf",&pmut_bin);
        pmut_bin = 0.02;
        if (pmut_bin<0.0 || pmut_bin>1.0)
        {
            printf("\n Probability of mutation entered is : %e",pmut_bin);
            printf("\n Entered value of probability  of mutation of binary variables is out of bounds, hence exiting \n");
            exit (1);
        }
    }
    if (nreal==0 && nbin==0)
    {
        printf("\n Number of real as well as binary variables, both are zero, hence exiting \n");
        exit(1);
    }
    choice=0;
    printf(" Input data successfully entered, now performing initialization \n");
    fprintf(fpt5,"\n Population size = %d",popsize);
    fprintf(fpt5,"\n Number of generations = %d",ngen);
    fprintf(fpt5,"\n Number of objective functions = %d",nobj);
    fprintf(fpt5,"\n Number of constraints = %d",ncon);
    fprintf(fpt5,"\n Number of real variables = %d",nreal);
    if (nreal!=0)
    {
        for (i=0; i<nreal; i++)
        {
            fprintf(fpt5,"\n Lower limit of real variable %d = %e",i+1,min_realvar[i]);
            fprintf(fpt5,"\n Upper limit of real variable %d = %e",i+1,max_realvar[i]);
        }
        fprintf(fpt5,"\n Probability of crossover of real variable = %e",pcross_real);
        fprintf(fpt5,"\n Probability of mutation of real variable = %e",pmut_real);
        fprintf(fpt5,"\n Distribution index for crossover = %e",eta_c);
        fprintf(fpt5,"\n Distribution index for mutation = %e",eta_m);
    }
    fprintf(fpt5,"\n Number of binary variables = %d",nbin);
    if (nbin!=0)
    {
        for (i=0; i<nbin; i++)
        {
            fprintf(fpt5,"\n Number of bits for binary variable %d = %d",i+1,nbits[i]);
            fprintf(fpt5,"\n Lower limit of binary variable %d = %e",i+1,min_binvar[i]);
            fprintf(fpt5,"\n Upper limit of binary variable %d = %e",i+1,max_binvar[i]);
        }
        fprintf(fpt5,"\n Probability of crossover of binary variable = %e",pcross_bin);
        fprintf(fpt5,"\n Probability of mutation of binary variable = %e",pmut_bin);
    }
    fprintf(fpt5,"\n Seed for random number generator = %e",seed);
    bitlength = 0;
    if (nbin!=0)
    {
        for (i=0; i<nbin; i++)
        {
            bitlength += nbits[i];
        }
    }
    fprintf(fpt1,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt2,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt3,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt4,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation, rank, crowding_distance\n",nobj,ncon,nreal,bitlength);
    nbinmut = 0;
    nrealmut = 0;
    nbincross = 0;
    nrealcross = 0;

    // 读取问题参数
    read_prob_param();
    // 根据参数申请空间
    allocate_prob();
    // 输入问题
    input_prob();

    parent_pop = (population *)malloc(sizeof(population));
    child_pop = (population *)malloc(sizeof(population));
    mixed_pop = (population *)malloc(sizeof(population));
    allocate_memory_pop (parent_pop, popsize);
    allocate_memory_pop (child_pop, popsize);
    allocate_memory_pop (mixed_pop, 2*popsize);
    randomize();
    initialize_pop (parent_pop);
    printf(" Initialization done, now performing first generation\n");
    decode_pop(parent_pop);
    evaluate_pop (parent_pop);
    assign_rank_and_crowding_distance (parent_pop);
    report_pop (parent_pop, fpt1);
    fprintf(fpt4,"# gen = 1\n");
    report_pop(parent_pop,fpt4);
    printf("gen = 1\n");
    fflush(stdout);
    fflush(fpt1);
    fflush(fpt2);
    fflush(fpt3);
    fflush(fpt4);
    fflush(fpt5);
    //sleep(1);
    for (i=2; i<=ngen; i++)
    {
        selection (parent_pop, child_pop);
        mutation_pop (child_pop);
        decode_pop(child_pop);
        evaluate_pop(child_pop);
        merge (parent_pop, child_pop, mixed_pop);
        fill_nondominated_sort (mixed_pop, parent_pop);
        /* Comment following four lines if information for all
        generations is not desired, it will speed up the execution */
        fprintf(fpt4,"# gen = %d\n",i);
        report_pop(parent_pop,fpt4);
        fflush(fpt4);
        printf("gen = %d\n",i);
    }
    printf(" Generations finished, now reporting solutions\n");
    report_pop(parent_pop,fpt2);
    report_feasible(parent_pop,fpt3);
    
    // 输出 task
    FILE *fpt_task;
    fpt_task = fopen("output/task_pop.out", "w");
    report_pop_task(parent_pop, fpt_task);
    fclose(fpt_task);

    if (nreal!=0)
    {
        fprintf(fpt5,"\n Number of crossover of real variable = %d",nrealcross);
        fprintf(fpt5,"\n Number of mutation of real variable = %d",nrealmut);
    }
    if (nbin!=0)
    {
        fprintf(fpt5,"\n Number of crossover of binary variable = %d",nbincross);
        fprintf(fpt5,"\n Number of mutation of binary variable = %d",nbinmut);
    }
    fflush(stdout);
    fflush(fpt1);
    fflush(fpt2);
    fflush(fpt3);
    fflush(fpt4);
    fflush(fpt5);
    fclose(fpt1);
    fclose(fpt2);
    fclose(fpt3);
    fclose(fpt4);
    fclose(fpt5);
    if (nreal!=0)
    {
        free (min_realvar);
        free (max_realvar);
    }
    if (nbin!=0)
    {
        free (min_binvar);
        free (max_binvar);
        free (nbits);
    }
    deallocate_memory_pop (parent_pop, popsize);
    deallocate_memory_pop (child_pop, popsize);
    deallocate_memory_pop (mixed_pop, 2*popsize);
    free (parent_pop);
    free (child_pop);
    free (mixed_pop);
    // 释放问题申请的空间
    deallocate_prob();
    printf(" Routine successfully exited \n");
    return (0);
}