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

📄 sflalgorithm.cpp

📁 一个使用遗传算法实现桥梁的最优化维护的代码
💻 CPP
字号:
#include "StdAfx.h"
#include ".\sflalgorithm.h"
#include <math.h>

CSFLAlgorithm::CSFLAlgorithm(void)
{
}

CSFLAlgorithm::~CSFLAlgorithm(void)
{
	//撤销程序中动态分配的内存
	//if(this->piGoodIndex)free(piGoodIndex);
	//if(this->piWorseIndex)free(piWorseIndex);
	
    for(int j = 0; j < this->iPopSize; j++)
    {
		if(pPop[j].pChrom)
		  free(pPop[j].pChrom);
    }
	if(this->pPop)free(pPop);
	//if(this->piSort) free(piSort);
}
// 设置种群大小
void CSFLAlgorithm::SetPopSize(int iVar)
{
	this->iPopSize = iVar;
}

// 设置memeplexes的大小
void CSFLAlgorithm::SetMemEachSize(int iVar)
{
	this->iMemiEachSize = iVar;
}

// 设置ShuIterations的大小
void CSFLAlgorithm::SetShuIterations(int iVar)
{
	this->iShuIterations = iVar;
}

// 设置GenEachMem的大小
void CSFLAlgorithm::SetGenEachMem(int iVar)
{
	this->iGenEachMem = iVar;
}
// 设置染色体长度
void CSFLAlgorithm::SetLchrom(int iVar)
{
	this->iLchrom = iVar;
}
void CSFLAlgorithm::advance_random()  /* 产生55个随机数 */
{
    int j1;
    double new_random;
    for(j1 = 0; j1 < 24; j1++)
    {
        new_random = oldrand[j1] - oldrand[j1+31];
        if(new_random < 0.0) new_random = new_random + 1.0;
        oldrand[j1] = new_random;
    }
    for(j1 = 24; j1 < 55; j1++)
    {
        new_random = oldrand [j1] - oldrand [j1-24];
        if(new_random < 0.0) new_random = new_random + 1.0;
        oldrand[j1] = new_random;
    }
}

int CSFLAlgorithm::flip(float prob) /* 以一定概率产生0或1 */
{
   
    if(randomperc() <= prob)
        return(1);
    else
        return(0);
}

void CSFLAlgorithm::randomize()  /* 设定随机数种子并初始化随机数发生器 */
{
    float randomseed;

    int j1;
    for(j1=0; j1<=54; j1++)
      oldrand[j1] = 0.0;
    jrand=0;
      do
        {
            
          //   printf("随机数种子[0-1]:");
            //  scanf("%f", &randomseed);
			 randomseed = 0.5;
         }
        while((randomseed < 0.0) || (randomseed > 1.0));
    warmup_random(randomseed);
}

double CSFLAlgorithm::randomnormaldeviate() /* 产生随机标准差 */
{
    //double sqrt(), log(), sin(), cos();
    
    double t, rndx1;
    if(rndcalcflag)
    {   rndx1 = sqrt(- 2.0*log((double) randomperc()));
        t = 6.2831853072 * (double) randomperc();
        rndx2 = rndx1 * sin(t);
        rndcalcflag = 0;
        return(rndx1 * cos(t));
    }
    else
    {
        rndcalcflag = 1;
        return(rndx2);
    }
}

float CSFLAlgorithm::randomperc() /*与库函数random()作用相同, 产生[0,1]之间一个随机数 */
{
    jrand++;
    if(jrand >= 55)
    {
        jrand = 1;
        advance_random();
    }
    return((float) oldrand[jrand]);
}

int CSFLAlgorithm::rnd(int low, int high) /*在整数low和high之间产生一个随机整数*/
{
    int i;
    
    if(low >= high)
        i = low;
    else
    {
        i =(int)((randomperc() * (high - low + 1)) + low);
        if(i > high) i = high;
    }
    return(i);
}


void CSFLAlgorithm::warmup_random(float random_seed)  /* 初始化随机数发生器*/
{
    int j1, ii;
    double new_random, prev_random;

    oldrand[54] = random_seed;
    new_random = 0.000000001;
    prev_random = random_seed;
    for(j1 = 1 ; j1 <= 54; j1++)
    {
        ii = (21*j1)%54;
        oldrand[ii] = new_random;
        new_random = prev_random-new_random;
        if(new_random<0.0) new_random = new_random + 1.0;
        prev_random = oldrand[ii];
    }
    advance_random();
    advance_random();
    advance_random();
    jrand = 0;
}

void CSFLAlgorithm::initialize()  /* 遗传算法初始化 */
{
	 /* 键盘输入遗传算法参数 */
   // initdata();
    /* 确定染色体的字节长度 */
	this->iChromSize = (this->iLchrom/(8*sizeof(unsigned)));
    if(iLchrom%(8*sizeof(unsigned))) iChromSize++;
    /*分配给全局数据结构空间 */
    initmalloc();
    /* 初始化随机数发生器 */
    randomize();
    /* 初始化全局计数变量和一些数值*/
    
    /* 初始化种群,并统计计算结果 */
    initpop();
    /* statistics(oldpop);
    initreport();*/
}
void CSFLAlgorithm::initmalloc()     /*为全局数据变量分配空间 */
{
  unsigned nbytes;
  //char  *malloc();
  int j;
  /* 分配给当前代和新一代种群内存空间 */
  nbytes = iPopSize*sizeof(struct individual);
  if((pPop = (struct individual *) new char[nbytes]) == NULL)
  {
    printf( "no memory for Pop \n" );
    
  }
/* 分配给染色体内存空间 */
  nbytes = iChromSize*sizeof(unsigned);
  for(j = 0; j < this->iPopSize; j++)
    {
		if((pPop[j].pChrom = (unsigned *) malloc(nbytes)) == NULL)
		 printf("no memory for newpop chromosomes");
    }
 /* if((bestfit.chrom = (unsigned *) malloc(nbytes)) == NULL)
    nomemory("bestfit chromosome");

*/

/*	if((piSort = (int *) malloc(sizeof(int)*iPopSize)) == NULL)
	{
		printf( "no memory for piSort \n" );
	}*/
}
void CSFLAlgorithm::initpop()  /* 随机初始化种群 */
{
    int j, j1, k, stop;
    unsigned mask = 1;
	for(j = 0; j < this->iPopSize; j++)
    {
		for(k = 0; k < this->iChromSize; k++)
        {
			pPop[j].pChrom[k] = 0;
            if(k == (iChromSize-1))
                stop = this->iLchrom - (k*(8*sizeof(unsigned)));
            else
                stop =8*sizeof(unsigned);
            for(j1 = 1; j1 <= stop; j1++)
            {
               pPop[j].pChrom[k] = pPop[j].pChrom[k]<<1;

               if(flip(fInitPop))
                  pPop[j].pChrom[k] = pPop[j].pChrom[k]|mask;
            }
        }
       // oldpop[j].xsite = 0;
        objfunc(&(pPop[j]));  /* 计算初始适应度*/
    }
}
void CSFLAlgorithm::objfunc(struct individual *critter)  /* 计算适应度函数值 */
{
    unsigned mask=1;
    unsigned bitpos;
    unsigned tp;
    double  bitpow ;
    int j, k, stop;
	critter->dVarible = 0.0;
    for(k = 0; k < iChromSize; k++)
    {
		if(k == (this->iChromSize-1))
			stop = this->iLchrom-(k*(8*sizeof(unsigned)));
        else
            stop =8*sizeof(unsigned);
		tp = critter->pChrom[k];
        for(j = 0; j < stop; j++)
        {
            bitpos = j + (8*sizeof(unsigned))*k;
            if((tp&mask) == 1)
            {
                bitpow = pow(2.0,(double) bitpos);
				critter->dVarible = critter->dVarible + bitpow;
            }
            tp = tp>>1;
        }
    }

   	critter->dVarible =1+critter->dVarible/(pow(2.0,(double)this->iLchrom)-1);
    //critter->fitness =critter->varible*sin(critter->varible*10*atan(1.0)*4)+2.0;
	critter->dFitness =-1*(critter->dVarible-1.2)*(critter->dVarible-1.4)+20;
}
//对整个种群进行降序排列
void CSFLAlgorithm::Sort()
{
	//根据适应度值进行排序
	individual inTemp;
	int i,j;
	for(i = 0 ;i < this->iPopSize ; i++)
	{
		for(j = i + 1;j<this->iPopSize;j++)
		{
			if(this->pPop[i].dFitness<this->pPop[j].dFitness)
			{
				inTemp = pPop[i];
				pPop[i] = pPop[j];
				pPop[j] = inTemp;
			}

		}
	}
}
//进行一次净化
void CSFLAlgorithm::SFL()
{
	double dWorstFitness;
    int iWorstIndex,iBestIndex;
	int m,it,i;
	iGlobalBestIndex = 0; //经过排序后最好的个体排在第一
	for( m = 0;m<this->iMemNum;m++)
		for(it = 0;it<this->iGenEachMem;it++)
		{
			//先找出iWorstIndex,iBestIndex的值
            iWorstIndex = m;
            iBestIndex = m;
			for(i = 0 ; i<this->iMemiEachSize ; i++)
			{
				if(pPop[iMemNum*i+m].dFitness > pPop[iBestIndex].dFitness)
				{
					iBestIndex = iMemNum*i+m;
				}
				if(pPop[iMemNum*i+m].dFitness < pPop[iWorstIndex].dFitness)
				{
					iWorstIndex = iMemNum*i+m;
				}
			}
            dWorstFitness = pPop[iWorstIndex].dFitness;
			//修改iWorstIndex的值
			this->ChangeFrogPos(iWorstIndex,iBestIndex);
			if(dWorstFitness < pPop[iWorstIndex].dFitness)//如果变换后比原来的适应值得到改善
			{
				//比全局最佳适应值更好,则修改iGlobalBestIndex
				if(pPop[iWorstIndex].dFitness>pPop[iGlobalBestIndex].dFitness)
				{
					iGlobalBestIndex = iWorstIndex;
				}
				continue;
			}
			this->ChangeFrogPos(iWorstIndex,iGlobalBestIndex);
			if(dWorstFitness < pPop[iWorstIndex].dFitness)//如果变换后比原来的适应值得到改善
			{
				//比全局最佳适应值更好,则修改iGlobalBestIndex
				if(pPop[iWorstIndex].dFitness>pPop[iGlobalBestIndex].dFitness)
				{
					iGlobalBestIndex = iWorstIndex;
				}
				continue;
			}
			//如果得不到改善,则随机产生一个新的位置
			this->RndIndividual(&pPop[iWorstIndex]);
			//比全局最佳适应值更好,则修改iGlobalBestIndex
			if(pPop[iWorstIndex].dFitness>pPop[iGlobalBestIndex].dFitness)
			{
				iGlobalBestIndex = iWorstIndex;
			}
		}
}
//改变的frog的位置
//按照一定的概率,将iWorstIndex的对应部分染色体修改为iBestIndex对应的染色体
void CSFLAlgorithm::ChangeFrogPos(int iWorstIndex,int iBestIndex)
{
	unsigned mask = 1 ;
    int j, k, stop;
	float fTemp = this->randomperc();//产生一个0-1之间的随机数
    for(k = 0; k < iChromSize; k++)
    {
		if(k == (this->iChromSize-1))
			stop = this->iLchrom-(k*(8*sizeof(unsigned)));
        else
            stop =8*sizeof(unsigned);
		mask = 11;
        for(j = 0; j < stop; j++)
        {  
			if(this->flip(fTemp))
			{
				//修改对应的基因值
				this->pPop[iWorstIndex].pChrom[k] = (this->pPop[iWorstIndex].pChrom[k]&~mask)|(pPop[iBestIndex].pChrom[k]&mask);
			    
			}
			mask = mask << 1;
        }
    }
	//重新计算适应值
	this->objfunc(&pPop[iWorstIndex]);
}
//随机化个体的染色体
void CSFLAlgorithm::RndIndividual(struct individual *critter)
{
	int j, j1, k, stop;
    unsigned mask = 1;
	for(k = 0; k < this->iChromSize; k++)
        {
			critter->pChrom[k] = 0;
            if(k == (iChromSize-1))
                stop = this->iLchrom - (k*(8*sizeof(unsigned)));
            else
                stop =8*sizeof(unsigned);
            for(j1 = 1; j1 <= stop; j1++)
            {
               critter->pChrom[k] = critter->pChrom[k]<<1;

               if(flip(fInitPop))
                  critter->pChrom[k] = critter->pChrom[k]|mask;
            }
        }
       // oldpop[j].xsite = 0;
   objfunc(critter);  /* 计算初始适应度*/
}
//进行优化
void CSFLAlgorithm::Run()
{
	  int  gen;
     for(gen=0; gen<this->iShuIterations; gen++)
     {
         //排序
		 this->Sort();
         //进行SFL运算
		 
		 this->SFL();
            /* 输出新一代统计数据 */
   	 }
	 //输出结果
	 this->Report();
}
// 设置出示种群个体中染色体中1出现的概率
void CSFLAlgorithm::SetInitPop(float fVar)
{
	this->fInitPop = fVar;
}
//获得优化的结果
double CSFLAlgorithm::GetResult()
{
	return this->pPop[iGlobalBestIndex].dVarible;
}

// 产生计算结果报告
void CSFLAlgorithm::Report(void)
{
	for(int i = 0 ;i<this->iPopSize ;i++)
		printf("num:%d  varue:%f  fitness %f \n",i,this->pPop[i].dVarible,this->pPop[i].dFitness);
}

// 设置的数量
void  CSFLAlgorithm::SetMemNum(int iVar)
{
	this->iMemNum = iVar;
}

⌨️ 快捷键说明

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