View Javadoc
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  
19  import org.apache.commons.math4.legacy.analysis.MultivariateMatrixFunction;
20  
21  /** Class representing the Jacobian of a multivariate vector function.
22   * <p>
23   * The rows iterate on the model functions while the columns iterate on the parameters; thus,
24   * the numbers of rows is equal to the dimension of the underlying function vector
25   * value and the number of columns is equal to the number of free parameters of
26   * the underlying function.
27   * </p>
28   * @since 3.1
29   */
30  public class JacobianFunction implements MultivariateMatrixFunction {
31  
32      /** Underlying vector-valued function. */
33      private final MultivariateDifferentiableVectorFunction f;
34  
35      /** Simple constructor.
36       * @param f underlying vector-valued function
37       */
38      public JacobianFunction(final MultivariateDifferentiableVectorFunction f) {
39          this.f = f;
40      }
41  
42      /** {@inheritDoc} */
43      @Override
44      public double[][] value(double[] point) {
45  
46          // set up parameters
47          final DerivativeStructure[] dsX = new DerivativeStructure[point.length];
48          for (int i = 0; i < point.length; ++i) {
49              dsX[i] = new DerivativeStructure(point.length, 1, i, point[i]);
50          }
51  
52          // compute the derivatives
53          final DerivativeStructure[] dsY = f.value(dsX);
54  
55          // extract the Jacobian
56          final double[][] y = new double[dsY.length][point.length];
57          final int[] orders = new int[point.length];
58          for (int i = 0; i < dsY.length; ++i) {
59              for (int j = 0; j < point.length; ++j) {
60                  orders[j] = 1;
61                  y[i][j] = dsY[i].getPartialDerivative(orders);
62                  orders[j] = 0;
63              }
64          }
65  
66          return y;
67      }
68  }