Пример #1
0
/*-------------------------------------------------------------
  BTypeFromStem() - determines whether stem is a bshort or bfloat.
  -------------------------------------------------------------*/
int BTypeFromStem(char *stem) {
  char tmpstr[2000];

  sprintf(tmpstr,"%s_000.bfloat",stem);
  if (fio_FileExistsReadable(tmpstr)) return(BFLOAT_FILE);

  sprintf(tmpstr,"%s_000.bshort",stem);
  if (fio_FileExistsReadable(tmpstr)) return(BSHORT_FILE);

  printf("WARNING: cannot find file for bstem %s\n",stem);

  return(MRI_VOLUME_TYPE_UNKNOWN);
}
Пример #2
0
/*--------------------------------------------------------------*/
static void check_options(void) {
  int n;
  if(SrcValFile == NULL && AnnotFile == NULL && LabelFile == NULL){
    printf("ERROR: need to specify source value file\n");
    exit(1);
  }
  if(SrcValFile && AnnotFile){
    printf("ERROR: cannot spec both --src and --src-annot\n");
    exit(1);
  }
  if(SrcValFile && LabelFile){
    printf("ERROR: cannot spec both --src and --src-label\n");
    exit(1);
  }
  if(AnnotFile && LabelFile){
    printf("ERROR: cannot spec both --src-annot and --src-label\n");
    exit(1);
  }
  if(TrgValFile == NULL){
    printf("ERROR: need to specify target value file\n");
    exit(1);
  }
  if(nsurfs == 0){
    printf("ERROR: must specify at least one source:target registration pair\n");
    exit(1);
  }
  for(n=0; n<nsurfs;n++){
    if(!fio_FileExistsReadable(SurfRegFile[n])){
      printf("ERROR: %s does not exist or is not readable by you\n",SurfRegFile[n]);
      exit(1);
    }
  }
  return;
}
Пример #3
0
/*------------------------------------------------------------*/
DVT *DVTread(char *dvtfile) {
  DVT *dvt = NULL;
  FILE *fp;
  int nrows, ncols, r, c;
  char tmpstr[4001];

  if (!fio_FileExistsReadable(dvtfile)) {
    printf("ERROR: %s does not exist or is not readable\n",dvtfile);
    return(NULL);
  }

  nrows = fio_NLines(dvtfile);
  if (nrows == 0) {
    printf("ERROR: reading %s, no rows found\n",dvtfile);
    return(NULL);
  }

  fp = fopen(dvtfile,"r");
  fgets(tmpstr,4000,fp);
  ncols = gdfCountItemsInString(tmpstr);
  if (ncols == 0) {
    printf("ERROR: reading %s, no cols found\n",dvtfile);
    fclose(fp);
    return(NULL);
  }
  fclose(fp);

  nrows = nrows-1;
  ncols = ncols-1;
  printf("%s  nrows = %d, ncols = %d\n",dvtfile,nrows,ncols);

  dvt = DVTalloc(nrows,ncols,dvtfile);
  if (dvt == NULL) return(NULL);
  dvt->transposed = 0;

  fp = fopen(dvtfile,"r");

  /* Read the first row = names of columns */
  fscanf(fp,"%s",tmpstr); /* swallow the first one */
  for (c=0; c < ncols; c++) {
    fscanf(fp,"%s",tmpstr);
    DVTsetName(dvt,c,tmpstr,2);
  }

  for (r=0; r < nrows; r++) {
    /* First column is row name */
    fscanf(fp,"%s",tmpstr);
    DVTsetName(dvt,r,tmpstr,1);
    //printf("r=%d, RowName = %s\n",r,dvt->RowNames[r]);
    for (c=0; c < ncols; c++) {
      fscanf(fp,"%f",&dvt->D->rptr[r+1][c+1]);
    }
  }

  fclose(fp);
  return(dvt);
}
Пример #4
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;
}
Пример #5
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);
}
Пример #6
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);
}
Пример #7
0
/*--------------------------------------------------*/
int main(int argc, char **argv)
{
    int nargs, err, asegid, c, r, s, nctx, annot,vtxno,nripped;
    int annotid, IsCortex=0, IsWM=0, IsHypo=0, hemi=0, segval=0;
    int RibbonVal=0,nbrute=0;
    float dmin=0.0, lhRibbonVal=0, rhRibbonVal=0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


    return(0);
}
Пример #8
0
/*------------------------------------------------------------*/
static int parse_commandline(int argc, char **argv) {
    int  nargc , nargsused;
    char **pargv, *option ;

    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, "--checkopts"))   checkoptsonly = 1;
        else if (!strcasecmp(option, "--nocheckopts")) checkoptsonly = 0;
        else if (!strcasecmp(option, "--norev")) ReverseMapFlag = 0;
        else if (!strcasecmp(option, "--no-rev")) ReverseMapFlag = 0;
        else if (!strcasecmp(option, "--nnf")) ReverseMapFlag = 0;
        else if (!strcasecmp(option, "--nnfr")) ReverseMapFlag = 1;
        else if (!strcasecmp(option, "--no-hash")) UseHash = 0;
        else if (!strcasecmp(option, "--jac")) DoJac = 1;
        else if (!strcasecmp(option, "--no-jac")) DoJac = 0;
        else if (!strcasecmp(option, "--randn")) DoSynthRand = 1;
        else if (!strcasecmp(option, "--ones")) DoSynthOnes = 1;

        else if (!strcasecmp(option, "--src") || !strcasecmp(option, "--sval")) {
            if (nargc < 1) CMDargNErr(option,1);
            SrcValFile = pargv[0];
            if(!fio_FileExistsReadable(SrcValFile)) {
                printf("ERROR: %s does not exist or is not readable by you\n",SrcValFile);
                exit(1);
            }
            nargsused = 1;
        }
        else if (!strcasecmp(option, "--trg") || !strcasecmp(option, "--tval")
                 || !strcasecmp(option, "--o")) {
            if (nargc < 1) CMDargNErr(option,1);
            TrgValFile = pargv[0];
            nargsused = 1;
        }
        else if (!strcasecmp(option, "--streg")) {
            if (nargc < 2) CMDargNErr(option,2);
            SurfRegFile[nsurfs] = pargv[0];
            nsurfs++;
            SurfRegFile[nsurfs] = pargv[1];
            nsurfs++;
            nargsused = 2;
        }
        else {
            fprintf(stderr,"ERROR: Option %s unknown\n",option);
            if (CMDsingleDash(option))
                fprintf(stderr,"       Did you really mean -%s ?\n",option);
            exit(-1);
        }
        nargc -= nargsused;
        pargv += nargsused;
    }
    return(0);
}
int
main(int argc, char *argv[]) {
  char         **av, *avg_surf_name, *canon_surf_name, fname[STRLEN],
  *mdir, ico_fname[STRLEN], *hemi, *out_sname ;
  int          ac, nargs, i, vno, n ;
  VERTEX       *v ;
  MRI_SURFACE  *mris_ico ;
  MRI_SP       *mrisp_total ;
  LTA          *lta ;
  VOL_GEOM     vg;
  float        average_surface_area = 0.0 ;
  MATRIX *XFM=NULL;
  GCA_MORPH *gcam=NULL;

  memset((void *) &vg, 0, sizeof (VOL_GEOM));

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

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

  mdir = getenv("FREESURFER_HOME") ;
  if (!mdir)
    ErrorExit(ERROR_BADPARM, 
              "%s: no FREESURFER_HOME in environment.\n",Progname);
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }
  if (sdir == NULL) {
    sdir =  getenv("SUBJECTS_DIR");
    if (!sdir)
      ErrorExit(ERROR_BADPARM, 
                "%s: no SUBJECTS_DIR in environment.\n",Progname);
  }
  if (sdirout == NULL) sdirout = sdir;
  if (argc < 6) usage_exit() ;

  hemi = argv[1] ;
  avg_surf_name = argv[2] ;
  canon_surf_name = argv[3] ;
  out_sname = argv[4] ;

  printf("---------------------------------------------------\n");
  printf("hemi            = %s\n",hemi);
  printf("avg_surf_name   = %s\n",avg_surf_name);
  printf("canon_surf_name = %s\n",canon_surf_name);
  printf("out_sname       = %s\n",out_sname);
  printf("xform           = %s\n",xform_name);
  printf("---------------------------------------------------\n");
  printf("\n\n");
  fflush(stdout);

#define SCALE 1
  mrisp_total = MRISPalloc(SCALE, 3) ;
  for (n = 0, i = 5 ; i < argc ; i++) {
    MRI *mri;
    MRI_SURFACE *mris;
    MRI_SP *mrisp;

    printf("\n---------------------------------------------------\n");
    printf("#@# processing subject %d/%d %s...\n", i-4,argc-5,argv[i]) ;
    fflush(stdout);

    // read sphere.reg
    sprintf(fname, "%s/%s/surf/%s.%s", sdir, argv[i], hemi, canon_surf_name) ;
    printf("  Reading %s\n",fname);
    fflush(stdout);
    mris = MRISread(fname) ;
    if (!mris) {
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
      exit(1);
    }
    // get "pial" surface vertex into ->origx, origy, origz
    if (MRISreadOriginalProperties(mris, orig_name) != NO_ERROR)
      ErrorExit(ERROR_BADFILE,"%s: could not read orig file for %s.\n",
                Progname, argv[1]);
    // read transform
    if (0) {
      sprintf(fname, "%s/%s/mri/transforms/%s", sdir, argv[i], xform_name) ;
      lta = LTAreadEx(fname) ;
      if (!lta)
        ErrorExit(ERROR_BADPARM, 
                  "%s: could not read transform from %s", Progname, fname) ;
    }

    // read T1 volume
    sprintf(fname, "%s/%s/mri/T1.mgz", sdir, argv[i]) ;
    if (fio_FileExistsReadable(fname)) mri = MRIreadHeader(fname,MRI_MGH_FILE);
    else {
      sprintf(fname, "%s/%s/mri/T1", sdir, argv[i]) ;
      mri = MRIreadHeader(fname, MRI_UCHAR); // MRI_CORONAL_SLICE_DIRECTORY) ;
    }
    printf("  Read %s\n",fname);
    fflush(stdout);

    if (!mri)
      ErrorExit(ERROR_BADPARM, 
                "%s: could not read reference MRI volume from %s",
                Progname, fname) ;

    // save current vertex position into ->cx
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    // get the vertex position from ->origx, ... 
    // (get the "pial" vertex position)
    MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRIScomputeMetricProperties(mris) ;
    printf("  Surface area: %2.1f cm^2\n", mris->total_area/100) ;
    fflush(stdout);
    average_surface_area += mris->total_area ;

    // this means that we transform "pial" surface

    if (xform_name)
    {
      if (!strcmp(xform_name,"talairach.xfm")) {
        printf("  Applying linear transform\n");
        fflush(stdout);
        XFM = DevolveXFMWithSubjectsDir(argv[i], NULL, "talairach.xfm", sdir);
        if (XFM == NULL) exit(1);
        MRISmatrixMultiply(mris, XFM);
        MatrixFree(&XFM);
      } else if (!strcmp(xform_name,"talairach.m3z")) {
        printf("  Applying GCA Morph\n");
        fflush(stdout);
        sprintf(fname, "%s/%s/mri/transforms/talairach.m3z", sdir, argv[i]) ;
        gcam = GCAMreadAndInvert(fname);
        if (gcam == NULL) exit(1);
        GCAMmorphSurf(mris, gcam);
        GCAMfree(&gcam);
      } else {
        printf("ERROR: don't know what to do with %s\n",xform_name);
        exit(1);
      }
    }

    // save transformed position in ->orig 
    // (store "pial" vertices position in orig)
    MRIScomputeMetricProperties(mris) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
    // get the vertex position from ->cx 
    // (note that this is not transformed)  sphere.reg vertices
    MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
    // mris contains sphere.reg in vertex and pial vertices in orig
    // map to a theta-phi space and accumulate values
    mrisp = MRIScoordsToParameterization(mris, NULL, SCALE, ORIGINAL_VERTICES) ;
    MRISPaccumulate(mrisp, mrisp_total, 0) ;
    MRISPaccumulate(mrisp, mrisp_total, 1) ;
    MRISPaccumulate(mrisp, mrisp_total, 2) ;
    MRISPfree(&mrisp) ;
    MRISfree(&mris) ;
    MRIfree(&mri) ;
    //LTAfree(&lta) ;
    fflush(stdout);
    n++ ;
  }
  printf("Finished loading all data\n");
  average_surface_area /= (float)n ;
  printf("Avg surf area = %g cm\n",average_surface_area/100.0);
  fflush(stdout);

  // mrisp_total lost info on the modified surface
  sprintf(ico_fname, "%s/lib/bem/ic%d.tri", mdir, ico_no) ;
  printf("Reading icosahedron from %s...\n", ico_fname) ;
  mris_ico = ICOread(ico_fname) ;
  if (!mris_ico)
    ErrorExit(ERROR_NOFILE, "%s: could not read icosahedron file %s\n",
              Progname,ico_fname) ;
  MRISscaleBrain(mris_ico, mris_ico,
                 DEFAULT_RADIUS/MRISaverageRadius(mris_ico)) ;
  // save current ico position to ->cx, cy, cz
  MRISsaveVertexPositions(mris_ico, CANONICAL_VERTICES) ;
  // using mrisp_total to calculate position into ->origx, origy, origz 
  // (orig is the "pial" vertices)
  MRIScoordsFromParameterization(mrisp_total, mris_ico, ORIGINAL_VERTICES) ;
  // copy geometry info
  memcpy((void *) &mris_ico->vg, (void *) &vg, sizeof (VOL_GEOM));

  if (Gdiag_no >= 0 && Gdiag_no < mris_ico->nvertices) {
    int n ;
    VERTEX *vn ;

    v = &mris_ico->vertices[Gdiag_no] ;
    printf( "v %d: x = (%2.2f, %2.2f, %2.2f)\n",
            Gdiag_no, v->origx, v->origy, v->origz) ;
    for (n = 0 ; n < v->vnum ; n++) {
      vn = &mris_ico->vertices[v->v[n]] ;
      printf( "v %d: x = (%2.2f, %2.2f, %2.2f)\n",
              v->v[n], vn->origx, vn->origy, vn->origz) ;
    }
  }
  // write *h.sphere.reg
  sprintf(fname, "%s/%s/surf/%s.%s", 
          sdirout, out_sname, hemi, canon_surf_name) ;
  if (Gdiag & DIAG_SHOW)
    printf("writing average canonical surface to %s\n", fname);
  MRISwrite(mris_ico, fname) ;

  // get "pial vertices" from orig
  MRISrestoreVertexPositions(mris_ico, ORIG_VERTICES);
  for (vno = 0 ; vno < mris_ico->nvertices ; vno++) {
    v = &mris_ico->vertices[vno] ;
    // n = number of subjects
    v->x /= (float)n ;
    v->y /= (float)n ;
    v->z /= (float)n ;
  }
  if (normalize_area) {
    MRIScomputeMetricProperties(mris_ico) ;
    printf("setting group surface area to be %2.1f cm^2 (scale=%2.2f)\n",
           average_surface_area/100.0,
           sqrt(average_surface_area/mris_ico->total_area)) ;

#if 0
    MRISscaleBrain(mris_ico, mris_ico,
                   sqrt(average_surface_area/mris_ico->total_area)) ;
#else
    mris_ico->group_avg_surface_area = average_surface_area ;
#endif
    MRIScomputeMetricProperties(mris_ico) ;
  }

  sprintf(fname, "%s/%s/surf/%s.%s", sdirout,out_sname, hemi, avg_surf_name) ;
  printf("writing average %s surface to %s\n", avg_surf_name, fname);
  MRISwrite(mris_ico,  fname) ;

  if (0) {
    char path[STRLEN] ;
    LTA  *lta ;

    FileNamePath(fname, path) ;
    lta = LTAalloc(1, NULL) ;
    // write to a different location
    sprintf(fname, "%s/../mri/transforms/%s", path,xform_name) ;
    LTAwriteEx(lta, fname) ;
    LTAfree(&lta) ;
  }

  MRISfree(&mris_ico) ;
  MRISPfree(&mrisp_total) ;

  printf("mris_make_average_surface done\n");

  exit(0) ;
  return(0) ;  /* for ansi */
}
Пример #10
0
int
main(int argc, char *argv[])
{
  char   **av ;
  int    ac, nargs ;
  MRI    *mri=NULL ;
  char   *xform_fname=NULL, *in_fname=NULL, *out_fname=NULL ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_add_xform_to_header.c,v 1.12 2011/03/02 00:04:13 nicks Exp $",
           "$Name:  $");

  argc -= nargs;

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

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

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

  if (argc < 2)
  {
    ErrorExit(ERROR_BADPARM, "%s: no transform name specified", Progname) ;
  }
  xform_fname = argv[1] ;

  if (argc < 3)
  {
    ErrorExit(ERROR_BADPARM, "%s: no input name specified", Progname) ;
  }
  in_fname = argv[2] ;

  if (argc < 4)
  {
    out_fname = in_fname ;
  }
  else
  {
    out_fname = argv[3] ;
  }

  if (verbose)
  {
    fprintf(stderr, "reading from %s...", in_fname) ;
  }

  // we have two cases, in_fname is just a directory name or .mgz
  if (fio_IsDirectory(in_fname))
  {
    mri = MRIreadInfo(in_fname) ;  // must be old COR volume
  }
  else if (fio_FileExistsReadable(in_fname))
  {
    char *ext = fio_extension(in_fname);
    if (ext==0)
    {
      ErrorExit(ERROR_BADPARM, "%s: no extension found", Progname) ;
    }
    printf("INFO: extension is %s\n", ext);
    if (strcmp(ext, "mgz")==0 || strcmp(ext, "mgh")==0)
    {
      mri = MRIread(in_fname);  // mgh or mgz
    }
    else
    {
      ErrorExit(ERROR_BADPARM,
                "%s: currently only .mgz or .mgh saves transform name",
                Progname) ;
    }
  }
  if (!mri)
    ErrorExit(ERROR_NO_FILE, "%s: could not open source file %s",
              Progname, in_fname) ;

  if (! CopyNameOnly)
  {
    // why do we need to load the transform at this time
    // mri is removed anyway???? -- good point, added -s for noload
    if (input_transform_file(xform_fname, &mri->transform) != OK)
      ErrorPrintf(ERROR_NO_MEMORY,
                  "%s: could not read xform file '%s'\n",
                  Progname, xform_fname);
    // my guess is just to verify the validity of the transform?
    mri->linear_transform = get_linear_transform_ptr(&mri->transform) ;
    mri->inverse_linear_transform =
      get_inverse_linear_transform_ptr(&mri->transform) ;
    mri->free_transform = 1 ;
  }
  strcpy(mri->transform_fname, xform_fname) ;

  if (verbose)
  {
    fprintf(stderr, "done.\nwriting to %s...", out_fname) ;
  }
  // this writes COR-.info only
  if (fio_IsDirectory(out_fname))
  {
    MRIwriteInfo(mri, out_fname) ;
  }
  else
  {
    MRIwrite(mri, out_fname);  // currently only mgh format write xform info
  }

  if (verbose)
  {
    fprintf(stderr, "done.\n") ;
  }

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

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

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

  if (argc == 0) usage_exit();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  printf("mri_aparc2wmseg done\n");
  return(0);
}
Пример #12
0
/* --------------------------------------------- */
static int parse_commandline(int argc, char **argv) {
  int  nargc , nargsused;
  char **pargv, *option ;

  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 (!strcmp(option, "--help"))  print_help() ;
    else if (!strcmp(option, "--version")) print_version() ;
    else if (!strcmp(option, "--debug"))   debug = 1;
    else if (!strcmp(option, "--checkopts"))   checkoptsonly = 1;
    else if (!strcmp(option, "--nocheckopts")) checkoptsonly = 0;
    else if (!strcmp(option, "--no-unknown")) MapUnhitToUnknown = 0;
    else if (!strcmp(option, "--ldir-default")) labeldirdefault = 1;
    else if (!strcmp(option, "--noverbose")) verbose = 0;
    else if (!strcmp(option, "--maxstatwinner")) maxstatwinner = 1;
    else if (!strcmp(option, "--dilate-into-unknown")) 
    {
      dilate_label_name = pargv[0] ;
      printf("dilating label %s into bordering unknown vertices\n", 
             dilate_label_name) ;
      nargsused = 1;
    }
    else if (!strcmp(option, "--s") || !strcmp(option, "--subject")) {
      if (nargc < 1) CMDargNErr(option,1);
      subject = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--h") || !strcmp(option, "--hemi")) {
      if (nargc < 1) CMDargNErr(option,1);
      hemi = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--ctab")) {
      if (nargc < 1) CMDargNErr(option,1);
      if (!fio_FileExistsReadable(pargv[0])) {
        printf("ERROR: cannot find or read %s\n",pargv[0]);
        exit(1);
      }
      CTabFile = pargv[0];
      nargsused = 1;
    } 
    else if (!strcmp(option, "--l")) {
      if (nargc < 1) CMDargNErr(option,1);
      if (!fio_FileExistsReadable(pargv[0])) {
        printf("ERROR: cannot find or read %s\n",pargv[0]);
        exit(1);
      }
      LabelFiles[nlabels] = pargv[0];
      nlabels++;
      nargsused = 1;
    } 
    else if (!strcmp(option, "--thresh")) {
      if (nargc < 1) CMDargNErr(option,1);
      sscanf(pargv[0],"%lf",&LabelThresh);
      DoLabelThresh = 1;
      nargsused = 1;
    } 
    else if (!strcmp(option, "--ldir")) {
      if (nargc < 1) CMDargNErr(option,1);
      labeldir = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--a") || !strcmp(option, "--annot")) {
      if (nargc < 1) CMDargNErr(option,1);
      AnnotName = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--annot-path")) {
      if (nargc < 1) CMDargNErr(option,1);
      AnnotPath = pargv[0];
      nargsused = 1;
    } else if (!strcmp(option, "--nhits")) {
      if (nargc < 1) CMDargNErr(option,1);
      NHitsFile = pargv[0];
      nargsused = 1;
    } else {
      fprintf(stderr,"ERROR: Option %s unknown\n",option);
      if (CMDsingleDash(option))
        fprintf(stderr,"       Did you really mean -%s ?\n",option);
      exit(-1);
    }
    nargc -= nargsused;
    pargv += nargsused;
  }
  return(0);
}
Пример #13
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;
}