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 */
033public class TournamentSelection implements SelectionPolicy {
034
035    /** number of chromosomes included in the tournament selections */
036    private int arity;
037
038    /**
039     * Creates a new TournamentSelection instance.
040     *
041     * @param arity how many chromosomes will be drawn to the tournament
042     */
043    public TournamentSelection(final int arity) {
044        this.arity = arity;
045    }
046
047    /**
048     * Select two chromosomes from the population. Each of the two selected
049     * chromosomes is selected based on n-ary tournament -- this is done by
050     * drawing {@link #arity} random chromosomes without replacement from the
051     * population, and then selecting the fittest chromosome among them.
052     *
053     * @param population the population from which the chromosomes are chosen.
054     * @return the selected chromosomes.
055     * @throws MathIllegalArgumentException if the tournament arity is bigger than the population size
056     */
057    public ChromosomePair select(final Population population) throws MathIllegalArgumentException {
058        return new ChromosomePair(tournament((ListPopulation) population),
059                                  tournament((ListPopulation) population));
060    }
061
062    /**
063     * Helper for {@link #select(Population)}. Draw {@link #arity} random chromosomes without replacement from the
064     * population, and then select the fittest chromosome among them.
065     *
066     * @param population the population from which the chromosomes are chosen.
067     * @return the selected chromosome.
068     * @throws MathIllegalArgumentException if the tournament arity is bigger than the population size
069     */
070    private Chromosome tournament(final ListPopulation population) throws MathIllegalArgumentException {
071        if (population.getPopulationSize() < this.arity) {
072            throw new MathIllegalArgumentException(LocalizedFormats.TOO_LARGE_TOURNAMENT_ARITY,
073                                                   arity, population.getPopulationSize());
074        }
075        // auxiliary population
076        ListPopulation tournamentPopulation = new ListPopulation(this.arity) {
077            /** {@inheritDoc} */
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}