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 */
017package org.apache.commons.math3.optim.nonlinear.scalar;
018
019import org.apache.commons.math3.analysis.MultivariateFunction;
020import org.apache.commons.math3.analysis.UnivariateFunction;
021import org.apache.commons.math3.analysis.function.Logit;
022import org.apache.commons.math3.analysis.function.Sigmoid;
023import org.apache.commons.math3.exception.DimensionMismatchException;
024import org.apache.commons.math3.exception.NumberIsTooSmallException;
025import org.apache.commons.math3.util.FastMath;
026import org.apache.commons.math3.util.MathUtils;
027
028/**
029 * <p>Adapter for mapping bounded {@link MultivariateFunction} to unbounded ones.</p>
030 *
031 * <p>
032 * This adapter can be used to wrap functions subject to simple bounds on
033 * parameters so they can be used by optimizers that do <em>not</em> directly
034 * support simple bounds.
035 * </p>
036 * <p>
037 * The principle is that the user function that will be wrapped will see its
038 * parameters bounded as required, i.e when its {@code value} method is called
039 * with argument array {@code point}, the elements array will fulfill requirement
040 * {@code lower[i] <= point[i] <= upper[i]} for all i. Some of the components
041 * may be unbounded or bounded only on one side if the corresponding bound is
042 * set to an infinite value. The optimizer will not manage the user function by
043 * itself, but it will handle this adapter and it is this adapter that will take
044 * care the bounds are fulfilled. The adapter {@link #value(double[])} method will
045 * be called by the optimizer with unbound parameters, and the adapter will map
046 * the unbounded value to the bounded range using appropriate functions like
047 * {@link Sigmoid} for double bounded elements for example.
048 * </p>
049 * <p>
050 * As the optimizer sees only unbounded parameters, it should be noted that the
051 * start point or simplex expected by the optimizer should be unbounded, so the
052 * user is responsible for converting his bounded point to unbounded by calling
053 * {@link #boundedToUnbounded(double[])} before providing them to the optimizer.
054 * For the same reason, the point returned by the {@link
055 * org.apache.commons.math3.optimization.BaseMultivariateOptimizer#optimize(int,
056 * MultivariateFunction, org.apache.commons.math3.optimization.GoalType, double[])}
057 * method is unbounded. So to convert this point to bounded, users must call
058 * {@link #unboundedToBounded(double[])} by themselves!</p>
059 * <p>
060 * This adapter is only a poor man solution to simple bounds optimization constraints
061 * that can be used with simple optimizers like
062 * {@link org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer
063 * SimplexOptimizer}.
064 * A better solution is to use an optimizer that directly supports simple bounds like
065 * {@link org.apache.commons.math3.optim.nonlinear.scalar.noderiv.CMAESOptimizer
066 * CMAESOptimizer} or
067 * {@link org.apache.commons.math3.optim.nonlinear.scalar.noderiv.BOBYQAOptimizer
068 * BOBYQAOptimizer}.
069 * One caveat of this poor-man's solution is that behavior near the bounds may be
070 * numerically unstable as bounds are mapped from infinite values.
071 * Another caveat is that convergence values are evaluated by the optimizer with
072 * respect to unbounded variables, so there will be scales differences when
073 * converted to bounded variables.
074 * </p>
075 *
076 * @see MultivariateFunctionPenaltyAdapter
077 *
078 * @since 3.0
079 */
080public class MultivariateFunctionMappingAdapter
081    implements MultivariateFunction {
082    /** Underlying bounded function. */
083    private final MultivariateFunction bounded;
084    /** Mapping functions. */
085    private final Mapper[] mappers;
086
087    /** Simple constructor.
088     * @param bounded bounded function
089     * @param lower lower bounds for each element of the input parameters array
090     * (some elements may be set to {@code Double.NEGATIVE_INFINITY} for
091     * unbounded values)
092     * @param upper upper bounds for each element of the input parameters array
093     * (some elements may be set to {@code Double.POSITIVE_INFINITY} for
094     * unbounded values)
095     * @exception DimensionMismatchException if lower and upper bounds are not
096     * consistent, either according to dimension or to values
097     */
098    public MultivariateFunctionMappingAdapter(final MultivariateFunction bounded,
099                                              final double[] lower, final double[] upper) {
100        // safety checks
101        MathUtils.checkNotNull(lower);
102        MathUtils.checkNotNull(upper);
103        if (lower.length != upper.length) {
104            throw new DimensionMismatchException(lower.length, upper.length);
105        }
106        for (int i = 0; i < lower.length; ++i) {
107            // note the following test is written in such a way it also fails for NaN
108            if (!(upper[i] >= lower[i])) {
109                throw new NumberIsTooSmallException(upper[i], lower[i], true);
110            }
111        }
112
113        this.bounded = bounded;
114        this.mappers = new Mapper[lower.length];
115        for (int i = 0; i < mappers.length; ++i) {
116            if (Double.isInfinite(lower[i])) {
117                if (Double.isInfinite(upper[i])) {
118                    // element is unbounded, no transformation is needed
119                    mappers[i] = new NoBoundsMapper();
120                } else {
121                    // element is simple-bounded on the upper side
122                    mappers[i] = new UpperBoundMapper(upper[i]);
123                }
124            } else {
125                if (Double.isInfinite(upper[i])) {
126                    // element is simple-bounded on the lower side
127                    mappers[i] = new LowerBoundMapper(lower[i]);
128                } else {
129                    // element is double-bounded
130                    mappers[i] = new LowerUpperBoundMapper(lower[i], upper[i]);
131                }
132            }
133        }
134    }
135
136    /**
137     * Maps an array from unbounded to bounded.
138     *
139     * @param point Unbounded values.
140     * @return the bounded values.
141     */
142    public double[] unboundedToBounded(double[] point) {
143        // Map unbounded input point to bounded point.
144        final double[] mapped = new double[mappers.length];
145        for (int i = 0; i < mappers.length; ++i) {
146            mapped[i] = mappers[i].unboundedToBounded(point[i]);
147        }
148
149        return mapped;
150    }
151
152    /**
153     * Maps an array from bounded to unbounded.
154     *
155     * @param point Bounded values.
156     * @return the unbounded values.
157     */
158    public double[] boundedToUnbounded(double[] point) {
159        // Map bounded input point to unbounded point.
160        final double[] mapped = new double[mappers.length];
161        for (int i = 0; i < mappers.length; ++i) {
162            mapped[i] = mappers[i].boundedToUnbounded(point[i]);
163        }
164
165        return mapped;
166    }
167
168    /**
169     * Compute the underlying function value from an unbounded point.
170     * <p>
171     * This method simply bounds the unbounded point using the mappings
172     * set up at construction and calls the underlying function using
173     * the bounded point.
174     * </p>
175     * @param point unbounded value
176     * @return underlying function value
177     * @see #unboundedToBounded(double[])
178     */
179    public double value(double[] point) {
180        return bounded.value(unboundedToBounded(point));
181    }
182
183    /** Mapping interface. */
184    private interface Mapper {
185        /**
186         * Maps a value from unbounded to bounded.
187         *
188         * @param y Unbounded value.
189         * @return the bounded value.
190         */
191        double unboundedToBounded(double y);
192
193        /**
194         * Maps a value from bounded to unbounded.
195         *
196         * @param x Bounded value.
197         * @return the unbounded value.
198         */
199        double boundedToUnbounded(double x);
200    }
201
202    /** Local class for no bounds mapping. */
203    private static class NoBoundsMapper implements Mapper {
204        /** {@inheritDoc} */
205        public double unboundedToBounded(final double y) {
206            return y;
207        }
208
209        /** {@inheritDoc} */
210        public double boundedToUnbounded(final double x) {
211            return x;
212        }
213    }
214
215    /** Local class for lower bounds mapping. */
216    private static class LowerBoundMapper implements Mapper {
217        /** Low bound. */
218        private final double lower;
219
220        /**
221         * Simple constructor.
222         *
223         * @param lower lower bound
224         */
225        LowerBoundMapper(final double lower) {
226            this.lower = lower;
227        }
228
229        /** {@inheritDoc} */
230        public double unboundedToBounded(final double y) {
231            return lower + FastMath.exp(y);
232        }
233
234        /** {@inheritDoc} */
235        public double boundedToUnbounded(final double x) {
236            return FastMath.log(x - lower);
237        }
238
239    }
240
241    /** Local class for upper bounds mapping. */
242    private static class UpperBoundMapper implements Mapper {
243
244        /** Upper bound. */
245        private final double upper;
246
247        /** Simple constructor.
248         * @param upper upper bound
249         */
250        UpperBoundMapper(final double upper) {
251            this.upper = upper;
252        }
253
254        /** {@inheritDoc} */
255        public double unboundedToBounded(final double y) {
256            return upper - FastMath.exp(-y);
257        }
258
259        /** {@inheritDoc} */
260        public double boundedToUnbounded(final double x) {
261            return -FastMath.log(upper - x);
262        }
263
264    }
265
266    /** Local class for lower and bounds mapping. */
267    private static class LowerUpperBoundMapper implements Mapper {
268        /** Function from unbounded to bounded. */
269        private final UnivariateFunction boundingFunction;
270        /** Function from bounded to unbounded. */
271        private final UnivariateFunction unboundingFunction;
272
273        /**
274         * Simple constructor.
275         *
276         * @param lower lower bound
277         * @param upper upper bound
278         */
279        LowerUpperBoundMapper(final double lower, final double upper) {
280            boundingFunction   = new Sigmoid(lower, upper);
281            unboundingFunction = new Logit(lower, upper);
282        }
283
284        /** {@inheritDoc} */
285        public double unboundedToBounded(final double y) {
286            return boundingFunction.value(y);
287        }
288
289        /** {@inheritDoc} */
290        public double boundedToUnbounded(final double x) {
291            return unboundingFunction.value(x);
292        }
293    }
294}