Reputation: 23
I'm currently working on a hill climb genetic algorithm program using the p5.js library.
The program uses the genetic algorithm format to recreate any image you want. It works similar to this program that I found a video of on youtube.
I have a Gene class that, among other things, has an attribute called 'graphic' that is set equal to a new p5.graphic object once the gene is created.
There is also a Population class that has an attribute called 'genes' which is an array of 10 Gene objects. The Population class's method getHealthiest() returns the Gene in the genes array that's graphic looks most like the target image. Also, in the Population class, there is a evolve() method.
Here is where my problem arises. Within the evolve() method, I want to 1. determine the healthiest gene and 2. empty out the genes array except for the healthiest gene, and refill it with 9 other genes that are variations of the healthiest gene. To do so, I need to set the graphic attribute of the new Genes equal to that of the healthiest 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();
}
}
Currently, I do this by setting the two pixel arrays equal to each other pixel by pixel, but I wonder if there is a more efficient way to do so. I tried simply writng:
this.genes[i].graphic.pixels = healthiestGene.graphic.pixels;
but that didn't do anything. I would love any suggesting for how I may set these two pixel arrays equal to each other without having to go through them pixel by pixel.
Thanks!
Upvotes: 2
Views: 560
Reputation: 42174
You probably don't want to set the new instance equal to the old instance, because then any changes you make to the child will affect the parent as well. Instead, you probably want to make a copy.
You could create a new graphics instance, then draw the old instance to the new one. Something like this:
var pg2 = createGraphics(pg.width, pg.height);
pg2.image(pg, 0, 0);
At this point, pg2
will contain whatever pg
originally had.
Upvotes: 2