001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math3.analysis.differentiation;
018
019import org.apache.commons.math3.analysis.MultivariateMatrixFunction;
020
021/** Class representing the Jacobian of a multivariate vector function.
022 * <p>
023 * The rows iterate on the model functions while the columns iterate on the parameters; thus,
024 * the numbers of rows is equal to the dimension of the underlying function vector
025 * value and the number of columns is equal to the number of free parameters of
026 * the underlying function.
027 * </p>
028 * @since 3.1
029 */
030public class JacobianFunction implements MultivariateMatrixFunction {
031
032    /** Underlying vector-valued function. */
033    private final MultivariateDifferentiableVectorFunction f;
034
035    /** Simple constructor.
036     * @param f underlying vector-valued function
037     */
038    public JacobianFunction(final MultivariateDifferentiableVectorFunction f) {
039        this.f = f;
040    }
041
042    /** {@inheritDoc} */
043    public double[][] value(double[] point) {
044
045        // set up parameters
046        final DerivativeStructure[] dsX = new DerivativeStructure[point.length];
047        for (int i = 0; i < point.length; ++i) {
048            dsX[i] = new DerivativeStructure(point.length, 1, i, point[i]);
049        }
050
051        // compute the derivatives
052        final DerivativeStructure[] dsY = f.value(dsX);
053
054        // extract the Jacobian
055        final double[][] y = new double[dsY.length][point.length];
056        final int[] orders = new int[point.length];
057        for (int i = 0; i < dsY.length; ++i) {
058            for (int j = 0; j < point.length; ++j) {
059                orders[j] = 1;
060                y[i][j] = dsY[i].getPartialDerivative(orders);
061                orders[j] = 0;
062            }
063        }
064
065        return y;
066
067    }
068
069}