1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.math4.legacy.genetics;
18
19 import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException;
20
21 /**
22 * Stops after a fixed number of generations.
23 * <p>
24 * Each time {@link #isSatisfied(Population)} is invoked, a generation counter
25 * is incremented. Once the counter reaches the configured
26 * {@code maxGenerations} value, {@link #isSatisfied(Population)} returns true.
27 *
28 * @since 2.0
29 */
30 public class FixedGenerationCount implements StoppingCondition {
31 /** Number of generations that have passed. */
32 private int numGenerations;
33
34 /** Maximum number of generations (stopping criteria). */
35 private final int maxGenerations;
36
37 /**
38 * Create a new FixedGenerationCount instance.
39 *
40 * @param maxGenerations number of generations to evolve
41 * @throws NumberIsTooSmallException if the number of generations is < 1
42 */
43 public FixedGenerationCount(final int maxGenerations) throws NumberIsTooSmallException {
44 if (maxGenerations <= 0) {
45 throw new NumberIsTooSmallException(maxGenerations, 1, true);
46 }
47 this.maxGenerations = maxGenerations;
48 }
49
50 /**
51 * Determine whether or not the given number of generations have passed. Increments the number of generations
52 * counter if the maximum has not been reached.
53 *
54 * @param population ignored (no impact on result)
55 * @return <code>true</code> IFF the maximum number of generations has been exceeded
56 */
57 @Override
58 public boolean isSatisfied(final Population population) {
59 if (this.numGenerations < this.maxGenerations) {
60 numGenerations++;
61 return false;
62 }
63 return true;
64 }
65
66 /**
67 * Returns the number of generations that have already passed.
68 * @return the number of generations that have passed
69 */
70 public int getNumGenerations() {
71 return numGenerations;
72 }
73 }