import java.io.*;
import javax.swing.*;

      class yy extends f_xj
      {  
	  double xi[]; // independent variable data set
      double yi[]; //dependent variable data set
      double a[];  //fit function coefficient set
      int nn;
  	  public yy(String filename,double ia[])
      {
        //read the data to curvefit
        //get the data file and initial fit coefficient when class is defined
	    double[] Xi=new double[500];
        double[] Yi=new double[500];
        int n=ia.length;
        a=new double[n];
        seta(ia);
        int i=-1;
        try{
	    BufferedReader fin=new BufferedReader(new FileReader(filename));
        try {
        while(fin != null)
        {
        i++;
        Xi[i]=Text.readDouble(fin);
        Yi[i]=Text.readDouble(fin);
        }
        } catch(EOFException e_eof) {System.out.println("end of file"); }
        }catch(IOException e_io) {System.out.println("dosya bulunamadı"); }        
      nn=i;
      xi=new double[nn];
      yi=new double[nn];
      for(int j=0;j<nn;j++){xi[j]=Xi[j];yi[j]=Yi[j];}     
      a=ia;
      }
      
      public void seta(double ia[])
      {
	      //assign new fit coefficient set 
	      for(int ii=0;ii<nn;ii++)
              a[ii]=ia[ii];
	  }
	  public double[] geta()
      {
	     // return fit coefficient set
	     return a;
	  }
	  
	  double Cp(double T,double ai[])
      {a=ai;
      double R=8.3145;
      double A1=T/(ai[0]+T);
      double A2=ai[0]/(ai[0]+T);
      double cp=R*(ai[1]+(ai[2]-ai[1])*A1*A1*(1.0-A2*(ai[3]+ai[4]*A1+ai[5]*A1*A1+ai[6]*A1*A1*A1)));
      return cp; //kJ/kgK
      }      
      
      public double func(double ai[])
      {
      double ff=0;
      double w;
      double yy;
       for(int i=0;i<nn;i++)
	    {w= Cp(xi[i],ai)-yi[i];
        ff+=w*w;
	    }
      return ff;
	  }
}
public class nelder1
{
    public static void main(String args[]) throws IOException
    {
    String in_name=JOptionPane.showInputDialog(" veri dosyasının ismini giriniz : ");
    //String in_name="D1.txt";
    double a[];
    a=new double[7];
    a[0] = 1.0; 
    a[1] = 1.0;
    a[2] = 1.0; 
    a[3] = 1.0; 
    a[4] = 1.0; 
    a[5] = 1.0; 
    a[6] = 1.0;    
    double da[];
    da=new double[7];
    da[0] =0.3;
    da[1] =0.3;
    da[2] =0.3;
    da[3] =0.3;
    da[4] =0.3;
    da[5] =0.3;
    da[6] =0.3;
    yy f=new yy(in_name,a);
    int i=0;
    double p[]=nelder.nelder(f,a,da,1000,1e-15,0);
    String s1=" optimisation value  : \n"+Matrix.toStringT(p)+"\n";
    s1+="original function value = "+f.func(a)+"\n";
    s1+="function value = "+f.func(p)+"\n";
    s1+="standard division= "+Math.sqrt(f.func(p)/(f.nn-1));
    System.out.println(s1);
    Plot pp=new Plot(f.xi,f.yi);
    pp.setPlotType(0,20); 
    double y[]=new double[f.xi.length];
    for(i=0;i<f.xi.length;i++)
    {y[i]=f.Cp(f.xi[i],f.a);}
    pp.addData(f.xi,y);
    pp.plot();
    }

}
