package Maths;

import java.lang.Math;

import java.util.* ;

import Ui.*;

public class Polynom extends Object implements java.io.Serializable {

 /** This class is the parent class from which all types of polynomials will be derived */


 int degree ;/** Holds the degree of the polynomial*/
	
 public double knots[][]  ;/**Holds the list of knots that form the intervals, together with their multiplicity**/

 protected double controlp[][] ;/**Holds the list of the 2-D coordinates of the controlpoints **/

 public double h[];// Holds the distance between the nodes/knots

 public int dimension = 2;//holds the dimension of the space

 public static int number_drawing_points = 100; //holds the number of requested drawing points

 protected int minimal_degree = 2; // holds the minimal degree from which we start to draw a curve
 
 public Curve curve; //holds a link to the curve object that this polynomial is related to




 public Polynom (){
 /*Constructor */
 }


 public Polynom (Vector controlpoints, int degree){

 /*Constructor
	input: the controlpoints in vector format ;
	       the degree;
	Last change:  TMC  20 Jan 98    2:25 pm
	*/


	/*we call the method that initialises the array format of the
	  controlpoints, the calculation of the knots/nodes and the setting of the degree*/
 	Init_Knots_ControlPoints_Degree(controlpoints) ;

 	this.degree = degree;

 }


 public double[][] GiveControlPoints(){

	return controlp;

 }

 public int GiveDimension(){

	return dimension;

 }

 public static void ChangeNrDrawPoints(int nr){

	number_drawing_points = nr;

 }




 public int Position(double val,double[] knotsset) {

   /**returns the index of the knot that is immediately smaller then the value,assumes the val 

      lies between the extremal values found in set

      input : the value;
	      the knotset wherein we are looking for tha value
      output : the index of the subinterval wherein the value lies

      **/

   int t = 0;

   while(t < knotsset.length && val >= knotsset[t]){t++;}; //we go to the next subinterval, untill the end or value fits

   if (t < knotsset.length){ return --t;}//we found a fitting interval, so return the first index of the interval

   else {return -1;};//we couldn't fit the value into a interval


 };
 



 protected  double Alpha(int i,int j, double val, double knotsset[]){
   /*calculates the coefficients that are used in the implementation of the deBoor scheme, must be overriden*/

   return val;

 };



 public double[][]  deBoor(double deboorpoints[], double val, double knotsset[] ){

   /**implements the deBoor scheme

      input: the deBoorpoints; the degree; 

             the value where you want to evaluate your polynom

      output: the full deBoor scheme	     

	Last change:  TMC  11 Jan 98    2:25 pm
      **/

   double A[][] = Init_Matrix(degree+1,degree+1);

   double alf;


   for(int i = 0; i <= degree; i++) A[i][0] = deboorpoints[i] ;

   /*the deBoor scheme*/

   for(int j = 1;j <= degree;j++){

     for(int i = j;i <= degree;i++){

       alf = this.Alpha(i,j,val,knotsset);

       A[i][j] = alf*A[i][j-1]+(1-alf)*A[i-1][j-1];

     };                           

   };
// pm(A);
  return A;

 }


 public void Init_Knots_ControlPoints_Degree(Vector controlpoints){

	/* This method calls upon the method that changes the format for the controlpoints from vector to array (I);
                       calls upon the method that sets the degree(II);
                       calls upon the method that calculates the position of the knots/nodes(III);
                       calls upon the method that calculates the position of the curvesegments(IV);


	   input : the controlpoints in vector format

	 */


	ControlPoints_vector2ControlPoints_array(controlpoints);//(I)

 	this.setDegree();//(II)

	(this.curve).setDegree(this.degree);//  the degree depends of the number of controlpoints

	if (degree >=1 && controlp[0].length > degree){ Parameterise();//(III)

        					        curve.curvesegmentpoints = CalculateCurvesegments();//(IV)
						      }

	else{int temparray[][] = new int [dimension][1];

			for ( int dim = 0; dim < dimension ; dim++ ){

				temparray[dim][0]=-1;

			};

	      curve.curvesegmentpoints = temparray;
        }

 }







 protected double[] Calculate_h ( double [][] controlpoints){

	/*  Calulates the distances beteween the positions of the nodes/knots
	    h[0] is the distance between knot[0] and knot[1]

	    input : the controlpoints

	    output : the array of distances

	      */


	final int EUCLIDIAN = 0;

	final int CENTRIPETAL = 1;

	final int ARCLENGTH = 2;

	final int CONSTANT = 3;

	int max = controlpoints[0].length-1 ;

	double distance ;

	double total_distance = 0.0;

	double h[] = new double[max];



	switch ( curve.GiveParamMode() ){

	case EUCLIDIAN : // here we take the euclidian distance between controlpoints c[i] and c[i-1] as distance h[i]

		for ( int i = 0; i < max ; i++ ){

			distance = 0.0;

			for ( int dim = 0; dim < dimension ; dim++ ){

				distance += Math.pow((controlpoints[dim][i+1] - controlpoints[dim][i]), 2);

			};


		       h[i] = Math.sqrt(distance);

		       total_distance+=h[i];

		}     ;


		break;


	case CENTRIPETAL : // here we take the the square of the euclidian distance between controlpoints c[i] and c[i-1]as distance h[i]

		for ( int i = 0; i < max ; i++ ){

			distance = 0.0;

			for ( int dim = 0; dim < dimension ; dim++ ){

				distance += Math.pow((controlpoints[dim][i+1] - controlpoints[dim][i]), 2);

			};

		       h[i] = Math.sqrt(Math.sqrt(distance));

		       total_distance+=h[i];

		}     ;

		break;

	case ARCLENGTH ://here we try to estimate the arclength as a measure for the distance
			// the algoritm used stems from 'Numerical algorithms with C', Springer-Verlag
		{
		 if (max >= 2){
			double s[][] = new double[max+2][dimension];

			double temp[][] = new double[max+2][dimension];

			double sigma = 1.3;


			temp = Transpose(controlpoints);

			for (int i = 1; i < max+1 ; i++ ){

				s[i] = VectorSum(temp[i],temp[i-1],(-1));

			}


			if ( curve.closed ){

				s[0] = s[max];

				s[max+1] = s[1];

			}

			else{

				s[0] = VectorSum(ScalarProduct(2.0,ScalarProduct((VectorProduct(s[1],s[2])/VectorProduct(s[1],s[1])),s[1])),s[2],(-1));

				s[max+1] = VectorSum(ScalarProduct(2.0,ScalarProduct((VectorProduct(s[max],s[max-1])/VectorProduct(s[max],s[max])),s[max])),s[max-1],(-1));

			}

			for ( int i = 1; i <= max ; i++ ){

				double s2[] = s[i-1];

				double t[] = VectorSum(s[i-1],s[i],1);

				double c = ComputeC(s2,t);

				s2 = VectorSum(s[i],s[i+1],1);

				t = s[i+1];

				c+= ComputeC(s2,t);

				h[i-1] = VectorNorm(s[i])*(1+sigma*(0.5*(c)-1));

		       total_distance+=h[i-1];

			}

		 }

	        }
	        break;


	case CONSTANT :// the knots.nodes are placed equidistantly

		distance = 1.0;
		for ( int i = 0; i < max ; i++ ){

			h[i] = distance;

		       total_distance+=h[i];

		};

	        break;

	}


	for ( int i = 0; i < max ; i++ ){ //normalisation of the interval

		h[i] /= total_distance;

	};

	return h;

 }


 public void Parameterise(){

       /* Searches a parameterisation for the curve,
          by callint the method Calculate_h we get the distance between the knots/nodes

	  input: the controlpoints in array form

	  output: the knots, the first knot has value 0, the last value 1
        */

	int max = controlp[0].length ;

	double total_distance = 0.0;

	knots = new double[2][max];

	h = Calculate_h(controlp);


	knots[0][0] = 0; //the first knot has value 0, and multiplicity 1

	knots[1][0] = 1;

	for ( int i = 1; i < max ; i++ ){

	       total_distance += h[i-1];

	       knots[0][i] = knots[0][i-1] + h[i-1];

	       knots[1][i] = 1;

	}


 }


 public double[]  Evaluate(double value){

   /**evaluates the Polynomial at value , using the deBoor scheme

      input: value of the parameter

      output: the 2-D coordinates of the point**/

   double dbpoints[]=new double[degree+1];

   double coor[]=new double[2];

   try {

	   for(int dim = 0; dim < dimension; dim++){

	     coor[dim]=deBoor(controlp[dim],value,knots[0])[degree][degree];

	   };


   }

   catch (NullPointerException e){ //should there be no knots available yet, more of an extra safety measure really

	   coor[0]=0.0;

	   coor[1]=0.0;

	   System.out.println(" no knots");

   }

   return coor;

 };



 // Now some methods for interfacing with the UI via the Curve class


 public int[][] GiveDrawPoints(Vector controlpoints){

// in UI control, this gets called (since Math doesn't provide for its controlpoints here, but gets them from UI)

    this.Init_Knots_ControlPoints_Degree(controlpoints);

    return this.GiveDrawPoints();

 }



 public int[][] GiveDrawPoints(){

    /* Calculates the drawing points, using the controlpoints in array format
       by evaluating the polynomial for different values 0:1/(number drawing points):1


	output :  the array of drawing points

     */

    int draw_points[][] = new int[dimension][number_drawing_points+1];

    double [] temp;

    for ( int i = 0 ; i <= number_drawing_points ; i++ ){

	    if ( degree >= minimal_degree ){// we satisfy the minimal degree condition

		 double getal = ((double)i)/number_drawing_points;

		 temp = Evaluate(getal);

	    }

	    else{// the degree is too small , so since we have to return something, we return zero

	        temp = new double[2];

		temp[0] = 0;
		temp[1] = 0;


	    };

	for ( int dim = 0; dim < dimension ; dim ++ ){

		draw_points[dim][i] = (int)temp[dim];

	}

    }


    return draw_points;

 }



public void ControlPoints_vector2ControlPoints_array(Vector controlpoints){

	/*This method changes the format of controlpoints from vector to array and stocks it into controlp,
	  multiple controlpoints in vector, are stored as seperate entries in the array !!

	  THIS IS THE ONLY METHOD IN POLYNOM THAT IS DEPENDENT ON THE DIMENSION OF THE PROBLEM,THAT YOU
	  CAN'T ALLEVIATE BY JUST CHANGING THE DIMENSION ATTRIBUTE !

	  input: the controlpoints in vector format
	  output: the controlpoints in array format

	*/

	int max = controlpoints.size();

	int max2 = max + (this.curve).additional_multiplicity;

	controlp = new double[dimension][max2];

	int cummulated = 0;// this is a kind of shift, that takes into account the sum
			   //of the multplicity of the multiple controlpoints
			   //that have already been added to the array


	for ( int i = 0; i < max ; i++ ){//for each vector controlpoint

		ControlPoint pnt = ((ControlPoint)(controlpoints.elementAt(i)));


		for (int j =1 ; j <= pnt.multiplicity;j++ ){//for every multiplicity >1, we create a controlp

			controlp[0][i+j-1+cummulated] = pnt.x;//DIMENSION dependency

			controlp[1][i+j-1+cummulated] = pnt.y;

		}

		cummulated += pnt.multiplicity-1;

	};

//pm(controlp);
}


 public int[][] CalculateCurvesegments(){
	/* calculates the coordinates of the boundaries of the
           curvesegments, here we have only one segment so the boundaries are the first and last controlpoints

	   output :the coordinates of the boundaries of the curvesegments */

 	double segm[][] = new double[dimension][2];


	for (int dim = 0; dim < dimension; dim++ ){

		segm[dim][0] = controlp[dim][0];

		segm[dim][1] = controlp[dim][controlp[0].length-1];
	}

        return Double2Int(segm);
 }


 public Polynom Clone(){

	return new Polynom();

 }



 protected void setDegree(){

     this.degree = controlp[0].length-1;

 }




 public boolean deg_change(int ch){

	curve.CalculateDrawPoints();

	return true;

 }


public void MoveControlPoints(int[] distance){

	/* changes the coordinates of the controlpoints, by moving them over a distance

	input : the distance

	 */

	int max = controlp[0].length;


	for ( int i = 0; i < max ; i++ ){

		for (int dim = 0; dim < dimension; dim++ ){

			controlp[dim][i] =controlp[dim][i] + distance[dim];

		}

	}


}



//some pre-(3D-API/java.media) mathematical support methods


 protected int[][] Double2Int(double [][] dmatr){

 /* Turns a double matrix into an integer matrix

     in : the double matrix dmatr

     out : the integer matrix , of the same dimensions as dmatr

  */

	int max1 = dmatr.length;

	int max2 = dmatr[0].length;

	int imatr[][] = new int[max1][max2];

	for ( int i = 0; i < max1 ; i++){

		for ( int j = 0; j < max2; j++ ){

			imatr[i][j] =(int) dmatr[i][j];

		}


	};

	return imatr;
  }





 protected double ComputeC(double s[], double t[]){

 /* calulates the C used in the Parameterisation method of arc length approximation */


	double z = VectorProduct(s,t);

	double n = VectorProduct(s,s)*VectorProduct(t,t);

	double S = Math.sqrt(1-Math.pow(z, 2)/n);

	if ( S == 0.0 ) {return 0.0;}

	else if ( S > 0.0 ){

			double gamma = Math.asin(S);

			if ( z < 0 ) gamma = Math.PI - gamma;

			return (S/gamma);

	     }
	 else {return 0.0;};

 }



 protected double[][]  Init_Matrix(int rows, int columns){

   /*initialises a matrix (rows x colums) to zero

     in : the numbers of required rows and columns

     out : a double zero matrix

   */



   double matrix[][] = new double[rows][columns];

   for(int i = 0;i < rows;i++)

     for(int j = 0;j < columns;j++) matrix[i][j] = 0;

   return matrix;

 };
 


 protected double VectorProduct(double one[],double two[]){

 /* calculates the vectorproduct

    in : 1xn double matrices one and two

    out : the vectorproduct of one and two

  */

	int max1 = one.length;

	int max2 = two.length;

	double p = 0.0; //the product

	double vpp = 0.0; //the sum holding positive values

	double vpn = 0.0; //the sum holding negative values

	if (max1 == max2  ){ //vectors must be of equal length

		for ( int i = 0; i < max1; i++ ){

			p = one[i]*two[i];

			if ( p >= 0 ){

			vpp+= p;

			}

			else{

			vpn+= p;

			}

		}

		return (vpp+vpn);

        }

	else{

	      System.out.println("not of equal length !");

	      return 0;
        }

 }



 protected double[] ScalarProduct(double scalar,double one[]){

 /* calculates the scalarproduct

    in : 1xn double matrix one and the double scalar scalar

    out : the vectorproduct of one and two

  */

	int max1 = one.length;

	double result[] = new double [max1];


	for ( int i = 0; i < max1; i++ ){

		result[i] = scalar * one[i];

	}

	return result;

 }



 protected double[] VectorSum(double one[],double two[], int sign){

	int max1 = one.length;

	int max2 = two.length;

	double sum[] = new double[max1];

	if (max1 == max2  ){

		for ( int i = 0; i < max1; i++ ){

			sum[i] = one[i] + (sign*two[i]);

		}

        }

	else{

	      System.out.println("not of equal length !");

        }

	return sum;

 }

 protected double[][] Transpose(double matrix[][]){

	int rows = matrix.length;

	int col = matrix[0].length;

	double tmatrix[][] = new double[col][rows];

	for (int i = 0 ; i < rows ;i++ ){

		for (int j = 0 ; j < col ; j++ ){

			tmatrix[j][i] = matrix[i][j];

		}

	}

	return tmatrix;
 }



 public double VectorNorm (double vector[]){

	 int max = vector.length;

	 double norm = 0.0;

	 for ( int i = 0; i < max ; i++ ){

    	       norm += Math.pow((vector[i]), 2);

	 }

	 norm = Math.sqrt(norm);

	 return norm;

 }






//some debugging printing methods

 public  void pm (double[][] matr){


	int max1 = matr.length;

	int max2 = matr[0].length;

	for ( int i =0;i<max1 ;i++ ){


		for ( int j = 0; j<max2 ;j++ ){

			System.out.print(matr[i][j]);

			System.out.print(" ");

		}

	System.out.println();


	};
	System.out.println();
	System.out.println();


}

 public  void pm (double[] matr){


	int max1 = matr.length;

	for ( int i =0;i<max1 ;i++ ){

			System.out.println(matr[i]);

			System.out.print(" ");


	};



 }


 public  void pm (int[][] matr){


	int max1 = matr.length;

	int max2 = matr[0].length;

	for ( int i =0;i<max1 ;i++ ){


		for ( int j = 0; j<max2 ;j++ ){

			System.out.print(matr[i][j]);

			System.out.print(" ");

		}

	System.out.println();


	};



 }


}
