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     */
017    
018    package org.apache.commons.math3.optim;
019    
020    import org.apache.commons.math3.util.FastMath;
021    import org.apache.commons.math3.exception.NotStrictlyPositiveException;
022    
023    /**
024     * Simple implementation of the {@link ConvergenceChecker} interface using
025     * only objective function values.
026     *
027     * Convergence is considered to have been reached if either the relative
028     * difference between the objective function values is smaller than a
029     * threshold or if either the absolute difference between the objective
030     * function values is smaller than another threshold.
031     * <br/>
032     * The {@link #converged(int,PointValuePair,PointValuePair) converged}
033     * method will also return {@code true} if the number of iterations has been set
034     * (see {@link #SimpleValueChecker(double,double,int) this constructor}).
035     *
036     * @version $Id: SimpleValueChecker.java 1416643 2012-12-03 19:37:14Z tn $
037     * @since 3.0
038     */
039    public class SimpleValueChecker
040        extends AbstractConvergenceChecker<PointValuePair> {
041        /**
042         * If {@link #maxIterationCount} is set to this value, the number of
043         * iterations will never cause
044         * {@link #converged(int,PointValuePair,PointValuePair)}
045         * to return {@code true}.
046         */
047        private static final int ITERATION_CHECK_DISABLED = -1;
048        /**
049         * Number of iterations after which the
050         * {@link #converged(int,PointValuePair,PointValuePair)} method
051         * will return true (unless the check is disabled).
052         */
053        private final int maxIterationCount;
054    
055        /** Build an instance with specified thresholds.
056         *
057         * In order to perform only relative checks, the absolute tolerance
058         * must be set to a negative value. In order to perform only absolute
059         * checks, the relative tolerance must be set to a negative value.
060         *
061         * @param relativeThreshold relative tolerance threshold
062         * @param absoluteThreshold absolute tolerance threshold
063         */
064        public SimpleValueChecker(final double relativeThreshold,
065                                  final double absoluteThreshold) {
066            super(relativeThreshold, absoluteThreshold);
067            maxIterationCount = ITERATION_CHECK_DISABLED;
068        }
069    
070        /**
071         * Builds an instance with specified thresholds.
072         *
073         * In order to perform only relative checks, the absolute tolerance
074         * must be set to a negative value. In order to perform only absolute
075         * checks, the relative tolerance must be set to a negative value.
076         *
077         * @param relativeThreshold relative tolerance threshold
078         * @param absoluteThreshold absolute tolerance threshold
079         * @param maxIter Maximum iteration count.
080         * @throws NotStrictlyPositiveException if {@code maxIter <= 0}.
081         *
082         * @since 3.1
083         */
084        public SimpleValueChecker(final double relativeThreshold,
085                                  final double absoluteThreshold,
086                                  final int maxIter) {
087            super(relativeThreshold, absoluteThreshold);
088    
089            if (maxIter <= 0) {
090                throw new NotStrictlyPositiveException(maxIter);
091            }
092            maxIterationCount = maxIter;
093        }
094    
095        /**
096         * Check if the optimization algorithm has converged considering the
097         * last two points.
098         * This method may be called several time from the same algorithm
099         * iteration with different points. This can be detected by checking the
100         * iteration number at each call if needed. Each time this method is
101         * called, the previous and current point correspond to points with the
102         * same role at each iteration, so they can be compared. As an example,
103         * simplex-based algorithms call this method for all points of the simplex,
104         * not only for the best or worst ones.
105         *
106         * @param iteration Index of current iteration
107         * @param previous Best point in the previous iteration.
108         * @param current Best point in the current iteration.
109         * @return {@code true} if the algorithm has converged.
110         */
111        @Override
112        public boolean converged(final int iteration,
113                                 final PointValuePair previous,
114                                 final PointValuePair current) {
115            if (maxIterationCount != ITERATION_CHECK_DISABLED) {
116                if (iteration >= maxIterationCount) {
117                    return true;
118                }
119            }
120    
121            final double p = previous.getValue();
122            final double c = current.getValue();
123            final double difference = FastMath.abs(p - c);
124            final double size = FastMath.max(FastMath.abs(p), FastMath.abs(c));
125            return difference <= size * getRelativeThreshold() ||
126                difference <= getAbsoluteThreshold();
127        }
128    }