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.Collections;
020import java.util.List;
021
022import org.apache.commons.math3.exception.NotPositiveException;
023import org.apache.commons.math3.exception.NullArgumentException;
024import org.apache.commons.math3.exception.NumberIsTooLargeException;
025import org.apache.commons.math3.exception.OutOfRangeException;
026import org.apache.commons.math3.exception.util.LocalizedFormats;
027import org.apache.commons.math3.util.FastMath;
028
029/**
030 * Population of chromosomes which uses elitism (certain percentage of the best
031 * chromosomes is directly copied to the next generation).
032 *
033 * @since 2.0
034 */
035public class ElitisticListPopulation extends ListPopulation {
036
037    /** percentage of chromosomes copied to the next generation */
038    private double elitismRate = 0.9;
039
040    /**
041     * Creates a new {@link ElitisticListPopulation} instance.
042     *
043     * @param chromosomes list of chromosomes in the population
044     * @param populationLimit maximal size of the population
045     * @param elitismRate how many best chromosomes will be directly transferred to the next generation [in %]
046     * @throws NullArgumentException if the list of chromosomes is {@code null}
047     * @throws NotPositiveException if the population limit is not a positive number (< 1)
048     * @throws NumberIsTooLargeException if the list of chromosomes exceeds the population limit
049     * @throws OutOfRangeException if the elitism rate is outside the [0, 1] range
050     */
051    public ElitisticListPopulation(final List<Chromosome> chromosomes, final int populationLimit,
052                                   final double elitismRate)
053        throws NullArgumentException, NotPositiveException, NumberIsTooLargeException, OutOfRangeException {
054
055        super(chromosomes, populationLimit);
056        setElitismRate(elitismRate);
057    }
058
059    /**
060     * Creates a new {@link ElitisticListPopulation} instance and initializes its inner chromosome list.
061     *
062     * @param populationLimit maximal size of the population
063     * @param elitismRate how many best chromosomes will be directly transferred to the next generation [in %]
064     * @throws NotPositiveException if the population limit is not a positive number (&lt; 1)
065     * @throws OutOfRangeException if the elitism rate is outside the [0, 1] range
066     */
067    public ElitisticListPopulation(final int populationLimit, final double elitismRate)
068        throws NotPositiveException, OutOfRangeException {
069
070        super(populationLimit);
071        setElitismRate(elitismRate);
072    }
073
074    /**
075     * Start the population for the next generation. The <code>{@link #elitismRate}</code>
076     * percents of the best chromosomes are directly copied to the next generation.
077     *
078     * @return the beginnings of the next generation.
079     */
080    public Population nextGeneration() {
081        // initialize a new generation with the same parameters
082        ElitisticListPopulation nextGeneration =
083                new ElitisticListPopulation(getPopulationLimit(), getElitismRate());
084
085        final List<Chromosome> oldChromosomes = getChromosomeList();
086        Collections.sort(oldChromosomes);
087
088        // index of the last "not good enough" chromosome
089        int boundIndex = (int) FastMath.ceil((1.0 - getElitismRate()) * oldChromosomes.size());
090        for (int i = boundIndex; i < oldChromosomes.size(); i++) {
091            nextGeneration.addChromosome(oldChromosomes.get(i));
092        }
093        return nextGeneration;
094    }
095
096    /**
097     * Sets the elitism rate, i.e. how many best chromosomes will be directly transferred to the next generation [in %].
098     *
099     * @param elitismRate how many best chromosomes will be directly transferred to the next generation [in %]
100     * @throws OutOfRangeException if the elitism rate is outside the [0, 1] range
101     */
102    public void setElitismRate(final double elitismRate) throws OutOfRangeException {
103        if (elitismRate < 0 || elitismRate > 1) {
104            throw new OutOfRangeException(LocalizedFormats.ELITISM_RATE, elitismRate, 0, 1);
105        }
106        this.elitismRate = elitismRate;
107    }
108
109    /**
110     * Access the elitism rate.
111     * @return the elitism rate
112     */
113    public double getElitismRate() {
114        return this.elitismRate;
115    }
116
117}