File size: 2,692 Bytes
c574d3a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
import java.util.ArrayList;
import java.util.Random;
public class GA {
public static ArrayList<ArrayList<Integer>> crossover(Individual a, Individual b, int[][] imgArray){
ArrayList<ArrayList<Integer>> newRoots = new ArrayList<>();
for (int i = 0; i < a.getSegments().size(); i++) {
ArrayList<Integer> currRootCoords = new ArrayList<>();
//Calculate average coords
int newX = (a.getSegments().get(i).getRootNode().getX() + b.getSegments().get(i).getRootNode().getX() ) / 2;
int newY = (a.getSegments().get(i).getRootNode().getY() + b.getSegments().get(i).getRootNode().getY() ) / 2;
currRootCoords.add(newX);
currRootCoords.add(newY);
newRoots.add(currRootCoords);
}
return newRoots;
}
public static Individual tournamentSelection(Individual a, Individual b){
if (a.getRank() == b.getRank()){
return a.getCrowdingDistance() > b.getCrowdingDistance() ? a : b;
} else {
return a.getRank() > b.getRank() ? a: b;
}
}
public static ArrayList<ArrayList<ArrayList<Integer>>> mutate(ArrayList<ArrayList<ArrayList<Integer>>> children, int[][] imgArray){
Random r = new Random();
for (int i = 0; i < children.size(); i++) {
for (int j = 0; j < children.get(i).size(); j++) {
if(r.nextDouble() < 0.8){
int newX = r.nextInt(imgArray[0].length);
int newY = r.nextInt(imgArray.length);
children.get(i).get(j).set(0, newY);
children.get(i).get(j).set(1, newX);
}
}
}
return children;
}
public static ArrayList<ArrayList<ArrayList<Integer>>> doGA(int[][] imgArray, Population parentPopulation, int numIndividuals){
ArrayList<Individual> parents = parentPopulation.getIndividuals();
ArrayList<ArrayList<ArrayList<Integer>>> children = new ArrayList<>();
for (int i = 0; i < numIndividuals * 3; i++) {
Random r = new Random();
//TODO: Ensure that we cannot get the same two individuals
Individual crossover_individual_a = GA.tournamentSelection(parents.get(r.nextInt(parents.size())), parents.get(r.nextInt(parents.size())));
Individual crossover_individual_b = GA.tournamentSelection(parents.get(r.nextInt(parents.size())), parents.get(r.nextInt(parents.size())));
children.add((GA.crossover(crossover_individual_a, crossover_individual_b, imgArray)));
}
children = mutate(children, imgArray);
return children;
}
}
|