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.nonlinear.scalar;
018    
019    import org.apache.commons.math3.analysis.MultivariateFunction;
020    import org.apache.commons.math3.analysis.UnivariateFunction;
021    import org.apache.commons.math3.analysis.function.Logit;
022    import org.apache.commons.math3.analysis.function.Sigmoid;
023    import org.apache.commons.math3.exception.DimensionMismatchException;
024    import org.apache.commons.math3.exception.NumberIsTooSmallException;
025    import org.apache.commons.math3.util.FastMath;
026    import 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     * @version $Id: MultivariateFunctionMappingAdapter.java 1416643 2012-12-03 19:37:14Z tn $
079     * @since 3.0
080     */
081    public class MultivariateFunctionMappingAdapter
082        implements MultivariateFunction {
083        /** Underlying bounded function. */
084        private final MultivariateFunction bounded;
085        /** Mapping functions. */
086        private final Mapper[] mappers;
087    
088        /** Simple constructor.
089         * @param bounded bounded function
090         * @param lower lower bounds for each element of the input parameters array
091         * (some elements may be set to {@code Double.NEGATIVE_INFINITY} for
092         * unbounded values)
093         * @param upper upper bounds for each element of the input parameters array
094         * (some elements may be set to {@code Double.POSITIVE_INFINITY} for
095         * unbounded values)
096         * @exception DimensionMismatchException if lower and upper bounds are not
097         * consistent, either according to dimension or to values
098         */
099        public MultivariateFunctionMappingAdapter(final MultivariateFunction bounded,
100                                                  final double[] lower, final double[] upper) {
101            // safety checks
102            MathUtils.checkNotNull(lower);
103            MathUtils.checkNotNull(upper);
104            if (lower.length != upper.length) {
105                throw new DimensionMismatchException(lower.length, upper.length);
106            }
107            for (int i = 0; i < lower.length; ++i) {
108                // note the following test is written in such a way it also fails for NaN
109                if (!(upper[i] >= lower[i])) {
110                    throw new NumberIsTooSmallException(upper[i], lower[i], true);
111                }
112            }
113    
114            this.bounded = bounded;
115            this.mappers = new Mapper[lower.length];
116            for (int i = 0; i < mappers.length; ++i) {
117                if (Double.isInfinite(lower[i])) {
118                    if (Double.isInfinite(upper[i])) {
119                        // element is unbounded, no transformation is needed
120                        mappers[i] = new NoBoundsMapper();
121                    } else {
122                        // element is simple-bounded on the upper side
123                        mappers[i] = new UpperBoundMapper(upper[i]);
124                    }
125                } else {
126                    if (Double.isInfinite(upper[i])) {
127                        // element is simple-bounded on the lower side
128                        mappers[i] = new LowerBoundMapper(lower[i]);
129                    } else {
130                        // element is double-bounded
131                        mappers[i] = new LowerUpperBoundMapper(lower[i], upper[i]);
132                    }
133                }
134            }
135        }
136    
137        /**
138         * Maps an array from unbounded to bounded.
139         *
140         * @param point Unbounded values.
141         * @return the bounded values.
142         */
143        public double[] unboundedToBounded(double[] point) {
144            // Map unbounded input point to bounded point.
145            final double[] mapped = new double[mappers.length];
146            for (int i = 0; i < mappers.length; ++i) {
147                mapped[i] = mappers[i].unboundedToBounded(point[i]);
148            }
149    
150            return mapped;
151        }
152    
153        /**
154         * Maps an array from bounded to unbounded.
155         *
156         * @param point Bounded values.
157         * @return the unbounded values.
158         */
159        public double[] boundedToUnbounded(double[] point) {
160            // Map bounded input point to unbounded point.
161            final double[] mapped = new double[mappers.length];
162            for (int i = 0; i < mappers.length; ++i) {
163                mapped[i] = mappers[i].boundedToUnbounded(point[i]);
164            }
165    
166            return mapped;
167        }
168    
169        /**
170         * Compute the underlying function value from an unbounded point.
171         * <p>
172         * This method simply bounds the unbounded point using the mappings
173         * set up at construction and calls the underlying function using
174         * the bounded point.
175         * </p>
176         * @param point unbounded value
177         * @return underlying function value
178         * @see #unboundedToBounded(double[])
179         */
180        public double value(double[] point) {
181            return bounded.value(unboundedToBounded(point));
182        }
183    
184        /** Mapping interface. */
185        private interface Mapper {
186            /**
187             * Maps a value from unbounded to bounded.
188             *
189             * @param y Unbounded value.
190             * @return the bounded value.
191             */
192            double unboundedToBounded(double y);
193    
194            /**
195             * Maps a value from bounded to unbounded.
196             *
197             * @param x Bounded value.
198             * @return the unbounded value.
199             */
200            double boundedToUnbounded(double x);
201        }
202    
203        /** Local class for no bounds mapping. */
204        private static class NoBoundsMapper implements Mapper {
205            /** {@inheritDoc} */
206            public double unboundedToBounded(final double y) {
207                return y;
208            }
209    
210            /** {@inheritDoc} */
211            public double boundedToUnbounded(final double x) {
212                return x;
213            }
214        }
215    
216        /** Local class for lower bounds mapping. */
217        private static class LowerBoundMapper implements Mapper {
218            /** Low bound. */
219            private final double lower;
220    
221            /**
222             * Simple constructor.
223             *
224             * @param lower lower bound
225             */
226            public LowerBoundMapper(final double lower) {
227                this.lower = lower;
228            }
229    
230            /** {@inheritDoc} */
231            public double unboundedToBounded(final double y) {
232                return lower + FastMath.exp(y);
233            }
234    
235            /** {@inheritDoc} */
236            public double boundedToUnbounded(final double x) {
237                return FastMath.log(x - lower);
238            }
239    
240        }
241    
242        /** Local class for upper bounds mapping. */
243        private static class UpperBoundMapper implements Mapper {
244    
245            /** Upper bound. */
246            private final double upper;
247    
248            /** Simple constructor.
249             * @param upper upper bound
250             */
251            public UpperBoundMapper(final double upper) {
252                this.upper = upper;
253            }
254    
255            /** {@inheritDoc} */
256            public double unboundedToBounded(final double y) {
257                return upper - FastMath.exp(-y);
258            }
259    
260            /** {@inheritDoc} */
261            public double boundedToUnbounded(final double x) {
262                return -FastMath.log(upper - x);
263            }
264    
265        }
266    
267        /** Local class for lower and bounds mapping. */
268        private static class LowerUpperBoundMapper implements Mapper {
269            /** Function from unbounded to bounded. */
270            private final UnivariateFunction boundingFunction;
271            /** Function from bounded to unbounded. */
272            private final UnivariateFunction unboundingFunction;
273    
274            /**
275             * Simple constructor.
276             *
277             * @param lower lower bound
278             * @param upper upper bound
279             */
280            public LowerUpperBoundMapper(final double lower, final double upper) {
281                boundingFunction   = new Sigmoid(lower, upper);
282                unboundingFunction = new Logit(lower, upper);
283            }
284    
285            /** {@inheritDoc} */
286            public double unboundedToBounded(final double y) {
287                return boundingFunction.value(y);
288            }
289    
290            /** {@inheritDoc} */
291            public double boundedToUnbounded(final double x) {
292                return unboundingFunction.value(x);
293            }
294        }
295    }