/*
*   CLASS:      CurveSmooth
*
*   USAGE:      Class for smoothing a curve and obtaining the maxima and minima of a curve
*               Smoothing methods: moving average window or Savitzky-Golay filter
*
*   WRITTEN BY: Dr Michael Thomas Flanagan
*
*   DATE:       February 2012
*   AMENDED:    26-27 February 2012, 3-17 March 2012 
*
*   DOCUMENTATION:
*   See Michael Thomas Flanagan's Java library on-line web pages:
*   http://www.ee.ucl.ac.uk/~mflanaga/java/
*   http://www.ee.ucl.ac.uk/~mflanaga/java/Smooth.html
*
*   Copyright (c) 2012  Michael Thomas Flanagan
*
*   PERMISSION TO COPY:
*
* Permission to use, copy and modify this software and its documentation for NON-COMMERCIAL purposes is granted, without fee,
* provided that an acknowledgement to the author, Dr Michael Thomas Flanagan at www.ee.ucl.ac.uk/~mflanaga, appears in all copies
* and associated documentation or publications.
*
* Redistributions of the source code of this source code, or parts of the source codes, must retain the above copyright notice, this list of conditions
* and the following disclaimer and requires written permission from the Michael Thomas Flanagan:
*
* Redistribution in binary form of all or parts of this class must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution and requires written permission from the Michael Thomas Flanagan:
*
* Dr Michael Thomas Flanagan makes no representations about the suitability or fitness of the software for any or for a particular purpose.
* Dr Michael Thomas Flanagan shall not be liable for any damages suffered as a result of using, modifying or distributing this software
* or its derivatives.
*
***************************************************************************************/

package flanagan.analysis;

import flanagan.math.ArrayMaths;
import flanagan.math.Conv;
import flanagan.math.Fmath;
import flanagan.math.Matrix;
import flanagan.interpolation.CubicSpline;
import flanagan.plot.*;

import java.util.ArrayList;
import java.math.BigDecimal;
import java.math.BigInteger;

public class CurveSmooth{
    
    private double[] xData = null;                                  // original x data, y = f(x)  
    private double[] yData = null;                                  // original y data, y = f(x)  
    private BigDecimal[] xBDdata = null;                            // original arbitrary precision x data, y = f(x)  
    private BigDecimal[] yBDdata = null;                            // original arbitrary precision y data, y = f(x)  
    private int nPoints = 0;                                        // number of data points
    private boolean arbprec = false;                                // = true if arbitrary precision data entered
      
    private double[] yDataMovAv = null;                             // moving average smoothed y data, double precision, y = f(x)  
    private BigDecimal[] yDataMovAvBD = null;                       // moving average smoothed y data, arbitrary precision, y = f(x)  
    private double[] yDataSavGol = null;                            // Savitzky-Golay smoothed y data, y = f(x)  
    private double[] yDataSavGolFirst = null;                       // Savitzky-Golay smoothed first derivative (dy/dx) data, y = f(x)  
    private double[] yDataSavGolSecond = null;                      // Savitzky-Golay smoothed second derivative (d^2y/dx^2) data, y = f(x)  
    private double[] yDataSavGolNth = null;                         // Savitzky-Golay smoothed nth derivative (d^ny/dx^n) data, y = f(x)  
        
    private int lastMethod = 0;                                     // = 0: none called
                                                                    // = 1: moving window average
                                                                    // = 2: Savitzky-Golay filter                                                           
    private int nMethods = 2;                                       // number of methods
    private int lastPlotMethod = 0;                                 // = 0: none called
                                                                    // = 1: moving window average
                                                                    // = 2: Savitzky-Golay filter, no derivatives
                                                                    // = 3: Savitzky-Golay filter + first derivative
                                                                    // = 4: Savitzky-Golay filter + second derivative
                                                                    // = 5: Savitzky-Golay filter + nth derivative                                                              
                                                              
    private int maWindowWidth = 0;                                  // width of the smoothing window in the running average method, y=f(x)
   
    private int sgWindowWidth = 0;                                  // width of smoothing window in the Savitzky-Golay method, y=f(x)
    private int sgPolyDeg = 4;                                      // Savitzky-Golay smoothing polynomial degree
    private double[] derivSavGol = null;                            // Savitzky-Golay smoothed derivative (d^ny/dx^n), y = f(x)  
    private int sgDerivOrderUsed = 0;                               // Savitzky-Golay derivative order used in last derivative smoothing
     
    private boolean calcSavGol = false;                             // = true when Savitzky-Golay smoothing performed
    private boolean calcMovAv = false;                              // = true when moving average smoothing performed
    
    private boolean firstDeriv = false;                             // = true when Savitzky-Golay first derivative smoothing performed
    private boolean secondDeriv = false;                            // = true when Savitzky-Golay second derivative smoothing performed
    private boolean nthSet = false;                                 // = true when any Savitzky-Golay derivative smoothing performed
    
    private double[][] sgArrayC = null;                             // Savitzky-Golay filter coefficients
    private double[] sgCoeff = null;                                // Savitzky-Golay filter coefficients: first row
    
    private double extentMovAv = -1.0;                              // Extent of the moving average window smoothing
    private double extentSavGol = -1.0;                             // Extent of the Savitzky-Golay smoothing
    
    private ArrayList almin = new ArrayList();      // ArrayList of minima points - working array
    private ArrayList almax = new ArrayList();      // ArrayList of maxima points - working array
    private ArrayList alminBD = new ArrayList();      // ArrayList of arbitrary precision minima points - working array
    private ArrayList almaxBD = new ArrayList();      // ArrayList of arbitrary precision mimaxima points - working array
    private double[][][] minima = null;                             // double[][][] array of minima points; minima[][0] - x coordinate, minima[][1] - y coordinate,
    private double[][][] maxima = null;                             // double[][][] array of maxima points; maxima[][0] - x coordinate, maxima[][1] - y coordinate,                                                               
    private BigDecimal[][][] minimaBD = null;                       // minima as arbitrary precision  
    private BigDecimal[][][] maximaBD = null;                       // maxima as arbitrary precision
                                                                    // [method][2: =0 x values, =1 y values][number of minima] 
                                                                    // [0][][]  = unsmoothed data
                                                                    // [1][][]  = moving average smoothed data
                                                                    // [2][][]  = Savitzky-Golay smoothed data       
    private int[] nMin = null;                                      // number of minima 
    private int[] nMax = null;                                      // number of maxima                                                                 
                                                                    // [0]  = unsmoothed data
                                                                    // [1]  = moving average smoothed data
                                                                    // [2]  = Savitzky-Golay smoothed data
    private boolean[] minimaCalc = null;                            // = true when minima found
    private boolean[] maximaCalc = null;                            // = true when maxima found
                                                                    // [0]  = unsmoothed data
                                                                    // [1]  = moving average smoothed data
                                                                    // [2]  = Savitzky-Golay smoothed data
       
    private CubicSpline csSavGol = null;                            // Cubic spline interpolation of the Savitzky-Golay smoothed data
    private CubicSpline csMovAv = null;                             // Cubic spline interpolation of the moving averagey smoothed data
    
    // CONSTRUCTORS
    
    // Constructor - data as double, y = f(x)
    public CurveSmooth(double[] x, double[] y){ 
        this.xData = x;
        this.yData = y;
        this.check();
        this.ascend();
    }
    
    // Constructor - data as double - no x data, y = f(x)
    public CurveSmooth(double[] y){ 
        int n = y.length;
        this.yData = y;
        this.xData = new double[n];
        for(int i=0; i=this.nPoints)test1 = false;
            }
        }
        if(!test2){
            ArrayMaths am = new ArrayMaths(this.xData);
            am =  am.sort();
            int[] indices = am.originalIndices();
            double[] holdx = new double[this.nPoints];
            double[] holdy = new double[this.nPoints];
            BigDecimal[] holdxBD = new BigDecimal[this.nPoints];
            BigDecimal[] holdyBD = null;
            if(this.arbprec)holdyBD = new BigDecimal[this.nPoints];
            for(int i=0; i=ww){
                lp = i - ww;
            }
            else{
                lp = 0;               
            }
            if(i<=this.nPoints-ww-1){                    
                up = i + ww;
            }
            else{
                up = this.nPoints - 1;
            }
            int nw = up - lp + 1;
            if(this.arbprec){
                BigDecimal sumbd = new BigDecimal("0.0");
                for(int j=lp; j<=up; j++){               
                    sumbd = sumbd.add(this.yBDdata[j]);
                }
                String xx = (new Integer(nw)).toString();
                this.yDataMovAvBD[i] = sumbd.divide(new BigDecimal(xx), BigDecimal.ROUND_HALF_UP);
                this.yDataMovAv[i] = this.yDataMovAvBD[i].doubleValue();
            }
            else{
                double sum = 0.0;
                for(int j=lp; j<=up; j++){               
                    sum += this.yData[j];
                }
                this.yDataMovAv[i] = sum/nw;
                String xx = (new Double(this.yDataMovAv[i])).toString();
                this.yDataMovAvBD[i] = new BigDecimal(xx);
            }
        }
        
        // Set up interpolation
        this.csMovAv = new CubicSpline(this.xData, this.yDataMovAv);
                
        this.calcMovAv = true;
        return Conv.copy(this.yDataMovAv);
     
    }
    
    
    // Smooth with a moving average window of width maWindowWidth
    // With plotting
    public double[] movingAveragePlot(int maWindowWidth){
        double[] ret = this.movingAverage(maWindowWidth);
        this.plot();
        return ret;
    }
    
    // Smooth with a moving average window of width maWindowWidth
    // Return values as BigDecimal
    // No Plotting
    public BigDecimal[] movingAverageAsBigDecimal(int maWindowWidth){
        this.movingAverage(maWindowWidth);
        return Conv.copy(this.yDataMovAvBD);
    }
    
    // Smooth with a moving average window of width maWindowWidth
    // Return values as BigDecimal
    // No Plotting
    public BigDecimal[] movingAverageAsBigDecimalPlot(int maWindowWidth){
        this.movingAverageAsBigDecimal(maWindowWidth);
        this.plot();
        return Conv.copy(this.yDataMovAvBD);
    }
    
    // Return window half extension
    private int windowHalf(int width){
    
        int ww = 0;
        if(Fmath.isEven(width)){
            ww = width/2;
        }
        else{
           ww = (width-1)/2;
        }
        return ww;
    }
    
    // Adust width to an odd number of points
    private int windowLength(int width){
    
        int ww = 0;
        if(Fmath.isEven(width)){
            ww = width+1;
        }
        else{
           ww = width;
        }
        return ww;
    }
       
    // SAVITZKY-GOLAY FILTER
    
     // Smooth with a Savitzky-Golay filter with a window of dimensions sgWindowWidthx and sgWindowWidthy
    public double[] savitzkyGolay(int sgWindowWidth){              
       
        this.lastMethod = 2;
        this.lastPlotMethod = 2;
        this.yDataSavGol = new double[this.nPoints];
        
        // adjust window width to an odd number of points
        this.sgWindowWidth = this.windowLength(sgWindowWidth);
        
        // Apply filter 
        this.savitzkyGolayCommon(this.sgWindowWidth);
                       
        // Set up interpolation
        this.csSavGol = new CubicSpline(this.xData, Conv.copy(this.yDataSavGol));
         
                 
        this.calcSavGol = true;
        return Conv.copy(this.yDataSavGol);
    }
    
     // Common method for smoothing with a Savitzky-Golay filter with a window width
    private double[] savitzkyGolayCommon(int width){
        
        // Set filter dimension term
        int ww = (width - 1)/2;

        
        // Calculate filter coefficients
        double[] coeff = (this.savitzkyGolayFilter(ww, ww))[0];
        
        // Padout the data to solve edge effects
        double[] psData = this.padData(this.yData, ww);

        // Apply filter       
        for(int i=ww; ithis.sgPolyDeg)throw new IllegalArgumentException("The derivative order, " + 1 + ", must be less than or equal to the polynomial degree, " + this.sgPolyDeg + ".");
        this.lastMethod = 2;
        this.lastPlotMethod = 3;        
        double[][] ret = this.savitzkyGolay(sgWindowWidth, 1); 
        this.yDataSavGolFirst = ret[1];
        if(!this.nthSet)this.yDataSavGolNth = ret[1];
        this.nthSet = true;
        this.firstDeriv = true;
        return ret;
    }
    
    // Smooth with a Savitzky-Golay filter with a window of width sgWindowWidth
    // First derivative also calculated
    // With plotting
    public double[][] savitzkyGolayPlusFirstDerivPlot(int sgWindowWidth){
        double[][]ret = this.savitzkyGolayPlusFirstDeriv(sgWindowWidth);
        this.plot();
        this.firstDeriv = true;
        return ret;
    }
    
    // Smooth with a Savitzky-Golay filter with a window of width sgWindowWidth
    // Second derivative also calculated
    // No plotting
    public double[][] savitzkyGolayPlusSecondDeriv(int sgWindowWidth){
        if(2>this.sgPolyDeg)throw new IllegalArgumentException("The derivative order, " + 2 + ", must be less than or equal to the polynomial degree, " + this.sgPolyDeg + ".");
        this.lastMethod = 2;
        this.lastPlotMethod = 4;
        
        double[][] ret = this.savitzkyGolay(sgWindowWidth, 2); 
        this.yDataSavGolSecond = ret[1];
        if(!this.nthSet)this.yDataSavGolNth = ret[1];
        this.nthSet = true;
        this.secondDeriv = true;
        return ret;
    }
    
    // Smooth with a Savitzky-Golay filter with a window of width sgWindowWidth
    // Second derivative also calculated
    // With plotting
    public double[][] savitzkyGolayPlusSecondDerivPlot(int sgWindowWidth){
        double[][] ret = this.savitzkyGolayPlusSecondDeriv(sgWindowWidth);
        this.plot();
        this.secondDeriv = true;
        return ret;
    }
    
    // Smooth with a Savitzky-Golay filter with a window of width sgWindowWidth
    // nth derivative also calculated
    // No plotting
    public double[][] savitzkyGolay(int sgWindowWidth, int n){
        if(n>this.sgPolyDeg)throw new IllegalArgumentException("The  derivative order " +  n + ", must be less than or equal to the polynomial degree, " + this.sgPolyDeg + ".");
 
        this.sgDerivOrderUsed = n;
        double[][] ret = new double[2][this.nPoints];
        
         // adjust window width to an odd number of points
        this.sgWindowWidth = this.windowLength(sgWindowWidth);
        int ww = (this.sgWindowWidth - 1)/2;
        
        if(!this.calcSavGol)this.savitzkyGolay(sgWindowWidth);
        ret[0] = this.yDataSavGol;
        
        // get filter coefficients
        double[] coeff = this.sgArrayC[n]; 
        
        // Padout the data to solve edge effects
        double[] psData = this.padData(this.yData, ww);

        // Apply filter       
        for(int i=ww; i2){
            data[8] = this.xData;
            sp = new int[5];
            sl = new int[5];
            sp[4] = 0;
            sl[4] = 3;
            for(int i=0;i<4; i++){
                sp[i] = sph[i];
                sl[i] = slh[i];
            }
        }
        data[0] = this.xData;
        data[1] = this.yData;
        data[2] = this.xData;
        
        PlotGraph pg = new PlotGraph(data);
            
        pg.setPoint(sp);
        pg.setLine(sl);
        pg.setGraphTitle("Original (circles) and smoothed (squares) data");
        pg.setGraphTitle2(method);
        pg.setXaxisLegend("x values");
        pg.setYaxisLegend("y values");
        pg.plot();
    }
  
    // SMOOTHED VALUES
    
    // Return last method smoothed y data
    public double[] getSmoothedValues(){
        double[] ret = null;
        switch(this.lastMethod){
            case 0: throw new IllegalArgumentException("No smoothing method has been called");
            case 1: ret = this.yDataMovAv;
                    break;
            case 2: ret = this.yDataSavGol;
                    break;
        }
        return Conv.copy(ret);
    }
    
    // Return moving average smoothed y data
    public double[] getMovingAverageValues(){
        if(!this.calcMovAv)throw new IllegalArgumentException("No moving average smoothing method has been called");
        return Conv.copy(this.yDataMovAv);
    } 
    
    // Return moving average smoothed y data as BigDecimal
    public BigDecimal[] getMovingAverageValuesAsBigDecimal(){
        if(!this.calcMovAv)throw new IllegalArgumentException("No moving average smoothing method has been called");
        return Conv.copy(this.yDataMovAvBD);
    }
    
    // Return Savitzky-Golay smoothed y data
    public double[] getSavitzkyGolaySmoothedValues(){
        if(!this.calcSavGol)throw new IllegalArgumentException("No Savitzky-Golay smoothing method has been called");
        return Conv.copy(this.yDataSavGol);
    }
        
    // Return Savitzky-Golay smoothed first derivative dy/dx data
    public double[] getSavitzkyGolayFirstDerivatives(){
        return getSavitzkyGolaySmoothedFirstDerivValues();
    }
    
    // Return Savitzky-Golay smoothed first derivative dy/dx data
    public double[] getSavitzkyGolaySmoothedFirstDerivValues(){
        if(!this.firstDeriv)throw new IllegalArgumentException("No Savitzky-Golay first derivative smoothing method has been called");
        return Conv.copy(this.yDataSavGolFirst);
    }
    
    // Return Savitzky-Golay smoothed second derivative dy/dx data
    public double[] getSavitzkyGolaySecondDerivatives(){
        return getSavitzkyGolaySmoothedSecondDerivValues();
    }
    
    // Return Savitzky-Golay smoothed second derivative d^2y/dx^2 data
    public double[] getSavitzkyGolaySmoothedSecondDerivValues(){
        if(!this.secondDeriv)throw new IllegalArgumentException("No Savitzky-Golay second derivative smoothing method has been called");
        return Conv.copy(this.yDataSavGolSecond);
    }
    
    // Return last Savitzky-Golay smoothed nth derivative d^ny/dx^n data
    public double[] getSavitzkyGolayNthDerivatives(){
        return getSavitzkyGolaySmoothedNthDerivValues();
    }
    
    // Return last Savitzky-Golay smoothed nth derivative d^ny/dx^n data
    public double[] getSavitzkyGolaySmoothedNthDerivValues(){
        if(!this.nthSet)throw new IllegalArgumentException("No Savitzky-Golay derivative smoothing method has been called");
        return Conv.copy(this.yDataSavGolNth);
    }
    
    // Return last Savitzky-Golay smoothed nth derivative d^ny/dx^n data
    public double[] getSavitzkyGolayDerivatives(){
        if(!this.nthSet)throw new IllegalArgumentException("No Savitzky-Golay derivative smoothing method has been called");
        return Conv.copy(this.yDataSavGolNth);
    }
    
     // Return  Savitzky-Golay smoothed nth derivative d^ny/dx^n data
    public double[] getSavitzkyGolayNthDerivatives(int n){
        return getSavitzkyGolaySmoothedNthDerivValues(n);
    }
    
    // Return  Savitzky-Golay smoothed nth derivative d^ny/dx^n data
    public double[] getSavitzkyGolayDerivatives(int n){
        return getSavitzkyGolaySmoothedNthDerivValues(n);
    }
    
    // Return Savitzky-Golay smoothed nth derivative d^ny/dx^n data
    public double[] getSavitzkyGolaySmoothedNthDerivValues(int n){
        if(!this.nthSet)throw new IllegalArgumentException("No Savitzky-Golay derivative smoothing method has been called");
        double[] ret = null;
        switch(n){
            case 0: ret = this.yDataSavGol;
                    break;
            case 1: if(!this.firstDeriv)throw new IllegalArgumentException("No Savitzky-Golay first derivative smoothing method has been called");
                    ret = this.yDataSavGolFirst;
                    break;
            case 2: if(!this.secondDeriv)throw new IllegalArgumentException("No Savitzky-Golay second derivative smoothing method has been called");
                    ret = this.yDataSavGolSecond;
                    break;
            default: ret = this.yDataSavGolNth;
                    break;
        }
        return Conv.copy(ret);
    }
    
    // EXTENT OF THE SMOOTHING
    
    // Return the extent of the moving average window smoothing
    public double extentMovingAverage(){
        if(!this.calcMovAv)throw new IllegalArgumentException("No moving average smoothing method has been called");
        this.extentMovAv = this.extent(this.yData, this.yDataMovAv);
        return this.extentMovAv;
    }
    
    // Return the extent of the Savitzky-Golay smoothing
    public double extentSavitzkyGolay(){
        if(!this.calcSavGol)throw new IllegalArgumentException("No Savitzky-Golay smoothing method has been called");
        this.extentSavGol = this.extent(this.yData, this.yDataSavGol);
        return this.extentSavGol;
    }
    
    // Calculate extent of smoothing
    private double extent(double[] yOrigl, double[] ySmooth){
        
        double range = Fmath.maximum(yOrigl) - Fmath.minimum(yOrigl);
        
        double sum = 0.0;
        for(int i=0; iyy[i+1]){
                               plateau = false;
                           }
                        }
                    }
                }
            }
            else{
                if(yy[i]yy[i-1]){
                    plateau = false;
                    if(yy[i]>yy[i+1]){
                        nnMax++;
                        this.almax.add(xx[i]);
                        this.almax.add(yy[i]); 
                    }
                    else{
                        if(yy[i]==yy[i+1]){
                            plateau = true;
                            iPlat = i;
                        }
                    }
                }
                else{
                    if(yy[i]==yy[i-1]){
                        if(yy[i]>yy[i+1]){
                            plateau = false;
                            nnMax++;
                            double xxp = (xx[i]+xx[iPlat])/2.0;
                            this.almax.add(xxp);
                            this.almax.add(yy[i]);
                        }
                        else{
                           if(yy[i]yy[i-1] && yy[i]>yy[i+1]){
                    nnMax++;
                    this.almax.add(xx[i]);
                    this.almax.add(yy[i]);
                }
                else{
                    if(yy[i]>yy[i-1] && yy[i]==yy[i+1]){
                        plateau = true;
                        iPlat = i;
                    }
                }
            }
        }   
    
        this.nMax[flag] = nnMax;
        holdx = new double[nnMax];
        holdy = new double[nnMax];
        holdxBD = new BigDecimal[nnMax];
        holdyBD = new BigDecimal[nnMax];
        k = 0;
        for(int i=0; i 

Ads help maintain this website.