📄 geneticalgorithm.txt
字号:
void move_individual(n)
int n;
{
int cx,cy,dx,dy,sp,vf,sumx,sumy;
int i,j,a,sgn[3],num;
double vect[8][2]={{1,0},{1,1},{0,1},{-1,1},
{-1,0},{-1,-1},{0,-1},{1,-1}};
double vx,vy,d1,d2;
double _cos,cos_max;
cx=iatr[n][0];
cy=iatr[n][1];
sp=decode_gene(n,0,1)+1;
for(i=0;i<3;i++)
{
sgn [ i]=decode_gene(n,9+i,1);
if(sgn [ i]==0) sgn [ i]=-1;
}
sumx=0;sumy=0;num=0;
vf=decode_gene(n,5,2)+1;
for(i=-vf;i<=vf;i++)
for(j=-vf;j<=vf;j++)
{
if(i!=0||j!=0)
{
a=get_world(cx+j,cy+i);
if(a==1||a==2)
{ num++;
if(a==sp)
{
sumx=sumx+sgn[0]*j;
sumy=sumy+sgn[0]*i;
}
else
{
sumx=sumx+sgn[1]*j;
sumy=sumy+sgn[1]*i;
}
} else
if(a==3||a==5)
{
num++;
sumx=sumx+sgn[2]*j;
sumy=sumy+sgn[2]*i;
}
}
}
if(num!=0)
{
vx=(double)sumx/(double)num;
vy=(double)sumy/(double)num;
if(vx!=0||vy!=0)
{
cos_max=-1.0;
j=0;
for(i=0;i<8;i++)
{
d1=sqrt(vx*vx+vy*vy);
d2=sqrt(vect [ i][0]*vect [ i][0]+vect [ i][1]*vect [ i][1]);
_cos=(vx*vect [ i][0]+vy*vect [ i][1])/d1/d2;
if(_cos>cos_max)
{
cos_max=_cos;j=i;
}
}
dx=cx+(int)vect[j][0];
dy=cy+(int)vect[j][1];
if(dx>=0 && dx<wx && dy>=0 && dy<wy)
if(world[dx][dy]==0)
move_pos(n,cx,cy,dx,dy);
}
else move_randomly(n);
}
else move_randomly(n);
}
void act1_attack(n)
int n;
{
int sft[8][2]={{1,0},{1,1},{0,1},{-1,1},
{-1,0},{-1,-1},{0,-1},{1,-1}};
int x1,y1,x2,y2,n2;
int found,rndnum;
double attack1,attack2,sa1,sa2,da1,da2,rnd1,rnd2,La1,La2;
x1=iatr[n][0];y1=iatr[n][1];
found=0;
while(found==0)
{
rndnum=random(8);
x2=x1+sft[rndnum][0];
y2=y1+sft[rndnum][1];
if(get_world(x2,y2)==1||get_world(x2,y2)==2)
found=1;
}
found=0;n2=0;
while(found==0)
{
if(iatr[n2][0]==x2 && iatr[n2][1]==y2 && iflg[n2]==1)
found=1; else n2++;
}
sa1=(double)decode_gene(n,19,3);
da1=(double)decode_gene(n,22,3);
sa2=(double)decode_gene(n2,19,3);
da2=(double)decode_gene(n2,22,3);
rnd1=(double)random(1001)/1000.0;
rnd2=(double)random(1001)/1000.0;
attack1=(double)iatr[n][2]+sa1*20.0/7.0*rnd1+da1*20.0/7.0*rnd2;
rnd1=(double)random(1001)/1000.0;
rnd2=(double)random(1001)/1000.0;
attack2=(double)iatr[n2][2]+sa2*20.0/7.0*rnd1+da2*20.0/7.0*rnd2;
La1=decode_gene(n,25,3);
La2=decode_gene(n2,25,3);
rnd1=(double)random(1001)/1000.0;
iatr[n][2]=iatr[n][2]-(int)((double)La1*rnd1);
rnd2=(double)random(1001)/1000.0;
iatr[n2][2]=iatr[n2][2]-(int)((double)La2*rnd2);
if(attack1>=attack2)
iatr[n2][2]=iatr[n2][2]-40;
else
iatr[n][2]=iatr[n][2]-40;
if(iatr[n][2]<=0) remove_life(n);
if(iatr[n2][2]<=0) remove_life(n2);
}
void act2_eat(n)
int n;
{
int sft[8][2]={{1,0},{1,1},{0,1},{-1,1},
{-1,0},{-1,-1},{0,-1},{1,-1}};
int x1,y1,x2,y2,n2,ef;
int found,rndnum;
x1=iatr[n][0];y1=iatr[n][1];
found=0;
while(found==0)
{
rndnum=random(8);
x2=x1+sft[rndnum][0];
y2=y1+sft[rndnum][1];
if(get_world(x2,y2)==3||get_world(x2,y2)==5)
found=1;
}
ef=decode_gene(n,28,4);
iatr[n][2]=iatr[n][2]+(int)(40.0*(50.0+(double)ef*50.0/15.0)/100.0);
if(iatr[n][2]>100) iatr[n][2]=100;
found=0;n2=0;
while(found==0)
{
if(fatr[n2][0]==x2 && fatr[n2][1]==y2 && fflg[n2]==1)
found=1; else n2++;
}
remove_food(n2);
}
void act3_makechild(n)
int n;
{
int i,j,k,x,y,x2,y2,found,n2,trial;
int x3,y3;
double rnd;
if(pop_size+1<=MAX_POP)
{
x=iatr[n][0];y=iatr[n][1];
found=0;
while(found==0)
{
x2=x+random(3)-1;
y2=y+random(3)-1;
if(x2!=x||y2!=y)
if(get_world(x2,y2)==gene[n][0]+1);
found=1;
}
found=0; n2=0;
while(found==0)
{
if((iatr[n2][0]==x2 || iatr[n2][1]==y2) && iflg[n2]==1)
found=1; else n2++;
if(n2>=pop_size-1) return;
}
found=0;trial=0;
while(found==0 && trial<50)
{
i=random(3)-1;j=random(3)-1;
k=random(2);
if(k==0) { x3=x+i;y3=y+j;}
else { x3=x2+i;y3=y2+j;}
if(get_world(x3,y3)==0) found=1;
trial++;
}
if(found==1)
{
pop_size++;
uni_crossover(gene,n,n2,pop_size-1,0.5,G_LENGTH);
for(i=1;i<G_LENGTH;i++)
{
rnd=random(10001)/10000.0;
if(rnd<=MUTATION)
if(gene[pop_size-1] [ i]==1)
gene[pop_size-1] [ i]=0;
else gene[pop_size-1] [ i]=1;
}
iatr[n][2]=iatr[n][2]-45;
if(iatr[n][2]<=0) remove_life(n);
iatr[n2][2]=iatr[n2][2]-45;
if(iatr[n2][2]<=0) remove_life(n2);
iatr[pop_size-1][0]=x3;
iatr[pop_size-1][1]=y3;
iatr[pop_size-1][2]=100;
iatr[pop_size-1][3]=0;
iflg[pop_size-1]=1;
world[x3][y3]=gene[pop_size-1][0]+1;
g_disp_unit(x3,y3,gene[pop_size-1][0]+1);
}
}
}
void act_individual(n)
int n;
{
int i,j,k,pattern,action,cr,ca;
int act[3];
int pat[6][3]={{1,2,3},{1,3,2},{2,1,3},
{3,1,2},{2,3,1},{3,2,1}};
int sp;
double rnd;
sp=decode_gene(n,0,1)+1;
for(i=0;i<3;i++) act [ i]=0;
for(i=-1;i<=1;i++)
for(j=-1;j<=1;j++)
{
if(i!=0||j!=0)
{
k=get_world(iatr[n][0]+j,iatr[n][1]+i);
if(k==1||k==2) act[0]=1;
if(k==3||k==5) act[1]=1;
if(k==sp) act[2]=1;
}
}
cr=decode_gene(n,16,3);
rnd=(double)random(10001)/10000.0;
if(rnd<=(double)cr/7.0)
{
action=random(3);
while(act[action]==0)
action=random(3);
}
else
{
ca=decode_gene(n,13,3);
if(ca<3) pattern=0;else pattern=ca-2;
i=0;
action=pat[pattern] [ i]-1;
while( act[action]==0)
{
i++;
action=pat[pattern] [ i]-1;
}
}
switch(action+1)
{
case 1: act1_attack(n);break;
case 2: act2_eat(n);break;
case 3: act3_makechild(n);
}
}
void init_flags()
{
int i;
for(i=0;ifor(i=0;i<food_size;i++) fflg [ i]=1;
}
void act_lives()
{
int i,j,k,x,y,move,a;
for(i=0;i{
if(iflg [ i]==1)
{
move=1;
for(j=-1;j<=1;j++)
for(k=-1;k<=1;k++)
{
if(j!=0||k!=0)
{
a=get_world(iatr [ i][0]+k,iatr [ i][1]+j);
if(a==1||a==2||a==3||a==5)
move=0;
}
}
if(move==1)
move_individual(i);
else
act_individual(i);
}
}
}
void increase_age()
{
int i,j,s;
for(i=0;i{
if(iflg [ i]==1)
{
j=decode_gene(i,1,4);
s=SL_MIN+j;
iatr [ i][3]++;
if(iatr [ i][3]>s)
remove_life(i);
}
}
}
void increase_frsh()
{
int i;
for(i=0;i<food_size;i++)
if(fflg [ i]==1)
{
fatr [ i][3]++;
if((fatr [ i][2]==0 && fatr [ i][3]>TL1)||
(fatr [ i][2]==1 && fatr [ i][3]>TL2))
remove_food(i);
}
}
void gabage_col()
{
int i,j;
int new_pop,new_food;
new_food=0;
for(i=0;i<food_size;i++)
if(fflg [ i]==1)
{
new_food++;
for(j=0;j<4;j++)
fatr[new_food-1][j]=fatr [ i][j];
}
food_size=new_food;
new_pop=0;
for(i=0;iif(iflg [ i]==1)
{
new_pop++;
for(j=0;j<G_LENGTH;j++)
gene[new_pop-1][j]=gene [ i][j];
for(j=0;j<4;j++)
iatr[new_pop-1][j]=iatr [ i][j];
}
pop_size=new_pop;
}
void make_foods()
{
int i,x,y;
for(i=0;i<NEWFOODS;i++)
{
if(food_size+1<=MAX_FOOD)
{
food_size++;
find_empty(&x,&y);
fatr[food_size-1][0]=x;
fatr[food_size-1][1]=y;
fatr[food_size-1][2]=0;
fatr[food_size-1][3]=0;
fflg[food_size-1]=1;
world[x][y]=3;
g_disp_unit(x,y,3);
}
}
}
void calc_population(n1,n2)
int *n1,*n2;
{
int i,p1,p2;
p1=0;p2=0;
if(pop_size>0)
for(i=0;iif(gene [ i][0]==0) p1++; else p2++;
*n1=p1;
*n2=p2;
}
main()
{
int i,work;
int n1,n2,n1old,n2old;
char choice[2];
randomize();
g_init();
settextstyle(0,0,4);
gprintf(220,20,4,0,"ALIFE");
setcolor(9);
disp_hz24("基于遗传算法的人工生命模拟",150,60,25);
setcolor(15);
disp_hz16("人工环境及生物分布",10,160,20);
disp_hz16("1:随机产生 2: 读文件产生 ==>",10,190,20);
gscanf(300,190,15,1,4,"%s",choice);
work=atoi(choice);
if(work==2) load_world_file();else make_world();
make_lives_and_foods();
init_flags();
calc_population(&n1old,&n2old);
g_init_frames();
g_draw_world();
g_init_graph();
for(i=1;i<121;i++)
{
init_flags();
act_lives();
increase_age();
increase_frsh();
gabage_col();
make_foods();
calc_population(&n1,&n2);
g_plot_population(i,n1,n2,n1old,n2old);
n1old=n1;n2old=n2;
g_disp_genotype();
}
setcolor(9);
disp_hz16("回车键结束",10,430,20);
getch();
}
java jgap实例
package demo;
import java.io.File;
import java.io.FileNotFoundException;
import org.jgap.Chromosome;
import org.jgap.Configuration;
import org.jgap.FitnessFunction;
import org.jgap.Gene;
import org.jgap.Genotype;
import org.jgap.IChromosome;
import org.jgap.UnsupportedRepresentationException;
import org.jgap.data.DataTreeBuilder;
import org.jgap.data.IDataCreators;
import org.jgap.impl.DefaultConfiguration;
import org.jgap.impl.IntegerGene;
import org.jgap.xml.XMLDocumentBuilder;
import org.jgap.xml.XMLManager;
import org.w3c.dom.Document;
import examples.MinimizingMakeChangeFitnessFunction;
public class GaDemo
{
public static void main(String[] args) throws Exception
{
//构型
Configuration conf = new DefaultConfiguration();
// Care that the fittest individual of the current population is
// always taken to the next generation.
// Consider: With that, the pop. size may exceed its original
// size by one sometimes!
// -------------------------------------------------------------
conf.setPreservFittestIndividual(true);
// Set the fitness function we want to use, which is our
// MinimizingMakeChangeFitnessFunction. We construct it with
// the target amount of change passed in to this method.
// ---------------------------------------------------------
FitnessFunction myFunc = new GaDemoFitnessFunction();
conf.setFitnessFunction(myFunc);
Gene[] sampleGenes = new Gene[2];
sampleGenes[0] = new IntegerGene(conf,0,9999999);
sampleGenes[1] = new IntegerGene(conf,0,9999999);
IChromosome sampleChromosome = new Chromosome(conf, sampleGenes);
conf.setSampleChromosome(sampleChromosome);
conf.setPopulationSize(80);
Genotype population;
try
{
Document doc = XMLManager.readFile(new File("GADEMO.xml"));
population = XMLManager.getGenotypeFromDocument(conf, doc);
}
catch (UnsupportedRepresentationException uex)
{
// JGAP codebase might have changed between two consecutive runs.
// --------------------------------------------------------------
population = Genotype.randomInitialGenotype(conf);
}
catch (FileNotFoundException fex)
{
population = Genotype.randomInitialGenotype(conf);
}
// Evolve the population. Since we don't know what the best answer
// is going to be, we just evolve the max number of times.
// ---------------------------------------------------------------
long startTime = System.currentTimeMillis();
for (int i = 0; i < 50; i++)
{
population.evolve();
}
long endTime = System.currentTimeMillis();
System.out.println("Total evolution time: " + (endTime - startTime) + " ms");
IChromosome bestSolutionSoFar = population.getFittestChromosome();
System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 0));
System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 1));
DataTreeBuilder builder = DataTreeBuilder.getInstance();
IDataCreators doc2 = builder.representGenotypeAsDocument(population);
// create XML document from generated tree
XMLDocumentBuilder docbuilder = new XMLDocumentBuilder();
Document xmlDoc = (Document) docbuilder.buildDocument(doc2);
XMLManager.writeFile(xmlDoc, new File("GADEMO.xml"));
}
}
package demo;
import org.jgap.FitnessFunction;
import org.jgap.IChromosome;
public class GaDemoFitnessFunction extends FitnessFunction
{
private static final long serialVersionUID = 1L;
@Override
protected double evaluate(IChromosome a_subject)
{
int totalCoins = 1;
int numberOfGenes = a_subject.size();
for (int i = 0; i < numberOfGenes; i++)
{
totalCoins += (Integer) a_subject.getGene(i).getAllele();
}
return totalCoins;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -