我目前正在使用p5.js库进行爬山遗传算法程序。
该程序使用遗传算法格式重新创建您想要的任何图像。它与this program类似,我在youtube上发现了一个视频。
我有一个Gene类,除其他外,还有一个名为'graphic'的属性,一旦创建了基因,它就被设置为等于一个新的p5.graphic对象。
还有一个Population类,它有一个名为'genes'的属性,它是一个包含10个Gene对象的数组。 Population类的方法getHealthiest()返回基因数组中的Gene,该数组的图形看起来最像目标图像。此外,在Population类中,有一个evolve()方法。
这是我的问题出现的地方。在evolve()方法中,我想1.确定最健康的基因,并且2.除了最健康的基因之外清空基因阵列,并用其他9种基因重新填充,这些基因是最健康基因的变异。为此,我需要将新Genes的图形属性设置为最健康的Gene的图形属性。
this.evolve = function() {
var healthiestGene = this.getHealthiest(); //sets a variable equal to the healthiest gene
this.genes = []; //clearing out the genes array of the population
for (var i=0; i < this.populationSize; i++) {
this.genes[i] = new Gene(this.target); //creating a new Gene object
//This is the problem area
this.genes[i].graphic.loadPixels();
for (var j=0; j < healthiestGene.numPixels; j++){
this.genes[i].graphic.pixels[j] = healthiestGene.graphic.pixels[j];
}
this.genes[i].graphic.updatePixels();
if (i!=0) {
this.genes[i].mutate(); //I mutate every Gene in the array but one
}
this.genes[i].evaluateFitness();
}
}
目前,我通过设置两个像素阵列逐个像素地彼此相等来做到这一点,但我想知道是否有更有效的方法来做到这一点。我试着简单地写:
this.genes[i].graphic.pixels = healthiestGene.graphic.pixels;
但那没有做任何事情。我很乐意任何建议我如何设置这两个像素阵列彼此相等,而不必逐个像素地通过它们。
谢谢!
您可能不希望仅将新实例设置为等于旧实例,因为您对子实例所做的任何更改也会影响父实例。相反,您可能想要制作副本。
您可以创建一个新的图形实例,然后将旧实例绘制到新实例。像这样的东西:
var pg2 = createGraphics(pg.width, pg.height);
pg2.image(pg, 0, 0);
在这一点上,pg2
将包含pg
最初拥有的任何东西。