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.  *      http://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. package org.apache.commons.math4.legacy.optim.nonlinear.scalar;

  18. import org.apache.commons.math4.legacy.analysis.MultivariateFunction;
  19. import org.apache.commons.math4.legacy.analysis.UnivariateFunction;
  20. import org.apache.commons.math4.legacy.analysis.function.Logit;
  21. import org.apache.commons.math4.legacy.analysis.function.Sigmoid;
  22. import org.apache.commons.math4.legacy.exception.NullArgumentException;
  23. import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
  24. import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException;
  25. import org.apache.commons.math4.core.jdkmath.JdkMath;

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

  84.     /** Simple constructor.
  85.      * @param bounded bounded function
  86.      * @param lower lower bounds for each element of the input parameters array
  87.      * (some elements may be set to {@code Double.NEGATIVE_INFINITY} for
  88.      * unbounded values)
  89.      * @param upper upper bounds for each element of the input parameters array
  90.      * (some elements may be set to {@code Double.POSITIVE_INFINITY} for
  91.      * unbounded values)
  92.      * @exception DimensionMismatchException if lower and upper bounds are not
  93.      * consistent, either according to dimension or to values
  94.      */
  95.     public MultivariateFunctionMappingAdapter(final MultivariateFunction bounded,
  96.                                               final double[] lower, final double[] upper) {
  97.         // safety checks
  98.         NullArgumentException.check(lower);
  99.         NullArgumentException.check(upper);
  100.         if (lower.length != upper.length) {
  101.             throw new DimensionMismatchException(lower.length, upper.length);
  102.         }
  103.         for (int i = 0; i < lower.length; ++i) {
  104.             // note the following test is written in such a way it also fails for NaN
  105.             if (!(upper[i] >= lower[i])) {
  106.                 throw new NumberIsTooSmallException(upper[i], lower[i], true);
  107.             }
  108.         }

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

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

  143.         return mapped;
  144.     }

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

  157.         return mapped;
  158.     }

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

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

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

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

  198.         /** {@inheritDoc} */
  199.         @Override
  200.         public double boundedToUnbounded(final double x) {
  201.             return x;
  202.         }
  203.     }

  204.     /** Local class for lower bounds mapping. */
  205.     private static final class LowerBoundMapper implements Mapper {
  206.         /** Low bound. */
  207.         private final double lower;

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

  216.         /** {@inheritDoc} */
  217.         @Override
  218.         public double unboundedToBounded(final double y) {
  219.             return lower + JdkMath.exp(y);
  220.         }

  221.         /** {@inheritDoc} */
  222.         @Override
  223.         public double boundedToUnbounded(final double x) {
  224.             return JdkMath.log(x - lower);
  225.         }
  226.     }

  227.     /** Local class for upper bounds mapping. */
  228.     private static final class UpperBoundMapper implements Mapper {

  229.         /** Upper bound. */
  230.         private final double upper;

  231.         /** Simple constructor.
  232.          * @param upper upper bound
  233.          */
  234.         UpperBoundMapper(final double upper) {
  235.             this.upper = upper;
  236.         }

  237.         /** {@inheritDoc} */
  238.         @Override
  239.         public double unboundedToBounded(final double y) {
  240.             return upper - JdkMath.exp(-y);
  241.         }

  242.         /** {@inheritDoc} */
  243.         @Override
  244.         public double boundedToUnbounded(final double x) {
  245.             return -JdkMath.log(upper - x);
  246.         }
  247.     }

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

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

  264.         /** {@inheritDoc} */
  265.         @Override
  266.         public double unboundedToBounded(final double y) {
  267.             return boundingFunction.value(y);
  268.         }

  269.         /** {@inheritDoc} */
  270.         @Override
  271.         public double boundedToUnbounded(final double x) {
  272.             return unboundingFunction.value(x);
  273.         }
  274.     }
  275. }