[44] | 1 | package cecj.fitness; |
---|
| 2 | |
---|
| 3 | import java.util.Arrays; |
---|
| 4 | import java.util.List; |
---|
| 5 | |
---|
| 6 | import cecj.interaction.InteractionResult; |
---|
| 7 | |
---|
| 8 | import ec.EvolutionState; |
---|
| 9 | import ec.Individual; |
---|
| 10 | import ec.simple.SimpleFitness; |
---|
| 11 | |
---|
| 12 | public class CompetitiveFitnessSharing implements FitnessAggregateMethod { |
---|
| 13 | |
---|
| 14 | private float[] fitnesses; |
---|
| 15 | |
---|
| 16 | public void prepareToAggregate(EvolutionState state, int subpop) { |
---|
| 17 | fitnesses = new float[state.population.subpops[subpop].individuals.length]; |
---|
| 18 | Arrays.fill(fitnesses, 0.0f); |
---|
| 19 | } |
---|
| 20 | |
---|
| 21 | public void addToAggregate(EvolutionState state, int subpop, |
---|
| 22 | List<List<InteractionResult>> results, int weight) { |
---|
| 23 | |
---|
| 24 | Individual[] inds = state.population.subpops[subpop].individuals; |
---|
| 25 | if (results.size() != inds.length) { |
---|
| 26 | throw new IllegalArgumentException( |
---|
| 27 | "Results list's size must be equal to subpopulation size."); |
---|
| 28 | } |
---|
| 29 | |
---|
| 30 | int numOpponents = results.get(0).size(); |
---|
| 31 | float[] opponentSum = new float[numOpponents]; |
---|
| 32 | for (int opponent = 0; opponent < numOpponents; opponent++) { |
---|
| 33 | for (int ind = 0; ind < inds.length; ind++) { |
---|
| 34 | opponentSum[opponent] += results.get(ind).get(opponent).getNumericValue(); |
---|
| 35 | } |
---|
| 36 | } |
---|
| 37 | |
---|
| 38 | for (int ind = 0; ind < inds.length; ind++) { |
---|
| 39 | float indFitness = 0; |
---|
| 40 | for (int opponent = 0; opponent < numOpponents; opponent++) { |
---|
| 41 | if (opponentSum[opponent] == 0) { |
---|
| 42 | continue; |
---|
| 43 | } |
---|
| 44 | |
---|
| 45 | indFitness += results.get(ind).get(opponent).getNumericValue() |
---|
| 46 | / opponentSum[opponent]; |
---|
| 47 | } |
---|
| 48 | |
---|
| 49 | fitnesses[ind] += indFitness * weight; |
---|
| 50 | ((SimpleFitness) (inds[ind].fitness)).setFitness(state, indFitness, false); |
---|
| 51 | } |
---|
| 52 | } |
---|
| 53 | |
---|
| 54 | public void assignFitness(EvolutionState state, int subpop) { |
---|
| 55 | Individual[] inds = state.population.subpops[subpop].individuals; |
---|
| 56 | for (int ind = 0; ind < inds.length; ind++) { |
---|
| 57 | ((SimpleFitness) inds[ind].fitness).setFitness(state, fitnesses[ind], false); |
---|
| 58 | } |
---|
| 59 | } |
---|
| 60 | } |
---|