123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- package algorithms.geneticAlgorithm.Components.Selections;
- import java.util.ArrayList;
- import java.util.Random;
- import algorithms.geneticAlgorithm.Components.GAIndividual;
- import algorithms.geneticAlgorithm.Components.GASelectionStrategy;
- public class TournamentSelectionStrategy<I extends GAIndividual> implements GASelectionStrategy<I> {
- public class Range{
-
- public double min;
- public double max;
- public Range(double min, double max){
- this.min = min;
- this.max = max;
- }
- }
-
- private ArrayList<I> currentPop;
- public int tournamentSize;
- private Random rng;
- private ArrayList<Range> tournamentWheel;
- public ArrayList<I> competitors;
- public double selectProb;
- private double maxRange;
-
-
- public TournamentSelectionStrategy(){
- currentPop = new ArrayList<I>();
- tournamentSize = 1;
- rng = new Random();
- selectProb = 1;
- }
-
- public TournamentSelectionStrategy(int tSize, double selectProb){
- currentPop = new ArrayList<I>();
- rng = new Random();
- tournamentSize = tSize;
- this.selectProb = selectProb;
- }
-
- @Override
- public void setCurrentPopulation(ArrayList<I> population) {
- currentPop = population;
- }
-
- public void setTournamentSize(int size){
- tournamentSize = size;
- }
- @Override
- public ArrayList<I> selectIndividuals() {
- ArrayList<I> parents = new ArrayList<I>();
- parents.add(selectSingleIndividual());
- parents.add(selectSingleIndividual());
- return parents;
- }
-
- public I selectSingleIndividual(){
- tournamentSelection();
- initWheel();
- double index = rng.nextDouble() * maxRange;
- for(int i = 0; i < tournamentWheel.size(); i++){
- if(index >= tournamentWheel.get(i).min && index <= tournamentWheel.get(i).max){
- return competitors.get(i);
- }
- }
- return competitors.get(rng.nextInt(competitors.size()));
- }
-
- public void tournamentSelection(){
- competitors = new ArrayList<I>();
- for(int i = 0; i < tournamentSize; i++){
- I candidate = chooseCandidate();
- int size = competitors.size();
- for(int j = 0; j <= size; j++){
- if(j != size){
- if(competitors.get(j).getFittness() < candidate.getFittness()){
- competitors.add(j, candidate);
- break;
- }
- }else{
- competitors.add(candidate);
- }
- }
- }
- }
-
- public I chooseCandidate(){
- int index = rng.nextInt(currentPop.size());
- I candidate = currentPop.get(index);
- return candidate;
- }
-
- public void initWheel(){
- tournamentWheel = new ArrayList<Range>();
- int power = 0;
- maxRange = 0;
- for(int i = 0; i < tournamentSize; i++){
- double currentProb = selectProb * Math.pow((1- selectProb), power);
- Range range = new Range(maxRange, maxRange + currentProb);
- tournamentWheel.add(range);
- maxRange += currentProb;
- power++;
- }
- }
- }
|