Пример #1
0
int main(int argc, const char * argv[])
{
    static const double endingCondition = 0.000000001;
    
    printSeparator();
    printf(" This program will successively run iterations of the     \n");
    printf(" Jacobi Algorithm for diagonalization until some form of  \n");
    printf(" convergence is reacheed.\n");
    printSeparator();
    BOOL shouldSort = promptShouldUseSorting();
    BOOL demoMode = promptShouldUseDemo();
    int iterations = 1;
    if (!demoMode) {
        iterations = promptIterations();
    }
    
    for (int i = 0; i < iterations; i++) {
        printSeparator();
        printLine();
        
        MatrixRef A = MatrixCreateRandomSymmetric(5);
        double offA = JacobiSquareSumOffDiagonal(A, NULL);
        
        if (demoMode) {
            printf("Starting 5x5 symmetric matrix: \n\n");
            MatrixPrint(A);
            
            printLine();
            printf("Starting off(A): %6.2f\n\n", offA);
            
            printSeparator();
            printLine();
        }
        
        MatrixRef B = Jacobi(A, shouldSort, endingCondition);
        
        if (demoMode) {
            printLine();
            printSeparator();
            printLine();
            printf("Finishing matrix: \n\n");
            MatrixPrint(B);
        }
        
        MatrixDestroy(B); B = NULL;
        MatrixDestroy(A); A = NULL;
    }
    
#if defined(__MINGW32__) || defined(_WIN32)
    system("PAUSE");
#endif
    
    return 0;
}
Пример #2
0
bool
MatrixTest::AreMatricesEqual( MATRIX *m1, MATRIX *m2, float tolerance=0.0 )
{
    bool areEqual = true;

    if ( m1->rows == m2->rows &&
            m2->cols == m2->cols )
    {

        int numberOfRows =  m1->rows;
        int numberOfColumns = m1->cols;

        for ( int row=0; row<numberOfRows; row++ )
        {
            for ( int column=0; column<numberOfColumns; column++ )
            {

                int index = column + row * numberOfColumns;
                float difference = fabs( m1->data[ index ] - m2->data[ index ] );

                if ( difference > tolerance )
                {
                    areEqual = false;
                    std::cerr << "MatrixTest::AreMatricesEqual() not equal: (" <<
                              m1->data[ index ] << ", " << m2->data[ index ] << ")\n";
                    std::cerr.flush();
                }
            }
        }
    }
    else
    {
        std::cerr << "MatrixTest::AreMatricesEqual() not equal: m1: (" <<
                  m1->rows << ", " << m1->cols << "), m2: (" <<
                  m2->rows << ", " << m2->cols << ")\n";
        areEqual = false;
    }

    if (! areEqual)
    {
        std::cerr << "actual:\n";
        MatrixPrint(stderr, m1);
        std::cerr << "expected:\n";
        MatrixPrint(stderr, m2);
    }

    return areEqual;
}
Пример #3
0
int main(void) {
    float M1[9], M2[3], *M3;
    float *inverse;
    int i = 0;
    for (i = 0; i < 3; ++i) {
        scanf("%f", &M1[i]);
    }
    scanf("%f", &M2[0]);
    for (; i < 6; ++i) {
        scanf("%f", &M1[i]);
    }
    scanf("%f", &M2[1]);
    for(; i < 9; ++i) {
        scanf("%f", &M1[i]);
    }
    scanf("%f", &M2[2]);
    //printf("%f\n\n", M2[3]);

    //MatrixPrint(M1, 3, 3);
    //MatrixPrint(M2, 1, 3);
    MatrixInvert3x3(M1, &inverse);
    //MatrixPrint(inverse, 3, 3);
    MatrixMultiply(inverse, 3, 3, M2, 1, 3, &M3);
    MatrixPrint(M3, 1, 3);
    return 0;
}
Пример #4
0
int main(int argc, char ** argv)
{
	char op;
	char mStr[1024];
	matrix ans, m1, m2;
	int sc = 0;

	if(argc > 1){
		op = getOp(argv[1]);
	} else {
		printf("Which operation: ");
		op = getOp(NULL);
	}


	printf("First matrix:\n");
	scanf("%s", mStr);
	m1 = MatrixInit(mStr);

	if(op == 'a' || op == 's' || op == 'm'){
		printf("Second matrix:\n");
		scanf("%s", mStr);
		m2 = MatrixInit(mStr);
	} else if(op == 'c') {
		printf("Scalar multiple:\n");
		scanf("%d", &sc);
	}

	switch(op){
		case 'a':
			ans = MatrixAdd(m1, m2);
			break;
		case 's':
			ans = MatrixSub(m1, m2);
			break;
		case 'm':
			ans = MatrixMul(m1, m2);
			break;
		case 'i':
			ans = MatrixInv(m1);
			break;
		case 'c':
			ans = MatrixSMul(m1, i2f(sc));
			break;
		default:
			printf("Something went very wrong.\n");
			return 1;
	}

	printf("Answer:\n");
	MatrixPrint(ans);

	MatrixFree(m1);
	MatrixFree(ans);
	if(op == 'a' || op == 's' || op == 'm'){
		MatrixFree(m2);
	}

	return 0;
}
Пример #5
0
static int
write_snapshot(MRI *mri_target, MRI *mri_source, MATRIX *m_vox_xform, 
	       GCA_MORPH_PARMS *parms, int fno, int conform, char *in_fname)
{
  MRI *mri_aligned ;
  char fname[STRLEN] ;

  if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
    {
      printf("source->target vox->vox transform:\n") ;
      MatrixPrint(stdout, m_vox_xform) ;
    }
  if (conform || 1)
    {
      mri_aligned = MRIalloc(mri_target->width, mri_target->height,
			     mri_target->depth,mri_source->type);
      MRIcopyHeader(mri_target, mri_aligned) ;
      MRIlinearTransformInterp(mri_source, mri_aligned, m_vox_xform, SAMPLE_NEAREST);
    }
  else
    {
      mri_aligned = MRITransformedCenteredMatrix(mri_source, mri_target, m_vox_xform) ;
    }
  if (in_fname)
    sprintf(fname, "%s_%s", parms->base_name, in_fname) ;
  else
    sprintf(fname, "%s_%03d", parms->base_name, fno) ;
  MRIwriteImageViews(mri_aligned, fname, IMAGE_SIZE) ;
  if (in_fname)
    sprintf(fname, "%s_%s.mgz", parms->base_name, in_fname) ;
  else
    sprintf(fname, "%s_%03d.mgz", parms->base_name, fno) ;
  printf("writing snapshot to %s...\n", fname) ;
  MRIwrite(mri_aligned, fname) ;
  MRIfree(&mri_aligned) ;

  {
#if 0
    mri_aligned = MRIsrcTransformedCentered(mri_source, mri_target, m_vox_xform,
					    SAMPLE_NEAREST) ;
#else
    mri_aligned = MRITransformedCenteredMatrix(mri_source, mri_target, m_vox_xform) ;
#endif
    if (in_fname)
      sprintf(fname, "orig_%s_%s.mgz", parms->base_name, in_fname) ;
    else
      sprintf(fname, "orig_%s_%03d.mgz", parms->base_name, fno) ;
    printf("writing snapshot to %s...\n", fname) ;
    MRIwrite(mri_aligned, fname) ;
    MRIfree(&mri_aligned) ;
  }

  return(NO_ERROR) ;
}
Пример #6
0
main(){
  Matrix *cmA, *vt, *mtR, *tmp;
  int i;
  double z=1;

  double xy[][2]={ // from 0.jpg
    148,537,
    347,220,
    263,367,
    413,315,
  },uv[][2]={ // from 1.jpg
    371,230,
    463,230,
    383,379,
    530,327,
  };
  double ans[3][3];
  cmA=MatrixAlloc(8,8);
  vt=MatrixAlloc(1,8);

  // create A (col-major)
  for(i=0;i<4;i++){
    cmA->data[cmA->W*0+(i*2  )]=z*xy[i][0];
    cmA->data[cmA->W*1+(i*2  )]=z*xy[i][1];
    cmA->data[cmA->W*2+(i*2  )]=z*z;
    cmA->data[cmA->W*3+(i*2  )]=0;
    cmA->data[cmA->W*4+(i*2  )]=0;
    cmA->data[cmA->W*5+(i*2  )]=0;
    cmA->data[cmA->W*6+(i*2  )]=-xy[i][0]*uv[i][0];
    cmA->data[cmA->W*7+(i*2  )]=-xy[i][1]*uv[i][0];
    cmA->data[cmA->W*0+(i*2+1)]=0;
    cmA->data[cmA->W*1+(i*2+1)]=0;
    cmA->data[cmA->W*2+(i*2+1)]=0;
    cmA->data[cmA->W*3+(i*2+1)]=z*xy[i][0];
    cmA->data[cmA->W*4+(i*2+1)]=z*xy[i][1];
    cmA->data[cmA->W*5+(i*2+1)]=z*z;
    cmA->data[cmA->W*6+(i*2+1)]=-xy[i][0]*uv[i][1];
    cmA->data[cmA->W*7+(i*2+1)]=-xy[i][1]*uv[i][1];
    vt->data[i*2  ]=z*uv[i][0];
    vt->data[i*2+1]=z*uv[i][1];
  }

  // solve Least-squares equation
  mtR=MatrixAlloc(8,8);
  MatrixQRDecompColMajor(mtR,cmA);
  tmp=MatrixAlloc(1,8);
  MatrixMultT(tmp,vt,cmA);
  MatrixSimeqLr(tmp,mtR);
  MatrixPrint(tmp);
}
Пример #7
0
static int
register_mri(MRI *mri_in, MRI *mri_ref, MORPH_PARMS *parms, MATRIX *m_L) {
  MRI     *mri_in_windowed, *mri_ref_windowed ;

  fprintf(stderr, "aligning volume with average...\n") ;

  if (window_size > 0) {
    double in_means[3], ref_means[3] ;

    MRIcenterOfMass(mri_in, in_means, 0) ;
    MRIcenterOfMass(mri_ref, ref_means, 0) ;
    printf("windowing ref around (%d, %d, %d) and input around (%d, %d, %d)\n",
           nint(ref_means[0]), nint(ref_means[1]), nint(ref_means[2]),
           nint(in_means[0]), nint(in_means[1]), nint(in_means[2])) ;
    mri_in_windowed =
      MRIwindow(mri_in, NULL, WINDOW_HANNING,nint(in_means[0]),
                nint(in_means[1]), nint(in_means[2]),window_size);
    mri_ref_windowed =
      MRIwindow(mri_ref,NULL,WINDOW_HANNING,nint(ref_means[0]),
                nint(ref_means[1]), nint(ref_means[2]),window_size);
    mri_in = mri_in_windowed ;
    mri_ref = mri_ref_windowed ;
  }

  MRIrigidAlign(mri_in, mri_ref, parms, m_L) ;

  fprintf(stderr, "final transform:\n") ;
  MatrixPrint(stderr, parms->lta->xforms[0].m_L) ;
  fprintf(stderr, "\n") ;

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON) {
    MRI *mri_aligned ;

    mri_aligned =
      MRIapplyRASlinearTransform(mri_in, NULL, parms->lta->xforms[0].m_L) ;
    MRIwriteImageViews(mri_aligned, "after_alignment", IMAGE_SIZE) ;
    MRIfree(&mri_aligned) ;
  }


  MatrixCopy(parms->lta->xforms[0].m_L, m_L) ;
  return(NO_ERROR) ;
}
Пример #8
0
static MATRIX *
initialize_transform(MRI *mri_in, MRI *mri_ref, MP *parms) {
  MATRIX *m_L ;

  fprintf(stderr, "initializing alignment using PCA...\n") ;
  if (Gdiag & DIAG_WRITE && parms->write_iterations > 0) {
    MRIwriteImageViews(parms->mri_ref, "ref", IMAGE_SIZE) ;
    MRIwriteImageViews(parms->mri_in, "before_pca", IMAGE_SIZE) ;
  }

  if (nopca)
    m_L = MatrixIdentity(3, NULL) ;
  else
    m_L = compute_pca(mri_in, mri_ref) ;

  init_scaling(mri_in, mri_ref, m_L) ;
#if 0
  init_translation(mri_in, mri_ref, m_L) ; /* in case PCA failed */
#endif

  /* convert it to RAS mm coordinates */
  MRIvoxelXformToRasXform(mri_in, mri_ref, m_L, m_L) ;

  if (Gdiag & DIAG_SHOW) {
    printf("initial transform:\n") ;
    MatrixPrint(stdout, m_L) ;
  }
  if (Gdiag & DIAG_WRITE && parms->write_iterations > 0) {
    MRI *mri_aligned ;

    mri_aligned = MRIapplyRASlinearTransform(parms->mri_in, NULL, m_L) ;
    MRIwriteImageViews(mri_aligned, "after_pca", IMAGE_SIZE) ;
    MRIfree(&mri_aligned) ;
  }
  return(m_L) ;
}
Пример #9
0
Файл: maw.c Проект: ubsan/MAL
int main(void)
{
    char mStr[1024];
    matrix *ans, *m1, *m2;
    int sc = 0;

    printf("Which operation: ");
    char op = tolower(getchar());

    while(op != '+' || op != '-' || op != '*' || op != '/' || op != 'i') {
        puts(opErr);
        op = tolower(getchar());
    }

    printf("First matrix:\n");
    scanf("%s", mStr);
    m1 = MatrixInit(mStr);
    MatrixPrint(m1);

    if(op == 'a' || op == 's' || op == 'm') {
        printf("Second matrix:\n");
        scanf("%s", mStr);
        m2 = MatrixInit(mStr);
        MatrixPrint(m2);
    } else if(op == 'c') {
        printf("Scalar multiple:\n");
        scanf("%d", &sc);
    }

    switch(op) {
    case 'a':
        ans = MatrixAdd(m1, m2);
        break;
    case 's':
        ans = MatrixSub(m1, m2);
        break;
    case 'm':
        ans = MatrixMul(m1, m2);
        break;
    case 'i':
        ans = MatrixInv(m1);
        break;
    case 'c':
        ans = MatrixSMul(m1, sc);
        break;
    default:
        printf("Something went very wrong.\n");
        return 1;
    }

    printf("Answer:\n");
    MatrixPrint(ans);

    MatrixFree(m1);
    MatrixFree(ans);
    if(op == 'a' || op == 's' || op == 'm') {
        MatrixFree(m2);
    }

    return 0;
}
Пример #10
0
int
main(int argc, char *argv[])
{
  char         **av, *source_fname, *target_fname, *out_fname, fname[STRLEN] ;
  int          ac, nargs, new_transform = 0, pad ;
  MRI          *mri_target, *mri_source, *mri_orig_source ;
  MRI_REGION   box ;
  struct timeb start ;
  int          msec, minutes, seconds ;
  GCA_MORPH    *gcam ;
  MATRIX       *m_L/*, *m_I*/ ;
  LTA          *lta ;


  /* initialize the morph params */
  memset(&mp, 0, sizeof(GCA_MORPH_PARMS));
  /* for nonlinear morph */
  mp.l_jacobian = 1 ;
  mp.min_sigma = 0.4 ;
  mp.l_distance = 0 ;
  mp.l_log_likelihood = .025 ;
  mp.dt = 0.005 ;
  mp.noneg = True ;
  mp.exp_k = 20 ;
  mp.diag_write_snapshots = 1 ;
  mp.momentum = 0.9 ;
  if (FZERO(mp.l_smoothness))
    mp.l_smoothness = 2 ;
  mp.sigma = 8 ;
  mp.relabel_avgs = -1 ;
  mp.navgs = 256 ;
  mp.levels = 6 ;
  mp.integration_type = GCAM_INTEGRATE_BOTH ;
  mp.nsmall = 1 ;
  mp.reset_avgs = -1 ;
  mp.npasses = 3 ;
  mp.regrid = regrid? True : False ;
  mp.tol = 0.1 ;
  mp.niterations = 1000 ;
	
  TimerStart(&start) ;
  setRandomSeed(-1L) ;
  DiagInit(NULL, NULL, NULL) ;
  ErrorInit(NULL, NULL, NULL) ;

  Progname = argv[0] ;
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
    {
      nargs = get_option(argc, argv) ;
      argc -= nargs ;
      argv += nargs ;
    }

  if (argc < 4)
    usage_exit(1) ;

  source_fname = argv[1] ;
  target_fname = argv[2] ;
  out_fname = argv[3] ;
  FileNameOnly(out_fname, fname) ;
  FileNameRemoveExtension(fname, fname) ;
  strcpy(mp.base_name, fname) ;
  mri_source = MRIread(source_fname) ;
  if (!mri_source)
    ErrorExit(ERROR_NOFILE, "%s: could not read source label volume %s",
	      Progname, source_fname) ;

  if (mri_source->type == MRI_INT)
    {
      MRI *mri_tmp = MRIchangeType(mri_source, MRI_FLOAT, 0, 1, 1) ;
      MRIfree(&mri_source); mri_source = mri_tmp ;
    }
  mri_target = MRIread(target_fname) ;
  if (!mri_target)
    ErrorExit(ERROR_NOFILE, "%s: could not read target label volume %s",
	      Progname, target_fname) ;
  if (mri_target->type == MRI_INT)
    {
      MRI *mri_tmp = MRIchangeType(mri_target, MRI_FLOAT, 0, 1, 1) ;
      MRIfree(&mri_target); mri_target = mri_tmp ;
    }
  if (erosions > 0)
    {
      int n ;
      for (n = 0 ; n < erosions ; n++)
	{
	  MRIerodeZero(mri_target, mri_target) ;
	  MRIerodeZero(mri_source, mri_source) ;
	}
    }
  if (scale_values > 0)
    {
      MRIscalarMul(mri_source, mri_source, scale_values) ;
      MRIscalarMul(mri_target, mri_target, scale_values) ;
    }
  if (transform && transform->type == MORPH_3D_TYPE)
    TransformRas2Vox(transform, mri_source,NULL) ;
  if (use_aseg == 0)
    {
      if (match_peak_intensity_ratio)
	MRImatchIntensityRatio(mri_source, mri_target, mri_source, .8, 1.2, 
			       100, 125) ;
      else if (match_mean_intensity)
	MRImatchMeanIntensity(mri_source, mri_target, mri_source) ;
      MRIboundingBox(mri_source, 0, &box) ;
      pad = (int)ceil(PADVOX * 
		      MAX(mri_target->xsize,MAX(mri_target->ysize,mri_target->zsize)) / 
		      MIN(mri_source->xsize,MIN(mri_source->ysize,mri_source->zsize))); 
#if 0
      { MRI *mri_tmp ;
	if (pad < 1)
	  pad = 1 ;
	printf("padding source with %d voxels...\n", pad) ;
	mri_tmp = MRIextractRegionAndPad(mri_source, NULL, &box, pad) ;
	if ((Gdiag & DIAG_WRITE) && DIAG_VERBOSE_ON)
	  MRIwrite(mri_tmp, "t.mgz") ;
	MRIfree(&mri_source) ;
	mri_source = mri_tmp ;
      }
#endif
    }
  mri_orig_source = MRIcopy(mri_source, NULL) ;

  mp.max_grad = 0.3*mri_source->xsize ;

  if (transform == NULL)
    transform = TransformAlloc(LINEAR_VOXEL_TO_VOXEL, NULL) ;

  if (transform->type != MORPH_3D_TYPE)  // initializing m3d from a linear transform
    {
      new_transform = 1 ;
      lta = ((LTA *)(transform->xform)) ;
      if (lta->type != LINEAR_VOX_TO_VOX)
	{
	  printf("converting ras xform to voxel xform\n") ;
	  m_L = MRIrasXformToVoxelXform(mri_source, mri_target, lta->xforms[0].m_L, NULL) ;
	  MatrixFree(&lta->xforms[0].m_L) ;
	  lta->type = LINEAR_VOX_TO_VOX ;
	}
      else
	{
	  printf("using voxel xform\n") ;
	  m_L = lta->xforms[0].m_L ;
	}
#if 0
      if (Gsx >= 0)   // update debugging coords
	{
	  VECTOR *v1, *v2 ;

	  v1 = VectorAlloc(4, MATRIX_REAL) ;
	  Gsx -= (box.x-pad) ;
	  Gsy -= (box.y-pad) ;
	  Gsz -= (box.z-pad) ;
	  V3_X(v1) = Gsx ; V3_Y(v1) = Gsy ; V3_Z(v1) = Gsz ;
	  VECTOR_ELT(v1,4) = 1.0 ;
	  v2 = MatrixMultiply(m_L, v1, NULL) ;
      
	  Gsx = nint(V3_X(v2)) ; Gsy = nint(V3_Y(v2)) ; Gsz = nint(V3_Z(v2)) ;
	  MatrixFree(&v2) ; MatrixFree(&v1) ;
	  printf("mapping by transform (%d, %d, %d) --> (%d, %d, %d) for rgb writing\n",
		 Gx, Gy, Gz, Gsx, Gsy, Gsz) ;
	}
#endif
      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
	write_snapshot(mri_target, mri_source, m_L, &mp, 0, 1, "linear_init");

      lta->xforms[0].m_L = m_L ;
      printf("initializing GCAM with vox->vox matrix:\n") ;
      MatrixPrint(stdout, m_L) ;
      gcam = GCAMcreateFromIntensityImage(mri_source, mri_target, transform) ;
#if 0
      gcam->gca = gcaAllocMax(1, 1, 1, 
			      mri_target->width, mri_target->height, 
			      mri_target->depth,
			      0, 0) ;
#endif
      GCAMinitVolGeom(gcam, mri_source, mri_target) ;
      if (use_aseg)
	{
	  if (ribbon_name)
	    {
	      char fname[STRLEN], path[STRLEN], *str, *hemi ;
	      int  h, s, label ;
	      MRI_SURFACE *mris_white, *mris_pial ;
	      MRI         *mri ;

	      for (s = 0 ; s <= 1 ; s++) // source and target
		{
		  if (s == 0)
		    {
		      str = source_surf ;
		      mri = mri_source ;
		      FileNamePath(mri->fname, path) ;
		      strcat(path, "/../surf") ;
		    }
		  else
		    {
		      mri = mri_target ;
		      FileNamePath(mri->fname, path) ;
		      strcat(path, "/../elastic") ;
		      str = target_surf ;
		    }
		  // sorry - these values come from FreeSurferColorLUT.txt
		  MRIreplaceValueRange(mri, mri, 1000, 1034, Left_Cerebral_Cortex) ;
		  MRIreplaceValueRange(mri, mri, 1100, 1180, Left_Cerebral_Cortex) ;
		  MRIreplaceValueRange(mri, mri, 2000, 2034, Right_Cerebral_Cortex) ;
		  MRIreplaceValueRange(mri, mri, 2100, 2180, Right_Cerebral_Cortex) ;
		  for (h = LEFT_HEMISPHERE ; h <= RIGHT_HEMISPHERE ; h++)  
		    {
		      if (h == LEFT_HEMISPHERE)
			{
			  hemi = "lh" ;
			  label = Left_Cerebral_Cortex ;
			}
		      else
			{
			  label = Right_Cerebral_Cortex ;
			  hemi = "rh" ;
			}
		      sprintf(fname, "%s/%s%s.white", path, hemi, str) ;
		      mris_white = MRISread(fname) ;
		      if (mris_white == NULL)
			ErrorExit(ERROR_NOFILE, "%s: could not read surface %s", Progname, fname) ;
		      MRISsaveVertexPositions(mris_white, WHITE_VERTICES) ;
		      sprintf(fname, "%s/%s%s.pial", path, hemi, str) ;
		      mris_pial = MRISread(fname) ;
		      if (mris_pial == NULL)
			ErrorExit(ERROR_NOFILE, "%s: could not read surface %s", Progname, fname) ;
		      MRISsaveVertexPositions(mris_pial, PIAL_VERTICES) ;
		      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
			{
			  sprintf(fname, "sb.mgz") ;
			  MRIwrite(mri_source, fname) ; 
			  sprintf(fname, "tb.mgz") ;
			  MRIwrite(mri_target, fname) ;
			}

		      insert_ribbon_into_aseg(mri, mri, mris_white, mris_pial, h) ;
		      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
			{
			  sprintf(fname, "sa.mgz") ;
			  MRIwrite(mri_source, fname) ; 
			  sprintf(fname, "ta.mgz") ;
			  MRIwrite(mri_target, fname) ;
			}
		      MRISfree(&mris_white) ; MRISfree(&mris_pial) ;
		    }
		}
	      if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
		{
		  sprintf(fname, "s.mgz") ;
		  MRIwrite(mri_source, fname) ; 
		  sprintf(fname, "t.mgz") ;
		  MRIwrite(mri_target, fname) ;
		}
	    }
	  GCAMinitLabels(gcam, mri_target) ;
	  GCAMsetVariances(gcam, 1.0) ;
	  mp.mri_dist_map = create_distance_transforms(mri_source, mri_target, NULL, 40.0, gcam) ;
	}
    }
  else  /* use a previously create morph and integrate it some more */
    {
      printf("using previously create gcam...\n") ;
      gcam = (GCA_MORPH *)(transform->xform) ;
      GCAMrasToVox(gcam, mri_source) ;
      if (use_aseg)
	{
	  GCAMinitLabels(gcam, mri_target) ;
	  GCAMsetVariances(gcam, 1.0) ;
	  mp.mri_dist_map = create_distance_transforms(mri_source, mri_target, NULL, 40.0, gcam) ;
	}
      else
	GCAMaddIntensitiesFromImage(gcam, mri_target) ;
    }
  if (gcam->width != mri_source->width ||
      gcam->height != mri_source->height ||
      gcam->depth != mri_source->depth)
    ErrorExit(ERROR_BADPARM, "%s: warning gcam (%d, %d, %d), doesn't match source vol (%d, %d, %d)",
	      Progname, gcam->width, gcam->height, gcam->depth,
	      mri_source->width, mri_source->height, mri_source->depth) ;
	
  mp.mri_diag = mri_source ;
  mp.diag_morph_from_atlas = 0 ;
  mp.diag_write_snapshots = 1 ;
  mp.diag_sample_type = use_aseg ? SAMPLE_NEAREST : SAMPLE_TRILINEAR ;
  mp.diag_volume = use_aseg ? GCAM_LABEL : GCAM_MEANS ;

  if (renormalize)
    GCAMnormalizeIntensities(gcam, mri_target) ;
  if (mp.write_iterations != 0)
    {
      char fname[STRLEN] ;
      MRI  *mri_gca ;
		
      if (getenv("DONT_COMPRESS"))
        sprintf(fname, "%s_target.mgh", mp.base_name) ;
      else
        sprintf(fname, "%s_target.mgz", mp.base_name) ;
      if (mp.diag_morph_from_atlas == 0)
      {
        printf("writing target volume to %s...\n", fname) ;
        MRIwrite(mri_target, fname) ;
        sprintf(fname, "%s_target", mp.base_name) ;
        MRIwriteImageViews(mri_target, fname, IMAGE_SIZE) ;
      }
      else
      {
        if (use_aseg)
          mri_gca = GCAMwriteMRI(gcam, NULL, GCAM_LABEL) ;
        else
        {
          mri_gca = MRIclone(mri_source, NULL) ;
          GCAMbuildMostLikelyVolume(gcam, mri_gca) ;
        }
	  printf("writing target volume to %s...\n", fname) ;
	  MRIwrite(mri_gca, fname) ;
	  sprintf(fname, "%s_target", mp.base_name) ;
	  MRIwriteImageViews(mri_gca, fname, IMAGE_SIZE) ;
	  MRIfree(&mri_gca) ;
	}
    }

  if (nozero)
    {
      printf("disabling zero nodes\n") ;
      GCAMignoreZero(gcam, mri_target) ;
    }
  mp.mri = mri_target ;
  if (mp.regrid == True && new_transform == 0)
    GCAMregrid(gcam, mri_target, PAD, &mp, &mri_source) ;

  mp.write_fname = out_fname ;
  GCAMregister(gcam, mri_source, &mp) ; // atlas is target, morph target into register with it
  if (apply_transform)
    {
      MRI *mri_aligned ;
      char   fname[STRLEN] ;
		
      FileNameRemoveExtension(out_fname, fname) ;
      strcat(fname, ".mgz") ;
      mri_aligned = GCAMmorphToAtlas(mp.mri, gcam, NULL, -1, mp.diag_sample_type) ;
      printf("writing transformed output volume to %s...\n", fname) ;
      MRIwrite(mri_aligned, fname) ;
      MRIfree(&mri_aligned) ;
    }
  printf("writing warp vector field to %s\n", out_fname) ;
  GCAMvoxToRas(gcam) ;
  GCAMwrite(gcam, out_fname) ;
  GCAMrasToVox(gcam, mri_source) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("registration took %d minutes and %d seconds.\n", 
	 minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Пример #11
0
// returns the mask if necessary
MRI*
CopyGcamToDeltaField(GCA_MORPH* gcam, MRI* field)
{
  if ( !field ) throw std::string(" Field not set in CopyGcamToDeltaField\n");

  // allocate the mask
  MRI* mask = MRIalloc( field->width,
                        field->height,
                        field->depth,
                        MRI_UCHAR );
  unsigned int maskCounter = 0;
  unsigned char ucOne(1);//, ucZero(0);
  // fill the mask with true values to start with

  for (int z=0; z<field->depth; ++z)
    for (int y=0; y<field->height; ++y)
      for (int x=0; x<field->width; ++x)
        MRIvox(mask, x,y,z) = ucOne;


  GMN* pnode = NULL;

  // currently bug in transform.c - names are swapped
  //MATRIX* v2r_atlas = VGgetVoxelToRasXform( &gcam->atlas, NULL, 0);
  //MATRIX* r2v_image = VGgetRasToVoxelXform( &gcam->image, NULL, 0);
  MATRIX* v2r_atlas = VGgetRasToVoxelXform( &gcam->atlas, NULL, 0);
  //MATRIX* r2v_image = VGgetVoxelToRasXform( &gcam->image, NULL, 0);
  MATRIX* r2v_image = extract_r_to_i( field );
  MATRIX* transform = MatrixMultiply( r2v_image, v2r_atlas, NULL);

  std::cout << " vox 2 ras atlas = \n";
  MatrixPrint( stdout, v2r_atlas );
  std::cout << " ras 2 vox image = \n";
  MatrixPrint( stdout, r2v_image );
  std::cout << " product = \n";
  MatrixPrint( stdout, transform);
  std::cout << std::endl;

  // using the above matrix, go through the nodes of the GCAM
  // and associate the delta to the transformed node
  //
  // !!!! The strong underlying assumption is that the IMAGE and ATLAS associated
  // with the GCAM share the same RAS
  //
  VECTOR *vx = VectorAlloc(4, MATRIX_REAL);
  VECTOR_ELT(vx, 4) = 1.0;
  VECTOR_ELT(vx, 1) = 0.0;
  VECTOR_ELT(vx, 2) = 0.0;
  VECTOR_ELT(vx, 3) = 0.0;

  VECTOR *vfx= VectorAlloc(4, MATRIX_REAL);

  MatrixMultiply(transform, vx, vfx);
  std::cout << " transform at origin\n";
  MatrixPrint(stdout, vfx);

  int shift_x, shift_y, shift_z;

  shift_x = myNint( VECTOR_ELT(vfx, 1) );
  shift_y = myNint( VECTOR_ELT(vfx, 2) );
  shift_z = myNint( VECTOR_ELT(vfx, 3) );

  unsigned int invalidCount = 0;
  int img_x, img_y, img_z;
  for ( int z=0, maxZ=gcam->depth; z<maxZ; ++z)
    for ( int y=0, maxY=gcam->height; y<maxY; ++y)
      for ( int x=0, maxX=gcam->width; x<maxX; ++x)
      {
#if 0
        // indexing is 1-based - NR
        VECTOR_ELT(vx, 1) = x;
        VECTOR_ELT(vx, 2) = y;
        VECTOR_ELT(vx, 3) = z;

        MatrixMultiply(transform, vx, vfx);

        img_x = myNint( VECTOR_ELT(vfx, 1) );
        img_y = myNint( VECTOR_ELT(vfx, 2) );
        img_z = myNint( VECTOR_ELT(vfx, 3) );
#endif

        img_x = x + shift_x;
        img_y = y + shift_y;
        img_z = z + shift_z;

        if ( img_x < 0 || img_x > field->width-1 ||
             img_y < 0 || img_y > field->height-1 ||
             img_z < 0 || img_z > field->depth-1 )
        {
          maskCounter++;
          continue;
        }
        pnode = &gcam->nodes[x][y][z];

        //if (pnode->invalid) continue;
        if ( pnode->invalid == GCAM_POSITION_INVALID )
        {
          ++invalidCount;
          continue;
        }

#if 0
        if ( img_x == g_vDbgCoords[0] &&
             img_y == g_vDbgCoords[1] &&
             img_z == g_vDbgCoords[2] )
        {
          std::cout << " node " << img_x
          << " , " << img_y
          << " , " << img_z
          << " comes from "
          << x << " , " << y << " , " << z
          << " -> " << pnode->x
          << " , " << pnode->y
          << " , " << pnode->z << std::endl;
        }
#endif

        MRIsetVoxVal(mask, img_x, img_y, img_z, 0, ucOne );

        MRIsetVoxVal( field, img_x, img_y, img_z, 0,
                      pnode->x - img_x );
        MRIsetVoxVal( field, img_x, img_y, img_z, 1,
                      pnode->y - img_y );
        MRIsetVoxVal( field, img_x, img_y, img_z, 2,
                      pnode->z - img_z );

      }
  std::cout << " invalid voxel count = " << invalidCount << std::endl;
  if ( !g_vDbgCoords.empty() )
  {
    int x,y,z;

    pnode = &gcam->nodes[gcam->width/2][gcam->height/2][gcam->depth/2];

    for (unsigned int ui=0; ui<3; ++ui)
      VECTOR_ELT(vx, ui+1) = g_vDbgCoords[ui];

    MATRIX* minv = MatrixInverse(transform, NULL);
    MatrixMultiply(minv, vx, vfx);

    std::cout << " debugging at coords = \n";
    std::copy( g_vDbgCoords.begin(), g_vDbgCoords.end(),
               std::ostream_iterator<int>( std::cout, " ") );
    std::cout << std::endl;

    x = myNint( VECTOR_ELT( vfx, 1) );
    y = myNint( VECTOR_ELT( vfx, 2) );
    z = myNint( VECTOR_ELT( vfx, 3) );

    std::cout << " linear transf to get gcam xyz = "
    << x << " , " << y << " , " << z << std::endl;
    if ( x < 0 || x > gcam->width -1 ||
         y < 0 || y > gcam->height-1 ||
         z < 0 || z > gcam->depth -1 )
      std::cout << " out of bounds\n";
    else
    {
      pnode = &gcam->nodes[x][y][z];
      std::cout << " value of gcam = "
      << pnode->x << " , "
      << pnode->y << " , "
      << pnode->z << std::endl;
    }
  }


//   for( int z(0), maxZ(field->depth); z<maxZ; ++z)
//     for( int y(0), maxY(field->height); y<maxY; ++y)
//       for( int x(0), maxX(field->width); x<maxX; ++x)
//  {

//    if ( !GCAMsampleMorph(gcam, x,y,z,
//     &pxd, &pyd, &pzd) )
//      {
//        MRIvox(mask, x,y,z) = ucZero;
//        maskCounter++;
//        continue;
//      }
//    MRIsetVoxVal( field, x,y,z, 0,
//    pxd - x );
//    MRIsetVoxVal( field, x,y,z, 1,
//    pyd - y );
//    MRIsetVoxVal( field, x,y,z, 2,
//    pzd - z );

//  } // next x,y,z

  if ( !maskCounter )
  {
    MRIfree(&mask);
    return NULL;
  }
  return mask;
}
Пример #12
0
int
main(int argc, char *argv[]) {
  char   **av, *cp ;
  int    ac, nargs, i, dof, no_transform, which, sno = 0, nsubjects = 0 ;
  MRI    *mri=0, *mri_mean = NULL, *mri_std=0, *mri_T1=0,*mri_binary=0,*mri_dof=NULL,
                             *mri_priors = NULL ;
  char   *subject_name, *out_fname, fname[STRLEN] ;
  /*  LTA    *lta;*/
  MRI *mri_tmp=0 ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_make_template.c,v 1.26 2011/03/02 00:04:22 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (!strlen(subjects_dir)) {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,"%s: SUBJECTS_DIR not defined in environment.\n",
                Progname) ;
    strcpy(subjects_dir, cp) ;
  }

  if (argc < 3)  usage_exit(1) ;

  out_fname = argv[argc-1] ;

  no_transform = first_transform ;
  if (binary_name)   /* generate binarized volume with priors and */
  {                  /* separate means and variances */
    for (which = BUILD_PRIORS ; which <= OFF_STATS ; which++) {
      /* for each subject specified on cmd line */
      for (dof = 0, i = 1 ; i < argc-1 ; i++) {
        if (*argv[i] == '-')   /* don't do transform for next subject */
        { no_transform = 1 ;
          continue ;
        }
        dof++ ;
        subject_name = argv[i] ;
        if (which != BUILD_PRIORS) {
          sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name);
          fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ;
          mri_T1 = MRIread(fname) ;
          if (!mri_T1)
            ErrorExit(ERROR_NOFILE,"%s: could not open volume %s",
                      Progname,fname);
        }

        sprintf(fname, "%s/%s/mri/%s",subjects_dir,subject_name,binary_name);
        fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ;
        mri_binary = MRIread(fname) ;
        if (!mri_binary)
          ErrorExit(ERROR_NOFILE,"%s: could not open volume %s",
                    Progname,fname);

        /* only count voxels which are mostly labeled */
        MRIbinarize(mri_binary, mri_binary, WM_MIN_VAL, 0, 100) ;
        if (transform_fname && no_transform-- <= 0) {
          sprintf(fname, "%s/%s/mri/transforms/%s",
                  subjects_dir, subject_name, transform_fname) ;

          fprintf(stderr, "reading transform %s...\n", fname) ;
          ////////////////////////////////////////////////////////
#if 1
          {
            TRANSFORM *transform ;
            transform = TransformRead(fname) ;
            if (transform == NULL)
              ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n",Progname, fname) ;
            mri_tmp = TransformApply(transform, mri_T1, NULL) ;
            TransformFree(&transform) ;
          }
#else
          lta = LTAreadEx(fname);
          if (lta == NULL)
            ErrorExit(ERROR_NOFILE,
                      "%s: could not open transform file %s\n",
                      Progname, fname) ;
          /* LTAtransform() runs either MRIapplyRASlinearTransform()
          for RAS2RAS or MRIlinearTransform() for Vox2Vox. */
          /* MRIlinearTransform() calls MRIlinearTransformInterp() */
          mri_tmp = LTAtransform(mri_T1, NULL, lta);
          MRIfree(&mri_T1) ;
          mri_T1 = mri_tmp ;
          LTAfree(&lta);
          lta = NULL;
#endif
          if (DIAG_VERBOSE_ON)
            fprintf(stderr, "transform application complete.\n") ;
        }
        if (which == BUILD_PRIORS) {
          mri_priors =
            MRIupdatePriors(mri_binary, mri_priors) ;
        } else {
          if (!mri_mean) {
            mri_dof = MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth,
                               MRI_UCHAR) ;
            mri_mean =
              MRIalloc(mri_T1->width, mri_T1->height,mri_T1->depth,MRI_FLOAT);
            mri_std =
              MRIalloc(mri_T1->width,mri_T1->height,mri_T1->depth,MRI_FLOAT);
            if (!mri_mean || !mri_std)
              ErrorExit(ERROR_NOMEMORY, "%s: could not allocate templates.\n",
                        Progname) ;
          }

          if (DIAG_VERBOSE_ON)
            fprintf(stderr, "updating mean and variance estimates...\n") ;
          if (which == ON_STATS) {
            MRIaccumulateMaskedMeansAndVariances(mri_T1, mri_binary, mri_dof,
                                                 90, 100, mri_mean, mri_std) ;
            fprintf(stderr, "T1 = %d, binary = %d, mean = %2.1f\n",
                    (int)MRIgetVoxVal(mri_T1, 141,100,127,0),
                    MRIvox(mri_binary, 141,100,127),
                    MRIFvox(mri_mean, 141,100,127)) ;
          } else  /* computing means and vars for off */
            MRIaccumulateMaskedMeansAndVariances(mri_T1, mri_binary, mri_dof,
                                                 0, WM_MIN_VAL-1,
                                                 mri_mean, mri_std) ;
          MRIfree(&mri_T1) ;
        }
        MRIfree(&mri_binary) ;
      }

      if (which == BUILD_PRIORS) {
        mri = MRIcomputePriors(mri_priors, dof, NULL) ;
        MRIfree(&mri_priors) ;
        fprintf(stderr, "writing priors to %s...\n", out_fname) ;
      } else {
        MRIcomputeMaskedMeansAndStds(mri_mean, mri_std, mri_dof) ;
        mri_mean->dof = dof ;

        fprintf(stderr, "writing T1 means with %d dof to %s...\n", mri_mean->dof,
                out_fname) ;
        if (!which)
          MRIwrite(mri_mean, out_fname) ;
        else
          MRIappend(mri_mean, out_fname) ;
        MRIfree(&mri_mean) ;
        fprintf(stderr, "writing T1 variances to %s...\n", out_fname);
        if (dof <= 1)
          MRIreplaceValues(mri_std, mri_std, 0, 1) ;
        mri = mri_std ;
      }

      if (!which)
        MRIwrite(mri, out_fname) ;
      else
        MRIappend(mri, out_fname) ;
      MRIfree(&mri) ;
    }
  }
  else {
    /* for each subject specified on cmd line */

    if (xform_mean_fname) {
      m_xform_mean = MatrixAlloc(4,4,MATRIX_REAL) ;
      /* m_xform_covariance = MatrixAlloc(12,12,MATRIX_REAL) ;*/
    }

    dof = 0;
    for (i = 1 ; i < argc-1 ; i++) {

      if (*argv[i] == '-') {
        /* don't do transform for next subject */
        no_transform = 1 ;
        continue ;
      }
      dof++ ;

      subject_name = argv[i] ;
      sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name);
      fprintf(stderr, "%d of %d: reading %s...\n", i, argc-2, fname) ;
      mri_T1 = MRIread(fname) ;
      if (!mri_T1)
        ErrorExit(ERROR_NOFILE,"%s: could not open volume %s",Progname,fname);
      check_mri(mri_T1) ;

      if (binarize)
        MRIbinarize(mri_T1, mri_T1, binarize, 0, 1) ;
      if (erode) {
        int i ;
        printf("eroding input %d times\n", erode) ;
        for (i = 0 ; i < erode ; i++)
          MRIerode(mri_T1, mri_T1) ;
      }
      if (open) {
        int i ;
        printf("opening input %d times\n", open) ;
        for (i = 0 ; i < open ; i++)
          MRIerode(mri_T1, mri_T1) ;
        for (i = 0 ; i < open ; i++)
          MRIdilate(mri_T1, mri_T1) ;
      }

      check_mri(mri_T1) ;
      if (transform_fname) {

        sprintf(fname, "%s/%s/mri/transforms/%s",
                subjects_dir, subject_name, transform_fname) ;

        fprintf(stderr, "reading transform %s...\n", fname) ;
        ////////////////////////////////////////////////////////
#if 1
        {
          TRANSFORM *transform ;
          transform = TransformRead(fname) ;
          if (transform == NULL)
            ErrorExit(ERROR_NOFILE, "%s: could not open transform file %s\n",Progname, fname) ;
          mri_tmp = TransformApply(transform, mri_T1, NULL) ;
          if (DIAG_VERBOSE_ON)
            MRIwrite(mri_tmp, "t1.mgz") ;
          TransformFree(&transform) ;
        }
#else
        lta = LTAreadEx(fname);
        if (lta == NULL)
          ErrorExit(ERROR_NOFILE,
                    "%s: could not open transform file %s\n",
                    Progname, fname) ;
        printf("transform matrix -----------------------\n");
        MatrixPrint(stdout,lta->xforms[0].m_L);
        /* LTAtransform() runs either MRIapplyRASlinearTransform()
        for RAS2RAS or MRIlinearTransform() for Vox2Vox. */
        /* MRIlinearTransform() calls MRIlinearTransformInterp() */
        mri_tmp = LTAtransform(mri_T1, NULL, lta);
        printf("----- -----------------------\n");
        LTAfree(&lta);
#endif
        MRIfree(&mri_T1);
        mri_T1 = mri_tmp ; // reassign pointers
        if (DIAG_VERBOSE_ON)
          fprintf(stderr, "transform application complete.\n") ;
      }

      if (!mri_mean) {
        mri_mean =
          MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_FLOAT) ;
        mri_std =
          MRIalloc(mri_T1->width, mri_T1->height, mri_T1->depth, MRI_FLOAT) ;
        if (!mri_mean || !mri_std)
          ErrorExit(ERROR_NOMEMORY, "%s: could not allocate templates.\n",
                    Progname) ;
        // if(transform_fname == NULL){
        if (DIAG_VERBOSE_ON)
          printf("Copying geometry\n");
        MRIcopyHeader(mri_T1,mri_mean);
        MRIcopyHeader(mri_T1,mri_std);
        // }
      }

      check_mri(mri_mean) ;
      if (!stats_only) {
        if (DIAG_VERBOSE_ON)
          fprintf(stderr, "updating mean and variance estimates...\n") ;
        MRIaccumulateMeansAndVariances(mri_T1, mri_mean, mri_std) ;
      }

      check_mri(mri_mean) ;
      if (DIAG_VERBOSE_ON)
        MRIwrite(mri_mean, "t2.mgz") ;
      MRIfree(&mri_T1) ;
      no_transform = 0;
    } /* end loop over subjects */

    if (xform_mean_fname) {
      FILE   *fp ;
      VECTOR *v = NULL, *vT = NULL ;
      MATRIX *m_vvT = NULL ;
      int    rows, cols ;

      nsubjects = sno ;

      fp = fopen(xform_covariance_fname, "w") ;
      if (!fp)
        ErrorExit(ERROR_NOFILE, "%s: could not open covariance file %s",
                  Progname, xform_covariance_fname) ;
      fprintf(fp, "nsubjects=%d\n", nsubjects) ;

      MatrixScalarMul(m_xform_mean, 1.0/(double)nsubjects, m_xform_mean) ;
      printf("means:\n") ;
      MatrixPrint(stdout, m_xform_mean) ;
      MatrixAsciiWrite(xform_mean_fname, m_xform_mean) ;

      /* subtract the mean from each transform */
      rows = m_xform_mean->rows ;
      cols = m_xform_mean->cols ;
      for (sno = 0 ; sno < nsubjects ; sno++) {
        MatrixSubtract(m_xforms[sno], m_xform_mean, m_xforms[sno]) ;
        v = MatrixReshape(m_xforms[sno], v, rows*cols, 1) ;
        vT = MatrixTranspose(v, vT) ;
        m_vvT = MatrixMultiply(v, vT, m_vvT) ;
        if (!m_xform_covariance)
          m_xform_covariance =
            MatrixAlloc(m_vvT->rows, m_vvT->cols,MATRIX_REAL) ;
        MatrixAdd(m_vvT, m_xform_covariance, m_xform_covariance) ;
        MatrixAsciiWriteInto(fp, m_xforms[sno]) ;
      }

      MatrixScalarMul(m_xform_covariance, 1.0/(double)nsubjects,
                      m_xform_covariance) ;
      printf("covariance:\n") ;
      MatrixPrint(stdout, m_xform_covariance) ;
      MatrixAsciiWriteInto(fp, m_xform_covariance) ;
      fclose(fp) ;
      if (stats_only)
        exit(0) ;
    }

    MRIcomputeMeansAndStds(mri_mean, mri_std, dof) ;
    check_mri(mri_mean) ;
    check_mri(mri_std) ;

    mri_mean->dof = dof ;

    if (smooth) {
      MRI *mri_kernel, *mri_smooth ;

      printf("applying smoothing kernel\n") ;
      mri_kernel = MRIgaussian1d(smooth, 100) ;
      mri_smooth = MRIconvolveGaussian(mri_mean, NULL, mri_kernel) ;
      MRIfree(&mri_kernel) ;
      MRIfree(&mri_mean) ;
      mri_mean = mri_smooth ;
    }
    fprintf(stderr, "\nwriting T1 means with %d dof to %s...\n", mri_mean->dof,
            out_fname) ;
    MRIwrite(mri_mean, out_fname) ;
    MRIfree(&mri_mean) ;
    if (dof <= 1) /* can't calculate variances - set them to reasonable val */
    {
      //               src      dst
      MRIreplaceValues(mri_std, mri_std, 0, 1) ;
    }
    if (!novar) {
      // mri_std contains the variance here  (does it?? I don't think so -- BRF)
      if (!var_fname) {
        fprintf(stderr, "\nwriting T1 standard deviations to %s...\n", out_fname);
        MRIappend(mri_std, out_fname) ;
      } else {
        fprintf(stderr, "\nwriting T1 standard deviations to %s...\n", var_fname);
        MRIwrite(mri_std, var_fname) ;
      }
    }
    MRIfree(&mri_std) ;
    if (mri)
      MRIfree(&mri);
  } /* end if binarize */
  return(0) ;
}
Пример #13
0
// modify transform to vox-to-vox
static void modify_transform(TRANSFORM *transform, MRI *mri_inputs, GCA *gca) {
    LTA *lta=0;
    MATRIX *i_to_r=0, *r_to_i=0, *tmpmat=0, *vox2vox;
    MRI *mri_buf = 0;
    GCA_MORPH *gcam = 0;
    static int warned = 0;

    // temp buf to get the transform
    mri_buf = MRIallocHeader(mri_inputs->width,
                             mri_inputs->height,
                             mri_inputs->depth,
                             mri_inputs->type,1);
    MRIcopyHeader(mri_inputs, mri_buf);

    //////////////////////////////////////////////////////////////////////////
    // non-linear transform case
    //////////////////////////////////////////////////////////////////////////
    if (transform->type == MORPH_3D_TYPE) {
        gcam = (GCA_MORPH *) transform->xform;
        if (gcam->atlas.valid) // means it contains the dst volume information
        {
            mri_buf->c_r = gcam->atlas.c_r;
            mri_buf->c_a = gcam->atlas.c_a;
            mri_buf->c_s = gcam->atlas.c_s;
            if (warned == 0) {
                if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
                    fprintf
                    (stderr,
                     "INFO: modified c_(r,a,s) using the non-linear "
                     "transform dst value.\n");
                warned = 1;
            }
        }
        else // this is an old 3d, I should use c_(ras) = 0
        {
            mri_buf->c_r = 0;
            mri_buf->c_a = 0;
            mri_buf->c_s = 0;
            if (warned == 0) {
                if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
                    fprintf(stderr, "INFO: modified c_(r,a,s) = 0.\n");
                warned = 1;
            }
        }
    }
    ////////////////////////////////////////////////////////////////////////////
    /// linear transform case
    ////////////////////////////////////////////////////////////////////////////
    else if (transform->type == LINEAR_VOX_TO_VOX) {
        lta = (LTA *) (transform->xform);
        // modify using the xform dst
        if (lta->xforms[0].dst.valid) {
            mri_buf->c_r = lta->xforms[0].dst.c_r;
            mri_buf->c_a = lta->xforms[0].dst.c_a;
            mri_buf->c_s = lta->xforms[0].dst.c_s;
            if (warned == 0) {
                if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
                    fprintf(stderr, "INFO: modified c_(r,a,s) using the xform dst.\n");
                warned = 1;
            }
        } else // keep the old behavior
        {
            mri_buf->c_r = 0;
            mri_buf->c_a = 0;
            mri_buf->c_s = 0;
            if (warned == 0) {
                if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
                    fprintf(stderr, "INFO: modified c_(r,a,s) = 0.\n");
                warned = 1;
            }
        }
    } else if (transform->type == LINEAR_RAS_TO_RAS) {
        lta = (LTA *) (transform->xform);
        // modify using the xform dst
        if (lta->xforms[0].dst.valid) {
            mri_buf->c_r = lta->xforms[0].dst.c_r;
            mri_buf->c_a = lta->xforms[0].dst.c_a;
            mri_buf->c_s = lta->xforms[0].dst.c_s;
            if (warned == 0) {
                if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
                    fprintf(stderr, "INFO: modified c_(r,a,s) using the xform dst\n");
                warned = 1;
            }
        }
        // dst invalid
        else if (getenv("USE_AVERAGE305"))// use average_305 value
            // (usually ras-to-ras comes from MNI transform)
        {
            mri_buf->c_r = -0.095;
            mri_buf->c_a = -16.51;
            mri_buf->c_s =   9.75;
            if (warned == 0) {
                if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) {
                    fprintf
                    (stderr,
                     "INFO: modified c_(r,a,s) using average_305 value\n");
                    fprintf
                    (stderr,
                     "INFO: if this is not preferred, set environment "
                     "variable NO_AVERAGE305\n");
                }
                warned = 1;
            }
        }
        else // keep old behavior
        {
            mri_buf->c_r = 0;
            mri_buf->c_a = 0;
            mri_buf->c_s = 0;
            if (warned == 0) {
                if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
                    fprintf
                    (stderr, "INFO: xform.dst invalid thus modified c_(r,a,s) = 0.\n");
                warned = 1;
            }
        }
        /////////////////////////////////////////////////////////////////
        printf("INFO: original RAS-to-RAS transform\n");
        MatrixPrint(stdout, lta->xforms[0].m_L);
        // going from vox->RAS->TalRAS
        i_to_r = extract_i_to_r(mri_inputs);
        tmpmat = MatrixMultiply(lta->xforms[0].m_L, i_to_r, NULL);
        r_to_i = extract_r_to_i(mri_buf);
        // going from TalRAS -> voxel
        vox2vox = MatrixMultiply(r_to_i, tmpmat,NULL );
        printf("INFO: modified VOX-to-VOX transform\n");
        MatrixPrint(stdout, vox2vox);
        // store it
        MatrixCopy(vox2vox, lta->xforms[0].m_L);
        // now mark it as vox-to-vox
        transform->type = LINEAR_VOX_TO_VOX;
        // free up memory
        MatrixFree(&r_to_i);
        MatrixFree(&i_to_r);
        MatrixFree(&tmpmat);
        MatrixFree(&vox2vox);
    }
    /////////////////////////////////////////////////////////////////
    // OK now we know what the target c_(ras) should be
    // we reset c_(ras) value for GCA node and priors
    GCAreinit(mri_buf, gca);

    MRIfree(&mri_buf);
}
int
MRIcomputePartialVolumeFractions(MRI *mri_src, MATRIX *m_vox2vox, 
                                 MRI *mri_seg, MRI *mri_wm, MRI *mri_subcort_gm, MRI *mri_cortex,
				 MRI *mri_csf,
                                 int wm_val, int subcort_gm_val, int cortex_val, int csf_val)
{
  int    x, y, z, xs, ys, zs, label ;
  VECTOR *v1, *v2 ;
  MRI    *mri_counts ;
  float  val, count ;
  MATRIX *m_inv ;

  m_inv = MatrixInverse(m_vox2vox, NULL) ;
  if (m_inv == NULL)
  {
    MatrixPrint(stdout, m_vox2vox) ;
    ErrorExit(ERROR_BADPARM, "MRIcomputePartialVolumeFractions: non-invertible vox2vox matrix");
  }
  mri_counts = MRIcloneDifferentType(mri_src, MRI_INT) ;

  v1 = VectorAlloc(4, MATRIX_REAL) ;
  v2 = VectorAlloc(4, MATRIX_REAL) ;
  VECTOR_ELT(v1, 4) = 1.0 ; VECTOR_ELT(v2, 4) = 1.0 ;
  for (x = 0 ; x < mri_seg->width ; x++)
  {
    V3_X(v1) = x ;
    for (y = 0 ; y < mri_seg->height ; y++)
    {
      V3_Y(v1) = y ;
      for (z = 0 ; z < mri_seg->depth ; z++)
      {
        if (x == Gx && y == Gy && z == Gz)
          DiagBreak() ;
        V3_Z(v1) = z ;
        MatrixMultiply(m_vox2vox, v1, v2) ;
        xs = nint(V3_X(v2)) ; ys = nint(V3_Y(v2)) ; zs = nint(V3_Z(v2)) ;
        if (xs >= 0 && ys >= 0 && zs >= 0 &&
            xs < mri_src->width && ys < mri_src->height && zs < mri_src->depth)
        {
          val = MRIgetVoxVal(mri_counts, xs, ys, zs, 0) ;
          MRIsetVoxVal(mri_counts, xs, ys, zs, 0, val+1) ;

          label = MRIgetVoxVal(mri_seg, x, y, z, 0) ;
          if (label == csf_val)
          {
            val = MRIgetVoxVal(mri_csf, xs, ys, zs, 0) ;
            MRIsetVoxVal(mri_csf, xs, ys, zs, 0, val+1) ;
          }
          else if (label == wm_val)
          {
            val = MRIgetVoxVal(mri_wm, xs, ys, zs, 0) ;
            MRIsetVoxVal(mri_wm, xs, ys, zs, 0, val+1) ;
          }
          else if (label == subcort_gm_val)
          {
            val = MRIgetVoxVal(mri_subcort_gm, xs, ys, zs, 0) ;
            MRIsetVoxVal(mri_subcort_gm, xs, ys, zs, 0, val+1) ;
          }
          else if (label == cortex_val)
          {
            val = MRIgetVoxVal(mri_cortex, xs, ys, zs, 0) ;
            MRIsetVoxVal(mri_cortex, xs, ys, zs, 0, val+1) ;
          }
          else
            DiagBreak() ;
        }
      }
    }
  }

  for (x = 0 ; x < mri_src->width ; x++)
    for (y = 0 ; y < mri_src->height ; y++)
      for (z = 0 ; z < mri_src->depth ; z++)
      {
        count = MRIgetVoxVal(mri_counts, x, y, z, 0) ;
        if (count >= 1)
        {
          if (x == Gx && y == Gy && z == Gz)
            DiagBreak() ;
          val = MRIgetVoxVal(mri_wm, x, y, z, 0) ;
          MRIsetVoxVal(mri_wm, x, y, z, 0, val/count) ;
          val = MRIgetVoxVal(mri_subcort_gm, x, y, z, 0) ;
          MRIsetVoxVal(mri_subcort_gm, x, y, z, 0, val/count) ;
          val = MRIgetVoxVal(mri_cortex, x, y, z, 0) ;
          MRIsetVoxVal(mri_cortex, x, y, z, 0, val/count) ;
          val = MRIgetVoxVal(mri_csf, x, y, z, 0) ;
          MRIsetVoxVal(mri_csf, x, y, z, 0, val/count) ;
        }
        else  // sample in other direction
        {
          V3_X(v1) = x ; V3_Y(v1) = y ; V3_Z(v1) = z ;
          MatrixMultiply(m_inv, v1, v2) ;
          MatrixMultiply(m_inv, v1, v2) ;
          xs = nint(V3_X(v2)) ; ys = nint(V3_Y(v2)) ; zs = nint(V3_Z(v2)) ;
          if (xs >= 0 && ys >= 0 && zs >= 0 &&
              xs < mri_seg->width && ys < mri_seg->height && zs < mri_seg->depth)
          {
            label = MRIgetVoxVal(mri_seg, xs, ys, zs, 0) ;
            if (label == csf_val)
              MRIsetVoxVal(mri_csf, x, y, z, 0, 1) ;
            else if (label == wm_val)
              MRIsetVoxVal(mri_wm, x, y, z, 0, 1) ;
            else if (label == subcort_gm_val)
              MRIsetVoxVal(mri_subcort_gm, x, y, z, 0, 1) ;
            else if (cortex_val)
              MRIsetVoxVal(mri_cortex, x, y, z, 0, 1) ;
            else
              DiagBreak() ;
          }
        }
      }
  VectorFree(&v1) ; VectorFree(&v2) ; MatrixFree(&m_inv) ;
  MRIfree(&mri_counts) ;

  return(NO_ERROR) ;
}
Пример #15
0
/*--------------------------------------------------*/
int main(int argc, char **argv)
{
    int nargs, err, asegid, c, r, s, nctx, annot,vtxno,nripped;
    int annotid, IsCortex=0, IsWM=0, IsHypo=0, hemi=0, segval=0;
    int RibbonVal=0,nbrute=0;
    float dmin=0.0, lhRibbonVal=0, rhRibbonVal=0;

    /* rkt: check for and handle version tag */
    nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $");
    if (nargs && argc - nargs == 1)
    {
        exit (0);
    }
    argc -= nargs;

    Progname = argv[0] ;
    argc --;
    argv++;
    ErrorInit(NULL, NULL, NULL) ;
    DiagInit(NULL, NULL, NULL) ;

    if (argc == 0)
    {
        usage_exit();
    }

    SUBJECTS_DIR = getenv("SUBJECTS_DIR");
    if (SUBJECTS_DIR==NULL)
    {
        printf("ERROR: SUBJECTS_DIR not defined in environment\n");
        exit(1);
    }

    parse_commandline(argc, argv);
    check_options();
    dump_options(stdout);

    /* ------ Load subject's lh white surface ------ */
    sprintf(tmpstr,"%s/%s/surf/lh.white",SUBJECTS_DIR,subject);
    printf("\nReading lh white surface \n %s\n",tmpstr);
    lhwhite = MRISread(tmpstr);
    if (lhwhite == NULL)
    {
        fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
        exit(1);
    }
    /* ------ Load subject's lh pial surface ------ */
    sprintf(tmpstr,"%s/%s/surf/lh.pial",SUBJECTS_DIR,subject);
    printf("\nReading lh pial surface \n %s\n",tmpstr);
    lhpial = MRISread(tmpstr);
    if (lhpial == NULL)
    {
        fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
        exit(1);
    }
    if (lhwhite->nvertices != lhpial->nvertices)
    {
        printf("ERROR: lh white and pial have a different number of "
               "vertices (%d,%d)\n",
               lhwhite->nvertices,lhpial->nvertices);
        exit(1);
    }

    /* ------ Load lh annotation ------ */
    sprintf(annotfile,"%s/%s/label/lh.%s.annot",SUBJECTS_DIR,subject,annotname);
    printf("\nLoading lh annotations from %s\n",annotfile);
    err = MRISreadAnnotation(lhwhite, annotfile);
    if (err)
    {
        printf("ERROR: MRISreadAnnotation() failed %s\n",annotfile);
        exit(1);
    }

    /* ------ Load subject's rh white surface ------ */
    sprintf(tmpstr,"%s/%s/surf/rh.white",SUBJECTS_DIR,subject);
    printf("\nReading rh white surface \n %s\n",tmpstr);
    rhwhite = MRISread(tmpstr);
    if (rhwhite == NULL)
    {
        fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
        exit(1);
    }
    /* ------ Load subject's rh pial surface ------ */
    sprintf(tmpstr,"%s/%s/surf/rh.pial",SUBJECTS_DIR,subject);
    printf("\nReading rh pial surface \n %s\n",tmpstr);
    rhpial = MRISread(tmpstr);
    if (rhpial == NULL)
    {
        fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
        exit(1);
    }
    if (rhwhite->nvertices != rhpial->nvertices)
    {
        printf("ERROR: rh white and pial have a different "
               "number of vertices (%d,%d)\n",
               rhwhite->nvertices,rhpial->nvertices);
        exit(1);
    }

    /* ------ Load rh annotation ------ */
    sprintf(annotfile,"%s/%s/label/rh.%s.annot",SUBJECTS_DIR,subject,annotname);
    printf("\nLoading rh annotations from %s\n",annotfile);
    err = MRISreadAnnotation(rhwhite, annotfile);
    if (err)
    {
        printf("ERROR: MRISreadAnnotation() failed %s\n",annotfile);
        exit(1);
    }

    if (lhwhite->ct)
    {
        printf("Have color table for lh white annotation\n");
    }
    if (rhwhite->ct)
    {
        printf("Have color table for rh white annotation\n");
    }
    //print_annotation_table(stdout);

    if (UseRibbon)
    {
        sprintf(tmpstr,"%s/%s/mri/lh.ribbon.mgz",SUBJECTS_DIR,subject);
        printf("Loading lh ribbon mask from %s\n",tmpstr);
        lhRibbon = MRIread(tmpstr);
        if (lhRibbon == NULL)
        {
            printf("ERROR: loading %s\n",tmpstr);
            exit(1);
        }
        sprintf(tmpstr,"%s/%s/mri/rh.ribbon.mgz",SUBJECTS_DIR,subject);
        printf("Loading rh ribbon mask from %s\n",tmpstr);
        rhRibbon = MRIread(tmpstr);
        if (rhRibbon == NULL)
        {
            printf("ERROR: loading  %s\n",tmpstr);
            exit(1);
        }
    }

    if (UseNewRibbon)
    {
        sprintf(tmpstr,"%s/%s/mri/ribbon.mgz",SUBJECTS_DIR,subject);
        printf("Loading ribbon segmentation from %s\n",tmpstr);
        RibbonSeg = MRIread(tmpstr);
        if (RibbonSeg == NULL)
        {
            printf("ERROR: loading %s\n",tmpstr);
            exit(1);
        }
    }

    if (LabelHypoAsWM)
    {
        sprintf(tmpstr,"%s/%s/mri/filled.mgz",SUBJECTS_DIR,subject);
        printf("Loading filled from %s\n",tmpstr);
        filled = MRIread(tmpstr);
        if (filled == NULL)
        {
            printf("ERROR: loading filled %s\n",tmpstr);
            exit(1);
        }
    }

    // ------------ Rip -----------------------
    if (RipUnknown)
    {
        printf("Ripping vertices labeled as unkown\n");
        nripped = 0;
        for (vtxno = 0; vtxno < lhwhite->nvertices; vtxno++)
        {
            annot = lhwhite->vertices[vtxno].annotation;
            CTABfindAnnotation(lhwhite->ct, annot, &annotid);
            // Sometimes the annotation will be "none" indicated by
            // annotid = -1. We interpret this as "unknown".
            if (annotid == 0 || annotid == -1)
            {
                lhwhite->vertices[vtxno].ripflag = 1;
                lhpial->vertices[vtxno].ripflag = 1;
                nripped++;
            }
        }
        printf("Ripped %d vertices from left hemi\n",nripped);
        nripped = 0;
        for (vtxno = 0; vtxno < rhwhite->nvertices; vtxno++)
        {
            annot = rhwhite->vertices[vtxno].annotation;
            CTABfindAnnotation(rhwhite->ct, annot, &annotid);
            if (annotid == 0 || annotid == -1)
            {
                rhwhite->vertices[vtxno].ripflag = 1;
                rhpial->vertices[vtxno].ripflag = 1;
                nripped++;
            }
        }
        printf("Ripped %d vertices from right hemi\n",nripped);
    }


    printf("\n");
    printf("Building hash of lh white\n");
    lhwhite_hash = MHTfillVertexTableRes(lhwhite, NULL,CURRENT_VERTICES,hashres);
    printf("\n");
    printf("Building hash of lh pial\n");
    lhpial_hash = MHTfillVertexTableRes(lhpial, NULL,CURRENT_VERTICES,hashres);
    printf("\n");
    printf("Building hash of rh white\n");
    rhwhite_hash = MHTfillVertexTableRes(rhwhite, NULL,CURRENT_VERTICES,hashres);
    printf("\n");
    printf("Building hash of rh pial\n");
    rhpial_hash = MHTfillVertexTableRes(rhpial, NULL,CURRENT_VERTICES,hashres);

    /* ------ Load ASeg ------ */
    sprintf(tmpstr,"%s/%s/mri/aseg.mgz",SUBJECTS_DIR,subject);
    if (!fio_FileExistsReadable(tmpstr))
    {
        sprintf(tmpstr,"%s/%s/mri/aseg.mgh",SUBJECTS_DIR,subject);
        if (!fio_FileExistsReadable(tmpstr))
        {
            sprintf(tmpstr,"%s/%s/mri/aseg/COR-.info",SUBJECTS_DIR,subject);
            if (!fio_FileExistsReadable(tmpstr))
            {
                printf("ERROR: cannot find aseg\n");
                exit(1);
            }
            else
            {
                sprintf(tmpstr,"%s/%s/mri/aseg/",SUBJECTS_DIR,subject);
            }
        }
    }

    printf("\nLoading aseg from %s\n",tmpstr);
    ASeg = MRIread(tmpstr);
    if (ASeg == NULL)
    {
        printf("ERROR: loading aseg %s\n",tmpstr);
        exit(1);
    }
    mritmp = MRIchangeType(ASeg,MRI_INT,0,0,1);
    MRIfree(&ASeg);
    ASeg = mritmp;

    if (CtxSegFile)
    {
        printf("Loading Ctx Seg File %s\n",CtxSegFile);
        CtxSeg = MRIread(CtxSegFile);
        if (CtxSeg == NULL)
        {
            exit(1);
        }
    }

    AParc = MRIclone(ASeg,NULL);
    if (OutDistFile != NULL)
    {
        Dist = MRIclone(ASeg,NULL);
        mritmp = MRIchangeType(Dist,MRI_FLOAT,0,0,0);
        if (mritmp == NULL)
        {
            printf("ERROR: could change type\n");
            exit(1);
        }
        MRIfree(&Dist);
        Dist = mritmp;
    }

    Vox2RAS = MRIxfmCRS2XYZtkreg(ASeg);
    printf("ASeg Vox2RAS: -----------\n");
    MatrixPrint(stdout,Vox2RAS);
    printf("-------------------------\n");
    CRS = MatrixAlloc(4,1,MATRIX_REAL);
    CRS->rptr[4][1] = 1;
    RAS = MatrixAlloc(4,1,MATRIX_REAL);
    RAS->rptr[4][1] = 1;

    if (crsTest)
    {
        printf("Testing point %d %d %d\n",ctest,rtest,stest);
        err = FindClosestLRWPVertexNo(ctest,rtest,stest,
                                      &lhwvtx, &lhpvtx,
                                      &rhwvtx, &rhpvtx, Vox2RAS,
                                      lhwhite,  lhpial,
                                      rhwhite, rhpial,
                                      lhwhite_hash, lhpial_hash,
                                      rhwhite_hash, rhpial_hash);

        printf("Result: err = %d\n",err);
        exit(err);
    }

    printf("\nLabeling Slice\n");
    nctx = 0;
    annot = 0;
    annotid = 0;
    nbrute = 0;

    // Go through each voxel in the aseg
    for (c=0; c < ASeg->width; c++)
    {
        printf("%3d ",c);
        if (c%20 ==19)
        {
            printf("\n");
        }
        fflush(stdout);
        for (r=0; r < ASeg->height; r++)
        {
            for (s=0; s < ASeg->depth; s++)
            {

                asegid = MRIgetVoxVal(ASeg,c,r,s,0);
                if (asegid == 3 || asegid == 42)
                {
                    IsCortex = 1;
                }
                else
                {
                    IsCortex = 0;
                }
                if (asegid >= 77 && asegid <= 82)
                {
                    IsHypo = 1;
                }
                else
                {
                    IsHypo = 0;
                }
                if (asegid == 2 || asegid == 41)
                {
                    IsWM = 1;
                }
                else
                {
                    IsWM = 0;
                }
                if (IsHypo && LabelHypoAsWM && MRIgetVoxVal(filled,c,r,s,0))
                {
                    IsWM = 1;
                }

                // integrate surface information
                //
                // Only Do This for GM,WM or Unknown labels in the ASEG !!!
                //
                // priority is given to the ribbon computed from the surface
                // namely
                //  ribbon=GM => GM
                //  aseg=GM AND ribbon=WM => WM
                //  ribbon=UNKNOWN => UNKNOWN
                if (UseNewRibbon && ( IsCortex || IsWM || asegid==0 ) )
                {
                    RibbonVal = MRIgetVoxVal(RibbonSeg,c,r,s,0);
                    MRIsetVoxVal(ASeg,c,r,s,0, RibbonVal);
                    if (RibbonVal==2 || RibbonVal==41)
                    {
                        IsWM = 1;
                        IsCortex = 0;
                    }
                    else if (RibbonVal==3 || RibbonVal==42)
                    {
                        IsWM = 0;
                        IsCortex = 1;
                    }
                    if (RibbonVal==0)
                    {
                        IsWM = 0;
                        IsCortex = 0;
                    }
                }

                // If it's not labeled as cortex or wm in the aseg, skip
                if (!IsCortex && !IsWM)
                {
                    continue;
                }

                // If it's wm but not labeling wm, skip
                if (IsWM && !LabelWM)
                {
                    continue;
                }

                // Check whether this point is in the ribbon
                if (UseRibbon)
                {
                    lhRibbonVal = MRIgetVoxVal(lhRibbon,c,r,s,0);
                    rhRibbonVal = MRIgetVoxVal(rhRibbon,c,r,s,0);
                    if (IsCortex)
                    {
                        // ASeg says it's in cortex
                        if (lhRibbonVal < 0.5 && rhRibbonVal < 0.5)
                        {
                            // but it is not part of the ribbon,
                            // so set it to unknown (0) and go to the next voxel.
                            MRIsetVoxVal(ASeg,c,r,s,0,0);
                            continue;
                        }
                    }
                }

                // Convert the CRS to RAS
                CRS->rptr[1][1] = c;
                CRS->rptr[2][1] = r;
                CRS->rptr[3][1] = s;
                RAS = MatrixMultiply(Vox2RAS,CRS,RAS);
                vtx.x = RAS->rptr[1][1];
                vtx.y = RAS->rptr[2][1];
                vtx.z = RAS->rptr[3][1];

                // Get the index of the closest vertex in the
                // lh.white, lh.pial, rh.white, rh.pial
                if (UseHash)
                {
                    lhwvtx = MHTfindClosestVertexNo(lhwhite_hash,lhwhite,&vtx,&dlhw);
                    lhpvtx = MHTfindClosestVertexNo(lhpial_hash, lhpial, &vtx,&dlhp);
                    rhwvtx = MHTfindClosestVertexNo(rhwhite_hash,rhwhite,&vtx,&drhw);
                    rhpvtx = MHTfindClosestVertexNo(rhpial_hash, rhpial, &vtx,&drhp);
                    if (lhwvtx < 0 && lhpvtx < 0 && rhwvtx < 0 && rhpvtx < 0)
                    {
                        /*
                        printf("  Could not map to any surface with hash table:\n");
                        printf("  crs = %d %d %d, ras = %6.4f %6.4f %6.4f \n",
                        c,r,s,vtx.x,vtx.y,vtx.z);
                        printf("  Using brute force search %d ... \n",nbrute);
                        fflush(stdout);
                        */
                        lhwvtx = MRISfindClosestVertex(lhwhite,vtx.x,vtx.y,vtx.z,&dlhw);
                        lhpvtx = MRISfindClosestVertex(lhpial,vtx.x,vtx.y,vtx.z,&dlhp);
                        rhwvtx = MRISfindClosestVertex(rhwhite,vtx.x,vtx.y,vtx.z,&drhw);
                        rhpvtx = MRISfindClosestVertex(rhpial,vtx.x,vtx.y,vtx.z,&drhp);
                        nbrute ++;
                        //exit(1);
                    }
                }
                else
                {
                    lhwvtx = MRISfindClosestVertex(lhwhite,vtx.x,vtx.y,vtx.z,&dlhw);
                    lhpvtx = MRISfindClosestVertex(lhpial,vtx.x,vtx.y,vtx.z,&dlhp);
                    rhwvtx = MRISfindClosestVertex(rhwhite,vtx.x,vtx.y,vtx.z,&drhw);
                    rhpvtx = MRISfindClosestVertex(rhpial,vtx.x,vtx.y,vtx.z,&drhp);
                }

                if (lhwvtx < 0)
                {
                    dlhw = 1000000000000000.0;
                }
                if (lhpvtx < 0)
                {
                    dlhp = 1000000000000000.0;
                }
                if (rhwvtx < 0)
                {
                    drhw = 1000000000000000.0;
                }
                if (rhpvtx < 0)
                {
                    drhp = 1000000000000000.0;
                }

                if (dlhw <= dlhp && dlhw < drhw && dlhw < drhp && lhwvtx >= 0)
                {
                    annot = lhwhite->vertices[lhwvtx].annotation;
                    hemi = 1;
                    if (lhwhite->ct)
                    {
                        CTABfindAnnotation(lhwhite->ct, annot, &annotid);
                    }
                    else
                    {
                        annotid = annotation_to_index(annot);
                    }
                    dmin = dlhw;
                }
                if (dlhp < dlhw && dlhp < drhw && dlhp < drhp && lhpvtx >= 0)
                {
                    annot = lhwhite->vertices[lhpvtx].annotation;
                    hemi = 1;
                    if (lhwhite->ct)
                    {
                        CTABfindAnnotation(lhwhite->ct, annot, &annotid);
                    }
                    else
                    {
                        annotid = annotation_to_index(annot);
                    }
                    dmin = dlhp;
                }

                if (drhw < dlhp && drhw < dlhw && drhw <= drhp && rhwvtx >= 0)
                {
                    annot = rhwhite->vertices[rhwvtx].annotation;
                    hemi = 2;
                    if (rhwhite->ct)
                    {
                        CTABfindAnnotation(rhwhite->ct, annot, &annotid);
                    }
                    else
                    {
                        annotid = annotation_to_index(annot);
                    }
                    dmin = drhw;
                }
                if (drhp < dlhp && drhp < drhw && drhp < dlhw && rhpvtx >= 0)
                {
                    annot = rhwhite->vertices[rhpvtx].annotation;
                    hemi = 2;
                    if (rhwhite->ct)
                    {
                        CTABfindAnnotation(rhwhite->ct, annot, &annotid);
                    }
                    else
                    {
                        annotid = annotation_to_index(annot);
                    }
                    dmin = drhp;
                }

                // Sometimes the annotation will be "none" indicated by
                // annotid = -1. We interpret this as "unknown".
                if (annotid == -1)
                {
                    annotid = 0;
                }

                // why was this here in the first place?
                /*
                       if (annotid == 0 &&
                           lhwvtx >= 0 &&
                           lhpvtx >= 0 &&
                           rhwvtx >= 0 &&
                           rhpvtx >= 0) {
                         printf("%d %d %d %d\n",
                                lhwhite->vertices[lhwvtx].ripflag,
                                lhpial->vertices[lhpvtx].ripflag,
                                rhwhite->vertices[rhwvtx].ripflag,
                                rhpial->vertices[rhpvtx].ripflag);
                  } */

                if ( IsCortex && hemi == 1)
                {
                    segval = annotid+1000 + baseoffset;  //ctx-lh
                }
                if ( IsCortex && hemi == 2)
                {
                    segval = annotid+2000 + baseoffset;  //ctx-rh
                }
                if (!IsCortex && hemi == 1)
                {
                    segval = annotid+3000 + baseoffset;  // wm-lh
                }
                if (!IsCortex && hemi == 2)
                {
                    segval = annotid+4000 + baseoffset;  // wm-rh
                }

                if (!IsCortex && dmin > dmaxctx && hemi == 1)
                {
                    segval = 5001;
                }
                if (!IsCortex && dmin > dmaxctx && hemi == 2)
                {
                    segval = 5002;
                }

                // This is a hack for getting the right cortical seg with --rip-unknown
                // The aparc+aseg should be passed as CtxSeg.
                if (IsCortex && CtxSeg)
                {
                    segval = MRIgetVoxVal(CtxSeg,c,r,s,0);
                }

                MRIsetVoxVal(ASeg,c,r,s,0,segval);
                MRIsetVoxVal(AParc,c,r,s,0,annot);
                if (OutDistFile != NULL)
                {
                    MRIsetVoxVal(Dist,c,r,s,0,dmin);
                }

                if (debug || annotid == -1)
                {
                    // Gets here when there is no label at the found vertex.
                    // This is different than having a vertex labeled as "unknown"
                    if (!debug)
                    {
                        continue;
                    }
                    printf("\n");
                    printf("Found closest vertex, but it has no label.\n");
                    printf("aseg id = %d\n",asegid);
                    printf("crs = %d %d %d, ras = %6.4f %6.4f %6.4f \n",
                           c,r,s,vtx.x,vtx.y,vtx.z);
                    if (lhwvtx > 0) printf("lhw  %d  %7.5f     %6.4f  %6.4f  %6.4f\n",
                                               lhwvtx, dlhw,
                                               lhwhite->vertices[lhwvtx].x,
                                               lhwhite->vertices[lhwvtx].y,
                                               lhwhite->vertices[lhwvtx].z);
                    if (lhpvtx > 0) printf("lhp  %d  %7.5f     %6.4f  %6.4f  %6.4f\n",
                                               lhpvtx, dlhp,
                                               lhpial->vertices[lhpvtx].x,
                                               lhpial->vertices[lhpvtx].y,
                                               lhpial->vertices[lhpvtx].z);
                    if (rhwvtx > 0) printf("rhw  %d  %7.5f     %6.4f  %6.4f  %6.4f\n",
                                               rhwvtx, drhw,
                                               rhwhite->vertices[rhwvtx].x,
                                               rhwhite->vertices[rhwvtx].y,
                                               rhwhite->vertices[rhwvtx].z);
                    if (rhpvtx > 0) printf("rhp  %d  %7.5f     %6.4f  %6.4f  %6.4f\n",
                                               rhpvtx, drhp,
                                               rhpial->vertices[rhpvtx].x,
                                               rhpial->vertices[rhpvtx].y,
                                               rhpial->vertices[rhpvtx].z);
                    printf("annot = %d, annotid = %d\n",annot,annotid);
                    CTABprintASCII(lhwhite->ct,stdout);
                    continue;
                }

                nctx++;
            }
        }
    }
    printf("nctx = %d\n",nctx);
    printf("Used brute-force search on %d voxels\n",nbrute);

    if (FixParaHipWM)
    {
        /* This is a bit of a hack. There are some vertices that have been
           ripped because they are "unkown". When the above alorithm finds
           these, it searches for the closest known vertex. If this is
           less than dmax away, then the wm voxel gets labeled
           accordingly.  However, there are often some voxels near
           ventralDC that are just close enough in 3d space to parahip to
           get labeled even though they are very far away along the
           surface. These voxels end up forming an island. CCSegment()
           will eliminate any islands. Unforunately, CCSegment() uses
           6-neighbor (face) definition of connectedness, so some voxels
           may be eliminated.
         */
        printf("Fixing Parahip LH WM\n");
        CCSegment(ASeg, 3016, 5001); //3016 = lhphwm, 5001 = unsegmented WM left
        printf("Fixing Parahip RH WM\n");
        CCSegment(ASeg, 4016, 5002); //4016 = rhphwm, 5002 = unsegmented WM right
    }

    printf("Writing output aseg to %s\n",OutASegFile);
    MRIwrite(ASeg,OutASegFile);

    if (OutAParcFile != NULL)
    {
        printf("Writing output aparc to %s\n",OutAParcFile);
        MRIwrite(AParc,OutAParcFile);
    }
    if (OutDistFile != NULL)
    {
        printf("Writing output dist file to %s\n",OutDistFile);
        MRIwrite(Dist,OutDistFile);
    }


    return(0);
}
Пример #16
0
/*---------------------------------------------------------*/
int main(int argc, char **argv) {
  int n,err, f, nhits, r,c,s;
  float ipr, bpr, intensity;
  float *framepower=NULL, val;
  LTA *lta;
  int nargs;
  //int endian,roitype;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_vol2roi.c,v 1.32 2011/03/02 00:04:25 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  if (argc == 0) usage_exit();

  parse_commandline(argc, argv);
  check_options();

  printf("--------------------------------------------------------\n");
  getcwd(tmpstr,2000);
  printf("%s\n",tmpstr);
  printf("%s\n",Progname);
  for (n=0;n<argc;n++) printf(" %s",argv[n]);
  printf("\n");
  printf("version %s\n",vcid);
  printf("--------------------------------------------------------\n");

  dump_options(stdout);

  /* --------- load in the (possibly 4-D) source volume --------------*/
  printf("Loading volume %s ...",srcvolid);
  mSrcVol = MRIread(srcvolid);
  if(mSrcVol == NULL) exit(1);
  printf("done\n");

  /* Dsrc: read the source registration file */
  if (srcregfile != NULL) {
    err = regio_read_register(srcregfile, &srcsubject, &ipr, &bpr,
                              &intensity, &Dsrc, &float2int_src);
    if (err) exit(1);
    printf("srcreg Dsrc -------------\n");
    MatrixPrint(stdout,Dsrc);
    printf("----------------------------------\n");
  } else Dsrc = NULL;

  /* Wsrc: Get the source warping Transform */
  Wsrc = NULL;
  /* Fsrc: Get the source FOV registration matrix */
  Fsrc = NULL;
  /* Qsrc: Compute the quantization matrix for src volume */
  Qsrc = FOVQuantMatrix(mSrcVol->width,  mSrcVol->height,  mSrcVol->depth,
                        mSrcVol->xsize,  mSrcVol->ysize,  mSrcVol->zsize);
  printf("ras2vox src (tkreg) Qsrc -------------\n");
  MatrixPrint(stdout,Qsrc);
  printf("----------------------------------\n");

  /* ----------- load in the label ----------------- */
  if (labelfile != NULL) {
    Label = LabelReadFile(labelfile);
    if (Label == NULL) exit(1);
    /* load in the source-to-label registration */
    if (src2lblregfile != NULL) {
      //err = regio_read_xfm(src2lblregfile, &Msrc2lbl);
      //if(err) exit(1);
      lta = LTAread(src2lblregfile);
      if (lta->type == LINEAR_VOX_TO_VOX) {
        printf("INFO: converting LTA to RAS\n");
        LTAvoxelTransformToCoronalRasTransform(lta);
      }
      Msrc2lbl = MatrixCopy(lta->xforms[0].m_L,NULL);
    } else if (labeltal) {
      /* Load the talairach.xfm and make it approp for reg.dat*/
      Msrc2lbl = DevolveXFM(srcsubject,NULL,talxfm);
      if (Msrc2lbl==NULL) exit(1);
    } else Msrc2lbl = NULL;
    if (Msrc2lbl != NULL) {
      printf("-- Source2Label %s ---- \n",src2lblregfile);
      MatrixPrint(stdout,Msrc2lbl);
      printf("-------------------------------\n");
    }
  } else {
    Label = NULL;
    Msrc2lbl = NULL;
  }

  /* -------------- load mask volume stuff -----------------------------*/
  if (mskvolid != NULL) {
    /* load the mask volume (single frame) */
    printf("Reading %s\n",mskvolid);
    mMskVol = MRIread(mskvolid);
    if(mMskVol == NULL) exit(1);
    if(mskframe > 0){
      mritmp = fMRIframe(mMskVol, mskframe, NULL);
      if(mritmp == NULL) exit(1);
      MRIfree(&mMskVol);
      mMskVol = mritmp;
    }

    /* Qmsk: Compute the quantization matrix for msk volume */
    /* crsFOV = Qmsk*xyzFOV */
    Qmsk = FOVQuantMatrix(mMskVol->width, mMskVol->height, mMskVol->depth,
                          mMskVol->xsize, mMskVol->ysize,  mMskVol->zsize);

    /* get the mask2source registration information */
    /* xyzSrc = Mmsk2src * xyzMsk */
    if (msk2srcregfile != NULL) {
      err = regio_read_mincxfm(msk2srcregfile, &Mmsk2src, NULL);
      if (err) exit(1);
    } else Mmsk2src = NULL;

    /* convert from Mask Anatomical to Src FOV */
    if (!msksamesrc) {
      mSrcMskVol = vol2vol_linear(mMskVol, Qmsk, NULL, NULL, Dmsk,
                                  Qsrc, Fsrc, Wsrc, Dsrc,
                                  mSrcVol->height, mSrcVol->width, mSrcVol->depth,
                                  Mmsk2src, INTERP_NEAREST, float2int_msk);
      if (mSrcMskVol == NULL) exit(1);
    } else mSrcMskVol = mMskVol;

    /* binarize the mask volume */
    mri_binarize(mSrcMskVol, mskthresh, msktail, mskinvert,
                 mSrcMskVol, &nmskhits);
  } else {
    mSrcMskVol = NULL;
    nmskhits = 0;
  }
  /*-------------- Done loading mask stuff -------------------------*/

  /* If this is a statistical volume, raise each frame to it's appropriate
     power (eg, stddev needs to be squared)*/
  if (is_sxa_volume(srcvolid)) {
    printf("INFO: Source volume detected as selxavg format\n");
    sxa = ld_sxadat_from_stem(srcvolid);
    if (sxa == NULL) exit(1);
    framepower = sxa_framepower(sxa,&f);
    if (f != mSrcVol->nframes) {
      fprintf(stderr," number of frames is incorrect (%d,%d)\n",
              f,mSrcVol->nframes);
      exit(1);
    }
    printf("INFO: Adjusting Frame Power\n");
    fflush(stdout);
    mri_framepower(mSrcVol,framepower);
  }

  /*--------- Prepare the final mask ------------------------*/
  if (Label != NULL) {
    mFinalMskVol = label2mask_linear(mSrcVol, Qsrc, Fsrc, Wsrc,
                                     Dsrc, mSrcMskVol,
                                     Msrc2lbl, Label, labelfillthresh, float2int_src,
                                     &nlabelhits, &nfinalhits);

    if (mFinalMskVol == NULL) exit(1);
  } else {
    mFinalMskVol = mSrcMskVol;
    nfinalhits = nmskhits;
  }

  if (!oldtxtstyle) {
    /* count the number of functional voxels = 1 in the mask */
    nfinalhits = 0;
    for (r=0;r<mFinalMskVol->height;r++) {
      for (c=0;c<mFinalMskVol->width;c++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIgetVoxVal(mFinalMskVol,c,r,s,0);
          if (val > 0.5) nfinalhits ++;
        }
      }
    }
    if (Label != NULL)
      nlabelhits = CountLabelHits(mSrcVol, Qsrc, Fsrc,
                                  Wsrc, Dsrc, Msrc2lbl,
                                  Label, labelfillthresh,float2int_src);
    else  nlabelhits = 0;
  }

  /*-------------------------------------------------------*/
  /*--------- Map the volume into the ROI -----------------*/
  printf("Averging over ROI\n");
  fflush(stdout);
  mROI = vol2maskavg(mSrcVol, mFinalMskVol,&nhits);
  if (mROI == NULL) exit(1);
  printf("Done averging over ROI (nhits = %d)\n",nhits);
  /*-------------------------------------------------------*/

  /* ------- Save the final mask ------------------ */
  if (finalmskvolid != 0) {
    //mri_save_as_bvolume(mFinalMskVol,finalmskvolid,endian,BF_FLOAT);
    //MRIwriteAnyFormat(mFinalMskVol,finalmskvolid,"bfloat",-1,NULL);
    sprintf(tmpstr,"%s.%s",finalmskvolid,outext);
    MRIwrite(mFinalMskVol,tmpstr);
  }

  /* ------- Save CRS of the the final mask ------------------ */
  if (finalmskcrs != NULL) {
    fp = fopen(finalmskcrs,"w");
    if (fp==NULL) {
      fprintf(stderr,"ERROR: cannot open %s\n",finalmskcrs);
      exit(1);
    }
    for (r=0;r<mFinalMskVol->height;r++) {
      for (c=0;c<mFinalMskVol->width;c++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIgetVoxVal(mFinalMskVol,c,r,s,0);
          if (val > 0.5) {
            fprintf(fp,"%d %d %d\n",c,r,s);
          }
        }
      }
    }
    fclose(fp);
  }

  /* If this is a statistical volume, lower each frame to it's appropriate
     power (eg, variance needs to be sqrt'ed) */
  if (is_sxa_volume(srcvolid)) {
    printf("INFO: Readjusting Frame Power\n");
    fflush(stdout);
    for (f=0; f < mROI->nframes; f++) framepower[f] = 1.0/framepower[f];
    mri_framepower(mROI,framepower);
  }

  /* save the target volume in an appropriate format */
  if(roifile != NULL){
    sprintf(tmpstr,"%s.%s",roifile,outext);
    MRIwrite(mROI,tmpstr);
    /* for a stat volume, save the .dat file */
    if (is_sxa_volume(srcvolid)) {
      sxa->nrows = 1;
      sxa->ncols = 1;
      sv_sxadat_by_stem(sxa,roifile);
    }
  }

  /* save as text */
  if(roitxtfile != NULL) {
    fp = fopen(roitxtfile,"w");
    if (fp==NULL) {
      fprintf(stderr,"ERROR: cannot open %s\n",roitxtfile);
      exit(1);
    }
    if (oldtxtstyle) {
      printf("INFO: saving as old style txt\n");
      fprintf(fp,"%d \n",nmskhits);
    }
    if (! plaintxtstyle ) {
      fprintf(fp,"%d \n",nlabelhits);
      fprintf(fp,"%d \n",nfinalhits);
    }
    for (f=0; f < mROI->nframes; f++)
      fprintf(fp,"%f\n",MRIgetVoxVal(mROI,0,0,0,f));
    fclose(fp);
  }

  /* ------- Mask the source and save it  ------------------ */
  if (srcmskvolid != 0) {
    for (r=0;r<mFinalMskVol->height;r++) {
      for (c=0;c<mFinalMskVol->width;c++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIgetVoxVal(mFinalMskVol,c,r,s,0);
          if (val < 0.5) {
            for (f=0; f < mROI->nframes; f++)
              MRIFseq_vox(mSrcVol,c,r,s,f) = 0.0;
          }
        }
      }
    }
    MRIwrite(mSrcVol,srcmskvolid);
  }

  /* ------- Save as a text list  ------------------ */
  if (ListFile != 0) {
    fp = fopen(ListFile,"w");
    for (c=0;c<mFinalMskVol->width;c++) {
      for (r=0;r<mFinalMskVol->height;r++) {
        for (s=0;s<mFinalMskVol->depth;s++) {
          val = MRIFseq_vox(mFinalMskVol,c,r,s,0);
          if(val < 0.5) continue;
	  fprintf(fp,"%3d %3d %3d ",c,r,s);
	  for (f=0; f < mROI->nframes; f++){
	    val = MRIgetVoxVal(mSrcVol,c,r,s,f);
	    fprintf(fp,"%f ",val);
          }
	  fprintf(fp,"\n");
        }
      }
    }
    fclose(fp);
  }

  return(0);
}
static MATRIX *
pca_matrix(MATRIX *m_in_evectors, double in_means[3],
           MATRIX *m_ref_evectors, double ref_means[3]) {
  float   dx, dy, dz ;
  MATRIX  *mRot, *m_in_T, *mOrigin, *m_L, *m_R, *m_T, *m_tmp ;
  double  x_angle, y_angle, z_angle, r11, r21, r31, r32, r33, cosy ;
  int     row, col ;

  m_in_T = MatrixTranspose(m_in_evectors, NULL) ;
  mRot = MatrixMultiply(m_ref_evectors, m_in_T, NULL) ;

  r11 = mRot->rptr[1][1] ;
  r21 = mRot->rptr[2][1] ;
  r31 = mRot->rptr[3][1] ;
  r32 = mRot->rptr[3][2] ;
  r33 = mRot->rptr[3][3] ;
  y_angle = atan2(-r31, sqrt(r11*r11+r21*r21)) ;
  cosy = cos(y_angle) ;
  z_angle = atan2(r21 / cosy, r11 / cosy) ;
  x_angle = atan2(r32 / cosy, r33 / cosy) ;

#define MAX_ANGLE  (RADIANS(30))
  if (fabs(x_angle) > MAX_ANGLE || fabs(y_angle) > MAX_ANGLE ||
      fabs(z_angle) > MAX_ANGLE) {
    MatrixFree(&m_in_T) ;
    MatrixFree(&mRot) ;
    printf("eigenvector swap detected: ignoring PCA...\n") ;
    return(MatrixIdentity(4, NULL)) ;
  }

  mOrigin = VectorAlloc(3, MATRIX_REAL) ;
  mOrigin->rptr[1][1] = ref_means[0] ;
  mOrigin->rptr[2][1] = ref_means[1] ;
  mOrigin->rptr[3][1] = ref_means[2] ;

  printf("reference volume center of mass at (%2.1f,%2.1f,%2.1f)\n",
         ref_means[0], ref_means[1], ref_means[2]) ;
  printf("input volume center of mass at     (%2.1f,%2.1f,%2.1f)\n",
         in_means[0], in_means[1], in_means[2]) ;
  dx = ref_means[0] - in_means[0] ;
  dy = ref_means[1] - in_means[1] ;
  dz = ref_means[2] - in_means[2] ;

  printf("translating volume by %2.1f, %2.1f, %2.1f\n",
         dx, dy, dz) ;
  printf("rotating volume by (%2.2f, %2.2f, %2.2f)\n",
         DEGREES(x_angle), DEGREES(y_angle), DEGREES(z_angle)) ;

  /* build full rigid transform */
  m_R = MatrixAlloc(4,4,MATRIX_REAL) ;
  m_T = MatrixAlloc(4,4,MATRIX_REAL) ;
  for (row = 1 ; row <= 3 ; row++) {
    for (col = 1 ; col <= 3 ; col++) {
      *MATRIX_RELT(m_R,row,col) = *MATRIX_RELT(mRot, row, col) ;
    }
    *MATRIX_RELT(m_T,row,row) = 1.0 ;
  }
  *MATRIX_RELT(m_R, 4, 4) = 1.0 ;

  /* translation so that origin is at ref eigenvector origin */
  dx = -ref_means[0] ;
  dy = -ref_means[1] ;
  dz = -ref_means[2] ;
  *MATRIX_RELT(m_T, 1, 4) = dx ;
  *MATRIX_RELT(m_T, 2, 4) = dy ;
  *MATRIX_RELT(m_T, 3, 4) = dz ;
  *MATRIX_RELT(m_T, 4, 4) = 1 ;
  m_tmp = MatrixMultiply(m_R, m_T, NULL) ;
  *MATRIX_RELT(m_T, 1, 4) = -dx ;
  *MATRIX_RELT(m_T, 2, 4) = -dy ;
  *MATRIX_RELT(m_T, 3, 4) = -dz ;
  MatrixMultiply(m_T, m_tmp, m_R) ;

  /* now apply translation to take in centroid to ref centroid */
  dx = ref_means[0] - in_means[0] ;
  dy = ref_means[1] - in_means[1] ;
  dz = ref_means[2] - in_means[2] ;
  *MATRIX_RELT(m_T, 1, 4) = dx ;
  *MATRIX_RELT(m_T, 2, 4) = dy ;
  *MATRIX_RELT(m_T, 3, 4) = dz ;
  *MATRIX_RELT(m_T, 4, 4) = 1 ;

  m_L = MatrixMultiply(m_R, m_T, NULL) ;
  if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON) {
    printf("m_T:\n") ;
    MatrixPrint(stdout, m_T) ;
    printf("m_R:\n") ;
    MatrixPrint(stdout, m_R) ;
    printf("m_L:\n") ;
    MatrixPrint(stdout, m_L) ;
  }
  MatrixFree(&m_R) ;
  MatrixFree(&m_T) ;

  MatrixFree(&mRot) ;
  VectorFree(&mOrigin) ;
  return(m_L) ;
}
static MRI *
align_with_average(MRI *mri_src, MRI *mri_avg) {
  MRI     *mri_aligned, *mri_in_red, *mri_ref_red ;
  MRI     *mri_in_windowed, *mri_ref_windowed, *mri_in_tmp, *mri_ref_tmp ;
  int     i ;
  MATRIX  *m_L ;

  printf("initializing alignment using PCA...\n") ;
  if (Gdiag & DIAG_WRITE) {
    MRIwriteImageViews(mri_avg, "ref", 400) ;
    MRIwriteImageViews(mri_src, "before_pca", 400) ;
  }

  m_L = align_pca(mri_src, mri_avg) ;
  if (Gdiag & DIAG_SHOW) {
    printf("initial transform:\n") ;
    MatrixPrint(stdout, m_L) ;
  }
  if (Gdiag & DIAG_WRITE) {
    if (sinc_flag)
      mri_aligned = MRIsincTransform(mri_src, NULL, m_L,sinchalfwindow) ;
    else
      mri_aligned = MRIlinearTransform(mri_src, NULL, m_L) ;
    MRIwriteImageViews(mri_aligned, "after_pca", 400) ;
    MRIfree(&mri_aligned) ;
  }

  printf("aligning volume with average...\n") ;

  if (window_flag) {
    mri_in_windowed =
      MRIwindow(mri_src, NULL, WINDOW_HANNING,127,127,127,100.0f);
    mri_ref_windowed =
      MRIwindow(mri_avg,NULL,WINDOW_HANNING,127,127,127,100.0f);
    mri_src = mri_in_windowed ;
    mri_avg = mri_ref_windowed ;
  }

  MRIscaleMeanIntensities(mri_src, mri_avg, mri_src);

  mri_in_red = mri_in_tmp = MRIcopy(mri_src, NULL) ;
  mri_ref_red = mri_ref_tmp = MRIcopy(mri_avg, NULL) ;
  for (i = 0 ; i < nreductions ; i++) {
    mri_in_red = MRIreduceByte(mri_in_tmp, NULL) ;
    mri_ref_red = MRIreduceByte(mri_ref_tmp,NULL);
    MRIfree(&mri_in_tmp);
    MRIfree(&mri_ref_tmp) ;
    mri_in_tmp = mri_in_red ;
    mri_ref_tmp = mri_ref_red ;
  }
  parms.mri_ref = mri_avg ;
  parms.mri_in = mri_src ;  /* for diagnostics */
  MRIrigidAlign(mri_in_red, mri_ref_red, &parms, m_L) ;

  printf("transforming input volume...\n") ;
  MatrixPrint(stderr, parms.lta->xforms[0].m_L) ;
  printf("\n") ;

  if (sinc_flag)
    mri_aligned = MRIsincTransform(mri_src, NULL, parms.lta->xforms[0].m_L,sinchalfwindow) ;
  else
    mri_aligned = MRIlinearTransform(mri_src, NULL, parms.lta->xforms[0].m_L) ;
  if (Gdiag & DIAG_WRITE)
    MRIwriteImageViews(mri_aligned, "after_alignment", 400) ;
  MRIfree(&mri_in_red) ;
  MRIfree(&mri_ref_red) ;

  return(mri_aligned) ;
}
Пример #19
0
/*---------------------------------------------------------------*/
int main(int argc, char **argv) {
  char *srcsubj;
  float betplaneres, inplaneres, intensity;
  MATRIX *R, *Xsrc, *invXsrc, *Xtarg, *Rtarg;
  int float2int, err;

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  if (argc == 0) usage_exit();

  parse_commandline(argc, argv);
  check_options();
  dump_options(stdout);

  /* Load the registration matrix, fix if necessary */
  err = regio_read_register(srcregpath, &srcsubj, &inplaneres,
                            &betplaneres, &intensity, &R,
                            &float2int);
  if (err) exit(1);
  printf("---- Input registration matrix --------\n");
  MatrixPrint(stdout,R);

  if (float2int == FLT2INT_TKREG && fixtkreg) {
    if (fvolid == NULL) {
      printf("ERROR: the input registration file requires that you "
             "supply an example functional volume with --fvol\n");
      exit(1);
    }
    FuncMRI = MRIreadHeader(fvolid,MRI_VOLUME_TYPE_UNKNOWN);
    if (FuncMRI==NULL) exit(1);
    printf("INFO: making tkreg matrix compatible with round\n");
    R = MRIfixTkReg(FuncMRI,R);
    printf("---- Fixed input registration matrix --------\n");
    MatrixPrint(stdout,R);
  }
  float2int = FLT2INT_ROUND;

  /* Load the source subject xfm */
  Xsrc = DevolveXFM(srcsubj,NULL,xfmrname);
  if (Xsrc == NULL) exit(1);
  invXsrc = MatrixInverse(Xsrc,NULL);

  /* Load the target subject xfm */
  Xtarg = DevolveXFM(targsubj,NULL,xfmrname);
  if (Xtarg == NULL) exit(1);

  /* Rtarg = R*inv(Xsrc)*Xtarg */
  Rtarg = MatrixMultiply(R,invXsrc,NULL);
  Rtarg = MatrixMultiply(Rtarg,Xtarg,Rtarg);

  printf("---- New registration matrix --------\n");
  MatrixPrint(stdout,Rtarg);

  err = regio_write_register(targregpath, targsubj, inplaneres,
                             betplaneres, intensity, Rtarg, float2int);

  if (err) {
    printf("ERROR: could not write to %s\n",targregpath);
    exit(1);
  }

  return(0);
  exit(0);
}
Пример #20
0
/*--------------------------------------------------*/
int main(int argc, char **argv) {
  int nargs, err, asegid, c, r, s, annot, hemioffset;
  int annotid;
  struct utsname uts;
  char *cmdline, cwd[2000];

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $");
  if (nargs && argc - nargs == 1) exit (0);
  argc -= nargs;
  cmdline = argv2cmdline(argc,argv);
  uname(&uts);
  getcwd(cwd,2000);

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  if (argc == 0) usage_exit();

  parse_commandline(argc, argv);
  check_options();
  dump_options(stdout);

  printf("\n");
  printf("%s\n",vcid);
  printf("cwd %s\n",cwd);
  printf("cmdline %s\n",cmdline);
  printf("sysname  %s\n",uts.sysname);
  printf("hostname %s\n",uts.nodename);
  printf("machine  %s\n",uts.machine);

  SUBJECTS_DIR = getenv("SUBJECTS_DIR");
  if (SUBJECTS_DIR==NULL) {
    printf("ERROR: SUBJECTS_DIR not defined in environment\n");
    exit(1);
  }
  printf("SUBJECTS_DIR %s\n",SUBJECTS_DIR);
  printf("subject %s\n",subject);
  printf("\n");
  fflush(stdout);

  /* ------ Load subject's lh white surface ------ */
  sprintf(tmpstr,"%s/%s/surf/lh.white",SUBJECTS_DIR,subject);
  printf("Reading lh white surface \n %s\n",tmpstr);
  lhwhite = MRISread(tmpstr);
  if (lhwhite == NULL) {
    fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
    exit(1);
  }

  printf("Building hash of lh white\n");
  lhwhite_hash = MHTfillVertexTableRes(lhwhite, NULL,CURRENT_VERTICES,16);

  /* ------ Load lh annotation ------ */
  sprintf(annotfile,"%s/%s/label/lh.aparc.annot",SUBJECTS_DIR,subject);
  printf("Loading lh annotations from %s\n",annotfile);
  err = MRISreadAnnotation(lhwhite, annotfile);
  if (err) {
    printf("ERROR: MRISreadAnnotation() failed %s\n",annotfile);
    exit(1);
  }

  /* ------ Load subject's rh surface ------ */
  sprintf(tmpstr,"%s/%s/surf/rh.white",SUBJECTS_DIR,subject);
  printf("Reading rh white surface \n %s\n",tmpstr);
  rhwhite = MRISread(tmpstr);
  if (rhwhite == NULL) {
    fprintf(stderr,"ERROR: could not read %s\n",tmpstr);
    exit(1);
  }
  if (debug) printf("Building hash of rh white\n");
  rhwhite_hash = MHTfillVertexTableRes(rhwhite, NULL,CURRENT_VERTICES,16);

  /* ------ Load rh annotation ------ */
  sprintf(annotfile,"%s/%s/label/rh.aparc.annot",SUBJECTS_DIR,subject);
  printf("Loading rh annotations from %s\n",annotfile);
  err = MRISreadAnnotation(rhwhite, annotfile);
  if (err) {
    printf("ERROR: MRISreadAnnotation() failed %s\n",annotfile);
    exit(1);
  }

  if (debug && lhwhite->ct) printf("Have color table for annotation\n");
  if (debug) print_annotation_table(stdout);

  /* ------ Load ASeg ------ */
  sprintf(tmpstr,"%s/%s/mri/aseg.mgz",SUBJECTS_DIR,subject);
  if (!fio_FileExistsReadable(tmpstr)) {
    sprintf(tmpstr,"%s/%s/mri/aseg.mgh",SUBJECTS_DIR,subject);
    if (!fio_FileExistsReadable(tmpstr)) {
      sprintf(tmpstr,"%s/%s/mri/aseg/COR-.info",SUBJECTS_DIR,subject);
      if (!fio_FileExistsReadable(tmpstr)) {
        printf("ERROR: cannot find aseg\n");
        exit(1);
      } else
        sprintf(tmpstr,"%s/%s/mri/aseg/",SUBJECTS_DIR,subject);
    }
  }

  printf("Loading aseg from %s\n",tmpstr);
  ASeg = MRIread(tmpstr);
  if (ASeg == NULL) {
    printf("ERROR: loading aseg %s\n",tmpstr);
    exit(1);
  }
  mritmp = MRIchangeType(ASeg,MRI_INT,0,0,0);
  MRIfree(&ASeg);
  ASeg = mritmp;
  WMSeg = MRIclone(ASeg,NULL);

  Vox2RAS = MRIxfmCRS2XYZtkreg(ASeg);
  if (debug) {
    printf("ASeg Vox2RAS: -----------\n");
    MatrixPrint(stdout,Vox2RAS);
    printf("-------------------------\n");
  }
  CRS = MatrixAlloc(4,1,MATRIX_REAL);
  CRS->rptr[4][1] = 1;
  RAS = MatrixAlloc(4,1,MATRIX_REAL);
  RAS->rptr[4][1] = 1;

  // Go through each voxel in the aseg
  printf("\n");
  printf("Labeling WM\n");
  for (c=0; c < ASeg->width; c++) {
    if (debug) printf("%3d ",c);
    if (debug && c%20 ==19) printf("\n");
    for (r=0; r < ASeg->height; r++) {
      for (s=0; s < ASeg->depth; s++) {

        // If it's not labeled as white matter in the aseg, set
        // seg value to that from the aseg and skip the rest
        asegid = MRIgetVoxVal(ASeg,c,r,s,0);
        if (asegid != 2 && asegid != 41) {
          MRIsetVoxVal(WMSeg,c,r,s,0,asegid);
          continue;
        }

        // Convert the CRS to RAS
        CRS->rptr[1][1] = c;
        CRS->rptr[2][1] = r;
        CRS->rptr[3][1] = s;
        RAS = MatrixMultiply(Vox2RAS,CRS,RAS);
        vtx.x = RAS->rptr[1][1];
        vtx.y = RAS->rptr[2][1];
        vtx.z = RAS->rptr[3][1];

        // Get the index of the closest vertex in the
        // lh.white, rh.white
        lhwvtx = MHTfindClosestVertexNo(lhwhite_hash,lhwhite,&vtx,&dlhw);
        rhwvtx = MHTfindClosestVertexNo(rhwhite_hash,rhwhite,&vtx,&drhw);

        if ( (lhwvtx < 0) && (rhwvtx < 0) ) {
          printf("ERROR: could not map to any surface.\n");
          printf("crs = %d %d %d, ras = %6.4f %6.4f %6.4f \n",
                 c,r,s,vtx.x,vtx.y,vtx.z);
          exit(1);
        }

        if (lhwvtx < 0) dlhw = 1000000000000000.0;
        if (rhwvtx < 0) drhw = 1000000000000000.0;

        if (dlhw < drhw) {
          // Left hemi is closer than the right
          annot = lhwhite->vertices[lhwvtx].annotation;
          hemioffset = 1000;
          if (lhwhite->ct)
            CTABfindAnnotation(lhwhite->ct, annot, &annotid);
          else
            annotid = annotation_to_index(annot);
        } else {
          // Right hemi is closer than the left
          annot = rhwhite->vertices[rhwvtx].annotation;
          hemioffset = 2000;
          if (rhwhite->ct)
            CTABfindAnnotation(lhwhite->ct, annot, &annotid);
          else
            annotid = annotation_to_index(annot);
        }

        MRIsetVoxVal(WMSeg,c,r,s,0,annotid+hemioffset);
      }
    }
  }

  printf("\nWriting output wmseg to %s\n",WMSegFile);
  MRIwrite(WMSeg,WMSegFile);

  printf("mri_aparc2wmseg done\n");
  return(0);
}
int
main(int argc, char *argv[]) {
  char   **av, fname[STRLEN] ;
  int    ac, nargs ;
  char   *reg_fname, *in_fname, *out_stem, *cp ;
  int    msec, minutes, seconds, nvox, float2int ;
  struct timeb start ;
  MRI_SURFACE *mris_lh_white, *mris_rh_white, *mris_lh_pial, *mris_rh_pial ;
  MRI         *mri_aseg, *mri_seg, *mri_pial, *mri_tmp, *mri_ribbon, *mri_in, *mri_cortex, 
    *mri_subcort_gm, *mri_wm, *mri_csf ;
  MATRIX      *m_regdat ;
  float       intensity, betplaneres, inplaneres ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_compute_volume_fractions.c,v 1.9 2012/11/07 18:58:02 greve Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }
  if (argc < 4)
    usage_exit(1) ;
  if (!strlen(sdir)) {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,
                "%s: SUBJECTS_DIR not defined in environment.\n", Progname) ;
    strcpy(sdir, cp) ;
  }
  reg_fname = argv[1] ; in_fname = argv[2] ;
  out_stem = argv[3] ; Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  if (stricmp(reg_fname, "identity.nofile") == 0)
  {
    printf("using identity transform\n") ;
    m_regdat = NULL ;
    inplaneres = betplaneres = intensity = 1 ;
    float2int = 0 ;
    if (subject == NULL)
      subject = "unknown" ;
  }
  else
  {
    char *saved_subject = subject ;
    printf("reading registration file %s\n", reg_fname) ;
    regio_read_register(reg_fname, &subject, &inplaneres,
                        &betplaneres, &intensity,  &m_regdat,
                        &float2int);
    
    if (saved_subject)  // specified on cmdline
      subject = saved_subject ;
    m_regdat = regio_read_registermat(reg_fname) ;
    if (m_regdat == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not load registration file from %s", Progname,reg_fname) ;
  }
  printf("Format is %s\n",fmt);
    
  sprintf(fname, "%s/%s/surf/lh.white", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_lh_white = MRISread(fname) ;
  if (mris_lh_white == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load lh white surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/rh.white", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_rh_white = MRISread(fname) ;
  if (mris_rh_white == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load rh white surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/lh.pial", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_lh_pial = MRISread(fname) ;
  if (mris_lh_pial == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load lh pial surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/surf/rh.pial", sdir, subject) ;
  printf("reading surface %s\n", fname) ;
  mris_rh_pial = MRISread(fname) ;
  if (mris_rh_pial == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load rh pial surface from %s", Progname,fname) ;

  sprintf(fname, "%s/%s/mri/aseg.mgz", sdir, subject) ;
  printf("reading volume %s\n", fname) ;
  mri_aseg = MRIread(fname) ;
  if (mri_aseg == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load aseg volume from %s", Progname,fname) ;

  printf("reading movable volume %s\n", in_fname) ;
  mri_in = MRIread(in_fname) ;
  if (mri_in == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load input volume from %s", Progname,in_fname) ;
 
  nvox = (int)ceil(256/resolution); 
  mri_pial = MRIalloc(nvox, nvox, nvox, MRI_UCHAR) ;
  MRIsetResolution(mri_pial, resolution, resolution, resolution) ;

  mri_pial->xstart = -resolution*mri_pial->width/2.0 ;
  mri_pial->xend = resolution*mri_pial->width/2.0 ;
  mri_pial->ystart = -resolution*mri_pial->height/2.0 ;
  mri_pial->yend = resolution*mri_pial->height/2.0 ;
  mri_pial->zstart = -resolution*mri_pial->depth/2.0 ;
  mri_pial->zend = resolution*mri_pial->depth/2 ;
  mri_pial->c_r = mri_aseg->c_r ; mri_pial->c_a = mri_aseg->c_a ; mri_pial->c_s = mri_aseg->c_s ;
  MRIreInitCache(mri_pial) ; 

  printf("filling interior of lh pial surface...\n") ;
  MRISfillInterior(mris_lh_pial, resolution, mri_pial) ;
  mri_seg = MRIclone(mri_pial, NULL) ;
  mri_tmp = MRIclone(mri_pial, NULL) ;
  printf("filling interior of rh pial surface...\n") ;
  MRISfillInterior(mris_rh_pial, resolution, mri_tmp) ;
  MRIcopyLabel(mri_tmp, mri_pial, 1) ;
  MRIclear(mri_tmp) ;
  printf("filling interior of lh white matter surface...\n") ;
  MRISfillWhiteMatterInterior(mris_lh_white, mri_aseg, mri_seg, resolution,
                              WM_VAL, SUBCORT_GM_VAL, CSF_VAL);
  printf("filling interior of rh white matter surface...\n") ;
  MRISfillWhiteMatterInterior(mris_rh_white, mri_aseg, mri_tmp, resolution,
                              WM_VAL, SUBCORT_GM_VAL, CSF_VAL);
  MRIcopyLabel(mri_tmp, mri_seg, WM_VAL) ;
  MRIcopyLabel(mri_tmp, mri_seg, SUBCORT_GM_VAL) ;
  MRIcopyLabel(mri_tmp, mri_seg, CSF_VAL) ;
  MRIfree(&mri_tmp) ;
  
  mri_ribbon = MRInot(mri_seg, NULL) ;
  MRIcopyLabel(mri_seg, mri_pial, CSF_VAL) ;
  MRIreplaceValuesOnly(mri_pial, mri_pial, CSF_VAL, 0) ;
  MRIand(mri_ribbon, mri_pial, mri_ribbon, 1) ;
  MRIbinarize(mri_ribbon, mri_ribbon, 1, 0, GM_VAL) ;
  MRIcopyLabel(mri_ribbon, mri_seg, GM_VAL) ;
  MRIreplaceValuesOnly(mri_seg, mri_seg, CSF_VAL, 0) ;
  add_aseg_structures_outside_ribbon(mri_seg, mri_aseg, mri_seg, WM_VAL, SUBCORT_GM_VAL, CSF_VAL) ;


  {
    MATRIX *m_conformed_to_epi_vox2vox, *m_seg_to_conformed_vox2vox,
           *m_seg_to_epi_vox2vox ;

    if (m_regdat == NULL)    // assume identity transform
      m_seg_to_epi_vox2vox = MRIgetVoxelToVoxelXform(mri_seg, mri_in) ;
    else
    {
      m_conformed_to_epi_vox2vox = MRIvoxToVoxFromTkRegMtx(mri_in, mri_aseg, m_regdat);
      m_seg_to_conformed_vox2vox = MRIgetVoxelToVoxelXform(mri_seg, mri_aseg) ;
      
      m_seg_to_epi_vox2vox = MatrixMultiply(m_conformed_to_epi_vox2vox, m_seg_to_conformed_vox2vox, NULL) ;
      MatrixFree(&m_regdat) ; MatrixFree(&m_conformed_to_epi_vox2vox) ; 
      MatrixFree(&m_seg_to_conformed_vox2vox);

    }
    printf("seg to EPI vox2vox matrix:\n") ;
    MatrixPrint(Gstdout, m_seg_to_epi_vox2vox) ;
    mri_cortex = MRIalloc(mri_in->width, mri_in->height, mri_in->depth, MRI_FLOAT) ;
    MRIcopyHeader(mri_in, mri_cortex) ;
    mri_subcort_gm = MRIclone(mri_cortex, NULL) ;
    mri_wm = MRIclone(mri_cortex, NULL) ;
    mri_csf = MRIclone(mri_cortex, NULL) ;
    printf("computing partial volume fractions...\n") ;
    MRIcomputePartialVolumeFractions(mri_in, m_seg_to_epi_vox2vox, mri_seg, mri_wm, mri_subcort_gm, mri_cortex, mri_csf,
                                     WM_VAL, SUBCORT_GM_VAL, GM_VAL, 0) ;
  }
  
  sprintf(fname, "%s.wm.%s", out_stem,fmt) ;
  printf("writing wm %% to %s\n", fname) ;
  MRIwrite(mri_wm, fname) ;

  sprintf(fname, "%s.subcort_gm.%s", out_stem,fmt) ;
  printf("writing subcortical gm %% to %s\n", fname) ;
  MRIwrite(mri_subcort_gm, fname) ;

  sprintf(fname, "%s.cortex.%s", out_stem, fmt) ;
  printf("writing cortical gm %% to %s\n", fname) ;
  MRIwrite(mri_cortex, fname) ;
  
  sprintf(fname, "%s.csf.%s", out_stem,fmt) ;
  printf("writing csf %% to %s\n", fname) ;
  MRIwrite(mri_csf, fname) ;

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("volume fraction calculation took %d minutes"
          " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Пример #22
0
/*---------------------------------------------------------------*/
int main(int argc, char **argv) {
  int n, v, c;
  FILE *fp;
  char *covarname;
  char SumFile[2000];
  char DatFile[2000];
  char MatFile[2000];
  char OutGDFile[2000];
  int nargs;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_gdfglm.c,v 1.8.2.1 2011/05/05 15:29:51 greve Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  if (argc == 0) usage_exit();

  printf("\n\n");
  printf("%s ",Progname);
  for (n=0; n < argc; n++) printf("%s ",argv[n]);
  printf("\n\n");
  printf("%s\n\n",vcid);

  parse_commandline(argc, argv);
  check_options();
  dump_options(stdout);

  X = gdfMatrixDODS(fsgd,NULL);
  if (X==NULL) exit(1);
  if (debug) MatrixPrint(stdout,X);


  Xnorm = MatrixNormalizeCol(X,NULL,NULL);
  Xcondition = sqrt(MatrixNSConditionNumber(Xnorm));
  MatrixFree(&Xnorm);
  printf("INFO: Normalized Design Matrix Condition Number is %g\n",
         Xcondition);
  if (Xcondition > 100000) {
    printf("ERROR: Design matrix is badly conditioned, check for linear\n"
           "dependency  between columns (ie, two or more columns \n"
           "that add up to another column).\n\n");
    exit(1);
  }

  printf("Extracting DepVar\n");
  y = DVTgetDepVar(dvt,nDepVarList,DepVarList,wDepVar);

  printf("Performing Estimation\n");
  pinvX = MatrixPseudoInverse(X,NULL);
  beta = MatrixMultiply(pinvX,y,NULL);
  yhat = MatrixMultiply(X,beta,NULL);
  r = MatrixSubtract(y,yhat,NULL);
  dof = X->rows-X->cols;
  rvar = VectorVar(r, &rmean);
  rvar = rvar * (X->rows-1)/dof;

  printf("Beta: -----------------\n");
  MatrixPrint(stdout,beta);
  printf("---------------------------------\n\n");
  printf("rvar = %g, rstd = %g\n",rvar,sqrt(rvar));

  C = gdfContrastDODS(fsgd, wClass, wCovar);
  printf("C: -----------------\n");
  MatrixPrint(stdout,C);
  printf("---------------------------------\n\n");
  ces = MatrixMultiply(C,beta,NULL);
  vmf = ContrastVMF(X,C);
  tval = ces->rptr[1][1]/sqrt(rvar*vmf);
  sigtval = sigt(tval, rint(dof));
  printf("ces = %g, vmf = %g, t = %g, sigt = %g\n",
         ces->rptr[1][1],vmf,tval,sigtval);

  sprintf(SumFile,"%s.sum",OutBase);
  fp = fopen(SumFile,"w");
  fprintf(fp,"mri_gdfglm summary file\n\n");
  fprintf(fp,"Group Descriptor File %s\n",GDFile);
  fprintf(fp,"Dependent Variable File %s\n",DVTFile);
  fprintf(fp,"Dependent Variable Weights: ");
  if (wDepVar == NULL)
    fprintf(fp," all 1s\n");
  else {
    fprintf(fp,"\n");
    for (n=0; n < nwDepVar; n++)
      fprintf(fp," %s %g\n",DepVarList[n],wDepVar[n]);
  }

  fprintf(fp,"\n");
  fprintf(fp,"Class Contrast Weights: ");
  if (nwClass == 0)
    fprintf(fp," all 1s\n");
  else {
    fprintf(fp,"\n");
    for (n=0; n < nwClass; n++)
      fprintf(fp," %s %g\n",fsgd->classlabel[n],wClass[n]);
  }
  fprintf(fp,"\n");

  fprintf(fp,"Covar Contrast Weights: ");
  if (nwCovar == 0)
    if (!TestOffset) fprintf(fp," all 1s\n");
    else            fprintf(fp," all 0s\n");
  else {
    fprintf(fp,"\n");
    for (n=0; n < nwCovar; n++)
      fprintf(fp," %s %g",CovarList[n],wCovar[n]);
    fprintf(fp,"\n");
  }
  fprintf(fp,"TestOffset = %d\n",TestOffset);
  fprintf(fp,"\n");

  fprintf(fp,"Parameter Estimates and Contrast Weighting:\n\n");
  n = 0;
  for (v=0; v < fsgd->nvariables+1; v++) {
    if (v==0) covarname = "Offset";
    else     covarname = fsgd->varlabel[v-1];
    for (c=0; c < fsgd->nclasses; c++) {
      fprintf(fp,"%-10s %-10s  %12.5f   %5.2f\n",fsgd->classlabel[c],
              covarname,beta->rptr[n+1][1],C->rptr[1][n+1]);
      n++;
    }
    fprintf(fp,"\n");
  }
  fprintf(fp,"\n");

  fprintf(fp,"Residual Variance %g\n",rvar);
  fprintf(fp,"Residual StdDev   %g\n",sqrt(rvar));
  fprintf(fp,"DOF %g\n",dof);
  fprintf(fp,"\n");

  fprintf(fp,"Contrast Effect Size       %g\n",ces->rptr[1][1]);
  fprintf(fp,"Variance Reduction Factor  %g\n",1/vmf);
  fprintf(fp,"t-Ratio                    %g\n",tval);
  fprintf(fp,"Significance               %g\n",sigtval);
  fprintf(fp,"\n");
  fclose(fp);

  /*----------------------------------------*/
  sprintf(DatFile,"%s.dat",OutBase);
  fp = fopen(DatFile,"w");
  for (n=0; n < fsgd->ninputs; n++) {
    fprintf(fp,"%2d ",n);
    if (KeepSubjId) fprintf(fp,"%s",fsgd->subjid[n]);
    for (v=0; v < fsgd->nvariables; v++)
      fprintf(fp," %g",fsgd->varvals[n][v]);
    fprintf(fp," %g %g",y->rptr[n+1][1],yhat->rptr[n+1][1]);
    fprintf(fp,"\n");
  }
  fclose(fp);

  /*----------------------------------------*/
  sprintf(MatFile,"%s.mat",OutBase);
  all = MatrixHorCat(X,y,NULL);
  all = MatrixHorCat(all,yhat,NULL);
  all = MatrixHorCat(all,r,NULL);
  MatlabWrite(all,MatFile,"X");

  /*----------------------------------------*/
  sprintf(OutGDFile,"%s.gdf",OutBase);
  fp = fopen(OutGDFile,"w");
  gdfPrintHeader(fp,fsgd);
  fclose(fp);

  /*----------------------------------------*/
  WriteAllClassDat(OutBase,fsgd,y,yhat,X,beta);


  return(0);
}
Пример #23
0
void computeLDAweights(float *weights, MRI **mri_flash, MRI *mri_label, MRI *mri_mask, float *LDAmean1, float *LDAmean2, int nvolumes_total, int classID1, int classID2) {
  /* To make it consistent with later CNR computation */

  int m1, m2, x, y, z, depth, height, width;
  double denom, denom1, denom2, sumw;
  float data1, data2;
  int label;
  double Mdistance;

  MATRIX *InvSW, *SW1, *SW2;

  depth = mri_flash[0]->depth;
  width = mri_flash[0]->width;
  height = mri_flash[0]->height;

  SW1 = (MATRIX *)MatrixAlloc(nvolumes_total, nvolumes_total, MATRIX_REAL);
  SW2 = (MATRIX *)MatrixAlloc(nvolumes_total, nvolumes_total, MATRIX_REAL);

  for (m1=1; m1 <= nvolumes_total; m1++) {
    for (m2=m1; m2 <= nvolumes_total; m2++) {
      SW1->rptr[m1][m2] = 0.0; /* index starts from 1 for matrix */
      SW2->rptr[m1][m2] = 0.0; /* index starts from 1 for matrix */
    }
  }

  /* printf("SW matrix initialized \n"); */
  denom1 = 0.0;
  denom2 = 0.0;
  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++) {
        if (MRIvox(mri_mask, x, y, z) == 0) continue;

        label = (int) MRIgetVoxVal(mri_label, x, y, z,0);

        if (label != classID1 &&
            label != classID2)
          continue;

        if (label == classID1) {
          denom1 += 1.0;
          for (m1=0; m1 < nvolumes_total; m1++) {
            data1 = MRIFvox(mri_flash[m1], x, y, z) - LDAmean1[m1];
            for (m2=m1; m2 < nvolumes_total; m2++) {
              data2 = MRIFvox(mri_flash[m2], x, y, z) - LDAmean1[m2];
              SW1->rptr[m1+1][m2+1] += data1*data2;
            }
          }
        } else if (label == classID2) {
          denom2 += 1.0;
          for (m1=0; m1 < nvolumes_total; m1++) {
            data1 = MRIFvox(mri_flash[m1], x, y, z) - LDAmean2[m1];
            for (m2=m1; m2 < nvolumes_total; m2++) {
              data2 = MRIFvox(mri_flash[m2], x, y, z) - LDAmean2[m2];
              SW2->rptr[m1+1][m2+1] += data1*data2;
            }
          }
        }

      } /* for all data points */

  if (denom1 <= 0.0 || denom2 <= 0)
    ErrorExit(ERROR_BADPARM, "%s: one or two classes is empty. \n", Progname);

  if (DEBUG)
    printf("brain size = %g\n", denom);

  if (USE_ONE) {
    printf("ONLY use SW from first class\n");
    printf("Seems reducing background noise\n");
    for (m1=1; m1 <= nvolumes_total; m1++) {
      for (m2=m1; m2 <= nvolumes_total; m2++) {
        SW1->rptr[m1][m2] = SW1->rptr[m1][m2]/denom1;
        SW1->rptr[m2][m1] = SW1->rptr[m1][m2];
      }
    } /* for m1, m2 */

  } else {
    /* The following matches HBM2005 abstract's CNR definition */
    for (m1=1; m1 <= nvolumes_total; m1++) {
      for (m2=m1; m2 <= nvolumes_total; m2++) {
        SW1->rptr[m1][m2] = SW1->rptr[m1][m2]/denom1 + SW2->rptr[m1][m2]/denom2;
        SW1->rptr[m2][m1] = SW1->rptr[m1][m2];
      }
    } /* for m1, m2 */

    if (regularize) {
      printf("regularization of the covariance estimate\n");
      for (m1=1; m1 <= nvolumes_total; m1++)
        SW1->rptr[m1][m1] += eps;  /* prevent SW1 to be singular */

      /* Borrow SW2 to store its inverse */
      SW2 = MatrixInverse(SW1, SW2);
      if (SW2 == NULL) {
        printf("Inverse matrix is NULL. Exit. \n");
        exit(1);
      }

      /* (1-lambda)* inv(SW + eps I) + labmda*I */
      for (m1=1; m1 <= nvolumes_total; m1++) {
        for (m2=m1; m2 <= nvolumes_total; m2++) {
          SW2->rptr[m1][m2] = (1.0 - lambda)*SW2->rptr[m1][m2];
          SW2->rptr[m2][m1] = SW2->rptr[m1][m2];
        }
        SW2->rptr[m1][m1] += lambda;
      }

      SW1 = MatrixInverse(SW2, SW1); // this inverse is quite redundant, since it will be inverted back again later

    }
  }

  if (0) {
    printf("SW is:\n");
    MatrixPrint(stdout, SW1);
  }

#if 0
  /* The following approach is equivalent to use -regularize; i.e., regularizing is equivalent to set SW to indentity */
  /* Compute inverse of SW */
  if (just_test == 0)
    InvSW = MatrixInverse(SW1, NULL);
  else {
    InvSW = (MATRIX *)MatrixAlloc(nvolumes_total, nvolumes_total, MATRIX_REAL);
    for (m1=1; m1 <= nvolumes_total; m1++) {
      for (m2=1; m2 <= nvolumes_total; m2++) {
        InvSW->rptr[m1][m2] = 0.0; /* index starts from 1 for matrix */
      }
      InvSW->rptr[m1][m1] = 1.0;
    }
  }
#else
  /* Here, we try to ignore the covariance term */
  if (just_test) {
    for (m1=1; m1 < nvolumes_total; m1++) {
      for (m2=m1+1; m2 <= nvolumes_total; m2++) {
        SW1->rptr[m1][m2] = 0.0; /* index starts from 1 for matrix */
        SW1->rptr[m2][m1] = 0.0; /* index starts from 1 for matrix */
      }
    }
  }

  InvSW = MatrixInverse(SW1, NULL);

#endif

  if (InvSW == NULL) { /* inverse doesn't exist */
    ErrorExit(ERROR_BADPARM, "%s: singular fuzzy covariance matrix.\n", Progname);
  }


  if (0) {
    printf("Inverse SW is:\n");
    MatrixPrint(stdout, InvSW);
  }

  if (0) {
    printf("Means for class 2 is \n");
    for (m1=1; m1 <= nvolumes_total; m1++) {
      printf("%g ", LDAmean1[m1-1]);
    }
    printf("\n");
    printf("Means for class 3 is \n");
    for (m1=1; m1 <= nvolumes_total; m1++) {
      printf("%g ", LDAmean2[m1-1]);
    }
  }
  /* Compute weights */
  denom = 0.0;
  sumw = 0.0;
  if (CHOICE == 1) {
    /* Do not use invSW, assume SW is diagonal */
    printf("Ignore off-diagonal of SW\n");
    for (m1=1; m1 <= nvolumes_total; m1++) {
      weights[m1-1]= (LDAmean1[m1-1] - LDAmean2[m1-1])/(SW1->rptr[m1][m1] + 1e-15);

      sumw += weights[m1-1];
      denom += weights[m1-1]*weights[m1-1];
    }
  } else {
    for (m1=1; m1 <= nvolumes_total; m1++) {
      weights[m1-1]= 0.0;
      for (m2=1; m2 <= nvolumes_total; m2++) {
        weights[m1-1] += InvSW->rptr[m1][m2] *(LDAmean1[m2-1] - LDAmean2[m2-1]);
      }
      sumw += weights[m1-1];
      denom += weights[m1-1]*weights[m1-1];
    }
  }

  if (compute_m_distance) {
    Mdistance = 0;
    for (m1=0; m1 < nvolumes_total; m1++) {
      Mdistance += weights[m1]*(LDAmean1[m1] - LDAmean2[m1]);
    }
    printf("Mdistance = %g \n", Mdistance);
  }

  denom = sqrt(denom + 0.0000001);
  /* Normalized weights to have norm 1 */
  for (m1=1; m1 <= nvolumes_total; m1++) {
    if (sumw > 0)
      weights[m1-1] /= denom;
    else
      weights[m1-1] /= -denom;
  }

  MatrixFree(&InvSW);

  MatrixFree(&SW1);
  MatrixFree(&SW2);

  return;
}
Пример #24
0
int
main(int argc, char *argv[]) {
  TRANSFORM    *transform = NULL ;
  char         **av, fname[STRLEN], *gca_fname, *subject_name, *cp ;
  int          ac, nargs, i, n ;
  int          msec, minutes, seconds, nsubjects ;
  struct timeb start ;
  GCA          *gca ;
  MRI          *mri_parc, *mri_T1, *mri_PD ;
  FILE         *fp ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_ca_tissue_parms.c,v 1.8 2011/03/02 00:04:14 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (!strlen(subjects_dir)) /* hasn't been set on command line */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
                Progname);
    strcpy(subjects_dir, cp) ;
    if (argc < 3)
      usage_exit(1) ;
  }


  gca_fname = argv[1] ;
  nsubjects = argc-2 ;
  printf("computing average tissue parameters on %d subject\n",
         nsubjects) ;

  n = 0 ;

  printf("reading GCA from %s...\n", gca_fname) ;
  gca = GCAread(gca_fname) ;

  for (i = 0 ; i < nsubjects ; i++) {
    subject_name = argv[i+2] ;
    printf("processing subject %s, %d of %d...\n", subject_name,i+1,
           nsubjects);
    sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, parc_dir) ;
    if (DIAG_VERBOSE_ON)
      printf("reading parcellation from %s...\n", fname) ;
    mri_parc = MRIread(fname) ;
    if (!mri_parc)
      ErrorExit(ERROR_NOFILE, "%s: could not read parcellation file %s",
                Progname, fname) ;

    sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, T1_name) ;
    if (DIAG_VERBOSE_ON)
      printf("reading co-registered T1 from %s...\n", fname) ;
    mri_T1 = MRIread(fname) ;
    if (!mri_T1)
      ErrorExit(ERROR_NOFILE, "%s: could not read T1 data from file %s",
                Progname, fname) ;

    sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, PD_name) ;
    if (DIAG_VERBOSE_ON)
      printf("reading co-registered T1 from %s...\n", fname) ;
    mri_PD = MRIread(fname) ;
    if (!mri_PD)
      ErrorExit(ERROR_NOFILE, "%s: could not read PD data from file %s",
                Progname, fname) ;


    if (xform_name) {
      /*      VECTOR *v_tmp, *v_tmp2 ;*/

      sprintf(fname, "%s/%s/mri/%s", subjects_dir, subject_name, xform_name) ;
      printf("reading xform from %s...\n", fname) ;
      transform = TransformRead(fname) ;
      if (!transform)
        ErrorExit(ERROR_NOFILE, "%s: could not read xform from %s",
                  Progname, fname) ;
#if 0
      v_tmp = VectorAlloc(4,MATRIX_REAL) ;
      *MATRIX_RELT(v_tmp,4,1)=1.0 ;
      v_tmp2 = MatrixMultiply(lta->xforms[0].m_L, v_tmp, NULL) ;
      printf("RAS (0,0,0) -->\n") ;
      MatrixPrint(stdout, v_tmp2) ;
#endif

      if (transform->type == LINEAR_RAS_TO_RAS) {
        MATRIX *m_L ;
        m_L = ((LTA *)transform->xform)->xforms[0].m_L ;
        MRIrasXformToVoxelXform(mri_parc, mri_T1, m_L,m_L) ;
      }
#if 0
      v_tmp2 = MatrixMultiply(lta->xforms[0].m_L, v_tmp, v_tmp2) ;
      printf("voxel (0,0,0) -->\n") ;
      MatrixPrint(stdout, v_tmp2) ;
      VectorFree(&v_tmp) ;
      VectorFree(&v_tmp2) ;
      test(mri_parc, mri_T1, mri_PD, lta->xforms[0].m_L) ;
#endif
    }
    if (histo_parms)
      GCAhistogramTissueStatistics(gca,mri_T1,mri_PD,mri_parc,transform,histo_parms);
#if 0
    else
      GCAaccumulateTissueStatistics(gca, mri_T1, mri_PD, mri_parc, transform) ;
#endif

    MRIfree(&mri_parc) ;
    MRIfree(&mri_T1) ;
    MRIfree(&mri_PD) ;
  }
  GCAnormalizeTissueStatistics(gca) ;

  if (log_fname) {
    printf("writing tissue parameters to %s\n", log_fname) ;
    fp = fopen(log_fname, "w") ;
    for (n = 1 ; n < MAX_GCA_LABELS ; n++) {
      GCA_TISSUE_PARMS *gca_tp ;

      gca_tp = &gca->tissue_parms[n] ;
      if (gca_tp->total_training <= 0)
        continue ;
      fprintf(fp, "%d  %f  %f\n", n, gca_tp->T1_mean, gca_tp->PD_mean) ;
    }
    fclose(fp) ;
  }

  if (write_flag)
    GCAwrite(gca, gca_fname) ;
  GCAfree(&gca) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("tissue parameter statistic calculation took %d minutes"
         " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Пример #25
0
/*--------------------------------------------------*/
int main(int argc, char **argv)
{
  int nargs, nthin, nframestot=0, nr=0,nc=0,ns=0, fout;
  int r,c,s,f,outf,nframes,err,nthrep;
  double v, v1, v2, vavg, vsum;
  int inputDatatype=MRI_UCHAR;
  MATRIX *Upca=NULL,*Spca=NULL;
  MRI *Vpca=NULL;
  char *stem;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
  {
    exit (0);
  }
  argc -= nargs;

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  if (argc == 0)
  {
    usage_exit();
  }

  parse_commandline(argc, argv);
  check_options();
  dump_options(stdout);

  if(maskfile)
  {
    printf("Loading mask %s\n",maskfile);
    mask = MRIread(maskfile);
    if(mask == NULL)
    {
      exit(1);
    }
  }

  printf("ninputs = %d\n",ninputs);
  if(DoCheck)
  {
    printf("Checking inputs\n");
    for(nthin = 0; nthin < ninputs; nthin++)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Checking %2d %s\n",nthin,inlist[nthin]);
        fflush(stdout);
      }
      mritmp = MRIreadHeader(inlist[nthin],MRI_VOLUME_TYPE_UNKNOWN);
      if (mritmp == NULL)
      {
        printf("ERROR: reading %s\n",inlist[nthin]);
        exit(1);
      }
      if (nthin == 0)
      {
        nc = mritmp->width;
        nr = mritmp->height;
        ns = mritmp->depth;
      }
      if (mritmp->width != nc ||
          mritmp->height != nr ||
          mritmp->depth != ns)
      {
        printf("ERROR: dimension mismatch between %s and %s\n",
               inlist[0],inlist[nthin]);
        exit(1);
      }

      nframestot += mritmp->nframes;
      inputDatatype = mritmp->type; // used by DoKeepDatatype option
      MRIfree(&mritmp);
    }
  }
  else
  {
    printf("NOT Checking inputs, assuming nframestot = ninputs\n");
    nframestot = ninputs;
    mritmp = MRIreadHeader(inlist[0],MRI_VOLUME_TYPE_UNKNOWN);
    if (mritmp == NULL)
    {
      printf("ERROR: reading %s\n",inlist[0]);
      exit(1);
    }
    nc = mritmp->width;
    nr = mritmp->height;
    ns = mritmp->depth;
    MRIfree(&mritmp);
  }

  printf("nframestot = %d\n",nframestot);

  if (DoRMS)
  {
    if (ninputs != 1)
    {
      printf("ERROR: --rms supports only single input w/ multiple frames\n");
      exit (1);
    }
    if (nframestot == 1)
    {
      printf("ERROR: --rms input must have multiple frames\n");
      exit (1);
    }
  }

  if(ngroups != 0)
  {
    printf("Creating grouped mean matrix ngroups=%d, nper=%d\n",
           ngroups,nframestot/ngroups);
    M = GroupedMeanMatrix(ngroups,nframestot);
    if(M==NULL)
    {
      exit(1);
    }
    if(debug)
    {
      MatrixPrint(stdout,M);
    }
  }

  if(M != NULL)
  {
    if(nframestot != M->cols)
    {
      printf("ERROR: dimension mismatch between inputs (%d) and matrix (%d)\n",
             nframestot,M->rows);
      exit(1);
    }
  }

  if (DoPaired)
  {
    if (remainder(nframestot,2) != 0)
    {
      printf("ERROR: --paired-xxx specified but there are an "
             "odd number of frames\n");
      exit(1);
    }
  }

  printf("Allocing output\n");
  fflush(stdout);
  int datatype=MRI_FLOAT;
  if (DoKeepDatatype)
  {
    datatype = inputDatatype;
  }
  if (DoRMS)
  {
    // RMS always has single frame output
    mriout = MRIallocSequence(nc,nr,ns,datatype,1);
  }
  else
  {
    mriout = MRIallocSequence(nc,nr,ns,datatype,nframestot);
  }
  if (mriout == NULL)
  {
    exit(1);
  }
  printf("Done allocing\n");

  fout = 0;
  for (nthin = 0; nthin < ninputs; nthin++)
  {
    if (DoRMS) break; // MRIrms reads the input frames
    if(Gdiag_no > 0 || debug)
    {
      printf("Loading %dth input %s\n",
             nthin+1,fio_basename(inlist[nthin],NULL));
      fflush(stdout);
    }
    mritmp = MRIread(inlist[nthin]);
    if(mritmp == NULL)
    {
      printf("ERROR: loading %s\n",inlist[nthin]);
      exit(1);
    }
    if(nthin == 0)
    {
      MRIcopyHeader(mritmp, mriout);
      //mriout->nframes = nframestot;
    }
    if(DoAbs)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Removing sign from input\n");
      }
      MRIabs(mritmp,mritmp);
    }
    if(DoPos)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Setting input negatives to 0.\n");
      }
      MRIpos(mritmp,mritmp);
    }
    if(DoNeg)
    {
      if(Gdiag_no > 0 || debug)
      {
        printf("Setting input positives to 0.\n");
      }
      MRIneg(mritmp,mritmp);
    }
    for(f=0; f < mritmp->nframes; f++)
    {
      for(c=0; c < nc; c++)
      {
        for(r=0; r < nr; r++)
        {
          for(s=0; s < ns; s++)
          {
            v = MRIgetVoxVal(mritmp,c,r,s,f);
            MRIsetVoxVal(mriout,c,r,s,fout,v);
          }
        }
      }
      fout++;
    }
    MRIfree(&mritmp);
  }

  if(DoCombine)
  {
    // Average frames from non-zero voxels
    int nhits;
    mritmp = MRIallocSequence(nc,nr,ns,MRI_FLOAT,1);
    MRIcopyHeader(mritmp,mriout);
    for(c=0; c < nc; c++)
    {
      for(r=0; r < nr; r++)
      {
        for(s=0; s < ns; s++)
        {
          nhits = 0;
          vsum = 0;
          for(f=0; f < mriout->nframes; f++)
          {
            v = MRIgetVoxVal(mriout,c,r,s,f);
            if (v > 0)
            {
              vsum += v;
              nhits ++;
            }
          }
          if(nhits > 0 )
          {
            MRIsetVoxVal(mritmp,c,r,s,0,vsum/nhits);
          }
        } // for s
      }// for r
    } // for c
    MRIfree(&mriout);
    mriout = mritmp;
  } // do combine

  if(DoPrune)
  {
    // This computes the prune mask, applied below
    printf("Computing prune mask \n");
    PruneMask = MRIframeBinarize(mriout,FLT_MIN,NULL);
    printf("Found %d voxels in prune mask\n",MRInMask(PruneMask));
  }

  if(DoNormMean)
  {
    printf("Normalizing by mean across frames\n");
    MRInormalizeFramesMean(mriout);
  }
  if(DoNorm1)
  {
    printf("Normalizing by first across frames\n");
    MRInormalizeFramesFirst(mriout);
  }

  if(DoASL)
  {
    printf("Computing ASL matrix matrix\n");
    M = ASLinterpMatrix(mriout->nframes);
  }

  if(M != NULL)
  {
    printf("Multiplying by matrix\n");
    mritmp = fMRImatrixMultiply(mriout, M, NULL);
    if(mritmp == NULL)
    {
      exit(1);
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoPaired)
  {
    printf("Combining pairs\n");
    mritmp = MRIcloneBySpace(mriout,-1,mriout->nframes/2);
    for (c=0; c < nc; c++)
    {
      for (r=0; r < nr; r++)
      {
        for (s=0; s < ns; s++)
        {
          fout = 0;
          for (f=0; f < mriout->nframes; f+=2)
          {
            v1 = MRIgetVoxVal(mriout,c,r,s,f);
            v2 = MRIgetVoxVal(mriout,c,r,s,f+1);
            v = 0;
            if(DoPairedAvg)
            {
              v = (v1+v2)/2.0;
            }
            if(DoPairedSum)
            {
              v = (v1+v2);
            }
            if(DoPairedDiff)
            {
              v = v1-v2;  // difference
            }
            if(DoPairedDiffNorm)
            {
              v = v1-v2; // difference
              vavg = (v1+v2)/2.0;
              if (vavg != 0.0)
              {
                v = v/vavg;
              }
            }
            if(DoPairedDiffNorm1)
            {
              v = v1-v2; // difference
              if (v1 != 0.0)
              {
                v = v/v1;
              }
              else
              {
                v = 0;
              }
            }
            if(DoPairedDiffNorm2)
            {
              v = v1-v2; // difference
              if (v2 != 0.0)
              {
                v = v/v2;
              }
              else
              {
                v = 0;
              }
            }
            MRIsetVoxVal(mritmp,c,r,s,fout,v);
            fout++;
          }
        }
      }
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }
  nframes = mriout->nframes;
  printf("nframes = %d\n",nframes);

  if(DoBonfCor)
  {
    DoAdd = 1;
    AddVal = -log10(mriout->nframes);
  }

  if(DoMean)
  {
    printf("Computing mean across frames\n");
    mritmp = MRIframeMean(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }
  if(DoMedian)
  {
    printf("Computing median across frames\n");
    mritmp = MRIframeMedian(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }
  if(DoMeanDivN)
  {
    printf("Computing mean2 = sum/(nframes^2)\n");
    mritmp = MRIframeSum(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
    MRImultiplyConst(mriout, 1.0/(nframes*nframes), mriout);
  }
  if(DoSum)
  {
    printf("Computing sum across frames\n");
    mritmp = MRIframeSum(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }
  if(DoTAR1)
  {
    printf("Computing temoral AR1 %d\n",mriout->nframes-TAR1DOFAdjust);
    mritmp = fMRItemporalAR1(mriout,TAR1DOFAdjust,NULL,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoStd || DoVar)
  {
    printf("Computing std/var across frames\n");
    if(mriout->nframes < 2)
    {
      printf("ERROR: cannot compute std from one frame\n");
      exit(1);
    }
    //mritmp = fMRIvariance(mriout, -1, 1, NULL);
    mritmp = fMRIcovariance(mriout, 0, -1, NULL, NULL);
    if(DoStd)
    {
      MRIsqrt(mritmp, mritmp);
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMax)
  {
    printf("Computing max across all frames \n");
    mritmp = MRIvolMax(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMaxIndex)
  {
    printf("Computing max index across all frames \n");
    mritmp = MRIvolMaxIndex(mriout,1,NULL,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoConjunction)
  {
    printf("Computing conjunction across all frames \n");
    mritmp = MRIconjunct(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMin)
  {
    printf("Computing min across all frames \n");
    mritmp = MRIvolMin(mriout,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoSort)
  {
    printf("Sorting \n");
    mritmp = MRIsort(mriout,mask,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoVote)
  {
    printf("Voting \n");
    mritmp = MRIvote(mriout,mask,NULL);
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoMultiply)
  {
    printf("Multiplying by %lf\n",MultiplyVal);
    MRImultiplyConst(mriout, MultiplyVal, mriout);
  }

  if(DoAdd)
  {
    printf("Adding %lf\n",AddVal);
    MRIaddConst(mriout, AddVal, mriout);
  }

  if(DoSCM)
  {
    printf("Computing spatial correlation matrix (%d)\n",mriout->nframes);
    mritmp = fMRIspatialCorMatrix(mriout);
    if(mritmp == NULL)
    {
      exit(1);
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoPCA)
  {
    // Saves only non-zero components
    printf("Computing PCA\n");
    if(PCAMaskFile)
    {
      printf("  PCA Mask %s\n",PCAMaskFile);
      PCAMask = MRIread(PCAMaskFile);
      if(PCAMask == NULL)
      {
        exit(1);
      }
    }
    err=MRIpca(mriout, &Upca, &Spca, &Vpca, PCAMask);
    if(err)
    {
      exit(1);
    }
    stem = IDstemFromName(out);
    sprintf(tmpstr,"%s.u.mtx",stem);
    MatrixWriteTxt(tmpstr, Upca);
    sprintf(tmpstr,"%s.stats.dat",stem);
    WritePCAStats(tmpstr,Spca);
    MRIfree(&mriout);
    mriout = Vpca;
  }

  if(NReplications > 0)
  {
    printf("NReplications %d\n",NReplications);
    mritmp = MRIallocSequence(mriout->width,
                              mriout->height,
                              mriout->depth,
                              mriout->type,
                              mriout->nframes*NReplications);
    if(mritmp == NULL)
    {
      exit(1);
    }
    printf("Done allocing\n");
    MRIcopyHeader(mriout,mritmp);
    for(c=0; c < mriout->width; c++)
    {
      for(r=0; r < mriout->height; r++)
      {
        for(s=0; s < mriout->depth; s++)
        {
          outf = 0;
          for(nthrep = 0; nthrep < NReplications; nthrep++)
          {
            for(f=0; f < mriout->nframes; f++)
            {
              v = MRIgetVoxVal(mriout,c,r,s,f);
              MRIsetVoxVal(mritmp,c,r,s,outf,v);
              outf ++;
            }
          }
        }
      }
    }
    MRIfree(&mriout);
    mriout = mritmp;
  }

  if(DoPrune)
  {
    // Apply prune mask that was computed above
    printf("Applying prune mask \n");
    MRImask(mriout, PruneMask, mriout, 0, 0);
  }

  if(DoRMS)
  {
    printf("Computing RMS across input frames\n");
    mritmp = MRIread(inlist[0]);
    MRIcopyHeader(mritmp, mriout);
    MRIrms(mritmp,mriout);
  }

  printf("Writing to %s\n",out);
  err = MRIwrite(mriout,out);
  if(err)
  {
    exit(err);
  }

  return(0);
}
Пример #26
0
HYPRE_Int main(HYPRE_Int argc, char *argv[])
{
    HYPRE_Int mype, npes;
    HYPRE_Int symmetric;
    HYPRE_Int num_runs;
    Matrix *A;
    ParaSails *ps;
    FILE *file;
    HYPRE_Int n, beg_row, end_row;
    HYPRE_Real time0, time1;
    HYPRE_Real setup_time, solve_time;
    HYPRE_Real max_setup_time, max_solve_time;
    HYPRE_Real cost;

    HYPRE_Real *x, *b;
    HYPRE_Int i, niter;
    HYPRE_Real thresh;
    HYPRE_Real threshg;
    HYPRE_Int nlevels;
    HYPRE_Real filter;
    HYPRE_Real loadbal;

    hypre_MPI_Init(&argc, &argv);
    hypre_MPI_Comm_rank(hypre_MPI_COMM_WORLD, &mype);
    hypre_MPI_Comm_size(hypre_MPI_COMM_WORLD, &npes);

    /* Read number of rows in matrix */
    symmetric = atoi(argv[1]);
    num_runs  = atoi(argv[2]);

    file = fopen(argv[3], "r");
    assert(file != NULL);
#ifdef EMSOLVE
    hypre_fscanf(file, "%*d %d\n", &n);
#else
    hypre_fscanf(file, "%d\n", &n);
#endif
    fclose(file);
    assert(n >= npes);

    beg_row = (HYPRE_Int) ((HYPRE_Real)(mype*n) / npes) + 1; /* assumes 1-based */
    end_row = (HYPRE_Int) ((HYPRE_Real)((mype+1)* n) / npes);

    if (mype == 0)
        assert(beg_row == 1);
    if (mype == npes-1)
        assert(end_row == n);

#ifdef EMSOLVE
    beg_row--;
    end_row--;
#endif

    x = (HYPRE_Real *) malloc((end_row-beg_row+1) * sizeof(HYPRE_Real));
    b = (HYPRE_Real *) malloc((end_row-beg_row+1) * sizeof(HYPRE_Real));

    A = MatrixCreate(hypre_MPI_COMM_WORLD, beg_row, end_row);

    MatrixRead(A, argv[3]);
    if (mype == 0) 
        hypre_printf("%s\n", argv[3]);

    /* MatrixPrint(A, "A"); */

    /* Right-hand side */
    if (argc > 4)
    {
        RhsRead(b, A, argv[4]);
        if (mype == 0) 
            hypre_printf("Using rhs from %s\n", argv[4]);
    }
    else
    {
        for (i=0; i<end_row-beg_row+1; i++)
            b[i] = (HYPRE_Real) (2*rand()) / (HYPRE_Real) RAND_MAX - 1.0;
    }

    while (num_runs && num_runs >= -1)
    {
        /* Initial guess */
        for (i=0; i<end_row-beg_row+1; i++)
            x[i] = 0.0;

	if (num_runs == -1)
	{
            thresh = 0.0;
	    nlevels = 0;
	    filter = 0.0;
            loadbal = 0.0;
	}
	else
	{
            if (mype == 0)
            {
#if PARASAILS_EXT_PATTERN
                hypre_printf("Enter parameters threshg, thresh, nlevels, "
	            "filter, beta:\n");
	        fflush(stdout);
                hypre_scanf("%lf %lf %d %lf %lf", &threshg, &thresh, &nlevels, 
		    &filter, &loadbal);
#else
                hypre_printf("Enter parameters thresh, nlevels, "
	            "filter, beta:\n");
	        fflush(stdout);
                hypre_scanf("%lf %d %lf %lf", &thresh, &nlevels, 
		    &filter, &loadbal);
#endif
	    }

	    hypre_MPI_Bcast(&threshg, 1, hypre_MPI_DOUBLE, 0, hypre_MPI_COMM_WORLD);
	    hypre_MPI_Bcast(&thresh,  1, hypre_MPI_DOUBLE, 0, hypre_MPI_COMM_WORLD);
	    hypre_MPI_Bcast(&nlevels, 1, HYPRE_MPI_INT,    0, hypre_MPI_COMM_WORLD);
	    hypre_MPI_Bcast(&filter,  1, hypre_MPI_DOUBLE, 0, hypre_MPI_COMM_WORLD);
	    hypre_MPI_Bcast(&loadbal, 1, hypre_MPI_DOUBLE, 0, hypre_MPI_COMM_WORLD);

            if (nlevels < 0)
                break;
	}

        /**************
	 * Setup phase   
	 **************/

        hypre_MPI_Barrier(hypre_MPI_COMM_WORLD);
        time0 = hypre_MPI_Wtime();

        ps = ParaSailsCreate(hypre_MPI_COMM_WORLD, beg_row, end_row, symmetric);

        ps->loadbal_beta = loadbal;

#if PARASAILS_EXT_PATTERN
        ParaSailsSetupPatternExt(ps, A, threshg, thresh, nlevels);
#else
        ParaSailsSetupPattern(ps, A, thresh, nlevels);
#endif

        time1 = hypre_MPI_Wtime();
	setup_time = time1-time0;

        cost = ParaSailsStatsPattern(ps, A);
	if (cost > 5.e11)
	{
            hypre_printf("Aborting setup and solve due to high cost.\n");
	    goto cleanup;
	}

        hypre_MPI_Barrier(hypre_MPI_COMM_WORLD);
        time0 = hypre_MPI_Wtime();

        err = ParaSailsSetupValues(ps, A, filter);
        if (err != 0)
	{
            hypre_printf("ParaSailsSetupValues returned error.\n");
	    goto cleanup;
	}

        time1 = hypre_MPI_Wtime();
	setup_time += (time1-time0);

        ParaSailsStatsValues(ps, A);

	if (!strncmp(argv[3], "testpsmat", 8))
            MatrixPrint(ps->M, "M");

#if 0
        if (mype == 0) 
            hypre_printf("SETTING UP VALUES AGAIN WITH FILTERED PATTERN\n");
        ps->loadbal_beta = 0;
        ParaSailsSetupValues(ps, A, 0.0);
#endif

        /*****************
	 * Solution phase
	 *****************/

	niter = 3000;
        if (MatrixNnz(ps->M) == n) /* if diagonal preconditioner */
	    niter = 5000;

        hypre_MPI_Barrier(hypre_MPI_COMM_WORLD);
        time0 = hypre_MPI_Wtime();

        if (symmetric == 1)
            PCG_ParaSails(A, ps, b, x, 1.e-8, niter);
	else
            FGMRES_ParaSails(A, ps, b, x, 50, 1.e-8, niter);

        time1 = hypre_MPI_Wtime();
	solve_time = time1-time0;

        hypre_MPI_Reduce(&setup_time, &max_setup_time, 1, hypre_MPI_DOUBLE, hypre_MPI_MAX, 0, 
	    hypre_MPI_COMM_WORLD);
        hypre_MPI_Reduce(&solve_time, &max_solve_time, 1, hypre_MPI_DOUBLE, hypre_MPI_MAX, 0, 
	    hypre_MPI_COMM_WORLD);

	if (mype == 0)
	{
            hypre_printf("**********************************************\n");
            hypre_printf("***    Setup    Solve    Total\n");
            hypre_printf("III %8.1f %8.1f %8.1f\n", max_setup_time, max_solve_time, 
		max_setup_time+max_solve_time);
            hypre_printf("**********************************************\n");
	}

cleanup:
        ParaSailsDestroy(ps);

        num_runs--;
    }

    free(x);
    free(b);

    MatrixDestroy(A);
    hypre_MPI_Finalize();

    return 0;
}