Example #1
0
/* --------------------------------------------- */
static void check_options(void) {
  if(subject == NULL) {
    printf("ERROR: must specify a surface\n");
    exit(1);
  }
  if(OutTop == NULL){
    printf("ERROR: need to spec an output directory\n");
    exit(1);
  }
  if(csdbase==NULL) {
    printf("ERROR: need to specify a csd base\n");
    exit(1);
  }
  if(MaskFile && LabelFile) {
    printf("ERROR: cannot specify both a mask and a label\n");
    exit(1);
  }
  if(nRepetitions < 1) {
    printf("ERROR: need to specify number of simulation repitions\n");
    exit(1);
  }
  if(nFWHMList == 0){
    double fwhm;
    nFWHMList = 0;
    for(fwhm = 1; fwhm <= 30; fwhm++){
      FWHMList[nFWHMList] = fwhm;
      nFWHMList++;
    }
  }
  if(nThreshList == 0){
    nThreshList = 6;
    ThreshList[0] = 1.3; 
    ThreshList[1] = 2.0;
    ThreshList[2] = 2.3; 
    ThreshList[3] = 3.0; 
    ThreshList[4] = 3.3; 
    ThreshList[5] = 4.0;
  }
  if(StopFile == NULL) {
    sprintf(tmpstr,"%s/mri_mcsim.stop",OutTop);
    StopFile = strcpyalloc(tmpstr);
  }
  if(SaveFile == NULL) {
    sprintf(tmpstr,"%s/mri_mcsim.save",OutTop);
    SaveFile = strcpyalloc(tmpstr);
  }

  return;
}
Example #2
0
/*------------------------------------------------------------------------
  Parameters:

  Description:
  extract just the file name (no path) from a string.

  Return Values:
  nothing.
  ------------------------------------------------------------------------*/
char *
FileNameOnly(const char *full_name, char *fname)
{
  char *slash, *number, *at ;

  slash = strrchr(full_name, '/') ;

  if (fname)
  {
    if (!slash)
      strcpy(fname, full_name) ;
    else
      strcpy(fname, slash+1) ;
  }
  else  
  {
    // cannot process in place due to con
    // 
    // best solution: copy full_name to fname
    //
    fname = strcpyalloc(full_name);
    *slash = 0 ;
  }

  number = strrchr(fname, '#') ;
  if (number)
    *number = 0 ;
  at = strrchr(fname, '@') ;
  if (at)
    *at = 0 ;

  return(fname) ;
}
Example #3
0
char *
FileNameAbsolute(const char *fname, char *absFname)
{
  char pathname[MAXPATHLEN] ;
  int  len ;

  if (*fname == '/')
  {
    if (absFname != fname)
      strcpy(absFname, fname) ;
  }
  else   /* not already absolute */
  {
    len = strlen(fname) ;
    char * fn = strcpyalloc(fname);
    if (fn[len-1] == '/')
      fn[len-1] = 0 ;
#ifndef Linux
    getcwd(pathname,MAXPATHLEN-1) ;
#else
#if 0
    getcwd(pathname, MAXPATHLEN-1) ;
#else
    sprintf(pathname, ".") ;
#endif
#endif
    sprintf(absFname, "%s/%s", pathname, fn) ;
    free(fn);
  }
  return(absFname) ;
}
Example #4
0
/*-------------------------------------------------------------------
  GetNthItemFromString() - extracts the nth item from a string.
  An item is defined as one or more non-white space chars. If nth
  is -1, then it returns the last item. item is a string that
  must be freed by the caller. Same as gdfGetNthItemFromString().
  ------------------------------------------------------------------*/
char *GetNthItemFromString(const char *str, int nth) 
{
  char *item;
  int nitems,n;
  static char fmt[2000], tmpstr[2000];

  memset(fmt,'\0',2000);
  memset(tmpstr,'\0',2000);

  nitems = CountItemsInString(str);
  if (nth < 0) nth = nitems-1;
  if (nth >= nitems) {
    printf("ERROR: asking for item %d, only %d items in string\n",nth,nitems);
    printf("%s\n",str);
    return(NULL);
  }

  for (n=0; n < nth; n++) sprintf(fmt,"%s %%*s",fmt);
  sprintf(fmt,"%s %%s",fmt);
  //printf("fmt %s\n",fmt);
  sscanf(str,fmt,tmpstr);

  item = strcpyalloc(tmpstr);
  return(item);
}
Example #5
0
/*!
  \fn MRI *RFz2p(MRI *z, MRI *mask, int TwoSided, MRI *p)
  \brief Converts z to p. If TwoSided, then computes the unsigned p,
         but p keeps the sign of z.
*/
MRI *RFz2p(MRI *z, MRI *mask, int TwoSided, MRI *p)
{
  RFS *rfs;
  rfs = RFspecInit(0,NULL);
  rfs->name = strcpyalloc("gaussian");
  rfs->params[0] = 0;
  rfs->params[1] = 1;
  p = RFstat2P(z,rfs,mask,TwoSided,p);
  return(p);
}
Example #6
0
/* --------------------------------------------- */
static void check_options(void)
{
    if (subject == NULL)
    {
        printf("ERROR: must specify a subject\n");
        exit(1);
    }
    if (OutASegFile == NULL)
    {
        sprintf(tmpstr,"%s/%s/mri/%s+aseg.mgz",SUBJECTS_DIR,subject,annotname);
        OutASegFile = strcpyalloc(tmpstr);
    }
    if (UseRibbon && UseNewRibbon)
    {
        printf("ERROR: cannot --old-ribbon and --new-ribbon\n");
        exit(1);
    }
    if (CtxSegFile && ! RipUnknown)
    {
        printf("ERROR: can only use --ctxseg with --rip-unknown\n");
        exit(1);
    }
    if (CtxSegFile)
    {
        if (!fio_FileExistsReadable(CtxSegFile))
        {
            sprintf(tmpstr,"%s/%s/mri/%s",SUBJECTS_DIR,subject,CtxSegFile);
            if (! fio_FileExistsReadable(tmpstr))
            {
                printf("ERROR: cannot find %s or %s\n",CtxSegFile,tmpstr);
                exit(1);
            }
            CtxSegFile = strcpyalloc(tmpstr);
        }
    }
    if (FixParaHipWM && ! LabelWM)
    {
        FixParaHipWM  = 0;
    }

    return;
}
Example #7
0
char *Stem2Path(char *stem)
{
  char *path;
  char tmpstr[2000];

  // If stem exists, it is not a stem but a full path already
  if(fio_FileExistsReadable(stem)){
    path = strcpyalloc(stem);
    return(path);
  }
  // Now go thru each type
  sprintf(tmpstr,"%s.mgz",stem);
  if(fio_FileExistsReadable(tmpstr)){
    path = strcpyalloc(tmpstr);
    return(path);
  }
  sprintf(tmpstr,"%s.mgh",stem);
  if(fio_FileExistsReadable(tmpstr)){
    path = strcpyalloc(tmpstr);
    return(path);
  }
  sprintf(tmpstr,"%s.nii",stem);
  if(fio_FileExistsReadable(tmpstr)){
    path = strcpyalloc(tmpstr);
    return(path);
  }
  sprintf(tmpstr,"%s.nii.gz",stem);
  if(fio_FileExistsReadable(tmpstr)){
    path = strcpyalloc(tmpstr);
    return(path);
  }
  sprintf(tmpstr,"%s.bhdr",stem);
  if(fio_FileExistsReadable(tmpstr)){
    path = strcpyalloc(tmpstr);
    return(path);
  }

  printf("ERROR: could not determine format for %s\n",stem);
  exit(1);
}
Example #8
0
/*---------------------------------------------------------------*/
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);
}
Example #9
0
/* ------------------------------------------------------------------ */
static int parse_commandline(int argc, char **argv) {
  int  i, nargc , nargsused;
  char **pargv, *option ;
  char tmpstr[1000];

  if (argc < 1) usage_exit();

  nargc   = argc;
  pargv = argv;
  while (nargc > 0) {

    option = pargv[0];
    if (debug) printf("%d %s\n",nargc,option);
    nargc -= 1;
    pargv += 1;

    nargsused = 0;

    if (!strcasecmp(option, "--help"))           print_help() ;
    else if (!strcasecmp(option, "--version"))   print_version() ;
    else if (!strcasecmp(option, "--debug"))     debug = 1;
    else if (!strcasecmp(option, "--abs"))       DoAbs = 1;
    else if (!strcasecmp(option, "--nogmnnorm")) gmnnorm = 0;
    else if (!strcasecmp(option, "--rescale"))   rescale=1;
    else if (!strcasecmp(option, "--norescale")) rescale=0;
    else if (!strcasecmp(option, "--no-output")) NoOutput = 1;
    else if (!strcasecmp(option, "--fft"))       UseFFT = 1;
    else if (!strcasecmp(option, "--offset"))    AddOffset=1;
    else if (!strcasecmp(option, "--offset-mid")){
      AddOffset = 1;
      OffsetFrame = -1;
    }
    else if (!strcmp(option, "--hsc")) {
      if (nargc < 2) argnerr(option,2);
      sscanf(pargv[0],"%lf",&HSCMin);
      sscanf(pargv[1],"%lf",&HSCMax);
      DoHSC = 1;
      nargsused = 2;
    }
    else if (!strcmp(option, "--sum2")) {
      if (nargc < 1) argnerr(option,1);
      sum2file = pargv[0];
      pdfname  = "delta";
      //NoOutput = 1;
      nframes  = 1;
      nargsused = 1;
    }
    else if (!strcmp(option, "--hsynth")) {
      // eres mask DoTnorm out
      if (nargc < 3) argnerr(option,3);
      mri = MRIread(pargv[0]);
      mask = MRIread(pargv[1]);
      sscanf(pargv[2],"%d",&DoTNorm);
      mri2 = fMRIhsynth(mri, mask, DoTNorm);
      MRIwrite(mri2,pargv[3]);
      exit(0);
      nargsused = 2;
    }
    else if (!strcmp(option, "--vol") || !strcmp(option, "--o")) {
      if (nargc < 1) argnerr(option,1);
      volid = pargv[0];
      nargsused = 1;
      if (nth_is_arg(nargc, pargv, 1)) {
        volfmt = pargv[1];
        nargsused ++;
        volfmtid = checkfmt(volfmt);
      } 
    }
    else if (!strcmp(option, "--temp") || !strcmp(option, "--template")) {
      if(DoCurv){
	printf("ERROR: cannot use --temp and --curv\n");
	exit(1);
      }
      if(nargc < 1) argnerr(option,1);
      tempid = pargv[0];
      nargsused = 1;
      if (nth_is_arg(nargc, pargv, 1)) {
        tempfmt = pargv[1];
        nargsused ++;
        tempfmtid = checkfmt(tempfmt);
      } else tempfmtid = getfmtid(tempid);
    } else if (!strcmp(option, "--curv")) {
      if(tempid != NULL){
	printf("ERROR: cannot use --temp and --curv\n");
	exit(1);
      }
      if(nargc < 2) argnerr(option,2);
      subject = pargv[0];
      hemi = pargv[1];
      DoCurv = 1;
      nargsused = 2;
      sprintf(tmpstr,"%s/%s/surf/%s.thickness",getenv("SUBJECTS_DIR"),subject,hemi);
      tempid = strcpyalloc(tmpstr);
    } else if ( !strcmp(option, "--dim") ) {
      if (nargc < 4) argnerr(option,4);
      for (i=0;i<4;i++) sscanf(pargv[i],"%d",&dim[i]);
      nargsused = 4;
      dimSpeced = 1;
    } 
    else if ( !strcmp(option, "--nframes") ) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&nframes);
      nargsused = 1;
    } 
    else if ( !strcmp(option, "--TR") || !strcmp(option, "--tr") ) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&TR);
      nargsused = 1;
    } 
    else if ( !strcmp(option, "--res") ) {
      if (nargc < 4) argnerr(option,4);
      for (i=0;i<4;i++) sscanf(pargv[i],"%f",&res[i]);
      nargsused = 4;
      resSpeced = 1;
    } 
    else if ( !strcmp(option, "--vox-size") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&res[i]);
      nargsused = 4;
      resSpeced = 1;
      NewVoxSizeSpeced = 1;
    } 
    else if ( !strcmp(option, "--c_ras") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&cras[i]);
      nargsused = 3;
    } 
    else if ( !strcmp(option, "--p0") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&p0[i]);
      usep0 = 1;
      nargsused = 3;
    } 
    else if ( !strcmp(option, "--cdircos") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&cdircos[i]);
      nargsused = 3;
    } else if ( !strcmp(option, "--rdircos") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&rdircos[i]);
      nargsused = 3;
    } else if ( !strcmp(option, "--sdircos") ) {
      if (nargc < 3) argnerr(option,3);
      for (i=0;i<3;i++) sscanf(pargv[i],"%f",&sdircos[i]);
      nargsused = 3;
    } else if ( !strcmp(option, "--fwhm") ) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%f",&fwhm);
      gstd = fwhm/sqrt(log(256.0));
      nargsused = 1;
    } else if (!strcmp(option, "--precision")) {
      if (nargc < 1) argnerr(option,1);
      precision = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--seed")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%ld",&seed);
      nargsused = 1;
    } else if (!strcmp(option, "--seedfile")) {
      if (nargc < 1) argnerr(option,1);
      seedfile = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--pdf")) {
      if (nargc < 1) argnerr(option,1);
      pdfname = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--bb")) {
      if (nargc < 6) argnerr(option,6);
      sscanf(pargv[0],"%d",&boundingbox.x);
      sscanf(pargv[1],"%d",&boundingbox.y);
      sscanf(pargv[2],"%d",&boundingbox.z);
      sscanf(pargv[3],"%d",&boundingbox.dx);
      sscanf(pargv[4],"%d",&boundingbox.dy);
      sscanf(pargv[5],"%d",&boundingbox.dz);
      pdfname = "boundingbox";
      nargsused = 6;
    }
    else if (!strcasecmp(option, "--checker"))
      pdfname = "checker";
    else if (!strcmp(option, "--dof-num")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&numdof);
      nargsused = 1;
    } else if (!strcmp(option, "--val-a")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&ValueA);
      nargsused = 1;
    } else if (!strcmp(option, "--val-b")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&ValueB);
      nargsused = 1;
    } else if (!strcmp(option, "--radius")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&voxradius);
      nargsused = 1;
    } else if (!strcmp(option, "--dof-den") || !strcmp(option, "--dof")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&dendof);
      nargsused = 1;
    } else if (!strcmp(option, "--gmean")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&gausmean);
      nargsused = 1;
    } else if (!strcmp(option, "--gstd")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&gausstd);
      nargsused = 1;
    } else if (!strcmp(option, "--delta-crsf")) {
      if (nargc < 4) argnerr(option,4);
      sscanf(pargv[0],"%d",&delta_crsf[0]);
      sscanf(pargv[1],"%d",&delta_crsf[1]);
      sscanf(pargv[2],"%d",&delta_crsf[2]);
      sscanf(pargv[3],"%d",&delta_crsf[3]);
      delta_crsf_speced = 1;
      nargsused = 4;
    } else if (!strcmp(option, "--delta-val")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&delta_value);
      nargsused = 1;
    } else if (!strcmp(option, "--delta-val-off")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%lf",&delta_off_value);
      nargsused = 1;
    } else if (!strcmp(option, "--spike")) {
      if (nargc < 1) argnerr(option,1);
      sscanf(pargv[0],"%d",&SpikeTP);
      nargsused = 1;
    } else {
      fprintf(stderr,"ERROR: Option %s unknown\n",option);
      if (singledash(option))
        fprintf(stderr,"       Did you really mean -%s ?\n",option);
      exit(-1);
    }
    nargc -= nargsused;
    pargv += nargsused;
  }
  return(0);
}
Example #10
0
/*---------------------------------------------------------------*/
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);
}
Example #11
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, nthvtx, nnbrs1, nnbrs2, nthnbr, nbrvtxno1, nbrvtxno2;
  int nthface, annot1, annot2;
  VERTEX *vtx1, *vtx2;
  FACE *face1, *face2;
  float diff, maxdiff;

  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);

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

  if (surf1path == NULL && surfname == NULL) surfname = "orig";

  if (surf1path == NULL) {
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR1,subject1,hemi,surfname);
    surf1path = strcpyalloc(tmpstr);
  }
  if (surf2path == NULL) {
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR2,subject2,hemi,surfname);
    surf2path = strcpyalloc(tmpstr);
  }
  dump_options(stdout);

  //read-in each surface.  notice that the random number generator is
  //seeded with the same value prior to each read.  this is because in
  //the routine MRIScomputeNormals, if it finds a zero-length vertex
  //normal, is adds a random value to the x,y,z and recomputes the normal.
  //so if comparing identical surfaces, the seed must be the same so that
  //any zero-length vertex normals appear the same.
  setRandomSeed(seed) ;
  surf1 = MRISread(surf1path);
  if (surf1 == NULL) {
    printf("ERROR: could not read %s\n",surf1path);
    exit(1);
  }
  setRandomSeed(seed) ;
  surf2 = MRISread(surf2path);
  if (surf2 == NULL) {
    printf("ERROR: could not read %s\n",surf2path);
    exit(1);
  }
  printf("Number of vertices %d %d\n",surf1->nvertices,surf2->nvertices);
  printf("Number of faces    %d %d\n",surf1->nfaces,surf2->nfaces);

  //Number of Vertices ----------------------------------------
  if (surf1->nvertices != surf2->nvertices) {
    printf("Surfaces differ in number of vertices %d %d\n",
           surf1->nvertices,surf2->nvertices);
    exit(101);
  }
  //Number of Faces ------------------------------------------
  if (surf1->nfaces != surf2->nfaces) {
    printf("Surfaces differ in number of faces %d %d\n",
           surf1->nfaces,surf2->nfaces);
    exit(101);
  }

  //surf1->faces[10000].area = 100;
  //surf1->vertices[10000].x = 100;

  if (ComputeNormalDist) {
    double dist, dx, dy, dz, dot ;
    MRI    *mri_dist ;

    mri_dist = MRIalloc(surf1->nvertices,1,1,MRI_FLOAT) ;
    MRIScomputeMetricProperties(surf1) ;
    MRIScomputeMetricProperties(surf2) ;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      dx = vtx2->x-vtx1->x ;
      dy = vtx2->y-vtx1->y ;
      dz = vtx2->z-vtx1->z ;
      dist = sqrt(dx*dx + dy*dy + dz*dz) ;
      dot = dx*vtx1->nx + dy*vtx1->ny + dz*vtx1->nz ;
      dist = dist * dot / fabs(dot) ;
      MRIsetVoxVal(mri_dist, nthvtx, 0, 0, 0, dist) ;
    }
    MRIwrite(mri_dist, out_fname) ;
    MRIfree(&mri_dist) ;
    exit(0);
  }

  maxdiff=0;

  //------------------------------------------------------------
  if (CheckSurf) {
    printf("Comparing surfaces\n");

    // Loop over vertices ---------------------------------------
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      if (vtx1->ripflag != vtx2->ripflag) {
        printf("Vertex %d differs in ripflag %c %c\n",
               nthvtx,vtx1->ripflag,vtx2->ripflag);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      if (CheckXYZ) {
        diff=fabs(vtx1->x - vtx2->x);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in x %g %g\t(%g)\n",
                 nthvtx,vtx1->x,vtx2->x,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->y - vtx2->y);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in y %g %g\t(%g)\n",
                 nthvtx,vtx1->y,vtx2->y,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->z - vtx2->z);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in z %g %g\t(%g)\n",
                 nthvtx,vtx1->z,vtx2->z,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      if (CheckNXYZ) {
        diff=fabs(vtx1->nx - vtx2->nx);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in nx %g %g\t(%g)\n",
                 nthvtx,vtx1->nx,vtx2->nx,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->ny - vtx2->ny);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in ny %g %g\t(%g)\n",
                 nthvtx,vtx1->ny,vtx2->ny,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(vtx1->nz - vtx2->nz);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Vertex %d differs in nz %g %g\t(%g)\n",
                 nthvtx,vtx1->nz,vtx2->nz,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      nnbrs1 = surf1->vertices[nthvtx].vnum;
      nnbrs2 = surf2->vertices[nthvtx].vnum;
      if (nnbrs1 != nnbrs2) {
        printf("Vertex %d has a different number of neighbors %d %d\n",
               nthvtx,nnbrs1,nnbrs2);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      for (nthnbr=0; nthnbr < nnbrs1; nthnbr++) {
        nbrvtxno1 = surf1->vertices[nthvtx].v[nthnbr];
        nbrvtxno2 = surf2->vertices[nthvtx].v[nthnbr];
        if (nbrvtxno1 != nbrvtxno2) {
          printf("Vertex %d differs in the identity of the "
                 "%dth neighbor %d %d\n",nthvtx,nthnbr,nbrvtxno1,nbrvtxno2);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      if (error_count>=MAX_NUM_ERRORS) break;
    }// loop over vertices
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }

    // Loop over faces ----------------------------------------
    error_count=0;
    for (nthface=0; nthface < surf1->nfaces; nthface++) {
      face1 = &(surf1->faces[nthface]);
      face2 = &(surf2->faces[nthface]);
      if (CheckNXYZ) {
        diff=fabs(face1->nx - face2->nx);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in nx %g %g\t(%g)\n",
                 nthface,face1->nx,face2->nx,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(face1->ny - face2->ny);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in ny %g %g\t(%g)\n",
                 nthface,face1->ny,face2->ny,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
        diff=fabs(face1->nz - face2->nz);
        if (diff>maxdiff) maxdiff=diff;
        if (diff>thresh) {
          printf("Face %d differs in nz %g %g\t(%g)\n",
                 nthface,face1->nz,face2->nz,diff);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      }
      diff=fabs(face1->area - face2->area);
      if (diff>maxdiff) maxdiff=diff;
      if (diff>thresh) {
        printf("Face %d differs in area %g %g\t(%g)\n",
               nthface,face1->area,face2->area,diff);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      if (face1->ripflag != face2->ripflag) {
        printf("Face %d differs in ripflag %c %c\n",
               nthface,face1->ripflag,face2->ripflag);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
      for (nthvtx = 0; nthvtx < 3; nthvtx++) {
        if (face1->v[nthvtx] != face2->v[nthvtx]) {
          printf("Face %d differs in identity of %dth vertex %d %d\n",
                 nthface,nthvtx,face1->ripflag,face2->ripflag);
          if (++error_count>=MAX_NUM_ERRORS) break;
        }
      } // end loop over nthface vertex
      if (error_count>=MAX_NUM_ERRORS) break;
    } // end loop over faces
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }

    printf("Surfaces are the same\n");
    exit(0);
  } // end check surf

  // -----------------------------------------------------------------
  if (CheckCurv) {
    printf("Checking curv file %s\n",curvname);
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR1,subject1,hemi,curvname);
    printf("Loading curv file %s\n",tmpstr);
    if (MRISreadCurvatureFile(surf1, tmpstr) != 0) {
      printf("ERROR: reading curvature file %s\n",tmpstr);
      exit(1);
    }
    sprintf(tmpstr,"%s/%s/surf/%s.%s",SUBJECTS_DIR2,subject2,hemi,curvname);
    printf("Loading curv file %s\n",tmpstr);
    if (MRISreadCurvatureFile(surf2, tmpstr) != 0) {
      printf("ERROR: reading curvature file %s\n",tmpstr);
      exit(1);
    }
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      vtx1 = &(surf1->vertices[nthvtx]);
      vtx2 = &(surf2->vertices[nthvtx]);
      diff=fabs(vtx1->curv - vtx2->curv);
      if (diff>maxdiff) maxdiff=diff;
      if (diff > thresh) {
        printf("curv files differ at vertex %d %g %g\t(%g)\n",
               nthvtx,vtx1->curv,vtx2->curv,diff);
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
    } // end loop over vertices
    if (maxdiff>0) printf("maxdiff=%g\n",maxdiff);
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }
    printf("Curv files are the same\n");
    exit(0);
  } // end check curv

  // ---------------------------------------------------------
  if (CheckAParc) {
    printf("Checking AParc %s\n",aparcname);
    sprintf(tmpstr,"%s/%s/label/%s.%s.annot",
            SUBJECTS_DIR1,subject1,hemi,aparcname);
    printf("Loading aparc file %s\n",tmpstr);
    fflush(stdout);
    if (MRISreadAnnotation(surf1, tmpstr)) {
      printf("ERROR: MRISreadAnnotation() failed %s\n",tmpstr);
      exit(1);
    }
    if (aparc2name) aparcname = aparc2name;
    sprintf(tmpstr,"%s/%s/label/%s.%s.annot",
            SUBJECTS_DIR2,subject2,hemi,aparcname);
    printf("Loading aparc file %s\n",tmpstr);
    fflush(stdout);
    if (MRISreadAnnotation(surf2, tmpstr)) {
      printf("ERROR: MRISreadAnnotation() failed %s\n",tmpstr);
      exit(1);
    }
    error_count=0;
    for (nthvtx=0; nthvtx < surf1->nvertices; nthvtx++) {
      annot1 = surf1->vertices[nthvtx].annotation;
      annot2 = surf2->vertices[nthvtx].annotation;
      if (annot1 != annot2) {
        printf("aparc files differ at vertex %d: 1:%s 2:%s\n",
               nthvtx,
               CTABgetAnnotationName(surf1->ct,annot1),
               CTABgetAnnotationName(surf2->ct,annot2));
        if (++error_count>=MAX_NUM_ERRORS) break;
      }
    } // end loop over vertices
    if (error_count > 0) {
      printf("Exiting after finding %d errors\n",error_count);
      if (error_count>=MAX_NUM_ERRORS) {
        printf("Exceeded MAX_NUM_ERRORS loop guard\n");
      }
      exit(103);
    }
    printf("\n"
           "AParc files are the same\n"
           "------------------------\n");
    exit(0);
  }

  return 0;
}
Example #12
0
/* --------------------------------------------------------------
   regio_read_mincxfm() - reads a 3x4 transform as the last three
   lines of the xfmfile. Blank lines at the end will defeat it.
   If fileinfo != NULL, reads in the "fileinfo". This is the 3rd
   line in the minc xfm file. It will contain information about
   the center of the transform (-center). This is used by
   ltaMNIreadEx() to account for the non-zero center of the MNI
   talairach template. If the center infomation is not there,
   ltaMNIreadEx() assumes that the center is 0 and will produce
   the wrong transform. Thus, if one is going to write out the
   xfm, then one needs to keep track of this information when
   reading it in. regio_write_mincxfm() takes fileinfo as an
   argument. If one is not going to write out the xfm, then
   simply set fileinfo to NULL.
   -------------------------------------------------------------- */
int regio_read_mincxfm(char *xfmfile, MATRIX **R, char **fileinfo)
{
  FILE *fp;
  char tmpstr[1000];
  int r,c,n,nlines;
  float val;

  memset(tmpstr,'\0',1000);

  fp = fopen(xfmfile,"r");
  if (fp==NULL)
  {
    perror("regio_read_mincxfm");
    printf("ERROR: could not read %s\n",xfmfile);
    return(1);
  }

  fgetl(tmpstr, 900, fp) ;  /* MNI Transform File */
  if (strncmp("MNI Transform File", tmpstr, 18))
  {
    printf("ERROR: %s does not start as 'MNI Transform File'",xfmfile);
    return(1);
  }

  fgetl(tmpstr, 900, fp) ;   /* fileinfo */
  if (fileinfo != NULL)
  {
    *fileinfo = strcpyalloc(tmpstr);
    printf("\n%s\n\n",*fileinfo);
  }
  else printf("Not reading in xfm fileinfo\n");

  // Close it and open it up again to rewind it
  fclose(fp);
  fp = fopen(xfmfile,"r");

  /* Count the number of lines */
  nlines = 0;
  while (fgets(tmpstr,1000,fp) != NULL) nlines ++;
  rewind(fp);

  /* skip all but the last 3 lines */
  for (n=0;n<nlines-3;n++) fgets(tmpstr,1000,fp);

  *R = MatrixAlloc(4,4,MATRIX_REAL);
  if (*R == NULL)
  {
    fprintf(stderr,"regio_read_mincxfm(): could not alloc R\n");
    fclose(fp);
    return(1);
  }
  MatrixClear(*R);

  /* registration matrix */
  for (r=0;r<3;r++)
  { /* note: upper limit = 3 for xfm */
    for (c=0;c<4;c++)
    {
      n = fscanf(fp,"%f",&val);
      if (n != 1)
      {
        perror("regio_read_mincxfm()");
        fprintf(stderr,"Error reading R[%d][%d] from %s\n",r,c,xfmfile);
        fclose(fp);
        return(1);
      }
      (*R)->rptr[r+1][c+1] = val;
      /*printf("%7.4f ",val);*/
    }
    /*printf("\n");*/
  }
  (*R)->rptr[3+1][3+1] = 1.0;

  fclose(fp);
  return(0);
}
Example #13
0
int
main(int argc, char *argv[])
{
  char         **av, fname[STRLEN] ;
  int          ac, nargs, i ;
  char         *subject, *cp, mdir[STRLEN], *out_fname, *name ;
  int          r, g, b, nedits = 0 ;
  MRI          *mri=NULL, *mri_edits=NULL, *mri_aseg_auto=NULL;

  // default output file name:
  out_fname = strcpyalloc("edits.mgz");

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
    (argc, argv,
     "$Id: mri_compile_edits.c,v 1.6 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) ;

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

  if (argc < 2)
    usage_exit(1) ;

  if (strlen(sdir) == 0)
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (cp == NULL)
      ErrorExit
        (ERROR_BADPARM,
         "%s: SUBJECTS_DIR must be defined in the env or on cmdline "
         "with -sdir", Progname) ;
    strcpy(sdir, cp) ;
  }

  subject = argv[1] ;
  if (argv[2]) out_fname = argv[2] ;
  printf("Compiling volume edits for subject %s...\n", subject) ;
  fflush(stdout);

  sprintf(mdir, "%s/%s/mri", sdir, subject) ;

  /*
   * brain.mgz
   */
  sprintf(fname, "%s/brain.mgz", mdir) ;
  mri = MRIread(fname) ;
  if (mri)
  {
    if(NULL == mri_edits) mri_edits = MRIclone(mri, NULL) ;
    int edits = MRIsetVoxelsWithValue(mri,
                                      mri_edits,
                                      WM_EDITED_OFF_VAL,
                                      EDIT_BRAIN_OFF) ;
    edits += MRIsetVoxelsWithValue(mri,
                                   mri_edits,
                                   WM_EDITED_ON_VAL,
                                   EDIT_BRAIN_ON) ;
    nedits += edits;
    MRIfree(&mri) ;
    if (edits) printf("Found %d edits in brain.mgz\n",edits);
    fflush(stdout);
  }

  /*
   * wm.mgz
   */
  sprintf(fname, "%s/wm.mgz", mdir) ;
  mri = MRIread(fname) ;
  if (mri)
  {
    if(NULL == mri_edits) mri_edits = MRIclone(mri, NULL) ;
    int edits = MRIsetVoxelsWithValue(mri,
                                      mri_edits,
                                      WM_EDITED_OFF_VAL,
                                      EDIT_WM_OFF) ;
    edits += MRIsetVoxelsWithValue(mri, mri_edits,
                                   WM_EDITED_ON_VAL,
                                   EDIT_WM_ON) ;
    nedits += edits;
    MRIfree(&mri) ;
    if (edits) printf("Found %d edits in wm.mgz\n",edits);
    fflush(stdout);
  }

  /*
   * brainmask.mgz
   */
  sprintf(fname, "%s/brainmask.mgz", mdir) ;
  mri = MRIread(fname) ;
  if (mri)
  {
    if(NULL == mri_edits) mri_edits = MRIclone(mri, NULL) ;
    int edits = MRIsetVoxelsWithValue(mri,
                                      mri_edits,
                                      WM_EDITED_OFF_VAL,
                                      EDIT_BRAINMASK_OFF) ;
    edits += MRIsetVoxelsWithValue(mri, mri_edits,
                                   WM_EDITED_ON_VAL,
                                   EDIT_BRAINMASK_ON) ;
    nedits += edits;
    MRIfree(&mri) ;
    if (edits) printf("Found %d edits in brainmask.mgz\n",edits);
    fflush(stdout);
  }

  /*
   * brain.finalsurfs.mgz
   */
  sprintf(fname, "%s/brain.finalsurfs.mgz", mdir) ;
  mri = MRIread(fname) ;
  if (mri)
  {
    if(NULL == mri_edits) mri_edits = MRIclone(mri, NULL) ;
    int edits = MRIsetVoxelsWithValue(mri,
                                      mri_edits,
                                      WM_EDITED_OFF_VAL,
                                      EDIT_FINALSURFS_OFF) ;
    edits += MRIsetVoxelsWithValue(mri,
                                   mri_edits,
                                   WM_EDITED_ON_VAL,
                                   EDIT_FINALSURFS_ON) ;
    nedits += edits;
    MRIfree(&mri) ;
    if (edits) printf("Found %d edits in brain.finalsurfs.mgz\n",edits);
    fflush(stdout);
  }

  /*
   * aseg.mgz
   */
  sprintf(fname, "%s/aseg.mgz", mdir) ;
  mri = MRIread(fname) ;
  if (mri)
  {
    if(NULL == mri_edits) mri_edits = MRIclone(mri, NULL) ;
    sprintf(fname, "%s/aseg.auto.mgz", mdir) ;
    mri_aseg_auto = MRIread(fname) ;
    if (mri_aseg_auto)
    {
      int edits = MRIsetDifferentVoxelsWithValue(mri,
                                                 mri_aseg_auto,
                                                 mri_edits,
                                                 EDIT_ASEG_CHANGED);
      nedits += edits;
      MRIfree(&mri) ;
      MRIfree(&mri_aseg_auto) ;
      if (edits) printf("Found %d edits in aseg.mgz\n",edits);
      fflush(stdout);
    }
  }

  if (mri_edits)
  {
    mri_edits->ct = CTABalloc(CTAB_ENTRIES) ;
    strcpy (mri_edits->fname, "mri_compile_edits");
    for (i = 0 ; i < CTAB_ENTRIES ; i++)
    {
      switch (i)
      {
      case EDIT_WM_OFF:
        name = "wm-OFF" ;
        r = 0 ;
        g = 0 ;
        b = 255 ;
        break ;
      case EDIT_WM_ON:
        name = "wm-ON" ;
        r = 255 ;
        g = 0 ;
        b = 0 ;
        break ;
      case EDIT_BRAIN_OFF:
        name = "brain-OFF" ;
        r = 0 ;
        g = 255 ;
        b = 255 ;
        break ;
      case EDIT_BRAIN_ON:
        name = "brain-ON" ;
        r = 255 ;
        g = 255 ;
        b = 0 ;
        break ;
      case EDIT_BRAINMASK_OFF:
        name = "brainmask-OFF" ;
        r = 0 ;
        g = 64 ;
        b = 255 ;
        break ;
      case EDIT_BRAINMASK_ON:
        name = "brainmask-ON" ;
        r = 255 ;
        g = 26 ;
        b = 0 ;
        break ;
      case EDIT_FINALSURFS_OFF:
        name = "brain.finalsurf-OFF" ;
        r = 0 ;
        g = 128 ;
        b = 255 ;
        break ;
      case EDIT_FINALSURFS_ON:
        name = "brain.finalsurfs-ON" ;
        r = 255 ;
        g = 128 ;
        b = 0 ;
        break ;
      case EDIT_ASEG_CHANGED:
        name = "aseg-CHANGED" ;
        r = 255 ;
        g = 255 ;
        b = 128 ;
        break ;
      default:
        continue ;
      }

      strcpy(mri_edits->ct->entries[i]->name, name) ;
      mri_edits->ct->entries[i]->ri = r ;
      mri_edits->ct->entries[i]->gi = g ;
      mri_edits->ct->entries[i]->bi = b ;
      mri_edits->ct->entries[i]->ai = 255;

      /* Now calculate the float versions. */
      mri_edits->ct->entries[i]->rf =
        (float)mri_edits->ct->entries[i]->ri / 255.0;
      mri_edits->ct->entries[i]->gf =
        (float)mri_edits->ct->entries[i]->gi / 255.0;
      mri_edits->ct->entries[i]->bf =
        (float)mri_edits->ct->entries[i]->bi / 255.0;
      mri_edits->ct->entries[i]->af =
        (float)mri_edits->ct->entries[i]->ai / 255.0;
    }
  }

  // recon-all -show-edits greps on this text, so dont change it
  if (nedits && mri_edits)
  {
    printf("%d mri_compile_edits_found, saving results to %s\n",
           nedits, out_fname) ;
    MRIwrite(mri_edits, out_fname);
    printf("Edits can be viewed with command:\n");
    printf("tkmedit %s T1.mgz -segmentation %s\n",subject,out_fname);
  }
  else
  {
    printf("0 mri_compile_edits_found\n") ;
  }

  exit(0) ;
  return(0) ;
}
Example #14
0
/*----------------------------------------------------------------------
  Parameters:

  Description:
----------------------------------------------------------------------*/
static int
get_option(int argc, char *argv[])
{
  int    n,nargs = 0 ;
  char   *option ;
  float  f ;

  option = argv[1] + 1 ;            /* past '-' */
  if (!stricmp(option, "-help")||!stricmp(option, "-usage"))
  {
    print_help() ;
  }
  else if (!stricmp(option, "-version"))
  {
    print_version() ;
  }
  else if (!stricmp(option, "median"))
  {
    which_norm = NORM_MEDIAN ;
    printf("using median normalization\n") ;
  }
  else if (!stricmp(option, "vnum") || !stricmp(option, "distances"))
  {
    parms.nbhd_size = atof(argv[2]) ;
    parms.max_nbrs = atof(argv[3]) ;
    nargs = 2 ;
    fprintf(stderr, "nbr size = %d, max neighbors = %d\n",
            parms.nbhd_size, parms.max_nbrs) ;
  }
  else if (!stricmp(option, "nonorm"))
  {
    which_norm = NORM_NONE ;
    printf("disabling normalization\n") ;
  }
  else if (!stricmp(option, "vsmooth"))
  {
    parms.var_smoothness = 1 ;
    printf("using space/time varying smoothness weighting\n") ;
  }
  else if (!stricmp(option, "sigma"))
  {
    if (nsigmas >= MAX_SIGMAS)
    {
      ErrorExit(ERROR_NOMEMORY, "%s: too many sigmas specified (%d)\n",
                Progname, nsigmas) ;
    }
    sigmas[nsigmas] = atof(argv[2]) ;
    nargs = 1 ;
    nsigmas++ ;
  }
  else if (!stricmp(option, "vector"))
  {
    fprintf(stderr,
            "\nMultiframe Mode:\n");
    fprintf(stderr,
            "Use -addframe option to add extra-fields into average atlas\n");
    fprintf(stderr,
            "\t-addframe which_field where_in_atlas l_corr l_pcorr\n");
    fprintf(stderr,
            "\tfield code:\n");
    for (n=0 ; n < NUMBER_OF_VECTORIAL_FIELDS ; n++)
      fprintf(stderr,
              "\t      field %d is '%s' (type = %d)\n",
              n,ReturnFieldName(n),IsDistanceField(n));
    exit(1);
  }
  else if (!stricmp(option, "annot"))
  {
    annot_name = argv[2] ;
    fprintf(stderr,"zeroing medial wall in %s\n", annot_name) ;
    nargs=1;
  }
  else if (!stricmp(option, "init"))
  {
    use_initial_registration=1;
    fprintf(stderr,"use initial registration\n");
  }
  else if (!stricmp(option, "addframe"))
  {
    int which_field,where_in_atlas;
    float l_corr,l_pcorr;

    if (multiframes==0)
    {
      /* activate multiframes mode */
      initParms();
      multiframes = 1;
    }

    which_field=atoi(argv[2]);
    where_in_atlas=atoi(argv[3]);
    l_corr=atof(argv[4]);
    l_pcorr=atof(argv[5]);

    fprintf(stderr,
            "adding field %d (%s) with location %d in the atlas\n",
            which_field,ReturnFieldName(which_field),where_in_atlas) ;
    /* check if this field exist or not */
    for (n = 0 ; n < parms.nfields ; n++)
    {
      if (parms.fields[n].field==which_field)
      {
        fprintf(stderr,"ERROR: field already exists\n");
        exit(1);
      }
    }
    /* adding field into parms */
    n=parms.nfields++;
    SetFieldLabel(&parms.fields[n],
                  which_field,
                  where_in_atlas,
                  l_corr,
                  l_pcorr,
                  0,
                  which_norm);
    nargs = 4 ;
  }
  /* else if (!stricmp(option, "hippocampus")) */
  /*   { */
  /*   if(multiframes==0){ */
  /*    multiframes = 1 ; */
  /*    initParms(); */
  /*   } */
  /*   where=atoi(argv[2]); */
  /*   parms.l_corrs[]=atof(argv[3]); */
  /*   parms.l_pcorrs[]=atof(argv[4]); */
  /*   parms.frames[]=; */
  /*   parms. */
  /*     fprintf(stderr, "using hippocampus distance map\n") ; */
  /*   nargs=3; */
  /*   } */
  else if (!stricmp(option, "topology"))
  {
    parms.flags |= IPFLAG_PRESERVE_SPHERICAL_POSITIVE_AREA;
    fprintf(stderr, "preserving the topology of positive area triangles\n");
  }
  else if (!stricmp(option, "vnum") || !stricmp(option, "distances"))
  {
    parms.nbhd_size = atof(argv[2]) ;
    parms.max_nbrs = atof(argv[3]) ;
    nargs = 2 ;
    fprintf(stderr, "nbr size = %d, max neighbors = %d\n",
            parms.nbhd_size, parms.max_nbrs) ;
  }
  else if (!stricmp(option, "rotate"))
  {
    dalpha = atof(argv[2]) ;
    dbeta = atof(argv[3]) ;
    dgamma = atof(argv[4]) ;
    fprintf(stderr, "rotating brain by (%2.2f, %2.2f, %2.2f)\n",
            dalpha, dbeta, dgamma) ;
    nargs = 3 ;
  }
  else if (!stricmp(option, "reverse"))
  {
    reverse_flag = 1 ;
    fprintf(stderr, "mirror image reversing brain before morphing...\n") ;
  }
  else if (!stricmp(option, "min_degrees"))
  {
    min_degrees = atof(argv[2]) ;
    fprintf(stderr,
            "setting min angle for search to %2.2f degrees\n",
            min_degrees) ;
    nargs = 1 ;
  }
  else if (!stricmp(option, "max_degrees"))
  {
    max_degrees = atof(argv[2]) ;
    fprintf(stderr,
            "setting max angle for search to %2.2f degrees\n",
            max_degrees) ;
    nargs = 1 ;
  }
  else if (!stricmp(option, "nangles"))
  {
    nangles = atoi(argv[2]) ;
    fprintf(stderr, "setting # of angles/search per scale to %d\n", nangles) ;
    nargs = 1 ;
  }
  else if (!stricmp(option, "jacobian"))
  {
    jacobian_fname = argv[2] ;
    nargs = 1 ;
    printf("writing out jacobian of mapping to %s\n", jacobian_fname) ;
  }
  else if (!stricmp(option, "dist"))
  {
    sscanf(argv[2], "%f", &parms.l_dist) ;
    nargs = 1 ;
    use_defaults = 0 ;
    fprintf(stderr, "l_dist = %2.3f\n", parms.l_dist) ;
  }
  else if (!stricmp(option, "norot"))
  {
    fprintf(stderr, "disabling initial rigid alignment...\n") ;
    parms.flags |= IP_NO_RIGID_ALIGN ;
  }
  else if (!stricmp(option, "inflated"))
  {
    fprintf(stderr, "using inflated surface for initial alignment\n") ;
    parms.flags |= IP_USE_INFLATED ;
  }
  else if (!stricmp(option, "multi_scale"))
  {
    multi_scale = atoi(argv[2]) ;
    fprintf(stderr, "using %d scales for morphing\n", multi_scale) ;
    nargs = 1 ;
  }
  else if (!stricmp(option, "nsurfaces"))
  {
    parms.nsurfaces = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr,
            "using %d surfaces/curvatures for alignment\n",
            parms.nsurfaces) ;
  }
  else if (!stricmp(option, "infname"))
  {
    char fname[STRLEN] ;
    inflated_name = argv[2] ;
    surface_names[0] = argv[2] ;
    nargs = 1 ;
    printf("using %s as inflated surface name, "
           "and using it for initial alignment\n", inflated_name) ;
    sprintf(fname, "%s.H", argv[2]) ;
    curvature_names[0] = (char *)calloc(strlen(fname)+1, sizeof(char)) ;
    strcpy(curvature_names[0], fname) ;
    parms.flags |= IP_USE_INFLATED ;
  }
  else if (!stricmp(option, "nosulc"))
  {
    fprintf(stderr, "disabling initial sulc alignment...\n") ;
    parms.flags |= IP_NO_SULC ;
  }
  else if (!stricmp(option, "sulc"))
  {
    curvature_names[1] = argv[2] ;
    fprintf(stderr, "using %s to replace 'sulc' alignment\n",
            curvature_names[1]) ;
    nargs = 1 ;
    MRISsetSulcFileName(argv[2]);
  }

  else if (!stricmp(option, "surf0"))
  {
    surface_names[0]       = argv[2];
    fprintf(stderr, "using %s as input surface 0.\n",
            surface_names[0]) ;
    nargs = 1 ;
  }

  else if (!stricmp(option, "surf1"))
  {
    surface_names[1]       = argv[2];
    fprintf(stderr, "using %s as input surface 1.\n",
            surface_names[1]) ;
    nargs = 1 ;
  }

  else if (!stricmp(option, "surf2"))
  {
    surface_names[2]       = argv[2];
    fprintf(stderr, "using %s as input surface 2.\n",
            surface_names[2]) ;
    nargs = 1 ;
  }

  else if (!stricmp(option, "curv0"))
  {
    curvature_names[0]  = argv[2];
    fprintf(stderr, "using %s as curvature function for surface 0.\n",
            curvature_names[0]) ;
    nargs = 1 ;
  }

  else if (!stricmp(option, "curv1"))
  {
    curvature_names[1]  = argv[2];
    fprintf(stderr, "using %s as curvature function for surface 1.\n",
            curvature_names[1]) ;
    nargs = 1 ;
  }

  else if (!stricmp(option, "curv2"))
  {
    curvature_names[2]  = argv[2];
    fprintf(stderr, "using %s as curvature function for surface 2.\n",
            curvature_names[2]) ;
    nargs = 1 ;
  }


  else if (!stricmp(option, "lm"))
  {
    parms.integration_type = INTEGRATE_LINE_MINIMIZE ;
    fprintf(stderr, "integrating with line minimization\n") ;
  }
  else if (!stricmp(option, "search"))
  {
    parms.integration_type = INTEGRATE_LM_SEARCH ;
    fprintf(stderr, "integrating with binary search line minimization\n") ;
  }
  else if (!stricmp(option, "dt"))
  {
    parms.dt = atof(argv[2]) ;
    parms.base_dt = .2*parms.dt ;
    nargs = 1 ;
    fprintf(stderr, "momentum with dt = %2.2f\n", parms.dt) ;
  }
  else if (!stricmp(option, "area"))
  {
    use_defaults = 0 ;
    sscanf(argv[2], "%f", &parms.l_area) ;
    nargs = 1 ;
    fprintf(stderr, "using l_area = %2.3f\n", parms.l_area) ;
  }
  else if (!stricmp(option, "parea"))
  {
    use_defaults = 0 ;
    sscanf(argv[2], "%f", &parms.l_parea) ;
    nargs = 1 ;
    fprintf(stderr, "using l_parea = %2.3f\n", parms.l_parea) ;
  }
  else if (!stricmp(option, "nlarea"))
  {
    use_defaults = 0 ;
    sscanf(argv[2], "%f", &parms.l_nlarea) ;
    nargs = 1 ;
    fprintf(stderr, "using l_nlarea = %2.3f\n", parms.l_nlarea) ;
  }
  else if (!stricmp(option, "spring"))
  {
    use_defaults = 0 ;
    sscanf(argv[2], "%f", &parms.l_spring) ;
    nargs = 1 ;
    fprintf(stderr, "using l_spring = %2.3f\n", parms.l_spring) ;
  }
  else if (!stricmp(option, "corr"))
  {
    use_defaults = 0 ;
    sscanf(argv[2], "%f", &parms.l_corr) ;
    nargs = 1 ;
    fprintf(stderr, "using l_corr = %2.3f\n", parms.l_corr) ;
  }
  else if (!stricmp(option, "remove_negative"))
  {
    remove_negative = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "%sremoving negative triangles with iterative smoothing\n",
            remove_negative ? "" : "not ") ;
  }
  else if (!stricmp(option, "curv"))
  {
    parms.flags |= IP_USE_CURVATURE ;
    fprintf(stderr, "using smoothwm curvature for final alignment\n") ;
  }
  else if (!stricmp(option, "nocurv"))
  {
    parms.flags &= ~IP_USE_CURVATURE ;
    fprintf(stderr, "NOT using smoothwm curvature for final alignment\n") ;
  }
  else if (!stricmp(option, "sreg"))
  {
    starting_reg_fname = argv[2] ;
    nargs = 1 ;
    fprintf(stderr, "starting registration with coordinates in  %s\n",
            starting_reg_fname) ;
  }
  else if (!stricmp(option, "adaptive"))
  {
    parms.integration_type = INTEGRATE_ADAPTIVE ;
    fprintf(stderr, "using adaptive time step integration\n") ;
  }
  else if (!stricmp(option, "nbrs"))
  {
    nbrs = atoi(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "using neighborhood size=%d\n", nbrs) ;
  }
  else if (!stricmp(option, "tol"))
  {
    if (sscanf(argv[2], "%e", &f) < 1)
      ErrorExit(ERROR_BADPARM, "%s: could not scan tol from %s",
                Progname, argv[2]) ;
    parms.tol = (double)f ;
    nargs = 1 ;
    fprintf(stderr, "using tol = %2.2e\n", (float)parms.tol) ;
  }
  else if (!stricmp(option, "error_ratio"))
  {
    parms.error_ratio = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "error_ratio=%2.3f\n", parms.error_ratio) ;
  }
  else if (!stricmp(option, "dt_inc"))
  {
    parms.dt_increase = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "dt_increase=%2.3f\n", parms.dt_increase) ;
  }
  else if (!stricmp(option, "lap") || !stricmp(option, "lap"))
  {
    parms.l_lap = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "l_laplacian = %2.3f\n", parms.l_lap) ;
  }
  else if (!stricmp(option, "vnum"))
  {
    parms.nbhd_size = atof(argv[2]) ;
    parms.max_nbrs = atof(argv[3]) ;
    nargs = 2 ;
    fprintf(stderr, "nbr size = %d, max neighbors = %d\n",
            parms.nbhd_size, parms.max_nbrs) ;
  }
  else if (!stricmp(option, "dt_dec"))
  {
    parms.dt_decrease = atof(argv[2]) ;
    nargs = 1 ;
    fprintf(stderr, "dt_decrease=%2.3f\n", parms.dt_decrease) ;
  }
  else if (!stricmp(option, "ocorr"))
  {
    l_ocorr = atof(argv[2]) ;
    printf("setting overlay correlation coefficient to %2.1f\n", l_ocorr) ;
    nargs = 1 ;
    fprintf(stderr, "dt_decrease=%2.3f\n", parms.dt_decrease) ;
  }
  else if (!stricmp(option, "overlay"))
  {
    int navgs ;
    if (noverlays == 0)
    {
      atlas_size = 0 ;
    }
    if (multiframes == 0)
    {
      initParms() ;
      multiframes = 1 ;
    }
    overlays[noverlays++] = argv[2] ;
    navgs = atof(argv[3]) ;
    printf("reading overlay from %s and smoothing it %d times\n",
           argv[2], navgs) ;
    n=parms.nfields++;
    SetFieldLabel(&parms.fields[n],
                  OVERLAY_FRAME,
                  atlas_size,
                  l_ocorr,
                  0.0,
                  navgs,
                  which_norm);
    SetFieldName(&parms.fields[n], argv[2]) ;
    atlas_size++ ;
    nargs = 2 ;
  }
  else if (!stricmp(option, "distance"))
  {
    int navgs ;
    if (noverlays == 0)
    {
      atlas_size = 0 ;
    }
    if (multiframes == 0)
    {
      initParms() ;
      multiframes = 1 ;
    }
    overlays[noverlays++] = argv[2] ;
    navgs = atof(argv[3]) ;
    printf("reading overlay from %s and smoothing it %d times\n",
           argv[2], navgs) ;
    n=parms.nfields++;
    SetFieldLabel(&parms.fields[n],
                  DISTANCE_TRANSFORM_FRAME,
                  atlas_size,
                  l_ocorr,
                  0.0,
                  navgs,
                  NORM_MAX) ;
    SetFieldName(&parms.fields[n], argv[2]) ;
    atlas_size++ ;
    nargs = 2 ;
  }
  else if (!stricmp(option, "canon"))
  {
    canon_name = argv[2] ;
    nargs = 1 ;
    fprintf(stderr, "using %s for canonical properties...\n", canon_name) ;
  }
  else if (!stricmp(option, "overlay-dir"))
  {
    parms.overlay_dir = strcpyalloc(argv[2]) ;
    nargs = 1 ;
  }
  else switch (toupper(*option))
    {
    case 'M':
      parms.integration_type = INTEGRATE_MOMENTUM ;
      parms.momentum = atof(argv[2]) ;
      nargs = 1 ;
      fprintf(stderr, "momentum = %2.2f\n", (float)parms.momentum) ;
      break ;
    case 'L':
      if (nlabels >= MAX_LABELS-1)
        ErrorExit(ERROR_NO_MEMORY,
                  "%s: too many labels specified (%d max)",
                  Progname, MAX_LABELS) ;
      nargs = 3 ;
      labels[nlabels] = LabelRead(NULL, argv[2]) ;
      if (labels[nlabels] == NULL)
        ErrorExit(ERROR_NOFILE,
                  "%s: could not read label file %s",
                  Progname, argv[2]) ;
      label_gcsa[nlabels] = GCSAread(argv[3]) ;
      if (label_gcsa[nlabels] == NULL)
        ErrorExit(ERROR_NOFILE,
                  "%s: could not read GCSA file %s",
                  Progname, argv[3]) ;
      label_names[nlabels] = argv[4] ;
      CTABfindName(label_gcsa[nlabels]->ct, argv[4],&label_indices[nlabels]) ;

      if (label_indices[nlabels] < 0)
        ErrorExit(ERROR_NOFILE,
                  "%s: could not map name %s to index",
                  Progname, argv[3]) ;
      CTABannotationAtIndex(label_gcsa[nlabels]->ct, label_indices[nlabels],
                            &label_annots[nlabels]);
      nlabels++ ;
      gMRISexternalSSE = gcsaSSE ;
      break ;
    case 'E':
      parms.l_external = atof(argv[2]) ;
      nargs = 1 ;
      printf("setting l_external = %2.1f\n", parms.l_external) ;
      break ;
    case 'C':
      strcpy(curvature_fname, argv[2]) ;
      nargs = 1 ;
      break ;
    case 'A':
      sscanf(argv[2], "%d", &parms.n_averages) ;
      nargs = 1 ;
      fprintf(stderr, "using n_averages = %d\n", parms.n_averages) ;
      break ;
    case '1':
      single_surf = True ;
      printf("treating target as a single subject's surface...\n") ;
      break ;
    case 'S':
      scale = atof(argv[2]) ;
      fprintf(stderr, "scaling distances by %2.2f\n", scale) ;
      nargs = 1 ;
      break ;
    case 'N':
      sscanf(argv[2], "%d", &parms.niterations) ;
      nargs = 1 ;
      fprintf(stderr, "using niterations = %d\n", parms.niterations) ;
      break ;
    case 'W':
      Gdiag |= DIAG_WRITE ;
      sscanf(argv[2], "%d", &parms.write_iterations) ;
      nargs = 1 ;
      fprintf(stderr,
              "using write iterations = %d\n",
              parms.write_iterations) ;
      break ;
    case 'V':
      Gdiag_no = atoi(argv[2]) ;
      nargs = 1 ;
      break ;
    case 'O':
      orig_name = argv[2] ;
      nargs = 1 ;
      fprintf(stderr, "using %s for original properties...\n", orig_name) ;
      break ;
    case 'P':
      max_passes = atoi(argv[2]) ;
      fprintf(stderr, "limiting unfolding to %d passes\n", max_passes) ;
      nargs = 1 ;
      break ;
    case '?':
    case 'H':
    case 'U':
      print_help() ;
      exit(1) ;
      break ;
    default:
      fprintf(stderr, "unknown option %s\n", argv[1]) ;
      exit(1) ;
      break ;
    }

  return(nargs) ;
}
Example #15
0
/* --------------------------------------------- */
static void check_options(void) {
  int n;

  if (subject == NULL) {
    printf("ERROR: need to specify subject\n");
    exit(1);
  }
  if (hemi == NULL) {
    printf("ERROR: need to specify hemi\n");
    exit(1);
  }
  if (CTabFile == NULL) {
    printf("ERROR: need to specify color table file\n");
    exit(1);
  }
  if(AnnotName && AnnotPath) {
    printf("ERROR: cannot spec both --annot and --annot-path\n");
    exit(1);
  }
  if(AnnotName == NULL && AnnotPath == NULL) {
    printf("ERROR: need to specify annotation name\n");
    exit(1);
  }

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

  // Read the color table
  printf("Reading ctab %s\n",CTabFile);
  ctab = CTABreadASCII(CTabFile);
  if (ctab == NULL) {
    printf("ERROR: reading %s\n",CTabFile);
    exit(1);
  }
  if (dilate_label_name)
  {
    CTABfindName(ctab, dilate_label_name, &dilate_label_index) ;
    CTABannotationAtIndex(ctab, dilate_label_index, &dilate_label_annot);
    printf("label %s maps to index %d, annot %x\n",
           dilate_label_name, dilate_label_index, dilate_label_annot) ;
  }
  printf("Number of ctab entries %d\n",ctab->nentries);
  if (nlabels == 0) {
    printf("INFO: no labels specified, generating from ctab\n");
    if (labeldir == NULL) labeldir = ".";
    if (labeldirdefault) {
      sprintf(tmpstr,"%s/%s/label",SUBJECTS_DIR,subject);
      labeldir = strcpyalloc(tmpstr);
    }
    nlabels = ctab->nentries;
    for (n=0; n<nlabels; n++) {
      sprintf(tmpstr,"%s/%s.%s.label",labeldir,hemi,ctab->entries[n]->name);
      printf("%2d %s\n",n,tmpstr);
      LabelFiles[n] = strcpyalloc(tmpstr);
    }
  }
  return;
}
Example #16
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, nthlabel, n, vtxno, ano, index, nunhit;

  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);

  // Make sure subject exists
  sprintf(tmpstr,"%s/%s",SUBJECTS_DIR,subject);
  if (!fio_IsDirectory(tmpstr)) {
    printf("ERROR: cannot find %s\n",tmpstr);
    exit(1);
  }

  if(AnnotPath == NULL){
    // Get path to annot, make sure it does not exist
    sprintf(tmpstr,"%s/%s/label/%s.%s.annot",
	    SUBJECTS_DIR,subject,hemi,AnnotName);
    if (fio_FileExistsReadable(tmpstr)) {
      printf("ERROR: %s already exists\n",tmpstr);
      exit(1);
    }
    AnnotPath = strcpyalloc(tmpstr);
  }

  // Read the surf
  sprintf(tmpstr,"%s/%s/surf/%s.orig",SUBJECTS_DIR,subject,hemi);
  printf("Loading %s\n",tmpstr);
  mris = MRISread(tmpstr);
  if (mris == NULL) exit(1);

  // Set up color table
  set_atable_from_ctable(ctab);
  mris->ct = ctab;

  // Set up something to keep track of nhits
  nhits = MRIalloc(mris->nvertices,1,1,MRI_INT);

  // Set up something to keep track of max stat for that vertex
  if (maxstatwinner) maxstat = MRIalloc(mris->nvertices,1,1,MRI_FLOAT);

  // Go thru each label
  for (nthlabel = 0; nthlabel < nlabels; nthlabel ++) {
    label = LabelRead(subject,LabelFiles[nthlabel]);
    if (label == NULL) {
      printf("ERROR: reading %s\n",LabelFiles[nthlabel]);
      exit(1);
    }
    index = nthlabel;
    if (MapUnhitToUnknown) index ++;
    ano = index_to_annotation(index);
    printf("%2d %2d %s\n",index,ano,index_to_name(index));

    for (n = 0; n < label->n_points; n++) {
      vtxno = label->lv[n].vno;
      if (vtxno < 0 || vtxno > mris->nvertices) {
        printf("ERROR: %s, n=%d, vertex %d out of range\n",
               LabelFiles[nthlabel],n,vtxno);
        exit(1);
      }
      if(DoLabelThresh && label->lv[n].stat < LabelThresh) continue;

      if (maxstatwinner) {
        float stat = MRIgetVoxVal(maxstat,vtxno,0,0,0);
        if (label->lv[n].stat < stat) {
          if (verbose) {
            printf("Keeping prior label for vtxno %d "
                   "(old_stat=%f > this_stat=%f)\n",
                   vtxno,stat,label->lv[n].stat);
          }
          continue;
        }
        MRIsetVoxVal(maxstat,vtxno,0,0,0,label->lv[n].stat);
      }

      if (verbose) {
        if (MRIgetVoxVal(nhits,vtxno,0,0,0) > 0) {
          printf
            ("WARNING: vertex %d maps to multiple labels! (overwriting)\n",
             vtxno);
        }
      }
      MRIsetVoxVal(nhits,vtxno,0,0,0,MRIgetVoxVal(nhits,vtxno,0,0,0)+1);

      mris->vertices[vtxno].annotation = ano;
      //printf("%5d %2d %2d %s\n",vtxno,segid,ano,index_to_name(segid));
    } // label ponts
    LabelFree(&label);
  }// Label

  nunhit = 0;
  if (MapUnhitToUnknown) {
    printf("Mapping unhit to unknown\n");
    for (vtxno = 0; vtxno < mris->nvertices; vtxno++) {
      if (MRIgetVoxVal(nhits,vtxno,0,0,0) == 0) {
        ano = index_to_annotation(0);
        mris->vertices[vtxno].annotation = ano;
        nunhit ++;
      }
    }
    printf("Found %d unhit vertices\n",nunhit);
  }

  if (dilate_label_name)
  {
    dilate_label_into_unknown(mris, dilate_label_annot) ;
  }
  printf("Writing annot to %s\n",AnnotPath);
  MRISwriteAnnotation(mris, AnnotPath);

  if (NHitsFile != NULL) MRIwrite(nhits,NHitsFile);

  return 0;
}