void plot_add_model(plot *p, model_func *f, const mat *x_0, const size_t j, \
                    const mat *par, void *f_param, const double xmin,       \
                    const double xmax, const size_t npt, const strbuf title,\
                    const strbuf color)
{
    mat *x,*y,*X;
    size_t i;
    double x_i,y_i;
    
    x = mat_create(npt,1);
    y = mat_create(npt,1);
    X = mat_create_from_mat(x_0);
    
    for (i=0;i<npt;i++)
    {
        x_i = xmin + (xmax-xmin)*DRATIO(i,npt-1);
        mat_set(X,j,0,x_i);
        y_i = f(X,par,f_param);
        mat_set(x,i,0,x_i);
        mat_set(y,i,0,y_i);
    }
    plot_add_line(p,x,y,title,color);
    
    mat_destroy(x);
    mat_destroy(y);
    mat_destroy(X);
}
int main(void) 
{
  Item x = 5, y = 2, x2 = 6, y2 = 3;
  mat m1, m2, k1, k2;
  int i, j;

  printf("\nItems: ");
  item_print(x);
  printf(" ");
  item_print(y);
  printf("\n");
  printf("Item Addition: ");
  item_print(item_add(x, y));
  printf("\n");
  printf("Item Multiplication: ");
  item_print(item_mul(x, y));
  printf("\n");
  printf("Item Substraction: ");
  item_print(item_sub(x, y));
  printf("\n");
  printf("Item Division: ");
  item_print(item_div(x, y));
  printf("\n\n");
  m1 = mat_create(3, 2);
  m2 = mat_create(2, 3);
  k1 = mat_create(2, 2);
  k2 = mat_create(2, 2);
  for (i = 0; i < mat_rows(m1); i++)
    for (j = 0; j < mat_cols(m1); j++)
      mat_add_elem(m1, i, j, x);
  for (i = 0; i < mat_rows(m2); i++)
    for (j = 0; j < mat_cols(m2); j++)
      mat_add_elem(m2, i, j, y);
  for (i = 0; i < mat_rows(k1); i++)
    for (j = 0; j < mat_cols(k1); j++)
      {
  	mat_add_elem(k1, i, j, x2);
  	mat_add_elem(k2, i, j, y2);
      }
  printf("k1 Matrix: \n");
  mat_print(k1);
  printf("k2 Matrix: \n");
  mat_print(k2);
  printf("Addition: \n");
  mat_print(mat_add(k1, k2));
  printf("Substraction: \n");
  mat_print(mat_sub(k1, k2));
  printf("m1 Matrix: \n");
  mat_print(m1);
  printf("m2 Matrix: \n");
  mat_print(m2);
  printf("Multiplication: \n");
  mat_print(mat_mul(m1, m2));
  return 0;
}
Beispiel #3
0
MatrixFile     *matrix_create(const char *fname, Main_header * proto_mhptr) {
  MatrixFile     *mptr = NULL;
  FILE           *fptr, *mat_create();
  
  matrix_errno = MAT_OK;
  matrix_errtxt[0] = '\0';
  
  fptr = mat_create(fname, proto_mhptr);
  if (!fptr) return( NULL );
  
  mptr = (MatrixFile *) calloc(1, sizeof(MatrixFile));
  if (!mptr) {
    fclose( fptr );
    return( NULL );
  }
  
  mptr->fptr = fptr;
  
  mptr->fname = (char *) malloc(strlen(fname) + 1);
  if (!mptr->fname) {
    free( mptr );
    fclose( fptr );
    return( NULL );
  }
  
  strcpy(mptr->fname, fname);
  mptr->mhptr = (Main_header *) malloc(sizeof(Main_header));
  if (!mptr->mhptr) {
    free( mptr->fname );
    free( mptr );
    fclose( fptr );
    return( NULL );
  }
  
  memcpy(mptr->mhptr, proto_mhptr, sizeof(Main_header));
  mptr->dirlist = mat_read_directory(mptr);
  if (!mptr->dirlist) {
    free( mptr->fname );
    free( mptr->mhptr );
    free( mptr );
    fclose( fptr );
    return( NULL );
  }
  return mptr;
}
void plot_add_fit_predband(plot *p, const fit_data *d, const size_t ky,\
                           const mat *x_ex, const size_t kx,           \
                           const rs_sample *par, const double xmin,    \
                           const double xmax, const size_t npt,        \
                           const strbuf color)
{
    mat *x,*yp,*ym,*y_i_err,*X;
    rs_sample *s_y_i;
    size_t i;
    double x_i,yp_i,ym_i;
    
    x       = mat_create(npt,1);
    yp      = mat_create(npt,1);
    ym      = mat_create(npt,1);
    y_i_err = mat_create(1,1);
    s_y_i   = rs_sample_create(1,1,rs_sample_get_nsample(par));
    X       = mat_create_from_mat(x_ex);
    
    for (i=0;i<npt;i++)
    {
        x_i = xmin + (xmax-xmin)*DRATIO(i,npt-1);
        mat_set(X,kx,0,x_i);
        fit_data_model_rs_xeval(s_y_i,d,ky,X,par);
        rs_sample_var(y_i_err,s_y_i);
        mat_eqsqrt(y_i_err);
        yp_i = mat_get(rs_sample_pt_cent_val(s_y_i),0,0) + mat_get(y_i_err,0,0);
        ym_i = mat_get(rs_sample_pt_cent_val(s_y_i),0,0) - mat_get(y_i_err,0,0);
        mat_set(yp,i,0,yp_i);
        mat_set(ym,i,0,ym_i);
        mat_set(x,i,0,x_i);
    }
    
    plot_add_line(p,x,yp,"",color);
    plot_add_line(p,x,ym,"",color);
    
    mat_destroy(x);
    mat_destroy(yp);
    mat_destroy(ym);
    mat_destroy(y_i_err);
    rs_sample_destroy(s_y_i);
    mat_destroy(X);
}
Beispiel #5
0
void next_step_cal(FLUX *flux, PCS *pcs, TCONF *tconf, MAPPER *mapper, MESH *mesh, CDAT4 *vsf_lst)
{
	size_t eg_size = mapper->eg_size;
	size_t rt_size = mapper->rt_size;
	CDAT4 *vsf = mesh->vsf;
	FLUX *flux_lst = flux_create(mapper);
	flux_copy(flux_lst, flux);
	CDAT4 *sr_rvs = cdat4_create(mapper);
	sr_rvs_cal(sr_rvs, tconf, mesh);
	MAT *M = mat_create(eg_size*rt_size);
	MAT *S = mat_create(eg_size*rt_size);
	MAT *F = mat_create(eg_size*rt_size);
	EDAT4 *DFDM = edat4_create(mapper);
	EDAT4 *DNOD = edat4_create(mapper);
	cal_DFDM(DFDM, mesh);
	cal_m(M, DFDM, DNOD, mapper, mesh, sr_rvs);
	CDAT4 *chi_bar = cdat4_create(mapper);
	cal_chi_bar(chi_bar, tconf, mesh);
	cal_s(S, mapper, mesh);
	cal_f(F, mapper, mesh, chi_bar);
	mat_adds(M, S, -1.0);
	mat_adds(M, F, -1.0);
	VEC *src_eff = vec_create(eg_size*rt_size);
	src_eff_cal(src_eff,tconf,mesh,vsf_lst,flux_lst,pcs);
	VEC *sol = vec_ref_create(eg_size*rt_size, flux->data);
	(*mat_solver)(sol,M,src_eff,1024);
	vec_ref_free(sol);
	
	pcs_cal(pcs,flux,flux_lst,vsf,vsf_lst,tconf);
	cdat4_free(chi_bar);
	vec_free(src_eff);
	edat4_free(DNOD);
	edat4_free(DFDM);
	mat_free(F);
	mat_free(S);
	mat_free(M);
	cdat4_free(sr_rvs);
	flux_free(flux_lst);
}
void plot_add_func(plot *p, univar_func *f, void *f_param, const double xmin,\
                   const double xmax, const size_t npt, const strbuf title,  \
                   const strbuf color)
{
    mat *x,*y;
    size_t i;
    double x_i,y_i;
    
    x = mat_create(npt,1);
    y = mat_create(npt,1);
    
    for (i=0;i<npt;i++)
    {
        x_i = xmin + (xmax-xmin)*DRATIO(i,npt-1);
        y_i = f(x_i,f_param);
        mat_set(x,i,0,x_i);
        mat_set(y,i,0,y_i);
    }
    plot_add_line(p,x,y,title,color);
    
    mat_destroy(x);
    mat_destroy(y);
}
Beispiel #7
0
static
void
setupSeqProblem__ (int m, int n, int k,
		   double** p_A, double** p_B,
		   double** p_C, double** p_C_bound)
{
  if (p_A) {
    *p_A = mat_create (m, k);
    mat_randomize (m, k, *p_A);
  }
  if (p_B) {
    *p_B = mat_create (k, n);
    mat_randomize (k, n, *p_B);
  }
  if (p_C) {
    *p_C = mat_create (m, n);
    mat_setZero (m, n, *p_C);
  }
  if (p_C_bound) {
    *p_C_bound = mat_create (m, n);
    mat_setZero (m, n, *p_C_bound);
  }
}
Beispiel #8
0
void icaTransformInverse(double** S, int rows, int cols, int comp, int comp_rm,
                         double** X, double** K, double** W, double** RowData, int startEb,
                         int stopEb) {
    double **A;
    double *Total;
    FILE * OutputFile;
    int i, j;

    A = mat_create(comp, comp);
    Total = malloc(cols * sizeof(double));

    for (j = 0; j < cols; j++) {
        Total[j] = 0;
        for (i = 0; i < rows; i++)
            Total[j] = Total[j] + RowData[i][j];
        Total[j] = Total[j] / rows;
    }

    puts("Before");
    for (j = startEb; j < stopEb; j++)
        //for (j = 40; j < 90; j++)
        S[j][comp_rm] = 0;//////////////////////////////////////////////////////////////////////////////////

    puts("Debug");

    mat_mult(K, cols, comp, W, comp, comp, A); //A[cols, comp]
    mat_inverse(A, comp, W);
    mat_mult(S, rows, comp, W, comp, comp, X);
    //strcat(pPathFile, "_recontruction");



    OutputFile = fopen("/home/truongnh/eeg-lab411/SignalProcessing/RemoveEyeblink/Data/Output.txt",
                       "wb");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            if(j == comp_rm)
                fprintf(OutputFile, "%f\n", X[i][j] + Total[j]);
        }
        //fprintf(OutputFile, "\n");
    }
    fclose(OutputFile);

    for (j = 0; j < cols; j++) {
        for (i = 0; i < rows; i++)
            X[i][j] = X[i][j] + Total[j];
    }

    free(Total);
}
Beispiel #9
0
int main(void)
{
    mat *m;
    size_t dim[2];
    
    m = mat_create(6,6);
    
    io_init();
    
    io_set_fmt(IO_ASCII);
    mat_load(m,dim,"ex_io.dat:m");
    printf("%dx%d matrix loaded from %s:\n",(int)(dim[0]),(int)(dim[1]),FNAME);
    mat_print(m,"% .15e");
    io_set_fmt(IO_XML);
    mat_save("ex_io.xml:m",'w',m);

    io_finish();
    
    mat_destroy(m);
    
    return EXIT_SUCCESS;
}
Beispiel #10
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 argc, char *argv[])
{
    int i,j;
    rs_sample *s1,*s2,*res;
    size_t s1_dim[2],s2_dim[2],s1_nsample,s2_nsample;
    mat *sig;
    bool do_save_res, show_usage;
    strbuf out_elname,out_fname,in_elname[2],in_fname[2],in_path[2],out_path;
    char *spt[2];
    io_fmt_no fmt;
    
    /* argument parsing */
    i           = 1;
    j           = 0;
    show_usage  = false;
    do_save_res = false;
    fmt         = io_get_fmt();
    
    if (argc <= 1)
    {
        show_usage = true;
    }
    else
    {
        while (i < argc)
        {
            if (strcmp(argv[i],"-o") == 0)
            {
                if (i == argc - 1)
                {
                    show_usage = true;
                    break;
                }
                else
                {
                    strbufcpy(out_path,argv[i+1]);
                    do_save_res = true;
                    i += 2;
                }
            }
            else if (strcmp(argv[i],"-f") == 0)
            {
                if (i == argc - 1)
                {
                    show_usage = true;
                    break;
                }
                else
                {
                    if (strcmp(argv[i+1],"xml") == 0)
                    {
                        fmt = IO_XML;
                    }
                    else if (strcmp(argv[i+1],"ascii") == 0)
                    {
                        fmt = IO_ASCII;
                    }
                    else
                    {
                        fprintf(stderr,"error: format %s unknown\n",argv[i+1]);
                        return EXIT_FAILURE;
                    }
                    i += 2;
                }
            }
            else
            {
                if (j < 2)
                {
                    strbufcpy(in_path[j],argv[i]);
                    j++;
                    i++;
                }
                else
                {
                    show_usage = true;
                    break;
                }
            }
        }
    }
    if (show_usage)
    {
        fprintf(stderr,"usage: %s <in sample 1> <in sample 2> [-o <out sample>] [-f {ascii|xml}]\n",\
                argv[0]);
        return EXIT_FAILURE;
    }
    
    /* I/O init */
    io_set_fmt(fmt);
    io_init();
    
    /* getting sizes */
    rs_sample_load(NULL,&s1_nsample,s1_dim,in_path[0]);
    rs_sample_load(NULL,&s2_nsample,s2_dim,in_path[1]);
    
    /* allocation */
    s1  = rs_sample_create(s1_dim[0],s1_dim[1],s1_nsample);
    s2  = rs_sample_create(s2_dim[0],s2_dim[1],s2_nsample);
    res = rs_sample_create(s1_dim[0],s1_dim[1],s1_nsample);
    sig = mat_create(s1_dim[0],s1_dim[1]);
    
    /* loading samples */
    printf("-- loading sample from %s...\n",in_path[0]);
    rs_sample_load(s1,NULL,NULL,in_path[0]);
    printf("-- loading sample from %s...\n",in_path[1]);
    rs_sample_load(s2,NULL,NULL,in_path[1]);
    
    /* multiplying samples */
    printf("-- executing operation on samples...\n");
    rs_sample_binop(res,s1,s2,&BINOP);
    
    /* result output */
    rs_sample_varp(sig,res);
    mat_eqsqrt(sig);
    printf("central value:\n");
    mat_print(rs_sample_pt_cent_val(res),"%e");
    printf("standard deviation:\n");
    mat_print(sig,"%e");
    if (do_save_res)
    {
        get_elname(out_fname,out_elname,out_path);
        if (strlen(out_elname) == 0)
        {
            get_elname(in_fname[0],in_elname[0],in_path[0]);
            get_elname(in_fname[1],in_elname[1],in_path[1]);
            spt[0] = (strlen(in_elname[0]) == 0) ? in_fname[0] : in_elname[0];
            spt[1] = (strlen(in_elname[1]) == 0) ? in_fname[1] : in_elname[1];
            sprintf(out_path,"%s%c%s_%s_%s",out_fname,LATAN_PATH_SEP,argv[0],\
                    spt[0],spt[1]);
        }
        rs_sample_save(out_path,'w',res);
    }
    
    /* desallocation */
    rs_sample_destroy(s1);
    rs_sample_destroy(s2);
    rs_sample_destroy(res);
    mat_destroy(sig);

    /* I/O finish */
    io_finish();
    
    return EXIT_SUCCESS;
}
int main(int argc, char *argv[])
{
    rs_sample *s1,*res,*buf;
    size_t s1_dim[2],res_dim[2],s1_nsample,a,b,s,k,l;
    int i,j;
    mat *sig;
    bool do_save_res, show_usage, have_s;
    char *spt;
    strbuf out_elname,out_fname,in_elname,in_fname,in_path,out_path;
    io_fmt_no fmt;
    
    /* argument parsing */
    i           = 1;
    j           = 0;
    a           = 0;
    b           = 0;
    s           = 1;
    show_usage  = false;
    do_save_res = false;
    have_s      = false;
    fmt         = io_get_fmt();
    
    if (argc <= 3)
    {
        show_usage = true;
    }
    else
    {
        while (i < argc)
        {
            if (strcmp(argv[i],"-o") == 0)
            {
                if (i == argc - 1)
                {
                    show_usage = true;
                    break;
                }
                else
                {
                    strbufcpy(out_path,argv[i+1]);
                    do_save_res = true;
                    i += 2;
                }
            }
            else if (strcmp(argv[i],"-f") == 0)
            {
                if (i == argc - 1)
                {
                    show_usage = true;
                    break;
                }
                else
                {
                    if (strcmp(argv[i+1],"xml") == 0)
                    {
                        fmt = IO_XML;
                    }
                    else if (strcmp(argv[i+1],"ascii") == 0)
                    {
                        fmt = IO_ASCII;
                    }
                    else
                    {
                        fprintf(stderr,"error: format %s unknown\n",argv[i+1]);
                        return EXIT_FAILURE;
                    }
                    i += 2;
                }
            }
            else if (strcmp(argv[i],"-s") == 0)
            {
                if (i == argc - 1)
                {
                    show_usage = true;
                    break;
                }
                else
                {
                    s       = (size_t)atol(argv[i+1]);
                    have_s  = true;
                    i      += 2;
                }
            }
            else
            {
                if (j == 0)
                {
                    strbufcpy(in_path,argv[i]);
                    j++;
                    i++;
                }
                else if (j == 1)
                {
                    a = (size_t)atol(argv[i]);
                    j++;
                    i++;
                }
                else if (j == 2)
                {
                    b = (size_t)atol(argv[i]);
                    j++;
                    i++;
                }
                else
                {
                    show_usage = true;
                    break;
                }
            }
        }
    }
    if (show_usage)
    {
        fprintf(stderr,"usage: %s <in sample> <a> <b> [-o <out sample>] [-f {ascii|xml}]\n",\
                argv[0]);
        return EXIT_FAILURE;
    }
    
    /* I/O init */
    io_set_fmt(fmt);
    io_init();
    
    /* getting sizes */
    rs_sample_load(NULL,&s1_nsample,s1_dim,in_path);
    l          = b - a + 1;
    s          = (have_s) ? s : l;
    res_dim[0] = s;
    res_dim[1] = s1_dim[1];
    
    /* allocation */
    s1  = rs_sample_create(s1_dim[0],s1_dim[1],s1_nsample);
    buf = rs_sample_create(1,s1_dim[1],s1_nsample);
    res = rs_sample_create(res_dim[0],res_dim[1],s1_nsample);
    sig = mat_create(res_dim[0],res_dim[1]);
    
    /* loading samples */
    printf("-- loading sample from %s...\n",in_path);
    rs_sample_load(s1,NULL,NULL,in_path);
    
    /* multiplying samples */
    printf("-- taking subsample [%d,%d]...\n",(int)a,(int)b);
    for (k=0;k<s;k++)
    {
        rs_sample_get_subsamp(buf,s1,a+(k%l),0,a+(k%l),s1_dim[1]-1);
        rs_sample_set_subsamp(res,buf,k,0,k,s1_dim[1]-1);
    }
    
    
    /* result output */
    rs_sample_varp(sig,res);
    mat_eqsqrt(sig);
    printf("central value:\n");
    mat_print(rs_sample_pt_cent_val(res),"%e");
    printf("standard deviation:\n");
    mat_print(sig,"%e");
    if (do_save_res)
    {
        get_elname(out_fname,out_elname,out_path);
        if (strlen(out_elname) == 0)
        {
            get_elname(in_fname,in_elname,in_path);
            spt = (strlen(in_elname) == 0) ? in_fname : in_elname;
            sprintf(out_path,"%s%c%s_%s",out_fname,LATAN_PATH_SEP,argv[0],spt);
        }
        rs_sample_save(out_path,'w',res);
    }
    
    /* desallocation */
    rs_sample_destroy(s1);
    rs_sample_destroy(res);
    rs_sample_destroy(buf);
    mat_destroy(sig);
    
    /* I/O finish */
    io_finish();
    
    return EXIT_SUCCESS;
}
Beispiel #13
0
int main(void)
{
    mat *a,*b,*c,*d,*e,*f,*g,*h,*i,*j;
    const double b_init[] =
    {
        2.5,\
        2.0,\
        5.0
    };
    const double c_init[] =
    {
        1.0,10.0,6.7
    };
    
    a = mat_create(3,3);
    b = mat_create_from_ar(b_init,3,1);
    c = mat_create_from_ar(c_init,1,3);
    d = mat_create(2,2);
    e = mat_create(3,3);
    f = mat_create(3,3);
    g = mat_create(5,3);
    h = mat_create(3,5);
    i = mat_create(5,3);
    j = mat_create(3,1);
    
    randgen_init(12);
    latan_set_verb(DEBUG1);
    
    printf("---------- %-30s ----------\n","matrix product");
    printf("b =\n");
    mat_print(b,"%8.2f");
    printf("\n");
    printf("c =\n");
    mat_print(c,"%8.2f");
    printf("\n");
    printf("a <- b*c\n");
    mat_mul(a,b,'n',c,'n');
    printf("a =\n");
    mat_print(a,"%8.2f");
    printf("\n");

    printf("\n---------- %-30s ----------\n","sub-matrices");
    printf("d <- a(1:2,0:1)\n");
    mat_get_subm(d,a,1,0,2,1);
    printf("d =\n");
    mat_print(d,"%9.2f");
    printf("\n");
    printf("a(1,0:2) <- c\n");
    mat_set_subm(a,c,1,0,1,2);
    printf("a =\n");
    mat_print(a,"%8.2f");
    printf("\n");

    printf("\n---------- %-30s ----------\n","symmetric matrix product");
    printf("e <- a*t(a)\n");
    mat_mul(e,a,'n',a,'t');
    mat_print(e,"%8.2f");
    printf("\n");
    printf("e is assumed symmetric\n\n");
    mat_assume(e,MAT_SYM);
    printf("j <- e*b\n");
    mat_mul(j,e,'n',b,'t');
    mat_print(j,"%8.2f");
    printf("\n");
    printf("f <- a*e\n");
    mat_mul(f,a,'n',e,'n');
    mat_print(f,"%8.2f");
    printf("\n");
    printf("f <- e*t(a)\n");
    mat_mul(f,e,'n',a,'t');
    mat_print(f,"%8.2f");
    printf("\n");
    printf("g <- random(-1.0,1.0)\n");
    mat_rand_u(g,-1.0,1.0);
    mat_print(g,"%8.2f");
    printf("\n");
    printf("h <- e*t(g) (buffer should be created)\n");
    mat_mul(h,e,'n',g,'t');
    mat_print(h,"%8.2f");
    printf("\n");
    printf("i <- g*e\n");
    mat_mul(i,g,'n',e,'n');
    mat_print(i,"%8.2f");
    printf("\n");
    printf("e is not assumed symmetric anymore\n");
    mat_reset_assump(e);
    
    printf("\n---------- %-30s ----------\n","matrix inversion");
    printf("*** LU decomposition\n");
    printf("a <- random(-6.0,6.0)\n");
    mat_rand_u(a,-6.0,6.0);
    printf("a =\n");
    mat_print(a,"%8.2f");
    printf("\n");
    printf("e <- a^(-1)\n");
    mat_inv_LU(e,a);
    printf("e =\n");
    mat_print(e,"%8.2f");
    printf("\n");
    printf("f <- e*a\n");
    mat_mul(f,e,'n',a,'n');
    printf("f =\n");
    mat_print(f,"%8.2f");
    printf("\n");
    printf("*** pseudo-inverse with good-conditioned matrix\n");
    printf("a =\n");
    mat_print(a,"%8.2f");
    printf("\n");
    printf("e <- a^+\n");
    mat_pseudoinv(e,a);
    printf("e =\n");
    mat_print(e,"%8.2f");
    printf("\n");
    printf("f <- e*a\n");
    mat_mul(f,e,'n',a,'n');
    printf("f =\n");
    mat_print(f,"%8.2f");
    printf("\n");
    printf("*** symmetric pseudo-inverse with good-conditioned matrix\n");
    printf("a <- a*t(a)\n");
    mat_mul(a,a,'n',a,'t');
    mat_print(a,"%8.2f");
    printf("\n");
    printf("a is assumed symmetric and positive\n\n");
    mat_assume(a,(mat_flag)(MAT_SYM|MAT_POS));
    printf("e <- a^+\n");
    mat_pseudoinv(e,a);
    printf("e =\n");
    mat_print(e,"%8.2f");
    printf("\n");
    printf("f <- e*a\n");
    mat_mul(f,e,'n',a,'n');
    printf("f =\n");
    mat_print(f,"%8.2f");
    printf("\n");
    printf("*** Cholesky decomposition\n");
    printf("e <- a^(-1)\n");
    mat_inv_symChol(e,a);
    printf("e =\n");
    mat_print(e,"%8.2f");
    printf("\n");
    printf("f <- e*a\n");
    mat_mul(f,e,'n',a,'n');
    printf("f =\n");
    mat_print(f,"%8.2f");
    printf("\n");
    
    mat_destroy(a);
    mat_destroy(b);
    mat_destroy(c);
    mat_destroy(d);
    mat_destroy(e);
    mat_destroy(f);
    mat_destroy(g);
    mat_destroy(h);
    mat_destroy(i);
    mat_destroy(j);
    
    return EXIT_SUCCESS;
}
Beispiel #14
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;
}
Beispiel #15
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);
}
Beispiel #16
0
int main (int argc, char *argv[]) {

  uint32_t         nincvxls;
  uint32_t        *incvxls;
  analyze_volume_t vol;
  mat_t           *mat;
  dsr_t            lblhdr;
  dsr_t           *hdrs[2];
  uint8_t         *lblimg;
  char            *imgmsg;
  char            *hdrdata;
  args_t           args;
  struct argp      argp = {options, _parse_opt, "INPUT OUTPUT", doc};

  lblimg  = NULL;
  incvxls = NULL;
  mat     = NULL;
  imgmsg  = NULL;
  hdrdata = NULL;

  memset(&args, 0, sizeof(args));

  startup("tsmat", argc, argv, &argp, &args);

  if (analyze_open_volume(args.input, &vol)) {
    printf("error opening analyze volume from %s\n", args.input);
    goto fail;
  }

  nincvxls = _create_mask(&vol, &incvxls, &args);
  
  if (nincvxls < 0) {
    printf("error masking voxels\n");
    goto fail;
  }

  if (nincvxls == 0) {

    printf("All voxels have been thresholded - relax your constraints\n");
    goto fail;
  }

  /*
   * if a label file was not provided, but a mask file
   * was, use the mask file to set row/column labels 
   */
  if ((args.labelf == NULL) && (args.maskf != NULL)) {

    args.labelf = args.maskf;
  }

  if (args.labelf != NULL) {

    if (analyze_load(args.labelf, &lblhdr, &lblimg)) {
      printf("error loading label file %s\n", args.labelf);
      goto fail;
    }

    hdrs[0] = vol.hdrs;
    hdrs[1] = &lblhdr;

    if (analyze_hdr_compat_ptr(2, hdrs, 1)) {
      printf(
        "label file %s does not match volume files in %s\n",
        args.labelf, args.input);
      goto fail;
    }
  }

  mat = mat_create(
    args.output, nincvxls, nincvxls,
    (1 << MAT_IS_SYMMETRIC) | (1 << MAT_HAS_ROW_LABELS),
    MAT_HDR_DATA_SIZE,
    sizeof(graph_label_t));

  if (mat == NULL) {
    printf("error creating mat file %s\n", args.output);
    goto fail;
  }

  imgmsg = malloc(200);
  if (imgmsg == NULL) {
    printf("out of memory?\n");
    goto fail;
  } 
  
  sprintf(
    imgmsg,
    "vol dims: %u (%0.6f), y: %u (%0.6f), z: %u (%0.6f), t: %u (%0.6f)",
    analyze_dim_size(   vol.hdrs, 0),
    analyze_pixdim_size(vol.hdrs, 0),
    analyze_dim_size(   vol.hdrs, 1),
    analyze_pixdim_size(vol.hdrs, 1),
    analyze_dim_size(   vol.hdrs, 2),
    analyze_pixdim_size(vol.hdrs, 2),
    vol.nimgs,
    args.sampletime);


  if (args.hdrmsg != NULL) 
    hdrdata = malloc(strlen(imgmsg) + strlen(args.hdrmsg) + 3);
  else
    hdrdata = malloc(strlen(imgmsg) + 2);
  
  if (hdrdata == NULL) {
    printf("out of memory?\n");
    goto fail;
  }

  if (args.hdrmsg != NULL) 
    sprintf(hdrdata, "%s\n%s\n", args.hdrmsg, imgmsg);
  else
    sprintf(hdrdata, "%s\n", imgmsg);

  if (mat_write_hdr_data(mat, hdrdata, strlen(hdrdata)+1)) {
    printf("error writing header message \"%s\" to %s\n",
           hdrdata, args.output);
    goto fail;
  }
  
  if (lblimg != NULL) {
    if (_write_labels(&lblhdr, lblimg, mat, incvxls, nincvxls)) {
      printf("error writing labels to %s\n", args.output);
      goto fail;
    }
  }

  if (_mk_corr_matrix(&vol, mat, args.corrtype, incvxls, nincvxls)) {
    printf("error creating correlation matrix\n");
    goto fail;
  }

  mat_close(mat);
  analyze_free_volume(&vol);
  free(imgmsg);
  free(hdrdata);
  free(lblimg);
  free(incvxls);

  return 0;
  
fail:

  if (mat != NULL) mat_close(mat);
  return 1;
}
void plot_add_fit(plot *p, const fit_data *d, const size_t ky, const mat *x_ex,\
                  const size_t kx, const mat *par, const double xmin,          \
                  const double xmax, const size_t npt, const bool do_sub,      \
                  const unsigned int obj,  const strbuf dat_title,             \
                  const strbuf fit_title, const strbuf dat_color,              \
                  const strbuf fit_color)
{
    mat *x,*x_err,*y,*y_err,*cor_data;
    bool have_x_err;
    size_t nfitpt,ndata;
    size_t i,j;
    
    nfitpt        = fit_data_fit_point_num(d);
    ndata      = fit_data_get_ndata(d);
    j          = 0;
    have_x_err = fit_data_have_x_covar(d,kx);
    
    x          = mat_create(nfitpt,1);
    y          = mat_create(nfitpt,1);
    x_err      = mat_create(nfitpt,1);
    y_err      = mat_create(nfitpt,1);
    cor_data   = mat_create(ndata,1);

    if (par != NULL)
    {
        if (obj & PF_FIT)
        {
            plot_add_model(p,d->model->func[ky],x_ex,kx,par,d->model_param,\
                           xmin,xmax,npt,fit_title,fit_color);
        }
        if ((obj & PF_DATA)&&(do_sub))
        {
            fit_partresidual(cor_data,d,ky,x_ex,kx,par);
        }
        else
        {
            fit_data_get_y_k(cor_data,d,ky);
        }
    }
    else
    {
        fit_data_get_y_k(cor_data,d,ky);
    }
    if (obj & PF_DATA)
    {
        for (i=0;i<ndata;i++)
        {
            if (fit_data_is_fit_point(d,i))
            {
                mat_set(x,j,0,fit_data_get_x(d,i,kx));
                if (have_x_err)
                {
                    mat_set(x_err,j,0,                                       \
                            sqrt(mat_get(fit_data_pt_x_covar(d,kx,kx),i,i)));
                }
                mat_set(y,j,0,mat_get(cor_data,i,0));
                mat_set(y_err,j,0,                                       \
                        sqrt(mat_get(fit_data_pt_y_covar(d,ky,ky),i,i)));
                j++;
            }
        }
        if (have_x_err)
        {
            plot_add_dat(p,x,y,x_err,y_err,dat_title,dat_color);
        }
        else
        {
            plot_add_dat(p,x,y,NULL,y_err,dat_title,dat_color);
        }
    }
    
    mat_destroy(x);
    mat_destroy(x_err);
    mat_destroy(y);
    mat_destroy(y_err);
    mat_destroy(cor_data);
}
Beispiel #18
0
void plot_fit(const rs_sample *s_fit, fit_data *d, fit_param *param, const plot_flag f)
{
    plot *p[N_EX_VAR];
    double *xb[N_EX_VAR] = {NULL,NULL,NULL,NULL,NULL,NULL,NULL};
    double x_range[N_EX_VAR][2],b_int[2],dbind,a;
    size_t bind,vind,eind,k,phy_ind,s;
    strbuf color,gtitle,title,xlabel,ylabel;
    mat *phy_pt,*x_k,*fit,*cordat,**vol_av_corr,*yerrtmp;
    ens *ept;
    
    phy_pt     = mat_create(N_EX_VAR,1);
    x_k        = mat_create(param->nens,1);
    cordat     = mat_create(param->nens,1);
    MALLOC(vol_av_corr,mat **,param->nbeta);
    for (bind=0;bind<param->nbeta;bind++)
    {
        vol_av_corr[bind] = mat_create(param->nvol[bind],1);
    }

    for (k=0;k<N_EX_VAR;k++)
    {
        p[k] = plot_create();
    }
    
    param->scale_model = 1;
    fit = rs_sample_pt_cent_val(s_fit);
    if (IS_AN(param,AN_PHYPT)&&IS_AN(param,AN_SCALE))
    {
        phy_ind = 1;
        s       = fm_scaleset_taylor_npar(param);
    }
    else
    {
        phy_ind = 0;
        s       = 0;
    }
    for (k=0;k<N_EX_VAR;k++)
    {
        if (k == i_vind)
        {
            fit_data_get_x_k(x_k,d,i_Linv);
        }
        else
        {
            fit_data_get_x_k(x_k,d,k);
        }
        if ((k == i_a)||(k == i_ud)||(k == i_Linv)||(k == i_alpha)\
            ||(k == i_vind))
        {
            x_range[k][0] = 0.0;
        }
        else
        {
            x_range[k][0] = mat_get_min(x_k)-0.15*fabs(mat_get_min(x_k));
        }
        x_range[k][1] = mat_get_max(x_k)+0.15*fabs(mat_get_min(x_k));
        plot_set_scale_xmanual(p[k],x_range[k][0],x_range[k][1]);
    }
    if (f == Q)
    {
        sprintf(gtitle,"quantity: %s -- scale: %s -- datasets: %s -- ensembles: %s",\
                param->q_name,param->scale_part,param->dataset_cat,param->manifest);
        mat_set(phy_pt,i_ud,0,SQ(param->M_ud));
        mat_set(phy_pt,i_s,0,SQ(param->M_s));
        mat_set(phy_pt,i_umd,0,param->M_umd_val);
        mat_set(phy_pt,i_alpha,0,param->alpha);
        mat_set(phy_pt,i_bind,0,0.0);
        mat_set(phy_pt,i_vind,0,0.0);
        mat_set(phy_pt,i_a,0,0.0);
        mat_set(phy_pt,i_Linv,0,0.0);
        mat_set(phy_pt,i_fvM,0,param->qed_fvol_mass);
        /* regular plots */
        PLOT_ADD_FIT(PF_FIT,i_ud,phy_ind,"","rgb 'black'");
        PLOT_ADD_PB(i_ud,phy_ind,"rgb 'black'");
        PLOT_ADD_FIT(PF_FIT,i_s,phy_ind,"","rgb 'black'");
        PLOT_ADD_PB(i_s,phy_ind,"rgb 'black'");
        PLOT_ADD_FIT(PF_FIT,i_umd,phy_ind,"","rgb 'black'");
        PLOT_ADD_PB(i_umd,phy_ind,"rgb 'black'");
        PLOT_ADD_FIT(PF_FIT,i_alpha,phy_ind,"","rgb 'black'");
        PLOT_ADD_PB(i_alpha,phy_ind,"rgb 'black'");
        PLOT_ADD_FIT(PF_FIT,i_a,phy_ind,"","rgb 'black'");
        PLOT_ADD_PB(i_a,phy_ind,"rgb 'black'");
        PLOT_ADD_FIT(PF_FIT,i_Linv,phy_ind,"","rgb 'black'");
        PLOT_ADD_PB(i_Linv,phy_ind,"rgb 'black'");
        for (bind=0;bind<param->nbeta;bind++)
        {
            dbind      = (double)(bind);
            b_int[0]   = dbind - 0.1;
            b_int[1]   = dbind + 0.1;
            xb[i_bind] = b_int;
            fit_data_fit_region(d,xb);
            sprintf(color,"%d",1+(int)bind);
            sprintf(title,"beta = %s",param->beta[bind]);
            PLOT_ADD_FIT(PF_DATA,i_ud,phy_ind,title,color);
            PLOT_ADD_FIT(PF_DATA,i_s,phy_ind,title,color);
            PLOT_ADD_FIT(PF_DATA,i_umd,phy_ind,title,color);
            PLOT_ADD_FIT(PF_DATA,i_alpha,phy_ind,title,color);
            PLOT_ADD_FIT(PF_DATA,i_a,phy_ind,title,color);
            PLOT_ADD_FIT(PF_DATA,i_Linv,phy_ind,title,color);
            fit_data_fit_all_points(d,true);
        }
        /* volume averages plot */
        plot_add_fit(p[i_vind],d,phy_ind,phy_pt,i_Linv,fit,x_range[i_Linv][0],\
                     x_range[i_Linv][1],MOD_PLOT_NPT,true,PF_FIT,"","",       \
                     "rgb 'black'","rgb 'black'");
        plot_add_fit_predband(p[i_vind],d,phy_ind,phy_pt,i_Linv,s_fit,\
                              x_range[i_Linv][0],x_range[i_Linv][1],  \
                              MOD_PLOT_NPT/4,"rgb 'black'");
        fit_partresidual(cordat,d,phy_ind,phy_pt,i_Linv,fit);
        for(bind=0;bind<param->nbeta;bind++)
        {
            mat_zero(vol_av_corr[bind]);
        }
        for(eind=0;eind<param->nens;eind++)
        {
            ept  = param->point + eind;
            bind = (size_t)ind_beta(ept->beta,param);
            vind = (size_t)ind_volume((unsigned int)ept->L,(int)bind,param);
            mat_inc(vol_av_corr[bind],vind,0,mat_get(cordat,eind,0));
        }
        for (bind=0;bind<param->nbeta;bind++)
        for (vind=0;vind<param->nvol[bind];vind++)
        {
            mat_set(vol_av_corr[bind],vind,0,               \
                    mat_get(vol_av_corr[bind],vind,0)       \
                    /((double)(param->nenspvol[bind][vind])));
        }
        for(bind=0;bind<param->nbeta;bind++)
        {
            yerrtmp = mat_create(param->nvol[bind],1);
            
            rs_sample_varp(yerrtmp,param->s_vol_av[bind]);
            mat_eqsqrt(yerrtmp);
            sprintf(color,"%d",1+(int)bind);
            sprintf(title,"beta = %s",param->beta[bind]);
            plot_add_dat_yerr(p[i_vind],                                     \
                              rs_sample_pt_cent_val(param->s_vol_Linv[bind]),\
                              vol_av_corr[bind],yerrtmp,title,color);
            
            mat_destroy(yerrtmp);
        }

        /* display plots */
        switch (param->q_dim)
        {
            case 0:
                strbufcpy(ylabel,param->q_name);
                break;
            case 1:
                sprintf(ylabel,"%s (MeV)",param->q_name);
                break;
            default:
                sprintf(ylabel,"%s^%d (MeV^%d)",param->q_name,param->q_dim,\
                        param->q_dim);
                break;
        }
        
        sprintf(xlabel,"M_%s^2 (MeV^2)",param->ud_name);
        PLOT_ADD_EX(i_ud,s);
        PLOT_DISP(i_ud,"ud");
        sprintf(xlabel,"M_%s^2 (MeV^2)",param->s_name);
        PLOT_ADD_EX(i_s,s);
        PLOT_DISP(i_s,"s");
        strbufcpy(xlabel,"a (MeV^-1)");
        PLOT_ADD_EX(i_a,s);
        PLOT_DISP(i_a,"a");
        if (param->have_umd)
        {
            sprintf(xlabel,"%s (MeV^2)",param->umd_name);
            PLOT_ADD_EX(i_umd,s);
            PLOT_DISP(i_umd,"umd");
        }
        if (param->have_alpha)
        {
            strbufcpy(xlabel,"alpha");
            PLOT_ADD_EX(i_alpha,s);
            PLOT_DISP(i_alpha,"alpha");
        }
        strbufcpy(xlabel,"1/L (MeV)");
        PLOT_ADD_EX(i_Linv,s);
        PLOT_DISP(i_Linv,"Linv");
        PLOT_ADD_EX(i_vind,s);
        PLOT_DISP(i_vind,"Linv_av");
    }
    else if (f == SCALE)
    {
        sprintf(gtitle,"scale setting: %s -- datasets: %s -- ensembles: %s",
                param->scale_part,param->dataset_cat,param->manifest);
        for (bind=0;bind<param->nbeta;bind++)
        {
            dbind      = (double)(bind);
            b_int[0]   = dbind - 0.1;
            b_int[1]   = dbind + 0.1;
            xb[i_bind] = b_int;
            a          = mat_get(fit,bind,0);
            fit_data_fit_region(d,xb);
            mat_set(phy_pt,i_ud,0,SQ(a*param->M_ud));
            mat_set(phy_pt,i_s,0,SQ(a*param->M_s));
            mat_set(phy_pt,i_umd,0,SQ(a)*param->M_umd_val);
            mat_set(phy_pt,i_bind,0,bind);
            mat_set(phy_pt,i_a,0,a);
            mat_set(phy_pt,i_Linv,0,0.0);
            sprintf(color,"%d",1+(int)bind);
            sprintf(title,"beta = %s",param->beta[bind]);
            PLOT_ADD_FIT(PF_DATA|PF_FIT,i_ud,0,title,color);
            PLOT_ADD_FIT(PF_DATA|PF_FIT,i_s,0,title,color);
            PLOT_ADD_FIT(PF_DATA|PF_FIT,i_umd,0,title,color);
            PLOT_ADD_FIT(PF_DATA|PF_FIT,i_Linv,0,title,color);
            fit_data_fit_all_points(d,true);
        }
        sprintf(ylabel,"(a*M_%s)^2",param->scale_part);
        sprintf(xlabel,"(a*M_%s)^2",param->ud_name);
        PLOT_DISP(i_ud,"ud");
        sprintf(xlabel,"(a*M_%s)^2",param->s_name);
        PLOT_DISP(i_s,"s");
        if (param->have_umd)
        {
            sprintf(xlabel,"a^2*%s",param->umd_name);
            PLOT_DISP(i_umd,"umd");
        }
        strbufcpy(xlabel,"a/L");
        PLOT_DISP(i_Linv,"Linv");
    }
    param->scale_model = 0;
    
    mat_destroy(phy_pt);
    mat_destroy(x_k);
    mat_destroy(cordat);
    for (bind=0;bind<param->nbeta;bind++)
    {
        mat_destroy(vol_av_corr[bind]);
    }
    free(vol_av_corr);
    for (k=0;k<N_EX_VAR;k++)
    {
        plot_destroy(p[k]);
    }
}
Beispiel #19
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;
}
Beispiel #20
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;
}
Beispiel #21
0
void print_result(const rs_sample *s_fit, fit_param *param)
{
    size_t i;
    int j;
    mat *fit,*fit_var;
    strbuf buf;
    
    i   = 0;
    fit = rs_sample_pt_cent_val(s_fit);
    
    fit_var = mat_create(fit_model_get_npar(&(param->fm),param),1);
    
    rs_sample_varp(fit_var,s_fit);
    mpi_printf("\n");
    mpi_printf("fit parameters :\n");
    if (IS_AN(param,AN_SCALE))
    {
        for(j=0;j<(int)param->nbeta;j++)
        {
            sprintf(buf,"a_%s",param->beta[j]);
            PRINT_SCALE(buf);
        }
        if (param->s_M_ud_deg > 0)
        {
            for (j=0;j<param->s_M_ud_deg;j++)
            {
                sprintf(buf,"s_p_ud_%d",j+1);
                PRINT_PAR(buf);
            }
        }
        if (param->s_M_s_deg > 0)
        {
            for (j=0;j<param->s_M_s_deg;j++)
            {
                sprintf(buf,"s_p_s_%d",j+1);
                PRINT_PAR(buf);
            }
        }
        if (param->s_with_a2ud)
        {
            PRINT_PAR("s_a2ud");
        }
        if (param->s_with_a2s)
        {
            PRINT_PAR("s_a2s");
        }
        if (param->s_umd_deg > 0)
        {
            for (j=0;j<param->s_umd_deg;j++)
            {
                sprintf(buf,"s_p_umd_%d",j+1);
                PRINT_PAR(buf);
            }
        }
        if (param->s_with_qed_fvol)
        {
            PRINT_PAR("s_p_fvol_L");
        }
    }
    if (IS_AN(param,AN_PHYPT))
    {
        if (param->with_const)
        {
            PRINT_PAR("const");
        }
        if (param->M_ud_deg > 0)
        {
            for (j=0;j<param->M_ud_deg;j++)
            {
                sprintf(buf,"p_ud_%d",j+1);
                PRINT_PAR(buf);
            }
        }
        if (param->M_s_deg > 0)
        {
            for (j=0;j<param->M_s_deg;j++)
            {
                sprintf(buf,"p_s_%d",j+1);
                PRINT_PAR(buf);
            }
        }
        if (param->with_a2 > 0)
        {
            PRINT_PAR("p_a2");
        }
        if (param->with_alpha_sa > 0)
        {
            PRINT_PAR("p_alpha_sa");
        }
        if (param->with_a2ud)
        {
            PRINT_PAR("p_a2ud");
        }
        if (param->with_a2s)
        {
            PRINT_PAR("p_a2s");
        }
        if (param->umd_deg)
        {
            PRINT_PAR("p_umd");
        }
        if (param->with_udumd)
        {
            for (j=0;j<param->with_udumd;j++)
            {
                sprintf(buf,"p_udumd_%d",j+1);
                PRINT_PAR(buf);
            }
        }
        if (param->with_sumd)
        {
            for (j=0;j<param->with_sumd;j++)
            {
                sprintf(buf,"p_sumd_%d",j+1);
                PRINT_PAR(buf);
            }
        }
        if (param->with_a2umd)
        {
            PRINT_PAR("p_a2umd");
        }
        if (param->with_alpha_saumd)
        {
            PRINT_PAR("p_alpha_saumd");
        }
        if (param->alpha_deg)
        {
            PRINT_PAR("p_alpha");
        }
        if (param->with_udalpha)
        {
            for (j=0;j<param->with_udalpha;j++)
            {
                sprintf(buf,"p_udalpha_%d",j+1);
                PRINT_PAR(buf);
            }
        }
        if (param->with_salpha)
        {
            for (j=0;j<param->with_salpha;j++)
            {
                sprintf(buf,"p_salpha_%d",j+1);
                PRINT_PAR(buf);
            }
        }
        if (param->with_aalpha)
        {
            PRINT_PAR("p_aalpha");
        }
        if (param->with_qed_fvol)
        {
            if (param->with_qed_fvol_monopmod)
            {
                if (param->with_qed_fvol == 2)
                {
                    PRINT_PAR("p_Linv_2");
                }
            }
            else
            {
                for (j=0;j<param->with_qed_fvol;j++)
                {
                    sprintf(buf,"p_Linv_%d",j+1);
                    PRINT_PAR(buf);
                }
            }
        }
        if (IS_AN(param,AN_PHYPT)&&!IS_AN(param,AN_SCALE)&&\
            (strbufcmp(param->with_ext_a,"") != 0))
        {
            for(j=0;j<(int)param->nbeta;j++)
            {
                sprintf(buf,"corr_a_%s",param->beta[j]);
                PRINT_SCALE(buf);
            }
        }
    }
    mpi_printf("\n");
    
    mat_destroy(fit_var);
}
Beispiel #22
0
void fprint_table(FILE* stream, rs_sample *s_x[N_EX_VAR], rs_sample *s_q[2],\
                  const mat *res, const fit_param *param, const plot_flag f)
{
    mat **x_err,*q_err;
    const rs_sample *s_q_pt;
    size_t nens,ydim;
    size_t ens_ind;
    
    nens     = param->nens;
    ydim     = (f == SCALE) ? 0   : 1;
    s_q_pt   = s_q[ydim];
    
    x_err = mat_ar_create(N_EX_VAR,nens,1);
    q_err = mat_create(nens,1);
    
    /* computing errors */
    rs_sample_varp(x_err[i_ud],s_x[i_ud]);
    mat_eqsqrt(x_err[i_ud]);
    rs_sample_varp(x_err[i_s],s_x[i_s]);
    mat_eqsqrt(x_err[i_s]);
    rs_sample_varp(x_err[i_a],s_x[i_a]);
    mat_eqsqrt(x_err[i_a]);
    rs_sample_varp(x_err[i_umd],s_x[i_umd]);
    mat_eqsqrt(x_err[i_umd]);
    rs_sample_varp(x_err[i_Linv],s_x[i_Linv]);
    mat_eqsqrt(x_err[i_Linv]);
    rs_sample_varp(q_err,s_q_pt);
    mat_eqsqrt(q_err);
    
    /* display */
    fprintf(stream,"#%49s  ","ensemble");
    PRINT_DLABEL_WERR(param->ud_name);
    PRINT_DLABEL_WERR(param->s_name);
    if (f == Q)
    {
        PRINT_DLABEL_WERR("a");
    }
    if (param->have_umd)
    {
        PRINT_DLABEL_WERR(param->umd_name);
    }
    if (param->have_alpha)
    {
        PRINT_DLABEL("alpha");
    }
    PRINT_DLABEL_WERR("1/L");
    if (f == Q)
    {
        PRINT_DLABEL_WERR(param->q_name);
    }
    else if (f == SCALE)
    {
        PRINT_DLABEL_WERR(param->scale_part);
    }
    PRINT_DLABEL("residuals");
    fprintf(stream,"\n");
    for(ens_ind=0;ens_ind<nens;ens_ind++)
    {
        fprintf(stream,"%50s  ",param->point[ens_ind].dir);
        PRINT_X_WERR(i_ud);
        PRINT_X_WERR(i_s);
        if (f == Q)
        {
            PRINT_X_WERR(i_a);
        }
        if (param->have_umd)
        {
            PRINT_X_WERR(i_umd);
        }
        if (param->have_alpha)
        {
            PRINT_X(i_alpha);
        }
        PRINT_X_WERR(i_Linv);
        PRINT_CV_WERR(s_q_pt,q_err);
        PRINT_D(mat_get(res,ens_ind,0));
        fprintf(stream,"\n");
    }
    fprintf(stream,"\n");

    mat_ar_destroy(x_err,N_EX_VAR);
    mat_destroy(q_err);
}
Beispiel #23
0
int main(int argc, char* argv[])
{
    /*              parsing arguments           */
    /********************************************/
    double latspac_nu;
    qcd_options *opt;
    strbuf name[3],manf_name,unit,sink[3],source[3];
    size_t binsize,nboot,propdim[2],nt;
    char *cpt1,*cpt2;
    corr_no lastc;
    fit_model *fm_pt;
    
    opt = qcd_arg_parse(argc,argv,A_PLOT|A_SAVE_RS|A_LOAD_RG|A_PROP_NAME\
                        |A_PROP_LOAD|A_LATSPAC|A_QCOMP|A_FIT,2,0);
    cpt1 = strtok(opt->ss,"/");
    printf("%s\n",cpt1);
    if (cpt1)
    {
        cpt2 = strchr(cpt1,':');
        if (cpt2 == NULL)
        {
            fprintf(stderr,"error: sink/source option %s is invalid\n",\
                    cpt1);
            exit(EXIT_FAILURE);
        }
        strbufcpy(source[PP],cpt2+1);
        *cpt2 = '\0';
        strbufcpy(sink[PP],cpt1);
    }
    else
    {
        fprintf(stderr,"error: sink/source option %s is invalid\n",\
                opt->ss);
        exit(EXIT_FAILURE);
    }
    cpt1 = strtok(NULL,"/");
    if (cpt1)
    {
        cpt2 = strchr(cpt1,':');
        if (cpt2 == NULL)
        {
            fprintf(stderr,"error: sink/source option %s is invalid\n",\
                    cpt1);
            exit(EXIT_FAILURE);
        }
        strbufcpy(source[AP],cpt2+1);
        *cpt2 = '\0';
        strbufcpy(sink[AP],cpt1);
    }
    else
    {
        strbufcpy(sink[AP],sink[PP]);
        strbufcpy(source[AP],source[PP]);
    }
    cpt1 = strtok(NULL,"/");
    if (cpt1)
    {
        cpt2 = strchr(cpt1,':');
        if (cpt2 == NULL)
        {
            fprintf(stderr,"error: sink/source option %s is invalid\n",\
                    cpt1);
            exit(EXIT_FAILURE);
        }
        strbufcpy(source[AA],cpt2+1);
        *cpt2 = '\0';
        strbufcpy(sink[AA],cpt1);
    }
    else
    {
        strbufcpy(sink[AA],sink[PP]);
        strbufcpy(source[AA],source[PP]);
    }
    cpt1 = strtok(opt->channel[0],"/");
    if (cpt1)
    {
        sprintf(name[PP],"%s_%s_%s_%s",cpt1,opt->quark[0],sink[PP],source[PP]);
    }
    else
    {
        fprintf(stderr,"error: channel option %s is invalid\n",\
                opt->channel[0]);
        exit(EXIT_FAILURE);
    }
    cpt1 = strtok(NULL,"/");
    if (cpt1)
    {
        sprintf(name[AP],"%s_%s_%s_%s",cpt1,opt->quark[0],sink[AP],source[AP]);
    }
    else
    {
        fprintf(stderr,"error: channel option %s is invalid\n",\
                opt->channel[0]);
        exit(EXIT_FAILURE);
    }
    cpt1 = strtok(NULL,"/");
    if (cpt1)
    {
        sprintf(name[AA],"%s_%s_%s_%s",cpt1,opt->quark[0],sink[AA],source[AA]);
        lastc = AA;
        fm_pt = &fm_pseudosc3;
    }
    else
    {
        lastc = AP;
        fm_pt = &fm_pseudosc2;
    }
    strbufcpy(manf_name,opt->manf_name);
    binsize    = opt->binsize;
    nboot      = opt->nboot;
    latspac_nu = opt->latspac_nu;
    if (opt->have_latspac)
    {
        strbufcpy(unit," (MeV)");
    }
    else
    {
        strbufcpy(unit,"");
    }
    latan_set_verb(opt->latan_verb);
    minimizer_set_alg(opt->minimizer);
    mat_ar_loadbin(NULL,propdim,manf_name,name[PP],1);
    nt = propdim[0];
    io_set_fmt(opt->latan_fmt);
    io_init();
    
    /*              loading datas               */
    /********************************************/
    size_t ndat,nbdat;
    mat **prop[3];
    corr_no c;

    ndat    = (size_t)get_nfile(manf_name);
    nbdat   = ndat/binsize + ((ndat%binsize == 0) ? 0 : 1);
    
    for (c=PP;c<=lastc;c++)
    {
        prop[c] = mat_ar_create(nbdat,propdim[0],propdim[1]);
        qcd_printf(opt,"-- loading %s datas from %s...\n",name[c],manf_name);
        mat_ar_loadbin(prop[c],NULL,manf_name,name[c],binsize);
    }
    
    /*                propagator                */
    /********************************************/
    rs_sample *s_mprop[3];
    mat *mprop[3],*sigmprop[3];
    
    for (c=PP;c<=lastc;c++)
    {
        s_mprop[c]  = rs_sample_create(propdim[0],propdim[1],nboot);
        sigmprop[c] = mat_create(propdim[0],propdim[1]);
        qcd_printf(opt,"-- resampling %s mean propagator...\n",name[c]);
        randgen_set_state(opt->state);
        resample(s_mprop[c],prop[c],nbdat,&rs_mean,BOOT,NULL);
        mprop[c] = rs_sample_pt_cent_val(s_mprop[c]);
        rs_sample_varp(sigmprop[c],s_mprop[c]);
        mat_eqsqrt(sigmprop[c]);
    }
    
    /*           effective mass                 */
    /********************************************/
    rs_sample *s_effmass[3];
    mat *tem,*em[3],*sigem[3];
    size_t emdim[2];
    
    get_effmass_size(emdim,mprop[PP],1,EM_ACOSH);
    
    tem = mat_create(emdim[0],1);
    
    for (c=PP;c<=lastc;c++)
    {
        s_effmass[c] = rs_sample_create(emdim[0],emdim[1],nboot);
        sigem[c]     = mat_create(emdim[0],emdim[1]);
        qcd_printf(opt,"-- resampling %s effective mass...\n",name[c]);
        rs_sample_effmass(s_effmass[c],tem,s_mprop[c],1,EM_ACOSH);
        em[c] = rs_sample_pt_cent_val(s_effmass[c]);
        rs_sample_varp(sigem[c],s_effmass[c]);
        mat_eqsqrt(sigem[c]);
    }
    
    /*                  fit mass                */
    /********************************************/
    fit_data *d;
    rs_sample *s_fit;
    mat *fit,*limit,*sigfit,*scanres_t,*scanres_chi2,*scanres_mass,\
    *scanres_masserr;
    size_t npar,nti,tibeg,range[2],ta;
    size_t i,j;
    strbuf buf,range_info,latan_path;
    double pref_i,mass_i;
    
    d        = fit_data_create(nt,1,(size_t)(lastc+1));
    tibeg    = (size_t)(opt->range[0][0]);
    range[0] = 0;
    range[1] = 0;
    npar     = fit_model_get_npar(fm_pt,&nt);
    
    s_fit    = rs_sample_create(npar,1,nboot);
    fit      = rs_sample_pt_cent_val(s_fit);
    limit    = mat_create(npar,2);
    sigfit   = mat_create(npar,1);
    
    /** print operation **/
    if (!opt->do_range_scan)
    {
        qcd_printf(opt,"-- fitting and resampling...\n");
    }
    else
    {
        qcd_printf(opt,"-- scanning ranges [ti,%u] from ti= %u\n",\
                   opt->range[0][1],opt->range[0][0]);
        opt->nmanrange   = 1;
    }
    
    /** check ranges **/
    strbufcpy(range_info,"");
    qcd_printf(opt,"%-20s: ","corrected range(s)");
    fit_data_fit_all_points(d,false);
    for (i=0;i<opt->nmanrange;i++)
    {
        sprintf(buf,"_%u_%u",opt->range[i][0],opt->range[i][1]);
        strbufcat(range_info,buf);
        range[0] = (size_t)(opt->range[i][0]);
        range[1] = (size_t)(opt->range[i][1]);
        correct_range(range,mprop[PP],sigmprop[PP],opt);
        fit_data_fit_range(d,range[0],range[1],true);
    }
    qcd_printf(opt,"\n");
    
    nti             = MAX(range[1] - 1 - tibeg,1);
    scanres_t       = mat_create(nti,1);
    scanres_chi2    = mat_create(nti,1);
    scanres_mass    = mat_create(nti,1);
    scanres_masserr = mat_create(nti,1);
    
    /** set model **/
    fit_data_set_model(d,fm_pt,&nt);
    
    /** set correlation filter **/
    if (opt->corr == NO_COR)
    {
        for (i=0;i<nt;i++)
            for (j=0;j<nt;j++)
            {
                if (i != j)
                {
                    fit_data_set_data_cor(d,i,j,false);
                }
            }
    }
    
    /** set initial parameter values **/
    ta     = nt/8-(size_t)(mat_get(tem,0,0));
    mass_i = mat_get(em[PP],ta,0);
    if (latan_isnan(mass_i))
    {
        mass_i = 0.3;
    }
    mat_set(fit,0,0,mass_i);
    pref_i = mat_get(mprop[PP],ta,0)/(exp(-mass_i*ta)+exp(-mass_i*(nt-ta)));
    if (latan_isnan(pref_i))
    {
        pref_i = 1.0;
    }
    mat_set(fit,1,0,sqrt(pref_i));
    mat_set(fit,2,0,sqrt(pref_i));
    qcd_printf(opt,"%-22smass= %e -- prefactor_0= %e\n","initial parameters: ",\
               mat_get(fit,0,0),pref_i);
    
    /** set parameter limits **/
    mat_cst(limit,latan_nan());
    mat_set(limit,0,0,0.0);
    mat_set(limit,1,0,0.0);
    mat_set(limit,2,0,0.0);
    
    /** positive AP correlator **/
    rs_sample_eqabs(s_mprop[AP]);
    
    /** set x **/
    for (i=0;i<nt;i++)
    {
        fit_data_set_x(d,i,0,(double)(i)-opt->tshift);
    }
    
    /** regular correlator fit... **/
    if (!opt->do_range_scan)
    {
        latan_set_warn(false);
        rs_data_fit(s_fit,limit,NULL,s_mprop,d,NO_COR,NULL);
        latan_set_warn(true);
        rs_data_fit(s_fit,limit,NULL,s_mprop,d,opt->corr,NULL);
        rs_sample_varp(sigfit,s_fit);
        mat_eqsqrt(sigfit);
        if (fit_data_get_chi2pdof(d) > 2.0)
        {
            fprintf(stderr,"warning: bad final fit (chi^2/dof= %.2e)\n",\
                    fit_data_get_chi2pdof(d));
        }
        qcd_printf(opt,"-- results:\n");
        qcd_printf(opt,"%-10s= %.8f +/- %.8e %s\n","mass",\
                   mat_get(fit,0,0)/latspac_nu,       \
                   mat_get(sigfit,0,0)/latspac_nu,unit);
        qcd_printf(opt,"%-10s= %.8f +/- %.8e %s\n","decay",\
                   mat_get(fit,1,0)/latspac_nu,       \
                   mat_get(sigfit,1,0)/latspac_nu,unit);
        qcd_printf(opt,"%-10s= %.8f +/- %.8e %s\n","norm",\
                   mat_get(fit,2,0)/latspac_nu,       \
                   mat_get(sigfit,2,0)/latspac_nu,unit);
        qcd_printf(opt,"%-10s= %d\n","dof",fit_data_get_dof(d));
        qcd_printf(opt,"%-10s= %e\n","chi^2/dof",fit_data_get_chi2pdof(d));
        if (opt->do_save_rs_sample)
        {
            sprintf(latan_path,"%s_pseudosc_fit%s_%s.boot:%s_pseudosc_fit%s_%s",\
                    opt->quark[0],range_info,manf_name,opt->quark[0],\
                    range_info,manf_name);
            rs_sample_save_subsamp(latan_path,'w',s_fit,0,0,1,0);
        }
    }
    /** ...or fit range scanning **/
    else
    {
        qcd_printf(opt,"\n%-5s %-12s a*M_%-8s %-12s","ti/a","chi^2/dof",\
                   opt->quark[0],"error");
        for (i=tibeg;i<range[1]-1;i++)
        {
            latan_set_warn(false);
            rs_data_fit(s_fit,limit,NULL,s_mprop,d,NO_COR,NULL);
            latan_set_warn(true);
            rs_data_fit(s_fit,limit,NULL,s_mprop,d,opt->corr,NULL);
            rs_sample_varp(sigfit,s_fit);
            mat_eqsqrt(sigfit);
            mat_set(scanres_t,i-tibeg,0,(double)(i));
            mat_set(scanres_chi2,i-tibeg,0,fit_data_get_chi2pdof(d));
            mat_set(scanres_mass,i-tibeg,0,mat_get(fit,0,0));
            mat_set(scanres_masserr,i-tibeg,0,mat_get(sigfit,0,0));
            qcd_printf(opt,"\n% -4d % -.5e % -.5e % -.5e",(int)(i),\
                       fit_data_get_chi2pdof(d),mat_get(fit,0,0), \
                       mat_get(sigfit,0,0));
            fit_data_fit_point(d,i,false);
        }
        qcd_printf(opt,"\n\n");
    }
    
    /*                  plot                    */
    /********************************************/
    if (opt->do_plot)
    {
        mat *mbuf,*em_i,*sigem_i,*par,*ft[3],*comp[3];
        plot *p;
        strbuf key,dirname,color;
        size_t maxt,t,npoint;
        double dmaxt,nmass;
        
        mbuf    = mat_create(1,1);
        em_i    = mat_create(nrow(em[PP]),1);
        sigem_i = mat_create(nrow(em[PP]),1);
        par     = mat_create(2,1);
        
        if (!opt->do_range_scan)
        {
            maxt   = nt;
            dmaxt  = (double)maxt;
            npoint = fit_data_fit_point_num(d);
            
            /** chi^2 plot **/
            p = plot_create();
            i = 0;
            for (c=PP;c<=lastc;c++)
            {
                ft[c]   = mat_create(npoint,1);
                comp[c] = mat_create(npoint,1);
                for (t=0;t<nt;t++)
                {
                    if (fit_data_is_fit_point(d,t))
                    {
                        mat_set(ft[c],i%npoint,0,(double)(t)+0.33*(double)(c));
                        mat_set(comp[c],i%npoint,0,mat_get(d->chi2_comp,i,0));
                        i++;
                    }
                }
            }
            plot_set_scale_manual(p,-1.0,dmaxt,-5.0,5.0);
            plot_add_plot(p,"0.0 lt -1 lc rgb 'black' notitle","");
            plot_add_plot(p,"1.0 lt -1 lc rgb 'black' notitle","");
            plot_add_plot(p,"-1.0 lt -1 lc rgb 'black' notitle","");
            plot_add_plot(p,"2.0 lt -1 lc rgb 'dark-gray' notitle","");
            plot_add_plot(p,"-2.0 lt -1 lc rgb 'dark-gray' notitle","");
            plot_add_plot(p,"3.0 lt -1 lc rgb 'gray' notitle","");
            plot_add_plot(p,"-3.0 lt -1 lc rgb 'gray' notitle","");
            plot_add_plot(p,"4.0 lt -1 lc rgb 'light-gray' notitle","");
            plot_add_plot(p,"-4.0 lt -1 lc rgb 'light-gray' notitle","");
            plot_set_ylabel(p,"standard deviations");
            for (c=PP;c<=lastc;c++)
            {
                sprintf(color,"%d",(int)(c)+1);
                plot_add_points(p,ft[c],comp[c],c_name[c],color,"impulses");
            }
            plot_disp(p);
            if (opt->do_save_plot)
            {
                sprintf(dirname,"%s_dev",opt->save_plot_dir);
                plot_save(dirname,p);
            }
            plot_destroy(p);
        
            for (c=PP;c<=lastc;c++)
            {
                /** propagator plot **/
                p = plot_create();
                fit_data_fit_all_points(d,true);
                plot_set_scale_ylog(p);
                plot_set_scale_xmanual(p,0,dmaxt);
                sprintf(key,"%s %s propagator",opt->quark[0],c_name[c]);
                mat_eqabs(mprop[c]);
                plot_add_fit(p,d,c,mbuf,0,fit,0,dmaxt,1000,false,\
                             PF_FIT|PF_DATA,key,"","rgb 'red'","rgb 'red'");
                plot_disp(p);
                if (opt->do_save_plot)
                {
                    sprintf(dirname,"%s_prop_%s",opt->save_plot_dir,c_name[c]);
                    plot_save(dirname,p);
                }
                plot_destroy(p);
                
                /** effective mass plot **/
                p = plot_create();
                mat_eqmuls(em[c],1.0/latspac_nu);
                mat_eqmuls(sigem[c],1.0/latspac_nu);
                nmass = mat_get(fit,0,0)/latspac_nu;
                plot_add_hlineerr(p,nmass, mat_get(sigfit,0,0)/latspac_nu,\
                                  "rgb 'red'");
                sprintf(key,"%s %s effective mass",opt->quark[0],c_name[c]);
                plot_add_dat(p,tem,em[c],NULL,sigem[c],key,"rgb 'blue'");
                plot_disp(p);
                if (opt->do_save_plot)
                {
                    sprintf(dirname,"%s_em_%s",opt->save_plot_dir,c_name[c]);
                    plot_save(dirname,p);
                }
                plot_destroy(p);
            }
        }
        else
        {
            /* chi^2 plot */
            p = plot_create();
            plot_set_scale_manual(p,0,(double)(nt/2),0,5.0);
            plot_add_hline(p,1.0,"rgb 'black'");
            plot_add_dat(p,scanres_t,scanres_chi2,NULL,NULL,"chi^2/dof",\
                         "rgb 'blue'");
            plot_disp(p);
            if (opt->do_save_plot)
            {
                sprintf(dirname,"%s_chi2",opt->save_plot_dir);
                plot_save(dirname,p);
            }
            plot_destroy(p);
            
            /* mass plot */
            p = plot_create();
            plot_set_scale_xmanual(p,0,(double)(nt/2));
            sprintf(key,"a*M_%s",opt->quark[0]);
            plot_add_dat(p,scanres_t,scanres_mass,NULL,scanres_masserr,key,\
                         "rgb 'red'");
            plot_disp(p);
            if (opt->do_save_plot)
            {
                sprintf(dirname,"%s_mass",opt->save_plot_dir);
                plot_save(dirname,p);
            }
            plot_destroy(p);
        }
        
        mat_destroy(em_i);
        mat_destroy(sigem_i);
        mat_destroy(mbuf);
        mat_destroy(par);
        for (c=PP;c<=lastc;c++)
        {
            mat_destroy(ft[c]);
            mat_destroy(comp[c]);
        }
    }
    
    /*              desallocation               */
    /********************************************/
    free(opt);
    io_finish();
    mat_ar_destroy(prop[0],nbdat);
    mat_ar_destroy(prop[1],nbdat);
    for (c=PP;c<=lastc;c++)
    {
        rs_sample_destroy(s_mprop[c]);
        mat_destroy(sigmprop[c]);
        rs_sample_destroy(s_effmass[c]);
        mat_destroy(sigem[c]);
    }
    mat_destroy(tem);
    fit_data_destroy(d);
    rs_sample_destroy(s_fit);
    mat_destroy(limit);
    mat_destroy(sigfit);
    mat_destroy(scanres_t);
    mat_destroy(scanres_chi2);
    mat_destroy(scanres_mass);
    mat_destroy(scanres_masserr);
    
    return EXIT_SUCCESS;
}
Beispiel #24
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);
}