/**
 * void randn_mtx(double *mtx, int dim_i, int dim_j)
 * @brief Utility function to test the operations 
 * related to the generation of random normally
 * distributed numbers and to write these values
 * in a text file
**/
void test_randn(){
	int DIM_I = 900;
	int DIM_J=900;
	double sample;
	double *mtx;
	double *mean;
	int i,j;
	mtx = (double*)calloc(DIM_I*DIM_J,sizeof(double));
	mean = (double*)calloc(DIM_J,sizeof(double));

	/*Test to generated a normally distributed number*/
	sample = randn();
	printf("\n\n%lf\n",sample);
	
	/*Test to generate a matrix of normally distributed 
	 * random numbers*/
	randn_mtx(mtx,DIM_I,DIM_J);
	show_matrix(mtx,DIM_I,DIM_J);
	
	/*Test to modify the mean and the standard
	 * deviation of the matrix above*/
	modify_mean_stddev(mtx,5.0,2.0,DIM_I,DIM_J);
		
	printf("\n\n");
	show_matrix(mtx,DIM_I,DIM_J);
	
	/*Test to check if the values are written
	 * in the text file*/
	write_data(mtx,DIM_I,DIM_J);
	
	/*Test to see if the mean has been correctly
	 * modified*/
	stat_mean(mtx,mean,DIM_I,DIM_J);
	show_matrix(mean,1,DIM_J);
}
Ejemplo n.º 2
0
int main()
{
    int n = 3;
    std::vector<double> m1 = {25, 15, -5,
                              15, 18,  0,
                              -5,  0, 11};
    std::vector<double> c1 = cholesky(m1, n);
    #ifdef DEBUG
    show_matrix(c1, n);
    std::printf("\n");
    #endif
 
    n = 4;
    std::vector<double> m2 = {18, 22,  54,  42,
                              22, 70,  86,  62,
                              54, 86, 174, 134,
                              42, 62, 134, 106};
    std::vector<double> c2 = cholesky(m2, n);
    #ifdef DEBUG
    show_matrix(c2, n);
    std::printf("\n");
    #endif
 
    return 0;
}
void test_eigen_solver(void)
{
	int i = 0;
	int n = 3;
	int m = 3;

	double matrix_D[9] = {3.5712, 1.4007, 2.5214,
					      1.4007, 84.9129, 2.7030,
					      2.5214, 2.7030, 93.3993};
					      
	double lancz_trans_mtx[9];
	
	double a[3];
	double b[3];
	double eigvalues[3];
									  
	double exp_lancz_trans_mtx[9] = {65.0446, 40.8835, 0,
									 40.8835, 31.2460, 7.1235,
									 0, 7.1235, 85.5928};

	/*test lanczos procedure*/
	printf("Tm = lancz(D)'\n");
	printf("Matrix D'\n");	
	show_matrix(matrix_D, n, n);

	mtx_lanczos_procedure(matrix_D, a, b, n, m);
	
	
	/*construct tridiagonal matrix tm*/
	lancz_trans_mtx[0] = a[0];
	for(i=1;i<=m-1;i++){
		lancz_trans_mtx[i*m+i] = a[i]; 
		lancz_trans_mtx[i*m+i-m] = b[i-1]; 
		lancz_trans_mtx[i*m+(i-1)] = b[i-1]; 
	}
	
	printf("\n");
	printf("Expected Lanczos'\n");	
	show_matrix(exp_lancz_trans_mtx, m, m);
	printf("Obtained Lanczos'\n");	
	show_matrix(lancz_trans_mtx, m, m);
	
	/*call the MRRR routine*/
	mtx_mrrr(a, b, eigvalues, n);
	
	printf("\n");
	printf("expected eigvalues: 3.4789 84.1301 94.2744\n");	
	printf("obtained eigvalues: ");	
	
	for(i=0;i<3;i++){
		printf("%.4f ",eigvalues[i]);	
	}
	printf("\n\n");
	
}
Ejemplo n.º 4
0
/** 
 * Computes the validity lattice of a set of equalities. I.e., the lattice
 * induced on the last <tt>b</tt> variables by the equalities involving the
 * first <tt>a</tt> integer existential variables.  The submatrix of Eqs that
 * concerns only the existential variables (so the first a columns) is assumed
 * to be full-row rank.
 * @param Eqs the equalities
 * @param a the number of existential integer variables, placed as first
 * variables
 * @param vl the (returned) validity lattice, in homogeneous form. It is
 * allocated if initially set to null, or reused if already allocated.
 */
void Equalities_validityLattice(Matrix * Eqs, int a, Matrix** vl) {
  unsigned int b = Eqs->NbColumns-2-a;
  unsigned int r = Eqs->NbRows;
  Matrix * A=NULL, * B=NULL, *I = NULL, *Lb=NULL, *sol=NULL;
  Matrix *H, *U, *Q;
  unsigned int i;

  if (dbgCompParm) {
    printf("Computing validity lattice induced by the %d first variables of:"
	   ,a);
    show_matrix(Eqs);
  }
  if (b==0) {
    ensureMatrix((*vl), 1, 1);
    value_set_si((*vl)->p[0][0], 1);
    return;
  }

  /* 1- check that there is an integer solution to the equalities */
  /* OPT: could change integerSolution's profile to allocate or not*/
  Equalities_integerSolution(Eqs, &sol);
  /* if there is no integer solution, there is no validity lattice */
  if (sol==NULL) {
    if ((*vl)!=NULL) Matrix_Free(*vl);
    return;
  }
  Matrix_subMatrix(Eqs, 0, 1, r, 1+a, &A);
  Matrix_subMatrix(Eqs, 0, 1+a, r, 1+a+b, &B);
  linearInter(A, B, &I, &Lb);
  Matrix_Free(A);
  Matrix_Free(B);
  Matrix_Free(I);
  if (dbgCompParm) {
    show_matrix(Lb);
  }
  
  /* 2- The linear part of the validity lattice is the left HNF of Lb */
  left_hermite(Lb, &H, &Q, &U);
  Matrix_Free(Lb);
  Matrix_Free(Q);
  Matrix_Free(U);

  /* 3- build the validity lattice */
  ensureMatrix((*vl), b+1, b+1);
  Matrix_copySubMatrix(H, 0, 0, b, b, (*vl), 0,0);
  Matrix_Free(H);
  for (i=0; i< b; i++) {
    value_assign((*vl)->p[i][b], sol->p[0][a+i]);
  }
  Matrix_Free(sol);
  Vector_Set((*vl)->p[b],0, b);
  value_set_si((*vl)->p[b][b], 1);
  
} /* validityLattice */
Ejemplo n.º 5
0
/** 
 * Computes the intersection of two linear lattices, whose base vectors are
 * respectively represented in A and B.
 * If I and/or Lb is set to NULL, then the matrix is allocated. 
 * Else, the matrix is assumed to be allocated already. 
 * I and Lb are rk x rk, where rk is the rank of A (or B).
 * @param A the full-row rank matrix whose column-vectors are the basis for the
 * first linear lattice.
 * @param B the matrix whose column-vectors are the basis for the second linear
 * lattice.
 * @param Lb the matrix such that B.Lb = I, where I is the intersection.
 * @return their intersection.
 */
static void linearInter(Matrix * A, Matrix * B, Matrix ** I, Matrix **Lb) {
  Matrix * AB=NULL;
  int rk = A->NbRows;
  int a = A->NbColumns;
  int b = B->NbColumns;
  int i,j, z=0;

  Matrix * H, *U, *Q;
  /* ensure that the spanning vectors are in the same space */
  assert(B->NbRows==rk);
  /* 1- build the matrix 
   * (A 0 1)
   * (0 B 1)
   */
  AB = Matrix_Alloc(2*rk, a+b+rk);
  Matrix_copySubMatrix(A, 0, 0, rk, a, AB, 0, 0);
  Matrix_copySubMatrix(B, 0, 0, rk, b, AB, rk, a);
  for (i=0; i< rk; i++) {
      value_set_si(AB->p[i][a+b+i], 1);
      value_set_si(AB->p[i+rk][a+b+i], 1);
  }
  if (dbgCompParm) {
    show_matrix(AB);
  }

  /* 2- Compute its left Hermite normal form. AB.U = [H 0] */
  left_hermite(AB, &H, &Q, &U);
  Matrix_Free(AB);
  Matrix_Free(Q);
  /* count the number of non-zero colums in H */ 
  for (z=H->NbColumns-1; value_zero_p(H->p[H->NbRows-1][z]); z--);
  z++;
  if (dbgCompParm) {
    show_matrix(H);
    printf("z=%d\n", z);
  }
  Matrix_Free(H);
  /* if you split U in 9 submatrices, you have: 
   * A.U_13 = -U_33
   * B.U_23 = -U_33,
   * where the nb of cols of U_{*3} equals the nb of zero-cols of H
   * U_33 is a (the smallest) combination of col-vectors of A and B at the same
   * time: their intersection.
  */
  Matrix_subMatrix(U, a+b, z, U->NbColumns, U->NbColumns, I);
  Matrix_subMatrix(U, a, z, a+b, U->NbColumns, Lb);
  if (dbgCompParm) {
    show_matrix(U);
  }
  Matrix_Free(U);
} /* linearInter */
Ejemplo n.º 6
0
/** 
 * Given a full-row-rank nxm matrix M made of m row-vectors), computes the
 * basis K (made of n-m column-vectors) of the integer kernel of the rows of M
 * so we have: M.K = 0
*/
Matrix * int_ker(Matrix * M) {
  Matrix *U, *Q, *H, *H2, *K=NULL;
  int i, j, rk;

  if (dbgCompParm)
    show_matrix(M);
  /* eliminate redundant rows : UM = H*/
  right_hermite(M, &H, &Q, &U);
  for (rk=H->NbRows-1; (rk>=0) && Vector_IsZero(H->p[rk], H->NbColumns); rk--);
  rk++;
  if (dbgCompParmMore) {
    printf("rank = %d\n", rk);
  }
    
  /* there is a non-null kernel if and only if the dimension m of 
     the space spanned by the rows 
     is inferior to the number n of variables */
  if (M->NbColumns <= rk) {
    Matrix_Free(H);
    Matrix_Free(Q);
    Matrix_Free(U);
    K = Matrix_Alloc(M->NbColumns, 0);
    return K;
  }
  Matrix_Free(U); 
  Matrix_Free(Q);
  /* fool left_hermite  by giving NbRows =rank of M*/
  H->NbRows=rk;
  /* computes MU = [H 0] */
  left_hermite(H, &H2, &Q, &U); 
   if (dbgCompParmMore) {
    printf("-- Int. Kernel -- \n");
    show_matrix(M);
    printf(" = \n");
    show_matrix(H2);
    show_matrix(U); 
  }
  H->NbRows==M->NbRows;
  Matrix_Free(H);
  /* the Integer Kernel is made of the last n-rk columns of U */
  Matrix_subMatrix(U, 0, rk, U->NbRows, U->NbColumns, &K);

  /* clean up */
  Matrix_Free(H2);
  Matrix_Free(U);
  Matrix_Free(Q);
  return K;
} /* int_ker */
Ejemplo n.º 7
0
int main(void)
{
	int i;
	double m[15];
	for (i = 0; i < 15; i++) m[i] = i + 1;
 
	puts("before transpose:");
	show_matrix(m, 3, 5);
 
	transpose(m, 3, 5);
 
	puts("\nafter transpose:");
	show_matrix(m, 5, 3);
 
	return 0;
}
/**
 * void test_stats()
 * @brief Utility function to test the functions related to basic operations on matrixes
*/
void test_stats(){
	
	int DIM_I = 6;
	int DIM_J=6;
	double a[36]= {	3.5712, 1.4007, 2.5214,35.7680,12.5698,34.5678,
					1.4007, 84.9129, 2.7030, 64.5638,4.5645,56.4523,
					2.5214, 2.7030, 93.3993,32.4563,56.4322,24.4678,
					35.7680,64.5638,32.4563,43.2345,21.3456,32.5476,
					12.5698,4.5645,56.4322,21.3456,78.4356,65.4356,
					34.5678,56.4523,24.4678,32.5476,65.4356,21.4567
				  };
				
	double *mean = (double*)calloc(sizeof(double),DIM_J);
	double *b = (double*)calloc(sizeof(double),(DIM_J*DIM_I));
	
	
	//Shows the original matrix
	show_matrix(a,DIM_I,DIM_J);
	
	
	//Calculates the mean of the columns of the original matrix
	stat_mean(a,mean,DIM_I,DIM_J);
	
	//Shows the expected mean matrix
	printf("\nexpected mean matrix \n"
	"15.06650 35.76620 35.33000 38.31930 39.79720 39.15460");
	
	//Shows the mean matrix calculated
	printf("\n\nMean matrix \n");
	show_matrix(mean,1,DIM_J);
	
	//Shows the expected matrix with the mean removed
	printf("\nExpected matrix with the mean removed\n"
	"-11.49528 -34.36550 -32.80860 -2.55130 -27.22742 -4.58683\n"
	"-13.66578 49.14670 -32.62700 26.24450 -35.23272 17.29767\n"
	"-12.54508 -33.06320 58.06930 -5.86300 16.63498 -14.68683\n"
	"20.70152 28.79760 -2.87370 4.91520 -18.45162 -6.60703\n"
	"-2.49668 -31.20170 21.10220 -16.97370 38.63838 26.28097\n"
	"19.50132 20.68610 -10.86220 -5.77170 25.63838 -17.69793\n");
	
	//Calculates the matrix with the mean removed
	remove_mean_col(b,a,mean,DIM_I,DIM_J);
	
	//Shows the mean with the matrix removed	
	printf("\n Derivation from the mean matrix \n");
	show_matrix(b,DIM_I,DIM_J);
}
void test_basic_mtx_op(void)
{
	
	/******************************/
	/* Test the matrix operations */
	/******************************/
	int dim_i = 3;
	int dim_j = 3;
	int dim_k = 4;
	double matrix_A[9] = {0.9572, 0.1419, 0.7922,
						  0.4854, 0.4218, 0.9595,
						  0.8003, 0.9157, 0.6557};
	double matrix_B[12] = {0.8147, 0.9134, 0.2785, 0.9649,
						   0.9058, 0.6324, 0.5469, 0.1576,
						   0.1270, 0.0975, 0.9575, 0.9706};

	double matrix_D[9] = {3.5712, 1.4007, 2.5214,
					      1.4007, 84.9129, 2.7030,
					      2.5214, 2.7030, 93.3993};						   
						   
	double matrix_C[12];
	double matrix_B_prime[12];
	double matrix_L[9];
	double matrix_L_prime[9];
	double result = 0.0;	

	printf("Show Matrix A\n");	
	show_matrix(matrix_A, dim_i, dim_j);	
	printf("Show Matrix B\n");	
	show_matrix(matrix_B, dim_j, dim_k);	

	/*test for matrix multiplication*/
	printf("C = A * B\n");	
	mtx_mult(matrix_A, matrix_B, matrix_C, dim_i, dim_j, dim_k);
	show_matrix(matrix_C, dim_i, dim_k);	
	
	/*test for matrix transpose*/
	printf("B' = B\n");
	mtx_transpose(matrix_B, matrix_B_prime, dim_j, dim_k);	
	show_matrix(matrix_B_prime, dim_k, dim_j);	

	/*test for cholesky decomposition*/
	printf("Show Symmetric Matrix D\n");
	show_matrix(matrix_D, dim_i, dim_j);	
	
	printf("L = chol(D)\n");	
	mtx_chol(matrix_D, matrix_L, dim_i);
	show_matrix(matrix_L, dim_i, dim_i);
	
	printf("D = L*L'\n");	
	mtx_transpose(matrix_L, matrix_L_prime, dim_i, dim_i);	
	mtx_mult(matrix_L, matrix_L_prime, matrix_D, dim_i, dim_i, dim_i);
	show_matrix(matrix_D, dim_i, dim_i);

	/*test validation tag*/
	printf("Matrix test results validated using Matlab: \n");
	printf("All good! 05/15, FS\n");	
	
}
Ejemplo n.º 10
0
Archivo: covwt.c Proyecto: cran/teigen
int main(void) {
	// example numbers for calculating mycovwt
	double x[] = {1,2,3,4,5,6,7,8};
	//dimensions of x
	int r = 4; 
	int c = 2; 
	double wt[] = {56,57,58,59};
	double center[] = {1.23, 4.56};
	
	double* rv = (double*)calloc(c*c, sizeof(double));
	
	mycovwt(x, &r, &c, wt, center, &c, rv);
	show_matrix(rv, c, c);
	
	// should be (calculated in R):
	double correct[] = {2.91812 , 3.78358 , 3.78358 , 5.09795};
	printf("\n\nThe correct matrix should be:\n");
	show_matrix(correct, c, c);
	
	free(rv);
	return 0;
}
Ejemplo n.º 11
0
void main()
{
	int A[SIZE][SIZE] = {
		{5, 1},
		{2, 3}
	};
	int B[SIZE][SIZE] = {
		{3, 4},
		{6, 9}
	};
	int C[SIZE][SIZE];
	subtract2matrix(A, B, C);
	show_matrix(C);

}
Ejemplo n.º 12
0
/**
 * Given a matrix that defines a full-dimensional affine lattice, returns the 
 * affine sub-lattice spanned in the k first dimensions.
 * Useful for instance when you only look for the parameters' validity lattice.
 * @param lat the original full-dimensional lattice
 * @param subLat the sublattice
 */
void Lattice_extractSubLattice(Matrix * lat, unsigned int k, Matrix ** subLat) {
  Matrix * H, *Q, *U, *linLat = NULL;
  unsigned int i;
  dbgStart(Lattice_extractSubLattice);
  /* if the dimension is already good, just copy the initial lattice */
  if (k==lat->NbRows-1) {
    if (*subLat==NULL) {
      (*subLat) = Matrix_Copy(lat);
    }
    else {
      Matrix_copySubMatrix(lat, 0, 0, lat->NbRows, lat->NbColumns, (*subLat), 0, 0);
    }
    return;
  }
  assert(k<lat->NbRows-1);
  /* 1- Make the linear part of the lattice triangular to eliminate terms from 
     other dimensions */
  Matrix_subMatrix(lat, 0, 0, lat->NbRows, lat->NbColumns-1, &linLat);
  /* OPT: any integer column-vector elimination is ok indeed. */
  /* OPT: could test if the lattice is already in triangular form. */
  left_hermite(linLat, &H, &Q, &U);
  if (dbgCompParmMore) {
    show_matrix(H);
  }
  Matrix_Free(Q);
  Matrix_Free(U);
  Matrix_Free(linLat);
  /* if not allocated yet, allocate it */
  if (*subLat==NULL) {
    (*subLat) = Matrix_Alloc(k+1, k+1);
  }
  Matrix_copySubMatrix(H, 0, 0, k, k, (*subLat), 0, 0);
  Matrix_Free(H);
  Matrix_copySubMatrix(lat, 0, lat->NbColumns-1, k, 1, (*subLat), 0, k);
  for (i=0; i<k; i++) {
    value_set_si((*subLat)->p[k][i], 0);
  }
  value_set_si((*subLat)->p[k][k], 1);
  dbgEnd(Lattice_extractSubLattice);
} /* Lattice_extractSubLattice */
void test_pca(void){
	
	
	int DIM_I = 6;
	int DIM_J=6;
	int i;
	double a[36]= {	3.5712, 1.4007, 2.5214,35.7680,12.5698,34.5678,
					1.4007, 84.9129, 2.7030, 64.5638,4.5645,56.4523,
					2.5214, 2.7030, 93.3993,32.4563,56.4322,24.4678,
					35.7680,64.5638,32.4563,43.2345,21.3456,32.5476,
					12.5698,4.5645,56.4322,21.3456,78.4356,65.4356,
					34.5678,56.4523,24.4678,32.5476,65.4356,21.4567
					};
	double lancz_trans_mtx[36];				
	double *mean = (double*)calloc(sizeof(double),DIM_J);
	double *b = (double*)calloc(sizeof(double),(DIM_J*DIM_I));
	double *b_prime = (double*)calloc(sizeof(double),(DIM_J*DIM_I));
	double *cov= (double*)calloc(sizeof(double),(DIM_J*DIM_I));
	double *eigenvalues=(double*)calloc(sizeof(double),(DIM_J));
	double *Identity = (double*)calloc(sizeof(double),(DIM_J*DIM_I));
	double *mtx_diag= (double*)calloc(sizeof(double),(DIM_J*DIM_I));
	double *mtx_off_diag= (double*)calloc(sizeof(double),(DIM_J*DIM_I));
	double *ident_eigen= (double*)calloc(sizeof(double),(DIM_J*DIM_I));
	show_matrix(a,DIM_I,DIM_J);
	
	
		
	stat_mean(a,mean,DIM_I,DIM_J);
	
	printf("\nexpected mean matrix \n"
	"15.06650 35.76620 35.33000 38.31930 39.79720 39.15460");
	printf("\n\nMean matrix \n");
	
	show_matrix(mean,1,DIM_J);
	printf("\nexpected derivation from the mean matrix\n"
	"-11.49528 -34.36550 -32.80860 -2.55130 -27.22742 -4.58683\n"
	"-13.66578 49.14670 -32.62700 26.24450 -35.23272 17.29767\n"
	"-12.54508 -33.06320 58.06930 -5.86300 16.63498 -14.68683\n"
	"20.70152 28.79760 -2.87370 4.91520 -18.45162 -6.60703\n"
	"-2.49668 -31.20170 21.10220 -16.97370 38.63838 26.28097\n"
	"19.50132 20.68610 -10.86220 -5.77170 25.63838 -17.69793\n");
			
	printf("\n Derivation from the mean matrix \n");
	
	mtx_deriv_mean(b,a,mean,DIM_I,DIM_J);
	show_matrix(b,DIM_I,DIM_J);
	printf("\n");

	printf("Expected transpose matrix \n""-11.49528 -13.66578 -12.54508 20.70152 -2.49668 19.50132\n" 
"-34.36550 49.14670 -33.06320 28.79760 -31.20170 20.68610\n" 
"-32.80860 -32.62700 58.06930 -2.87370 21.10220 -10.86220\n" 
"-2.55130 26.24450 -5.86300 4.91520 -16.97370 -5.77170\n" 
"-27.22742 -35.23272 16.63498 -18.45162 38.63838 25.63838\n" 
"-4.58683 17.29767 -14.68683 -6.60703 26.28097 -17.69793\n"); 
	printf("\n\n Transpose matrix \n");
	
	mtx_transpose(b,b_prime,DIM_I,DIM_J);
	show_matrix(b_prime,DIM_J,DIM_I);
	
	printf("\nExpected multiplication prior to covariance matrix (b*b')\n"
	"3158.41375 351.58407 -995.33304 -613.17658 -720.63631 -1180.85189\n" 
"351.58407 5896.00026 -4342.15094 1890.97606 -3540.04502 -256.36445\n" 
"-995.33304 -4342.15094 5149.39843 -1617.44056 2644.62062 -839.09450\n" 
"-613.17658 1890.97606 -1617.44056 1674.38695 -1980.86959 646.12372\n"
"-720.63631 -3540.04502 2644.62062 -1980.86959 3896.80272 -299.87242\n" 
"-1180.85189 -256.36445 -839.09450 646.12372 -299.87242 1930.05954\n");
	
	printf("\n\n Multiplication prior to covariance matrix (b*b')\n");
	
	mtx_mult(b,b_prime,cov,DIM_I,DIM_J,DIM_I);
	show_matrix(cov,DIM_I,DIM_I);
	
	for (i=0;i<DIM_I*DIM_I;i++)
		cov[i] /= DIM_I;
	
	printf("\nExpected covarianc matrix\n"
	"526.40229 58.59735 -165.88884 -102.19610 -120.10605 -196.80865\n" 
"58.59735 982.66671 -723.69182 315.16268 -590.00750 -42.72741\n" 
"-165.88884 -723.69182 858.23307 -269.57343 440.77010 -139.84908\n" 
"-102.19610 315.16268 -269.57343 279.06449 -330.14493 107.68729\n" 
"-120.10605 -590.00750 440.77010 -330.14493 649.46712 -49.97874\n" 
"-196.80865 -42.72741 -139.84908 107.68729 -49.97874 321.67659\n");

	printf("\nCovariance matrix\n");
	
	show_matrix(cov,DIM_I,DIM_I);

	//a[0]*= 1000;	
	
	//mtx_lanczos_procedure(a,mtx_diag, mtx_off_diag,DIM_I,6);
	

	//show_matrix(Identity,DIM_I,DIM_I);
	//printf("\n Show the eigenvalues \n");
	//mtx_mrrr(mtx_diag, mtx_off_diag,eigenvalues,6);
	//show_matrix(eigenvalues,1,6);
	
	//mtx_lanczos_procedure(a,mtx_diag, mtx_off_diag,DIM_I,5);
	

	//show_matrix(Identity,DIM_I,DIM_I);
	//printf("\n Show the eigenvalues \n");
	//mtx_mrrr(mtx_diag, mtx_off_diag,eigenvalues,6);
	//show_matrix(eigenvalues,1,6);
	

	
	//mtx_lanczos_procedure(a,mtx_diag, mtx_off_diag,DIM_I,3);
	

	//show_matrix(Identity,DIM_I,DIM_I);
	//printf("\n Show the eigenvalues \n");
	//mtx_mrrr(mtx_diag, mtx_off_diag,eigenvalues,3);
	//show_matrix(eigenvalues,1,3);
	
	
	//	printf("\nElements of the diagonal\n");
		
	//show_matrix(mtx_diag,1,DIM_J);
	
		
	//	printf("\nElements off the diagonal\n");
	//show_matrix(mtx_off_diag,1,DIM_J);	
			//printf("\nIdentity matrix \n");
	
	//mtx_ident(Identity,DIM_I);
	
	//mtx_mult(eigenvalues,Identity,ident_eigen,1,3,3);
	//printf("\n Show the multiplication of eigen values with the matrix identity \n");
	//show_matrix(ident_eigen,3,3);
	
	//vect_sub(a,ident_eigen,(DIM_I*DIM_J));
	//printf("\n Show the substraction of a with the matrix identity* eigenvalues \n");
	//show_matrix(a,3,3);
	
	
	}
Ejemplo n.º 14
0
/**
 * Eliminates all the equalities in a set of constraints and returns the set of
 * constraints defining a full-dimensional polyhedron, such that there is a
 * bijection between integer points of the original polyhedron and these of the
 * resulting (projected) polyhedron).
 * If VL is set to NULL, this funciton allocates it. Else, it assumes that
 * (*VL) points to a matrix of the right size.
 * <p> The following things are done: 
 * <ol>
 * <li> remove equalities involving only parameters, and remove as many
 *      parameters as there are such equalities. From that, the list of
 *      eliminated parameters <i>elimParms</i> is built.
 * <li> remove equalities that involve variables. This requires a compression
 *      of the parameters and of the other variables that are not eliminated.
 *      The affine compresson is represented by matrix VL (for <i>validity
 *      lattice</i>) and is such that (N I 1)^T = VL.(N' I' 1), where N', I'
 *      are integer (they are the parameters and variables after compression).
 *</ol>
 *</p>
 */
void Constraints_fullDimensionize(Matrix ** M, Matrix ** C, Matrix ** VL, 
				  Matrix ** Eqs, Matrix ** ParmEqs, 
				  unsigned int ** elimVars, 
				  unsigned int ** elimParms,
				  int maxRays) {
  unsigned int i, j;
  Matrix * A=NULL, *B=NULL;
  Matrix * Ineqs=NULL;
  unsigned int nbVars = (*M)->NbColumns - (*C)->NbColumns;
  unsigned int nbParms;
  int nbElimVars;
  Matrix * fullDim = NULL;

  /* variables for permutations */
  unsigned int * permutation;
  Matrix * permutedEqs=NULL, * permutedIneqs=NULL;
  
  /* 1- Eliminate the equalities involving only parameters. */
  (*ParmEqs) = Constraints_removeParmEqs(M, C, 0, elimParms);
  /* if the polyehdron is empty, return now. */
  if ((*M)->NbColumns==0) return;
  /* eliminate the columns corresponding to the eliminated parameters */
  if (elimParms[0]!=0) {
    Constraints_removeElimCols(*M, nbVars, (*elimParms), &A);
    Matrix_Free(*M);
    (*M) = A;
    Constraints_removeElimCols(*C, 0, (*elimParms), &B);
    Matrix_Free(*C);
    (*C) = B;
    if (dbgCompParm) {
      printf("After false parameter elimination: \n");
      show_matrix(*M);
      show_matrix(*C);
    }
  }
  nbParms = (*C)->NbColumns-2;

  /* 2- Eliminate the equalities involving variables */
  /*   a- extract the (remaining) equalities from the poyhedron */
  split_constraints((*M), Eqs, &Ineqs);
  nbElimVars = (*Eqs)->NbRows;
  /*    if the polyhedron is already full-dimensional, return */
  if ((*Eqs)->NbRows==0) {
    Matrix_identity(nbParms+1, VL);
    return;
  }
  /*   b- choose variables to be eliminated */
  permutation = find_a_permutation((*Eqs), nbParms);

  if (dbgCompParm) {
    printf("Permuting the vars/parms this way: [ ");
    for (i=0; i< (*Eqs)->NbColumns-2; i++) {
      printf("%d ", permutation[i]);
    }
    printf("]\n");
  }

  Constraints_permute((*Eqs), permutation, &permutedEqs);
  Equalities_validityLattice(permutedEqs, (*Eqs)->NbRows, VL);

  if (dbgCompParm) {
    printf("Validity lattice: ");
    show_matrix(*VL);
  }
  Constraints_compressLastVars(permutedEqs, (*VL));
  Constraints_permute(Ineqs, permutation, &permutedIneqs);
  if (dbgCompParmMore) {
    show_matrix(permutedIneqs);
    show_matrix(permutedEqs);
  }
  Matrix_Free(*Eqs);
  Matrix_Free(Ineqs);
  Constraints_compressLastVars(permutedIneqs, (*VL));
  if (dbgCompParm) {
    printf("After compression: ");
    show_matrix(permutedIneqs);
  }
  /*   c- eliminate the first variables */
  assert(Constraints_eliminateFirstVars(permutedEqs, permutedIneqs));
  if (dbgCompParmMore) {
    printf("After elimination of the variables: ");
    show_matrix(permutedIneqs);
  }

  /*   d- get rid of the first (zero) columns, 
       which are now useless, and put the parameters back at the end */
  fullDim = Matrix_Alloc(permutedIneqs->NbRows,
			 permutedIneqs->NbColumns-nbElimVars);
  for (i=0; i< permutedIneqs->NbRows; i++) {
    value_set_si(fullDim->p[i][0], 1);
    for (j=0; j< nbParms; j++) {
      value_assign(fullDim->p[i][j+fullDim->NbColumns-nbParms-1], 
		   permutedIneqs->p[i][j+nbElimVars+1]);
    }
    for (j=0; j< permutedIneqs->NbColumns-nbParms-2-nbElimVars; j++) {
      value_assign(fullDim->p[i][j+1], 
		   permutedIneqs->p[i][nbElimVars+nbParms+j+1]);
    }
    value_assign(fullDim->p[i][fullDim->NbColumns-1], 
		 permutedIneqs->p[i][permutedIneqs->NbColumns-1]);
  }
  Matrix_Free(permutedIneqs);

} /* Constraints_fullDimensionize */
Ejemplo n.º 15
0
main()
#endif
{
	FILE			*fp = stdin;	  /* File pointer, default stdin */
	CRITICALS		*tuples, *lower_dim_tuples;
	int				i, temp;
	BOUNDARY		**boundary;
	CUBE			*cube;
	int				n, num_rows, num_cols;
	MATRIX			matrix, tmatrix;

	printf("\ncmat - version %1.2f\n\n", VERSION_NUM);

#ifndef NO_CMD_LINE
	/* Check the command line and open file if required */
	command_line(&fp,argc, argv, &n);
#else
	/* Read command info from standard input */
	command_input(&fp, &n);
#endif

	/* Read in info from the file, setting up Fsa and so on... */
	switch (read_file_info(fp)) {
		case FORMAT_ERROR:
			ERROR(FORMAT);
		case NOT_A_GEN:
			ERROR(GEN_ERR);
	}
	fclose(fp);	/* No more reading required */

	tuples = find_n_criticals(n);
	/* remove_inverse_criticals(&tuples);  We are ignoring inverse tuples */

	/* Calc boundaries and store in an array */
	boundary = NEW(BOUNDARY *, tuples->num);

	for (i = 0; i < tuples->num; i++) {
		boundary[i] = calc_bound(cube =
					create_n_cube(tuples->info[i]->word,
					tuples->info[i]->vert, n), TRIVIAL | RETAIN_INV_TUPLES);
					/* We are ignoring inverse tuples */
		delete_cube(cube);
	}

	lower_dim_tuples = find_n_criticals(n-1);
	/* remove_inverse_criticals(&lower_dim_tuples);  Ignoring inverse tuples */

	num_rows = tuples->num;
	/* Create the matrix */
	matrix = make_matrix_n(boundary, lower_dim_tuples, &num_rows);
	num_cols = lower_dim_tuples->num;

	/* It is often useful to have rows and columns the other way */
	/* Get transpose, and swap rows and cols */
	tmatrix = transpose(matrix, num_cols, num_rows);
	temp = num_rows;
	num_rows = num_cols;
	num_cols = temp;

	/* Display....for now */
	printf("\nMatrix: rows = %d, cols = %d\n\n", num_rows, num_cols);
	show_matrix(stdout, tmatrix, num_cols, num_rows, 20);

	/*printf("\nMatrix after Gaussian Elimination...\n");
	gaussian_elim(matrix, num_cols, num_rows);
	show_matrix(stdout, matrix, num_cols, num_rows);

	rank_criticals_n = count_non_zero_rows(matrix, num_cols, num_rows);*/

	/* Clean up */
	for (i=0; i < tuples->num - Num_gens; i++)
	delete_boundary(boundary[i]);
	free(boundary);
	delete_criticals(tuples);
	delete_criticals(lower_dim_tuples);
	
	delete_matrix(matrix, num_cols);
	delete_matrix(tmatrix, num_rows);

	return 0;
}
Ejemplo n.º 16
0
/** 
 * Given a system of equalities, looks if it has an integer solution in the
 * combined space, and if yes, returns one solution.
 * <p>pre-condition: the equalities are full-row rank (without the constant
 * part)</p>
 * @param Eqs the system of equations (as constraints)
 * @param I a feasible integer solution if it exists, else NULL. Allocated if
 * initially set to NULL, else reused.
 */
void Equalities_integerSolution(Matrix * Eqs, Matrix **I) {
  Matrix * Hm, *H=NULL, *U, *Q, *M=NULL, *C=NULL, *Hi;
  Matrix *Ip;
  int i;
  Value mod;
  unsigned int rk;
  if (Eqs==NULL){
    if ((*I)!=NULL) Matrix_Free(*I);
    I = NULL;
    return;
  }
  /* we use: AI = C = (Ha 0).Q.I = (Ha 0)(I' 0)^T */
  /* with I = Qinv.I' = U.I'*/
  /* 1- compute I' = Hainv.(-C) */
  /* HYP: the equalities are full-row rank */
  rk = Eqs->NbRows;
  Matrix_subMatrix(Eqs, 0, 1, rk, Eqs->NbColumns-1, &M);
  left_hermite(M, &Hm, &Q, &U);
  Matrix_Free(M);
  Matrix_subMatrix(Hm, 0, 0, rk, rk, &H);
  if (dbgCompParmMore) {
    show_matrix(Hm);
    show_matrix(H);
    show_matrix(U);
  }
  Matrix_Free(Q);
  Matrix_Free(Hm);
  Matrix_subMatrix(Eqs, 0, Eqs->NbColumns-1, rk, Eqs->NbColumns, &C);
  Matrix_oppose(C);
  Hi = Matrix_Alloc(rk, rk+1);
  MatInverse(H, Hi);
  if (dbgCompParmMore) {
    show_matrix(C);
    show_matrix(Hi);
  }
  /* put the numerator of Hinv back into H */
  Matrix_subMatrix(Hi, 0, 0, rk, rk, &H);
  Ip = Matrix_Alloc(Eqs->NbColumns-2, 1);
  /* fool Matrix_Product on the size of Ip */
  Ip->NbRows = rk;
  Matrix_Product(H, C, Ip);
  Ip->NbRows = Eqs->NbColumns-2;
  Matrix_Free(H);
  Matrix_Free(C);
  value_init(mod);
  for (i=0; i< rk; i++) {
    /* if Hinv.C is not integer, return NULL (no solution) */
    value_pmodulus(mod, Ip->p[i][0], Hi->p[i][rk]);
    if (value_notzero_p(mod)) { 
      if ((*I)!=NULL) Matrix_Free(*I);
      value_clear(mod);
      Matrix_Free(U);
      Matrix_Free(Ip);
      Matrix_Free(Hi);
      I = NULL;
      return;
    }
    else {
      value_pdivision(Ip->p[i][0], Ip->p[i][0], Hi->p[i][rk]);
    }
  }
  /* fill the rest of I' with zeros */
  for (i=rk; i< Eqs->NbColumns-2; i++) {
    value_set_si(Ip->p[i][0], 0);
  }
  value_clear(mod);
  Matrix_Free(Hi);
  /* 2 - Compute the particular solution I = U.(I' 0) */
  ensureMatrix((*I), Eqs->NbColumns-2, 1);
  Matrix_Product(U, Ip, (*I));
  Matrix_Free(U);
  Matrix_Free(Ip);
  if (dbgCompParm) {
    show_matrix(*I);
  }
}
Ejemplo n.º 17
0
int backtracking()
{
//Find the setof frames which minimizes the correlation as we done in ITG_3.2
//and also consider other metrics with meaningful weightage as follows
//	 metric			weightage	where(path traversal)
//(1)correlation	0.25		on fly
//(2)distance		0.25		on fly
//(3)brightness		0.125		|
//(4)blurriness		0.125		|________ create a matrix with weighted value
//(5)entropy		0.125		|			(of these 4 metrics)
//(6)face			0.125		|


	int i;
	int pos;
	int size = total_samples/n;
	abs_metrics = (float**)malloc(sizeof(float*)*n);
	for(i=0;i<n;i++) {
		abs_metrics[i]=(float*)malloc(sizeof(float)*size);
	}
	float best_metric;	
	cout<<"size:"<<size<<endl;
	flag = (int*) malloc(sizeof(int)*n);
	int* stack = (int*) malloc(sizeof(int)*n);
	index_samples =0;
//create a matrix with weighted value of all 4 metrics
// -brightness, -blurriness, -entropy, -face metric
	abs_metric_calc();
//show a 2D matrix
	show_matrix( abs_metrics,n,size);

	initialize_stack(stack );
#if TRACE_STEPS
	show_valid(stack);
#endif
	float present;
	i=0;
//	while(i<pow(size,n)) {
	while(stack_empty(stack)) {
#if TRACE_STEPS
		cout<<"i:"<<i<<endl;
		show_valid(stack);
#endif
		present = get_path_metrics(stack);
		if(i==0) {
			best_metric = present;
			copy(stack,flag,n);
#if PRINT_DEBUG
			cout<<"present:"<<present<<endl;
#endif
		}
		else if(present>best_metric) {
			best_metric = present;
			copy(stack,flag,n);
#if PRINT_DEBUG
			cout<<"present<best_corr:"<<best_metric<<endl;
			show_valid( flag);
#endif
		}
#if PRINT_DEBUG
		cout<<"correlation:"<<present<<"\t";
#endif
		stack_pop_push(stack);
		i++;
	}		
	return(0);
}
Ejemplo n.º 18
0
/**
 * Tests Constraints_fullDimensionize by comparing the Ehrhart polynomials 
 * @param A the input set of constraints
 * @param B the corresponding context
 * @param the number of samples to generate for the test
 * @return 1 if the Ehrhart polynomial had the same value for the
 * full-dimensional and non-full-dimensional sets of constraints, for their
 * corresponding sample parameters values.
 */
int test_Constraints_fullDimensionize(Matrix * A, Matrix * B, 
				      unsigned int nbSamples) {
  Matrix * Eqs= NULL, *ParmEqs=NULL, *VL=NULL;
  unsigned int * elimVars=NULL, * elimParms=NULL;
  Matrix * sample, * smallerSample=NULL;
  Matrix * transfSample=NULL;
  Matrix * parmVL=NULL;
  unsigned int i, j, r, nbOrigParms, nbParms;
  Value div, mod, *origVal=NULL, *fullVal=NULL;
  Matrix * VLInv;
  Polyhedron * P, *PC;
  Matrix * M, *C;
  Enumeration * origEP, * fullEP=NULL;
  const char **fullNames = NULL;
  int isOk = 1; /* holds the result */

  /* compute the origial Ehrhart polynomial */
  M = Matrix_Copy(A);
  C = Matrix_Copy(B);
  P = Constraints2Polyhedron(M, maxRays);
  PC = Constraints2Polyhedron(C, maxRays);
  origEP = Polyhedron_Enumerate(P, PC, maxRays, origNames);
  Matrix_Free(M);
  Matrix_Free(C);
  Polyhedron_Free(P);
  Polyhedron_Free(PC);

  /* compute the full-dimensional polyhedron corresponding to A and its Ehrhart
     polynomial */
  M = Matrix_Copy(A);
  C = Matrix_Copy(B);
  nbOrigParms = B->NbColumns-2;
  Constraints_fullDimensionize(&M, &C, &VL, &Eqs, &ParmEqs, 
			       &elimVars, &elimParms, maxRays);
  if ((Eqs->NbRows==0) && (ParmEqs->NbRows==0)) {
    Matrix_Free(M);
    Matrix_Free(C);
    Matrix_Free(Eqs);
    Matrix_Free(ParmEqs);
    free(elimVars);
    free(elimParms);
    return 1;
  }
  nbParms = C->NbColumns-2;
  P = Constraints2Polyhedron(M, maxRays);
  PC = Constraints2Polyhedron(C, maxRays);
  namesWithoutElim(origNames, nbOrigParms, elimParms, &fullNames);
  fullEP = Polyhedron_Enumerate(P, PC, maxRays, fullNames);
  Matrix_Free(M);
  Matrix_Free(C);
  Polyhedron_Free(P);
  Polyhedron_Free(PC);
  
  /* make a set of sample parameter values and compare the corresponding
     Ehrhart polnomials */
  sample = Matrix_Alloc(1,nbOrigParms);
  transfSample = Matrix_Alloc(1, nbParms);
  Lattice_extractSubLattice(VL, nbParms, &parmVL);
  VLInv = Matrix_Alloc(parmVL->NbRows, parmVL->NbRows+1);
  MatInverse(parmVL, VLInv);
  if (dbg) {
    show_matrix(parmVL);
    show_matrix(VLInv);
  }
  srand(nbSamples);
  value_init(mod);
  value_init(div);
  for (i = 0; i< nbSamples; i++) {
    /* create a random sample */
    for (j=0; j< nbOrigParms; j++) {
      value_set_si(sample->p[0][j], rand()%100);
    }
    /* compute the corresponding value for the full-dimensional
       constraints */
    valuesWithoutElim(sample, elimParms, &smallerSample); 
    /* (N' i' 1)^T = VLinv.(N i 1)^T*/
    for (r = 0; r < nbParms; r++) {
      Inner_Product(&(VLInv->p[r][0]), smallerSample->p[0], nbParms,
		    &(transfSample->p[0][r]));
      /* add the constant part */
      value_addto(transfSample->p[0][r], transfSample->p[0][r], 
					 VLInv->p[r][VLInv->NbColumns-2]);
      value_pdivision(div, transfSample->p[0][r], 
			 VLInv->p[r][VLInv->NbColumns-1]);
      value_subtract(mod, transfSample->p[0][r], div);
      /* if the parameters value does not belong to the validity lattice, the
	 Ehrhart polynomial is zero. */
      if (!value_zero_p(mod)) {
	fullEP = Enumeration_zero(nbParms, maxRays);
	break;
      }
    }
    /* compare the two forms of the Ehrhart polynomial.*/
    if (origEP ==NULL) break; /* NULL has loose semantics for EPs */
    origVal = compute_poly(origEP, sample->p[0]);
    fullVal = compute_poly(fullEP, transfSample->p[0]);
    if (!value_eq(*origVal, *fullVal)) {
      isOk = 0;
      printf("EPs don't match. \n Original value = ");
      value_print(stdout, VALUE_FMT, *origVal);
      printf("\n Original sample = [");
      for (j=0; j<sample->NbColumns; j++) {
	value_print(stdout, VALUE_FMT, sample->p[0][j]);
	printf(" ");
      }
      printf("] \n EP = ");
      if(origEP!=NULL) {
	print_evalue(stdout, &(origEP->EP), origNames);
      }
      else {
	printf("NULL");
      }
      printf(" \n Full-dimensional value = ");
      value_print(stdout, P_VALUE_FMT, *fullVal);
      printf("\n full-dimensional sample = [");
      for (j=0; j<sample->NbColumns; j++) {
	value_print(stdout, VALUE_FMT, transfSample->p[0][j]);
	printf(" ");
      }
      printf("] \n EP = ");
      if(origEP!=NULL) {
	print_evalue(stdout, &(origEP->EP), fullNames);
      }
      else {
	printf("NULL");
      }
    }
    if (dbg) {
      printf("\nOriginal value = ");
      value_print(stdout, VALUE_FMT, *origVal);
      printf("\nFull-dimensional value = ");
      value_print(stdout, P_VALUE_FMT, *fullVal);
      printf("\n");
    }
    value_clear(*origVal);
    value_clear(*fullVal);
  }
  value_clear(mod);
  value_clear(div);
  Matrix_Free(sample);
  Matrix_Free(smallerSample);
  Matrix_Free(transfSample);
  Enumeration_Free(origEP);
  Enumeration_Free(fullEP);
  return isOk;
} /* test_Constraints_fullDimensionize */
Ejemplo n.º 19
0
/** extracts the equalities involving the parameters only, try to introduce
    them back and compare the two polyhedra.
    Reads a polyhedron and a context.
 */
int test_Constraints_Remove_parm_eqs(Matrix * A, Matrix * B) {
  int isOk = 1;
  Matrix * M, *C, *Cp, * Eqs, *M1, *C1;
  Polyhedron *Pm, *Pc, *Pcp, *Peqs, *Pint;
  unsigned int * elimParms;
  printf("----- test_Constraints_Remove_parm_eqs() -----\n");
  M1 = Matrix_Copy(A);
  C1 = Matrix_Copy(B);

  M = Matrix_Copy(M1);
  C = Matrix_Copy(C1);

   /* compute the combined polyhedron */
  Pm = Constraints2Polyhedron(M, maxRays);
  Pc = Constraints2Polyhedron(C, maxRays);
  Pcp = align_context(Pc, Pm->Dimension, maxRays);
  Polyhedron_Free(Pc);
  Pc = DomainIntersection(Pm, Pcp, maxRays);
  Polyhedron_Free(Pm);
  Polyhedron_Free(Pcp);
  Matrix_Free(M);
  Matrix_Free(C);

  /* extract the parm-equalities, expressed in the combined space */
  Eqs = Constraints_Remove_parm_eqs(&M1, &C1, 1, &elimParms);

  printf("Removed equalities: \n");
  show_matrix(Eqs); 
  printf("Polyhedron without equalities involving only parameters: \n");
  show_matrix(M1);  
  printf("Context without equalities: \n");
  show_matrix(C1);  
  
  /* compute the supposedly-same polyhedron, using the extracted equalities */
  Pm = Constraints2Polyhedron(M1, maxRays);
  Pcp = Constraints2Polyhedron(C1, maxRays);
  Peqs = align_context(Pcp, Pm->Dimension, maxRays);
  Polyhedron_Free(Pcp);
  Pcp = DomainIntersection(Pm, Peqs, maxRays);
  Polyhedron_Free(Peqs);
  Polyhedron_Free(Pm);
  Peqs = Constraints2Polyhedron(Eqs, maxRays);
  Matrix_Free(Eqs);
  Matrix_Free(M1);
  Matrix_Free(C1);
  Pint = DomainIntersection(Pcp, Peqs, maxRays);
  Polyhedron_Free(Pcp);
  Polyhedron_Free(Peqs);

  /* test their equality */
  if (!PolyhedronIncludes(Pint, Pc)) {
    isOk = 0;
  }
  else {
    if (!PolyhedronIncludes(Pc, Pint)) {
      isOk = 0;
    }
  }
  Polyhedron_Free(Pc);
  Polyhedron_Free(Pint);
  return isOk;
} /* test_Constraints_Remove_parm_eqs() */
Ejemplo n.º 20
0
Archivo: f4.cpp Proyecto: pzinn/M2
void F4GB::do_spairs()
{
  if (hilbert && hilbert->nRemainingExpected() == 0)
    {
      if (M2_gbTrace >= 1)
        fprintf(stderr, "-- skipping degree...no elements expected in this degree\n");
      return;
    }
  reset_matrix();
  reset_syz_matrix();
  clock_t begin_time = clock();

  n_lcmdups = 0;
  make_matrix();

  if (M2_gbTrace >= 5) {
    fprintf(stderr, "---------\n");
    show_matrix();
    fprintf(stderr, "---------\n");
  }

  clock_t end_time = clock();
  clock_make_matrix += end_time - begin_time;
  double nsecs = static_cast<double>(end_time - begin_time);
  nsecs /= CLOCKS_PER_SEC;
  if (M2_gbTrace >= 2)
    fprintf(stderr, " make matrix time = %f\n", nsecs);

  if (M2_gbTrace >= 2)
    H.dump();

  begin_time = clock();
  gauss_reduce(true);
  end_time = clock();
  clock_gauss += end_time - begin_time;

  //  fprintf(stderr, "---------\n");
  //  show_matrix();
  //  fprintf(stderr, "---------\n");

  nsecs = static_cast<double>(end_time - begin_time);
  nsecs /= CLOCKS_PER_SEC;
  if (M2_gbTrace >= 2)
    {
      fprintf(stderr, " gauss time          = %f\n", nsecs);

      fprintf(stderr, " lcm dups            = %ld\n", n_lcmdups);
      if (M2_gbTrace >= 5)
        {
          fprintf(stderr, "---------\n");
          show_matrix();
          fprintf(stderr, "---------\n");
          show_syz_matrix();
          //  show_new_rows_matrix();
        }
    }
  new_GB_elements();
  int ngb = INTSIZE(gb);
  if (M2_gbTrace >= 1) {
    fprintf(stderr, " # GB elements   = %d\n", ngb);
    if (M2_gbTrace >= 5) show_gb_array(gb);
    if (using_syz)
      fprintf(stderr, " # syzygies      = %ld\n", static_cast<long>(syz_basis.size()));
    if (M2_gbTrace >= 5) show_syz_basis();
  }

  clear_matrix();
  clear_syz_matrix();
}
Ejemplo n.º 21
0
/** Removes the equalities that involve only parameters, by eliminating some
 * parameters in the polyhedron's constraints and in the context.<p> 
 * <b>Updates M and Ctxt.</b>
 * @param M1 the polyhedron's constraints
 * @param Ctxt1 the constraints of the polyhedron's context
 * @param renderSpace tells if the returned equalities must be expressed in the
 * parameters space (renderSpace=0) or in the combined var/parms space
 * (renderSpace = 1)
 * @param elimParms the list of parameters that have been removed: an array
 * whose 1st element is the number of elements in the list.  (returned)
 * @return the system of equalities that involve only parameters.
 */
Matrix * Constraints_Remove_parm_eqs(Matrix ** M1, Matrix ** Ctxt1, 
				     int renderSpace, 
				     unsigned int ** elimParms) {
  int i, j, k, nbEqsParms =0;
  int nbEqsM, nbEqsCtxt, allZeros, nbTautoM = 0, nbTautoCtxt = 0;
  Matrix * M = (*M1);
  Matrix * Ctxt = (*Ctxt1);
  int nbVars = M->NbColumns-Ctxt->NbColumns;
  Matrix * Eqs;
  Matrix * EqsMTmp;
  
  /* 1- build the equality matrix(ces) */
  nbEqsM = 0;
  for (i=0; i< M->NbRows; i++) {
    k = First_Non_Zero(M->p[i], M->NbColumns);
    /* if it is a tautology, count it as such */
    if (k==-1) {
      nbTautoM++;
    }
    else {
      /* if it only involves parameters, count it */
      if (k>= nbVars+1) nbEqsM++;
    }
  }

  nbEqsCtxt = 0;
  for (i=0; i< Ctxt->NbRows; i++) {
    if (value_zero_p(Ctxt->p[i][0])) {
      if (First_Non_Zero(Ctxt->p[i], Ctxt->NbColumns)==-1) {
	nbTautoCtxt++;
      }
      else {
	nbEqsCtxt ++;
      }
    }
  }
  nbEqsParms = nbEqsM + nbEqsCtxt; 

  /* nothing to do in this case */
  if (nbEqsParms+nbTautoM+nbTautoCtxt==0) {
    (*elimParms) = (unsigned int*) malloc(sizeof(int));
    (*elimParms)[0] = 0;
    if (renderSpace==0) {
      return Matrix_Alloc(0,Ctxt->NbColumns);
    }
    else {
      return Matrix_Alloc(0,M->NbColumns);
    }
  }
  
  Eqs= Matrix_Alloc(nbEqsParms, Ctxt->NbColumns);
  EqsMTmp= Matrix_Alloc(nbEqsParms, M->NbColumns);
  
  /* copy equalities from the context */
  k = 0;
  for (i=0; i< Ctxt->NbRows; i++) {
    if (value_zero_p(Ctxt->p[i][0]) 
		     && First_Non_Zero(Ctxt->p[i], Ctxt->NbColumns)!=-1) {
      Vector_Copy(Ctxt->p[i], Eqs->p[k], Ctxt->NbColumns);
      Vector_Copy(Ctxt->p[i]+1, EqsMTmp->p[k]+nbVars+1, 
		  Ctxt->NbColumns-1);
      k++;
    }
  }
  for (i=0; i< M->NbRows; i++) {
    j=First_Non_Zero(M->p[i], M->NbColumns);
    /* copy equalities that involve only parameters from M */
    if (j>=nbVars+1) {
      Vector_Copy(M->p[i]+nbVars+1, Eqs->p[k]+1, Ctxt->NbColumns-1);
      Vector_Copy(M->p[i]+nbVars+1, EqsMTmp->p[k]+nbVars+1, 
		  Ctxt->NbColumns-1);
      /* mark these equalities for removal */
      value_set_si(M->p[i][0], 2);
      k++;
    }
    /* mark the all-zero equalities for removal */
    if (j==-1) {
      value_set_si(M->p[i][0], 2);
    }
  }

  /* 2- eliminate parameters until all equalities are used or until we find a
  contradiction (overconstrained system) */
  (*elimParms) = (unsigned int *) malloc((Eqs->NbRows+1) * sizeof(int));
  (*elimParms)[0] = 0;
  allZeros = 0;
  for (i=0; i< Eqs->NbRows; i++) {
    /* find a variable that can be eliminated */
    k = First_Non_Zero(Eqs->p[i], Eqs->NbColumns);
    if (k!=-1) { /* nothing special to do for tautologies */

      /* if there is a contradiction, return empty matrices */
      if (k==Eqs->NbColumns-1) {
	printf("Contradiction in %dth row of Eqs: ",k);
	show_matrix(Eqs);
	Matrix_Free(Eqs);
	Matrix_Free(EqsMTmp);
	(*M1) = Matrix_Alloc(0, M->NbColumns);
	Matrix_Free(M);
	(*Ctxt1) = Matrix_Alloc(0,Ctxt->NbColumns);
	Matrix_Free(Ctxt);
	free(*elimParms);
	(*elimParms) = (unsigned int *) malloc(sizeof(int));
	(*elimParms)[0] = 0;
	if (renderSpace==1) {
	  return Matrix_Alloc(0,(*M1)->NbColumns);
	}
	else {
	  return Matrix_Alloc(0,(*Ctxt1)->NbColumns);
	}
      }	
      /* if we have something we can eliminate, do it in 3 places:
	 Eqs, Ctxt, and M */
      else {
	k--; /* k is the rank of the variable, now */
	(*elimParms)[0]++;
	(*elimParms)[(*elimParms[0])]=k;
	for (j=0; j< Eqs->NbRows; j++) {
	  if (i!=j) {
	    eliminate_var_with_constr(Eqs, i, Eqs, j, k);
	    eliminate_var_with_constr(EqsMTmp, i, EqsMTmp, j, k+nbVars);
	  }
	}
	for (j=0; j< Ctxt->NbRows; j++) {
	  if (value_notzero_p(Ctxt->p[i][0])) {
	    eliminate_var_with_constr(Eqs, i, Ctxt, j, k);
	  }
	}
	for (j=0; j< M->NbRows; j++) {
	  if (value_cmp_si(M->p[i][0], 2)) {
	    eliminate_var_with_constr(EqsMTmp, i, M, j, k+nbVars);
	  }
	}
      }
    }
    /* if (k==-1): count the tautologies in Eqs to remove them later */
    else {
      allZeros++;
    }
  }
  
  /* elimParms may have been overallocated. Now we know how many parms have
     been eliminated so we can reallocate the right amount of memory. */
  if (!realloc((*elimParms), ((*elimParms)[0]+1)*sizeof(int))) {
    fprintf(stderr, "Constraints_Remove_parm_eqs > cannot realloc()");
  }

  Matrix_Free(EqsMTmp);

  /* 3- remove the "bad" equalities from the input matrices
     and copy the equalities involving only parameters */
  EqsMTmp = Matrix_Alloc(M->NbRows-nbEqsM-nbTautoM, M->NbColumns);
  k=0;
  for (i=0; i< M->NbRows; i++) {
    if (value_cmp_si(M->p[i][0], 2)) {
      Vector_Copy(M->p[i], EqsMTmp->p[k], M->NbColumns);
      k++;
    }
  }
  Matrix_Free(M);
  (*M1) = EqsMTmp;
  
  EqsMTmp = Matrix_Alloc(Ctxt->NbRows-nbEqsCtxt-nbTautoCtxt, Ctxt->NbColumns);
  k=0;
  for (i=0; i< Ctxt->NbRows; i++) {
    if (value_notzero_p(Ctxt->p[i][0])) {
      Vector_Copy(Ctxt->p[i], EqsMTmp->p[k], Ctxt->NbColumns);
      k++;
    }
  }
  Matrix_Free(Ctxt);
  (*Ctxt1) = EqsMTmp;
  
  if (renderSpace==0) {/* renderSpace=0: equalities in the parameter space */
    EqsMTmp = Matrix_Alloc(Eqs->NbRows-allZeros, Eqs->NbColumns);
    k=0;
    for (i=0; i<Eqs->NbRows; i++) {
      if (First_Non_Zero(Eqs->p[i], Eqs->NbColumns)!=-1) {
	Vector_Copy(Eqs->p[i], EqsMTmp->p[k], Eqs->NbColumns);
	k++;
      }
    }
  }
  else {/* renderSpace=1: equalities rendered in the combined space */
    EqsMTmp = Matrix_Alloc(Eqs->NbRows-allZeros, (*M1)->NbColumns);
    k=0;
    for (i=0; i<Eqs->NbRows; i++) {
      if (First_Non_Zero(Eqs->p[i], Eqs->NbColumns)!=-1) {
	Vector_Copy(Eqs->p[i], &(EqsMTmp->p[k][nbVars]), Eqs->NbColumns);
	k++;
      }
    }
  }
  Matrix_Free(Eqs);
  Eqs = EqsMTmp;

  return Eqs;
} /* Constraints_Remove_parm_eqs */
Ejemplo n.º 22
0
int main( int argc, char **argv)
{
  int i;
  const char **param_name;
  Matrix *C1, *P1;
  Polyhedron *P, *C;
  Enumeration *e, *en;

  Matrix * Validity_Lattice;
  int nb_parms;
  
#ifdef EP_EVALUATION
  Value *p, *tmp;
  int k;
#endif

  P1 = Matrix_Read();
  C1 = Matrix_Read();
  nb_parms = C1->NbColumns-2;
  if(nb_parms < 0) {
    fprintf( stderr, "Not enough parameters !\n" );
    exit(0);
  }

   /* Read the name of the parameters */
  param_name = Read_ParamNames(stdin,nb_parms);

  /* inflate the polyhedron, so that the inflated EP approximation will be an
     upper bound for the EP's polyhedron. */
  mpolyhedron_deflate(P1,nb_parms);

  /* compute a polynomial approximation of the Ehrhart polynomial */
  e = Ehrhart_Quick_Apx(P1, C1, &Validity_Lattice, 1024);
  
  Matrix_Free(C1);
  Matrix_Free(P1);

  printf("============ Ehrhart polynomial quick polynomial lower bound ============\n");
  show_matrix(Validity_Lattice);
  for( en=e ; en ; en=en->next ) {    
    Print_Domain(stdout,en->ValidityDomain, param_name);
    print_evalue(stdout,&en->EP, param_name);
    printf( "\n-----------------------------------\n" );
  }
 
#ifdef EP_EVALUATION
  if( isatty(0) && nb_parms != 0)
  {  /* no tty input or no polyhedron -> no evaluation. */
    printf("Evaluation of the Ehrhart polynomial :\n");
    p = (Value *)malloc(sizeof(Value) * (nb_parms));
    for(i=0;i<nb_parms;i++) 
      value_init(p[i]);
    FOREVER {
      fflush(stdin);
      printf("Enter %d parameters : ",nb_parms);
      for(k=0;k<nb_parms;++k) {
	scanf("%s",str);
	value_read(p[k],str);
      }
      fprintf(stdout,"EP( ");
      value_print(stdout,VALUE_FMT,p[0]);
      for(k=1;k<nb_parms;++k) {
	fprintf(stdout,",");
	value_print(stdout,VALUE_FMT,p[k]);
      }
      fprintf(stdout," ) = ");
      value_print(stdout,VALUE_FMT,*(tmp=compute_poly(en,p)));
      free(tmp);
      fprintf(stdout,"\n");  
    }
  }
Ejemplo n.º 23
0
/**
 * Given a matrix with m parameterized equations, compress the nb_parms
 * parameters and n-m variables so that m variables are integer, and transform
 * the variable space into a n-m space by eliminating the m variables (using
 * the equalities) the variables to be eliminated are chosen automatically by
 * the function.
 * <b>Deprecated.</b> Try to use Constraints_fullDimensionize instead.
 * @param M the constraints 
 * @param the number of parameters
 * @param validityLattice the the integer lattice underlying the integer
 * solutions.
*/
Matrix * full_dimensionize(Matrix const * M, int nbParms, 
			   Matrix ** validityLattice) {
  Matrix * Eqs, * Ineqs;
  Matrix * permutedEqs, * permutedIneqs;
  Matrix * Full_Dim;
  Matrix * WVL; /* The Whole Validity Lattice (vars+parms) */
  unsigned int i,j;
  int nbElimVars;
  unsigned int * permutation, * permutationInv;
  /* 0- Split the equalities and inequalities from each other */
  split_constraints(M, &Eqs, &Ineqs);

  /* 1- if the polyhedron is already full-dimensional, return it */
  if (Eqs->NbRows==0) {
    Matrix_Free(Eqs);
    (*validityLattice) = Identity_Matrix(nbParms+1);
    return Ineqs;
  }
  nbElimVars = Eqs->NbRows;

  /* 2- put the vars to be eliminated at the first positions, 
     and compress the other vars/parms
     -> [ variables to eliminate / parameters / variables to keep ] */
  permutation = find_a_permutation(Eqs, nbParms);
  if (dbgCompParm) {
    printf("Permuting the vars/parms this way: [ ");
    for (i=0; i< Eqs->NbColumns; i++) {
      printf("%d ", permutation[i]);
    }
    printf("]\n");
  }
  permutedEqs = mpolyhedron_permute(Eqs, permutation);
  WVL = compress_parms(permutedEqs, Eqs->NbColumns-2-Eqs->NbRows);
  if (dbgCompParm) {
    printf("Whole validity lattice: ");
    show_matrix(WVL);
  }
  mpolyhedron_compress_last_vars(permutedEqs, WVL);
  permutedIneqs = mpolyhedron_permute(Ineqs, permutation);
  if (dbgCompParm) {
    show_matrix(permutedEqs);
  }
  Matrix_Free(Eqs);
  Matrix_Free(Ineqs);
  mpolyhedron_compress_last_vars(permutedIneqs, WVL);
  if (dbgCompParm) {
    printf("After compression: ");
    show_matrix(permutedIneqs);
  }
  /* 3- eliminate the first variables */
  if (!mpolyhedron_eliminate_first_variables(permutedEqs, permutedIneqs)) {
    fprintf(stderr,"full-dimensionize > variable elimination failed. \n"); 
    return NULL;
  }
  if (dbgCompParm) {
    printf("After elimination of the variables: ");
    show_matrix(permutedIneqs);
  }

  /* 4- get rid of the first (zero) columns, 
     which are now useless, and put the parameters back at the end */
  Full_Dim = Matrix_Alloc(permutedIneqs->NbRows,
			  permutedIneqs->NbColumns-nbElimVars);
  for (i=0; i< permutedIneqs->NbRows; i++) {
    value_set_si(Full_Dim->p[i][0], 1);
    for (j=0; j< nbParms; j++) 
      value_assign(Full_Dim->p[i][j+Full_Dim->NbColumns-nbParms-1], 
		   permutedIneqs->p[i][j+nbElimVars+1]);
    for (j=0; j< permutedIneqs->NbColumns-nbParms-2-nbElimVars; j++) 
      value_assign(Full_Dim->p[i][j+1], 
		   permutedIneqs->p[i][nbElimVars+nbParms+j+1]);
    value_assign(Full_Dim->p[i][Full_Dim->NbColumns-1], 
		 permutedIneqs->p[i][permutedIneqs->NbColumns-1]);
  }
  Matrix_Free(permutedIneqs);
  
  /* 5- Keep only the the validity lattice restricted to the parameters */
  *validityLattice = Matrix_Alloc(nbParms+1, nbParms+1);
  for (i=0; i< nbParms; i++) {
    for (j=0; j< nbParms; j++)
      value_assign((*validityLattice)->p[i][j], 
		   WVL->p[i][j]);
    value_assign((*validityLattice)->p[i][nbParms], 
		 WVL->p[i][WVL->NbColumns-1]);
  }
  for (j=0; j< nbParms; j++) 
    value_set_si((*validityLattice)->p[nbParms][j], 0);
  value_assign((*validityLattice)->p[nbParms][nbParms], 
	       WVL->p[WVL->NbColumns-1][WVL->NbColumns-1]);

  /* 6- Clean up */
  Matrix_Free(WVL);
  return Full_Dim;
} /* full_dimensionize */
Ejemplo n.º 24
0
Archivo: main.cpp Proyecto: CCJY/coliru
int main() {
    int n = 3;
	
    double m1[] = {25, 15, -5,
                   15, 18,  0,
                   -5,  0, 11};
    double *c1 = cholesky(m1, n);
    show_matrix(c1, n);
    free(c1);
 
    n = 4;
    double m2[] = {18, 22,  54,  42,
                   22, 70,  86,  62,
                   54, 86, 174, 134,
                   42, 62, 134, 106};
 
	
	printf("\n");	
	double *c2 = cholesky4(m2, n);
    show_matrix(c2, n);
	free(c2);
	
	n = 1000;
	double *m3 = (double*)malloc(sizeof(double)*n*n);
	for(int i=0; i<n; i++) {
		for(int j=i; j<n; j++) {
			double element = 1.0*rand()/RAND_MAX;
			m3[i*n+j] = element;
			m3[j*n+i] = element;

		}
	}
	double *m4 = (double*)malloc(sizeof(double)*n*n);
	gemm_ATA(m3, m4, n); //make a positive-definite matrix
	printf("\n");
	//show_matrix(m4,n);

	double dtime;
	
	double *c3 = cholesky4(m4, n); //warm up OpenMP
	free(c3);

	dtime = omp_get_wtime();
	c3 = cholesky(m4, n);
	dtime = omp_get_wtime() - dtime;
	printf("dtime %f\n", dtime);

	dtime = omp_get_wtime();
	double *c4 = cholesky5(m4, n);
	dtime = omp_get_wtime() - dtime;
	printf("dtime %f\n", dtime);
	printf("%d\n", memcmp(c3, c4, sizeof(double)*n*n));
	//show_matrix(c3,n);
	printf("\n");
	//show_matrix(c4,n);
	//for(int i=0; i<100; i++) printf("%f %f %f \n", m4[i], c3[i], c4[i]);
	/*

	double *l = (double*)malloc(sizeof(double)*n*n);
	dtime = omp_get_wtime();
	cholesky_dll(m3, l, n);
	dtime = omp_get_wtime() - dtime;
	printf("dtime %f\n", dtime);
	*/
	//printf("%d\n", memcmp(c3, c4, sizeof(double)*n*n));
	//for(int i=0; i<100; i++) printf("%f %f %f \n", m3[i], c3[i], c4[i]);

	//free(c3);
	//free(c4);
	//free(m3);
	
    return 0;
	
}