MultivariateFunctionMappingAdapter.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      https://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */
  21. package org.hipparchus.optim.nonlinear.scalar;

  22. import org.hipparchus.analysis.MultivariateFunction;
  23. import org.hipparchus.analysis.UnivariateFunction;
  24. import org.hipparchus.analysis.function.Logit;
  25. import org.hipparchus.analysis.function.Sigmoid;
  26. import org.hipparchus.exception.LocalizedCoreFormats;
  27. import org.hipparchus.exception.MathIllegalArgumentException;
  28. import org.hipparchus.util.FastMath;
  29. import org.hipparchus.util.MathUtils;

  30. /**
  31.  * <p>Adapter for mapping bounded {@link MultivariateFunction} to unbounded ones.</p>
  32.  *
  33.  * <p>
  34.  * This adapter can be used to wrap functions subject to simple bounds on
  35.  * parameters so they can be used by optimizers that do <em>not</em> directly
  36.  * support simple bounds.
  37.  * </p>
  38.  * <p>
  39.  * The principle is that the user function that will be wrapped will see its
  40.  * parameters bounded as required, i.e when its {@code value} method is called
  41.  * with argument array {@code point}, the elements array will fulfill requirement
  42.  * {@code lower[i] <= point[i] <= upper[i]} for all i. Some of the components
  43.  * may be unbounded or bounded only on one side if the corresponding bound is
  44.  * set to an infinite value. The optimizer will not manage the user function by
  45.  * itself, but it will handle this adapter and it is this adapter that will take
  46.  * care the bounds are fulfilled. The adapter {@link #value(double[])} method will
  47.  * be called by the optimizer with unbound parameters, and the adapter will map
  48.  * the unbounded value to the bounded range using appropriate functions like
  49.  * {@link Sigmoid} for double bounded elements for example.
  50.  * </p>
  51.  * <p>
  52.  * As the optimizer sees only unbounded parameters, it should be noted that the
  53.  * start point or simplex expected by the optimizer should be unbounded, so the
  54.  * user is responsible for converting his bounded point to unbounded by calling
  55.  * {@link #boundedToUnbounded(double[])} before providing them to the optimizer.
  56.  * For the same reason, the point returned by the {@link
  57.  * org.hipparchus.optim.BaseMultivariateOptimizer#optimize(org.hipparchus.optim.OptimizationData[])}
  58.  * method is unbounded. So to convert this point to bounded, users must call
  59.  * {@link #unboundedToBounded(double[])} by themselves!</p>
  60.  * <p>
  61.  * This adapter is only a poor man solution to simple bounds optimization constraints
  62.  * that can be used with simple optimizers like
  63.  * {@link org.hipparchus.optim.nonlinear.scalar.noderiv.SimplexOptimizer
  64.  * SimplexOptimizer}.
  65.  * A better solution is to use an optimizer that directly supports simple bounds like
  66.  * {@link org.hipparchus.optim.nonlinear.scalar.noderiv.CMAESOptimizer
  67.  * CMAESOptimizer} or
  68.  * {@link org.hipparchus.optim.nonlinear.scalar.noderiv.BOBYQAOptimizer
  69.  * BOBYQAOptimizer}.
  70.  * One caveat of this poor-man's solution is that behavior near the bounds may be
  71.  * numerically unstable as bounds are mapped from infinite values.
  72.  * Another caveat is that convergence values are evaluated by the optimizer with
  73.  * respect to unbounded variables, so there will be scales differences when
  74.  * converted to bounded variables.
  75.  * </p>
  76.  *
  77.  * @see MultivariateFunctionPenaltyAdapter
  78.  *
  79.  */
  80. public class MultivariateFunctionMappingAdapter
  81.     implements MultivariateFunction {
  82.     /** Underlying bounded function. */
  83.     private final MultivariateFunction bounded;
  84.     /** Mapping functions. */
  85.     private final Mapper[] mappers;

  86.     /** Simple constructor.
  87.      * @param bounded bounded function
  88.      * @param lower lower bounds for each element of the input parameters array
  89.      * (some elements may be set to {@code Double.NEGATIVE_INFINITY} for
  90.      * unbounded values)
  91.      * @param upper upper bounds for each element of the input parameters array
  92.      * (some elements may be set to {@code Double.POSITIVE_INFINITY} for
  93.      * unbounded values)
  94.      * @exception MathIllegalArgumentException if lower and upper bounds are not
  95.      * consistent, either according to dimension or to values
  96.      */
  97.     public MultivariateFunctionMappingAdapter(final MultivariateFunction bounded,
  98.                                               final double[] lower, final double[] upper) {
  99.         // safety checks
  100.         MathUtils.checkNotNull(lower);
  101.         MathUtils.checkNotNull(upper);
  102.         if (lower.length != upper.length) {
  103.             throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
  104.                                                    lower.length, upper.length);
  105.         }
  106.         for (int i = 0; i < lower.length; ++i) {
  107.             if (!(upper[i] >= lower[i])) { // NOPMD - the test is written this way so it also fails for NaN
  108.                 throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_SMALL,
  109.                                                        upper[i], lower[i]);
  110.             }
  111.         }

  112.         this.bounded = bounded;
  113.         this.mappers = new Mapper[lower.length];
  114.         for (int i = 0; i < mappers.length; ++i) {
  115.             if (Double.isInfinite(lower[i])) {
  116.                 if (Double.isInfinite(upper[i])) {
  117.                     // element is unbounded, no transformation is needed
  118.                     mappers[i] = new NoBoundsMapper();
  119.                 } else {
  120.                     // element is simple-bounded on the upper side
  121.                     mappers[i] = new UpperBoundMapper(upper[i]);
  122.                 }
  123.             } else {
  124.                 if (Double.isInfinite(upper[i])) {
  125.                     // element is simple-bounded on the lower side
  126.                     mappers[i] = new LowerBoundMapper(lower[i]);
  127.                 } else {
  128.                     // element is double-bounded
  129.                     mappers[i] = new LowerUpperBoundMapper(lower[i], upper[i]);
  130.                 }
  131.             }
  132.         }
  133.     }

  134.     /**
  135.      * Maps an array from unbounded to bounded.
  136.      *
  137.      * @param point Unbounded values.
  138.      * @return the bounded values.
  139.      */
  140.     public double[] unboundedToBounded(double[] point) {
  141.         // Map unbounded input point to bounded point.
  142.         final double[] mapped = new double[mappers.length];
  143.         for (int i = 0; i < mappers.length; ++i) {
  144.             mapped[i] = mappers[i].unboundedToBounded(point[i]);
  145.         }

  146.         return mapped;
  147.     }

  148.     /**
  149.      * Maps an array from bounded to unbounded.
  150.      *
  151.      * @param point Bounded values.
  152.      * @return the unbounded values.
  153.      */
  154.     public double[] boundedToUnbounded(double[] point) {
  155.         // Map bounded input point to unbounded point.
  156.         final double[] mapped = new double[mappers.length];
  157.         for (int i = 0; i < mappers.length; ++i) {
  158.             mapped[i] = mappers[i].boundedToUnbounded(point[i]);
  159.         }

  160.         return mapped;
  161.     }

  162.     /**
  163.      * Compute the underlying function value from an unbounded point.
  164.      * <p>
  165.      * This method simply bounds the unbounded point using the mappings
  166.      * set up at construction and calls the underlying function using
  167.      * the bounded point.
  168.      * </p>
  169.      * @param point unbounded value
  170.      * @return underlying function value
  171.      * @see #unboundedToBounded(double[])
  172.      */
  173.     @Override
  174.     public double value(double[] point) {
  175.         return bounded.value(unboundedToBounded(point));
  176.     }

  177.     /** Mapping interface. */
  178.     private interface Mapper {
  179.         /**
  180.          * Maps a value from unbounded to bounded.
  181.          *
  182.          * @param y Unbounded value.
  183.          * @return the bounded value.
  184.          */
  185.         double unboundedToBounded(double y);

  186.         /**
  187.          * Maps a value from bounded to unbounded.
  188.          *
  189.          * @param x Bounded value.
  190.          * @return the unbounded value.
  191.          */
  192.         double boundedToUnbounded(double x);
  193.     }

  194.     /** Local class for no bounds mapping. */
  195.     private static class NoBoundsMapper implements Mapper {
  196.         /** {@inheritDoc} */
  197.         @Override
  198.         public double unboundedToBounded(final double y) {
  199.             return y;
  200.         }

  201.         /** {@inheritDoc} */
  202.         @Override
  203.         public double boundedToUnbounded(final double x) {
  204.             return x;
  205.         }
  206.     }

  207.     /** Local class for lower bounds mapping. */
  208.     private static class LowerBoundMapper implements Mapper {
  209.         /** Low bound. */
  210.         private final double lower;

  211.         /**
  212.          * Simple constructor.
  213.          *
  214.          * @param lower lower bound
  215.          */
  216.         LowerBoundMapper(final double lower) {
  217.             this.lower = lower;
  218.         }

  219.         /** {@inheritDoc} */
  220.         @Override
  221.         public double unboundedToBounded(final double y) {
  222.             return lower + FastMath.exp(y);
  223.         }

  224.         /** {@inheritDoc} */
  225.         @Override
  226.         public double boundedToUnbounded(final double x) {
  227.             return FastMath.log(x - lower);
  228.         }

  229.     }

  230.     /** Local class for upper bounds mapping. */
  231.     private static class UpperBoundMapper implements Mapper {

  232.         /** Upper bound. */
  233.         private final double upper;

  234.         /** Simple constructor.
  235.          * @param upper upper bound
  236.          */
  237.         UpperBoundMapper(final double upper) {
  238.             this.upper = upper;
  239.         }

  240.         /** {@inheritDoc} */
  241.         @Override
  242.         public double unboundedToBounded(final double y) {
  243.             return upper - FastMath.exp(-y);
  244.         }

  245.         /** {@inheritDoc} */
  246.         @Override
  247.         public double boundedToUnbounded(final double x) {
  248.             return -FastMath.log(upper - x);
  249.         }

  250.     }

  251.     /** Local class for lower and bounds mapping. */
  252.     private static class LowerUpperBoundMapper implements Mapper {
  253.         /** Function from unbounded to bounded. */
  254.         private final UnivariateFunction boundingFunction;
  255.         /** Function from bounded to unbounded. */
  256.         private final UnivariateFunction unboundingFunction;

  257.         /**
  258.          * Simple constructor.
  259.          *
  260.          * @param lower lower bound
  261.          * @param upper upper bound
  262.          */
  263.         LowerUpperBoundMapper(final double lower, final double upper) {
  264.             boundingFunction   = new Sigmoid(lower, upper);
  265.             unboundingFunction = new Logit(lower, upper);
  266.         }

  267.         /** {@inheritDoc} */
  268.         @Override
  269.         public double unboundedToBounded(final double y) {
  270.             return boundingFunction.value(y);
  271.         }

  272.         /** {@inheritDoc} */
  273.         @Override
  274.         public double boundedToUnbounded(final double x) {
  275.             return unboundingFunction.value(x);
  276.         }
  277.     }
  278. }