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