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

📄 nichegamodify.c

📁 采用FORTRAN编制的小生境遗传算法反演程序
💻 C
📖 第 1 页 / 共 2 页
字号:
/***************************************************************/
/*  程序功能: 實現小生境遺傳算法                              */
/*  參考文獻: 《遺傳算法原理及應用》                          */
/*  作者    : 周明 孫樹棟                                     */
/*  出版社  : 國防工業出版社(2001年第二版)                    */
/*  程序實現: 蒋龙聪                                          */
/*  單位    : 中國地質大學(武漢)地球物理與空間信息學院        */
/*  專業    : 地球探測與信息技術                              */
/*  研究方向: 地球物理數據處理及其地震層析成像                */
/*  説明    : 採用了Denis Cormier和Sita S.Raghavan的程序框架圖*/
/***************************************************************/

#include <stdio.h >
#include <stdlib.h>
#include <math.h>
#include <time.h>

/* 初始化遺傳算法參數,讀者可以根據實際問題修改設置參數值的大小*/

#define POPSIZE 100          /* 種群大小 */
#define N 50                /* 小生境保留值 */  
#define MAXGENS 200          /* 最大進化代數 */
#define NVARS 4             /* 反演參數的個數 */
#define PXOVER 0.8          /* 交叉概率 */
#define PMUTATION 0.2       /* 變異概率 采用实数编码 变异率可以放大些 配合非均匀变异 */
#define TRUE 1
#define FALSE 0
#define Lenth 120            /* 產生Gauss正態分佈而用的均勻分佈的長度 */
#define PI 3.1415926     /* 圓周率 */
#define RECEIVES 1001      /* 地震波形记录点数 */
#define shapeFactor 4        //非均勻變異中的形狀因子   //越大收敛早!~
#define HD  1              /*海明距離*/

int generation;              /* 當前代數值 */
int cur_best;                /* 最佳個體 */
double Penalty;
double Gfactor; 
double OBS[RECEIVES];
double h[3]={50,20,50};   
FILE *galog;                 /* 輸出文件 */


struct genotype              /* genotype (GT), a member of the population */
{
  double gene[NVARS];        /* a string of variables */
  double fitness;            /* GT's fitness */
  double upper[NVARS];       /* GT's variables upper bound */
  double lower[NVARS];       /* GT's variables lower bound */
  double cfitness;           /* cumulative fitness */
};

struct genotype population[POPSIZE+1];    /* population */
struct genotype newpopulation[POPSIZE+1]; /* new population; */
struct genotype nicheP[POPSIZE+N];        /* replaces the */
                                          /* old generation */
struct genotype popMemory[N];

/* Declaration of procedures used by this genetic algorithm */
void   initialize(void);
void   evaluate(void);
void   searchBest(void);
void   elitist(void);
void   select(void);
void   crossover(void);
void   Xover(int,int);
void   swap(double*,double*);
void   mutate(void);
void   nicheGA(void);
void   simulate(void);
double randval(double, double);
double randvalG(double,double);
double randvalNu(int,int,double,double);
double obFun(double x[]);
double hamming(int,int);
double hamming1(int,int);

/***************************************************************/
/* Initialization function: Initializes the values of genes    */
/* within the variables bounds. It also initializes (to zero)  */
/* all fitness values for each member of the population. It    */
/* reads upper and lower bounds of each variable from the      */
/* input file `gadata.txt'. It randomly generates values       */
/* between these bounds for each gene of each genotype in the  */
/* population. The format of the input file `gadata.txt' is    */
/* var1_lower_bound var1_upper bound                           */
/* var2_lower_bound var2_upper bound ...                       */
/***************************************************************/

void initialize(void)
{
	FILE *infile;
    int i, j;
    double lbound, ubound;
	double sum=0.0;
	if ((infile = fopen("gadata.txt","r"))==NULL)
	{
		fprintf(galog,"\nCannot open input file!\n");
        exit(1);
    }

/* initialize variables within the bounds */
	for(i=0; i<NVARS; i++)
	{
		fscanf(infile, "%lf",&lbound);
        fscanf(infile, "%lf",&ubound);
		for (j=0; j<POPSIZE; j++)
		{
			population[j].fitness = 0;
            population[j].cfitness= 0;
            population[j].lower[i]= lbound;
            population[j].upper[i]= ubound;
            population[j].gene[i] = randval(population[j].lower[i],population[j].upper[i]);
        }
	}
	fclose(infile);
	//產生第一個初始群體,爲了保持群體的差異性,引入Hamming距離加以控制和約束
/*
	j=0;
	for(i=0;i<NVARS; i++)
		population[j].gene[i]=randval(population[j].lower[i],population[j].upper[i]);
	while(j<POPSIZE)
	{
		j++;
		for(i=0; i<NVARS; i++)
		{
			population[j].gene[i]=randval(population[j].lower[i],population[j].upper[i]);
		}
		if(hamming(j,j-1)<HD)
			j--;
	}
*/
}

/***********************************************************/
/* Calculate the Hamming distance of two dataset           */
/***********************************************************/

double hamming(int i,int j)
{
	int k=0;
	double sum=0;
    for(k=0;k<NVARS;k++)
		sum=sum+(population[i].gene[k]-population[j].gene[k])*(population[i].gene[k]-population[j].gene[k]);
	return(sqrt(sum));
}

double hamming1(int i,int j)
{
	int k=0;
	double sum=0;
    for(k=0;k<NVARS;k++)
		sum=sum+(nicheP[i].gene[k]-nicheP[j].gene[k])*(nicheP[i].gene[k]-nicheP[j].gene[k]);
	return(sqrt(sum));
}

/***********************************************************/
/* Random value generator: Generates a value within bounds */
/* Generate uniform random numbers,the mutation is uniform */
/***********************************************************/

double randval(double low, double high)
{
	double val;
	val = low+((double)(rand()%1000)/1000.0)*(high-low);
	return(val);
}

/***********************************************************/
/* Random value generator: Generates a value within bounds */
/* Generate Gauss distribution random numbers,mutation also*/
/*****???????????????????????????????????????????????*******/
double randvalG(double low,double high)
{
	int i=0;
	double val,sum=0.0;
	for(i=0;i<Lenth;i++)
	{
		sum+=(double)(rand()%500)/500.0;
	}
	return (val=(low+high)/2+(high-low)*(sum-Lenth/2)/(Lenth/2));
}
/***********************************************************/
/* Random value generator: Generates a value within bounds */
/* Generate Non-unform random numbers,also the mutation    */
/*****???????????????????????????????????????????***********/

double randvalNu(int i,int j,double low,double high)
{
	double val;
	double r=generation/MAXGENS;
	double randN=(rand()%500)/500.0;
	if( (int) (randN+0.5)==0 )
		val=population[i].gene[j]+(high-population[i].gene[j])*(pow(randN*(1-r),shapeFactor));
	if( (int) ( randN+0.5)==1 )
		val=population[i].gene[j]-(population[i].gene[j]-low)*(pow(randN*(1-r),shapeFactor));
	return(val);          //非均匀变异
}

/*************************************************************/
/* Calculate the object function                             */
/* I chose Shuber function as a test function,while X[-10 10]*/
/* This function has the global minimum value,F(X)=-186.731  */
/*************************************************************/

double obFun(double x[])
{
	double g[RECEIVES],b[201],r[RECEIVES];//定义数组
	double dt=0.5,f0=60;  //数组赋值
	double t[3];//时间
	double v[4];
    double SUM;
	int mx=1;  
    int i=0,j=0,nw=100;



	v[0]=x[0];
	
	v[1]=x[1];
	
	v[2]=x[2];

	v[3]=x[3];
   
	
	//初始化反射系数数组		  
	for(i=0;i<RECEIVES;i++)
		r[i]=0.0;

	t[0]=2*h[0]/v[0];
	j=(int)(1000*t[0]/dt);
	r[j]=(v[1]-v[0])/(v[1]+v[0]); //1层 

	
	for(i=1;i<NVARS;i++)
	{
		t[i]=t[i-1]+2*h[i]/v[i];
		j=(int)(1000*t[i]/dt);
		r[j]=(v[i+1]-v[i])/(v[i+1]+v[i]);//2-4层
	}	

	
	for(i=-nw;i<nw+1;i++)
	{
		double a=(0.001*PI*f0*i*dt);
        b[i+nw]=(1.0-2.0*a*a)*exp(-a*a);//求取子波,0相位,
        
	}

	
	//Convolution   子波和参数做卷积
	for(i=0;i<RECEIVES;i++)//从第一道循环
	{
		double sum=0.0;
	    for(j=0;j<2*nw+1;j++)
		{
			if(i-j>=0&&i-j<=2*nw)
		    sum=sum+b[j]*r[i-j+1];
		}
		g[i]=sum;
		
	}

	for(i=0;i<RECEIVES;i++)    
	{       SUM=0.0;
	        SUM+=(OBS[i]-g[i])*(OBS[i]-g[i]);}  //目标函数
	        SUM=sqrt(SUM);
	return(5000.0-SUM);

}

/*************************************************************/
/* Evaluation function: This takes a user defined function.  */
/*************************************************************/

void evaluate(void)
{
	int mem;
	int i;
	double x[NVARS];
	for (mem = 0; mem < POPSIZE; mem++)
	{
		for (i=0;i<NVARS;i++)
            x[i] = population[mem].gene[i];
		population[mem].fitness =obFun(x);
	}
}

/***************************************************************/
/* searchBest function: This function keeps track of the       */
/* best member of the population. Note that the last entry in  */
/* the array Population holds a copy of the best individual    */
/***************从大到小排序排序********************************/

void searchBest()
{
	int mem;
    int i;
	struct genotype tempGA;
	for (mem=0;mem<POPSIZE-1;mem++)
	{
		for(i=mem+1;i<POPSIZE;i++)
		if (population[mem].fitness<population[i].fitness)
		{
			tempGA=population[mem];
			population[mem]=population[i];
			population[i]=tempGA;
		}
	}

	for(mem=0;mem<N;mem++)
		popMemory[mem]=population[mem];//記憶前N個基因
	
// once the best member in the population is found, copy the genes 
	population[POPSIZE]=population[0];
//    for (i = 0; i < NVARS; i++)
//		population[POPSIZE].gene[i] = population[0].gene[i];
}

/****************************************************************/
/* Elitist function: The best member of the previous generation */
/* is stored as the last in the array. If the best member of    */
/* the current generation is worse than the best member of the  */
/* previous generation, the latter one would replace the worst  */
/* member of the current population(保留最佳策略方案)           */
/****************************************************************/

void elitist()
{
	int i;
    double best, worst;             /* best and worst fitness values */
    int best_mem, worst_mem; /* indexes of the best and worst member */
    best = population[0].fitness;
    worst= population[0].fitness;
    for (i=0;i<POPSIZE-1;++i)
    {
		if(population[i].fitness>population[i+1].fitness)
		{  
            if (population[i].fitness>=best)
			{
				best = population[i].fitness;
                best_mem = i;
             }
            if (population[i+1].fitness<=worst)
            {
				worst=population[i+1].fitness;
                worst_mem=i+1;
            }
            }
		else
            {
			if (population[i].fitness<=worst)
			{
				worst = population[i].fitness;
                worst_mem=i;
            }
            if (population[i+1].fitness>= best)
            {
				best = population[i+1].fitness;
                best_mem =i+1;
             }
		}
	}
	printf("BestFitness=%8.4f \n",-best+5000.0);
/* if best individual from the new population is better than */
/* the best individual from the previous population, then    */
/* copy the best from the new population; else replace the   */
/* worst individual from the current population with the     */
/* best one from the previous generation                     */
	if (best>=population[POPSIZE].fitness)
    {
		for (i=0; i<NVARS; i++)
			population[POPSIZE].gene[i] = population[best_mem].gene[i];
		population[POPSIZE].fitness = population[best_mem].fitness;
    }
	else
    {
		for (i=0; i<NVARS; i++)
			population[worst_mem].gene[i] = population[POPSIZE].gene[i];
		population[worst_mem].fitness = population[POPSIZE].fitness;

⌨️ 快捷键说明

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