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