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

📄 demo2.cpp

📁 一个实现基因表达式编程来解决函数发现问题的小程序
💻 CPP
📖 第 1 页 / 共 2 页
字号:
       for(;k<nLengthOfGene;k++)
       {
          nSerialPos=RandomInt(nColumn+sizeof(functionset),nColumn+sizeof(functionset)+m_nNumOfGenes-1);
          oldpop[0][i].GeneSerial[k+j*nLengthOfGene]=fandt[nSerialPos];
         } 
     for(int a=0;a<m_ConstantNum;a++)
     oldpop[0][i].constants[a]=RandomFloat(m_LowerBound,m_UpperBound);
     
      }
   for(i=0;i<m_nGroupSize;i++)
   { 
	 oldpop[nCurGepNum][i].fitness=fitnessfunc(oldpop[nCurGepNum][i]);
     TotalF=oldpop[nCurGepNum][i].fitness+TotalF;
   } 
     for(i=0;i<=m_nNumOfGenes;i++)
		infixlength[i]=0;
}


void sort()
{
	sort1(oldpop[nCurGepNum],m_nGroupSize);
	sort1(newpop,m_nNextGroupSize);
	int insertpos;
	int a=0,b=0;

 for(insertpos=0;insertpos<m_nGroupSize;insertpos++)
	{
		if(oldpop[nCurGepNum][a].fitness>newpop[b].fitness)
		{
			evaluate(oldpop[nCurGepNum+1][insertpos],oldpop[nCurGepNum][a++]);
		}
		else
		{
			evaluate(oldpop[nCurGepNum+1][insertpos],newpop[b++]);
		}
	}
}

int recompare(struct individual chromosome)
{
	int i=1;
	for(int j=0;j<m_nGroupSize;j++)
	{
		if(strcmp(oldpop[nCurGepNum][j].GeneSerial,chromosome.GeneSerial)==0)
			i=0;
	}
	return i;
}

void generation()
 { 
   TotalF=0;
   //计算当前一代群体中每个个体的适应值F
   for(int i=0;i<m_nGroupSize;i++)
   { 
	 TotalF=oldpop[nCurGepNum][i].fitness+TotalF;
   } 
   for(int c=0;c<m_nNextGroupSize/2;c++)
   {  
      int nExchangePos1,nExchangePos2;
      int new1=select();
      int new2=select();
      while(new1==new2)
       {
        new1=select();
        new2=select();
       }
	 //随机产生one-point的位置
     nExchangePos1=RandomInt(0,nLength-1);
     nExchangePos2=RandomInt(0,nLength-1); 
	 if(nExchangePos1>nExchangePos2)
	 {
		 i=nExchangePos1;
		 nExchangePos1=nExchangePos2;
		 nExchangePos2=i;
	 }
     for (int m=0;m<nLength;m++)
      { 
          if (m>=nExchangePos1&&m<=nExchangePos2)
           { 
             newpop[2*c].GeneSerial[m]=oldpop[nCurGepNum][new2].GeneSerial[m];
             newpop[2*c+1].GeneSerial[m]=oldpop[nCurGepNum][new1].GeneSerial[m];
		  }
           else
           { 
             newpop[2*c].GeneSerial[m]=oldpop[nCurGepNum][new1].GeneSerial[m];
             newpop[2*c+1].GeneSerial[m]=oldpop[nCurGepNum][new2].GeneSerial[m];
           }

       }//for结束
      for(int b=0;b<m_ConstantNum;b++)
      {   newpop[2*c].constants[b]=oldpop[nCurGepNum][new1].constants[b];
          newpop[2*c+1].constants[b]=oldpop[nCurGepNum][new2].constants[b];
      }
	  while(!recompare(newpop[2*c]))
      {
		  mutation(newpop[2*c]);
      }
	  while(!recompare(newpop[2*c+1]))
	  {
		  mutation(newpop[2*c+1]);
      }
	  newpop[2*c].fitness=fitnessfunc(newpop[2*c]);
      newpop[2*c+1].fitness=fitnessfunc(newpop[2*c+1]);
   }
    sort();
}

void statistics()
{  
   int i,j;
   double sumfitness=0.0;
   double min=oldpop[nCurGepNum][0].fitness;
   double max=oldpop[nCurGepNum][0].fitness;
   for(j=0;j<m_nGroupSize;j++)
   {  sumfitness=sumfitness+oldpop[nCurGepNum][j].fitness;
      if(oldpop[nCurGepNum][j].fitness>max) max=oldpop[nCurGepNum][j].fitness;
      if(oldpop[nCurGepNum][j].fitness<min) min=oldpop[nCurGepNum][j].fitness;
      if(oldpop[nCurGepNum][j].fitness>bestfit->fitness)
        {  
           for(i=0;i<nLength;i++)
               bestfit->GeneSerial[i]=oldpop[nCurGepNum][j].GeneSerial[i];
           for(i=0;i<m_ConstantNum;i++)
               bestfit->constants[i]=oldpop[nCurGepNum][j].constants[i];
               bestfit->fitness=oldpop[nCurGepNum][j].fitness;
               bestfit->generation=nCurGepNum;
         }
   }
  avg=sumfitness/m_nGroupSize;
  for(i=0;i<m_nGroupSize;i++)
	  fprintf(out_fp,"第%d个个体:%s----%lf\n",i+1,oldpop[nCurGepNum][i].GeneSerial,oldpop[nCurGepNum][i].fitness);
  fprintf(out_fp,"第%d代统计:\n",nCurGepNum);
  fprintf(out_fp,"最小适应度:%f 最大适应度:%f 平均适应度:%f\n",min,max,avg);
  fprintf(out_fp,"迄今发现最佳个体=》所在代数:%d",bestfit->generation);
  fprintf(out_fp,"适应度:%f 染色体:%s \n",bestfit->fitness,bestfit->GeneSerial,bestfit->constants);
  for(i=0;i<m_ConstantNum;i++)
	  fprintf(out_fp,"对应的常数(%d):%lf\n",i,bestfit->constants[i]);
}

void printbinarytree(binarytreenode *root,int nodelevel)
{
	int i;
	if(root!=NULL)
	{
		printbinarytree(root->lchild,nodelevel+1);
			for(i=0;i<=4*nodelevel;i++)
				fprintf(out_fp," ");
			fprintf(out_fp,"%c",root->element);
			fprintf(out_fp,"\n");
		printbinarytree(root->rchild,nodelevel+1);
			
	}
}

void infixarray(binarytreenode *root,int i,int &pos)
{  
    binarytreenode * parentnode;
	if(root!=NULL)
	{
		switch(root->element)
		{
		case '+':
		case '-':
			infixarray(root->lchild,i,pos);
			infixmid[i][pos++]=root->element;
            infixarray(root->rchild,i,pos);
            break;
		case '*':
		case '/':
			parentnode=root;
			root=parentnode->lchild;
			if(root->element=='+'||root->element=='-')
			{
				infixmid[i][pos++]='(';
				infixarray(parentnode->lchild,i,pos);
				infixmid[i][pos++]=')';
			}
			else
				infixarray(parentnode->lchild,i,pos);
			infixmid[i][pos++]=parentnode->element;
			root=parentnode->rchild;
            if(root->element=='+'||root->element=='-')
			{
				infixmid[i][pos++]='(';
				infixarray(parentnode->rchild,i,pos);
				infixmid[i][pos++]=')';
			}
			else
				infixarray(parentnode->rchild,i,pos);
			break;
		default:{ if(islower(root->element))
					asize++;
			      infixmid[i][pos++]=root->element;
				}
		}
	}

}

void report()
{ 
  int lenofstring=0;
  nCurConNum=0;
  int finalpos=0;
  char *ptr=new char[20];
  double m;
  int pos=0;
  for(int i=0;i<=m_nNumOfGenes;i++)
  {
	  if(i<m_nNumOfGenes)
	  {
		  fprintf(out_fp,"sub-ET%d",i+1);
	  }
	  else 
		  fprintf(out_fp,"ET");
	  fprintf(out_fp,"\n");
	  buildatree(bestfit->GeneSerial,i*nLengthOfGene,(i+1)*nLengthOfGene);
	  infixarray(binarytree[0],i,infixlength[i]);
	  printbinarytree(binarytree[0],0);
	  fprintf(out_fp,"\n");
  }
  for(i=0;i<=m_nNumOfGenes;i++)
      lenofstring+=infixlength[i];
  infixstring=new char[lenofstring+20*asize];
  for(i=0;i<infixlength[m_nNumOfGenes];i++)
  {
	  if(isoperator(infixmid[m_nNumOfGenes][i]))
		  infixfinal[finalpos++]=infixmid[m_nNumOfGenes][i];
	  else 
	  {   infixfinal[finalpos++]='(';
		  for(int j=0;j<infixlength[infixmid[m_nNumOfGenes][i]-'1'];j++)
			  infixfinal[finalpos++]=infixmid[infixmid[m_nNumOfGenes][i]-'1'][j];
		  infixfinal[finalpos++]=')';
	  }
   }
  infixstring[pos++]='y';
  infixstring[pos++]='=';
  for(i=0;i<finalpos;i++)
  {   
     if(islower(infixfinal[i]))
	 {
         m=bestfit->constants[infixfinal[i]-'a'];
        if(m<0)
		{
		   infixstring[pos++]='(';
		   gcvt(m,10,ptr);
           for(int j=0;ptr[j]!='\0';j++)
			 infixstring[pos++]=ptr[j];
		   infixstring[pos++]=')';
		}
		else
		{
		   gcvt(m,10,ptr);
			for(int j=0;ptr[j]!='\0';j++)
			 infixstring[pos++]=ptr[j];
		}
	 }
	 else
		 infixstring[pos++]=infixfinal[i];

  }
  char *infixstring1=new char[pos];
  infixstring[pos]='\0';
  strcpy(infixstring1,infixstring);
  fprintf(out_fp,"函数表达式是:%s",infixstring);
  /*Engine *eng;
  mxArray *A=NULL,*Y=NULL;
  double *array=new double[20];
  for(i=0;i<20;i++)
	  array[i]=(-5+0.5*i);
  if(!(eng=engOpen(NULL)))
  {
	  printf("can't start Matlab engine!\n");
      exit(1);
  }
  A=mxCreateDoubleMatrix(1,20,mxREAL);
  Y=mxCreateDoubleMatrix(1,20,mxREAL);

  memcpy((char *)mxGetPr(A),array,20*sizeof(float));
  engPutVariable(eng,"A",A);
  //engEvalString(eng,"infixstring;");
  engEvalString(eng,"Y=A*A");
  engEvalString(eng,"plot(A,Y);");
  mxDestroyArray(A);
  mxDestroyArray(Y);
  //engClose(eng);
  delete array;*/
}

void freeall()
{   
   int i,j;
   for(i=0;i<=m_GepNum;i++)
      for(j=0;j<m_nGroupSize;j++)
      {
		  delete oldpop[i][j].GeneSerial;
		  delete oldpop[i][j].constants;
      }

   for(i=0;i<=m_GepNum;i++)
	   delete [] oldpop[i];
  delete []oldpop;
  for(i=0;i<m_nNextGroupSize;i++)
   {
	   delete [] newpop[i].GeneSerial;
	   delete [] newpop[i].constants;
   }
cout<<"line "<<__LINE__<<endl;
   delete []newpop;
   delete bestfit;
   delete []binarytree;
   delete midresult;
   delete data;

   delete terminalset;
   delete fandt;
   for(i=0;i<=m_nNumOfGenes;i++)
	   delete infixmid[i];
cout<<"line "<<__LINE__<<endl;
   delete []infixmid;
   delete infixfinal;
cout<<"line "<<__LINE__<<endl;
  delete [] infixstring;
}


void main()
{ 
  char in_filename[20];
  char out_filename[20];
  int i,j;
  time_t t;
  srand((unsigned) time(&t));

  printf("please input the file name of Data Source:\n");
  scanf("%s",in_filename);
  if((in_fp=fopen(in_filename,"rt"))==NULL)
  {
    fprintf(stderr,"cannot open input file %s\n",in_filename);
    exit(-1);
  }
  fscanf(in_fp,"%d%d%d%d%d%d%d%f%f%d%d",&m_GepNum,&m_nGroupSize,&m_nNextGroupSize,&m_nNumOfGenes,&m_nHeadSize,&m_LowerBound,&m_UpperBound,&m_PRecombination,&m_PMutation,&nRow,&nColumn);
  trainingset=new double *[nRow];
  for(i=0;i<nRow;i++)
  trainingset[i]=new double[nColumn];
  for(i=0;i<nRow;i++)
   for(j=0;j<nColumn;j++)
     fscanf(in_fp,"%lf",&trainingset[i][j]);
  m_nIdVariNum=nColumn-1;
  nLengthOfTail=m_nHeadSize*(nArity-1)+1;
  nLengthOfGene=m_nHeadSize+nLengthOfTail;
  nLength=nLengthOfGene*(m_nNumOfGenes+1);
  printf("please input the file name to store the results:\n");
  scanf("%s",out_filename);

   if((out_fp=fopen(out_filename,"w"))==NULL)
  {
    fprintf(stderr,"cannot open output file %s\n",out_filename);
    exit(-1);
  }
  if(strcmp(in_filename,out_filename)==0)
   {
      fseek(out_fp,0L,2);      //置out_fp为文件末尾;
    } 
  initialize();
  for(nCurGepNum=0;nCurGepNum<m_GepNum;nCurGepNum++)
  {
     fprintf(out_fp,"\n第%d代运行(共%d代):\n",nCurGepNum,m_GepNum);
     generation();
     statistics();
  }
report();
freeall();

fclose(in_fp);
fclose(out_fp);
}

⌨️ 快捷键说明

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