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.math4.legacy.analysis.differentiation;
018
019import org.apache.commons.math4.legacy.analysis.MultivariateVectorFunction;
020
021/** Class representing the gradient of a multivariate function.
022 * <p>
023 * The vectorial components of the function represent the derivatives
024 * with respect to each function parameters.
025 * </p>
026 * @since 3.1
027 */
028public class GradientFunction implements MultivariateVectorFunction {
029
030    /** Underlying real-valued function. */
031    private final MultivariateDifferentiableFunction f;
032
033    /** Simple constructor.
034     * @param f underlying real-valued function
035     */
036    public GradientFunction(final MultivariateDifferentiableFunction f) {
037        this.f = f;
038    }
039
040    /** {@inheritDoc} */
041    @Override
042    public double[] value(double[] point) {
043
044        // set up parameters
045        final DerivativeStructure[] dsX = new DerivativeStructure[point.length];
046        for (int i = 0; i < point.length; ++i) {
047            dsX[i] = new DerivativeStructure(point.length, 1, i, point[i]);
048        }
049
050        // compute the derivatives
051        final DerivativeStructure dsY = f.value(dsX);
052
053        // extract the gradient
054        final double[] y = new double[point.length];
055        final int[] orders = new int[point.length];
056        for (int i = 0; i < point.length; ++i) {
057            orders[i] = 1;
058            y[i] = dsY.getPartialDerivative(orders);
059            orders[i] = 0;
060        }
061
062        return y;
063    }
064}