T hotelling_t2_1test(
  boost::numeric::ublas::vector<T> mean1,
  boost::numeric::ublas::vector<T> mean2,
  boost::numeric::ublas::matrix<T> cov1,
  unsigned n1
){
  unsigned k=mean1.size();  

  boost::numeric::ublas::vector<T > mean_diff=mean1-mean2;
  boost::numeric::ublas::matrix<T>  cov_inv(cov1);
  invert_matrix(cov1  ,cov_inv);
  T t2_score=
  boost::numeric::ublas::inner_prod(
			      boost::numeric::ublas::prod( cov_inv,mean_diff)
			      ,mean_diff)*n1;
  T f_score= (t2_score*(n1 - k))/(k*(n1-1));

  std::cout << t2_score   << std::endl;
  std::cout << f_score   << std::endl;

  boost::math::fisher_f dist(k, n1-k);
  T p_score =boost::math::cdf(dist, f_score);

  std::cout << p_score << std::endl;
  T p_comp =boost::math::cdf(complement(dist, f_score));
  std::cout << p_comp << std::endl;
  //return p_comp;
  return p_score;
}
T hotelling_t2_2test(
  boost::numeric::ublas::vector<T> mean1,
  boost::numeric::ublas::vector<T> mean2,
  boost::numeric::ublas::matrix<T> cov1,
  boost::numeric::ublas::matrix<T> cov2, 
  unsigned n1,
  unsigned n2){
  unsigned k=mean1.size();  
//int n = n1 + n2 -1;
  boost::numeric::ublas::vector<T > mean_diff=mean1-mean2;
  boost::numeric::ublas::matrix<T>  
  pooled_cov=(cov1*(n1-1)+cov2*(n2-1))*1.0/(n1+n2-2) ;
  pooled_cov *= (1.0/n1+1.0/n2 );
  boost::numeric::ublas::matrix<T>  pooled_cov_inv(pooled_cov);
  invert_matrix(   pooled_cov  ,pooled_cov_inv);
//std::cout << mean_diff << std::endl;  
  T t2_score=
  boost::numeric::ublas::inner_prod(
			      boost::numeric::ublas::prod( pooled_cov_inv,mean_diff)
			      ,mean_diff);
  T f_score= (t2_score*(n1 + n2 - 1- k))/(k*(  n1 + n2 - 2));

  std::cout << t2_score   << std::endl;
  std::cout << f_score   << std::endl;

  boost::math::fisher_f dist(k, n1+n2-1-k);
  T p_score =boost::math::cdf(dist, f_score);

  std::cout << p_score << std::endl;
  T p_comp =boost::math::cdf(complement(dist, f_score));
  std::cout << p_comp << std::endl;
  //return p_comp;
  return p_score;
}
Example #3
0
/* should output:
 * print_matrix:
 *  3  1 -1
 *  0 -2  0
 *  5  0  0
 * matrix minor:
 *  0  0
 *  5  0
 * ineff_det: -10
 * eff_det: 10 
 * lu decomposition is not unique, output can be checked manually
 * invert_lower_tri_matrix: 
 * 1.000000 0.000000 0.000000 
 * 0.000000 1.000000 0.000000 
 * -1.666667 -0.833333 1.000000 
 * invert_upper_tri_matrix: 
 * 0.333333 0.166667 0.200000 
 * 0.000000 -0.500000 0.000000 
 * 0.000000 -0.000000 0.600000 
 * invert_matrix: 
 * 0.000000 0.000000 0.200000 
 * 0.000000 -0.500000 0.000000 
 * -1.000000 -0.500000 0.600000 */
void test_matrix_functions() {
	matrix *a = identity_matrix(3);
	a->entries[0][0] = 3.0;
	a->entries[0][1] = 1.0;
	a->entries[0][2] = -1.0;
	a->entries[1][1] = -2.0;
	a->entries[2][0] = 5.0;
	a->entries[2][2] = 0.0;
	printf("print_matrix: \n");
	print_matrix(*a);
	printf("matrix_minor: \n");
	print_matrix(*matrix_minor(*a, 1));
	printf("ineff_det: %lf\n", (double) ineff_det(*a));
	printf("eff_det: %lf\n", (double) eff_det(*a));
	matrix *a_cpy = copy_matrix(*a);
	printf("lu_decomp: \n");
	matrix **pl = lu_decomp(a_cpy, (int*) NULL);
	print_matrix(*pl[0]);	// prints p
	print_matrix(*pl[1]);	// prints l
	print_matrix(*a_cpy);	// prints u
	printf("invert_lower_tri_matrix: \n");
	print_matrix(*invert_lower_tri_matrix(*pl[1]));
	printf("invert_upper_tri_matrix: \n");
	print_matrix(*invert_upper_tri_matrix(*a_cpy));
	printf("invert_matrix: \n");
	print_matrix(*invert_matrix(*a));
}
GLint GLAPIENTRY
gluUnProject4(GLdouble winx, GLdouble winy, GLdouble winz, GLdouble clipw,
	      const GLdouble modelMatrix[16],
	      const GLdouble projMatrix[16],
	      const GLint viewport[4],
	      GLclampd nearZ, GLclampd farZ,
	      GLdouble * objx, GLdouble * objy, GLdouble * objz,
	      GLdouble * objw)
{
   /* matrice de transformation */
   GLdouble m[16], A[16];
   GLdouble in[4], out[4];
   GLdouble z = nearZ + winz * (farZ - nearZ);

   /* transformation coordonnees normalisees entre -1 et 1 */
   in[0] = (winx - viewport[0]) * 2 / viewport[2] - 1.0;
   in[1] = (winy - viewport[1]) * 2 / viewport[3] - 1.0;
   in[2] = 2.0 * z - 1.0;
   in[3] = clipw;

   /* calcul transformation inverse */
   matmul(A, projMatrix, modelMatrix);
   if (!invert_matrix(A, m))
      return GL_FALSE;

   /* d'ou les coordonnees objets */
   transform_point(out, m, in);
   if (out[3] == 0.0)
      return GL_FALSE;
   *objx = out[0] / out[3];
   *objy = out[1] / out[3];
   *objz = out[2] / out[3];
   *objw = out[3];
   return GL_TRUE;
}
Example #5
0
/* transformation du point ecran (winx,winy,winz) en point objet */
GLint gluUnProject(GLdouble winx,GLdouble winy,GLdouble winz,
                   const GLdouble model[16],const GLdouble proj[16],
                   const GLint viewport[4],
                   GLdouble *objx,GLdouble *objy,GLdouble *objz)
{
    /* matrice de transformation */
    GLdouble m[16], A[16];
    GLdouble in[4],out[4];

    /* transformation coordonnees normalisees entre -1 et 1 */
    in[0]=(winx-viewport[0])*2/viewport[2] - 1.0;
    in[1]=(winy-viewport[1])*2/viewport[3] - 1.0;
    in[2]=2*winz - 1.0;
    in[3]=1.0;

    /* calcul transformation inverse */
    matmul(A,proj,model);
    invert_matrix(A,m);

    /* d'ou les coordonnees objets */
    transform_point(out,m,in);
    *objx=out[0]/out[3];
    *objy=out[1]/out[3];
    *objz=out[2]/out[3];
    return GL_TRUE;
}
Example #6
0
int main(int argc, char** argv)
{
  int matrix_size;
  int silent = 0;
  int optchar;
  elem_t *a, *inv, *prod;
  elem_t eps;
  double error;
  double ratio;

  while ((optchar = getopt(argc, argv, "qt:")) != EOF)
  {
    switch (optchar)
    {
    case 'q': silent = 1; break;
    case 't': s_nthread = atoi(optarg); break;
    default:
      fprintf(stderr, "Error: unknown option '%c'.\n", optchar);
      return 1;
    }
  }

  if (optind + 1 != argc)
  {
    fprintf(stderr, "Error: wrong number of arguments.\n");
  }
  matrix_size = atoi(argv[optind]);

  /* Error checking. */
  assert(matrix_size >= 1);
  assert(s_nthread >= 1);

  eps = epsilon();
  a = new_matrix(matrix_size, matrix_size);
  init_matrix(a, matrix_size, matrix_size);
  inv = invert_matrix(a, matrix_size);
  prod = multiply_matrices(a, matrix_size, matrix_size,
                           inv, matrix_size, matrix_size);
  error = identity_error(prod, matrix_size);
  ratio = error / (eps * matrix_size);
  if (! silent)
  {
    printf("error = %g; epsilon = %g; error / (epsilon * n) = %g\n",
           error, eps, ratio);
  }
  if (isfinite(ratio) && ratio < 100)
    printf("Error within bounds.\n");
  else
    printf("Error out of bounds.\n");
  delete_matrix(prod);
  delete_matrix(inv);
  delete_matrix(a);

  return 0;
}
Example #7
0
  //! \brief Calculate the Graph Potentials of a molecule
  //! 
  //! based on
  //! V.E. and Rozenblit, A.B. Golender
  //! <em>Logical and Combinatorial Algorithms for Drug Design</em>. \n
  //! For an example see:
  //! Walters, W. P., Yalkowsky, S. H., \em JCICS, 1996, 36(5), 1015-1017.
  //! <a href="http://dx.doi.org/10.1021/ci950278o">DOI: 10.1021/ci950278o</a>
  void GraphPotentials(OBMol &mol, std::vector<double> &pot)
  {
    double det;

    vector<vector<double> > g,c,h;
    construct_g_matrix(mol,g);
    invert_matrix(g,det);
    construct_c_matrix(mol,c);
    mult_matrix(h,g,c);
    pot.resize(mol.NumAtoms()+1);

    for (unsigned int i = 0; i < mol.NumAtoms();++i)
      pot[i+1] = h[i][0];
  }
Example #8
0
 void ForceCeperley::InitMatrix() {
   Sinv.resize(N_basis, N_basis);
   h.resize(N_basis);
   c.resize(N_basis);
   for(int k=0; k<N_basis; k++) {
     h[k] = std::pow(Rcut, (k+2))/static_cast<double>(k+2);
     for(int j=0; j<N_basis; j++) {
      Sinv(k,j) = std::pow(Rcut, (m_exp+k+j+3))/static_cast<double>(m_exp+k+j+3);
     }
   }
   // in Numerics/DeterminantOperators.h
   invert_matrix(Sinv, false);
   // in Numerics/MatrixOperators.h
   MatrixOperators::product(Sinv, h.data(), c.data());
 }
void constants (components_t* components,int M, int D) {
    float log_determinant;
    float* matrix = (float*)malloc(sizeof(float) * D * D);

    for(int m = 0; m < M; m++) {
        // Invert covariance matrix
        memcpy(matrix,&(components->R[m*D*D]),sizeof(float) * D * D);
        invert_matrix(matrix,D,&log_determinant);
        memcpy(&(components->Rinv[m*D*D]),matrix,sizeof(float) * D * D);
    
        // Compute constant
        components->constant[m] = -D * 0.5f * logf(2 * PI) - 0.5f * log_determinant;
        components->CP[m] = components->constant[m] * 2.0;
    }
    normalize_pi(components, M);
    free(matrix);
}
Example #10
0
static void
compute_transfer_matrix(mat4x4 * M, struct vec3 * pvecs, struct vec3 * tvecs)
{
	/* T: texture coords */
	/* P: physical coords */
	/* M: result matrix */
	/* M * T = P */
	/* M = P * T^(-1) */
	mat4x4 T, P;
	_matrix_load_identity(&T);
	_matrix_load_identity(&P);
	T.m[0][0] = tvecs[0].x;
	T.m[0][1] = tvecs[0].y;
	T.m[0][2] = 1.0;
	T.m[0][3] = 0.0;

	T.m[1][0] = tvecs[1].x;
	T.m[1][1] = tvecs[1].y;
	T.m[1][2] = 1.0;
	T.m[1][3] = 0.0;

	T.m[2][0] = tvecs[2].x;
	T.m[2][1] = tvecs[2].y;
	T.m[2][2] = 1.0;
	T.m[2][3] = 0.0;

	P.m[0][0] = pvecs[0].x;
	P.m[0][1] = pvecs[0].y;
	P.m[0][2] = pvecs[0].z;
	P.m[0][3] = 0.0;

	P.m[1][0] = pvecs[1].x;
	P.m[1][1] = pvecs[1].y;
	P.m[1][2] = pvecs[1].z;
	P.m[1][3] = 0.0;

	P.m[2][0] = pvecs[2].x;
	P.m[2][1] = pvecs[2].y;
	P.m[2][2] = pvecs[2].z;
	P.m[2][3] = 0.0;

	invert_matrix(&T, &T);
	mulmm(M, &P, &T);
	return;
}
Example #11
0
int make_block_invertible_matrix_pair(gf2matrix **m, gf2matrix **minv, int bits)
{
	int rc = 0;
	int i, j;
	gf2matrix *out = NULL, *outinv = NULL;
	assert(bits % 4 == 0);
	assert(m);

	while (out == NULL || get_rows(out) != bits) {
		gf2matrix *temp = extend_block_invertible_by2(out);
		free_matrix(out);
		out = dup_matrix(temp);
		free_matrix(temp);
	}
	*m = out;
	if (minv) {
		outinv = invert_matrix(NULL, out);
		assert(outinv);
		*minv = outinv;
	}
	return rc;
}
Example #12
0
int main(int argc, char** argv)
{
  int matrix_size;
  int silent;
  elem_t *a, *inv, *prod;
  elem_t eps;
  double error;
  double ratio;

  matrix_size = (argc > 1) ? atoi(argv[1]) : 3;
  s_nthread   = (argc > 2) ? atoi(argv[2]) : 3;
  silent      = (argc > 3) ? atoi(argv[3]) : 0;

  eps = epsilon();
  a = new_matrix(matrix_size, matrix_size);
  init_matrix(a, matrix_size, matrix_size);
  inv = invert_matrix(a, matrix_size);
  prod = multiply_matrices(a, matrix_size, matrix_size,
                           inv, matrix_size, matrix_size);
  error = identity_error(prod, matrix_size);
  ratio = error / (eps * matrix_size);
  if (! silent)
  {
    printf("error = %g; epsilon = %g; error / (epsilon * n) = %g\n",
           error, eps, ratio);
  }
  if (ratio < 100)
    printf("Error within bounds.\n");
  else
    printf("Error out of bounds.\n");
  delete_matrix(prod);
  delete_matrix(inv);
  delete_matrix(a);

  return 0;
}
int main(){
	printf("Let's test some linear algebra functions....\n\n");
	
	// create a random nxn matrix for later use
	matrix_t A = create_random_matrix(DIM,DIM);
	printf("New Random Matrix A:\n");
	print_matrix(A);
	
	// also create random vector
	vector_t b = create_random_vector(DIM);
	printf("\nNew Random Vector b:\n");
	print_vector(b);
	
	// do an LUP decomposition on A
	matrix_t L,U,P;
	LUP_decomposition(A,&L,&U,&P);
	printf("\nL:\n");
	print_matrix(L);
	printf("U:\n");
	print_matrix(U);
	printf("P:\n");
	print_matrix(P);
	
	// do a QR decomposition on A
	matrix_t Q,R;
	QR_decomposition(A,&Q,&R);
	printf("\nQR Decomposition of A\n");
	printf("Q:\n");
	print_matrix(Q);
	printf("R:\n");
	print_matrix(R);
	
	// get determinant of A
	float det = matrix_determinant(A);
	printf("\nDeterminant of A : %8.4f\n", det);
	
	// get an inverse for A
	matrix_t Ainv = invert_matrix(A);
	if(A.initialized != 1) return -1;
	printf("\nAinverse\n");
	print_matrix(Ainv);
	
	// multiply A times A inverse
	matrix_t AA = multiply_matrices(A,Ainv);
	if(AA.initialized!=1) return -1;
	printf("\nA * Ainverse:\n");
	print_matrix(AA);
	
	// solve a square linear system
	vector_t x = lin_system_solve(A, b);
	printf("\nGaussian Elimination solution x to the equation Ax=b:\n");
	print_vector(x);
	
	// now do again but with qr decomposition method
	vector_t xqr = lin_system_solve_qr(A, b);
	printf("\nQR solution x to the equation Ax=b:\n");
	print_vector(xqr);
	
	// If b are the coefficients of a polynomial, get the coefficients of the
	// new polynomial b^2
	vector_t bb = poly_power(b,2);
	printf("\nCoefficients of polynomial b times itself\n");
	print_vector(bb);
	
	// clean up all the allocated memory. This isn't strictly necessary since
	// we are already at the end of the program, but good practice to do.
	destroy_matrix(&A);
	destroy_matrix(&AA);
	destroy_vector(&b);
	destroy_vector(&bb);
	destroy_vector(&x);
	destroy_vector(&xqr);
	destroy_matrix(&Q);
	destroy_matrix(&R);

	printf("DONE\n");
	return 0;
}
Example #14
0
void TGaussianMixture::invert_covariance() {
	for(unsigned int k=0; k<nclusters; k++) {
		det_cov[k] = invert_matrix(cov[k], inv_cov[k], p, LU);
	}
}
Example #15
0
/*---------------------------------------------------------------------+
|                                 main                                 |
| ==================================================================== |
|                                                                      |
| Function:  ...                                                       |
|                                                                      |
+---------------------------------------------------------------------*/
int main (int argc, char **argv)
{
	FILE	*statfile;
	int	i;
	clock_t	start_time;		/* start & stop times */
	clock_t	stop_time;
	float	elapsed_time;
	struct tms timer_info;		/* time accounting info */

	/*
	 * Process command line arguments...
	 */
	parse_args (argc, argv);
	if (verbose) printf ("%s: Scheduler TestSuite program\n\n", *argv);
	if (debug) {
		printf ("\tpriority type:  %s\n", priority_type);
		printf ("\tpriority:       %d\n", priority);
		printf ("\tlogfile:        %s\n", logfile);
	}

	/*
	 * Adjust the priority of this process if the real time flag is set
	 */
	if (!strcmp (priority_type, "fixed")) {
#ifndef __linux__
                if (setpri (0, DEFAULT_PRIORITY) < 0)
                        sys_error ("setpri failed", __FILE__, __LINE__);
#else
                if (setpriority(PRIO_PROCESS, 0, 0) < 0)
                        sys_error ("setpri failed", __FILE__, __LINE__);
#endif
	} else {
		if (nice ((priority - 50) - (nice (0) + 20)) < 0 && errno != 0)
			sys_error ("nice failed", __FILE__, __LINE__);
	}

	/*
	 * Read from raw I/O device and record elapsed time...
	 */
	start_time = time ((time_t*)&timer_info);

	for (i=0; i < TIMES; i++)
		invert_matrix ();

	stop_time = time ((time_t*)&timer_info);
	elapsed_time = (float) (stop_time - start_time) / 100.0;

	if ((statfile = fopen (logfile, "w")) == NULL)
		sys_error ("fopen failed", __FILE__, __LINE__);

	fprintf (statfile, "%f\n", elapsed_time);
	if (debug) printf ("\n\telapsed time: %f\n", elapsed_time);

	if (fclose (statfile) < 0)
		sys_error ("fclose failed", __FILE__, __LINE__);

	/*
	 * Exit with success!
	 */
	if (verbose) printf ("\nsuccessful!\n");
	return (0);
}
Example #16
0
/* Take a set of observations and make a preliminary fit using the
 * linear model of the orbit.  Then fill in zero for gdot, and return
 * the fit and an uncertainty matrix.  The gdot term of uncertainty
 * matrix is set to a nominal value.
 * Note covar is assumed to be 6x6 1-indexed matrix a la Numerical Recipes.
 */
void
prelim_fit(OBSERVATION obsarray[],
	   int nobs,
	   PBASIS *pout,
	   double **covar)
{
  double *beta, *soln, **alpha;
  int	i,j,k;
  double x,y,wtx,wty,*dx,*dy;
  

  beta=dvector(1,6);
  alpha=dmatrix(1,6,1,6);
  soln=dvector(1,6);
  dx=dvector(1,6);
  dy=dvector(1,6);

  /* clear all vectors/matrices*/
  for (i=1; i<=6; i++) {
    beta[i]=soln[i]=0.;
    for (j=1; j<=6; j++) alpha[i][j]=0.;
  }

  /*Collect the requisite sums*/
  for (i=0; i<nobs; i++) {
    wtx = 1./obsarray[i].dthetax;
    wtx *= wtx;
    wty = 1./obsarray[i].dthetay;
    wty *= wty;


    kbo2d_linear(pout,&(obsarray[i]),&x,dx,&y,dy);

    /* Note that the dx[6] and dy[6] terms will only make
     * even the least sense if the pout->g and adot were set to
     * some sensible value beforehand.
     */

    for (j=1; j<=6; j++) {
      beta[j] += obsarray[i].thetax * dx[j] * wtx;
      beta[j] += obsarray[i].thetay * dy[j] * wty;
      for (k=1; k<=j; k++) {
        alpha[j][k] += dx[j]*dx[k]*wtx;
        alpha[j][k] += dy[j]*dy[k]*wty; 
      }
    }
  }

  /* Symmetrize and invert the alpha matrix to give covar.  Note
   * that I'm only going to bother with the first 5 params.
   */
  for (i=1; i<=5; i++)
    for (j=1; j<i; j++)
      alpha[j][i]=alpha[i][j];


  if (invert_matrix(alpha,covar,5)) {
    /* some failure in the inversion...*/
    fprintf(stderr,"Error inverting the alpha matrix\n");
    exit(1);
  }

  /* Now multiply matrices to get the solution vector */
  for (i=1; i<=5; i++) {
    soln[i]=0.;
    for (j=1; j<=5; j++)
      soln[i] += covar[i][j]*beta[j];
  }
   
 /* fill in the PBASIS structure */
  pout->a =    soln[1];
  pout->adot = soln[2];
  pout->b =    soln[3];
  pout->bdot = soln[4];
  pout->g    = soln[5];
  pout->gdot = 0.;              /*assuming that prelim fit has no info here*/

  /*Set the gdot parts of the covariance matrix to nominal values */
  for (i=1; i<6; i++)
    covar[i][6]=covar[6][i]=0.;
  covar[6][6]=0.1*TPI*TPI*pow(pout->g,3.);

  free_dvector(dx,1,6);
  free_dvector(dy,1,6);
  free_dvector(soln,1,6);
  free_dvector(beta,1,6);
  free_dmatrix(alpha,1,6,1,6);
  return;
}
Example #17
0
static void get_matrix(void) {
  glGetDoublev(GL_MODELVIEW_MATRIX, _matrix);
  invert_matrix(_matrix, _matrix_inverse);
}
Example #18
0
static GstFlowReturn
gst_patchdetect_transform_ip (GstBaseTransform * trans, GstBuffer * buf)
{
  GstPatchdetect *patchdetect = GST_PATCHDETECT (trans);
  Frame frame;
  Point *points;
  int i, j;
  int blocks_x, blocks_y;
  int n_points;
  int n_patches;
  Patch *patches;
  guint8 *patchpix;
  int vec1_x, vec1_y;
  int vec2_x, vec2_y;
  Color detected_colors[24];
  gboolean detected = FALSE;

  frame.y = GST_BUFFER_DATA (buf);
  frame.ystride = gst_video_format_get_row_stride (patchdetect->format,
      0, patchdetect->width);
  frame.u =
      frame.y + gst_video_format_get_component_offset (patchdetect->format, 1,
      patchdetect->width, patchdetect->height);
  frame.ustride =
      gst_video_format_get_row_stride (patchdetect->format, 1,
      patchdetect->width);
  frame.v =
      frame.y + gst_video_format_get_component_offset (patchdetect->format, 2,
      patchdetect->width, patchdetect->height);
  frame.vstride =
      gst_video_format_get_row_stride (patchdetect->format, 2,
      patchdetect->width);
  frame.width = patchdetect->width;
  frame.height = patchdetect->height;
  frame.t = patchdetect->t;
  patchdetect->t++;

  blocks_y = (patchdetect->height & (~7)) / 8;
  blocks_x = (patchdetect->width & (~7)) / 8;

  patchpix = g_malloc0 (patchdetect->width * patchdetect->height);
  patches = g_malloc0 (sizeof (Patch) * 256);

  n_patches = 0;
  for (j = 0; j < blocks_y; j += 4) {
    for (i = 0; i < blocks_x; i += 4) {
      Stats block = { 0 };

      get_block_stats (&frame, i * 8, j * 8, &block);

      patches[n_patches].val = n_patches + 2;
      if (block.match) {
        if (patch_check (&frame, patchpix, i * 8, j * 8, 8, 8)) {
          patch_start (&frame, patchpix, patches + n_patches, i * 8, j * 8, 8,
              8);

          patches[n_patches].y = block.y;
          patches[n_patches].u = block.u;
          patches[n_patches].v = block.v;

          patch_grow (&frame, patchpix, patches + n_patches);
          n_patches++;
          g_assert (n_patches < 256);
        }
      }
    }
  }

  {
    int n;

    for (n = 0; n < n_patches; n++) {
      Patch *patch = &patches[n];
      int xsum;
      int ysum;

      if (patch->count > 10000)
        continue;
      patch->valid = TRUE;

      xsum = 0;
      ysum = 0;
      for (j = patch->ymin; j < patch->ymax; j++) {
        for (i = patch->xmin; i < patch->xmax; i++) {
          if (patchpix[j * frame.width + i] != patch->val)
            continue;
          xsum += i;
          ysum += j;
        }
      }

      patch->cen_x = xsum / patch->count;
      patch->cen_y = ysum / patch->count;
    }

  }

  points = g_malloc0 (sizeof (Point) * 1000);
  n_points = 0;

  for (i = 0; i < n_patches; i++) {
    for (j = i + 1; j < n_patches; j++) {
      int dist_x, dist_y;

      if (i == j)
        continue;

      dist_x = patches[i].cen_x - patches[j].cen_x;
      dist_y = patches[i].cen_y - patches[j].cen_y;

      if (dist_x < 0) {
        dist_x = -dist_x;
        dist_y = -dist_y;
      }
      if (ABS (2 * dist_y) < dist_x && dist_x < 100) {
        points[n_points].x = dist_x;
        points[n_points].y = dist_y;
        points[n_points].valid = TRUE;
        points[n_points].patch1 = i;
        points[n_points].patch2 = j;
        n_points++;
        g_assert (n_points < 1000);
      }
    }
  }

  {
    int dist;
    int ave_x = 0, ave_y = 0;
    for (dist = 50; dist >= 10; dist -= 5) {
      int sum_x, sum_y;
      int n_valid;

      sum_x = 0;
      sum_y = 0;
      n_valid = 0;
      for (i = 0; i < n_points; i++) {
        if (!points[i].valid)
          continue;
        sum_x += points[i].x;
        sum_y += points[i].y;
        n_valid++;
      }
      if (n_valid == 0)
        continue;
      ave_x = sum_x / n_valid;
      ave_y = sum_y / n_valid;

      for (i = 0; i < n_points; i++) {
        int d;
        if (!points[i].valid)
          continue;
        d = (points[i].x - ave_x) * (points[i].x - ave_x);
        d += (points[i].y - ave_y) * (points[i].y - ave_y);
        if (d > dist * dist)
          points[i].valid = FALSE;
      }
    }
    vec1_x = ave_x;
    vec1_y = ave_y;
  }

  n_points = 0;
  for (i = 0; i < n_patches; i++) {
    for (j = i + 1; j < n_patches; j++) {
      int dist_x, dist_y;

      if (i == j)
        continue;

      dist_x = patches[i].cen_x - patches[j].cen_x;
      dist_y = patches[i].cen_y - patches[j].cen_y;

      if (dist_y < 0) {
        dist_x = -dist_x;
        dist_y = -dist_y;
      }
      if (ABS (2 * dist_x) < dist_y && dist_y < 100) {
        points[n_points].x = dist_x;
        points[n_points].y = dist_y;
        points[n_points].valid = TRUE;
        points[n_points].patch1 = i;
        points[n_points].patch2 = j;
        n_points++;
        g_assert (n_points < 1000);
      }
    }
  }

  {
    int dist;
    int ave_x = 0, ave_y = 0;
    for (dist = 50; dist >= 10; dist -= 5) {
      int sum_x, sum_y;
      int n_valid;

      sum_x = 0;
      sum_y = 0;
      n_valid = 0;
      for (i = 0; i < n_points; i++) {
        if (!points[i].valid)
          continue;
        sum_x += points[i].x;
        sum_y += points[i].y;
        n_valid++;
      }
      if (n_valid == 0)
        continue;
      ave_x = sum_x / n_valid;
      ave_y = sum_y / n_valid;

      for (i = 0; i < n_points; i++) {
        int d;
        if (!points[i].valid)
          continue;
        d = (points[i].x - ave_x) * (points[i].x - ave_x);
        d += (points[i].y - ave_y) * (points[i].y - ave_y);
        if (d > dist * dist)
          points[i].valid = FALSE;
      }
    }
    vec2_x = ave_x;
    vec2_y = ave_y;
  }

#if 0
  for (i = 0; i < n_points; i++) {
    if (!points[i].valid)
      continue;
    paint_block (&frame, 4 * points[i].x, 240 + 4 * points[i].y, 16);
  }
#endif
#if 0
  paint_block (&frame, 360, 240, 16);
  paint_block (&frame, 360 + vec1_x, 240 + vec1_y, 16);
  paint_block (&frame, 360 + vec2_x, 240 + vec2_y, 16);
#endif

  {
    double m00, m01, m10, m11;
    double det;
    double v1, v2;
    double ave_v1 = 0, ave_v2 = 0;

    det = vec1_x * vec2_y - vec1_y * vec2_x;
    m00 = vec2_y / det;
    m01 = -vec2_x / det;
    m10 = -vec1_y / det;
    m11 = vec1_x / det;

    for (i = 0; i < n_patches - 1; i++) {
      int count = 0;
      double sum_v1 = 0;
      double sum_v2 = 0;

      if (!patches[i].valid)
        continue;

      n_points = 0;
      for (j = i + 1; j < n_patches; j++) {
        int diff_x = patches[j].cen_x - patches[i].cen_x;
        int diff_y = patches[j].cen_y - patches[i].cen_y;

        if (!patches[j].valid)
          continue;

        v1 = diff_x * m00 + diff_y * m01;
        v2 = diff_x * m10 + diff_y * m11;

        if (v1 > -0.5 && v1 < 5.5 && v2 > -0.5 && v2 < 3.5 &&
            ABS (v1 - rint (v1)) < 0.1 && ABS (v2 - rint (v2)) < 0.1) {
          sum_v1 += v1 - rint (v1);
          sum_v2 += v2 - rint (v2);
          count++;
        }
      }
      ave_v1 = sum_v1 / count;
      ave_v2 = sum_v2 / count;

      if (count > 20) {
        int k;
        for (j = 0; j < 4; j++) {
          for (k = 0; k < 6; k++) {
            Stats block;

            int xx;
            int yy;
            xx = patches[i].cen_x + (ave_v1 + k) * vec1_x + (ave_v2 +
                j) * vec2_x;
            yy = patches[i].cen_y + (ave_v1 + k) * vec1_y + (ave_v2 +
                j) * vec2_y;

            get_block_stats (&frame, xx - 4, yy - 4, &block);
            //GST_ERROR("%d %d: %d %d %d", k, j, block.y, block.u, block.v);

            detected_colors[k + j * 6].y = block.y;
            detected_colors[k + j * 6].u = block.u;
            detected_colors[k + j * 6].v = block.v;

            paint_block (&frame, xx - 4, yy - 4, 16);
          }
        }

        detected = TRUE;

#if 0
        for (j = i + 1; j < n_patches; j++) {
          int diff_x = patches[j].cen_x - patches[i].cen_x;
          int diff_y = patches[j].cen_y - patches[i].cen_y;
          int xx;
          int yy;

          if (!patches[j].valid)
            continue;

          v1 = diff_x * m00 + diff_y * m01;
          v2 = diff_x * m10 + diff_y * m11;

          if (v1 > -0.5 && v1 < 5.5 && v2 > -0.5 && v2 < 3.5 &&
              ABS (v1 - rint (v1)) < 0.1 && ABS (v2 - rint (v2)) < 0.1) {
            v1 = rint (v1);
            v2 = rint (v2);
            xx = patches[i].cen_x + (ave_v1 + v1) * vec1_x + (ave_v2 +
                v2) * vec2_x;
            yy = patches[i].cen_y + (ave_v1 + v1) * vec1_y + (ave_v2 +
                v2) * vec2_y;

            paint_block (&frame, patches[j].cen_x, patches[j].cen_y, 128);
            paint_block (&frame, xx, yy, 16);
          }
        }
        paint_block (&frame, patches[i].cen_x, patches[i].cen_y, 240);
#endif
        break;
      }
    }
  }

#define N 10
  if (detected) {
    int i, j, k;
    int n = N;
    double diff = 0;
    double matrix[10][10] = { {0} };
    double vy[10] = { 0 };
    double vu[10] = { 0 };
    double vv[10] = { 0 };
    double *by = patchdetect->by;
    double *bu = patchdetect->bu;
    double *bv = patchdetect->bv;
    double flip_diff = 0;

    for (i = 0; i < 24; i++) {
      diff += ABS (detected_colors[i].y - patch_colors[i].y);
      diff += ABS (detected_colors[i].u - patch_colors[i].u);
      diff += ABS (detected_colors[i].v - patch_colors[i].v);

      flip_diff += ABS (detected_colors[23 - i].y - patch_colors[i].y);
      flip_diff += ABS (detected_colors[23 - i].u - patch_colors[i].u);
      flip_diff += ABS (detected_colors[23 - i].v - patch_colors[i].v);
    }
    GST_ERROR ("uncorrected error %g (flipped %g)", diff / 24.0,
        flip_diff / 24.0);
    if (flip_diff < diff) {
      for (i = 0; i < 12; i++) {
        Color tmp;
        tmp = detected_colors[i];
        detected_colors[i] = detected_colors[23 - i];
        detected_colors[23 - i] = tmp;
      }
    }

    for (i = 0; i < 24; i++) {
      int dy = detected_colors[i].y - patch_colors[i].y;
      int du = detected_colors[i].u - patch_colors[i].u;
      int dv = detected_colors[i].v - patch_colors[i].v;
      int py = detected_colors[i].y - 128;
      int pu = detected_colors[i].u - 128;
      int pv = detected_colors[i].v - 128;
      int w = (i < 18) ? 1 : 2;
      double z[10];

      diff += ABS (dy) + ABS (du) + ABS (dv);

      z[0] = 1;
      z[1] = py;
      z[2] = pu;
      z[3] = pv;
      z[4] = py * py;
      z[5] = py * pu;
      z[6] = py * pv;
      z[7] = pu * pu;
      z[8] = pu * pv;
      z[9] = pv * pv;

      for (j = 0; j < n; j++) {
        for (k = 0; k < n; k++) {
          matrix[j][k] += w * z[j] * z[k];
        }

        vy[j] += w * dy * z[j];
        vu[j] += w * du * z[j];
        vv[j] += w * dv * z[j];
      }
    }

    invert_matrix (matrix, n);

    for (i = 0; i < n; i++) {
      by[i] = 0;
      bu[i] = 0;
      bv[i] = 0;
      for (j = 0; j < n; j++) {
        by[i] += matrix[i][j] * vy[j];
        bu[i] += matrix[i][j] * vu[j];
        bv[i] += matrix[i][j] * vv[j];
      }
    }

    //GST_ERROR("a %g %g %g b %g %g %g", ay, au, av, by, bu, bv);

    diff = 0;
    for (i = 0; i < 24; i++) {
      double cy, cu, cv;
      double z[10];
      int py = detected_colors[i].y - 128;
      int pu = detected_colors[i].u - 128;
      int pv = detected_colors[i].v - 128;

      z[0] = 1;
      z[1] = py;
      z[2] = pu;
      z[3] = pv;
      z[4] = py * py;
      z[5] = py * pu;
      z[6] = py * pv;
      z[7] = pu * pu;
      z[8] = pu * pv;
      z[9] = pv * pv;

      cy = 0;
      cu = 0;
      cv = 0;
      for (j = 0; j < n; j++) {
        cy += by[j] * z[j];
        cu += bu[j] * z[j];
        cv += bv[j] * z[j];
      }

      diff += fabs (patch_colors[i].y - (128 + py - cy));
      diff += fabs (patch_colors[i].u - (128 + pu - cu));
      diff += fabs (patch_colors[i].v - (128 + pv - cv));
    }
    GST_ERROR ("average error %g", diff / 24.0);
    patchdetect->valid = 3000;
  }

  if (patchdetect->valid > 0) {
    int n = N;
    guint8 *u1, *u2;
    guint8 *v1, *v2;
    double *by = patchdetect->by;
    double *bu = patchdetect->bu;
    double *bv = patchdetect->bv;

    patchdetect->valid--;
    u1 = g_malloc (frame.width);
    u2 = g_malloc (frame.width);
    v1 = g_malloc (frame.width);
    v2 = g_malloc (frame.width);

    for (j = 0; j < frame.height; j += 2) {
      for (i = 0; i < frame.width / 2; i++) {
        u1[2 * i + 0] = frame.u[(j / 2) * frame.ustride + i];
        u1[2 * i + 1] = u1[2 * i + 0];
        u2[2 * i + 0] = u1[2 * i + 0];
        u2[2 * i + 1] = u1[2 * i + 0];
        v1[2 * i + 0] = frame.v[(j / 2) * frame.vstride + i];
        v1[2 * i + 1] = v1[2 * i + 0];
        v2[2 * i + 0] = v1[2 * i + 0];
        v2[2 * i + 1] = v1[2 * i + 0];
      }
      for (i = 0; i < frame.width; i++) {
        int k;
        double z[10];
        double cy, cu, cv;
        int y, u, v;
        int py, pu, pv;

        y = frame.y[(j + 0) * frame.ystride + i];
        u = u1[i];
        v = v1[i];

        py = y - 128;
        pu = u - 128;
        pv = v - 128;

        z[0] = 1;
        z[1] = py;
        z[2] = pu;
        z[3] = pv;
        z[4] = py * py;
        z[5] = py * pu;
        z[6] = py * pv;
        z[7] = pu * pu;
        z[8] = pu * pv;
        z[9] = pv * pv;

        cy = 0;
        cu = 0;
        cv = 0;
        for (k = 0; k < n; k++) {
          cy += by[k] * z[k];
          cu += bu[k] * z[k];
          cv += bv[k] * z[k];
        }

        frame.y[(j + 0) * frame.ystride + i] = CLAMP (rint (y - cy), 0, 255);
        u1[i] = CLAMP (rint (u - cu), 0, 255);
        v1[i] = CLAMP (rint (v - cv), 0, 255);

        y = frame.y[(j + 1) * frame.ystride + i];
        u = u2[i];
        v = v2[i];

        py = y - 128;
        pu = u - 128;
        pv = v - 128;

        z[0] = 1;
        z[1] = py;
        z[2] = pu;
        z[3] = pv;
        z[4] = py * py;
        z[5] = py * pu;
        z[6] = py * pv;
        z[7] = pu * pu;
        z[8] = pu * pv;
        z[9] = pv * pv;

        cy = 0;
        cu = 0;
        cv = 0;
        for (k = 0; k < n; k++) {
          cy += by[k] * z[k];
          cu += bu[k] * z[k];
          cv += bv[k] * z[k];
        }

        frame.y[(j + 1) * frame.ystride + i] = CLAMP (rint (y - cy), 0, 255);
        u2[i] = CLAMP (rint (u - cu), 0, 255);
        v2[i] = CLAMP (rint (v - cv), 0, 255);
      }
      for (i = 0; i < frame.width / 2; i++) {
        frame.u[(j / 2) * frame.ustride + i] = (u1[2 * i + 0] +
            u1[2 * i + 1] + u2[2 * i + 0] + u2[2 * i + 1] + 2) >> 2;
        frame.v[(j / 2) * frame.vstride + i] = (v1[2 * i + 0] +
            v1[2 * i + 1] + v2[2 * i + 0] + v2[2 * i + 1] + 2) >> 2;
      }
    }

    g_free (u1);
    g_free (u2);
    g_free (v1);
    g_free (v2);
  }
Example #19
0
/**
 * @detail
 * All variables are named as in the fore mentioned paper
 * 1. Use a row of blocks of Matrix M to create a matrix X
 * 2. Use a column of blocks of Matrix M to create a matrix Y
 * 3. Get invertible matrices P and Q such that P(X.Minv.Y)Q = [I 0]
 *    (I is of r dimension; 0 is of 2-r dimension; 0 < r < 3)
 * 4. Define matrix A as follows:
 * 		a) if r = 0 then A = I
 * 		b) if r = 1 then A = [[1 1] [1 0]]
 * 		c) if r = 2 then A = [[0 1] [1 1]]
 * 5. Then the following is a (t+2, 2) block invertible matrix:
 * 		|  M           Y             |
 * 		|  X  X.Minv.Y + Pinv.A.Qinv |
 */
static gf2matrix *extend_block_invertible_by2(const gf2matrix *m)
{
	gf2matrix *result = NULL;
	gf2matrix *x = NULL, *y = NULL;
	int multiples = get_rows(m) / 2;
	int x_start = get_random(0, multiples - 1) * 2;
	int y_start = get_random(0, multiples - 1) * 2;
	if (!m) {
		gf2matrix *_2x2;
		get_2x2invertible_pair(get_random(0, MAX_2X2_INVERTIBLES - 1), &_2x2,
				NULL);
		result = dup_matrix(_2x2);
		return result;
	}
	/* print_matrix(m, "Extending m by 2:"); */

	/*  step 1 */
	x = extract_block_row(NULL, x_start, m);
	assert(x);
	/* print_matrix(x, "X:"); */

	/*  step 2 */
	y = extract_block_col(NULL, y_start, m);
	assert(y);
	/* print_matrix(y, "Y:"); */
	{ /*  steps 3, 4, 5 */
		int r; /* r is the rank of X.Minv.Y */
		gf2matrix *i0mat = new_matrix(2, 2);
		gf2matrix *prod = new_matrix(2, 2);
		gf2matrix *temp = NULL;
		gf2matrix *mInv = invert_matrix(NULL, m);
		gf2matrix *xminvy = NULL;
		gf2matrix *a2 = NULL;
		{
			assert(mInv);
			/*  calculate X.Minv.Y */
			gf2matrix *minvy = mul_matrices(NULL, mInv, y);
			xminvy = mul_matrices(NULL, x, minvy);
			assert(xminvy);
			free_matrix(minvy);
		}
		/* print_matrix(xminvy, "xM-1y: "); */
		r = calc_rank(xminvy);
		/* printf("rank of X.Minv.Y = %d\n", r); */
		init_IO_matrix(i0mat, r);
		/* print_matrix(i0mat, "I0:"); */
		a2 = make_A2_matrix(r);

		temp = new_matrix(2, 2);
		while (!result) {
			int i, j, i_tries, j_tries;
			for (i = get_random(0, MAX_2X2_INVERTIBLES - 1), i_tries = 0; i_tries
					< MAX_2X2_INVERTIBLES && !result; i = (i + 1)
					% MAX_2X2_INVERTIBLES, ++i_tries) {
				gf2matrix *q, *qinv;
				get_2x2invertible_pair(i, &q, &qinv);
				/* print_matrix(q, "Q:"); */
				mul_matrices(temp, xminvy, q);
				assert(temp);
				for (j = get_random(0, MAX_2X2_INVERTIBLES - 1), j_tries = 0; j_tries
						< MAX_2X2_INVERTIBLES && !result; j = (j + 1)
						% MAX_2X2_INVERTIBLES, ++j_tries) {
					gf2matrix *p, *pinv;
					get_2x2invertible_pair(j, &p, &pinv);
					mul_matrices(prod, p, temp);
					assert(prod);
					/* print_matrix(p, "P:"); */
					/* print_matrix(prod, "P.X.Minv.Y.Q:"); */
					if (comp_matrices(prod, i0mat) == 0) {
						/*  step 5 */
						result = extend_by_blocks(m, x, y, xminvy, pinv, a2,
								qinv);
						assert(result);
						break;
					}
				}
			}
		}
		free_matrix(a2);
		free_matrix(xminvy);
		free_matrix(mInv);
		free_matrix(prod);
		free_matrix(temp);
		free_matrix(i0mat);

		if (!result)
			printf("incorrect matrix expansion algorithm");
	}
	cleanup: free_matrix(y);
	free_matrix(x);
	return result;
}
Example #20
0
void decode_file(char *confFile, char *outFile, int nativeBlockNum, int parityBlockNum)
{
    int chunkSize = 1;
    int totalSize;

    uint8_t *dataBuf;
    uint8_t *codeBuf;

    int dataSize;
    int codeSize;

    FILE *fp_in;
    FILE *fp_out;

    int totalMatrixSize;
    int matrixSize;
    uint8_t *totalEncodingMatrix;
    uint8_t *encodingMatrix;
    if( ( fp_in = fopen(".METADATA","rb") ) == NULL )
    {
        printf("Can not open source file!\n");
        exit(0);
    }
    fscanf(fp_in, "%d", &totalSize);
    fscanf(fp_in, "%d %d", &parityBlockNum, &nativeBlockNum);
    //	chunkSize = (int) (ceil( (float) (totalSize / nativeBlockNum) )); 
    chunkSize = (totalSize / nativeBlockNum) + ( totalSize%nativeBlockNum != 0 ); 
#ifdef DEBUG
    printf("chunk size: %d\n", chunkSize);
#endif
    totalMatrixSize = nativeBlockNum * ( nativeBlockNum + parityBlockNum );
    totalEncodingMatrix = (uint8_t*) malloc( totalMatrixSize );
    matrixSize = nativeBlockNum * nativeBlockNum;
    encodingMatrix = (uint8_t*) malloc( matrixSize );
    int i;
    for(i =0; i<nativeBlockNum*(nativeBlockNum+parityBlockNum); i++)
    {
        fscanf(fp_in, "%d", totalEncodingMatrix+i);
    }

    dataSize = nativeBlockNum*chunkSize*sizeof(uint8_t);
    codeSize = nativeBlockNum*chunkSize*sizeof(uint8_t);
    dataBuf = (uint8_t*) malloc( dataSize );
    memset(dataBuf, 0, dataSize);
    codeBuf = (uint8_t*) malloc( codeSize);
    memset(codeBuf, 0, codeSize);

    if(confFile != NULL)
    {
        FILE *fp_conf;
        char input_file_name[100];
        int index;
        fp_conf = fopen(confFile, "r");

        for(i=0; i<nativeBlockNum; i++)
        {
            fscanf(fp_conf, "%s", input_file_name);
            index = atoi(input_file_name+1);

            copy_matrix(totalEncodingMatrix, encodingMatrix, index, i, nativeBlockNum);

            fp_in = fopen(input_file_name, "rb");
            fseek(fp_in, 0L, SEEK_SET);
            // this part can be process in parallel with computing inversed matrix
            fread(codeBuf+i*chunkSize, sizeof(uint8_t), chunkSize, fp_in);
            fclose(fp_in);
        }
        fclose(fp_conf);
    }
    else
    {
        for(i=0; i<nativeBlockNum; i++)
        {
            char input_file_name[100];
            int index;
            printf("Please enter the file name of fragment:\n");
            scanf("%s", input_file_name);
            index = atoi(input_file_name+1);
            printf("#%dth fragment\n", index);

            copy_matrix(totalEncodingMatrix, encodingMatrix, index, i, nativeBlockNum);

            fp_in = fopen(input_file_name, "rb");
            fseek(fp_in, 0L, SEEK_SET);
            // TODO: this part can be process in parallel with computing inversed matrix
            fread(codeBuf+i*chunkSize, sizeof(uint8_t), chunkSize, fp_in);
            fclose(fp_in);

        }
    }

    struct timespec start, end;
    double totalTime;
    clock_gettime(CLOCK_REALTIME,&start);
    uint8_t *decodingMatrix;
    decodingMatrix = (uint8_t*) malloc( matrixSize );

    invert_matrix(encodingMatrix, decodingMatrix, nativeBlockNum);
    //#ifndef DEBUG
    //	show_matrix(totalEncodingMatrix, nativeBlockNum+parityBlockNum, nativeBlockNum);
    //#endif

    //#ifndef DEBUG
    decode_chunk(dataBuf, decodingMatrix, codeBuf, nativeBlockNum, parityBlockNum, chunkSize);
    //#endif
    //#ifdef DEBUG
    //	uint8_t test_DM[16] = {1,0,0,0, 2,1,3,7, 3,1,2,6, 0,0,0,1};	
    //	decode_chunk(dataBuf, test_DM, codeBuf, nativeBlockNum, parityBlockNum, chunkSize);
    //#endif	
    clock_gettime(CLOCK_REALTIME,&end);
    totalTime = (double)(end.tv_sec-start.tv_sec)*1000+(double)(end.tv_nsec-start.tv_nsec)/(double)1000000L;
    printf("Total CPU decoding time: %fms\n", totalTime);

    if(outFile == NULL)
    {
        char output_file_name[100];
        printf("Enter the name of the decoded file:\n");
        scanf("%s", output_file_name);
        fp_out = fopen(output_file_name, "wb");
    }
    else
    {
        fp_out = fopen(outFile, "wb");
    }
    fwrite(dataBuf, sizeof(uint8_t), totalSize, fp_out);
    fclose(fp_out);

    free(dataBuf);
    free(codeBuf);

}
Example #21
0
void make_fit(int number,double *newcast)
{
  double *sj,*si,lavi,lavj,fav;
  long i,i1,j,j1,hi,hj,hi1,hj1,n,which;
  static int hdim;

  hdim=(embed-1)*DELAY;

  for (i=0;i<dim*embed;i++)
    localav[i]=0.0;
  for (i=0;i<dim;i++)
    foreav[i]=0.0;

  for (n=0;n<number;n++) {
    which=found[n];
    for (j=0;j<dim;j++) {
      sj=series[j];
      foreav[j] += sj[which+1];
      for (j1=0;j1<embed;j1++) {
	hj=j*embed+j1;
	localav[hj] += sj[which-j1*DELAY];
      }
    }
  }

  for (i=0;i<dim*embed;i++)
    localav[i] /= number;
  for (i=0;i<dim;i++)
    foreav[i] /= number;

  for (i=0;i<dim;i++) {
    si=series[i];
    for (i1=0;i1<embed;i1++) {
      hi=i*embed+i1;
      lavi=localav[hi];
      hi1=i1*DELAY;
      for (j=0;j<dim;j++) {
	sj=series[j];
	for (j1=0;j1<embed;j1++) {
	  hj=j*embed+j1;
	  lavj=localav[hj];
	  hj1=j1*DELAY;
	  mat[hi][hj]=0.0;
	  if (hj >= hi) {
	    for (n=0;n<number;n++) {
	      which=found[n];
	      mat[hi][hj] += (si[which-hi1]-lavi)*(sj[which-hj1]-lavj);
	    }
	  }
	}
      }
    }
  }
  
  for (i=0;i<dim*embed;i++)
    for (j=i;j<dim*embed;j++) {
      mat[i][j] /= number;
      mat[j][i]=mat[i][j];
    }
  
  imat=invert_matrix(mat,dim*embed);

  for (i=0;i<dim;i++) {
    si=series[i];
    fav=foreav[i];
    for (j=0;j<dim;j++) {
      sj=series[j];
      for (j1=0;j1<embed;j1++) {
	hj=j*embed+j1;
	lavj=localav[hj];
	hj1=j1*DELAY;
	vec[hj]=0.0;
	for (n=0;n<number;n++) {
	  which=found[n];
	  vec[hj] += (si[which+1]-fav)*(sj[which-hj1]-lavj);
	}
	vec[hj] /= number;
      }
    }

    multiply_matrix(imat,vec);

    newcast[i]=foreav[i];
    for (j=0;j<dim;j++) {
      for (j1=0;j1<embed;j1++) {
	hj=j*embed+j1;
	newcast[i] += vec[hj]*(cast[hdim-j1*DELAY][j]-localav[hj]);
      }
    }
  }
  
  for (i=0;i<dim*embed;i++)
    free(imat[i]);
  free(imat);
}
Example #22
0
/* invert gcov to get gcon */
void gcon_func(double gcov[][NDIM], double gcon[][NDIM])
{
  invert_matrix( gcov, gcon );
}
Example #23
0
int init_newton_transform(preprocessed *prep, float reqscale,
                          char *filename, int dimen)
/*
*/
{
  int  ii, jj;
  unsigned short matdim;
  double scale, onerow[MAX_DIMEN];
  PFile* dfpt;
  long foffset;
  double xfp;
  /* Open file
  */
  ASSERT(prep);
  ASSERT(filename);
  dfpt = file_must_open(NULL, filename, ("rb"), ESR_TRUE);
  prep->post_proc |= LIN_TRAN;
  prep->use_dim = dimen;
  pfread(&matdim, sizeof(short), 1, dfpt);
  if (matdim > MAX_DIMEN)
    SERVICE_ERROR(BAD_IMELDA);

  create_linear_transform(prep, matdim, 1);
  pfread(&scale, sizeof(double), 1, dfpt);

  if (reqscale != 0) scale = reqscale;
#if DEBUG
  PLogMessage("L: LDA Suggested scale is %.1f\n", scale);
#endif
  if (!prep->dim) prep->dim = matdim;
  else if (prep->dim != matdim)
  {
    log_report("Data (%d) and LDA (%d) dimensions don't match\n",
               prep->dim, matdim);
    SERVICE_ERROR(BAD_IMELDA);
  }

  /*  Eigenvalues, ignored
  */
  pfread(onerow, sizeof(double), matdim, dfpt);

  /*  Translation Vector
  */
  pfread(onerow, sizeof(double), matdim, dfpt);
  for (ii = 0; ii < matdim; ii++)
  {
    xfp = scale * (onerow[ii] - UTB_MEAN) + UTB_MEAN;
    if (xfp > 0.0)
      xfp += 0.5;
    else if (xfp < 0.0)
      xfp -= 0.5;

    prep->offset[ii] = (imeldata) xfp;
  }

  /*  The imelda matrix
  */
  for (ii = 0; ii < matdim; ii++)
  {
    pfread(onerow, sizeof(double), matdim, dfpt);
    for (jj = 0; jj < matdim; jj++)
      prep->imelda[ii][jj] = (covdata)(scale * onerow[jj]);
  }

  prep->imel_shift = scale_matrix_for_fixedpoint(prep->matrix,
                     prep->imelda, matdim);

  /* The inverse imelda matrix
   */
  foffset = pftell(dfpt);
  pfread(onerow, sizeof(double), matdim, dfpt);

  if (pfeof(dfpt) != 0)
  {
#ifdef SREC_ENGINE_VERBOSE_LOGGING
    PLogMessage("W: Inverting imelda matrix");
#endif
    invert_matrix(prep->imelda, prep->inverse, prep->dim);
  }
  else
  {
    pfseek(dfpt, foffset, SEEK_SET);

    for (ii = 0; ii < matdim; ii++)
    {
      pfread(onerow, sizeof(double), matdim, dfpt);
      for (jj = 0; jj < matdim; jj++)
        prep->inverse[ii][jj] = (covdata)(onerow[jj] / scale);
    }
  }

  prep->inv_shift = scale_matrix_for_fixedpoint(prep->invmat,
                    prep->inverse, matdim);

  pfclose(dfpt);
  return (0);
}