⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 userdefinables.cpp

📁 遗传算法程序最新版
💻 CPP
📖 第 1 页 / 共 3 页
字号:
/***************************************************************/* Single & Multi-Objective Real-Coded Genetic Algorithms Code *//* Author: Kumara Sastry                                       *//* Illinois Genetic Algorithms Laboratory (IlliGAL)            *//* Deparment of General Engineering                            *//* University of Illinois at Urbana-Champaign                  *//* 104 S. Mathews Ave, Urbana, IL 61801                        *//***************************************************************/#include <iostream>
#include <fstream>#include <iomanip>#include "ga.hpp"#include "random.hpp"#include "globalSetup.hpp"#include <math.h>
#include <vector>
#include <string> #define BLANK_STR " \t\n\r"using namespace std;GlobalSetup *globalSetup;Random myRandom;
double P1; //核函数的参数

//下面是需要从外部读入的模型的数据
double beta[200];        //拉格朗日乘子
double trnX[80][20];      //训练的输入数据
int dimension;   //  训练输入的行向量的个数
int n;    //非零的拉格朗日乘子的个数
double bias; //偏差



void ReadSvm()
{
	int i=0;
	fstream infilebeta;
	fstream infilebias;
	fstream infiletrnX;
	infilebeta.open("c:\\beta.dat",ios::in);
	infilebias.open("c:\\bias.dat",ios::in);
	infiletrnX.open("c:\\trnX.txt",ios::in);
	if(!infilebeta||!infilebias||!infiletrnX)
	{
		cout<<"at least one file can't be opened!\n";
		abort();
	}
	//读拉格朗日乘子
	while(!infilebeta.eof())
	{
		char s[20];
		infilebeta.getline(s,20);
		beta[i]=atof(s);
		i++;
	}
	n=i;
	char s[20];
	infilebias.getline(s,20);
	bias=atof(s); //偏差
	int trainline=0;
	//读训练的输入数据
	while(!infiletrnX.eof())
	{
		char s[100];
		char trnx[6][10];
		i=0;
		int length=0;
		infiletrnX.getline(s,100);
		for(int j=0;j<6;j++)
		{
			while(1)
			{
			if(s[i+length]!=','&&s[i+length]!=' ')
			{
				trnx[j][i]=s[i+length];
				i++;
			}
			else
			{
				i++;
				length=length+i;
				i=0;
				break;
			}
			}
			trnX[trainline][j]=atof(trnx[j]);
		}
		trainline++;
	}
	dimension=trainline;
	infilebeta.close();
	infilebias.close();
	infiletrnX.close();
}
//根据训练的模型求得函数值
double SvmFunction(double *tstX,double trnX[80][20],double *beta,double bias,int dimension ,int n)
{
	int ii,jj;
	double diff=0.0;
	double tstY;
	double *H=new double[n];
	for(ii=0; ii<n; ii++)
	{
		for(jj=0; jj<dimension;jj++)
			diff=diff+(-(tstX[jj]-trnX[ii][jj])*(tstX[jj]-trnX[ii][jj]));
		H[ii]=exp(diff/(2*P1*P1));
		tstY=tstY+H[ii]*beta[ii];
	}
	tstY=tstY+bias;
	delete[] H;
	return tstY;
}

/* Objective function and constraints go here */void globalEvaluate(double *x, double *objArray, double *constraintViolation,		    double *penalty, int *noOfViolations){  int ii;  FILE *outEvals;   for(ii = 0; ii < globalSetup->finalNoOfObjectives; ii++)    objArray[ii] = 0.0;    if(globalSetup->gaType == SGA) {    *objArray = SvmFunction(x,trnX,beta,bias,dimension,n);/*    constraintViolation[0] = (x[0]-5.0)*(x[0]-5.0) + x[1]*x[1] - 26.0;    if(constraintViolation[0] <= 0.0) constraintViolation[0] = 0.0;        constraintViolation[1] = 4*x[1] + x[2] - 20.0;    if(constraintViolation[1] <= 0.0) constraintViolation[1] = 0.0;
	*/  }
  //未改,可以分别用训练所得模型计算  else {    objArray[0] = -10*exp(-0.2*sqrt(x[0]*x[0] + x[1]*x[1])) - 10*exp(-0.2*sqrt(x[1]*x[1] + x[2]*x[2]));    objArray[1] = pow(fabs(x[0]),0.8) + pow(fabs(x[1]),0.8) + pow(fabs(x[2]),0.8) + 5.0*sin(x[0]*x[0]*x[0]) + 5.0*sin(x[1]*x[1]*x[1]) + 5.0*sin(x[2]*x[2]*x[2]);  }  *penalty = 0.0;    *noOfViolations = 0;  for(ii = 0; ii < globalSetup->finalNoOfConstraints; ii++) {    if(constraintViolation[ii]) ++(*noOfViolations);    if(globalSetup->constraintMethod == Penalty) {      if(globalSetup->penaltyFunction == Linear) 	*penalty += globalSetup->penaltyWeights[ii]*fabs(constraintViolation[ii]);      else if(globalSetup->penaltyFunction == Quadratic)	*penalty += globalSetup->penaltyWeights[ii]*	  (constraintViolation[ii]*constraintViolation[ii]);    }    else      *penalty += fabs(constraintViolation[ii]);  }
  if(globalSetup->savePopulation) {    outEvals = fopen(globalSetup->saveEvalSolutions, "a");    for(ii = 0; ii < globalSetup->noOfDecisionVariables; ii++) {      fprintf(outEvals, "%f\t", x[ii]);    }      for(ii = 0; ii < globalSetup->finalNoOfObjectives; ii++) {      fprintf(outEvals, "%f\t", objArray[ii]);    }    if(globalSetup->finalNoOfConstraints > 0) {      for(ii = 0; ii < globalSetup->finalNoOfConstraints; ii++) {	fprintf(outEvals, "%f\t", constraintViolation[ii]);      }      fprintf(outEvals, "%f", *penalty);    }    fprintf(outEvals, "\n");    fflush(outEvals);    fclose(outEvals);  }}/*  Read a non-comment, non-blank line from the specified file stream  At EOF, it returns NULL.  Otherwise, it returns the pointer to the first token.  (The string just read in is altered by strtok().)*/static char* readOneLine(char *pcBuf, int iMaxSize, FILE *fStream){  char *pToken;    do {    pToken = NULL;        *pcBuf = '\0';    fgets(pcBuf, iMaxSize, fStream);    if (feof(fStream))      break;        // get the first token    pToken = strtok(pcBuf, BLANK_STR);        // if there is no first token, it is a blank line.    // if the first token starts with '#', it is a comment line.  } while ((pToken == NULL) || (*pToken == '#'));     return (pToken);}  int main(int argc, char *argv[]) {  int ii;  const int ciBufSize = 1024;  char *pToken, caBuf[ciBufSize];  FILE *fInput, *fOutput;
  ReadSvm();  if(argc != 2) {    printf("Error! Usage is GAtbx inputfile\n");    exit(1);  }  fInput = fopen(argv[1], "r");  if (fInput == NULL) {    printf("Error! opening file %s\n", argv[1]);    exit(1);  }           globalSetup = new GlobalSetup;    if ((pToken = readOneLine(caBuf, ciBufSize, fInput)) == NULL) {    fclose(fInput);    printf("Error in the input file, please refer to the documentation\n");    exit(1);  }  //GA type  if (strcmp("SGA", pToken) == 0) {    globalSetup->gaType = SGA;  }  else if (strcmp("NSGA", pToken) == 0) {    globalSetup->gaType = NSGA;                //输入遗传算法类型  }  else {    fclose(fInput);    printf("Unknown parameter! It should be either SGA or NSGA\n");    exit(1);  }  // decision variables    // read the number of decision variables  if ((pToken = readOneLine(caBuf, ciBufSize, fInput)) == NULL) {    fclose(fInput);    printf("Error in the input file, please refer to the documentation\n");    exit(1);  }  // the number can't be less than or equal to zero  if ((globalSetup->noOfDecisionVariables = atoi(pToken)) <= 0) {    fclose(fInput);    printf("Error! number of decision variables should be > 0\n");    exit(1);  }  globalSetup->variableTypes = new VariableType[globalSetup->noOfDecisionVariables];  globalSetup->variableRanges = new double*[(globalSetup->noOfDecisionVariables)];  for(ii = 0; ii < globalSetup->noOfDecisionVariables; ii++) {    // read a line    if ((pToken = readOneLine(caBuf, ciBufSize, fInput)) == NULL) {      fclose(fInput);      printf("Error in the input file, please refer to the documentation\n");      exit(1);    }    // variable type    if (strcmp("double", pToken) == 0) {      globalSetup->variableTypes[ii] = Real;    }    else if (strcmp("int", pToken) == 0) {                   //读入决策变量的类型      globalSetup->variableTypes[ii] = Integer;    }    else {      fclose(fInput);      printf("Error in the input file, please refer to the documentation\n");      exit(1);    }        // variable ranges    // allocate memory    globalSetup->variableRanges[ii] = new double[2];          // lower bound    if ((pToken = strtok(NULL, BLANK_STR)) == NULL) {      fclose(fInput);      printf("Error in the input file, please refer to the documentation\n");      exit(1);    }    globalSetup->variableRanges[ii][0] = atof(pToken);      //variableRanges[i][0]存入第i个决策变量的下限,variableRanges[i][1]放上限    // upper bound    if ((pToken = strtok(NULL, BLANK_STR)) == NULL) {      fclose(fInput);      printf("Error in the input file, please refer to the documentation\n");      exit(1);    }    globalSetup->variableRanges[ii][1] = atof(pToken);    if(globalSetup->variableRanges[ii][1] <= globalSetup->variableRanges[ii][0]) {      fclose(fInput);      printf("Error! lower bound, %f, must be lower than the upper bound, %f\n", globalSetup->variableRanges[ii][0], globalSetup->variableRanges[ii][1]);      exit(1);    }  }  // objectives    // read the number of objectives  if ((pToken = readOneLine(caBuf, ciBufSize, fInput)) == NULL) {    fclose(fInput);    printf("Error in the input file, please refer to the documentation\n");    exit(1);  }  // the number can't be less than or equal to zero  if ((globalSetup->noOfRawObjectives = atoi(pToken)) <= 0) {    fclose(fInput);    printf("Error! number of objectives should be > 0\n");    exit(1);  }  globalSetup->finalNoOfObjectives = globalSetup->noOfRawObjectives;       //读入需优化的目标函数的个数  globalSetup->noOfLinearObjectiveCombinations = 0;  globalSetup->typeOfOptimizations = new OptimType[globalSetup->finalNoOfObjectives];  for(ii = 0; ii < globalSetup->finalNoOfObjectives; ii++) {    // read a line    if ((pToken = readOneLine(caBuf, ciBufSize, fInput)) == NULL) {      fclose(fInput);      printf("Error in the input file, please refer to the documentation\n");      exit(1);    }    // optimization type    if (strcmp("Min", pToken) == 0) {      globalSetup->typeOfOptimizations[ii] = Minimization;             //读入每个目标函数的优化类型:最大还是最小    }    else if (strcmp("Max", pToken) == 0) {      globalSetup->typeOfOptimizations[ii] = Maximization;    }    else {      fclose(fInput);      printf("Error! optimization type can either be Min or Max\n");      exit(1);    }   }  // constrained variables  // read the number of constrained variables  if ((pToken = readOneLine(caBuf, ciBufSize, fInput)) == NULL) {    fclose(fInput);    printf("Error in the input file, please refer to the documentation\n");    exit(1);  }  // the number can't be less than zero  if ((globalSetup->noOfRawConstraints = atoi(pToken)) < 0) {    fclose(fInput);    printf("Error! number of constraints should be >= 0\n");    exit(1);  }  else if (globalSetup->noOfRawConstraints == 0) {    if ((strlen(pToken) != 1) || (*pToken != '0')) {      fclose(fInput);      printf("Error! number of constraints should be >= 0\n");      exit(1);    }  }  globalSetup->noOfLinearConstraintCombinations = 0;                //读入约束条件的个数  globalSetup->finalNoOfConstraints = globalSetup->noOfRawConstraints;    // penalty weights  globalSetup->penaltyWeights = new double[globalSetup->finalNoOfConstraints];  for(ii = 0; ii < globalSetup->finalNoOfConstraints; ii++) {    // read a line    if ((pToken = readOneLine(caBuf, ciBufSize, fInput)) == NULL) {      fclose(fInput);      printf("Error in the input file, please refer to the documentation\n");      exit(1);    }    globalSetup->penaltyWeights[ii] = atof(pToken);         //如果有约束条件的话,依次读入其惩罚权重  }  // general parameters  // population size  if ((pToken = readOneLine(caBuf, ciBufSize, fInput)) == NULL) {    fclose(fInput);    printf("Error in the input file, please refer to the documentation\n");    exit(1);  }  if(strcmp("default", pToken) == 0) {    // Use a default value of 30*ell*log(ell);    printf("Using default population-sizing thumbrule: n = 30*ell*log(ell)\n");    // Take care of small problem sizes where log(ell) < 1    if(globalSetup->noOfDecisionVariables > 2)      globalSetup->populationSize = (int)(30*(globalSetup->noOfDecisionVariables)*log((double)(globalSetup->noOfDecisionVariables)));    else      globalSetup->populationSize = (int)(30*(globalSetup->noOfDecisionVariables));     //种群大小初始化(可默认)    //Round it to next nearest tenth number    if((globalSetup->populationSize)%10) globalSetup->populationSize += (globalSetup->populationSize)%10;    printf("The population size used is: %d\n", globalSetup->populationSize);  }  // the number can't be less than or equal to zero  else if ((globalSetup->populationSize = atoi(pToken)) <= 0) {    fclose(fInput);    printf("The population size must be > 0\n");    exit(1);  }  else if ((globalSetup->populationSize % 2) != 0) {    // the number can't be an odd number    fclose(fInput);    printf("Error! population size must be an even number\n");    exit(1);  }  // maximum generations  // the number can't be less than or equal to zero  if ((pToken = readOneLine(caBuf, ciBufSize, fInput)) == NULL) {    fclose(fInput);    printf("Error in the input file, please refer to the documentation\n");    exit(1);  }  if(strcmp("default", pToken) == 0) {    // Use a default value of 6*ell;    printf("Using default convergence-time thumbrule: tc = 6*ell\n");    globalSetup->maxGenerations = 6*(globalSetup->noOfDecisionVariables);    if((globalSetup->maxGenerations)%10) globalSetup->maxGenerations += 10-(globalSetup->maxGenerations)%10;    printf("The maximum number of generations set is: %d\n", globalSetup->maxGenerations);  }  else if ((globalSetup->maxGenerations = atoi(pToken)) <= 0) {    fclose(fInput);    printf("Error! maximum number of generations must be > 0\n");     //读入最大遗传代数(可默认)    exit(1);  }  // replace proportion  // the number should be in (0.0, 1.0]  if ((pToken = readOneLine(caBuf, ciBufSize, fInput)) == NULL) {    fclose(fInput);    printf("Error in the input file, please refer to the documentation\n");    exit(1);  }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -