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

📄 ga.cpp

📁 遗传算法类的声明及定义
💻 CPP
📖 第 1 页 / 共 2 页
字号:
	
	  p_newpop[j].fitness=0.0;
	  for(i=0; i<m_numpoint; i++)
	  {
		  p_newpop[j].objvalue[i] = p_observation[i]-p_calculation[i];
		  p_newpop[j].fitness += pow(p_newpop[j].objvalue[i],2.0);
	  }

	   /* 调整变异概率*/
	  m_pmutation=adjust_mp(p_newpop[j].fitness);
	  
	  /* 变异 */
	  mutation(p_newpop[j].chrom);

	  /* 解码并计算个体适应值 */	  
	  decode(&(p_newpop[j]));	  
	  WriteToFem(&(p_newpop[j]));
	  if(m_blErrorExit)return;
	  
	  objectfunc();
	  if(m_blErrorExit)return;
	  
	  ReadFromFem(p_calculation);
	  if(m_blErrorExit)return;
	  
	  p_newpop[j].fitness=0.0;
	  for(i=0; i<m_numpoint; i++)
	  {
		  p_newpop[j].objvalue[i] = p_observation[i]-p_calculation[i];
		  p_newpop[j].fitness += pow(p_newpop[j].objvalue[i],2.0);
	  }
      /********************** 第j个个体******************/

	  /********************** 第j+1个个体******************/
	  decode(&(p_newpop[j+1]));
	  
	  WriteToFem(&(p_newpop[j+1]));
	  if(m_blErrorExit)return;
	  
	  objectfunc();
	  if(m_blErrorExit)return;
	 
	  ReadFromFem(p_calculation);
	  if(m_blErrorExit)return;

	  p_newpop[j+1].fitness=0.0;
	  for(i=0; i<m_numpoint; i++)
	  {
		  p_newpop[j+1].objvalue[i] = p_observation[i]-p_calculation[i];
		  p_newpop[j+1].fitness += pow(p_newpop[j].objvalue[i],2.0);
	  }

	  /* 调整变异概率*/
	  m_pmutation=adjust_mp(p_newpop[j+1].fitness);
       /* 变异 */
      mutation(p_newpop[j+1].chrom);
	  
      /* 解码并计算个体适应值 */
      decode(&(p_newpop[j+1]));
	 
	  WriteToFem(&(p_newpop[j+1]));
	  if(m_blErrorExit)return;
	 
	  objectfunc();
	  if(m_blErrorExit)return;
	 
	  ReadFromFem(p_calculation);
	  if(m_blErrorExit)return;
	  
	  p_newpop[j+1].fitness=0.0;
	  for(i=0; i<m_numpoint; i++)
	  {
		  p_newpop[j+1].objvalue[i] = p_observation[i]-p_calculation[i];
		  p_newpop[j+1].fitness += pow(p_newpop[j].objvalue[i],2.0);
	  }
	  /********************** 第j+1个个体******************/
	  	  
      j = j+2;
  }
  while(j < (m_popsize-1));

  Replaceworst(p_newpop);
  Keepbest(p_newpop);
  Criterion();
}

/* 选择父代 */
int GA::select()  
{
    int i,j;

    i = randomint(1,m_popsize);
	j = randomint(1,m_popsize);
	
	if(i==j)
	{
		j = randomint(1,m_popsize);
	}

	if(p_oldpop[i].fitness<=p_oldpop[j].fitness)
		return(i-1);
	else
		return(j-1);
}

/* 遗传操作,双亲双子 */
void GA::crossover (BYTE *parent1, BYTE *parent2, BYTE *child1, BYTE *child2)

{
    int i,j, jcross;
    BYTE mask, btemp;
    if(flip(m_pcross))
    {
        jcross = randomint(1 ,(m_sumlchrom - 1));/* Cross between 1 and l-1 */
        m_ncross++;
        for(i = 1; i <= m_sumnumbytes; i++)
        {
            if(jcross >= (i*8))
            {
                child1[i-1] = parent1[i-1];
                child2[i-1] = parent2[i-1];
            }
            else if((jcross<(i*8)) && (jcross>((i-1)*8)))
            {
                mask = 1;
                for(j=1; j<=(jcross-1-((i-1)*8)); j++)
                {
                    btemp = 1;
                    mask = mask<<1;
                    mask = mask|btemp;
                }
                child1[i-1] = (parent1[i-1]&mask)|(parent2[i-1]&(~mask));
                child2[i-1] = (parent1[i-1]&(~mask))|(parent2[i-1]&mask);
            }
            else
            {
                child1[i-1] = parent2[i-1];
                child2[i-1] = parent1[i-1];
            }
        }
    }
    else
    {
        for(i=0; i<m_sumnumbytes; i++)
        {
            child1[i] = parent1[i];
            child2[i] = parent2[i];
        }
    }
}

/*变异操作*/
void GA::mutation(BYTE *child)   
{
    int i, j;
    BYTE mask, btemp = 1;
	
	for(i=0; i<m_sumnumbytes; i++)
	{
		mask = 0;
		
		for(j=1; j<=8; j++)
		{
			if(flip(m_pmutation))
            {
                mask = mask|(btemp<<j);
                m_nmutation++;
            }
		}
		child[i] = child[i]^mask;
	}
}

/*在整数low和high之间产生一个随机整数*/
int GA::randomint(int low, int high) 
{
	int medium;

 	medium = (int)((randomperc(&m_randseed)*(high-low))+low);
   
    return(medium);
}

/* 保留原种群中的最优个体 */
void GA::Keepbest(individual * population)
{
	m_bestfit.fitness = population[0].fitness;
	int numberbest = 0; /* stores the index of the best individual */
	
	for(int i=1; i<m_popsize; i++)
	{
		if(population[i].fitness < m_bestfit.fitness)
		{
            numberbest = i;
            m_bestfit.fitness = population[i].fitness;
		}
	}

	/* once the best member in the population is found, copy the genes */
	for(int j=0; j<m_sumnumbytes; j++)
		m_bestfit.chrom[j] = population[numberbest].chrom[j];

	for(int k=0; k<m_numvar; k++)
		m_bestfit.variable[k] = population[numberbest].variable[k];

	for(i=0; i<m_numpoint; i++)
		m_bestfit.objvalue[i] = population[numberbest].objvalue[i];

	m_bestfit.position = numberbest;	
}

/* 用原种群中的最优个体替换掉新种群中的最坏个体 */
void GA::Replaceworst(individual * population)
{
	double worstfitness = population[0].fitness;
	int numberworst = 0; /* stores the index of the best individual */
	
	for(int i=1; i<m_popsize; i++)
	{
		if(population[i].fitness > worstfitness)
		{
            numberworst = i;
            worstfitness = population[i].fitness;
		}
	}

	/* once the worst member in the population is found, replace the genes */
	for(int j=0; j<m_sumnumbytes; j++)
		population[numberworst].chrom[j] = m_bestfit.chrom[j];

	for(int k=0; k<m_numvar; k++)
		population[numberworst].variable[k] = m_bestfit.variable[k];

	for(i=0; i<m_numpoint; i++)
		population[numberworst].objvalue[i] = m_bestfit.objvalue[i];

	population[numberworst].fitness = m_bestfit.fitness;
}

/* 计算接口 */
void GA::Compute()
{
	individual * p_temp;
	
    initialize();
    if(m_blErrorExit)return;

	while((m_currentgen<m_maxgen)&&m_errorflag)
	{
		Statistics(p_oldpop);

		generation();
	    if(m_blErrorExit)return;

		m_bestfit.generation = m_currentgen;
	
		m_currentgen++;
		
		p_temp = p_oldpop;
		p_oldpop = p_newpop;
		p_newpop = p_temp;
		p_temp = NULL;
	
		WriteResult();
	    if(m_blErrorExit)return;
	}
}

/* 调节变异概率系数 */
double GA::adjust_mp(double fitness)
{
	double result;
	
	if(fitness<=m_averagefitness)
		result = m_pm1-(m_pm1-m_pm2)*(m_minfitness-fitness)/(m_minfitness-m_averagefitness);
	else
		result = m_pm1;
	
	return result;
}

/* 计算杂交概率系数 */
double GA::adjust_cp(double fitness)
{
	double result;
	
	if(fitness<=m_averagefitness)
		result = m_pc1-(m_pc1-m_pc2)*(fitness-m_averagefitness)/(m_minfitness-m_averagefitness);
	else
		result = m_pc1;
	
	return result;
}

/* 统计最大、最小及平均适应度 */
void GA::Statistics(individual *pop)
{
    m_sumfitness = 0.0;
	m_minfitness = pop[0].fitness;

    /* 计算最大、最小和累计适应度 */
    for(int i=0; i<m_popsize; i++)
    {
        m_sumfitness = m_sumfitness + pop[i].fitness;            
        if(pop[i].fitness < m_minfitness) 
			m_minfitness = pop[i].fitness;        
	}
    /* 计算平均适应度 */
    m_averagefitness = m_sumfitness/m_popsize;
}

/* 向文件中写反演变量性质的识别标志及其数值 */
void GA::WriteToFem(individual *pop)
{
	CString str;

	CString csBackOutFileName = mGcsFileName+_T(".btof");//back analysis to fem
	ofstream cBackOutFile;
	cBackOutFile.open((LPCSTR)csBackOutFileName); 
	if (cBackOutFile.fail())
	{
		AfxMessageBox("Cannot open input file of back analysis!!!",MB_OK);
		m_blErrorExit = true;
		return;
	}
	//write
    int index=1;

	cBackOutFile << m_numvar << endl;
    
	for(int i=0; i<m_numvar; i++)
	{
		str.Format("%d %d %d %d %.6f\n",index++, p_BAKindflag[i],
			p_iparameter[i], p_jparameter[i], pop->variable[i]);
		
		cBackOutFile << (LPCSTR)str;
	}

	//边界荷载输出
	if (m_numbndload > 0)
	{
		index=1;
		cBackOutFile << m_numbndload << endl;
		
		for(int j=0; j<m_numbndload; j++)
		{
			str.Format("%d %d %d %d %d %d %.4f %.4f %.4f %.4f %.4f %.4f\n",
				p_Bndload[j].index++, p_Bndload[j].wAddStage, p_Bndload[j].wAddStep, 
				p_Bndload[j].iNode1, p_Bndload[j].iNode2, p_Bndload[j].iCoordFlag,
				p_Bndload[j].BeginLoad1, p_Bndload[j].BeginLoad2, p_Bndload[j].BeginLoad3,
				p_Bndload[j].EndLoad1, p_Bndload[j].EndLoad2, p_Bndload[j].EndLoad3);
			
			cBackOutFile << (LPCSTR)str;
		}
	}

	cBackOutFile.close();
}

/* 读取有限元计算结果 */
void GA::ReadFromFem(double *calculatevalue)
{
	CString csFromFemFileName = mGcsFileName+_T(".ftob");//file from fem
	ifstream cFromFemFile;
	cFromFemFile.open((LPCSTR)csFromFemFileName); 
	if (cFromFemFile.fail())
	{
		AfxMessageBox("Cannot open input file of fem!!!",MB_OK);
		m_blErrorExit = true;
		return;
	}

	int index;
	
	for(int i=0;i<m_numpoint;i++)
	{
		cFromFemFile >> index;
		cFromFemFile >> calculatevalue[i];
	}

	cFromFemFile.close();
}

/* 输出每一代演化的最佳结果及其适应值 */
void GA::WriteResult()
{
	CString csToUserFileName = mGcsFileName+_T(".result");//file to user
	ofstream cResultFile;
	cResultFile.open((LPCSTR)csToUserFileName,ios::app);
	if (cResultFile.fail())
	{
		m_blErrorExit = true;
		AfxMessageBox("Cannot open output result file!!!",MB_OK);
		return;
	}
	cResultFile << "第" << m_currentgen << "代进化结果:" << endl;
	cResultFile << "适应值:" << m_bestfit.fitness << endl;
	cResultFile << "反演参数值依次为:";

	for(int i=0;i<m_numvar;i++)
		cResultFile << m_bestfit.variable[i] <<"  ";
	cResultFile << endl;

		cResultFile << "各量测点量测值与计算值之差分别为:" ;
	for(i=0; i<m_numpoint; i++)
		cResultFile << m_bestfit.objvalue[i] <<"  ";
	cResultFile << endl << endl;

	cResultFile.close();
}

//从MEA文件中读取监测数据
void GA::ReadMEA()
{
	CString csFromMeaFileName = mGcsFileName+_T(".MEA");//file from fem
	ifstream cFromMeaFile;
	cFromMeaFile.open((LPCSTR)csFromMeaFileName); 
	if (cFromMeaFile.fail())
	{
		AfxMessageBox("Cannot open input file of mea!!!",MB_OK);
		m_blErrorExit = true;
		return;
	}

	int iTemp;
	double dTemp;
	char tempch[256];

	cFromMeaFile.getline(tempch,256);
	for(int i=0;i<m_numpoint;i++)
	{
		cFromMeaFile >> iTemp >> dTemp >> dTemp >> dTemp  >> iTemp  >> iTemp
			 >> iTemp  >> iTemp  >> iTemp  >> iTemp  >> iTemp;
		cFromMeaFile >> p_observation[i];
		cFromMeaFile.getline(tempch,256);
	}

	cFromMeaFile.close();
}

void GA::Criterion()
{
	double dTemp;
	if(m_currentgen>1)
	{
		dTemp = fabs(m_oldbestfit.fitness - m_bestfit.fitness)/fabs(m_oldbestfit.fitness);
		if(dTemp<m_precision)
			m_convergencenumber++;
		if(m_convergencenumber>=m_precisionnum)
			m_errorflag = FALSE;
	}
}

⌨️ 快捷键说明

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