JacobianFunction.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.analysis.differentiation;

  18. import org.apache.commons.math4.legacy.analysis.MultivariateMatrixFunction;

  19. /** Class representing the Jacobian of a multivariate vector function.
  20.  * <p>
  21.  * The rows iterate on the model functions while the columns iterate on the parameters; thus,
  22.  * the numbers of rows is equal to the dimension of the underlying function vector
  23.  * value and the number of columns is equal to the number of free parameters of
  24.  * the underlying function.
  25.  * </p>
  26.  * @since 3.1
  27.  */
  28. public class JacobianFunction implements MultivariateMatrixFunction {

  29.     /** Underlying vector-valued function. */
  30.     private final MultivariateDifferentiableVectorFunction f;

  31.     /** Simple constructor.
  32.      * @param f underlying vector-valued function
  33.      */
  34.     public JacobianFunction(final MultivariateDifferentiableVectorFunction f) {
  35.         this.f = f;
  36.     }

  37.     /** {@inheritDoc} */
  38.     @Override
  39.     public double[][] value(double[] point) {

  40.         // set up parameters
  41.         final DerivativeStructure[] dsX = new DerivativeStructure[point.length];
  42.         for (int i = 0; i < point.length; ++i) {
  43.             dsX[i] = new DerivativeStructure(point.length, 1, i, point[i]);
  44.         }

  45.         // compute the derivatives
  46.         final DerivativeStructure[] dsY = f.value(dsX);

  47.         // extract the Jacobian
  48.         final double[][] y = new double[dsY.length][point.length];
  49.         final int[] orders = new int[point.length];
  50.         for (int i = 0; i < dsY.length; ++i) {
  51.             for (int j = 0; j < point.length; ++j) {
  52.                 orders[j] = 1;
  53.                 y[i][j] = dsY[i].getPartialDerivative(orders);
  54.                 orders[j] = 0;
  55.             }
  56.         }

  57.         return y;
  58.     }
  59. }