001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math3.genetics;
018
019import java.util.ArrayList;
020import java.util.List;
021
022import org.apache.commons.math3.exception.MathIllegalArgumentException;
023import org.apache.commons.math3.exception.util.LocalizedFormats;
024
025/**
026 * Tournament selection scheme. Each of the two selected chromosomes is selected
027 * based on n-ary tournament -- this is done by drawing {@link #arity} random
028 * chromosomes without replacement from the population, and then selecting the
029 * fittest chromosome among them.
030 *
031 * @since 2.0
032 * @version $Id: TournamentSelection.java 1416643 2012-12-03 19:37:14Z tn $
033 */
034public class TournamentSelection implements SelectionPolicy {
035
036    /** number of chromosomes included in the tournament selections */
037    private int arity;
038
039    /**
040     * Creates a new TournamentSelection instance.
041     *
042     * @param arity how many chromosomes will be drawn to the tournament
043     */
044    public TournamentSelection(final int arity) {
045        this.arity = arity;
046    }
047
048    /**
049     * Select two chromosomes from the population. Each of the two selected
050     * chromosomes is selected based on n-ary tournament -- this is done by
051     * drawing {@link #arity} random chromosomes without replacement from the
052     * population, and then selecting the fittest chromosome among them.
053     *
054     * @param population the population from which the chromosomes are chosen.
055     * @return the selected chromosomes.
056     * @throws MathIllegalArgumentException if the tournament arity is bigger than the population size
057     */
058    public ChromosomePair select(final Population population) throws MathIllegalArgumentException {
059        return new ChromosomePair(tournament((ListPopulation) population),
060                                  tournament((ListPopulation) population));
061    }
062
063    /**
064     * Helper for {@link #select(Population)}. Draw {@link #arity} random chromosomes without replacement from the
065     * population, and then select the fittest chromosome among them.
066     *
067     * @param population the population from which the chromosomes are choosen.
068     * @return the selected chromosome.
069     * @throws MathIllegalArgumentException if the tournament arity is bigger than the population size
070     */
071    private Chromosome tournament(final ListPopulation population) throws MathIllegalArgumentException {
072        if (population.getPopulationSize() < this.arity) {
073            throw new MathIllegalArgumentException(LocalizedFormats.TOO_LARGE_TOURNAMENT_ARITY,
074                                                   arity, population.getPopulationSize());
075        }
076        // auxiliary population
077        ListPopulation tournamentPopulation = new ListPopulation(this.arity) {
078            public Population nextGeneration() {
079                // not useful here
080                return null;
081            }
082        };
083
084        // create a copy of the chromosome list
085        List<Chromosome> chromosomes = new ArrayList<Chromosome> (population.getChromosomes());
086        for (int i=0; i<this.arity; i++) {
087            // select a random individual and add it to the tournament
088            int rind = GeneticAlgorithm.getRandomGenerator().nextInt(chromosomes.size());
089            tournamentPopulation.addChromosome(chromosomes.get(rind));
090            // do not select it again
091            chromosomes.remove(rind);
092        }
093        // the winner takes it all
094        return tournamentPopulation.getFittestChromosome();
095    }
096
097    /**
098     * Gets the arity (number of chromosomes drawn to the tournament).
099     *
100     * @return arity of the tournament
101     */
102    public int getArity() {
103        return arity;
104    }
105
106    /**
107     * Sets the arity (number of chromosomes drawn to the tournament).
108     *
109     * @param arity arity of the tournament
110     */
111    public void setArity(final int arity) {
112        this.arity = arity;
113    }
114
115}