blob: d99c64e41b8e80fae2ff7500671fa4b0d7d26400 (
plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
package jcgp.backend.population;
import java.util.Arrays;
import java.util.Collections;
import jcgp.backend.resources.Resources;
public class Population {
private final Chromosome[] chromosomes;
private final Resources resources;
/**
* Initialise a random population according to the parameters specified
* in the resources.
*
* @param resources the CGP resources
*/
public Population(Resources resources) {
this.resources = resources;
chromosomes = new Chromosome[resources.populationSize()];
for (int c = 0; c < chromosomes.length; c++) {
chromosomes[c] = new Chromosome(resources);
}
}
/**
* Initialise a population of copies of the given chromosome.
*
* @param parent
* @param resources
*/
public Population(Chromosome parent, Resources resources) {
this.resources = resources;
chromosomes = new Chromosome[resources.populationSize()];
for (int c = 0; c < chromosomes.length; c++) {
chromosomes[c] = new Chromosome(parent);
}
}
/**
* Returns the indexed chromosome.
*
* @param index
* @return
*/
public Chromosome getChromosome(int index) {
return chromosomes[index];
}
/**
* @return a random chromosome from this population.
*/
public Chromosome getRandomChromosome() {
return chromosomes[resources.getRandomInt(chromosomes.length)];
}
/**
* Copy a chromosome into a different position.
* After this returns, the target chromosome has
* identical connections and functions to the source
* one, though they are separate instances.
*
* This method does nothing if source == target.
*
* @param source
* @param target
*/
public void copyChromosome(int source, int target) {
if (source != target) {
chromosomes[target].copyGenes(chromosomes[source]);
}
}
public void reinitialise() {
for (int c = 0; c < chromosomes.length; c++) {
chromosomes[c].reinitialiseConnections();
}
}
public Chromosome getFittest() {
return chromosomes[chromosomes.length - 1];
}
public int getFittestIndex() {
return chromosomes.length - 1;
}
/**
* Sort the population into ascending order of fitness.
*/
public void sortAscending() {
Arrays.sort(chromosomes);
}
/**
* Sort the population into descending order of fitness.
*/
public void sortDescending() {
Arrays.sort(chromosomes, Collections.reverseOrder());
}
}
|