/*
*   CLASS:      SurfaceSmooth
*
*   USAGE:      Class for smoothing a surface
*               Smoothing methods: moving average window or Savitzky-Golay filter
*
*   WRITTEN BY: Dr Michael Thomas Flanagan
*
*   DATE:       5-16 March 2012
*   AMENDED:     
*
*   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/SurfaceSmooth.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.interpolation.BiCubicSpline;
import flanagan.math.Matrix;
import flanagan.plot.*;

import java.math.BigDecimal;
import java.math.BigInteger;

public class SurfaceSmooth{
    
    private double[] xData = null;                                  // original x data, z = f(x,y)
    private double[] yData = null;                                  // original y data, z = f(x,y)  
    private double[][] zData = null;                                // original z data, z = f(x,y)
    private BigDecimal[] xBDdata = null;                            // original arbitrary precision x data, z = f(x,y)
    private BigDecimal[] yBDdata = null;                            // original arbitrary precision y data, z = f(x,y)
    private BigDecimal[][] zBDdata = null;                          // original arbitrary precision z data, z = f(x,y)
    private int nPointsX = 0;                                       // number of  x data points, z = f(x,y)
    private int nPointsY = 0;                                       // number of  y data points, z = f(x,y)
    private int nPoints = 0;                                        // total number of data points
    private boolean arbprec = false;                                // = true if arbitrary precision data entered
    
    private double[][] zDataMovAv = null;                           // moving average smoothed z data, double precision, z = f(x,y)
    private BigDecimal[][] zDataMovAvBD = null;                     // moving average smoothed z data, arbitrary precision, z = f(x,y)
    private double[][] zDataSavGol = null;                          // Savitzky-Golay smoothed z data, z = f(x,y)             
    private double[][] derivSavGol = null;                          // Savitzky-Golay smoothed derivative (d^mnz/dx^mdy^n), z = f(x,y)  
    private int[][] sgCoeffIndices = null;                          // indices of the fitting polynomial and Savitzky-Golay filter coefficients
    private int nSGcoeff = 0;                                       // number of coefficients
    private int lastMethod = 0;                                     // = 0: none called
                                                                    // = 1: moving window average
                                                                    // = 2: Savitzky-Golay filter                                                           
    private int nMethods = 2;                                       // number of methods
                                                                                                                                
    private int maWindowWidthx = 0;                                 // x width of the  smoothing window in the running average method, z = f(x,y)
    private int maWindowWidthy = 0;                                 // y width of the  smoothing window in the running average method, z = f(x,y)
   
    private int sgWindowWidthx = 0;                                 // x width of smoothing window in the Savitzky-Golay method, z = f(x,y)
    private int sgWindowWidthy = 0;                                 // y width of smoothing window in the Savitzky-Golay method, z = f(x,y)

    private int sgPolyDeg = 4;                                      // Savitzky-Golay smoothing polynomial degree
    private double[][] sgArrayC = null;                             // Savitzky-Golay C matrix
   
    private boolean calcSavGol = false;                             // = true when Savitzky-Golay smoothing performed
    private boolean calcMovAv = false;                              // = true when moving average smoothing performed
    
    private boolean nthSet = false;                                 // = true when any Savitzky-Golay derivative smoothing performed
    
    private double extentMovAv = -1.0;                              // Extent of the moving average window smoothing
    private double extentSavGol = -1.0;                             // Extent of the Savitzky-Golay smoothing
        
    private BiCubicSpline bcsSavGol = null;                         // BiCubic spline interpolation of the Savitzky-Golay  smoothed data
    private BiCubicSpline bcsMovAv = null;                          // BiCubic spline interpolation of the moving averagey  smoothed data
    
    private int trunc = 4;                                          // truncation value for plot title values
    
    // CONSTRUCTORS
    
    // Constructor - data as  double, z=f(x,y)
    public SurfaceSmooth(double[] x, double[] y, double[][] z){ 
        this.xData = x;
        this.yData = y;
        this.zData = z;
        this.polyIndices();
        this.check();
        this.ascend();
    }
    
    // Constructor - data as  double - no x or y data, z=f(x,y)
    public SurfaceSmooth(double[][] z){ 
        int n = z.length;
        this.zData = z;
        this.yData = new double[n];
        for(int i=0; i=this.nPointsY)test1 = false;
            }
        }
        if(!test2){
            ArrayMaths am = new ArrayMaths(this.yData);
            am =  am.sort();
            int[] indices = am.originalIndices();
            double[] holdy = new double[this.nPointsY];
            double[][] holdz = new double[this.nPointsY][this.nPointsX];
            BigDecimal[] holdyBD = new BigDecimal[this.nPointsY];
            BigDecimal[][] holdzBD = null;
            if(this.arbprec)holdzBD = new BigDecimal[this.nPointsY][this.nPointsX];
            for(int i=0; i=this.nPointsX)test1 = false;
            }
        }
        if(!test2){
            ArrayMaths am = new ArrayMaths(this.xData);
            am =  am.sort();
            int[] indices = am.originalIndices();
            double[] holdx = new double[this.nPointsX];
            double[][] holdz = new double[this.nPointsY][this.nPointsX];
            BigDecimal[] holdxBD = new BigDecimal[this.nPointsX];
            BigDecimal[][] holdzBD = null;
            if(this.arbprec)holdzBD = new BigDecimal[this.nPointsY][this.nPointsX];
            for(int i=0; i=wwx){
                lpx = i - wwx;
            }
            else{
                lpx = 0;               
            }
            if(i<=this.nPointsX-wwx-1){                    
                upx = i + wwx;
            }
            else{
                upx = this.nPointsX - 1;
            }
            int nw1 = upx - lpx + 1;
            
            // Set y window limits
            for(int j=0; j=wwy){
                    lpy = j - wwy;
                }
                else{
                    lpy = 0;               
                }
                if(j<=this.nPointsY-wwy-1){                    
                    upy = j + wwy;
                }
                else{
                    upy = this.nPointsY - 1;
                }
                int nw2 = upy - lpy + 1;
  
                // Apply moving average window
                if(this.arbprec){
                    BigDecimal sumbd = new BigDecimal("0.0");
                    for(int k1=lpx; k1<=upx; k1++){
                        for(int k2=lpy; k2<=upy; k2++){
                            sumbd = sumbd.add(this.zBDdata[k2][k1]);
                        }
                    }
                    String xx = (new Integer(nw1*nw2)).toString();
                    this.zDataMovAvBD[j][i] = sumbd.divide(new BigDecimal(xx), BigDecimal.ROUND_HALF_UP);
                    this.zDataMovAv[j][i] = this.zDataMovAvBD[j][i].doubleValue();
                }
                else{
                    double sum = 0.0;
                    for(int k1=lpx; k1<=upx; k1++){
                        for(int k2=lpy; k2<=upy; k2++){
                            sum += this.zData[k2][k1];
                        }
                    }             
                    this.zDataMovAv[j][i] = sum/(nw1*nw2);
                    String xx = (new Double(this.zDataMovAv[j][i])).toString();
                    this.zDataMovAvBD[j][i] = new BigDecimal(xx);
                }
            }
        }
        
        // Set up interpolation
        this.bcsMovAv = new BiCubicSpline(this.yData, this.xData, this.zDataMovAv);
                
        this.calcMovAv = true;
        return Conv.copy(this.zDataMovAv);
     
    }
    
    // Smooth with a moving average window of dimensions maWindowWidth x maWindowWidth
    public double[][] movingAverage(int maWindowWidth){
        return this.movingAverage(maWindowWidth, maWindowWidth);   
    }
    
    // Smooth with a moving average window of dimensions maWindowWidthx and maWindowWidthy
    // Return values as BigDecimal
    public BigDecimal[][] movingAverageAsBigDecimal(int maWindowWidthx, int maWindowWidthy){
        this.movingAverage(maWindowWidthx, maWindowWidthy);
        return Conv.copy(this.zDataMovAvBD);
    }
    
    // Smooth with a moving average window of dimensions maWindowWidth x maWindowWidth
    // Return values as BigDecimal
    public BigDecimal[][] movingAverageAsBigDecimal(int maWindowWidth){
        this.movingAverage(maWindowWidth, maWindowWidth);
        return Conv.copy(this.zDataMovAvBD);
    }
    
    // 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 sgWindowWidthx, int sgWindowWidthy){              
       
        this.lastMethod = 2;
  
        this.zDataSavGol = new double[this.nPointsY][this.nPointsX];
        
        // adjust window width to an odd number of points
        this.sgWindowWidthx = this.windowLength(sgWindowWidthx);
        this.sgWindowWidthy = this.windowLength(sgWindowWidthy);
        
        // Apply filter 
        this.savitzkyGolayCommon(this.sgWindowWidthx, this.sgWindowWidthy);
                       
        // Set up interpolation
        this.bcsSavGol = new BiCubicSpline(this.yData, this.xData, Conv.copy(this.zDataSavGol));
         
                 
        this.calcSavGol = true;
        return Conv.copy(this.zDataSavGol);
    }
    
    // Smooth with a Savitzky-Golay filter with a window of dimensions sgWindowWidth x sgWindowWidth
    public double[][] savitzkyGolay(int sgWindowWidth){              
       return this.savitzkyGolay(sgWindowWidth, sgWindowWidth); 
    }
   
    // Common method for smoothing with a Savitzky-Golay filter with a window of widthx times widthy
    private double[][] savitzkyGolayCommon(int widthx, int widthy){
        
        // Set filter dimensions
        int wwx = (widthx - 1)/2;
        int wwy = (widthy - 1)/2;
        
        // Calculate filter coefficients
        double[] coeff = (this.savitzkyGolayFilter(wwx, wwx, wwy, wwy))[0];
        
        // Padout the data to solve edge effects
        double[][] psData = this.padData(this.zData, wwx, wwy);

        // Apply filter       
        for(int i=wwy; ithis.sgPolyDeg)throw new IllegalArgumentException("The sum of the derivative orders " + m + " plus " + n + ", must be less than or equal to the polynomial degree, " + this.sgPolyDeg + ".");
 
        this.lastMethod = 2;
        double[][][] ret = new double[2][this.nPointsY][this.nPointsX];
        
         // adjust window width to an odd number of points
        this.sgWindowWidthx = this.windowLength(sgWindowWidthx);
        int wwx = (this.sgWindowWidthx - 1)/2;
        this.sgWindowWidthy = this.windowLength(sgWindowWidthy);
        int wwy = (this.sgWindowWidthy - 1)/2;
        
        if(!this.calcSavGol)this.savitzkyGolay(sgWindowWidthx, sgWindowWidthy);
        ret[0] = this.zDataSavGol;
        
        // get filter coefficients
        int pointer = 0;
        boolean test = true;
        int len = this.sgCoeffIndices.length;
        while(test){
            if(this.sgCoeffIndices[pointer][0]==m && this.sgCoeffIndices[pointer][1]==n)test = false;
            pointer++;
            if(pointer>=len)throw new IllegalArgumentException("It should not have been possible to reach this situation, m = " + m + ", n = " + n);
        }
        double[] coeff = this.sgArrayC[pointer]; 
        
        // Padout the data to solve edge effects
        double[][] psData = this.padData(this.zData, wwx, wwy);

        // Apply filter       
        for(int i=wwy; i=this.nPointsY)throw new IllegalArgumentException("The index, " + yIndex + ", must be less than the number of y values, " + this.nPointsY);
        int flag = 0;
        double yValue = Fmath.truncate(this.yData[yIndex], this.trunc);
        this.commonPlot(flag, yIndex, yValue);        
    }
    
    // Plot x section for a given y value  - Savitzky-Golay
    public void plotSavitzkyGolayX(double yValue){
        if(!this.calcSavGol)throw new IllegalArgumentException("No Savitzky-Golay smoothing method has been called");
        int flag = 0;
        int yIndex = this.findValue(this.yData, yValue);
        yValue = Fmath.truncate(this.yData[yIndex], this.trunc);
        this.commonPlot(flag, yIndex, yValue);        
    }
    
    // Plot y section for a given x value index - Savitzky-Golay
    public void plotSavitzkyGolayY(int xIndex){
        if(!this.calcSavGol)throw new IllegalArgumentException("No Savitzky-Golay smoothing method has been called");
        if(xIndex>=this.nPointsX)throw new IllegalArgumentException("The index, " + xIndex + ", must be less than the number of x values, " + this.nPointsX);
        int flag = 1;
        double xValue = Fmath.truncate(this.xData[xIndex], this.trunc);
        this.commonPlot(flag, xIndex, xValue);        
    }
    
    // Plot y section for a given x value  - Savitzky-Golay
    public void plotSavitzkyGolayY(double xValue){
        if(!this.calcSavGol)throw new IllegalArgumentException("No Savitzky-Golay smoothing method has been called");
        int flag = 1;
        int xIndex = this.findValue(this.xData, xValue);
        xValue = Fmath.truncate(this.xData[xIndex], this.trunc);
        this.commonPlot(flag, xIndex, xValue);        
    }
    
    // Plot x section for a given y value index - Moving Average
    public void plotMovingAverageX(int yIndex){
        if(!this.calcMovAv)throw new IllegalArgumentException("No moving average smoothing method has been called");
        if(yIndex>=this.nPointsY)throw new IllegalArgumentException("The index, " + yIndex + ", must be less than the number of y values, " + this.nPointsY);
        int flag = 2;
        double yValue = Fmath.truncate(this.yData[yIndex], this.trunc);
        this.commonPlot(flag, yIndex, yValue);        
    }
    
    // Plot x section for a given y value  - Moving Average
    public void plotMovingAverageX(double yValue){
        if(!this.calcMovAv)throw new IllegalArgumentException("No moving average smoothing method has been called");
        int flag = 2;
        int yIndex = this.findValue(this.yData, yValue);
        yValue = Fmath.truncate(this.yData[yIndex], this.trunc);
        this.commonPlot(flag, yIndex, yValue);        
    }
    
    // Plot y section for a given x value index - Moving Average
    public void plotMovingAverageY(int xIndex){
        if(!this.calcMovAv)throw new IllegalArgumentException("No moving average smoothing method has been called");
        if(xIndex>=this.nPointsX)throw new IllegalArgumentException("The index, " + xIndex + ", must be less than the number of x values, " + this.nPointsX);
        int flag = 3;
        double xValue = Fmath.truncate(this.xData[xIndex], this.trunc);
        this.commonPlot(flag, xIndex, xValue);        
    }
    
    // Plot y section for a given x value  - Moving Average
    public void plotMovingAverageY(double xValue){
        if(!this.calcMovAv)throw new IllegalArgumentException("No moving average smoothing method has been called");
        int flag = 3;
        int xIndex = this.findValue(this.xData, xValue);
        xValue = Fmath.truncate(this.xData[xIndex], this.trunc);
        this.commonPlot(flag, xIndex, xValue);        
    }
    
    // find index for a value
    private int findValue(double[] array, double value){
        int len = array.length;
        boolean test = true;
        int counter = 0;
        while(test){
           if(Fmath.isEqualWithinLimits(array[counter], value, Math.abs(value)*0.001)){
               test = false;
           } 
           else{
               counter++;
               if(counter>=len)throw new IllegalArgumentException("The entered plot value, " + value + ",  must equal an entered data value");
           }
        }
        return counter;
    }
    
    // Common plot method
    private void commonPlot(int flag, int point, double value){

        String title0 = null;
        String title1 = null;
        String title1b = ",  Original data - circles,  Smoothed data - squares";
        String xleg = null;
        String yleg = null;
        int[] xPoints ={0, this.nPointsX/4, this.nPointsX/2, 3*this.nPointsX/4, this.nPointsX-1};
        int[] yPoints ={0, this.nPointsY/4, this.nPointsY/2, 3*this.nPointsY/4, this.nPointsY-1};
        double[][] data = new double[8][];
        double[] holdx1 = new double[5];
        double[] holdx2 = new double[5];
        double[] holdy1 = new double[5];
        double[] holdy2 = new double[5];
        
        switch(flag){
            case 0: // x plot Savitzky-Golay
                    title0 = "Savitzky-Golay smoothing with an x by y window of " + this.sgWindowWidthx + " by "+ this.sgWindowWidthy + " points";
                    title1 = "Plot of z versus x values for a y value of " + value + title1b;
                    xleg = "x values";
                    yleg = "y values";
                    data[0] = this.xData;
                    data[1] = this.zData[point];
                    data[2] = this.xData;
                    data[3] = this.zDataSavGol[point];
                    for(int i=0; i<5;i++){
                        holdx1[i] = this.xData[xPoints[i]];
                        holdy1[i] = this.zData[point][xPoints[i]];
                        holdx2[i] = this.xData[xPoints[i]];
                        holdy2[i] = this.zDataSavGol[point][xPoints[i]];
                    }
                    break;
            case 1: // y plot Savitzky-Golay
                    title0 = "Savitzky-Golay smoothing with an x by y window of " + this.sgWindowWidthx + " by "+ this.sgWindowWidthy + " points";
                    title1 = "Plot of z versus y values for a x value of " + value + title1b;
                    xleg = "y values";
                    yleg = "x values";
                    data[0] = this.yData;
                    data[2] = this.yData;
                    data[1] = new double[this.nPointsY];
                    data[3] = new double[this.nPointsY];
                    for(int i=0; i 

Ads help maintain this website.