[28] | 1 | package cecj.archive; |
---|
| 2 | |
---|
| 3 | import java.util.List; |
---|
| 4 | |
---|
| 5 | import ec.EvolutionState; |
---|
| 6 | import ec.Individual; |
---|
| 7 | import ec.util.Parameter; |
---|
| 8 | |
---|
| 9 | public class BestOfGenerationArchive extends CoevolutionaryArchive { |
---|
| 10 | |
---|
| 11 | private static final int UNBOUNDED_ARCHIVE_SIZE = -1; |
---|
| 12 | |
---|
| 13 | private static final String P_ARCHIVE_SIZE = "size"; |
---|
| 14 | private static final String P_SUBPOP = "subpop"; |
---|
| 15 | |
---|
| 16 | private int[] archiveSize; |
---|
| 17 | private int[] currentArchivePosition; |
---|
| 18 | |
---|
| 19 | @Override |
---|
| 20 | public void setup(EvolutionState state, Parameter base) { |
---|
| 21 | super.setup(state, base); |
---|
| 22 | |
---|
| 23 | currentArchivePosition = new int[numSubpopulations]; |
---|
| 24 | archiveSize = new int[numSubpopulations]; |
---|
| 25 | |
---|
| 26 | for (int subpop = 0; subpop < numSubpopulations; subpop++) { |
---|
| 27 | Parameter archiveSizeParameter = base.push(P_SUBPOP).push("" + subpop) |
---|
| 28 | .push(P_ARCHIVE_SIZE); |
---|
| 29 | archiveSize[subpop] = state.parameters.getIntWithDefault(archiveSizeParameter, null, |
---|
| 30 | UNBOUNDED_ARCHIVE_SIZE); |
---|
| 31 | if (archiveSize[subpop] <= 0 && archiveSize[subpop] != UNBOUNDED_ARCHIVE_SIZE) { |
---|
| 32 | state.output.fatal("Archive size must be > 0.\n", archiveSizeParameter); |
---|
| 33 | } |
---|
| 34 | } |
---|
| 35 | } |
---|
| 36 | |
---|
| 37 | public void submit(EvolutionState state) { |
---|
| 38 | for (int subpop = 0; subpop < numSubpopulations; subpop++) { |
---|
| 39 | Individual bestOfGeneration = findBestIndividual(getIndividuals(state, subpop)); |
---|
| 40 | List<Individual> archive = getArchive(state, subpop); |
---|
| 41 | |
---|
| 42 | if ((archiveSize[subpop] == UNBOUNDED_ARCHIVE_SIZE) |
---|
| 43 | || (archive.size() < archiveSize[subpop])) { |
---|
| 44 | archive.add(bestOfGeneration); |
---|
| 45 | } else { |
---|
| 46 | archive.set(currentArchivePosition[subpop], bestOfGeneration); |
---|
| 47 | currentArchivePosition[subpop]++; |
---|
| 48 | currentArchivePosition[subpop] %= archiveSize[subpop]; |
---|
| 49 | } |
---|
| 50 | } |
---|
| 51 | } |
---|
| 52 | |
---|
| 53 | private Individual findBestIndividual(List<Individual> inds) { |
---|
| 54 | Individual result = inds.get(0); |
---|
| 55 | for (Individual ind : inds) { |
---|
| 56 | if (ind.fitness.betterThan(result.fitness)) { |
---|
| 57 | result = ind; |
---|
| 58 | } |
---|
| 59 | } |
---|
| 60 | return result; |
---|
| 61 | } |
---|
| 62 | } |
---|