1 | package cecj.archive; |
---|
2 | |
---|
3 | import java.util.List; |
---|
4 | |
---|
5 | import ec.EvolutionState; |
---|
6 | import ec.Individual; |
---|
7 | import ec.SelectionMethod; |
---|
8 | import ec.select.SelectDefaults; |
---|
9 | import ec.util.Parameter; |
---|
10 | |
---|
11 | public class ArchiveRandomSelection extends SelectionMethod { |
---|
12 | |
---|
13 | /** default base */ |
---|
14 | private static final String P_ARCHIVAL_RANDOM = "archival-random"; |
---|
15 | |
---|
16 | private static final String P_SIZE = "size"; |
---|
17 | private static final int ENTIRE_ARCHIVE = -1; |
---|
18 | |
---|
19 | private int size; |
---|
20 | |
---|
21 | public Parameter defaultBase() { |
---|
22 | return SelectDefaults.base().push(P_ARCHIVAL_RANDOM); |
---|
23 | } |
---|
24 | |
---|
25 | @Override |
---|
26 | public void setup(EvolutionState state, Parameter base) { |
---|
27 | super.setup(state, base); |
---|
28 | |
---|
29 | Parameter sizeParam = base.push(P_SIZE); |
---|
30 | size = state.parameters.getIntWithDefault(sizeParam, null, ENTIRE_ARCHIVE); |
---|
31 | } |
---|
32 | |
---|
33 | @Override |
---|
34 | public int produce(int subpopulation, EvolutionState state, int thread) { |
---|
35 | throw new UnsupportedOperationException( |
---|
36 | "Archival selection methods do not support supopulation index-based produce method."); |
---|
37 | } |
---|
38 | |
---|
39 | @Override |
---|
40 | public int produce(int min, int max, int start, int subpop, Individual[] inds, |
---|
41 | EvolutionState state, int thread) { |
---|
42 | int n = 1; |
---|
43 | if (n > max) |
---|
44 | n = max; |
---|
45 | if (n < min) |
---|
46 | n = min; |
---|
47 | |
---|
48 | List<Individual> archive = ((ArchivingSubpopulation) state.population.subpops[subpop]) |
---|
49 | .getArchivalIndividuals(); |
---|
50 | List<Individual> popInds = ((ArchivingSubpopulation) state.population.subpops[subpop]) |
---|
51 | .getIndividuals(); |
---|
52 | |
---|
53 | if (!archive.isEmpty()) { |
---|
54 | for (int q = 0; q < n; q++) { |
---|
55 | int selected; |
---|
56 | if (size <= 0) { |
---|
57 | selected = state.random[thread].nextInt(archive.size()); |
---|
58 | } else { |
---|
59 | selected = archive.size() - state.random[thread].nextInt(size) - 1; |
---|
60 | selected = Math.max(selected, 0); |
---|
61 | } |
---|
62 | inds[start + q] = archive.get(selected); |
---|
63 | } |
---|
64 | } else { |
---|
65 | for (int q = 0; q < n; q++) { |
---|
66 | inds[start + q] = popInds.get(state.random[thread].nextInt(popInds.size())); |
---|
67 | } |
---|
68 | } |
---|
69 | |
---|
70 | return n; |
---|
71 | } |
---|
72 | } |
---|