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 java.util.concurrent.TimeUnit; 20 21 import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException; 22 23 /** 24 * Stops after a fixed amount of time has elapsed. 25 * <p> 26 * The first time {@link #isSatisfied(Population)} is invoked, the end time of 27 * the evolution is determined based on the provided <code>maxTime</code> value. 28 * Once the elapsed time reaches the configured <code>maxTime</code> value, 29 * {@link #isSatisfied(Population)} returns true. 30 * 31 * @since 3.1 32 */ 33 public class FixedElapsedTime implements StoppingCondition { 34 /** Maximum allowed time period (in nanoseconds). */ 35 private final long maxTimePeriod; 36 37 /** The predetermined termination time (stopping condition). */ 38 private long endTime = -1; 39 40 /** 41 * Create a new {@link FixedElapsedTime} instance. 42 * 43 * @param maxTime maximum number of seconds generations are allowed to evolve 44 * @throws NumberIsTooSmallException if the provided time is < 0 45 */ 46 public FixedElapsedTime(final long maxTime) throws NumberIsTooSmallException { 47 this(maxTime, TimeUnit.SECONDS); 48 } 49 50 /** 51 * Create a new {@link FixedElapsedTime} instance. 52 * 53 * @param maxTime maximum time generations are allowed to evolve 54 * @param unit {@link TimeUnit} of the maxTime argument 55 * @throws NumberIsTooSmallException if the provided time is < 0 56 */ 57 public FixedElapsedTime(final long maxTime, final TimeUnit unit) throws NumberIsTooSmallException { 58 if (maxTime < 0) { 59 throw new NumberIsTooSmallException(maxTime, 0, true); 60 } 61 maxTimePeriod = unit.toNanos(maxTime); 62 } 63 64 /** 65 * Determine whether or not the maximum allowed time has passed. 66 * The termination time is determined after the first generation. 67 * 68 * @param population ignored (no impact on result) 69 * @return <code>true</code> IFF the maximum allowed time period has elapsed 70 */ 71 @Override 72 public boolean isSatisfied(final Population population) { 73 if (endTime < 0) { 74 endTime = System.nanoTime() + maxTimePeriod; 75 } 76 77 return System.nanoTime() >= endTime; 78 } 79 }