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