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.math4.legacy.genetics;
018
019import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException;
020
021/**
022 * Stops after a fixed number of generations.
023 * <p>
024 * Each time {@link #isSatisfied(Population)} is invoked, a generation counter
025 * is incremented. Once the counter reaches the configured
026 * {@code maxGenerations} value, {@link #isSatisfied(Population)} returns true.
027 *
028 * @since 2.0
029 */
030public class FixedGenerationCount implements StoppingCondition {
031    /** Number of generations that have passed. */
032    private int numGenerations;
033
034    /** Maximum number of generations (stopping criteria). */
035    private final int maxGenerations;
036
037    /**
038     * Create a new FixedGenerationCount instance.
039     *
040     * @param maxGenerations number of generations to evolve
041     * @throws NumberIsTooSmallException if the number of generations is &lt; 1
042     */
043    public FixedGenerationCount(final int maxGenerations) throws NumberIsTooSmallException {
044        if (maxGenerations <= 0) {
045            throw new NumberIsTooSmallException(maxGenerations, 1, true);
046        }
047        this.maxGenerations = maxGenerations;
048    }
049
050    /**
051     * Determine whether or not the given number of generations have passed. Increments the number of generations
052     * counter if the maximum has not been reached.
053     *
054     * @param population ignored (no impact on result)
055     * @return <code>true</code> IFF the maximum number of generations has been exceeded
056     */
057    @Override
058    public boolean isSatisfied(final Population population) {
059        if (this.numGenerations < this.maxGenerations) {
060            numGenerations++;
061            return false;
062        }
063        return true;
064    }
065
066    /**
067     * Returns the number of generations that have already passed.
068     * @return the number of generations that have passed
069     */
070    public int getNumGenerations() {
071        return numGenerations;
072    }
073}