MultivariateFunctionPenaltyAdapter.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.exception.NullArgumentException;
  20. import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
  21. import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException;
  22. import org.apache.commons.math4.core.jdkmath.JdkMath;

  23. /**
  24.  * <p>Adapter extending bounded {@link MultivariateFunction} to an unbouded
  25.  * domain using a penalty function.</p>
  26.  *
  27.  * <p>
  28.  * This adapter can be used to wrap functions subject to simple bounds on
  29.  * parameters so they can be used by optimizers that do <em>not</em> directly
  30.  * support simple bounds.
  31.  * </p>
  32.  * <p>
  33.  * The principle is that the user function that will be wrapped will see its
  34.  * parameters bounded as required, i.e when its {@code value} method is called
  35.  * with argument array {@code point}, the elements array will fulfill requirement
  36.  * {@code lower[i] <= point[i] <= upper[i]} for all i. Some of the components
  37.  * may be unbounded or bounded only on one side if the corresponding bound is
  38.  * set to an infinite value. The optimizer will not manage the user function by
  39.  * itself, but it will handle this adapter and it is this adapter that will take
  40.  * care the bounds are fulfilled. The adapter {@link #value(double[])} method will
  41.  * be called by the optimizer with unbound parameters, and the adapter will check
  42.  * if the parameters is within range or not. If it is in range, then the underlying
  43.  * user function will be called, and if it is not the value of a penalty function
  44.  * will be returned instead.
  45.  * </p>
  46.  * <p>
  47.  * This adapter is only a poor-man's solution to simple bounds optimization
  48.  * constraints that can be used with simple optimizers like
  49.  * {@link org.apache.commons.math4.legacy.optim.nonlinear.scalar.noderiv.SimplexOptimizer
  50.  * SimplexOptimizer}.
  51.  * A better solution is to use an optimizer that directly supports simple bounds like
  52.  * {@link org.apache.commons.math4.legacy.optim.nonlinear.scalar.noderiv.CMAESOptimizer
  53.  * CMAESOptimizer} or
  54.  * {@link org.apache.commons.math4.legacy.optim.nonlinear.scalar.noderiv.BOBYQAOptimizer
  55.  * BOBYQAOptimizer}.
  56.  * One caveat of this poor-man's solution is that if start point or start simplex
  57.  * is completely outside of the allowed range, only the penalty function is used,
  58.  * and the optimizer may converge without ever entering the range.
  59.  * </p>
  60.  *
  61.  * @see MultivariateFunctionMappingAdapter
  62.  *
  63.  * @since 3.0
  64.  */
  65. public class MultivariateFunctionPenaltyAdapter
  66.     implements MultivariateFunction {
  67.     /** Underlying bounded function. */
  68.     private final MultivariateFunction bounded;
  69.     /** Lower bounds. */
  70.     private final double[] lower;
  71.     /** Upper bounds. */
  72.     private final double[] upper;
  73.     /** Penalty offset. */
  74.     private final double offset;
  75.     /** Penalty scales. */
  76.     private final double[] scale;

  77.     /**
  78.      * Simple constructor.
  79.      * <p>
  80.      * When the optimizer provided points are out of range, the value of the
  81.      * penalty function will be used instead of the value of the underlying
  82.      * function. In order for this penalty to be effective in rejecting this
  83.      * point during the optimization process, the penalty function value should
  84.      * be defined with care. This value is computed as:
  85.      * <div style="white-space: pre"><code>
  86.      *   penalty(point) = offset + &sum;<sub>i</sub>[scale[i] * &radic;|point[i]-boundary[i]|]
  87.      * </code></div>
  88.      * where indices i correspond to all the components that violates their boundaries.
  89.      *
  90.      * <p>
  91.      * So when attempting a function minimization, offset should be larger than
  92.      * the maximum expected value of the underlying function and scale components
  93.      * should all be positive. When attempting a function maximization, offset
  94.      * should be lesser than the minimum expected value of the underlying function
  95.      * and scale components should all be negative.
  96.      * minimization, and lesser than the minimum expected value of the underlying
  97.      * function when attempting maximization.
  98.      * </p>
  99.      * <p>
  100.      * These choices for the penalty function have two properties. First, all out
  101.      * of range points will return a function value that is worse than the value
  102.      * returned by any in range point. Second, the penalty is worse for large
  103.      * boundaries violation than for small violations, so the optimizer has an hint
  104.      * about the direction in which it should search for acceptable points.
  105.      * </p>
  106.      * @param bounded bounded function
  107.      * @param lower lower bounds for each element of the input parameters array
  108.      * (some elements may be set to {@code Double.NEGATIVE_INFINITY} for
  109.      * unbounded values)
  110.      * @param upper upper bounds for each element of the input parameters array
  111.      * (some elements may be set to {@code Double.POSITIVE_INFINITY} for
  112.      * unbounded values)
  113.      * @param offset base offset of the penalty function
  114.      * @param scale scale of the penalty function
  115.      * @exception DimensionMismatchException if lower bounds, upper bounds and
  116.      * scales are not consistent, either according to dimension or to boundary
  117.      * values
  118.      */
  119.     public MultivariateFunctionPenaltyAdapter(final MultivariateFunction bounded,
  120.                                               final double[] lower, final double[] upper,
  121.                                               final double offset, final double[] scale) {

  122.         // safety checks
  123.         NullArgumentException.check(lower);
  124.         NullArgumentException.check(upper);
  125.         NullArgumentException.check(scale);
  126.         if (lower.length != upper.length) {
  127.             throw new DimensionMismatchException(lower.length, upper.length);
  128.         }
  129.         if (lower.length != scale.length) {
  130.             throw new DimensionMismatchException(lower.length, scale.length);
  131.         }
  132.         for (int i = 0; i < lower.length; ++i) {
  133.             // note the following test is written in such a way it also fails for NaN
  134.             if (!(upper[i] >= lower[i])) {
  135.                 throw new NumberIsTooSmallException(upper[i], lower[i], true);
  136.             }
  137.         }

  138.         this.bounded = bounded;
  139.         this.lower   = lower.clone();
  140.         this.upper   = upper.clone();
  141.         this.offset  = offset;
  142.         this.scale   = scale.clone();
  143.     }

  144.     /**
  145.      * Computes the underlying function value from an unbounded point.
  146.      * <p>
  147.      * This method simply returns the value of the underlying function
  148.      * if the unbounded point already fulfills the bounds, and compute
  149.      * a replacement value using the offset and scale if bounds are
  150.      * violated, without calling the function at all.
  151.      * </p>
  152.      * @param point unbounded point
  153.      * @return either underlying function value or penalty function value
  154.      */
  155.     @Override
  156.     public double value(double[] point) {

  157.         for (int i = 0; i < scale.length; ++i) {
  158.             if (point[i] < lower[i] || point[i] > upper[i]) {
  159.                 // bound violation starting at this component
  160.                 double sum = 0;
  161.                 for (int j = i; j < scale.length; ++j) {
  162.                     final double overshoot;
  163.                     if (point[j] < lower[j]) {
  164.                         overshoot = scale[j] * (lower[j] - point[j]);
  165.                     } else if (point[j] > upper[j]) {
  166.                         overshoot = scale[j] * (point[j] - upper[j]);
  167.                     } else {
  168.                         overshoot = 0;
  169.                     }
  170.                     sum += JdkMath.sqrt(overshoot);
  171.                 }
  172.                 return offset + sum;
  173.             }
  174.         }

  175.         // all boundaries are fulfilled, we are in the expected
  176.         // domain of the underlying function
  177.         return bounded.value(point);
  178.     }
  179. }