Example usage for org.apache.commons.math3.fitting GaussianFitter fit

List of usage examples for org.apache.commons.math3.fitting GaussianFitter fit

Introduction

In this page you can find the example usage for org.apache.commons.math3.fitting GaussianFitter fit.

Prototype

public double[] fit(double[] initialGuess) 

Source Link

Document

Fits a Gaussian function to the observed points.

Usage

From source file:edu.ucsc.barrel.cdf_gen.SpectrumExtract.java

private static float find511(double[] x, double[] y) {
    GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
    double[] fit_params = { 10, Constants.DOUBLE_FILL, 1 }, curve = new double[PEAK_511_WIDTH - 4];
    int[] high_area = new int[PEAK_511_WIDTH];
    double m, b, slope = 0, this_low = 0, last_low = 0;
    int apex = 0, high_cnt = 0;

    // guess at a linear background
    m = (y[PEAK_511_WIDTH - 1] - y[0]) / (x[PEAK_511_WIDTH - 1] - x[0]);
    b = y[0] - m * x[0];//  w w  w .java  2  s .c o m

    //convert y to cnts/bin_width
    for (int bin_i = 0; bin_i < x.length; bin_i++) {
        y[bin_i] /= (RAW_EDGES[2][bin_i + PEAK_511_START + 1] - RAW_EDGES[2][bin_i + PEAK_511_START]);
    }

    //take the second derivitave to find peak
    for (int bin_i = 2; bin_i < x.length - 2; bin_i++) {
        curve[bin_i - 2] = y[bin_i + 2] - (2 * y[bin_i]) + y[bin_i - 2];
    }

    //find low point of second derivitave using moving average
    this_low = (curve[0] + curve[1] + curve[2]);
    last_low = this_low;
    for (int bin_i = 2; bin_i < curve.length - 1; bin_i++) {
        this_low += (curve[bin_i + 1] - curve[bin_i - 2]);
        if (this_low < last_low) {
            apex = bin_i + 2;
            last_low = this_low;
        }
    }

    //do the curve fit
    try {
        fit_params[1] = x[apex]; //guess for peak location
        for (int bin_i = apex - 3; bin_i < apex + 3; bin_i++) {
            fitter.addObservedPoint(x[bin_i], y[bin_i]);
        }
        fit_params = fitter.fit(fit_params);
    } catch (ArrayIndexOutOfBoundsException ex) {
        System.out.println(
                "Payload ID: " + CDF_Gen.getSetting("currentPayload") + " Date: " + CDF_Gen.getSetting("date"));
        System.out.println("Gaussian out of bounds: " + apex);
        fit_params[1] = Constants.DOUBLE_FILL;
    }
    return (float) fit_params[1];
}