Esempio n. 1
0
void icaTransform(double** X, int rows, int cols, int comp, double **S,
                  double** K, double** W) {
    double **A;
    FILE * OutputFile;
    int i, j;

    A = mat_create(comp, comp);

    //thuc hien ICA
    fastICA(X, rows, cols, comp, K, W, A, S);
    puts(">>>>>>>>>>...run ica complete.");

//In cac thanh phan doc lap
    FILE * file = fopen("/home/truongnh/eeg-lab411/SignalProcessing/RemoveEyeblink/Data/outICA.txt", "w+");
    for(i=0; i<rows; i++) {
        for(j=0; j<cols; j++) {
            fprintf(file, "%lf\t", S[i][j]);
        }
        fprintf(file, "\n");
    }
    fclose(file);


    /*
     //in cac thanh phan doc lap ra
     for (j = 0; j < comp; j++) {
     if(j==0)
     OutputFile = fopen("/storage/sdcard0/NickGun/EEG/Liec-len-xuong/DataICA", "wb");
     else
     OutputFile = fopen("/storage/sdcard0/NickGun/EEG/Liec-len-xuong/DataICA", "at");
     fprintf(OutputFile, "********************Comp %i\n", j);
     for (i = 0; i < rows; i++) {
     fprintf(OutputFile, "%f\n", S[i][j]);
     }
     fclose(OutputFile);
     }*/
    mat_delete(A, comp, comp);
}
int main()
{
  int i, j;
  int w, h;
  int levels, ct_levels, wt_levels,level_init;
  double rate,rate_init;
  ivec dfb_levels;
  mat source, dest;
  contourlet_t *contourlet;
  mat wavelet;
  int length;
  unsigned char *buffer;

  //³õʼ»¯²ÎÊý
  int argc=6;
      rate_init=2;
	  level_init=5;


#define LEVELS 5
#define IMPULSE 100.

  source = mat_pgm_read("1.pgm");
  h = mat_height(source);
  w = mat_width(source);
  dest = mat_new(w, h);
  rate = rate_init * w * h;
  levels = level_init;
  ct_levels = argc - 4;              /* contourlet levels */
  wt_levels = levels - ct_levels;    /* wavelet levels */
  dfb_levels = ivec_new(ct_levels);
  for(i = 0; i < ct_levels; i++)
    dfb_levels[i] = 4+i;


  buffer = bvec_new_zeros(BUFFER_SIZE);

  contourlet = contourlet_new(ct_levels, dfb_levels);
  contourlet->wt_levels = wt_levels;

  contourlet_transform(contourlet, source);
  wavelet = it_dwt2D(contourlet->low, it_wavelet_lifting_97, wt_levels);
  contourlet->dwt = it_wavelet2D_split(wavelet, wt_levels);

  /* normalize the subbands */
  for(i = 0; i < ct_levels; i++)
    for(j = 0; j < (1 << dfb_levels[i]); j++)
      mat_mul_by(contourlet->high[i][j], norm_high[1+i][dfb_levels[i]][j]);
  mat_mul_by(contourlet->low, norm_low[ct_levels]);

  /* make flat images */
  mat_pgm_write("dwt.pgm", wavelet);
  for(i = 0; i < ct_levels; i++) {
    char filename[256];

    mat dfb_rec = mat_new((h >> i) + 1, (w >> i) + 1);
    if(dfb_levels[i])
      dfb_flatten(contourlet->high[i], dfb_rec, dfb_levels[i]);
    else
      mat_set_submatrix(dfb_rec, contourlet->high[i][0], 0, 0);
    mat_incr(dfb_rec, 128);
    sprintf(filename, "dfb%d.pgm", i);
    mat_pgm_write(filename, dfb_rec);
    mat_decr(dfb_rec, 128);
    mat_delete(dfb_rec);
  }

  /* EZBC encoding */
  length = ezbc_encode(contourlet, buffer, BUFFER_SIZE, rate);

  /* EZBC decoding */
  ezbc_decode(contourlet, buffer, BUFFER_SIZE, rate);

  mat_pgm_write("rec_low.pgm", contourlet->dwt[0]);

  /* make flat images */
  for(i = 0; i < ct_levels; i++) {
    char filename[256];

    mat dfb_rec = mat_new((h >> i) + 1, (w >> i) + 1);
    if(dfb_levels[i])
      dfb_flatten(contourlet->high[i], dfb_rec, dfb_levels[i]);
    else
      mat_set_submatrix(dfb_rec, contourlet->high[i][0], 0, 0);
    mat_incr(dfb_rec, 128);
    sprintf(filename, "rec_dfb%d.pgm", i);
    mat_pgm_write(filename, dfb_rec);
    mat_decr(dfb_rec, 128);
    mat_delete(dfb_rec);
  }

  /* normalize the subbands */
  for(i = 0; i < ct_levels; i++)
    for(j = 0; j < (1 << dfb_levels[i]); j++)
      mat_div_by(contourlet->high[i][j], norm_high[1+i][dfb_levels[i]][j]);
  mat_div_by(contourlet->low, norm_low[ct_levels]);


  //  mat_pgm_write("rec_low.pgm", contourlet->dwt[0]);

  /* TODO: fix this in libit */
  if(wt_levels)
    wavelet = it_wavelet2D_merge(contourlet->dwt, wt_levels);
  else
    mat_copy(wavelet, contourlet->dwt[0]);

  mat_pgm_write("rec_dwt.pgm", wavelet);

  contourlet->low = it_idwt2D(wavelet, it_wavelet_lifting_97, wt_levels);

  contourlet_itransform(contourlet, dest);

  contourlet_delete(contourlet);

  mat_pgm_write("rec.pgm", dest);

  printf("rate = %f PSNR = %f\n", length * 8. / (w*h), 10*log10(255*255/mat_distance_mse(source, dest, 0)));

  ivec_delete(dfb_levels);
  mat_delete(dest);
  mat_delete(source);
  bvec_delete(buffer);

  return(0);
}
int main ()
{
  it_wavelet_t *wavelet;
  it_wavelet2D_t *wavelet2D;
  it_separable2D_t *separable;
  const char *image_in = "../data/test.pgm";
  const char *image_out = "out.pgm";
  const char *sound_in = "../data/test.wav";
  const char *sound_out = "out.wav";
  char pnm_type, comments[1000];
  int  width, height, maxval;
  int  levels;
  int  length, channels, srate, depth;
  mat  m, mt;
  vec  v, vt;

  levels = 4;

  /* Read the sound */
  if (!wav_info (sound_in, &channels, &srate, &depth, &length)) {
    fprintf (stderr, "unable to open file %s\n", sound_in);
    return (1);
  }
  printf
    ("file name = %s\nchannels = %d\nsampling rate = %d\ndepth = %d\nlength = %d samples/channel\n",
     sound_in, channels, srate, depth, length);

  m = mat_wav_read (sound_in);
  v = m[0];			/* consider only the first channel */

  /* Transform the sound */
  vt = it_dwt (v, it_wavelet_lifting_53, levels);
  vec_delete (v);

  /* Write down the coefficients */
  v = vec_new_eval (vt, rescale_sound, NULL);
  m[0] = v;
  mat_wav_write ("wavelet.wav", m, srate, depth);
  vec_delete (v);

  /* Reconstruct the sound */
  v = it_idwt (vt, it_wavelet_lifting_53, levels);
  vec_delete (vt);

  m[0] = v;
  mat_wav_write (sound_out, m, srate, depth);
  mat_delete (m);

  /* Test the separable transform */
  /* Warning: note that for the wavelet with more than 1 level of   */
  /* decomposition, the transform obtained by applying the wavelet  */
  /* on the rows, then on the columns of the image is *not* what is */
  /* usually called the separable wavelet. See this example:        */
  /* separable(wavelet1D)                   wavelet2D               */
  /*                                                                */
  /*   +------+------+------+               +------+------+------+  */
  /*   | L1L1 | L1H1 | L1H0 |               | L1L1 | LH1  |      |  */
  /*   +------+------+------+               +------+------+  LH0 |  */
  /*   | H1L1 | H1H1 | H1H0 |               | HL1  | HH1  |      |  */
  /*   +------+------+------+               +------+------+------+  */
  /*   |      |      |      |               |             |      |  */
  /*   | H0L1 | H0H1 | H0H0 |               |    HL0      |  HH0 |  */
  /*   +------+------+------+               +-------------+------+  */

  m = mat_pgm_read (image_in);
  printf ("PGM %dx%d\n", mat_height (m), mat_width (m));

  levels = 1;

  /* create a 1D wavelet object */
  wavelet = it_wavelet_new (it_wavelet_lifting_97, levels);
  /* create a separable transform out of the wavelet */
  separable = it_separable2D_new (wavelet);

  /* Transform the image */
  mt = (mat) it_transform2D (separable, m);
  mat_delete (m);

  /* Write down the coefficients (shifted & saturated) */
  m = mat_new_eval (mt, rescale_image, NULL);
  mat_pgm_write ("wavelet_separable.pgm", m);
  mat_delete (m);

  /* Reconstruct the image */
  m = (mat) it_itransform2D (separable, mt);
  mat_delete (mt);

  it_delete (separable);
  it_delete (wavelet);

  mat_pgm_write ("separable.pgm", m);
  mat_delete (m);

  /* Read the image */
  pnm_info (image_in, &pnm_type, &width, &height, &maxval, comments, 1000);
  printf ("file name = %s\npnm type = %c\n%dx%d -> maxval=%d\ncomments=%s\n",
	  image_in, pnm_type, width, height, maxval, "");

  m = mat_pgm_read (image_in);

  printf
    ("height(m) = %d\tmaxheight(m) = %d\nwidth(m) = %d\tmaxwidth(m) = %d\n",
     mat_height (m), mat_height_max (m), mat_width (m), mat_width_max (m));

  levels = 5;

  /* create a 2D wavelet object */
  wavelet2D = it_wavelet2D_new (it_wavelet_lifting_97, levels);

  /* Transform the image */
  mt = it_wavelet2D_transform (wavelet2D, m);
  mat_delete (m);

  /* Write down the coefficients (shifted & saturated) */
  m = mat_new_eval (mt, rescale_image, NULL);
  mat_pgm_write ("wavelet.pgm", m);
  mat_delete (m);

  /* Reconstruct the image */
  m = it_wavelet2D_itransform (wavelet2D, mt);
  mat_delete (mt);

  it_delete (wavelet2D);

  mat_pgm_write (image_out, m);
  mat_delete (m);

  return 0;
}
Esempio n. 4
0
/**
 * ICA function. Computes the W matrix from the
 * preprocessed data.
 */
static mat ICA_compute(mat X, int rows, int cols)
{
	mat TXp, GWX, W, Wd, W1, D, TU, TMP;
	vect d, lim;
	int i, it;

	// matrix creation
	TXp = mat_create(cols, rows);
	GWX = mat_create(rows, cols);
	W = mat_create(rows, rows);
	Wd = mat_create(rows, rows);
	D = mat_create(rows, rows);
	TMP = mat_create(rows, rows);
	TU = mat_create(rows, rows);
	W1 = mat_create(rows, rows);
	d = vect_create(rows);

	// W rand init
	mat_apply_fx(W, rows, rows, fx_rand, 0);

	// sW <- La.svd(W)
	mat_copy(W, rows, rows, Wd);
	svdcmp(Wd, rows, rows, d, D);

	// W <- sW$u %*% diag(1/sW$d) %*% t(sW$u) %*% W
	mat_transpose(Wd, rows, rows, TU);
	vect_apply_fx(d, rows, fx_inv, 0);
	mat_diag(d, rows, D);
	mat_mult(Wd, rows, rows, D, rows, rows, TMP);
	mat_mult(TMP, rows, rows, TU, rows, rows, D);
	mat_mult(D, rows, rows, W, rows, rows, Wd); // W = Wd

	// W1 <- W 
	mat_copy(Wd, rows, rows, W1);

	// lim <- rep(1000, maxit); it = 1
	lim = vect_create(MAX_ITERATIONS);
	for (i=0; i<MAX_ITERATIONS; i++)
		lim[i] = 1000;
	it = 0;


	// t(X)/p
	mat_transpose(X, rows, cols, TXp);
	mat_apply_fx(TXp, cols, rows, fx_div_c, cols);

	while (lim[it] > TOLERANCE && it < MAX_ITERATIONS) {
		// wx <- W %*% X
		mat_mult(Wd, rows, rows, X, rows, cols, GWX);

		// gwx <- tanh(alpha * wx)
		mat_apply_fx(GWX, rows, cols, fx_tanh, 0);
		
		// v1 <- gwx %*% t(X)/p
		mat_mult(GWX, rows, cols, TXp, cols, rows, TMP); // V1 = TMP
		
		// g.wx <- alpha * (1 - (gwx)^2)
		mat_apply_fx(GWX, rows, cols, fx_1sub_sqr, 0);

		// v2 <- diag(apply(g.wx, 1, FUN = mean)) %*% W
		mat_mean_rows(GWX, rows, cols, d);
		mat_diag(d, rows, D);
		mat_mult(D, rows, rows, Wd, rows, rows, TU); // V2 = TU

		// W1 <- v1 - v2
		mat_sub(TMP, TU, rows, rows, W1);
		
		// sW1 <- La.svd(W1)
		mat_copy(W1, rows, rows, W);
		svdcmp(W, rows, rows, d, D);

		// W1 <- sW1$u %*% diag(1/sW1$d) %*% t(sW1$u) %*% W1
		mat_transpose(W, rows, rows, TU);
		vect_apply_fx(d, rows, fx_inv, 0);
		mat_diag(d, rows, D);
		mat_mult(W, rows, rows, D, rows, rows, TMP);
		mat_mult(TMP, rows, rows, TU, rows, rows, D);
		mat_mult(D, rows, rows, W1, rows, rows, W); // W1 = W
		
		// lim[it + 1] <- max(Mod(Mod(diag(W1 %*% t(W))) - 1))
		mat_transpose(Wd, rows, rows, TU);
		mat_mult(W, rows, rows, TU, rows, rows, TMP);
		lim[it+1] = fabs(mat_max_diag(TMP, rows, rows) - 1);

		// W <- W1
		mat_copy(W, rows, rows, Wd);

		it++;
	}

	// clean up
	mat_delete(TXp, cols, rows);
	mat_delete(GWX, rows, cols);
	mat_delete(W, rows, rows);
	mat_delete(D, rows, rows);
	mat_delete(TMP, rows, rows);
	mat_delete(TU, rows, rows);
	mat_delete(W1, rows, rows);
	vect_delete(d);	

	return Wd;
}
Esempio n. 5
0
/**
 * Main FastICA function. Centers and whitens the input
 * matrix, calls the ICA computation function ICA_compute()
 * and computes the output matrixes.
 */
void fastICA(mat X, int rows, int cols, int compc, mat K, mat W, mat A, mat S)
{
	mat XT, V, TU, D, X1, _A;
	vect scale, d;

	// matrix creation
	XT = mat_create(cols, rows);
	X1 = mat_create(compc, rows);
	V = mat_create(cols, cols);
	D = mat_create(cols, cols);
	TU = mat_create(cols, cols);
	scale = vect_create(cols);
	d = vect_create(cols);

	/*
	 * CENTERING
	 */
	mat_center(X, rows, cols, scale);


	/*
	 * WHITENING
	 */

	// X <- t(X); V <- X %*% t(X)/rows 
	mat_transpose(X, rows, cols, XT);
	mat_apply_fx(X, rows, cols, fx_div_c, rows);
	mat_mult(XT, cols, rows, X, rows, cols, V);
	
	// La.svd(V)
	svdcmp(V, cols, cols, d, D);  // V = s$u, d = s$d, D = s$v

	// D <- diag(c(1/sqrt(d))
	vect_apply_fx(d, cols, fx_inv_sqrt, 0);	
	mat_diag(d, cols, D);

	// K <- D %*% t(U)
	mat_transpose(V, cols, cols, TU);
	mat_mult(D, cols, cols, TU, cols, cols, V); // K = V 

	// X1 <- K %*% X
	mat_mult(V, compc, cols, XT, cols, rows, X1);

	/*
	 * FAST ICA
	 */
	_A = ICA_compute(X1, compc, rows);

	
	/*
	 * OUTPUT
	 */

	// X <- t(x)
	mat_transpose(XT, cols, rows, X);
	mat_decenter(X, rows, cols, scale);

	// K
	mat_transpose(V, compc, cols, K);

	// w <- a %*% K; S <- w %*% X
	mat_mult(_A, compc, compc, V, compc, cols, D);	
	mat_mult(D, compc, cols, XT, cols, rows, X1);
	// S
	mat_transpose(X1, compc, rows, S);

	// A <- t(w) %*% solve(w * t(w))
	mat_transpose(D, compc, compc, TU);
	mat_mult(D, compc, compc, TU, compc, compc, V);
	mat_inverse(V, compc, D);
	mat_mult(TU, compc, compc, D, compc, compc, V);
	// A
	mat_transpose(V, compc, compc, A);

	// W
	mat_transpose(_A, compc, compc, W);

	// cleanup
	mat_delete(XT, cols, rows);
	mat_delete(X1, compc, rows);
	mat_delete(V, cols, cols);
	mat_delete(D, cols, cols);
	mat_delete(TU,cols, cols);
	vect_delete(scale);
	vect_delete(d);
}
Esempio n. 6
0
int ProcessData(){
  int i, j, ii;
  int comp = 14; //so thanh phan doc lap
  
  //khai bao matrix X la ma tran dung de luu eegData doc tu file Edf
  mat X;
  int rows_X, cols_X;//so hang, cot cua ma tran
  
  mat K, W, A, S;
  
  double *Af3; //du lieu kenh AF3
  double *EyeBlink;//dang tin hieu eyeblink
  double *Component;
  double *Comp_Wavelet;
  double Mean_X, Mean_Y, S_X, S_Y, Denom, Cr_Correlate;
  
  FILE *FileOut;
  
  X = mat_create(SAMPLE_MAX, CHANNEL_NUMBER);//cap phat bo nho cho X
  
  /**
   * READ DATA
   */
  printf("\nStart read EEG data..........\n");
  rows_X = readData(X);//goi ham doc file edf, luu du lieu vao ma tran X
  cols_X = CHANNEL_NUMBER;
  rows_X = 128;
  //END READ DATA
  
  /**
   * RUN ICA
   */
  printf("\nStart run ICA..........\n");
  //cap phat vung nho cho cac matrix
  W = mat_create(comp, comp); 
  A = mat_create(comp, comp);
  K = mat_create(cols_X, comp);
  S = mat_create(rows_X, comp);	
  
  fastICA(X, rows_X, cols_X, comp, K, W, A, S);//run ICA, matrix output: S
#ifdef DEBUG
  //kiem tra xem matrix S thu ve co dung khong
  FileOut = fopen("/home/nick_gun/Desktop/Lab-2013/SAMSUNG_2013_2014/Code/EEGProject/Debug/ICA_Out.txt", "wb");
  for(i=0; i<rows_X; i++){
    for(j=0;j<1;j++)
      fprintf(FileOut, "%f ", S[i][3]);
    fprintf(FileOut, "\n");  
  }
  fclose(FileOut);
#endif
  
  //END RUN ICA
  
  
  /**
   * RUN WAVELET
   * Compute Wavelet and Recontruction Detail/Aprroximation 
   * with AF3(for recontruction eyeblink) and each component(ICA)
   * Then use Cross Correlation for Detect EyeBlink Component
   * 
   * Ref: http://paulbourke.net/miscellaneous/correlate/
   */
  printf("\nStart run Wavelet..........\n");
  //1.RUN WAVELET FOR FA3
  //copy du lieu sang Af3
  Af3 = malloc(SAMPLE*sizeof(double));
  for(i=0;i<SAMPLE;i++)
    Af3[i]=X[i][5];
  
  //chay wavelet daub4 cho Af3 va tai tao tin hieu eyeblink
  EyeBlink = reWavelet(SAMPLE, 32, 64, Af3);
  
  //compute mean of EyeBlink and absolute EyeBlink
  S_X=0; Mean_X=0;
  for(i=0;i<SAMPLE;i++){
    //if(EyeBlink[i]<0) EyeBlink[i]=-EyeBlink[i];
    Mean_X+=EyeBlink[i];
  }
  Mean_X=Mean_X/SAMPLE;
  for(i=0;i<SAMPLE;i++)
    S_X+=(EyeBlink[i]-Mean_X)*(EyeBlink[i]-Mean_X);
    
#ifdef DEBUG
  //print eyeblink
  FileOut = fopen("/home/nick_gun/Desktop/Lab-2013/SAMSUNG_2013_2014/Code/EEGProject/Debug/Eyeblink.txt", "wb");
  for(i=0; i<SAMPLE; i++)
    fprintf(FileOut, "%f\n", EyeBlink[i]);
  fclose(FileOut);
#endif  
  
  //2.RUN WAVELET FOR COMPONENT ICA
  Comp_Wavelet = malloc(SAMPLE*sizeof(double));
  Component = malloc(SAMPLE*sizeof(double));
  
  
  
  //loop load one of all channel
  for(ii=0;ii<comp;ii++){
    //2.1.COMPUTE WAVELET FOR EACH COMPONENT
    for(j=0;j<SAMPLE;j++)
      Component[j]=S[j][ii];
    Comp_Wavelet = reWavelet(SAMPLE, 16, 32, Component);
    
#ifdef DEBUG
    if(ii==0)	FileOut = fopen("/home/nick_gun/Desktop/Lab-2013/SAMSUNG_2013_2014/Code/EEGProject/Debug/Comp_Wavelet.txt", "wb");
    else 	FileOut = fopen("/home/nick_gun/Desktop/Lab-2013/SAMSUNG_2013_2014/Code/EEGProject/Debug/Comp_Wavelet.txt", "at");
    fprintf(FileOut, "Comp_Wavelet %d ***************\n", ii);
    for(j=0; j<SAMPLE; j++){
      //if(Comp_Wavelet[j]<0) Comp_Wavelet[j]=-Comp_Wavelet[j];
      fprintf(FileOut, "%f\n", Comp_Wavelet[j]); 
    }
    fclose(FileOut);
#endif
  
    //2.2.COMPUTE WITH EYEBLINK USE CROSS CORRELATION
    //compute mean and absolute Component
    S_Y=0; Mean_Y=0;
    for(j=0;j<SAMPLE;j++){
      //if(Comp_Wavelet[j]<0)	Comp_Wavelet[j]=-Comp_Wavelet[j];
      Mean_Y+=Comp_Wavelet[j];
    }
    Mean_Y=Mean_Y/SAMPLE;
    for(j=0;j<SAMPLE;j++)
      S_Y+=(Comp_Wavelet[j]-Mean_Y)*(Comp_Wavelet[j]-Mean_Y);
    
    Denom = sqrt(S_X*S_Y);
    //compute cross correlate at delay = 0
    Cr_Correlate=0;
    for(j=0;j<SAMPLE;j++){
      Cr_Correlate+=EyeBlink[j]*Comp_Wavelet[j];
    }
    Cr_Correlate=Cr_Correlate/Denom;
    printf("==%d===%f===\n",ii,  Cr_Correlate);
  }
  //END RUN WAVELET
  
  free(Af3);
  free(EyeBlink);
  free(Component);
  free(Comp_Wavelet);
  mat_delete(X, SAMPLE_MAX, CHANNEL_NUMBER);//giai phong ma tran X
  mat_delete(W, comp, comp);
  mat_delete(A, comp, comp);
  mat_delete(K, cols_X, comp);
  mat_delete(S, rows_X, comp);
  
  return rows_X;
}
Esempio n. 7
0
/**
 * Main FastICA function. Centers and whitens the input
 * matrix, calls the ICA computation function ICA_compute()
 * and computes the output matrixes.
 */
void fastICA(mat X, int rows, int cols, int compc, mat K, mat W, mat A, mat S) {
    mat XT, V, TU, D, X1, _A;
    vect scale, d;
    clock_t clock1, clock2;
    float time;
    //char ascii_path[512];
    //strcpy(ascii_path, "/storage/sdcard0/NickGun/EEG/Log.txt");
    //FILE *Log;

    //chu thich voi truong hop 14 kenh, 2s (256mau) du lieu, 14 thanh phan doc lap>>> cols = 14, rows = 256, compc = 14
    // matrix creation
    XT = mat_create(cols, rows); //14x256
    X1 = mat_create(compc, rows); //14x256
    V = mat_create(cols, cols); //14x14
    D = mat_create(cols, cols); //14x14
    TU = mat_create(cols, cols); //14x14
    scale = vect_create(cols); //14
    d = vect_create(cols); //14

    clock1 = clock();
    /*
     * CENTERING
     */
    mat_center(X, rows, cols, scale); //tru di gia tri trung binh cua moi cot

    clock2 = clock();
    time = (clock2 - clock1) / CLOCKS_PER_SEC;
    //Log = fopen(ascii_path, "wb");
    //fprintf(Log, "CENTERING %f \n", time);
    //fclose(Log);

    clock1 = clock();
    /*
     * WHITENING
     */

    // X <- t(X); V <- X %*% t(X)/rows
    mat_transpose(X, rows, cols, XT); //XT la chuyen vi cua ma tran X[256][14] >>> XT[14][256]
    mat_apply_fx(X, rows, cols, fx_div_c, rows); //lay tung gia tri cua X[i][j] chia cho 14
    mat_mult(XT, cols, rows, X, rows, cols, V); //V=XT*X >>>V[14][14]

    // La.svd(V)
    svdcmp(V, cols, cols, d, D); // V = s$u, d = s$d, D = s$v

    // D <- diag(c(1/sqrt(d))
    vect_apply_fx(d, cols, fx_inv_sqrt, 0);
    mat_diag(d, cols, D);

    // K <- D %*% t(U)
    mat_transpose(V, cols, cols, TU);
    mat_mult(D, cols, cols, TU, cols, cols, V); // K = V

    // X1 <- K %*% X
    mat_mult(V, compc, cols, XT, cols, rows, X1);

    clock2 = clock();
    time = (clock2 - clock1) / CLOCKS_PER_SEC;
    //Log = fopen(ascii_path, "at");
    //fprintf(Log, "WHITENING %f \n", time);
    //fclose(Log);

    clock1 = clock();
    /*
     * FAST ICA
     */
    _A = ICA_compute(X1, compc, rows);

    clock2 = clock();
    time = (clock2 - clock1) / CLOCKS_PER_SEC;
    //Log = fopen(ascii_path, "at");
    //fprintf(Log, "FASTICA %f \n", time);
    //fclose(Log);

    clock1 = clock();
    /*
     * OUTPUT
     */

    // X <- t(x)
    mat_transpose(XT, cols, rows, X);
    mat_decenter(X, rows, cols, scale);

    // K
    mat_transpose(V, compc, cols, K);

    // w <- a %*% K; S <- w %*% X
    mat_mult(_A, compc, compc, V, compc, cols, D);
    mat_mult(D, compc, cols, XT, cols, rows, X1);

    // S
    mat_transpose(X1, compc, rows, S);

    // A <- t(w) %*% solve(w * t(w))
    mat_transpose(D, compc, compc, TU);
    mat_mult(D, compc, compc, TU, compc, compc, V);
    mat_inverse(V, compc, D); //ham nay tinh mat tran ngich dao
    mat_mult(TU, compc, compc, D, compc, compc, V);
    // A
    mat_transpose(V, compc, compc, A);

    // W
    mat_transpose(_A, compc, compc, W);

    // cleanup
    mat_delete(XT, cols, rows);
    mat_delete(X1, compc, rows);
    mat_delete(V, cols, cols);
    mat_delete(D, cols, cols);
    mat_delete(TU, cols, cols);
    vect_delete(scale);
    vect_delete(d);

    clock2 = clock();
    time = (clock2 - clock1) / CLOCKS_PER_SEC;
    //Log = fopen(ascii_path, "at");
    //fprintf(Log, "OUTPUT %f \n", time);
    //fclose(Log);
}
Esempio n. 8
0
/**
 * ICA function. Computes the W matrix from the
 * preprocessed data.
 */
static mat ICA_compute(mat X, int rows, int cols) {
    mat TXp, GWX, W, Wd, W1, D, TU, TMP;
    vect d, lim;
    int i, it;

    FILE *OutputFile;

    clock_t clock1, clock2;
    float time;

    //char ascii_path[512];
    //strcpy(ascii_path, "/storage/sdcard0/NickGun/EEG/Log.txt");
    //FILE *Log;

    // matrix creation
    TXp = mat_create(cols, rows);
    GWX = mat_create(rows, cols);
    W = mat_create(rows, rows);
    Wd = mat_create(rows, rows);
    D = mat_create(rows, rows);
    TMP = mat_create(rows, rows);
    TU = mat_create(rows, rows);
    W1 = mat_create(rows, rows);
    d = vect_create(rows);

    // W rand init
    mat_apply_fx(W, rows, rows, fx_rand, 0);

    // sW <- La.svd(W)
    mat_copy(W, rows, rows, Wd);
    svdcmp(Wd, rows, rows, d, D);

    // W <- sW$u %*% diag(1/sW$d) %*% t(sW$u) %*% W
    mat_transpose(Wd, rows, rows, TU);
    vect_apply_fx(d, rows, fx_inv, 0);
    mat_diag(d, rows, D);
    mat_mult(Wd, rows, rows, D, rows, rows, TMP);
    mat_mult(TMP, rows, rows, TU, rows, rows, D);
    mat_mult(D, rows, rows, W, rows, rows, Wd); // W = Wd

    // W1 <- W
    mat_copy(Wd, rows, rows, W1);

    // lim <- rep(1000, maxit); it = 1
    lim = vect_create(MAX_ITERATIONS);
    for (i = 0; i < MAX_ITERATIONS; i++)
        lim[i] = 1000;
    it = 0;

    // t(X)/p
    mat_transpose(X, rows, cols, TXp);
    mat_apply_fx(TXp, cols, rows, fx_div_c, cols);

    while (lim[it] > TOLERANCE && it < MAX_ITERATIONS) {
        // wx <- W %*% X
        mat_mult(Wd, rows, rows, X, rows, cols, GWX);

        // gwx <- tanh(alpha * wx)
        mat_apply_fx(GWX, rows, cols, fx_tanh, 0);

        // v1 <- gwx %*% t(X)/p
        mat_mult(GWX, rows, cols, TXp, cols, rows, TMP); // V1 = TMP

        // g.wx <- alpha * (1 - (gwx)^2)
        mat_apply_fx(GWX, rows, cols, fx_1sub_sqr, 0);

        // v2 <- diag(apply(g.wx, 1, FUN = mean)) %*% W
        mat_mean_rows(GWX, rows, cols, d);
        mat_diag(d, rows, D);
        mat_mult(D, rows, rows, Wd, rows, rows, TU); // V2 = TU

        // W1 <- v1 - v2
        mat_sub(TMP, TU, rows, rows, W1);

        // sW1 <- La.svd(W1)
        mat_copy(W1, rows, rows, W);
        svdcmp(W, rows, rows, d, D);

        // W1 <- sW1$u %*% diag(1/sW1$d) %*% t(sW1$u) %*% W1
        mat_transpose(W, rows, rows, TU);
        vect_apply_fx(d, rows, fx_inv, 0);
        mat_diag(d, rows, D);
        mat_mult(W, rows, rows, D, rows, rows, TMP);
        mat_mult(TMP, rows, rows, TU, rows, rows, D);
        mat_mult(D, rows, rows, W1, rows, rows, W); // W1 = W

        // lim[it + 1] <- max(Mod(Mod(diag(W1 %*% t(W))) - 1))
        mat_transpose(Wd, rows, rows, TU); //chuyen vi
        mat_mult(W, rows, rows, TU, rows, rows, TMP); //TMP=WxTU
        lim[it + 1] = fabs(mat_max_diag(TMP, rows, rows) - 1);

        if(lim[it+1]<0.1)
            break;


        /*
        OutputFile = fopen("/storage/sdcard0/Nickgun/EEG/data/lim",
        			"at");
        fprintf(OutputFile, "%f \n", lim[it+1]);

        fclose(OutputFile);
        // W <- W1
        */
        mat_copy(W, rows, rows, Wd);

        it++;
    }

    // clean up
    mat_delete(TXp, cols, rows);
    mat_delete(GWX, rows, cols);
    mat_delete(W, rows, rows);
    mat_delete(D, rows, rows);
    mat_delete(TMP, rows, rows);
    mat_delete(TU, rows, rows);
    mat_delete(W1, rows, rows);
    vect_delete(d);

    return Wd;
}
Esempio n. 9
0
File: main.c Progetto: Flyswat/wmmp
int main ( int argc, char *argv[] ) {

	parser_t * parser = NULL;
	uint key = 0, Nc = 0, Nv = 0, Ns = 0, epw, e;
	double wcr_start,
		wcr_step,
		wcr_end,
		wcr = 0.0;
	vec wcr_vec;

	mat 	U = NULL;


	if ( argc == 1 )
	{
		fprintf( stderr, "Usage: %s config.cfg\n", argv[0] );
		exit( EXIT_FAILURE );
	}

	parser = parser_init( argc, argv, argv[1], NULL );

	key = parser_get_int( parser, "KEY" );
	wcr_vec = parser_get_vec( parser, "WCR" );
	Nv  = parser_get_int( parser, "Nv" );
	Nc  = parser_get_int( parser, "Nc" );
	Ns  = parser_get_int( parser, "Ns" );
	epw  = parser_get_int( parser, "EPW" );
	parser_delete( parser );


	if (vec_length(wcr_vec) != 3)
	{
		fprintf( stderr, "Invalid config for WCR values\n" );
		exit( EXIT_FAILURE );
	}
	wcr_start = wcr_vec[0];
	wcr_step = wcr_vec[1];
	wcr_end = wcr_vec[2];

	U = make_carriers( Nc, Nv, key );

	for (wcr = wcr_start; wcr <= wcr_end; wcr += wcr_step)
	{
		for (e=0; e<epw;e++)
		{
			mat	U_est = NULL,
				Y = NULL,
				Y_attack = NULL;

			// gen watermarks with U
			Y = make_Y(Nv, Ns, Nc, U, wcr);

			// Estimated carriers from PCA
			U_est = estimate_carriers(Y, Nv, Nc);

			// Attack Y
			Y_attack = attack(Y,U_est);

			print_dist(Y,Y_attack,wcr);

			mat_delete( Y );
			mat_delete( Y_attack );
			mat_delete( U_est );
		}
	}

	mat_delete( U );

	exit( EXIT_SUCCESS );
}