alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Commons Math example source code file (HarmonicFitter.java)

This example Commons Math source code file (HarmonicFitter.java) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Commons Math tags/keywords

curvefitter, curvefitter, differentiablemultivariatevectorialoptimizer, functionevaluationexception, harmoniccoefficientsguesser, harmoniccoefficientsguesser, harmonicfitter, harmonicfitter, harmonicfunction, optimizationexception, parametricharmonicfunction, parametricharmonicfunction, parametricrealfunction, weightedobservedpoint

The Commons Math HarmonicFitter.java source code

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.commons.math.optimization.fitting;

import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.MathRuntimeException;
import org.apache.commons.math.optimization.DifferentiableMultivariateVectorialOptimizer;
import org.apache.commons.math.optimization.OptimizationException;

/** This class implements a curve fitting specialized for sinusoids.
 * <p>Harmonic fitting is a very simple case of curve fitting. The
 * estimated coefficients are the amplitude a, the pulsation ? and
 * the phase ?: <code>f (t) = a cos (? t + ?). They are
 * searched by a least square estimator initialized with a rough guess
 * based on integrals.</p>
 * @version $Revision: 786479 $ $Date: 2009-06-19 08:36:16 -0400 (Fri, 19 Jun 2009) $
 * @since 2.0
 */
public class HarmonicFitter {

    /** Fitter for the coefficients. */
    private final CurveFitter fitter;

    /** Values for amplitude, pulsation ? and phase ?. */
    private double[] parameters;

    /** Simple constructor.
     * @param optimizer optimizer to use for the fitting
     */
    public HarmonicFitter(final DifferentiableMultivariateVectorialOptimizer optimizer) {
        this.fitter = new CurveFitter(optimizer);
        parameters  = null;
    }

    /** Simple constructor.
     * <p>This constructor can be used when a first guess of the
     * coefficients is already known.</p>
     * @param optimizer optimizer to use for the fitting
     * @param initialGuess guessed values for amplitude (index 0),
     * pulsation ? (index 1) and phase ? (index 2)
     */
    public HarmonicFitter(final DifferentiableMultivariateVectorialOptimizer optimizer,
                          final double[] initialGuess) {
        this.fitter     = new CurveFitter(optimizer);
        this.parameters = initialGuess.clone();
    }

    /** Add an observed weighted (x,y) point to the sample.
     * @param weight weight of the observed point in the fit
     * @param x abscissa of the point
     * @param y observed value of the point at x, after fitting we should
     * have P(x) as close as possible to this value
     */
    public void addObservedPoint(double weight, double x, double y) {
        fitter.addObservedPoint(weight, x, y);
    }

    /** Fit an harmonic function to the observed points.
     * @return harmonic function best fitting the observed points
     * @throws OptimizationException if the sample is too short or if
     * the first guess cannot be computed
     */
    public HarmonicFunction fit() throws OptimizationException {
        try {

            // shall we compute the first guess of the parameters ourselves ?
            if (parameters == null) {
                final WeightedObservedPoint[] observations = fitter.getObservations();
                if (observations.length < 4) {
                    throw new OptimizationException("sample contains {0} observed points, at least {1} are required",
                                                    observations.length, 4);
                }

                HarmonicCoefficientsGuesser guesser = new HarmonicCoefficientsGuesser(observations);
                guesser.guess();
                parameters = new double[] {
                                 guesser.getGuessedAmplitude(),
                                 guesser.getGuessedPulsation(),
                                 guesser.getGuessedPhase()
                            };

            }

            double[] fitted = fitter.fit(new ParametricHarmonicFunction(), parameters);
            return new HarmonicFunction(fitted[0], fitted[1], fitted[2]);

        } catch (FunctionEvaluationException fee) {
            // this should never happen
            throw MathRuntimeException.createInternalError(fee);
        }
    }

    /** Parametric harmonic function. */
    private static class ParametricHarmonicFunction implements ParametricRealFunction {

        /** {@inheritDoc} */
        public double value(double x, double[] parameters) {
            final double a     = parameters[0];
            final double omega = parameters[1];
            final double phi   = parameters[2];
            return a * Math.cos(omega * x + phi);
        }

        /** {@inheritDoc} */
        public double[] gradient(double x, double[] parameters) {
            final double a     = parameters[0];
            final double omega = parameters[1];
            final double phi   = parameters[2];
            final double alpha = omega * x + phi;
            final double cosAlpha = Math.cos(alpha);
            final double sinAlpha = Math.sin(alpha);
            return new double[] { cosAlpha, -a * x * sinAlpha, -a * sinAlpha };
        }

    }

}

Other Commons Math examples (source code examples)

Here is a short list of links related to this Commons Math HarmonicFitter.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.