コード例 #1
0
int
main(int argc, char *argv[])
{
  double           thresh ;
  MRI              *mri, *mri_abs ;
  char             *out_stem, fname[STRLEN] ;
  MRI_SEGMENTATION *mriseg ;
  int              s ;
  LABEL            *area ;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  mri = MRIread(argv[1]) ;
  if (mri == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not load MRI from %s\n", Progname, argv[1]) ;

  if (use_abs)
    mri_abs = MRIabs(mri, NULL) ;
  else
    mri_abs = MRIcopy(mri, NULL) ;

  thresh = atof(argv[2]) ;
  out_stem = argv[3] ;

  mriseg = MRIsegment(mri, thresh, 1e10) ;
  MRIremoveSmallSegments(mriseg, size_thresh) ;
  printf("segmenting volume at threshold %2.1f yields %d segments\n", thresh, mriseg->nsegments) ;

  for (s = 0 ; s < mriseg->nsegments ; s++)
  {
    area = MRIsegmentToLabel(mriseg, mri_abs, s) ;
    sprintf(fname, "%s.%3.3d.label", out_stem, s) ;
    LabelWrite(area, fname) ;
    
  }
  return(0) ;
}
コード例 #2
0
ファイル: mri_mcsim.c プロジェクト: guo2004131/freesurfer
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, n, err;
  char tmpstr[2000], *signstr=NULL,*SUBJECTS_DIR, fname[2000];
  //char *OutDir = NULL;
  RFS *rfs;
  int nSmoothsPrev, nSmoothsDelta;
  MRI *z, *zabs=NULL, *sig=NULL, *p=NULL;
  int FreeMask = 0;
  int nthSign, nthFWHM, nthThresh;
  double sigmax, zmax, threshadj, csize, csizeavg, searchspace,avgvtxarea;
  int csizen;
  int nClusters, cmax,rmax,smax;
  SURFCLUSTERSUM *SurfClustList;
  struct timeb  mytimer;
  LABEL *clabel;
  FILE *fp, *fpLog=NULL;

  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();
  if (checkoptsonly) return(0);
  dump_options(stdout);

  if(LogFile){
    fpLog = fopen(LogFile,"w");
    if(fpLog == NULL){
      printf("ERROR: opening %s\n",LogFile);
      exit(1);
    }
    dump_options(fpLog);
  } 

  if(SynthSeed < 0) SynthSeed = PDFtodSeed();
  srand48(SynthSeed);

  SUBJECTS_DIR = getenv("SUBJECTS_DIR");

  // Create output directory
  printf("Creating %s\n",OutTop);
  err = fio_mkdirp(OutTop,0777);
  if(err) exit(1);
  for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
    for(nthThresh = 0; nthThresh < nThreshList; nthThresh++){
      for(nthSign = 0; nthSign < nSignList; nthSign++){
	if(SignList[nthSign] ==  0) signstr = "abs"; 
	if(SignList[nthSign] == +1) signstr = "pos"; 
	if(SignList[nthSign] == -1) signstr = "neg"; 
	sprintf(tmpstr,"%s/fwhm%02d/%s/th%02d",
		OutTop,(int)round(FWHMList[nthFWHM]),
		signstr,(int)round(10*ThreshList[nthThresh]));
	sprintf(fname,"%s/%s.csd",tmpstr,csdbase);
	if(fio_FileExistsReadable(fname)){
	  printf("ERROR: output file %s exists\n",fname);
	  if(fpLog) fprintf(fpLog,"ERROR: output file %s exists\n",fname);
          exit(1);
	}
	err = fio_mkdirp(tmpstr,0777);
	if(err) exit(1);
      }
    }
  }

  // Load the target surface
  sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR,subject,hemi,surfname);
  printf("Loading %s\n",tmpstr);
  surf = MRISread(tmpstr);
  if(!surf) return(1);

  // Handle masking
  if(LabelFile){
    printf("Loading label file %s\n",LabelFile);
    sprintf(tmpstr,"%s/%s/label/%s.%s.label",
	    SUBJECTS_DIR,subject,hemi,LabelFile);
    if(!fio_FileExistsReadable(tmpstr)){
      printf(" Cannot find label file %s\n",tmpstr);
      sprintf(tmpstr,"%s",LabelFile);
      printf(" Trying label file %s\n",tmpstr);
      if(!fio_FileExistsReadable(tmpstr)){
	printf("  ERROR: cannot read or find label file %s\n",LabelFile);
	exit(1);
      }
    }
    printf("Loading %s\n",tmpstr);
    clabel = LabelRead(NULL, tmpstr);
    mask = MRISlabel2Mask(surf, clabel, NULL);
    FreeMask = 1;
  }
  if(MaskFile){
    printf("Loading %s\n",MaskFile);
    mask = MRIread(MaskFile);
    if(mask == NULL) exit(1);
  }
  if(mask && SaveMask){
    sprintf(tmpstr,"%s/mask.mgh",OutTop);
    printf("Saving mask to %s\n",tmpstr);
    err = MRIwrite(mask,tmpstr);
    if(err) exit(1);
  }

  // Compute search space
  searchspace = 0;
  nmask = 0;
  for(n=0; n < surf->nvertices; n++){
    if(mask && MRIgetVoxVal(mask,n,0,0,0) < 0.5) continue;
    searchspace += surf->vertices[n].area;
    nmask++;
  }
  printf("Found %d voxels in mask\n",nmask);
  if(surf->group_avg_surface_area > 0)
    searchspace *= (surf->group_avg_surface_area/surf->total_area);
  printf("search space %g mm2\n",searchspace);
  avgvtxarea = searchspace/nmask;
  printf("average vertex area %g mm2\n",avgvtxarea);

  // Determine how many iterations are needed for each FWHM
  nSmoothsList = (int *) calloc(sizeof(int),nFWHMList);
  for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
    nSmoothsList[nthFWHM] = MRISfwhm2niters(FWHMList[nthFWHM], surf);
    printf("%2d %5.1f  %4d\n",nthFWHM,FWHMList[nthFWHM],nSmoothsList[nthFWHM]);
    if(fpLog) fprintf(fpLog,"%2d %5.1f  %4d\n",nthFWHM,FWHMList[nthFWHM],nSmoothsList[nthFWHM]);
  }
  printf("\n");

  // Allocate the CSDs
  for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
    for(nthThresh = 0; nthThresh < nThreshList; nthThresh++){
      for(nthSign = 0; nthSign < nSignList; nthSign++){
	csd = CSDalloc();
	sprintf(csd->simtype,"%s","null-z");
	sprintf(csd->anattype,"%s","surface");
	sprintf(csd->subject,"%s",subject);
	sprintf(csd->hemi,"%s",hemi);
	sprintf(csd->contrast,"%s","NA");
	csd->seed = SynthSeed;
	csd->nreps = nRepetitions;
	csd->thresh = ThreshList[nthThresh];
	csd->threshsign = SignList[nthSign];
	csd->nullfwhm = FWHMList[nthFWHM];
	csd->varfwhm = -1;
	csd->searchspace = searchspace;
	CSDallocData(csd);
	csdList[nthFWHM][nthThresh][nthSign] = csd;
      }
    }
  }

  // Alloc the z map
  z = MRIallocSequence(surf->nvertices, 1,1, MRI_FLOAT, 1);

  // Set up the random field specification
  rfs = RFspecInit(SynthSeed,NULL);
  rfs->name = strcpyalloc("gaussian");
  rfs->params[0] = 0;
  rfs->params[1] = 1;

  printf("Thresholds (%d): ",nThreshList);
  for(n=0; n < nThreshList; n++) printf("%5.2f ",ThreshList[n]);
  printf("\n");
  printf("Signs (%d): ",nSignList);
  for(n=0; n < nSignList; n++)  printf("%2d ",SignList[n]);
  printf("\n");
  printf("FWHM (%d): ",nFWHMList);
  for(n=0; n < nFWHMList; n++) printf("%5.2f ",FWHMList[n]);
  printf("\n");

  // Start the simulation loop
  printf("\n\nStarting Simulation over %d Repetitions\n",nRepetitions);
  if(fpLog) fprintf(fpLog,"\n\nStarting Simulation over %d Repetitions\n",nRepetitions);
  TimerStart(&mytimer) ;
  for(nthRep = 0; nthRep < nRepetitions; nthRep++){
    msecTime = TimerStop(&mytimer) ;
    printf("%5d %7.1f ",nthRep,(msecTime/1000.0)/60);
    if(fpLog) {
      fprintf(fpLog,"%5d %7.1f ",nthRep,(msecTime/1000.0)/60);
      fflush(fpLog);
    }
    // Synthesize an unsmoothed z map
    RFsynth(z,rfs,mask); 
    nSmoothsPrev = 0;
    
    // Loop through FWHMs
    for(nthFWHM=0; nthFWHM < nFWHMList; nthFWHM++){
      printf("%d ",nthFWHM);
      if(fpLog) {
	fprintf(fpLog,"%d ",nthFWHM);
	fflush(fpLog);
      }
      nSmoothsDelta = nSmoothsList[nthFWHM] - nSmoothsPrev;
      nSmoothsPrev = nSmoothsList[nthFWHM];
      // Incrementally smooth z
      MRISsmoothMRI(surf, z, nSmoothsDelta, mask, z); // smooth z
      // Rescale
      RFrescale(z,rfs,mask,z);
      // Slightly tortured way to get the right p-values because
      //   RFstat2P() computes one-sided, but I handle sidedness
      //   during thresholding.
      // First, use zabs to get a two-sided pval bet 0 and 0.5
      zabs = MRIabs(z,zabs);
      p = RFstat2P(zabs,rfs,mask,0,p);
      // Next, mult pvals by 2 to get two-sided bet 0 and 1
      MRIscalarMul(p,p,2.0);
      sig = MRIlog10(p,NULL,sig,1); // sig = -log10(p)
      for(nthThresh = 0; nthThresh < nThreshList; nthThresh++){
	for(nthSign = 0; nthSign < nSignList; nthSign++){
	  csd = csdList[nthFWHM][nthThresh][nthSign];

	  // If test is not ABS then apply the sign
	  if(csd->threshsign != 0) MRIsetSign(sig,z,0);
	  // Get the max stats
	  sigmax = MRIframeMax(sig,0,mask,csd->threshsign,
			       &cmax,&rmax,&smax);
	  zmax = MRIgetVoxVal(z,cmax,rmax,smax,0);
	  if(csd->threshsign == 0){
	    zmax = fabs(zmax);
	    sigmax = fabs(sigmax);
	  }
	  // Mask
	  if(mask) MRImask(sig,mask,sig,0.0,0.0);

	  // Surface clustering
	  MRIScopyMRI(surf, sig, 0, "val");
	  if(csd->threshsign == 0) threshadj = csd->thresh;
	  else threshadj = csd->thresh - log10(2.0); // one-sided test
	  SurfClustList = sclustMapSurfClusters(surf,threshadj,-1,csd->threshsign,
						0,&nClusters,NULL);
	  // Actual area of cluster with max area
	  csize  = sclustMaxClusterArea(SurfClustList, nClusters);
	  // Number of vertices of cluster with max number of vertices. 
	  // Note: this may be a different cluster from above!
	  csizen = sclustMaxClusterCount(SurfClustList, nClusters);
	  // Area of this cluster based on average vertex area. This just scales
	  // the number of vertices.
	  csizeavg = csizen * avgvtxarea;
	  if(UseAvgVtxArea) csize = csizeavg;
	  // Store results
	  csd->nClusters[nthRep] = nClusters;
	  csd->MaxClusterSize[nthRep] = csize;
	  csd->MaxSig[nthRep] = sigmax;
	  csd->MaxStat[nthRep] = zmax;
	} // Sign
      } // Thresh
    } // FWHM
    printf("\n");
    if(fpLog) fprintf(fpLog,"\n");
    if(SaveEachIter || fio_FileExistsReadable(SaveFile)) SaveOutput();
    if(fio_FileExistsReadable(StopFile)) {
      printf("Found stop file %s\n",StopFile);
      goto finish;
    }
  } // Simulation Repetition

 finish:

  SaveOutput();

  msecTime = TimerStop(&mytimer) ;
  printf("Total Sim Time %g min (%g per rep)\n",
	 msecTime/(1000*60.0),(msecTime/(1000*60.0))/nthRep);
  if(fpLog) fprintf(fpLog,"Total Sim Time %g min (%g per rep)\n",
		    msecTime/(1000*60.0),(msecTime/(1000*60.0))/nthRep);

  if(DoneFile){
    fp = fopen(DoneFile,"w");
    fprintf(fp,"%g\n",msecTime/(1000*60.0));
    fclose(fp);
  }
  printf("mri_mcsim done\n");
  if(fpLog){
    fprintf(fpLog,"mri_mcsim done\n");
    fclose(fpLog);
  }
  exit(0);
}
コード例 #3
0
ファイル: mri_volsynth.c プロジェクト: ewong718/freesurfer
/*---------------------------------------------------------------*/
int main(int argc, char **argv)
{
  int c,r,s,f;
  double val,rval;
  FILE *fp;
  MRI *mritmp;

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

  /* assign default geometry */
  cdircos[0] = 1.0;
  cdircos[1] = 0.0;
  cdircos[2] = 0.0;
  rdircos[0] = 0.0;
  rdircos[1] = 1.0;
  rdircos[2] = 0.0;
  sdircos[0] = 0.0;
  sdircos[1] = 0.0;
  sdircos[2] = 1.0;
  res[0] = 1.0;
  res[1] = 1.0;
  res[2] = 1.0;
  cras[0] = 0.0;
  cras[1] = 0.0;
  cras[2] = 0.0;
  res[3] = 2.0; /* TR */

  if (argc == 0) usage_exit();

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

  if(tempid != NULL) {
    printf("INFO: reading template header\n");
    if(! DoCurv) mritemp = MRIreadHeader(tempid,tempfmtid);
    else         mritemp = MRIread(tempid);
    if (mritemp == NULL) {
      printf("ERROR: reading %s header\n",tempid);
      exit(1);
    }
    if(NewVoxSizeSpeced){
      dim[0] = round(mritemp->width*mritemp->xsize/res[0]);
      dim[1] = round(mritemp->height*mritemp->ysize/res[1]);
      dim[2] = round(mritemp->depth*mritemp->zsize/res[2]);
      dim[3] = mritemp->nframes;
      res[3] = mritemp->tr;
      dimSpeced = 1;
    }
    if(dimSpeced){
      mritmp = MRIallocSequence(dim[0],dim[1],dim[2],MRI_FLOAT,dim[3]);
      MRIcopyHeader(mritemp,mritmp);
      MRIfree(&mritemp);
      mritemp = mritmp;
    }
    if(resSpeced){
      mritemp->xsize = res[0];
      mritemp->ysize = res[1];
      mritemp->zsize = res[2];
      mritemp->tr    = res[3];
    }

    dim[0] = mritemp->width;
    dim[1] = mritemp->height;
    dim[2] = mritemp->depth;
    if (nframes > 0) dim[3] = nframes;
    else             dim[3] = mritemp->nframes;
    mritemp->nframes = dim[3];
  }

  if(mritemp) {
    if(SpikeTP >= mritemp->nframes){
      printf("ERROR: SpikeTP = %d >= mritemp->nframes = %d\n",
             SpikeTP,mritemp->nframes);
      exit(1);
    }
  }

  printf("Synthesizing\n");
  srand48(seed);
  if (strcmp(pdfname,"gaussian")==0)
    mri = MRIrandn(dim[0], dim[1], dim[2], dim[3], gausmean, gausstd, NULL);
  else if (strcmp(pdfname,"uniform")==0)
    mri = MRIdrand48(dim[0], dim[1], dim[2], dim[3], 0, 1, NULL);
  else if (strcmp(pdfname,"const")==0)
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], ValueA, NULL);
  else if (strcmp(pdfname,"sphere")==0) {
    if(voxradius < 0)
      voxradius =
        sqrt( pow(dim[0]/2.0,2)+pow(dim[1]/2.0,2)+pow(dim[2]/2.0,2) )/2.0;
    printf("voxradius = %lf\n",voxradius);
    mri = MRIsphereMask(dim[0], dim[1], dim[2], dim[3],
                        dim[0]/2.0, dim[1]/2.0, dim[2]/2.0,
                        voxradius, ValueA, NULL);
  } else if (strcmp(pdfname,"delta")==0) {
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], delta_off_value, NULL);
    if (delta_crsf_speced == 0) {
      delta_crsf[0] = dim[0]/2;
      delta_crsf[1] = dim[1]/2;
      delta_crsf[2] = dim[2]/2;
      delta_crsf[3] = dim[3]/2;
    }
    printf("delta set to %g at %d %d %d %d\n",delta_value,delta_crsf[0],
           delta_crsf[1],delta_crsf[2],delta_crsf[3]);
    MRIFseq_vox(mri,
                delta_crsf[0],
                delta_crsf[1],
                delta_crsf[2],
                delta_crsf[3]) = delta_value;
  } else if (strcmp(pdfname,"chi2")==0) {
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("chi2");
    rfs->params[0] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    printf("Synthesizing chi2 with dof=%d\n",dendof);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"z")==0) {
    printf("Synthesizing z \n");
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("gaussian");
    rfs->params[0] = 0; // mean
    rfs->params[1] = 1; // std
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"t")==0) {
    printf("Synthesizing t with dof=%d\n",dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("t");
    rfs->params[0] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"tr")==0) {
    printf("Synthesizing t with dof=%d as ratio of z/sqrt(chi2)\n",dendof);
    rfs = RFspecInit(seed,NULL);
    // numerator
    rfs->name = strcpyalloc("gaussian");
    rfs->params[0] = 0; // mean
    rfs->params[1] = 1; // std
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
    // denominator
    rfs->name = strcpyalloc("chi2");
    rfs->params[0] = dendof;
    mri2 = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri2,rfs,NULL);
    fMRIsqrt(mri2,mri2); // sqrt of chi2
    mri = MRIdivide(mri,mri2,mri);
    MRIscalarMul(mri, mri, sqrt(dendof)) ;
    MRIfree(&mri2);
  } else if (strcmp(pdfname,"F")==0) {
    printf("Synthesizing F with num=%d den=%d\n",numdof,dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("F");
    rfs->params[0] = numdof;
    rfs->params[1] = dendof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
  } else if (strcmp(pdfname,"Fr")==0) {
    printf("Synthesizing F with num=%d den=%d as ratio of two chi2\n",
           numdof,dendof);
    rfs = RFspecInit(seed,NULL);
    rfs->name = strcpyalloc("chi2");
    // numerator
    rfs->params[0] = numdof;
    mri = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri,rfs,NULL);
    // denominator
    rfs->params[0] = dendof;
    mri2 = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    RFsynth(mri2,rfs,NULL);
    mri = MRIdivide(mri,mri2,mri);
    MRIscalarMul(mri, mri, (double)dendof/numdof) ;
    MRIfree(&mri2);
  } else if (strcmp(pdfname,"voxcrs")==0) {
    // three frames. 1st=col, 2nd=row, 3rd=slice
    printf("Filling with vox CRS\n");
    mri = MRIconst(dim[0], dim[1], dim[2], 3, 0, NULL);
    for(c=0; c < mri->width; c ++){
      for(r=0; r < mri->height; r ++){
        for(s=0; s < mri->depth; s ++){
          MRIsetVoxVal(mri,c,r,s,0,c);
          MRIsetVoxVal(mri,c,r,s,1,r);
          MRIsetVoxVal(mri,c,r,s,2,s);
        }
      }
    }
  } else if (strcmp(pdfname,"boundingbox")==0) {
    printf("Setting bounding box \n");
    if(mritemp == NULL)
      mritemp = MRIconst(dim[0], dim[1], dim[2], dim[3], 0, NULL);
    mri = MRIsetBoundingBox(mritemp,&boundingbox,ValueA,ValueB);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"checker")==0) {
    printf("Checker \n");
    mri=MRIchecker(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"sliceno")==0) {
    printf("SliceNo \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with sliceno\n");
      exit(1);
    }
    mri=MRIsliceNo(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"indexno")==0) {
    printf("IndexNo \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with indexno\n");
      exit(1);
    }
    mri=MRIindexNo(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else if (strcmp(pdfname,"crs")==0) {
    printf("CRS \n");
    if(mritemp == NULL){
      printf("ERROR: need --temp with crs\n");
      exit(1);
    }
    mri=MRIcrs(mritemp,NULL);
    if(!mri) exit(1);
  } 
  else {
    printf("ERROR: pdf %s unrecognized, must be gaussian, uniform,\n"
	   "const, delta, checker\n", pdfname);
    exit(1);
  }
  if (tempid != NULL) {
    MRIcopyHeader(mritemp,mri);
    mri->type = MRI_FLOAT;
    // Override
    if(nframes > 0) mri->nframes = nframes;
    if(TR > 0) mri->tr = TR;
  } else {
    if(mri == NULL) {
      usage_exit();
    }
    mri->xsize = res[0];
    mri->ysize = res[1];
    mri->zsize = res[2];
    mri->tr    = res[3];
    mri->x_r = cdircos[0];
    mri->x_a = cdircos[1];
    mri->x_s = cdircos[2];
    mri->y_r = rdircos[0];
    mri->y_a = rdircos[1];
    mri->y_s = rdircos[2];
    mri->z_r = sdircos[0];
    mri->z_a = sdircos[1];
    mri->z_s = sdircos[2];
    if(!usep0){
      mri->c_r = cras[0];
      mri->c_a = cras[1];
      mri->c_s = cras[2];
    } 
    else MRIp0ToCRAS(mri, p0[0], p0[1], p0[2]);
  }

  if (gstd > 0) {
    if(!UseFFT){
      printf("Smoothing\n");
      MRIgaussianSmooth(mri, gstd, gmnnorm, mri); /* gmnnorm = 1 = normalize */
    }
    else {
      printf("Smoothing with FFT \n");
      mri2 = MRIcopy(mri,NULL);
      mri = MRI_fft_gaussian(mri2, mri,
                             gstd, gmnnorm); /* gmnnorm = 1 = normalize */
    }
    if (rescale) {
      printf("Rescaling\n");
      if (strcmp(pdfname,"z")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"chi2")==0)  RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"t")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"tr")==0)    RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"F")==0)     RFrescale(mri,rfs,NULL,mri);
      if (strcmp(pdfname,"Fr")==0)    RFrescale(mri,rfs,NULL,mri);
    }
  }

  if(DoHSC){
    // This multiplies each frame by a random number
    // between HSCMin HSCMax to simulate heteroscedastisity
    printf("Applying HSC %lf %lf\n",HSCMin,HSCMax);
    for(f=0; f < mri->nframes; f++){
      rval = (HSCMax-HSCMin)*drand48() + HSCMin;
      if(debug) printf("%3d %lf\n",f,rval);
      for(c=0; c < mri->width; c ++){
	for(r=0; r < mri->height; r ++){
	  for(s=0; s < mri->depth; s ++){
	    val = MRIgetVoxVal(mri,c,r,s,f);
	    MRIsetVoxVal(mri,c,r,s,f,rval*val);
	  }
        }
      }
    }
  }

  if(AddOffset) {
    printf("Adding offset\n");
    offset = MRIread(tempid);
    if(offset == NULL) exit(1);
    if(OffsetFrame == -1) OffsetFrame = nint(offset->nframes/2);
    printf("Offset frame %d\n",OffsetFrame);
    mritmp = fMRIframe(offset, OffsetFrame, NULL);
    if(mritmp == NULL) exit(1);
    MRIfree(&offset);
    offset = mritmp;
    fMRIaddOffset(mri, offset, NULL, mri);
  }

  if(SpikeTP > 0){
    printf("Spiking time point %d\n",SpikeTP);
    for(c=0; c < mri->width; c ++){
      for(r=0; r < mri->height; r ++){
        for(s=0; s < mri->depth; s ++){
          MRIsetVoxVal(mri,c,r,s,SpikeTP,1e9);
        }
      }
    }
  }

  if(DoAbs){
    printf("Computing absolute value\n");
    MRIabs(mri,mri);
  }

  if(!NoOutput){
    printf("Saving\n");
    if(!DoCurv)  MRIwriteAnyFormat(mri,volid,volfmt,-1,NULL);
    else {
      printf("Saving in curv format\n");
      MRIScopyMRI(surf, mri, 0, "curv");
      MRISwriteCurvature(surf,volid);
    }
  }

  if(sum2file){
    val = MRIsum2All(mri);
    fp = fopen(sum2file,"w");
    if(fp == NULL){
      printf("ERROR: opening %s\n",sum2file);
      exit(1);
    }
    printf("sum2all: %20.10lf\n",val);
    printf("vrf: %20.10lf\n",1/val);
    fprintf(fp,"%20.10lf\n",val);
  }

  return(0);
}
コード例 #4
0
ファイル: mri_concat.c プロジェクト: guo2004131/freesurfer
/*--------------------------------------------------*/
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);
}