/*
*   Class ImmunoAssay
*
*   Contains methods for fitting immunoassay results to a choice of equations,
*   for comparing the fit between equations and for obtaining the
*   analyte concentration for a given assay response
*
*   This class is a subclass of Regression
*
*   WRITTEN BY: Dr Michael Thomas Flanagan
*
*   DATE:	    20 January - 7 February 2011
*   MODIFIED:   17-28 February 2011, 1 March 2011, 11 March 2011, 30 March 2011, 1 April 2012
*
*   DOCUMENTATION:
*   See Michael Thomas Flanagan's Java library on-line web page:
*   http://www.ee.ucl.ac.uk/~mflanaga/java/ImmunoAssay.html
*   http://www.ee.ucl.ac.uk/~mflanaga/java/Regression.html
*   http://www.ee.ucl.ac.uk/~mflanaga/java/
*
* Copyright (c) 2011 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.physchem;

import flanagan.physchem.ImmunoChemistry;
import flanagan.math.Conv;
import flanagan.math.Fmath;
import flanagan.math.ArrayMaths;
import flanagan.analysis.Regression;
import flanagan.analysis.RegressionFunction;
import flanagan.analysis.RegressionFunction3;
import flanagan.analysis.Stat;
import flanagan.interpolation.CubicSpline;
import flanagan.interpolation.CubicInterpolation;
import flanagan.interpolation.LinearInterpolation;
import flanagan.plot.PlotGraph;
import flanagan.io.FileInput;
import flanagan.io.FileOutput;
import flanagan.io.FileChooser;
import flanagan.io.Db;

import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.io.File;


public class ImmunoAssay extends Regression{

    private double[] analyteConcns = null;                      // analyte concentrations
    private double[] log10AnalyteConcns = null;                 // log10(analyte concentrations)
    private double[] logeAnalyteConcns = null;                  // loge(analyte concentrations)
    private boolean analyteEntered = false;                     // = true when analyte concentrations have been entered
    private int analyteConcnFlag = 0;                           // = 0: analyte entered as analyte concentrations
                                                                // = 1: analyte entered as log10(analyte concentrations)
                                                                // = 2: analyte entered as loge(analyte concentrations)

    private int nAnalyteConcns = 0;                             // number of entered standard analyte concentrations

    private double[] responses = null;                          // standard curve responses
    private double[] log10Responses = null;                     // log10(standard curve responses)
    private double[] logeResponses = null;                      // loge(standard curve responses)
    private boolean responsesEntered = false;                   // = true when standard curve responses have been entered
    private int nResponses = 0;                                 // number of entered responses
    private int responsesFlag = 0;                              // = 0: responses entered as responses
                                                                // = 1: responses as log10(responses)
                                                                // = 2: responses as loge(responses)
    private boolean responsesPlot = true;                       // = false if log needed and responses are <= 0
    private double responsesMax = 0;                            // maximum response value
    private double responsesMin = 0;                            // minimum response value
    private double responsesRange = 0;                          // response value range

    private int nWeights = 0;                                   // number of entered weights
    private double weightsMean = 0.0;                           // mean of the weights
    private double weightsSD = 0.0;                             // standard deviation of the weights
    private int weightOption = 0;                               // = 0: no weights or weights as entered
                                                                // = 1: weights proportional to the responses
                                                                // = 2: weights proportional to the square root of the responses

    private boolean setDataOneDone = false;                     // = true when setDataOne has been successfully called

    private double[] interpolationConcns = null;                // analyte concentrations for standard curve responses after fitting or interpolation
    private double[] calculatedResponses = null;                // calculated standard curve responses after fitting or interpolation
    private String[] propagatedErrors = null;                   // propagated errors in the calculation of concentrations for given responses
    private int nInterp = 1000;                                 // number of points in the fitted or interpolation response curve

    private CubicSpline interp = null;                          // Cubic spline instance for getSampleConcn method
    private LinearInterpolation linterp = null;                 // LinearInterpolation instance for getSampleConcn method
    private CubicSpline errorp = null;                          // Cubic spline instance for getSampleConcn error method
    private CubicSpline cs = null;                              // Cubic spline instance for CubicSpline method
    private CubicInterpolation ci = null;                       // Cubic interpolation instance for CubicInterpolation method
    private LinearInterpolation li = null;                      // Linear interpolation instance for LinearInterpolation method

    private String titleZero = null;                            // Assay title
    private String titleOne = null;                             // Plot and print title - line two
    private String filename = "ImmunoAssayOutput.txt";          // Default output file name
    private String dataFilename = null;                         // Data input file name
    private boolean dataRead = false;                           // = true if data read from a file

    private double interpAnalyteStart = 0.0;                    // start of the non-ambiguous analyte concentration range of the fitted standard curve
    private double interpAnalyteEnd = 0.0;                      // end of the non-ambiguous analyte concentration range of the fitted standard curve
    private double interpResponseStart = 0.0;                   // start of the non-ambiguous range of the fitted standard curve
    private double interpResponseEnd = 0.0;                     // end of the non-ambiguous response range of the fitted standard curve
    private int interpStartIndex = 0;                           // index of the start of the non-ambiguous response range of the fitted standard curve
    private int interpEndIndex = 0;                             // index of the end of the non-ambiguous range of the fitted standard curve
    private boolean ambigCheck = false;                         // = true if the fitted standard curve is not monotonic
    private boolean curveDirection = true;                      // = true if the responses increase with increasing analyte concentration
                                                                // = false if the responses decrease with increasing analyte concentration
    private double workingResponseMin = 0.0;                    // minimum of the working range of the fitted standard curve
    private double workingResponseMax = 0.0;                    // maximum of the working range of the fitted standard curve
    private double minimumAerror = 0.0;                         // minimum propagated sample analyte concentration error
    private double maximumAerror = 0.0;                         // maximum propagated sample analyte concentration error
    private double meanAerror = 0.0;                            // mean propagated sample analyte concentration error
    private double sdAerror = 0.0;                              // standard deviation of the propagated sample analyte concentration error

    private int nTurningPoints = 0;                             // number of turning points in the standard curve
    private int[] turnIndices = null;                           // indices of turning points in the standard curve
    private int nWorking = 0;                                   // number of data points in the unambiguous range

    private int polyDegree = 0;                                 // degree of polynomial in polynomial fitting
    private int bestPolyDegree = 0;                             // degree of polynomial in best polynomial fitting
    private int polyNterms = 0;                                 // number of terms in the non-integer polynomial fitting

    private String compFilename = "ImmunoAssayComparison.txt";  // Default comparison output file name
    private int resultFlag = -1;                                // comparison result flag
    private double significance = 0.05;                         // probability significance level in statistical tests

    private double sampleResponse = 0.0;                        // last entered sample response of unkown concentration
    private double sampleConcn = 0.0;                           // analyte concn found for last entered sample response of unkown concentration
    private double sampleError = 0.0;                           // error of the analyte concn found for last entered sample response of unkown concentration

    private int nPlot = 0;                                      // Number of entered data points included in the plotting
    private int plotOptions = 0;                                // = 0: analyte concn v. response
                                                                // = 1: log10(analyte concn) v. response
                                                                // = 2: loge(analyte concn) v. response
                                                                // = 3: log10(analyte concn) v. log10(response)
    private boolean supressPlot = false;                        // = true: plot display supressed
                                                                // = 4: loge(analyte concn) v. loge(response)

    private int nMethods = 15;                                  // Number of methods available
    private String[] methodNames = new String[nMethods];        // Method names array
    private int[] methodIndices = new int[nMethods]; ;          // Indices linking methodUsed (below) to displayed names

    private int methodUsed = 8;                                 // Fitting or interpolation method used
                                                                // = 0:  Cubic spline
                                                                // = 1:  Cubic interpolation
                                                                // = 2:  Polynomial of user supplied degree n
                                                                // = 3:  Best fit polynomial
                                                                // = 4:  Non-integer polynomial
                                                                // = 5:  Sigmoid threshold function
                                                                // = 6:  Sips sigmoid function
                                                                // = 7:  Four parameter logistic function (EC50 dose response curve)
                                                                // = 8:  Five parameter logistic function
                                                                // = 9:  Shifted rectangular hyperbola
                                                                // = 10: Rectangular hyperbola
                                                                // = 11: Amersham equation
                                                                // = 12: Four parameter logistic function (top and bottom fixed)
                                                                // = 13: Five parameter logistic function (top and bottom fixed)
                                                                // = 14: Linear interpolation

    private boolean sampleErrorFlag = true;                    // = false if method cannot calculate a sample concentration err9or

    private boolean amershamFlag1 = true;                       // = true:  Amersham model initial estimates calculated
                                                                // = false: Amersham model initial estimates supplied

    private double bottom = 0.0;                                // Logistic fixed method bottom value
    private double top = 0.0;                                   // Logistic fixed method top value

    private boolean compWindow = false;                         // = true if comparison choice window used

    private String[] outliers = null;                           // list of outlier indicator messages
    private double residualsMean = 0.0;                         // mean of the unweighted residuals
    private double residualsSD = 0.0;                           // standard deviation of the unweighted residuals
    private double confidenceLevel = 0.95;                      // Confidence level of the confidence interval used on outlier testing
    // Outlier test critical values
    // Sample size
    private double[] critSize = {3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 30, 40, 50, 60, 100, 120};
    // 99% level
    private double[] critValuesOne = {1.15, 1.49, 1.75, 1.94, 2.10, 2.22, 2.32, 2.41, 2.55, 2.66, 2.71, 2.75, 2.82, 2.88, 3.10, 3.24, 3.34, 3.41, 3.60, 3.66};
    // 95% level
    private double[] critValuesFive = {1.15, 1.46, 1.67, 1.82, 1.94, 2.03, 2.11, 2.18, 2.29, 2.37, 2.41, 2.44, 2.50, 2.56, 2.74, 2.87, 2.96, 3.03, 3.21, 3.27};
    private CubicSpline critValues = null;                      // critical value interpolation function
    private double anscombeC = 0.0;                             // Calculated critical value
    private boolean outlierFlag = false;                        // = true if possible outliers found

    private boolean degSet = false;                             // = true if polynomial degree set
    private boolean nTermsSet = false;                          // = true if polynomial nterms set
    private boolean fourBotTopSet = false;                      // = true if four parameter top and bottom set
    private boolean fiveBotTopSet = false;                      // = true if five parameter top and bottom set


    // CONSTRUCTORS

    // Constructor without title
    public ImmunoAssay(){
        this.titleZero = "Program ImmunoAssay";
        super.supressErrorMessages = true;
        super.trueErrors = false;
        this.methodList();
    }

    // Constructor with title
    public ImmunoAssay(String title){
        this.titleZero = "Program ImmunoAssay: " + title;
        super.supressErrorMessages = true;
        super.trueErrors = false;
        this.methodList();
    }

    // Constructor without title
    // with total analyte concns and arbitrary unit responses entered
    public ImmunoAssay(double[] analytes, double[] responses){
        this.titleZero = "Program ImmunoAssay";
        this.nAnalyteConcns = analytes.length;
        this.analyteConcns = Conv.copy(analytes);
        this.analyteConcnFlag = 0;
        this.analyteEntered = true;
        this.nResponses = responses.length;
        this.responses = Conv.copy(responses);
        this.responsesFlag = 0;
        this.responsesEntered = true;
        super.xErrorsEntered = false;
        super.yErrorsEntered = false;
        super.supressErrorMessages = true;
        super.trueErrors = false;
        this.methodList();
    }

    // Constructor without title
    // with total analyte concns, arbitrary unit responses and weights entered
    public ImmunoAssay(double[] analytes, double[] responses, double[] yWeights){
        this.titleZero = "Program ImmunoAssay";
        this.nAnalyteConcns = analytes.length;
        this.analyteConcns = Conv.copy(analytes);
        this.analyteConcnFlag = 0;
        this.analyteEntered = true;
        this.nResponses = responses.length;
        this.responses = Conv.copy(responses);
        this.responsesFlag = 0;
        this.responsesEntered = true;
        this.nWeights = yWeights.length;
        super.yErrors = super.checkForZeroWeights(yWeights);
        if(super.weightOpt)super.weightFlag = 1;
        super.xErrorsEntered = false;
        super.yErrorsEntered = true;
        super.supressErrorMessages = true;
        super.trueErrors = false;
        this.methodList();
    }
    
    // Constructor without title
    // with total analyte concns, arbitrary unit responses and both analyte and response errors entered
    public ImmunoAssay(double[] analytes, double[] responses, double[] xWeights, double[] yWeights){
        this.titleZero = "Program ImmunoAssay";
        this.nAnalyteConcns = analytes.length;
        this.analyteConcns = Conv.copy(analytes);
        this.analyteConcnFlag = 0;
        this.analyteEntered = true;
        this.nResponses = responses.length;
        this.responses = Conv.copy(responses);
        this.responsesFlag = 0;
        this.responsesEntered = true;
        this.nWeights = yWeights.length;
        super.yErrors = yWeights;
        double[][] xErrors = new double[1][this.nWeights];
        xErrors[0] = xWeights;
        super.xErrors = xErrors;
        super.jointZeroCheck(xErrors, yWeights);
        if(super.weightOpt)super.weightFlag = 1;
        super.xErrorsEntered = true;
        super.yErrorsEntered = true;
        super.weightOpt = true;
        super.weightFlag = 1;
        super.supressErrorMessages = true;
        super.trueErrors = true;
        this.methodList();
    }

    // Constructor without title
    // with total analyte concns, arbitrary unit responses and weights entered
    public ImmunoAssay(double[] analytes, double[] responses, double[] yWeights, String title){
        this.titleZero = "Program ImmunoAssay: " + title;
        this.nAnalyteConcns = analytes.length;
        this.analyteConcns = Conv.copy(analytes);
        this.analyteConcnFlag = 0;
        this.analyteEntered = true;
        this.nResponses = responses.length;
        this.responses = Conv.copy(responses);
        this.responsesFlag = 0;
        this.responsesEntered = true;
        this.nWeights = yWeights.length;
        super.yErrors = super.checkForZeroWeights(yWeights);
        if(super.weightOpt)super.weightFlag = 1;
        super.xErrorsEntered = false;
        super.yErrorsEntered = true;
        super.supressErrorMessages = true;
        super.trueErrors = false;
        this.methodList();
    }
    
    // Constructor with title
    // with total analyte concns and arbitrary unit responses entered
    public ImmunoAssay(double[] analytes, double[] responses, String title){
        this.titleZero = "Program ImmunoAssay: " + title;
        this.nAnalyteConcns = analytes.length;
        this.analyteConcns = Conv.copy(analytes);
        this.analyteConcnFlag = 0;
        this.analyteEntered = true;
        this.nResponses = responses.length;
        this.responses = Conv.copy(responses);
        this.responsesFlag = 0;
        super.xErrorsEntered = false;
        super.yErrorsEntered = false;
        this.responsesEntered = true;
        super.supressErrorMessages = true;
        super.trueErrors = false;
        this.methodList();
    }

    // Constructor with title
    // with total analyte concns, arbitrary unit responses and yWeights entered
    public ImmunoAssay(double[] analytes, double[] responses, double[] xWeights, double[] yWeights, String title){
        this.titleZero = "Program ImmunoAssay: " + title;
        this.nAnalyteConcns = analytes.length;
        this.analyteConcns = Conv.copy(analytes);
        this.analyteEntered = true;
        this.analyteConcnFlag = 0;
        this.nResponses = responses.length;
        this.responses = Conv.copy(responses);
        this.responsesFlag = 0;
        this.responsesEntered = true;
        this.nWeights = yWeights.length;
        super.yErrors = yWeights;
        double[][] xErrors = new double[1][this.nWeights];
        xErrors[0] = xWeights;
        super.xErrors = xErrors;
        super.jointZeroCheck(xErrors, yWeights);
        super.xErrorsEntered = true;
        super.yErrorsEntered = true;
        super.weightOpt = true;
        super.weightFlag = 1;
        super.supressErrorMessages = true;
        super.trueErrors = true;
        this.methodList();
    }

    // Construct an indexed method list
    private void methodList(){

        // initialise method names and method name indices

        //      methodUsed
        //      = 0:  Cubic spline
        //      = 1:  Cubic interpolation
        //      = 2:  Polynomial of user supplied degree n
        //      = 3:  Best fit polynomial
        //      = 4:  Non-integer polynomial
        //      = 5:  Sigmoid threshold function
        //      = 6:  Sips sigmoid function
        //      = 7:  Four parameter logistic function (EC50 dose response curve)
        //      = 8:  Five parameter logistic function
        //      = 9:  Shifted rectangular hyperbola
        //      = 10: Rectangular hyperbola
        //      = 11: Amersham equation
        //      = 12: Four parameter logistic function (top and bottom fixed)
        //      = 13: Five parameter logistic function (top and bottom fixed)
        //      = 14: Linear interpolation

        this.methodNames[0] = "CubicSpline";
        this.methodIndices[0] = 0;
        this.methodNames[1] = "Five parameter logistic function";
        this.methodIndices[1] = 13;
        this.methodNames[2] = "Five parameter logistic function (top and bottom fixed)";
        this.methodIndices[2] = 6;
        this.methodNames[3] = "Four parameter logistic function";
        this.methodIndices[3] = 5;
        this.methodNames[4] = "Four parameter logistic function (top and bottom fixed)";
        this.methodIndices[4] = 7;
        this.methodNames[5] = "Best fit polynomial";
        this.methodIndices[5] = 8;
        this.methodNames[6] = "Polynomial of user supplied degree ";
        this.methodIndices[6] = 9;
        this.methodNames[7] = "Non-integer polynomial";
        this.methodIndices[7] = 3;
        this.methodNames[8] = "Sigmoid threshold function";
        this.methodIndices[8] = 1;
        this.methodNames[9] = "Sips sigmoid function";
        this.methodIndices[9] = 10;
        this.methodNames[10] = "Shifted rectangular hyperbola";
        this.methodIndices[10] = 11;
        this.methodNames[11] = "Rectangular hyperbola";
        this.methodIndices[11] = 12;
        this.methodNames[12] = "Amersham equation";
        this.methodIndices[12] = 4;
        this.methodNames[13] = "Cubic interpolation";
        this.methodIndices[13] = 2;
        this.methodNames[14] = "Linear interpolation";
        this.methodIndices[14] = 14;

    }

    // ENTER DATA METHODS

    // Enter standard analyte concentrations
    public void enterAnalyteConcns(double[] concn){
        this.setDataOneDone = false;
        this.nAnalyteConcns = concn.length;
        this.analyteConcns = Conv.copy(concn);
        this.analyteConcnFlag = 0;
        this.analyteEntered = true;
    }

    // Enter standard analyte concentrations as log10(concn)
    public void enterAnalyteConcnsAsLog10(double[] logconcn){
        this.setDataOneDone = false;
        this.nAnalyteConcns = logconcn.length;
        this.log10AnalyteConcns = Conv.copy(logconcn);
        this.analyteConcns = this.antiLog10(logconcn);
        this.analyteConcnFlag = 1;
        this.analyteEntered = true;
    }

    // Enter standard analyte concentrations as loge(concn)
    public void enterAnalyteConcnsAsLogE(double[] logconcn){
        this.setDataOneDone = false;
        this.nAnalyteConcns = logconcn.length;
        this.logeAnalyteConcns = Conv.copy(logconcn);
        this.analyteConcns = this.antiLoge(logconcn);
        this.analyteConcnFlag = 2;
        this.analyteEntered = true;
    }

    // Enter standard curve responses
    public void enterResponses(double[] responses){
        this.setDataOneDone = false;
        this.nResponses = responses.length;
        this.responses = Conv.copy(responses);
        this.responsesFlag = 0;
        this.responsesEntered = true;
    }

    // Enter standard curve responses as log10
    public void enterResponsesAsLog10(double[] responses){
        this.setDataOneDone = false;
        this.nResponses = responses.length;
        this.log10Responses = Conv.copy(responses);
        this.responses = this.antiLog10(responses);
        this.responsesFlag = 1;
        this.responsesEntered = true;
    }

    // Enter standard curve responses as loge
    public void enterResponsesAsLogE(double[] responses){
        this.setDataOneDone = false;
        this.nResponses = responses.length;
        this.logeResponses = Conv.copy(responses);
        this.responses = this.antiLoge(responses);
        this.responsesFlag = 2;
        this.responsesEntered = true;
    }

    // Enter weighting factors
    public void enterWeights(double[] yWeights){
        this.setDataOneDone = false;
        this.nWeights = yWeights.length;
        super.yErrors = super.checkForZeroWeights(yWeights);
        super.yErrorsEntered = true;
        if(super.weightOpt)super.weightFlag = 1;
    }

    // Enter weighting factors as log10
    public void enterWeightsAslog10(double[] yWeights){
        this.setDataOneDone = false;
        this.nWeights = yWeights.length;
        super.yErrors = this.antiLog10(super.checkForZeroWeights(yWeights));
        if(super.weightOpt)super.weightFlag = 1;
        super.yErrorsEntered = true;
    }

    // Enter weighting factors as loge
    public void enterWeightsAslogE(double[] yWeights){
        this.setDataOneDone = false;
        this.nWeights = yWeights.length;
        super.yErrors = this.antiLoge(super.checkForZeroWeights(yWeights));
        if(super.weightOpt)super.weightFlag = 1;
        super.yErrorsEntered = true;
    }

    // Convert multiplicative weighting factors to uncertainty estimate yWeights
    public void enterMultiplicativeWeights(double[] yWeights){
        this.setDataOneDone = false;
        this.nWeights = yWeights.length;
        super.yErrors = Conv.copy(super.checkForZeroWeights(yWeights));
        for(int i=0; i0){
            super.yErrors = new double[this.nResponses];
            for(int i=0; i0){
            super.yErrors = new double[this.nResponses];
            for(int i=0; i0){
                        pos3 = this.separatorPosition(line);
                        if(pos3==-1){
                            word = line.trim();
                        }
                        else{
                            word = (line.substring(0, pos3)).trim();
                        }
                        super.yErrors[i] = Double.parseDouble(word);
                        if(super.yErrors[i]==1.0)weightCheck++;
                     }
                }
            }
        }
        this.analyteConcnFlag = 0;
        this.analyteEntered = true;
        this.responsesEntered = true;
        if(weightCheck!=this.nAnalyteConcns){
            this.nWeights = this.nAnalyteConcns;
            super.yErrors = super.checkForZeroWeights(super.yErrors);
            if(super.weightOpt)super.weightFlag = 1;
            super.yErrorsEntered = true;
        }
        this.dataRead = true;
    }

    // Return entered analyte concentration
    public double[] getAnalyteConcns(){
        return this.analyteConcns;
    }

    // Return entered responses
    public double[] getResponses(){
        return this.responses;
    }


    // Return entered title
    public String getTitle(){
        return this.titleZero;
    }


    // INTERPOLATION METHODS

    // CubicSpline interpolation
    public void cubicSpline(){
        if(this.nAnalyteConcns<3)throw new IllegalArgumentException("Method cubicSpline requres at least 3 data points; only " + this.nAnalyteConcns + " were supplied");
        this.methodUsed = 0;
        this.sampleErrorFlag = false;
        this.titleOne = "Cubic spline ";
        if(!this.setDataOneDone)this.setDataOne();
        this.cs = new CubicSpline(this.analyteConcns, this.responses);
        for(int i=0; i al = super.bestPolynomial();
        this.bestPolyDegree = ((Integer)al.get(0)).intValue();
        this.titleOne += " " + this.bestPolyDegree;
        for(int i=0; i=this.nAnalyteConcns/2){
                if(this.responses[this.nAnalyteConcns-1]>=this.responses[0]){
                    throw new IllegalArgumentException("The data appears incompatible with a competitive assay");
                }
                else{
                    System.out.println("The data has been queried as that of a competitive assay but the fitting has not been aborted");
                }
            }
        }
    }


    // CHOOSE A FITTING EQUATION

    // Select a single fitting equation
    public void selectEquation(){

        ArrayList choice = chooseEquation(0);

        int choice0 = ((Integer)choice.get(0)).intValue();
        int choice1 = ((Integer)choice.get(1)).intValue();
        double choice2 = ((Double)choice.get(2)).doubleValue();
        double choice3 = ((Double)choice.get(3)).doubleValue();

        switch(choice0){
            case 1: this.fiveParameterLogisticFit();
                    break;
            case 2: this.fiveParameterLogisticFit(choice2, choice3);
                    break;
            case 3: this.fourParameterLogisticFit();
                    break;
            case 4: this.fourParameterLogisticFit(choice2, choice3);
                    break;
            case 5: this.bestPolynomialFit();
                    break;
            case 6: this.polynomialFit(choice1);
                    break;
            case 7: this.nonIntegerPolynomialFit(choice1);
                    break;
            case 8: this.sigmoidThresholdFit();
                    break;
            case 9: this.sipsSigmoidFit();
                    break;
            case 10: this.shiftedRectangularHyperbolaFit();
                    break;
            case 11: this.rectangularHyperbolaFit();
                    break;
            case 12: this.amershamFit();
                    break;
            case 13: this.cubicSpline();
                    break;
            case 14: this.linearInterpolation();
                    break;


        }
    }

    // Choose a fitting equation
    // flag = 0:  choice of a single equation
    // flag = 1:  first choice of a comparison
    // flag = 2:  second choice of a comparison
    private ArrayList chooseEquation(int flag){

        ArrayList ret = new ArrayList();
        String headerCommentP = null;
        String[] commentsP = null;
        String[] boxTitlesP = null;


        switch(flag){
            case 0: headerCommentP = "Choose a fitting equation";
                    commentsP = new String[15];
                    break;
            case 1: headerCommentP = "Choose the first equation of the comparison";
                    commentsP = new String[13];
                    break;
            case 2: headerCommentP = "Choose the second equation of the comparison";
                    commentsP = new String[13];
                    break;
        }
        commentsP[0] = "1.  Five paramater logistic equation";
        commentsP[1] = "2.  Five paramater logistic equation (top & bottom fixed)";
        commentsP[2] = "3.  Four paramater logistic equation";
        commentsP[3] = "4.  Four paramater logistic equation (top & bottom fixed)";
        commentsP[4] = "5.  Best fit polynomial";
        commentsP[5] = "6.  Polynomial of user supplied degree";
        commentsP[6] = "7.  Non-integer polynomial";
        commentsP[7] = "8.  Sigmoid threshold function";
        commentsP[8] = "9.  Sips sigmoid function";
        commentsP[9] = "10.  Shifted rectangular hyperbola";
        commentsP[10] = "11.  Rectangular hyperbola";
        commentsP[11] = "12.  Amersham mass action model";

        if(flag==0){
            commentsP[12] = "13.  Cubic spline";
            commentsP[13] = "14.  Linear interpolation\n\n";
            commentsP[14] = "Click on the appropriate button below";
            String[] hold1 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"};
            boxTitlesP = hold1;
        }
        else{
            commentsP[12] = "\nClick on the appropriate button below";
            String[] hold2 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
            boxTitlesP = hold2;
        }

        int defaultBoxP = 0;
        int ret0 = 1 + JOptionPane.showOptionDialog(null, commentsP, headerCommentP, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,null, boxTitlesP, boxTitlesP[defaultBoxP]);
        ret.add(new Integer(ret0));
        int ret1 = 0;
        if(ret0==6)ret1 = Db.readInt("enter polynomial degree");
        if(ret0==7)ret1 = Db.readInt("enter non-integer polynomial number of terms");
        ret.add(new Integer(ret1));
        double ret2 = 0.0;
        double ret3 = 0.0;
        if(ret0==2){
            ret2 = Db.readDouble("Enter five parameter logistic fixed bottom value");
            ret3 = Db.readDouble("Enter five parameter logistic fixed top value");
        }
        if(ret0==4){
            ret2 = Db.readDouble("Enter four parameter logistic fixed bottom value");
            ret3 = Db.readDouble("Enter four parameter logistic fixed top value");
        }
        ret.add(new Double(ret2));
        ret.add(new Double(ret3));

        return ret;
    }

    // SET SUPERCLASS VARIABLES AND DATA PREPARATION METHODS

    // Take logs to the base 10 of the analyte concentrations
    private double[] log10(double[] array){

        int n = array.length;
        double[] ret = new double[n];
        this.nPlot = this.nAnalyteConcns;
        for(int i=0; i1){
                double sumR = 0.0;
                double sumYW = 0.0;
                double sumXW = 0.0;
                for(int j=iFirst; j1)this.responsesPlot = false;
        }

        // log calculations
        // responses
        if(this.responsesPlot){
            switch(this.responsesFlag){
                case 0: this.log10Responses = this.log10(this.responses);
                        this.logeResponses = this.loge(this.analyteConcns);
                        break;
                case 1: this.logeResponses = this.loge(this.responses);
                        break;
                case 2: this.log10Responses = this.log10(this.responses);
                        break;
            }
        }

        // Supress warning messages in CubicSpline instances
        CubicSpline.supress();



        // Set arrays in super class
        double[][] xData = new double[1][this.nResponses];
        xData[0] = this.analyteConcns;
        if(super.xErrorsEntered){
            super.setDefaultValues(xData, this.responses, super.xErrors, super.yErrors);
        }
        else{
            super.setDefaultValues(xData, this.responses, super.yErrors);
        }
        
        // Maximum and minimum response values and range
        this.responsesMax = Fmath.maximum(this.responses);
        this.responsesMin = Fmath.minimum(this.responses);
        this.responsesRange = this.responsesMax - this.responsesMin;

        // Set interpolation or fitted curve array dimensions and analyte values
        this.setInterpolationData();

        // Set outlier critical value
        if(this.nAnalyteConcns<=3){
            this.anscombeC = this.critValuesFive[0];
        }
        else{
            if(this.nAnalyteConcns>=120){
                this.anscombeC = this.critValuesFive[19];
            }
            else{
                if(this.confidenceLevel==0.95){
                    this.critValues = new CubicSpline(critSize, critValuesFive);
                }
                else{
                    this.critValues = new CubicSpline(critSize, critValuesOne);
                }
                this.anscombeC = this.critValues.interpolate((double)this.nAnalyteConcns);
            }
        }

        this.setDataOneDone = true;
    }

    // Set outlier confidence level to 99%
    public void setNintyNineLevel(){
        this.confidenceLevel = 0.99;
    }

    // Set outlier confidence level to 95%
    public void setNintyFiveLevel(){
        this.confidenceLevel = 0.95;
    }



    // Set interpolation data arrays
    private void setInterpolationData(){
        this.interpolationConcns = new double[this.nInterp];
        this.calculatedResponses = new double[this.nInterp];
        double incr = (this.analyteConcns[this.nAnalyteConcns-1] - this.analyteConcns[0])/(this.nInterp - 1);
        this.interpolationConcns[0] = this.analyteConcns[0];
        for(int i=1; i4)throw new IllegalArgumentException("The plot option, " + opt + ", must be greater than or equal to 0 and less than 5");
        this.plotOptions = opt;
    }

    // Supress plotting
    private void supressPlot(){
        this.supressPlot = true;
    }

    // Unsupress plotting
    private void unsupressPlot(){
        this.supressPlot = false;
    }

    // plot the standard curve
    private int plott(){
            int returnFlag = 1;

            double[][] plotData = new double[4][];
            PlotGraph pg = null;
            switch(this.plotOptions){
                case 0: plotData[0] = this.analyteConcns;
                        plotData[1] = this.responses;
                        plotData[2] = this.interpolationConcns;
                        plotData[3] = this.calculatedResponses;
                        pg = new PlotGraph(plotData);
                        pg.setXaxisLegend("Analyte concentration (a)");
                        pg.setYaxisLegend("Assay response (r) ");
                        break;
                case 1: int nLen1 = this.nAnalyteConcns;
                        int nLen2 = this.nInterp;
                        if(nLen1!=this.nPlot){
                            nLen1=this.nPlot;
                            nLen2=this.nInterp-1;
                        }
                        plotData[0] = new double[nLen1];
                        plotData[1] = new double[nLen1];
                        plotData[2] = new double[nLen2];
                        plotData[3] = new double[nLen2];
                        if(nLen1!=this.nAnalyteConcns){
                            for(int i=1; imaxAbsResidual){
                maxAbsResidual = Math.abs(this.residual[i]);
                maxOutlierIndex = i;
            }
        }
        for(int i=0; ithis.anscombeC*this.residualsSD){
                this.outliers[i] = "possible outlier";
                if(i==maxOutlierIndex) this.outliers[i] += " (***)";
                this.outlierFlag = true;
            }
        }

        // Count number of turning points in standard curve
        int direction = 1;
        this.nTurningPoints = 0;
        boolean checkFlag = false;
        ArrayList turns = new ArrayList();
        double gap = calculatedResponses[1] - calculatedResponses[0];
        if(gap < 0.0)direction= -1;
        if(gap==0.0)checkFlag = true;
        for(int i=2; i=calculatedResponses[i-1])checkFlag = true;
            }
            if(checkFlag){
                this.nTurningPoints++;
                turns.add(new Integer(i));
                direction = -direction;
                this.ambigCheck = true;
                checkFlag = false;
            }
        }

        // calculate limited range for one turning point
        if(this.nTurningPoints==1){
            this.turnIndices = new int[1];
            this.turnIndices[0] = ((Integer)turns.get(0)).intValue();
            if(this.turnIndices[0]<=this.nInterp/2){
                this.interpStartIndex = this.turnIndices[0];
            }
            else{
                this.interpEndIndex  = this.turnIndices[0];
            }
            System.out.println(methodNames[mFlag]);
            System.out.println("The fitted or interpolated standard curve is not monotonic");
            System.out.println("The useable analyte concentration range is " +  this.interpolationConcns[this.interpStartIndex] + " to " +  this.interpolationConcns[this.interpEndIndex]);
        }

        // calculate limited range for two or more turning points
        if(this.nTurningPoints>1){

            this.turnIndices = new int[this.nTurningPoints];
            for(int i= 0; i=ntd[j])testMax++;
                    }
                }
                if(testMax==this.nTurningPoints){
                    this.interpStartIndex = nts[i];
                    this.interpEndIndex = nte[i];
                }
                else{
                    testMax = 0;
                }
                if(testMax!=0)break;
            }
            System.out.println(methodNames[mFlag]);
            System.out.println("The fitted or interpolated standard curve is not monotonic");
            System.out.println("The useable analyte concentration range is " +  this.interpolationConcns[this.interpStartIndex] + " to " +  this.interpolationConcns[this.interpEndIndex]);
        }

        // define usable range in the standard curve
        this.interpAnalyteStart = this.interpolationConcns[this.interpStartIndex];
        this.interpAnalyteEnd = this.interpolationConcns[this.interpEndIndex];
        this.interpResponseStart = this.calculatedResponses[this.interpStartIndex];
        this.interpResponseEnd = this.calculatedResponses[this.interpEndIndex];


        // Prepare response concn interpolation data within the working range
        this.nWorking = this.interpEndIndex - this.interpStartIndex + 1;
        double[] xx = new double[this.nWorking];
        double[] yy = new double[this.nWorking];
        for(int i=0; ithis.interpResponseEnd)this.curveDirection = false;

        // revisit working range
        this.workingResponseMin = Fmath.minimum(this.calculatedResponses);
        if(this.curveDirection){
            if(this.workingResponseMinthis.interpResponseEnd)this.workingResponseMax = this.interpResponseEnd;
        }
        else{
            if(this.workingResponseMax>this.interpResponseStart)this.workingResponseMax = this.interpResponseStart;
        }

        // Prepare response error concn interpolation data within the working range
        double[] ee = new double[this.nWorking];
        double yError = Math.sqrt(super.sumOfSquaresError/(this.nAnalyteConcns - super.nParam));

        if(this.sampleErrorFlag){
            if(!super.yErrorsEntered){
                for(int i=0; i=this.analyteConcns[i]){
                            iS = i;
                            breakFlag = true;
                        }
                        if(breakFlag)break;
                    }
                    breakFlag = false;
                    for(int i=this.nAnalyteConcns-1; i>=0; i--){
                        if(this.interpAnalyteEnd<=this.analyteConcns[i]){
                            iF = i;
                            breakFlag = true;
                        }
                        if(breakFlag)break;
                    }
                }
                int nwe = iF - iS + 1;
                double[] ew = new double[nwe];
                for(int i=0; igap0)gap0 = gap1;
                    }
                    if(gap0>0.6*Math.abs(Fmath.maximum(ew) - Fmath.minimum(ew)))monoCheck = false;
                }

                // scale weights to overall fitting variance
                double[] sWeights = new double[this.nAnalyteConcns];
                double scale = yError/this.weightsMean;
                for(int i=0; i alpe = new ArrayList();
            for(int i=0; ithis.interpResponseEnd)checkFlag2 = true;
                }
                else{
                    if(this.responses[i]>this.interpResponseStart || this.responses[i]this.interpResponseEnd)checkFlag = true;
        }
        else{
            if(response>this.interpResponseStart || responsethis.workingResponseMax)yErrorPlus=this.workingResponseMax;
            fac += (yErrorPlus - response)/yError;
            double xErrorPlus = this.interp.interpolate(yErrorPlus);
            this.sampleError = Math.abs(xErrorPlus - xErrorMinus)/fac;

        }

        return concn;
    }

    // return unknown analyte concentration error
    public double getSampleConcnError(){
        if(this.methodUsed==0){
            System.out.println("ImmunoAssay method: getSampleConcnError()");
            System.out.println("A sample concentration error is not meaningful in the case of a cubic spline interpolation");
            System.out.println("NaN returned");
        }
        if(this.methodUsed==1){
            System.out.println("ImmunoAssay method: getSampleConcnError()");
            System.out.println("A sample concentration error is not meaningful in the case of a cubic interpolation");
            System.out.println("NaN returned");
        }
        if(this.methodUsed==14){
            System.out.println("ImmunoAssay method: getSampleConcnError()");
            System.out.println("A sample concentration error is not meaningful in the case of a linear interpolation");
            System.out.println("NaN returned");
        }

        return this.sampleError;
    }

    // FITTED CURVE GET DETAILS AND RESET METHODS

    // Reset the number of points used in the interpolated standard curve
    public void resetNfittedCurve(int nInterp){
        this.nInterp = nInterp;
    }

    // Return the interpolated standard curve analyte concentrations
    public double[] getFittedStandardCurveConcns(){
        return Conv.copy(this.interpolationConcns);
    }

    // Return the interpolated standard curve analyte responses
    public double[] getFittedStandardCurveResponses(){
        return Conv.copy(this.calculatedResponses);
    }

    // Return the working analyte concentratio range of the standard curve
    public double[] getWorkingConcentrationRange(){
        double[] ret = {this.interpAnalyteStart, this.interpAnalyteEnd};
        return ret;
    }

    // Return the working response range of the standard curve
    public double[] getWorkingResponseRange(){
        double[] ret = {this.interpResponseStart, this.interpResponseEnd};
        return ret;
    }

    // Return the model parameter values
    public double[] getModelParameterValues(){
        return Conv.copy(super.best);
    }

    // Return the model parameter errors
    public double[] getModelParameterErrors(){
        return Conv.copy(super.bestSd);
    }

    // Return number of turning points in the standard curve
    public int getNumberOfTurningPoints(){
        return this.nTurningPoints;
    }

    // Return unweighted sum of squares
    public double getSumOfSquares(){
        return super.sumOfSquaresError;
    }

    // Return unweighted sum of squares
    public double getUnWeightedSumOfSquares(){
        return super.sumOfSquaresError;
    }

    // Return weighted sum of squares
    public double getWeightedSumOfSquares(){
        return super.chiSquare;
    }

    // Return analyte concentrations at the turning points in the standard curve
    public double[] getTurningPointConcns(){

        double[] ret = null;
        if(this.nTurningPoints>0){
            ret = new double[this.nTurningPoints];
            for(int i=0; i0){
            ret = new double[this.nTurningPoints];
            for(int i=0; i |t|");
            }
            else{
                fout.printtab(" ", super.field);
                fout.println("estimate");
            }

            if(super.invertFlag){
                fout.printtab(" ", super.field);
                fout.printtab(" ", super.field);
                fout.printtab(" ", super.field);
                fout.println("variation (%)");
            }
            else{
                fout.println("   ");
            }

            for(int i=0; i al1 = this.fittingForCompare(model1index, degree1, bottom1, top1, nTerms1, false);
        sumOfSquaresComp[0] = ((Double)al1.get(0)).doubleValue();
        nParamComp[0] =((Integer)al1.get(1)).intValue();
        methodNameComp[0] = (String)al1.get(2);

        // Fit to second equation
        if(!this.compWindow){
            if(model1index==2){
                bottom2 = Db.readDouble("Enter five parameter logistic bottom value");
                top2 = Db.readDouble("Enter five parameter logistic top value");
            }
            if(model1index==4){
                bottom2 = Db.readDouble("Enter four parameter logistic bottom value");
                top2 = Db.readDouble("Enter four parameter logistic top value");
            }
            if(model1index==6 && !this.degSet){
                degree2 = Db.readInt("Enter the polynomial degree");
            }
            if(model1index==7){
                nTerms2 = Db.readInt("Enter the non-integer polynomial number of terms");
            }
        }
        ArrayList al2 = this.fittingForCompare(model2index, degree2, bottom2, top2, nTerms2, true);
        sumOfSquaresComp[1] = ((Double)al2.get(0)).doubleValue();
        nParamComp[1] =((Integer)al2.get(1)).intValue();
        methodNameComp[1] = (String)al2.get(2);


        // Compare the goodness of fit to the two equations
        ArrayList al3 = ImmunoAssay.comparisonTest(modelXindices, sumOfSquaresComp[0], nParamComp[0], this.nAnalyteConcns, sumOfSquaresComp[1], nParamComp[1], this.nAnalyteConcns, significance);
        int resultFlag = ((Integer)al3.get(0)).intValue();
        int model1indexn = ((Integer)al3.get(1)).intValue();
        int model2indexn = ((Integer)al3.get(2)).intValue();
        double fRatio = ((Double)al3.get(3)).doubleValue();
        double fProb = ((Double)al3.get(4)).doubleValue();
        double fRatioAtSignificanceLevel = ((Double)al3.get(5)).doubleValue();
        int degreesOfFreedom1 = ((Integer)al3.get(6)).intValue();
        int degreesOfFreedom2 = ((Integer)al3.get(7)).intValue();
        if(model1indexn!=model1index){
            int holdI = nParamComp[0];
            nParamComp[0] = nParamComp[1];
            nParamComp[1] = holdI;
            double holdD = sumOfSquaresComp[0];
            sumOfSquaresComp[0] = sumOfSquaresComp[1];
            sumOfSquaresComp[1] = holdD;
            String holdS = methodNameComp[0];
            methodNameComp[0] = methodNameComp[1];
            methodNameComp[1] = holdS;
        }

        // Print the analysis to a text file
        int pos = filename.indexOf(".");
        if(pos==-1)filename = filename + ".txt";
        FileOutput fout = new FileOutput(filename);
        fout.println(this.titleZero);
        fout.println("Comparison of two fitting procedures");
        if(this.dataRead)fout.println("Data input file name " + dataFilename);
        fout.dateAndTimeln(filename);
        fout.println();
        fout.println("Equations compared:");
        fout.println("   Equation One: " + methodNameComp[0]);
        fout.println("   Equation Two: " + methodNameComp[1]);
        fout.println();

        fout.print("                    ", super.field);
        fout.print("Eqation", super.field);
        fout.println("Eqation");

        fout.print("                    ", super.field);
        fout.print("One", super.field);
        fout.println("Two");

        fout.print("Sum of squares      ", super.field);
        fout.print(Fmath.truncate(sumOfSquaresComp[0], super.prec), super.field);
        fout.println(Fmath.truncate(sumOfSquaresComp[1], super.prec));

        fout.print("Degrees of freedom  ", super.field);
        fout.print((this.nAnalyteConcns-nParamComp[0]), super.field);
        fout.println((this.nAnalyteConcns-nParamComp[1]));

        fout.println();

        switch(resultFlag){
            case 0: fout.printtab("Extra sum of squares F-ratio =                 ");
                    fout.println(Fmath.truncate(fRatio, super.prec));
                    fout.printtab("F-ratio probabilty =                           ");
                    fout.println(Fmath.truncate(fProb, super.prec));
                    fout.printtab("F value at the " + significance + " significance level = ");
                    fout.println(Fmath.truncate(fRatioAtSignificanceLevel, super.prec));
                    fout.println();
                    if(fProb<=significance){
                        fout.println("In terms of a best fit Equation Two is the preferred fit.");
                        if(Math.abs(nParamComp[1]-nParamComp[0])==1){
                            fout.println("The additional parameter has, given a " + significance + " significance level, significantly improved the fit.");
                        }
                        else{
                            fout.println("The additional parameters have, given a " + significance + " significance level, significantly improved the fit.");
                        }
                    }
                    else{
                        fout.println("In terms of a best fit Equation One is the preferred fit");
                        if(Math.abs(nParamComp[1]-nParamComp[0])==1){
                            fout.println("The additional parameter has not, given a " + significance + " significance level, significantly improved the fit.");
                        }
                        else{
                            fout.println("The additional parameters have not, given a " + significance + " significance level, significantly improved the fit.");
                        }
                    }
                   break;
            case 1: fout.println("The fittings to the two equations cannot be distinguished using an F-test analysis");
                    break;
            case 2: fout.printtab("Variance F-ratio =                            ");
                    fout.println(Fmath.truncate(fRatio, super.prec));
                    fout.printtab("F-ratio probabilty =                          ");
                    fout.println(Fmath.truncate(fProb, super.prec));
                    fout.printtab("F value at the " + significance + " significance level = ");
                    fout.println(Fmath.truncate(fRatioAtSignificanceLevel, super.prec));
                    fout.println();
                    if(fProb<=significance){
                        fout.println("In terms of a best fit Equation Two is the preferred fit");
                        fout.println("as indicated by the F-ratio analysis and a given significance level of " + significance);
                    }
                    else{
                        fout.println("The fittings to the two equations cannot be distinguished using an F-test analysis");
                    }
                    break;
        }
        fout.println("However, the choice of the model to be used as a standard curve should include, along with this comparison,");
        fout.println("observation of the displayed graphs and of the detailed analyses listed below");


        fout.println();
        fout.println();
        fout.println("Details of the two compared fitting exercises");
        fout.println();
        FileInput fin = new FileInput("ImmunoAssayTemp.txt");
        int n = fin.numberOfLines();
        String line = null;
        for(int i=0; i fittingForCompare(int index, int degree, double bottom, double top, int nTerms, boolean catFlag){

        ArrayList al = new ArrayList();
        String methodName = null;

        switch(index){
            case 1: this.fiveParameterLogisticFit();
                    methodName = this.methodNames[1];
                    break;
            case 2: this.fiveParameterLogisticFit(bottom, top);
                    methodName = methodNames[2];
                    break;
            case 3: this.fourParameterLogisticFit();
                    methodName = methodNames[3];
                    break;
            case 4: this.fourParameterLogisticFit(bottom, top);
                    methodName = methodNames[4];
                    break;
            case 5: this.bestPolynomialFit();
                    methodName = methodNames[5] + ": degree = " + this.bestPolyDegree;
                    break;
            case 6: this.polynomialFit(degree);
                    methodName = methodNames[6] + degree;
                    break;
            case 7: this.nonIntegerPolynomialFit(nTerms);
                    methodName = methodNames[7];
                    break;
            case 8: this.sigmoidThresholdFit();
                    methodName = methodNames[8];
                    break;
            case 9: this.sipsSigmoidFit();
                    methodName = methodNames[9];
                    break;
            case 10: this.shiftedRectangularHyperbolaFit();
                    methodName = methodNames[10];
                    break;
            case 11: this.rectangularHyperbolaFit();
                    methodName = methodNames[11];
                    break;
            case 12: this.amershamFit();
                    methodName = methodNames[12];
                    break;

            default: throw new IllegalArgumentException("Method number " + index + " not recognised");
        }

        // Output results to a temporary file
        FileOutput fout = null;
        String tempFileName = "ImmunoAssayTemp.txt";
        if(catFlag){
            fout = new FileOutput(tempFileName, 'a');
        }
        else{
            fout = new FileOutput(tempFileName);
        }
        this.commonPrint(fout);
        fout.println();
        fout.println();
        fout.close();

        // Return data to compare method
        al.add(new Double(super.chiSquare));
        al.add(new Integer(super.nParam));
        al.add(methodName);

        return al;
    }


    // Comparison test for two fitted models using F-ratio analysis
    public static ArrayList comparisonTest(int modelXindices[], double sumOfSquares1, int nParameters1, int nData1, double sumOfSquares2, int nParameters2, int nData2, double significance){

        ArrayList  al = new ArrayList();
        double fRatio = Double.NaN;
        double fProb = Double.NaN;
        double fRatioAtSignificanceLevel =  Double.NaN;
        double[] sumOfSquares = {sumOfSquares1, sumOfSquares2};
        int[] nParameters = {nParameters1, nParameters2};
        int[] nData = {nData1, nData2};
        int[] degreesOfFreedom = {(nData1 - nParameters1), (nData2 - nParameters2)};
        double[] variances = new double[2];
        double extraSumOfSquares = Double.NaN;
        int extraSumDegreesOfFreedom = 0;
        int extraDegreesOfFreedom = 0;
        int resultFlag = -1;

        if(nParameters1!=nParameters2 && nData1==nData2){
            // different number of parameters
            if(nParameters[0]>nParameters[1]){
                double holdD =sumOfSquares[0];
                sumOfSquares[0] = sumOfSquares[1];
                sumOfSquares[1] = holdD;
                int holdI = nParameters[0];
                nParameters[0] = nParameters[1];
                nParameters[1] = holdI;
                holdI = nData[0];
                nData[0] = nData[1];
                nData[1] = holdI;
                holdI = degreesOfFreedom[0];
                degreesOfFreedom[0] = degreesOfFreedom[1];
                degreesOfFreedom[1] = holdI;
                holdI = modelXindices[0];
                modelXindices[0] = modelXindices[1];
                modelXindices[1] = holdI;
            }
            if(sumOfSquares[0]>sumOfSquares[1]){
                // if sum of squares reduced with addition of extra parameters
                extraSumOfSquares = sumOfSquares[0] - sumOfSquares[1];
                extraSumDegreesOfFreedom = degreesOfFreedom[0] - degreesOfFreedom[1];
                fRatio =  extraSumOfSquares*degreesOfFreedom[1]/(extraSumDegreesOfFreedom*sumOfSquares[1]);
                fProb = Stat.fCompCDF(fRatio, extraSumDegreesOfFreedom, degreesOfFreedom[1]);
                fRatioAtSignificanceLevel =  Stat.fTestValueGivenFprob(significance, extraSumDegreesOfFreedom, degreesOfFreedom[1]);
                resultFlag = 0;
            }
        }
        if(resultFlag==-1){
            // identical number of parameters or non-reduced sum of squares on adding extra parameters or non-identical number of data points
            if(sumOfSquares[0]==sumOfSquares[1] && degreesOfFreedom[0]==degreesOfFreedom[1]){
                // equal number of degrees of freedom and sum of squares
                resultFlag = 1;
            }
            else{
                // different number of degrees of freedom and/or different sum of squares
                variances[0] = sumOfSquares[0]/degreesOfFreedom[0];
                variances[1] = sumOfSquares[1]/degreesOfFreedom[1];
                if(variances[0]<=variances[1]){
                    double holdD = variances[0];
                    variances[0] = variances[1];
                    variances[1] = holdD;
                    holdD =sumOfSquares[0];
                    sumOfSquares[0] = sumOfSquares[1];
                    sumOfSquares[1] = holdD;
                    int holdI = nParameters[0];
                    nParameters[0] = nParameters[1];
                    nParameters[1] = holdI;
                    holdI = nData[0];
                    nData[0] = nData[1];
                    nData[1] = holdI;
                    holdI = degreesOfFreedom[0];
                    degreesOfFreedom[0] = degreesOfFreedom[1];
                    degreesOfFreedom[1] = holdI;
                    holdI = modelXindices[0];
                    modelXindices[0] = modelXindices[1];
                    modelXindices[1] = holdI;
                }
                fRatio = variances[0]/variances[1];
                fProb = Stat.fCompCDF(fRatio, degreesOfFreedom[0], degreesOfFreedom[1]);
                fRatioAtSignificanceLevel =  Stat.fTestValueGivenFprob(significance, degreesOfFreedom[0], degreesOfFreedom[1]);
                resultFlag = 2;
            }
        }

        // return data to compare method
        al.add(new Integer(resultFlag));
        al.add(new Integer(modelXindices[0]));
        al.add(new Integer(modelXindices[1]));
        al.add(new Double(fRatio));
        al.add(new Double(fProb));
        al.add(new Double(fRatioAtSignificanceLevel));
        al.add(new Integer(degreesOfFreedom[0]));
        al.add(new Integer(degreesOfFreedom[1]));
        al.add(new Integer(nData[0]));
        al.add(new Integer(nData[1]));

        return al;
    }

    // Delete a file
    // used by compare method to delete a temporary file
    public void deleteFile(String fileName){

        // deletion flag
        boolean flag = true;

        // Create an instance of File representing the named file
        File file0 = new File(fileName);

        // Check that the file exists
        if(!file0.exists()){
            System.err.println("Method deleteFile: no file or directory of the name " + fileName + " found");
            flag = false;
        }

        // Check whether FileName is write protected
        if(flag && !file0.canWrite()){
            System.err.println("Method deleteFile: " + fileName + " is write protected and cannot be deleted");
            flag = false;
        }

        // Check, if fileName is a directory, that it is empty
        if(flag && file0.isDirectory()){
            String[] dirFiles = file0.list();
            if (dirFiles.length > 0){
                System.err.println("Method deleteFile: " + fileName + " is a directory which is not empty; no action was taken");
                flag = false;
            }
        }

        // Delete file
        if(flag){
            flag = file0.delete();
            if(!flag)System.err.println("Method deleteFile: deletion of the temporary file " + fileName + " failed");
        }
    }

    // ANCILLARY METHODS

    // Returns true if all x[i+1]>x[i] or all x[i+1]=0)y[1] = this.calcSquareWeight(p[0], p[1],  p[2], p[3], x[0], p[4], this.xErrors[0][ii], this.yErrors[ii]);
        return y;
    }

    // Calculate response
    public double calcResponse(double assocK, double labelF,  double antibodyF,  double nsbF, double analyteF, double scaleF){
        double term1 = assocK + labelF + analyteF;
        double numer = 2.0*antibodyF*(labelF - nsbF)/labelF;
        double denom = term1 + antibodyF + Math.sqrt(Fmath.square(term1 - antibodyF) + 4.0*assocK*antibodyF);
        double signal = scaleF*(numer/denom + nsbF/labelF);
        return signal;
    }
    
       // Calculate response
    public double calcSquareWeight(double assocK, double labelF,  double antibodyF,  double nsbF, double analyteF, double scaleF, double xError, double yError){
        double term0 = 2.0*antibodyF*(labelF - nsbF)/labelF;
        double term1 = assocK + labelF + analyteF;
        double term2 = Math.sqrt(Fmath.square(term1 - antibodyF) + 4.0*assocK*antibodyF);
        double term3 = 1.0 + (term1 - antibodyF)/term2;
        double numer = scaleF*term0*term3;      
        double denom = term1 + antibodyF + term2;
        denom *= denom;
        double deriv = numer/denom;
        return yError*yError + deriv*deriv*xError*xError;
    }
        
    public void setXerrors(double[][] xErrors){
        this.xErrors = xErrors;
    }
    
    public void setYerrors(double[] yErrors){
        this.yErrors = yErrors;
    }
}



 
 

Ads help maintain this website.