Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Fitness function
- public long getFitness() {
- long fitness = getLength();
- return fitness;
- }
- // Selection method
- public void selection(Network[] population, Network[] newGeneration) {
- long eFitness = 0;
- for(int i = 0; i < population.length; i++) {
- eFitness += population[i].getFitness();
- }
- for(int i = 0; i < Info.POPULATION; i++) {
- Network child = Network.breed(getByRoulette(eFitness, population), getByRoulette(eFitness, population));
- newGeneration[i] = child;
- }
- }
- // Roulette method
- public Network getByRoulette(long eFitness, Network[] population) {
- long rand = (long) (rnd.nextDouble() * eFitness);
- long runningSum = 0;
- for(int i = 0; i < population.length; i++) {
- runningSum += population[i].getFitness();
- if(runningSum > rand) {
- return population[i];
- }
- }
- return null;
- }
- // new generation method
- private Network[] newGeneration(int species, Network[] population) {
- Network[] newGeneration = new Network[Info.POPULATION];
- // Average the total fitnesses
- for(int i = 0; i < Info.POPULATION; i++) {
- population[i].setFitness(population[i].getFitness() / Info.REPLAY_NETWORKS);
- }
- Arrays.sort(population, Maths.SORT_FITNESS);
- if(population[0].getFitness() > mech.highestFitnessEver) {
- mech.highestFitnessEver = population[0].getFitness();
- }
- totalFitnessOfBest[species] += population[0].getFitness();
- selection(population, newGeneration);
- if(Info.GENERATION % Info.GRAPH_SCALE == 0) {
- mech.averageFitnessOfBest[species] = totalFitnessOfBest[species] / Info.GRAPH_SCALE;
- if(mech.averageFitnessOfBest[species] > highestAverageFitness) {
- highestAverageFitness = mech.averageFitnessOfBest[species];
- }
- totalFitnessOfBest[species] = 0;
- mech.addScore(species, (long) mech.averageFitnessOfBest[species]);
- }
- if(Info.GENERATION % 5 == 0) {
- try {
- population[0].save(saveFile, false, Info.GENERATION, (int) mech.averageFitnessOfBest[species], species);
- }
- catch(IOException e) {
- e.printStackTrace();
- }
- }
- return newGeneration;
- }
Advertisement
Add Comment
Please, Sign In to add comment