示例#1
0
static MRI *
make_atrophy_map(MRI *mri_time1, MRI *mri_time2, MRI *mri_dst, TRANSFORM *transform1, TRANSFORM *transform2,
                 int *gray_labels, int ngray, int *csf_labels, int ncsf) {
  int            x, y, z, label1, label2, n, found, xp, yp, zp, spacing ;
  GCA_MORPH_NODE *gcamn1, *gcamn2 ;
  GCA_MORPH      *gcam1, *gcam2 ;
  float           volume ;

  if (mri_dst == NULL) {
    mri_dst = MRIalloc(mri_time1->width, mri_time1->height, mri_time1->depth, MRI_FLOAT) ;
    MRIcopyHeader(mri_time1, mri_dst) ;
  }

  gcam1 = (GCA_MORPH*)transform1->xform ;
  gcam2 = (GCA_MORPH*)transform2->xform ;
  spacing = gcam1->spacing ;

  for (x = 0 ; x < mri_time1->width ; x++) {
    xp = x / spacing;
    for (y = 0 ; y < mri_time1->height ; y++) {
      yp = y / spacing;
      for (z = 0 ; z < mri_time1->depth ; z++) {
        if (x == Gx && y == Gy && z == Gz)
          DiagBreak() ;
        label1 = MRIgetVoxVal(mri_time1, x, y, z, 0) ;
        label2 = MRIgetVoxVal(mri_time2, x, y, z, 0) ;
        if (label1 == label2)
          continue ;

        /* if label1 was one of the gray types and label2 one of the csf, call it atrophy */
        for (found = n = 0 ; n < ngray ; n++)
          if (label1 == gray_labels[n]) {
            found = 1 ;
            break ;
          }
        if (found == 0)
          continue ;
        for (found = n = 0 ; n < ncsf ; n++)
          if (label2 == csf_labels[n]) {
            found = 1 ;
            break ;
          }
        if (found == 0)
          continue ;
        zp = z / spacing;
        gcamn1 = &gcam1->nodes[xp][yp][zp] ;
        gcamn2 = &gcam2->nodes[xp][yp][zp] ;
        volume = 0 ;
        if (FZERO(gcamn1->area) == 0)
          volume += gcamn1->orig_area / gcamn1->area ;
        if (FZERO(gcamn2->area) == 0)
          volume += gcamn2->orig_area / gcamn2->area ;
        MRIsetVoxVal(mri_dst, x, y, z, 0, volume) ;
      }
    }
  }


  return(mri_dst) ;
}
static int
rip_vertices_out_of_fov(MRI_SURFACE *mris, MRI *mri_profiles) {
  int  vno, n, i, good, nsamples ;
  VERTEX *v ;

  nsamples = mri_profiles->nframes ;
  for (vno = 0 ; vno < mris->nvertices ; vno++) {
    v = &mris->vertices[vno] ;
    for (good = i = 0 ; good == 0 && i < nsamples ; i++)
      if (!FZERO(MRIgetVoxVal(mri_profiles, vno, 0, 0, i)))
        good = 1 ;
    if (!good) {
      v->ripflag = 1 ;
      v->annotation = 0 ;
    }
  }

  // rip stuff around the identically 0 ones, as they can't be trusted
  for (vno = 0 ; vno < mris->nvertices ; vno++) {
    v = &mris->vertices[vno] ;
    if (v->ripflag != 1)
      continue ;
    for (n = 0 ; n < v->vtotal ; n++) {
      mris->vertices[v->v[n]].ripflag = 2 ;
      mris->vertices[v->v[n]].annotation = 0 ;
    }
  }
  for (vno = 0 ; vno < mris->nvertices ; vno++) {
    v = &mris->vertices[vno] ;
    if (v->ripflag == 2)
      v->ripflag = 1 ;
  }
  return(NO_ERROR) ;
}
static int
rip_bad_vertices(MRI_SURFACE *mris, MRI *mri_profiles) {
  int    unknown_index, bad, i, vno, index ;
  VERTEX *v ;

  CTABfindName(mris->ct, "Unknown", &unknown_index) ;
  printf("unknown index = %d\n", unknown_index) ;
  for (vno = 0 ; vno < mris->nvertices ; vno++) {
    v = &mris->vertices[vno] ;
    if (vno == Gdiag_no)
      DiagBreak() ;
    if (v->ripflag)
      continue ;

    CTABfindAnnotation(mris->ct, v->annotation, &index);
    if (index == unknown_index) {
      v->annotation = 0 ;
      v->ripflag = 1 ;
    } else {
      bad = 1 ;
      for (i = 0 ; i < mri_profiles->nframes ; i++) {
        if (!FZERO(MRIgetVoxVal(mri_profiles, vno, 0, 0, i)))
          bad = 0 ;
      }
      if (bad) {
        v->ripflag = 1 ;
        v->annotation = 0 ;
      }
    }

  }
  MRISripFaces(mris) ;
  MRIScomputeMetricProperties(mris) ;
  return(NO_ERROR) ;
}
示例#4
0
static MRI *
compute_bias(MRI *mri_src, MRI *mri_dst, MRI *mri_bias)
{
  int x, y, z ;
  float bias, src, dst ;

  if (!mri_bias)
    mri_bias = MRIalloc
               (mri_src->width, mri_src->height, mri_src->depth, MRI_FLOAT) ;

  MRIcopyHeader(mri_src, mri_bias) ;
  for (x = 0 ; x < mri_src->width ; x++)
  {
    for (y = 0; y < mri_src->height ; y++)
    {
      for (z = 0 ; z < mri_src->depth ; z++)
      {
        src = MRIgetVoxVal(mri_src, x, y, z, 0) ;
        dst = MRIgetVoxVal(mri_dst, x, y, z, 0) ;
        if (FZERO(src))
        {
          bias = 1 ;
        }
        else
        {
          bias = dst/src ;
        }
        MRIsetVoxVal(mri_bias, x, y, z, 0, bias) ;
      }
    }
  }

  return(mri_bias) ;
}
示例#5
0
int
MRISscaleUp(MRI_SURFACE *mris)
{
  int     vno, n, max_v, max_n ;
  VERTEX  *v ;
  float   ratio, max_ratio ;

  max_ratio = 0.0f ;
  max_v = max_n = 0 ;
  for (vno = 0 ; vno < mris->nvertices ; vno++)
  {
    v = &mris->vertices[vno] ;
    if (v->ripflag)
    {
      continue ;
    }
    if (vno == Gdiag_no)
    {
      DiagBreak() ;
    }
    for (n = 0 ; n < v->vnum ; n++)
    {
      if (FZERO(v->dist[n]))   /* would require infinite scaling */
      {
        continue ;
      }
      ratio = v->dist_orig[n] / v->dist[n] ;
      if (ratio > max_ratio)
      {
        max_v = vno ;
        max_n = n ;
        max_ratio = ratio ;
      }
    }
  }

  fprintf(stderr, "max @ (%d, %d), scaling brain by %2.3f\n",
          max_v, max_n, max_ratio) ;
#if 0
  MRISscaleBrain(mris, mris, max_ratio) ;
#else
  for (vno = 0 ; vno < mris->nvertices ; vno++)
  {
    v = &mris->vertices[vno] ;
    if (v->ripflag)
    {
      continue ;
    }
    if (vno == Gdiag_no)
    {
      DiagBreak() ;
    }
    for (n = 0 ; n < v->vnum ; n++)
    {
      v->dist_orig[n] /= max_ratio ;
    }
  }
#endif
  return(NO_ERROR) ;
}
示例#6
0
static int
normalize_timepoints_with_samples(MRI *mri, GCA_SAMPLE *gcas, int nsamples, int nsoap)
{
  int   frame, i, x, y, z ;
  double target, val ;
  MRI    *mri_ctrl, *mri_bias, *mri_target, *mri_frame ;

  mri_ctrl = MRIcloneDifferentType(mri, MRI_UCHAR) ;
  mri_bias = MRIcloneDifferentType(mri, MRI_FLOAT) ;
  mri_target = MRIcloneDifferentType(mri, MRI_FLOAT) ;

  for (i = 0 ; i < nsamples ; i++)
  {
    if (i == Gdiag_no)
      DiagBreak() ;
    x = nint(gcas[i].x)  ; y = nint(gcas[i].y) ; z = nint(gcas[i].z) ;
    MRIsetVoxVal(mri_ctrl, x, y, z, 0, CONTROL_MARKED) ;
    for (target = 0.0, frame = 0 ; frame < mri->nframes ; frame++)
      target += MRIgetVoxVal(mri, x, y, z, frame) ;
    target /= mri->nframes ;
    MRIsetVoxVal(mri_target, x, y, z, 0, target) ;
  }

  // build a bias correction for each time point (which each has its own frame)
  for (frame = 0 ; frame < mri->nframes ; frame++)
  {
    MRIclear(mri_bias) ; 
    for (i = 0 ; i < nsamples ; i++)
    {
      if (i == Gdiag_no)
        DiagBreak() ;
      x = nint(gcas[i].x)  ; y = nint(gcas[i].y) ; z = nint(gcas[i].z) ;
      target = MRIgetVoxVal(mri_target, x, y, z, 0) ;
      val = MRIgetVoxVal(mri, x, y, z, frame) ;
      if (FZERO(val))
        val = 1.0 ;
      MRIsetVoxVal(mri_bias, x, y, z, 0, target/val) ;
    }
    MRIbuildVoronoiDiagram(mri_bias, mri_ctrl, mri_bias) ;
    MRIsoapBubble(mri_bias, mri_ctrl, mri_bias, nsoap) ;
    mri_frame = MRIcopyFrame(mri, NULL, frame, 0) ;
    MRImultiply(mri_frame, mri_bias, mri_frame) ;
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
      char fname[STRLEN] ;
      sprintf(fname, "frame%d.mgz", frame) ;
      MRIwrite(mri_frame, fname) ;
      sprintf(fname, "bias%d.mgz", frame) ;
      MRIwrite(mri_bias, fname) ;
      sprintf(fname, "target%d.mgz", frame) ;
      MRIwrite(mri_target, fname) ;
    }
    MRIcopyFrame(mri_frame, mri, 0, frame) ;
  }
  MRIfree(&mri_bias) ; MRIfree(&mri_target) ; MRIfree(&mri_ctrl) ;
  return(NO_ERROR) ;
}
示例#7
0
static double
entropy(int *class_counts, int nclasses, int *Nc)
{
  int    c ;
  double ent, p, total ;

#define DIVIDE_BY_CLASS_TOTAL 1
#if DIVIDE_BY_CLASS_TOTAL
  double norm_class_counts[MAX_CLASSES] ;

  for (total = 0.0, c = 0 ; c < nclasses ; c++)
  {
    if (Nc[c] > 0)
    {
      norm_class_counts[c] = (double)class_counts[c] / (double)Nc[c] ;
      total += norm_class_counts[c] ;
    }
    else  // then class_counts[c] has to be 0 also
      norm_class_counts[c] = 0.0 ;
  }
  if (FZERO(total))  // shouldn't ever happen
    return(0.0) ;
  for (ent = 0.0, c = 0 ; c < nclasses ; c++)
  {
    p = norm_class_counts[c] / total ;
    if (p > 0)
      ent -= p * log(p) ;
  }
#else

  for (total = 0.0, c = 0 ; c < nclasses ; c++)
    total += (double)class_counts[c];
  if (FZERO(total))
    return(0.0) ;
  for (ent = 0.0, c = 0 ; c < nclasses ; c++)
  {
    p = (double)class_counts[c] / total ;
    if (p > 0)
      ent -= p * log(p) ;
  }
#endif
  return(ent) ;
}
示例#8
0
文件: utils.c 项目: vgurev/freesurfer
/*------------------------------------------------------------------------
  Parameters:

  Description:

  Return Values:
  nothing.
  ------------------------------------------------------------------------*/
double
latan2(double y, double x)
{
  int oerr ;
  double val ;

  oerr = errno ;
  if (FZERO(x) && FZERO(y))
    val = 0.0 ;
  else
    val = atan2(y, x) ;
  if (val < -PI)
    val += 2.0 * PI ;
  if (val > PI)
    val -= 2.0 * PI ;

  if (oerr != errno)
    ErrorPrintf(ERROR_BADPARM,
                "error %d, y %f, x %f\n", errno, (float)y, (float)x) ;
  return(val) ;
}
示例#9
0
MRI *
MRIcomputeConditionalProbabilities(MRI *mri_T1, MRI *mri_mean,
                                   MRI *mri_std, MRI *mri_dst)
{
    int       x, y, z, width, height, depth ;
    BUFTYPE   *pT1, *pmean, *pstd ;
    float     p, mean, std, val, n, *pdst ;


    width = mri_T1->width ;
    height = mri_T1->height ;
    depth = mri_T1->depth ;

    if (!mri_dst)
        mri_dst = MRIalloc(width, height, depth, MRI_FLOAT) ;

    for (z = 0 ; z < depth ; z++)
    {
        for (y = 0 ; y < height ; y++)
        {
            pT1 = &MRIvox(mri_T1, 0, y, z) ;
            pmean = &MRIvox(mri_mean, 0, y, z) ;
            pstd = &MRIvox(mri_std, 0, y, z) ;
            pdst = &MRIFvox(mri_dst, 0, y, z) ;
            for (x = 0 ; x < width ; x++)
            {
                if (DEBUG_POINT(x,y,z))
                    DiagBreak() ;
                val = (float)*pT1++ ;
                mean = (float)*pmean++ ;
                std = (float)*pstd++ ;
                if (FZERO(std))
                    std = 1.0 ;
#if 0
                if (std < 10.0)  /* hack!!!!! - not enough observations */
                    std = 10.0 ;
#endif
                n = 1 / (std * sqrt(2.0*M_PI)) ;
                p = n * exp(-SQR(val - mean) / (2.0f*SQR(std))) ;
                *pdst++ = p*100.0f ;
            }
        }
    }
    return(mri_dst) ;
}
示例#10
0
static int
rfTrainTree(RANDOM_FOREST *rf, TREE *tree, int *training_classes, double **training_data, int ntraining)
{
  int    done = 0, n, iter, tno, fno, f, i ;
  double total_entropy, last_f ;

  total_entropy = entropy(tree->root.class_counts, rf->nclasses, tree->root.class_counts) ;
  
  // make sure there is at least one feature with nonzero range
  for (f = 0 ; f < tree->nfeatures ; f++)
  {
    fno = tree->feature_list[f] ;
    last_f = training_data[tree->root.training_set[0]][fno] ;
    for (i = 1 ; i < tree->root.total_counts ; i++)
    {
      tno = tree->root.training_set[i] ;
      if (training_data[tno][fno] != last_f)
	break ;
    }
    if (i < tree->root.total_counts) 
      break ;  // found one feature with some spread
  }
  if (f >= tree->nfeatures)  // all features are identical - can't train
  {
    rfFindLeaves(tree) ;
    return(ERROR_BADPARM) ;
  }
  iter = 0 ;
  while (!done && !FZERO(total_entropy))
  {
    done = rfTrainNode(rf, tree, &tree->root, training_classes, training_data, rf->ntraining);
    rfFindLeaves(tree) ;
    for (total_entropy = 0.0, n = 0 ; n < tree->nleaves ; n++)
      total_entropy += entropy(tree->leaves[n]->class_counts, rf->nclasses, tree->root.class_counts) ;
    if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
      printf("\taverage leaf entropy = %2.4f, nleaves = %d, max depth %d\n",
	     total_entropy/tree->nleaves, tree->nleaves, tree->depth) ;
    if (iter++ > 10)
      break ;
  }
  if (tree->nleaves == 0)  // only if loop above never executed
    rfFindLeaves(tree) ;
  return(NO_ERROR) ;
}
static int
cvector_compute_t_test(float *c1_mean, float *c1_var,
                       float *c2_mean, float *c2_var,
                       int num_class1, int num_class2,
                       float *pvals, int num) {
  int    i ;
  double t, numer, denom ;

  for (i = 0 ; i < num ; i++) {
    numer = (c1_mean[i] - c2_mean[i]) ;
    denom = sqrt(c1_var[i]/num_class1) + sqrt(c2_var[i]/num_class2) ;
    t = numer / denom ;
    if (FZERO(denom))
      pvals[i] = 1.0f ;
    else
      pvals[i] = sigt(t, num_class1+num_class2-2) ;
  }
  return(NO_ERROR) ;
}
示例#12
0
static int
MRISfindOptimalRigidPosition(MRI_SURFACE *mris, MRI *mri, INTEGRATION_PARMS *parms) {
  double    dx, dy, dz, old_sse, sse, pct_change, dt, dx_total, dy_total, dz_total ;
  int       i ;

  i = 0 ;
  sse = compute_surface_dist_sse(mris, mri) ;
  dt = .1 ;

  dx_total = dy_total = dz_total = 0;
  do {
    old_sse = sse ;
    compute_rigid_gradient(mris, mri, &dx, &dy, &dz) ;
    apply_rigid_gradient(mris, dx*dt, dy*dt, dz*dt) ;
    sse = compute_surface_dist_sse(mris, mri) ;
    dx_total += dt*dx ;
    dy_total += dt*dy ;
    dz_total += dt*dz ;
    pct_change = 100.0 * ((old_sse - sse) / old_sse) ;
    if (pct_change < 0) {
      dt *=-1 ;
      apply_rigid_gradient(mris, dx*dt, dy*dt, dz*dt) ;
      dx_total += dt*dx ;
      dy_total += dt*dy ;
      dz_total += dt*dz ;
    }

    if (Gdiag & DIAG_WRITE) {
      char fname[STRLEN] ;
      sprintf(fname, "lh.%4.4d", ++parms->start_t) ;
      MRISwrite(mris, fname) ;
    }
    if (FZERO(sse))
      break ;
  } while (pct_change > .01);

  printf("after rigid positioning, delta = (%2.0f, %2.0f, %2.0f)\n", dx_total, dy_total, dz_total) ;
  return(NO_ERROR) ;
}
示例#13
0
static double
find_optimal_threshold(RF *rf, TREE *tree, NODE *parent, NODE *left, NODE *right, double **training_data, int ntraining, int fno, double *pinfo_gain, int nsteps, double fmin, double fmax)
{
  double step, thresh, best_thresh, info_gain, best_info_gain ;

  step = (fmax - fmin) / (nsteps-1) ;
  if (FZERO(step) || step < rf->min_step_size)
    return(0.0) ;

  best_info_gain = -1e10; best_thresh = 0 ;
  for (thresh = fmin ; thresh < fmax ; thresh += step)
  {
    info_gain = compute_info_gain(rf, tree, parent, left, right, training_data, fno,thresh) ;
    if (info_gain < 0)
      DiagBreak() ;
    if (info_gain > best_info_gain && left->total_counts>0 && right->total_counts>0)
    {
      best_info_gain = info_gain ;
      best_thresh = thresh ;
    }
  }
  *pinfo_gain = best_info_gain ;
  return(best_thresh) ;
}
示例#14
0
/* TODO: fix all ==s left */
int segment_intersection_2d_tol(double ax1, double ay1, double ax2,
				double ay2, double bx1, double by1,
				double bx2, double by2, double *x1,
				double *y1, double *x2, double *y2,
				double tol)
{
    double tola, tolb;

    double d, d1, d2, ra, rb, t;

    int switched = 0;

    /* TODO: Works for points ? */
    G_debug(4, "segment_intersection_2d()");
    G_debug(4, "    ax1  = %.18f, ay1  = %.18f", ax1, ay1);
    G_debug(4, "    ax2  = %.18f, ay2  = %.18f", ax2, ay2);
    G_debug(4, "    bx1  = %.18f, by1  = %.18f", bx1, by1);
    G_debug(4, "    bx2  = %.18f, by2  = %.18f", bx2, by2);


    /* Check identical lines */
    if ((FEQUAL(ax1, bx1, tol) && FEQUAL(ay1, by1, tol) &&
	 FEQUAL(ax2, bx2, tol) && FEQUAL(ay2, by2, tol)) ||
	(FEQUAL(ax1, bx2, tol) && FEQUAL(ay1, by2, tol) &&
	 FEQUAL(ax2, bx1, tol) && FEQUAL(ay2, by1, tol))) {
	G_debug(2, " -> identical segments");
	*x1 = ax1;
	*y1 = ay1;
	*x2 = ax2;
	*y2 = ay2;
	return 5;
    }

    /*  'Sort' lines by x1, x2, y1, y2 */
    if (bx1 < ax1)
	switched = 1;
    else if (bx1 == ax1) {
	if (bx2 < ax2)
	    switched = 1;
	else if (bx2 == ax2) {
	    if (by1 < ay1)
		switched = 1;
	    else if (by1 == ay1) {
		if (by2 < ay2)
		    switched = 1;	/* by2 != ay2 (would be identical */
	    }
	}
    }

    if (switched) {
	t = ax1;
	ax1 = bx1;
	bx1 = t;
	t = ay1;
	ay1 = by1;
	by1 = t;
	t = ax2;
	ax2 = bx2;
	bx2 = t;
	t = ay2;
	ay2 = by2;
	by2 = t;
    }

    d = (ax2 - ax1) * (by1 - by2) - (ay2 - ay1) * (bx1 - bx2);
    d1 = (bx1 - ax1) * (by1 - by2) - (by1 - ay1) * (bx1 - bx2);
    d2 = (ax2 - ax1) * (by1 - ay1) - (ay2 - ay1) * (bx1 - ax1);

    G_debug(2, "    d  = %.18g", d);
    G_debug(2, "    d1 = %.18g", d1);
    G_debug(2, "    d2 = %.18g", d2);

    tola = tol / MAX(fabs(ax2 - ax1), fabs(ay2 - ay1));
    tolb = tol / MAX(fabs(bx2 - bx1), fabs(by2 - by1));
    G_debug(2, "    tol  = %.18g", tol);
    G_debug(2, "    tola = %.18g", tola);
    G_debug(2, "    tolb = %.18g", tolb);
    if (!FZERO(d, tol)) {
	ra = d1 / d;
	rb = d2 / d;

	G_debug(2, "    not parallel/collinear: ra = %.18g", ra);
	G_debug(2, "                            rb = %.18g", rb);

	if ((ra <= -tola) || (ra >= 1 + tola) || (rb <= -tolb) ||
	    (rb >= 1 + tolb)) {
	    G_debug(2, "        no intersection");
	    return 0;
	}

	ra = MIN(MAX(ra, 0), 1);
	*x1 = ax1 + ra * (ax2 - ax1);
	*y1 = ay1 + ra * (ay2 - ay1);

	G_debug(2, "        intersection %.18f, %.18f", *x1, *y1);
	return 1;
    }

    /* segments are parallel or collinear */
    G_debug(3, " -> parallel/collinear");

    if ((!FZERO(d1, tol)) || (!FZERO(d2, tol))) {	/* lines are parallel */
	G_debug(2, "  -> parallel");
	return 0;
    }

    /* segments are colinear. check for overlap */

    /*    aa = adx*adx + ady*ady;
       bb = bdx*bdx + bdy*bdy;

       t = (ax1-bx1)*bdx + (ay1-by1)*bdy; */


    /* Collinear vertical */
    /* original code assumed lines were not both vertical
     *  so there is a special case if they are */
    if (FEQUAL(ax1, ax2, tol) && FEQUAL(bx1, bx2, tol) &&
	FEQUAL(ax1, bx1, tol)) {
	G_debug(2, "  -> collinear vertical");
	if (ay1 > ay2) {
	    t = ay1;
	    ay1 = ay2;
	    ay2 = t;
	}			/* to be sure that ay1 < ay2 */
	if (by1 > by2) {
	    t = by1;
	    by1 = by2;
	    by2 = t;
	}			/* to be sure that by1 < by2 */
	if (ay1 > by2 || ay2 < by1) {
	    G_debug(2, "   -> no intersection");
	    return 0;
	}

	/* end points */
	if (FEQUAL(ay1, by2, tol)) {
	    *x1 = ax1;
	    *y1 = ay1;
	    G_debug(2, "   -> connected by end points");
	    return 1;		/* endpoints only */
	}
	if (FEQUAL(ay2, by1, tol)) {
	    *x1 = ax2;
	    *y1 = ay2;
	    G_debug(2, "  -> connected by end points");
	    return 1;		/* endpoints only */
	}

	/* general overlap */
	G_debug(3, "   -> vertical overlap");
	/* a contains b */
	if (ay1 <= by1 && ay2 >= by2) {
	    G_debug(2, "    -> a contains b");
	    *x1 = bx1;
	    *y1 = by1;
	    *x2 = bx2;
	    *y2 = by2;
	    if (!switched)
		return 3;
	    else
		return 4;
	}
	/* b contains a */
	if (ay1 >= by1 && ay2 <= by2) {
	    G_debug(2, "    -> b contains a");
	    *x1 = ax1;
	    *y1 = ay1;
	    *x2 = ax2;
	    *y2 = ay2;
	    if (!switched)
		return 4;
	    else
		return 3;
	}

	/* general overlap, 2 intersection points */
	G_debug(2, "    -> partial overlap");
	if (by1 > ay1 && by1 < ay2) {	/* b1 in a */
	    if (!switched) {
		*x1 = bx1;
		*y1 = by1;
		*x2 = ax2;
		*y2 = ay2;
	    }
	    else {
		*x1 = ax2;
		*y1 = ay2;
		*x2 = bx1;
		*y2 = by1;
	    }
	    return 2;
	}

	if (by2 > ay1 && by2 < ay2) {	/* b2 in a */
	    if (!switched) {
		*x1 = bx2;
		*y1 = by2;
		*x2 = ax1;
		*y2 = ay1;
	    }
	    else {
		*x1 = ax1;
		*y1 = ay1;
		*x2 = bx2;
		*y2 = by2;
	    }
	    return 2;
	}

	/* should not be reached */
	G_warning(("Vect_segment_intersection() ERROR (collinear vertical segments)"));
	G_warning("%.15g %.15g", ax1, ay1);
	G_warning("%.15g %.15g", ax2, ay2);
	G_warning("x");
	G_warning("%.15g %.15g", bx1, by1);
	G_warning("%.15g %.15g", bx2, by2);
	return 0;
    }

    G_debug(2, "   -> collinear non vertical");

    /* Collinear non vertical */
    if ((bx1 > ax1 && bx2 > ax1 && bx1 > ax2 && bx2 > ax2) ||
	(bx1 < ax1 && bx2 < ax1 && bx1 < ax2 && bx2 < ax2)) {
	G_debug(2, "   -> no intersection");
	return 0;
    }

    /* there is overlap or connected end points */
    G_debug(2, "   -> overlap/connected end points");

    /* end points */
    if ((ax1 == bx1 && ay1 == by1) || (ax1 == bx2 && ay1 == by2)) {
	*x1 = ax1;
	*y1 = ay1;
	G_debug(2, "    -> connected by end points");
	return 1;
    }
    if ((ax2 == bx1 && ay2 == by1) || (ax2 == bx2 && ay2 == by2)) {
	*x1 = ax2;
	*y1 = ay2;
	G_debug(2, "    -> connected by end points");
	return 1;
    }

    if (ax1 > ax2) {
	t = ax1;
	ax1 = ax2;
	ax2 = t;
	t = ay1;
	ay1 = ay2;
	ay2 = t;
    }				/* to be sure that ax1 < ax2 */
    if (bx1 > bx2) {
	t = bx1;
	bx1 = bx2;
	bx2 = t;
	t = by1;
	by1 = by2;
	by2 = t;
    }				/* to be sure that bx1 < bx2 */

    /* a contains b */
    if (ax1 <= bx1 && ax2 >= bx2) {
	G_debug(2, "    -> a contains b");
	*x1 = bx1;
	*y1 = by1;
	*x2 = bx2;
	*y2 = by2;
	if (!switched)
	    return 3;
	else
	    return 4;
    }
    /* b contains a */
    if (ax1 >= bx1 && ax2 <= bx2) {
	G_debug(2, "    -> b contains a");
	*x1 = ax1;
	*y1 = ay1;
	*x2 = ax2;
	*y2 = ay2;
	if (!switched)
	    return 4;
	else
	    return 3;
    }

    /* general overlap, 2 intersection points (lines are not vertical) */
    G_debug(2, "    -> partial overlap");
    if (bx1 > ax1 && bx1 < ax2) {	/* b1 is in a */
	if (!switched) {
	    *x1 = bx1;
	    *y1 = by1;
	    *x2 = ax2;
	    *y2 = ay2;
	}
	else {
	    *x1 = ax2;
	    *y1 = ay2;
	    *x2 = bx1;
	    *y2 = by1;
	}
	return 2;
    }
    if (bx2 > ax1 && bx2 < ax2) {	/* b2 is in a */
	if (!switched) {
	    *x1 = bx2;
	    *y1 = by2;
	    *x2 = ax1;
	    *y2 = ay1;
	}
	else {
	    *x1 = ax1;
	    *y1 = ay1;
	    *x2 = bx2;
	    *y2 = by2;
	}
	return 2;
    }

    /* should not be reached */
    G_warning(("segment_intersection_2d() ERROR (collinear non vertical segments)"));
    G_warning("%.15g %.15g", ax1, ay1);
    G_warning("%.15g %.15g", ax2, ay2);
    G_warning("x");
    G_warning("%.15g %.15g", bx1, by1);
    G_warning("%.15g %.15g", bx2, by2);

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


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

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

  if (argc < 4)
    usage_exit(1) ;

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

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

  mp.max_grad = 0.3*mri_source->xsize ;

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

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

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

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

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

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

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

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

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

  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("registration took %d minutes and %d seconds.\n", 
	 minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
示例#16
0
int
main(int argc, char *argv[])
{
  char         **av, *in_surf_fname, *out_fname, fname[STRLEN], *cp ;
  int          ac, nargs, msec, err ;
  MRI_SURFACE  *mris ;
  struct timeb then ;
  float        max_dim ;

  char cmdline[CMD_LINE_LEN] ;

  make_cmd_version_string
  (argc, argv,
   "$Id: mris_sphere.c,v 1.57 2011/03/02 00:04:34 nicks Exp $",
   "$Name: stable5 $", cmdline);

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

#ifdef FS_CUDA
  /* print GPU device info */
  MRISCdeviceInfo();
#endif // FS_CUDA

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

  memset(&parms, 0, sizeof(parms)) ;
  parms.dt = .05 ;
  parms.projection = PROJECT_ELLIPSOID ;
  parms.tol = .5 /*1e-1*/ ;
  parms.n_averages = 1024 ;
  parms.min_averages = 0 ;
  parms.l_angle = 0.0 /* L_ANGLE */ ;
  parms.l_area = 0.0 /* L_AREA */ ;
  parms.l_neg = 0.0 ;
  parms.l_dist = 1.0 ;
  parms.l_spring = 0.0 ;
  parms.l_area = 1.0 ;
  parms.l_boundary = 0.0 ;
  parms.l_curv = 0.0 ;
  parms.niterations = 25 ;
  parms.write_iterations = 1000 ;
  parms.a = parms.b = parms.c = 0.0f ;  /* ellipsoid parameters */
  parms.dt_increase = 1.01 /* DT_INCREASE */;
  parms.dt_decrease = 0.99 /* DT_DECREASE*/ ;
  parms.error_ratio = 1.03 /*ERROR_RATIO */;
  parms.integration_type = INTEGRATE_LINE_MINIMIZE ;
  parms.momentum = 0.9 ;
  parms.desired_rms_height = -1.0 ;
  parms.base_name[0] = 0 ;
  parms.Hdesired = 0.0 ;   /* a flat surface */
  parms.nbhd_size = 7 ;
  parms.max_nbrs = 8 ;

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

  parms.scale = scale ;

  if (argc != 3) // catches args beyond the expected two
  {
    usage_exit() ;
  }

  parms.base_dt = base_dt_scale * parms.dt ;
  in_surf_fname = argv[1] ;
  out_fname = argv[2] ;

  printf("%s\n",vcid);
  printf("  %s\n",MRISurfSrcVersion());
  fflush(stdout);

  if (parms.base_name[0] == 0)
  {
    FileNameOnly(out_fname, fname) ;
    cp = strchr(fname, '.') ;
    if (cp)
    {
      strcpy(parms.base_name, cp+1) ;
    }
    else
    {
      strcpy(parms.base_name, "sphere") ;
    }
  }

  mris = MRISread(in_surf_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, in_surf_fname) ;

  MRISaddCommandLine(mris, cmdline) ;

  fprintf(stderr, "reading original vertex positions...\n") ;
  if (!FZERO(disturb))
  {
    mrisDisturbVertices(mris, disturb) ;
  }
  if (quick == 0)
  {
    // don't need original properties unless preserving metric
    err = MRISreadOriginalProperties(mris, orig_name) ;
    if(err)
    {
      exit(1);
    }
  }
  if (smooth_avgs > 0)
  {
    MRISsaveVertexPositions(mris, TMP_VERTICES) ;
    MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRISaverageVertexPositions(mris, smooth_avgs) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
  }

  if (!FZERO(ralpha) || !FZERO(rbeta) || !FZERO(rgamma))
  {
    MRISrotate(mris,mris,RADIANS(ralpha),RADIANS(rbeta),RADIANS(rgamma)) ;
    //                if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRISwrite(mris, "rot") ;
  }
  fprintf(stderr, "unfolding cortex into spherical form...\n");
  if (talairach)
  {
    MRIStalairachTransform(mris, mris) ;
    MRISwrite(mris, "tal") ;
  }

  if (xform_fname)
  {
    LTA *lta ;
    MRI *mri ;
    TRANSFORM transform ;

    lta = LTAread(xform_fname) ;
    if (lta == NULL)
    {
      ErrorExit(ERROR_NOFILE, "%s: could not load %s", xform_fname) ;
    }
    mri = MRIread(vol_fname) ;
    if (mri == NULL)
    {
      ErrorExit(ERROR_NOFILE, "%s: could not load %s", vol_fname) ;
    }
    transform.type = lta->type ;
    transform.xform = (void *)lta ;
    MRIStransform(mris, mri, &transform, mri) ;
    MRIfree(&mri) ;
    LTAfree(&lta) ;
    MRISwrite(mris, "xfm") ;
  }
#if 0
  max_dim = MAX(abs(mris->xlo), abs(mris->xhi)) ;
  max_dim = MAX(abs(max_dim), abs(mris->ylo)) ;
  max_dim = MAX(abs(max_dim), abs(mris->yhi)) ;
  max_dim = MAX(abs(max_dim), abs(mris->zlo)) ;
  max_dim = MAX(abs(max_dim), abs(mris->zhi)) ;
#else
  max_dim = MAX(abs(mris->xhi-mris->xlo), abs(mris->yhi-mris->ylo)) ;
  max_dim = MAX(max_dim,abs(mris->zhi-mris->zlo)) ;
#endif
  if (max_dim > .75*DEFAULT_RADIUS)
  {
    float ratio = .75*DEFAULT_RADIUS / (max_dim) ;
    printf("scaling brain by %2.3f...\n", ratio) ;
    MRISscaleBrain(mris, mris, ratio) ;
  }

  if (target_radius < 0)
  {
    target_radius = sqrt(mris->total_area / (4*M_PI)) ;
    printf("setting target radius to be %2.3f to match surface areas\n",
           target_radius) ;
  }
  //  MRISsampleAtEachDistance(mris, parms.nbhd_size, parms.max_nbrs) ;
  if (!load && inflate)
  {
    INTEGRATION_PARMS inflation_parms ;

    MRIScenter(mris, mris) ;
    memset(&inflation_parms, 0, sizeof(INTEGRATION_PARMS)) ;
    strcpy(inflation_parms.base_name, parms.base_name) ;
    inflation_parms.write_iterations = parms.write_iterations ;
    inflation_parms.niterations = inflate_iterations ;
    inflation_parms.l_spring_norm = l_spring_norm ;
    inflation_parms.l_spring = inflate_spring ;
    inflation_parms.l_nlarea = inflate_nlarea ;
    inflation_parms.l_area = inflate_area ;
    inflation_parms.n_averages = inflate_avgs ;
    inflation_parms.l_expand = l_expand ;
    inflation_parms.l_tspring = inflate_tspring ;
    inflation_parms.l_sphere = l_sphere ;
    inflation_parms.l_convex = l_convex ;
#define SCALE_UP 2
    inflation_parms.a = SCALE_UP*DEFAULT_RADIUS ;
    inflation_parms.tol = inflate_tol ;
    inflation_parms.integration_type = INTEGRATE_MOMENTUM ;
    inflation_parms.momentum = 0.9 ;
    inflation_parms.dt = inflate_dt ;

    /* store the inflated positions in the v->c? field so that they can
      be used in the repulsive term.
    */
    /*    inflation_parms.l_repulse_ratio = .1 ;*/
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    if (l_expand > 0)
    {
      MRISexpandSurface(mris, target_radius/2, &inflation_parms, 0, 1) ;
      l_expand = parms.l_expand = 0 ;
    }
    MRIScenter(mris, mris) ;
    mris->x0 = mris->xctr ;
    mris->y0 = mris->yctr ;
    mris->z0 = mris->zctr ;
    MRISinflateToSphere(mris, &inflation_parms) ;
    if (inflation_parms.l_expand > 0)
    {
      inflation_parms.l_expand = 0 ;
      inflation_parms.niterations += (inflate_iterations*.1) ;
      MRISinflateToSphere(mris, &inflation_parms) ;
    }
    MRISscaleBrain(mris, mris, target_radius/(DEFAULT_RADIUS*SCALE_UP)) ;
    parms.start_t = inflation_parms.start_t ;
    MRISresetNeighborhoodSize(mris, nbrs) ;
  }

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRISwrite(mris, "before") ;
  }
  MRISprojectOntoSphere(mris, mris, target_radius) ;
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
  {
    MRISwrite(mris, "after") ;
  }
  fprintf(stderr,"surface projected - minimizing metric distortion...\n");
  MRISsetNeighborhoodSize(mris, nbrs) ;
  if (quick)
  {
    if (!load)
    {
#if 0
      parms.n_averages = 32 ;
      parms.tol = .1 ;
      parms.l_parea = parms.l_dist = 0.0 ;
      parms.l_nlarea = 1 ;
#endif
      MRISprintTessellationStats(mris, stderr) ;
      MRISquickSphere(mris, &parms, max_passes) ;
    }
  }
  else
  {
    MRISunfold(mris, &parms, max_passes) ;
  }
  if (remove_negative)
  {
    parms.niterations = 1000 ;
    MRISremoveOverlapWithSmoothing(mris,&parms) ;
  }
  if (!load)
  {
    fprintf(stderr, "writing spherical brain to %s\n", out_fname) ;
    MRISwrite(mris, out_fname) ;
  }

  msec = TimerStop(&then) ;
  fprintf(stderr, "spherical transformation took %2.2f hours\n",
          (float)msec/(1000.0f*60.0f*60.0f));
  exit(0) ;
  return(0) ;  /* for ansi */
}
int
main(int argc, char *argv[]) {
  char   **av, fname[STRLEN] ;
  int    ac, nargs, i ;
  MRI    *mri_flash[MAX_IMAGES], *mri_T1, *mri_PD ;
  char   *in_fname, *out_PD_fname, *out_T1_fname ;
  int          msec, minutes, seconds, nvolumes ;
  struct timeb start ;

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

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

  TimerStart(&start) ;
  parms.dt = 1e-6 ;
  parms.tol = 1e-5 ;
  parms.momentum = 0.0 ;
  parms.niterations = 20 ;

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

  if (argc < 4)
    usage_exit(1) ;

  out_T1_fname = argv[argc-2] ;
  out_PD_fname = argv[argc-1] ;
  FileNameOnly(out_T1_fname, fname) ;
  FileNameRemoveExtension(fname, fname) ;
  strcpy(parms.base_name, fname) ;

  nvolumes = 0 ;
  for (i = 1 ; i < argc-2 ; i++) {
    if (argv[i][0] == '-') {
      if (!stricmp(argv[i]+1, "te"))
        te = atof(argv[i+1]) ;
      else if (!stricmp(argv[i]+1, "tr"))
        tr = atof(argv[i+1]) ;
      else if (!stricmp(argv[i]+1, "fa"))
        fa = RADIANS(atof(argv[i+1])) ;
      else
        ErrorExit(ERROR_BADPARM, "%s: unsupported MR parameter %s",
                  Progname, argv[i]+1) ;
      i++ ;  /* skip parameter */
      continue ;
    }

    in_fname = argv[i] ;
    printf("reading %s...", in_fname) ;

    mri_flash[nvolumes] = MRIread(in_fname) ;
    if (!mri_flash[nvolumes])
      ErrorExit(Gerror, "%s: MRIread(%s) failed", Progname, in_fname) ;
    if (tr > 0) {
      mri_flash[nvolumes]->tr = tr ;
      tr = 0 ;
    }
    if (te > 0) {
      mri_flash[nvolumes]->te = te ;
      te = 0 ;
    }
    if (fa > 0) {
      mri_flash[nvolumes]->flip_angle = fa ;
      fa = 0 ;
    }
    printf("TE = %2.2f, TR = %2.2f, alpha = %2.2f\n", mri_flash[nvolumes]->te,
           mri_flash[nvolumes]->tr, DEGREES(mri_flash[nvolumes]->flip_angle)) ;
    mri_flash[nvolumes]->flip_angle = mri_flash[nvolumes]->flip_angle;
    if (conform) {
      MRI *mri_tmp ;

      printf("embedding and interpolating volume\n") ;
      mri_tmp = MRIconform(mri_flash[nvolumes]) ;
      /*      MRIfree(&mri_src) ;*/
      mri_flash[nvolumes] = mri_tmp ;
    }
    if (FZERO(mri_flash[nvolumes]->tr) ||
        FZERO(mri_flash[nvolumes]->flip_angle))
      ErrorExit(ERROR_BADPARM, "%s: invalid TR or FA for image %d:%s",
                Progname, nvolumes, in_fname) ;
    nvolumes++ ;
  }
  printf("using %d FLASH volumes to estimate tissue parameters.\n", nvolumes) ;
  mri_T1 = MRIclone(mri_flash[0], NULL) ;
  mri_PD = MRIclone(mri_flash[0], NULL) ;


  {
    double   sse, last_T1, last_PD, total_rms, avg_rms ;
    int      x, y, z, width, height, depth, total_vox, ignored, nvox ;
    struct timeb first_slice ;

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

    TimerStart(&first_slice) ;

    last_T1 = last_PD = 1000 ;
    sse = 0.0 ;
    width = mri_T1->width ;
    height = mri_T1->height ;
    depth = mri_T1->depth ;
    total_vox = width*depth*height ;
#if 0
    estimateVoxelParameters(mri_flash, nvolumes, width/2, height/2, depth/2,
                            mri_T1, mri_PD, last_T1, last_PD) ;
#endif
    if (Gdiag_no == 999) {
      x = 130 ;
      y = 124 ;
      z = 74 ; /* CSF */
      computeErrorSurface("error_surf_csf.dat",mri_flash,nvolumes,x,y,z,500,3000,500,3000);
      x = 161 ;
      y = 157 ;
      z = 63 ;  /* wm */
      computeErrorSurface("error_surf_wm.dat",mri_flash,nvolumes,x,y,z,250,3000,250,3000);
      x = 166 ;
      y = 153 ;
      z = 63 ;  /* gm */
      computeErrorSurface("error_surf_gm.dat",mri_flash,nvolumes,x,y,z,250,3000,250,3000);
    }
    avg_rms = 0 ;
    for (ignored = z = 0 ; z < depth ; z++) {
      if (z > 0)
        printf("z = %d, avg rms=%2.1f, T1=%2.0f, PD=%2.0f...\n",
               z, avg_rms, last_T1, last_PD) ;
#if 0
      if (z > 0 && z*width*height - ignored > 0) {
        int processed = z*width*height - ignored, hours ;

        msec = TimerStop(&first_slice) ;
        seconds = nint((float)msec/1000.0f) ;
        minutes = seconds / 60 ;
        seconds = seconds % 60 ;
        hours = minutes / 60 ;
        minutes = minutes % 60 ;
        printf("%02d:%02d:%02d total processing time ... ",
               hours,minutes,seconds);
        msec = (int)((float)(total_vox-ignored)*msec/(float)processed) ;
        seconds = nint((float)msec/1000.0f) ;
        minutes = seconds / 60 ;
        seconds = seconds % 60 ;
        hours = minutes / 60 ;
        minutes = minutes % 60 ;
        printf("estimate %02d:%02d:%02d remaining.\n", hours,minutes, seconds);
      }
#endif
      if (write_iterations > 0 && z > 0 && !(z%write_iterations)) {
        printf("writing T1 esimates to %s...\n", out_T1_fname) ;
        printf("writing PD estimates to %s...\n", out_PD_fname) ;
        MRIwrite(mri_T1, out_T1_fname) ;
        MRIwrite(mri_PD, out_PD_fname) ;
        printf("writing residuals to %s...\n", residual_name) ;
        if (residual_name) {
          MRI *mri_res, *mri_res_total = NULL ;
          for (i = 0 ; i < nvolumes ; i++) {

            mri_res = compute_residuals(mri_flash[i], mri_T1, mri_PD) ;
            sprintf(fname, "%s%d.mgh", residual_name, i) ;
#if 0
            MRIwrite(mri_res, fname) ;
#endif
            if (!mri_res_total) {
              mri_res_total = MRIcopy(mri_res, NULL) ;
            } else {
              MRIsadd(mri_res, mri_res_total, mri_res_total) ;
            }

            MRIfree(&mri_res) ;
          }
          MRIsscalarMul(mri_res_total, mri_res_total, 1.0/(float)nvolumes) ;
          MRIssqrt(mri_res_total, mri_res_total) ;
          sprintf(fname, "%s.mgh", residual_name) ;
          MRIwrite(mri_res_total, fname) ;
        }
      }

      nvox = 0 ;
      total_rms = 0 ;
      for (y = 0 ; y < height ; y++) {
#if 0
        if (y%32 == 0 && nvox > 0)
          printf("z = %d, y = %d, avg rms=%2.1f, T1=%2.0f, PD=%2.0f...\n",
                 z, y, total_rms/(double)nvox, last_T1, last_PD) ;
#endif
        for (x = 0 ; x < width ; x++) {
#if 0
          for (i = 0 ; i < nvolumes ; i++)
            if (MRISvox(mri_flash[i],x,y,z) > thresh)
              break ;
          if (i >= nvolumes)
#else
          if (no_valid_data(mri_flash, nvolumes, x, y, z, thresh))
#endif
          {
            ignored++ ;
            MRISvox(mri_T1, x, y, z) = MRISvox(mri_PD, x, y, z) = 0 ;
            /*            last_T1 = last_PD = 1000 ;*/
            continue ;
          }
#if 0
          sse = findInitialParameters(mri_flash, nvolumes, x, y, z,
                                      last_PD-1000, last_PD+1000,
                                      last_T1-1000, last_T1+1000,
                                      &last_PD, &last_T1, 10) ;
#endif
#if 0
          sse = findInitialParameters(mri_flash, nvolumes, x, y, z,
                                      last_PD-100, last_PD+100,
                                      last_T1-100, last_T1+100,
                                      &last_PD, &last_T1, 10) ;
          if (last_T1 <= MIN_T1 || last_PD <= 0) {
            ignored++ ;
            MRISvox(mri_T1, x, y, z) = MRISvox(mri_PD, x, y, z) = 0 ;
            /*            last_T1 = last_PD = 1000 ;*/
            continue ;
          }
#endif
          sse = estimateVoxelParameters(mri_flash, nvolumes, x, y, z,
                                        mri_T1, mri_PD, nsteps) ;
          nvox++ ;
          last_T1 = MRISvox(mri_T1, x, y, z) ;
          last_PD = MRISvox(mri_PD, x, y, z) ;
          total_rms += sqrt(sse/nvolumes) ;
          if (!finite(total_rms))
            DiagBreak() ;
        }
      }
      avg_rms = total_rms / nvox ;
      if (!finite(avg_rms))
        DiagBreak() ;
    }
  }


  printf("writing T1 esimates to %s...\n", out_T1_fname) ;
  printf("writing PD estimates to %s...\n", out_PD_fname) ;
  MRIwrite(mri_T1, out_T1_fname) ;
  MRIwrite(mri_PD, out_PD_fname) ;
  if (residual_name) {
    MRI *mri_res_total = NULL ;

    for (i = 0 ; i < nvolumes ; i++) {
      MRI *mri_res ;

      mri_res = compute_residuals(mri_flash[i], mri_T1, mri_PD) ;
#if 0
      sprintf(fname, "%s%d.mgh", residual_name, i) ;
      MRIwrite(mri_res, fname) ;
#endif
      if (!mri_res_total) {
        mri_res_total = MRIcopy(mri_res, NULL) ;
      } else {
        MRIsadd(mri_res, mri_res_total, mri_res_total) ;
      }
      MRIfree(&mri_res) ;
    }
    MRIsscalarMul(mri_res_total, mri_res_total, 1.0/(float)nvolumes) ;
    MRIssqrt(mri_res_total, mri_res_total) ;
    sprintf(fname, "%s.mgh", residual_name) ;
    MRIwrite(mri_res_total, fname) ;
  }
  MRIfree(&mri_T1) ;
  MRIfree(&mri_PD) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("parameter estimation took %d minutes and %d seconds.\n",
         minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
示例#18
0
int
RFclassify(RANDOM_FOREST *rf, double *feature, double *p_pval, int true_class)
{
  int    max_class = -1, n, c ;
  NODE   *node ;
  double max_count, class_counts[MAX_CLASSES], total_count ;
  TREE   *tree ;

  memset(class_counts, 0, sizeof(class_counts)) ;
  for (n = 0 ; n < rf->ntrees ; n++)
  {
    tree = &rf->trees[n] ;

    // now prune trees that only had one training class as they just bias labeling
    for (c = 0 ; c < rf->nclasses ; c++)
      if (tree->root.class_counts[c] == tree->root.total_counts)
	break ;
    if (c < rf->nclasses)  // one class has all counts - prune this tree
      continue ;  // don't use this tree in classification
    node = rfFindLeaf(rf, &tree->root, feature) ;
    for (c = 0 ; c < rf->nclasses ; c++)
      class_counts[c] += node->class_counts[c] ;

    if (DIAG_VERBOSE_ON)
    {
      int t ;

      printf("tree %d: ", n) ;
      for  (c = 0 ; c < rf->nclasses ; c++)
	printf(" C%d=%2.f (%d) ", c, 100.0f*tree->root.class_counts[c]/tree->root.total_counts, 
	       tree->root.class_counts[c]) ;
      for (t = 0 ; t < tree->nleaves ; t++)  // diagnostic
	if (node == tree->leaves[t])
	{
	  printf("leaf %d: ", t) ;
	  for  (c = 0 ; c < rf->nclasses ; c++)
	    printf(" C%d=%2.0f (%d) ", c, 100.0*(float)node->class_counts[c]/node->total_counts, 
		   node->class_counts[c]) ;
	  printf("\n") ;
	}
    }
  }

  for (total_count = c = 0 ; c < rf->nclasses ; c++)
    total_count += class_counts[c] ;
  if (FZERO(total_count))
    return(0) ;
  for (max_count = c = 0 ; c < rf->nclasses ; c++)
  {
    if (class_counts[c] > max_count)
    {
      max_count = class_counts[c] ;
      max_class = c ;
      if (p_pval)
	*p_pval = (double)class_counts[c]/total_count ;
    }
    rf->pvals[c] = (double)class_counts[c]/total_count ;
  }

  if (DIAG_VERBOSE_ON) for (c = 0 ; c < rf->nclasses ; c++)
  {
    if (true_class >= 0)
    {
      if (c == max_class)
      {
        printf("%s: p = %2.2f ", rf->class_names[c], 100.0*class_counts[c]/total_count) ;
        if (c==true_class)
          printf("CORRECT\n") ;
        else
          printf("(true = %s, p = %2.2f)\n", rf->class_names[true_class], 100.0*class_counts[true_class]/total_count) ;
      }
    }
    else
      printf("%s: p = %2.2f %s\n", 
             rf->class_names[c], 100*(double)class_counts[c]/total_count, 
	     c==max_class?"MAX":"") ;

  }
  return(max_class) ;
}
static MRI *
MRIcomputeSurfaceDistanceIntensities(MRI_SURFACE *mris,  MRI *mri_ribbon, MRI *mri_aparc, MRI *mri, MRI *mri_aseg, int whalf) 
{
  MRI          *mri_features, *mri_binary, *mri_white_dist, *mri_pial_dist ;
  int          vno, ngm, outside_of_ribbon, label0, label, ohemi_label, xi, yi, zi, xk, yk, zk, x0, y0, z0, hemi_label, assignable ;
  double       xv, yv, zv, step_size, dist, thickness, wdist, pdist, snx, sny, snz, nx, ny, nz, xl, yl, zl, x, y, z, dot, angle ;
  VERTEX       *v ;

  mri_features = MRIallocSequence(mris->nvertices, 1, 1, MRI_FLOAT, 1) ;  // one samples inwards, one in ribbon, and one outside
  MRIcopyHeader(mri, mri_features) ;

  mri_binary = MRIcopy(mri_ribbon, NULL) ;
  mri_binary = MRIbinarize(mri_ribbon, NULL, 1, 0, 1) ;
  mri_pial_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_pial_dist+1, DTRANS_MODE_SIGNED,NULL);
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRIwrite(mri_pial_dist, "pd.mgz") ;

  MRIclear(mri_binary) ;
  MRIcopyLabel(mri_ribbon, mri_binary, Left_Cerebral_White_Matter) ;
  MRIcopyLabel(mri_ribbon, mri_binary, Right_Cerebral_White_Matter) ;
  MRIbinarize(mri_binary, mri_binary, 1, 0, 1) ;
  mri_white_dist = MRIdistanceTransform(mri_binary, NULL, 1, max_white_dist+1, DTRANS_MODE_SIGNED,NULL);
  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRIwrite(mri_white_dist, "wd.mgz") ;

  if (mris->hemisphere == LEFT_HEMISPHERE)
  {
    ohemi_label = Right_Cerebral_Cortex ;
    hemi_label = Left_Cerebral_Cortex ;
  }
  else
  {
    hemi_label = Right_Cerebral_Cortex ;
    ohemi_label = Left_Cerebral_Cortex ;
  }

  step_size = mri->xsize/2 ;
  for (vno = 0 ; vno < mris->nvertices ; vno++)
  {
    v = &mris->vertices[vno] ;
    if (vno == Gdiag_no)
      DiagBreak() ;
    if (v->ripflag)
      continue ;  // not cortex
    nx = v->pialx - v->whitex ; ny = v->pialy - v->whitey ; nz = v->pialz - v->whitez ;
    thickness = sqrt(nx*nx + ny*ny + nz*nz) ;
    if (FZERO(thickness))
      continue ;   // no  cortex here


    x = (v->pialx + v->whitex)/2 ; y = (v->pialy + v->whitey)/2 ; z = (v->pialz + v->whitez)/2 ;  // halfway between white and pial is x0
    MRISsurfaceRASToVoxelCached(mris, mri_aseg, x, y, z, &xl, &yl, &zl) ;
    x0 = nint(xl); y0 = nint(yl) ; z0 = nint(zl) ;
    label0 = MRIgetVoxVal(mri_aparc, x0, y0, z0,0) ;

    // compute surface normal in voxel coords
    MRISsurfaceRASToVoxelCached(mris, mri_aseg, x+v->nx, y+v->ny, z+v->nz, &snx, &sny, &snz) ;
    snx -= xl ; sny -= yl ; snz -= zl ;

    for (ngm = 0, xk = -whalf ; xk <= whalf ; xk++)
    {
      xi = mri_aseg->xi[x0+xk] ;
      for (yk = -whalf ; yk <= whalf ; yk++)
      {
	yi = mri_aseg->yi[y0+yk] ;
	for (zk = -whalf ; zk <= whalf ; zk++)
	{
	  zi = mri_aseg->zi[z0+zk] ;
	  label = MRIgetVoxVal(mri_aseg, xi, yi, zi,0) ;
	  if (xi == Gx && yi == Gy && zi == Gz)
	    DiagBreak() ;
	  if (label != hemi_label)
	    continue ;
	  label = MRIgetVoxVal(mri_aparc, xi, yi, zi,0) ;
	  if (label && label != label0)  // if  outside the ribbon it won't be assigned to a parcel
	    continue ;  // constrain it to be in the same cortical parcel

	  // search along vector connecting x0 to this point to make sure it is we don't perforate wm or leave and re-enter cortex
	  nx = xi-x0 ; ny = yi-y0 ; nz = zi-z0 ;
	  thickness = sqrt(nx*nx + ny*ny + nz*nz) ;
	  assignable = 1 ;  // assume this point should be counted
	  if (thickness > 0)
	  {
	    nx /= thickness ; ny /= thickness ; nz /= thickness ;
	    dot = nx*snx + ny*sny + nz*snz ; angle = acos(dot) ;
	    if (FABS(angle) > angle_threshold)
	      assignable = 0 ;
	    outside_of_ribbon = 0 ;
	    for (dist = 0 ; assignable && dist <= thickness ; dist += step_size) 
	    {
	      xv = x0+nx*dist ;  yv = y0+ny*dist ;  zv = z0+nz*dist ; 
	      if (nint(xv) == Gx && nint(yv) == Gy && nint(zv) == Gz)
		DiagBreak() ;
	      MRIsampleVolume(mri_pial_dist, xv, yv, zv, &pdist) ;
	      MRIsampleVolume(mri_white_dist, xv, yv, zv, &wdist) ;
	      label = MRIgetVoxVal(mri_aseg, xi, yi, zi,0) ;
	      if (SKIP_LABEL(label) || label == ohemi_label)
		assignable = 0 ;
	      if (wdist < 0)  // entered wm - not assignable
		assignable = 0 ;
	      else
	      {
		if (pdist > 0)  // outside pial surface
		  outside_of_ribbon = 1 ;
		else
		{
		  if (outside_of_ribbon) // left ribbon and reentered
		    assignable = 0 ;
		}
	      }
	    }
	  }  // close of thickness > 0
	  if (assignable)
	    ngm++ ;
	  else
	    DiagBreak() ;
	}
      }
    }
    
    MRIsetVoxVal(mri_features, vno, 0, 0, 0, ngm) ;
  }

  MRIfree(&mri_white_dist) ; MRIfree(&mri_pial_dist) ; MRIfree(&mri_binary) ;
  return(mri_features) ;
}
static int
normalize_timepoints(MRI *mri, double thresh, double cross_time_sigma)
{
  int   frame, x, y, z, skip, nvox ;
  double target, val ;
  MRI    *mri_ctrl, *mri_bias, *mri_target, *mri_frame, *mri_kernel ;

  mri_ctrl = MRIcloneDifferentType(mri, MRI_UCHAR) ;
  mri_bias = MRIcloneDifferentType(mri, MRI_FLOAT) ;
  mri_target = MRIcloneDifferentType(mri, MRI_FLOAT) ;
  mri_kernel = MRIgaussian1d(cross_time_sigma, -1) ;

  for (nvox = x = 0 ; x < mri->width ; x++)
    for (y = 0 ; y < mri->height ; y++)
      for (z = 0 ; z < mri->depth ; z++)
      {
        if (x == Gx && y == Gy && z == Gz)
          DiagBreak() ;
        for (target = 0.0, frame = 0 ; frame < mri->nframes ; frame++)
          target += MRIgetVoxVal(mri, x, y, z, frame) ;
        target /= mri->nframes ;
        if (FZERO(target))
          continue ;  // both vals  0
        skip = 0 ;
        for (frame = 0 ; frame < mri->nframes ; frame++)
        {
          val = MRIgetVoxVal(mri, x, y, z, frame) ;
          if (fabs(val-target) > thresh)
          {
            skip = 1 ;
            break ;
          }
        }
        if (skip)
          continue ;
        nvox++ ;
        MRIsetVoxVal(mri_ctrl, x, y, z, 0, CONTROL_MARKED) ;
        MRIsetVoxVal(mri_target, x, y, z, 0, target) ;
      }

  printf("%d voxels found to base intensity correction on\n", nvox) ;

  // build a bias correction for each time point (which each has its own frame)
  for (frame = 0 ; frame < mri->nframes ; frame++)
  {
    MRIclear(mri_bias) ; 
    for (x = 0 ; x < mri->width ; x++)
      for (y = 0 ; y < mri->height ; y++)
        for (z = 0 ; z < mri->depth ; z++)
        {
          target = MRIgetVoxVal(mri_target, x, y, z, 0) ;
          val = MRIgetVoxVal(mri, x, y, z, frame) ;
          if (FZERO(val))
            val = 1.0 ;
          MRIsetVoxVal(mri_bias, x, y, z, 0, target/val) ;
        }
    MRIbuildVoronoiDiagram(mri_bias, mri_ctrl, mri_bias) ;
    MRIconvolveGaussian(mri_bias, mri_bias, mri_kernel) ;
    //    MRIsoapBubble(mri_bias, mri_ctrl, mri_bias, nsoap) ;
    mri_frame = MRIcopyFrame(mri, NULL, frame, 0) ;
    MRImultiply(mri_frame, mri_bias, mri_frame) ;
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    {
      char fname[STRLEN] ;
      sprintf(fname, "frame%d.mgz", frame) ;
      MRIwrite(mri_frame, fname) ;
      sprintf(fname, "bias%d.mgz", frame) ;
      MRIwrite(mri_bias, fname) ;
      sprintf(fname, "target%d.mgz", frame) ;
      MRIwrite(mri_target, fname) ;
    }
    MRIcopyFrame(mri_frame, mri, 0, frame) ;
  }
  MRIfree(&mri_bias) ; MRIfree(&mri_kernel) ; MRIfree(&mri_target) ; MRIfree(&mri_ctrl) ;
  return(NO_ERROR) ;
}
示例#21
0
int
main(int argc, char *argv[]) {
  char   **av ;
  int    ac, nargs, width, height, depth, x, y, z, xborder, yborder, zborder,
  xrborder, yrborder, zrborder ;
  char   *in_fname, *out_fname ;
  MRI    *mri_smooth, *mri_grad, *mri_filter_src, *mri_filter_dst, *mri_dst,
  *mri_tmp, *mri_blur, *mri_src, *mri_filtered, *mri_direction,
  *mri_offset, *mri_up, *mri_polv, *mri_dir, *mri_clip, *mri_full ;
  MRI_REGION  region, clip_region ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_nlfilter.c,v 1.14 2011/03/02 00:04:23 nicks Exp $", "$Name:  $");
  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 < 3)
    usage_exit() ;

  in_fname = argv[1] ;
  out_fname = argv[2] ;

  mri_full = mri_src = MRIread(in_fname) ;
  if (!mri_src)
    ErrorExit(ERROR_NOFILE, "%s: could not read '%s'", Progname, in_fname) ;
  if (!FZERO(blur_sigma))   /* allocate a blurring kernel */
  {
    mri_blur = MRIgaussian1d(blur_sigma, 0) ;
    if (!mri_blur)
      ErrorExit(ERROR_BADPARM,
                "%s: could not allocate blurring kernel with sigma=%2.3f",
                Progname, blur_sigma) ;
  } else
    mri_blur = NULL ;

  MRIboundingBox(mri_full, 0, &clip_region) ;
  REGIONexpand(&clip_region, &clip_region, (filter_window_size+1)/2) ;
  mri_src = MRIextractRegion(mri_full, NULL, &clip_region) ;
  width = mri_src->width ;
  height = mri_src->height ;
  depth = mri_src->depth ;
  mri_dst = MRIclone(mri_src, NULL) ;
  if (!mri_dst)
    ErrorExit(ERROR_NOFILE, "%s: could allocate space for destination image",
              Progname) ;

  for (z = 0 ; z < depth ; z += region_size) {
    for (y = 0 ; y < height ; y += region_size) {
      DiagHeartbeat((float)(z*height+y) / (float)(height*(depth-1))) ;
      for (x = 0 ; x < width ; x += region_size) {
        region.x = x ;
        region.y = y ;
        region.z = z ;
        region.dx = region.dy = region.dz = region_size ;
        if (region.x == 142)
          DiagBreak() ;
        REGIONexpand(&region, &region, (filter_window_size+1)/2) ;
        MRIclipRegion(mri_src, &region, &region) ;
        if (region.x == 142)
          DiagBreak() ;

        /* check for < 0 width regions */
        xborder = x-region.x ;
        yborder = y-region.y ;
        zborder = z-region.z ;
        xrborder = MAX(0, (region.dx-xborder) - region_size) ;
        yrborder = MAX(0, (region.dy-yborder) - region_size) ;
        zrborder = MAX(0, (region.dz-zborder) - region_size) ;
#if 0
        if (region.dx < 2*xborder || region.dy<2*yborder||region.dz<2*zborder)
          continue ;
#endif

        if (DIAG_VERBOSE_ON && (Gdiag & DIAG_SHOW))
          fprintf(stderr, "extracting region (%d, %d, %d) --> (%d, %d, %d)...",
                  region.x,region.y,region.z, region.x+region.dx-1,
                  region.y+region.dy-1,region.z+region.dz-1) ;
        mri_clip = MRIextractRegion(mri_src, NULL, &region) ;
        if (DIAG_VERBOSE_ON && (Gdiag & DIAG_SHOW))
          fprintf(stderr, "done.\nsmoothing region and up-sampling...") ;

        if (mri_blur)   /* smooth the input image to generate offset field */
          mri_smooth = MRIconvolveGaussian(mri_clip, NULL, mri_blur) ;
        else
          mri_smooth = MRIcopy(mri_clip, NULL) ;  /* no smoothing */
        if (!mri_smooth)
          ErrorExit(ERROR_BADPARM, "%s: image smoothing failed", Progname) ;

        /* now up-sample the smoothed image, and compute offset field in
           up-sampled domain */
        mri_up = MRIupsample2(mri_smooth, NULL) ;
        if (!mri_up)
          ErrorExit(ERROR_BADPARM, "%s: up sampling failed", Progname) ;
        MRIfree(&mri_smooth) ;
        if (DIAG_VERBOSE_ON && (Gdiag & DIAG_SHOW))
          fprintf(stderr, "done.\n") ;
        mri_smooth = mri_up ;
        mri_grad = MRIsobel(mri_smooth, NULL, NULL) ;
        mri_dir = MRIclone(mri_smooth, NULL) ;
        MRIfree(&mri_smooth) ;
        if (DIAG_VERBOSE_ON && (Gdiag & DIAG_SHOW))
          fprintf(stderr, "computing direction map...") ;
        mri_direction =
          MRIoffsetDirection(mri_grad, offset_window_size, NULL, mri_dir) ;

        if (DIAG_VERBOSE_ON && (Gdiag & DIAG_SHOW))
          fprintf(stderr, "computing offset magnitudes...") ;
        MRIfree(&mri_grad) ;
        mri_offset =
          MRIoffsetMagnitude(mri_direction, NULL, offset_search_len);
        MRIfree(&mri_direction) ;
        if (!mri_offset)
          ErrorExit(ERROR_NOMEMORY,
                    "%s: offset calculation failed", Progname) ;
        if (DIAG_VERBOSE_ON && (Gdiag & DIAG_SHOW))
          fprintf(stderr, "done.\nfiltering image...") ;
        mri_filter_src = MRIupsample2(mri_clip, NULL) ;
        MRIfree(&mri_clip) ;
        switch (filter_type) {
        case FILTER_CPOLV_MEDIAN:
          mri_polv = MRIplaneOfLeastVarianceNormal(mri_filter_src,NULL,5);
          mri_filter_dst =
            MRIpolvMedian(mri_filter_src, NULL, mri_polv,filter_window_size);
          MRIfree(&mri_polv) ;
          break ;
        case FILTER_GAUSSIAN:
          mri_filter_dst =
            MRIconvolveGaussian(mri_filter_src, NULL, mri_gaussian) ;
          if (!mri_filter_dst)
            ErrorExit(ERROR_NOMEMORY,
                      "%s: could not allocate temporary buffer space",Progname);
          break ;
        case FILTER_MEDIAN:
          mri_filter_dst = MRImedian(mri_filter_src,NULL,filter_window_size, NULL);
          if (!mri_filter_dst)
            ErrorExit(ERROR_NOMEMORY,
                      "%s: could not allocate temporary buffer space",Progname);
          break ;
        case FILTER_MEAN:
          mri_filter_dst = MRImean(mri_filter_src, NULL, filter_window_size) ;
          if (!mri_filter_dst)
            ErrorExit(ERROR_NOMEMORY,
                      "%s: could not allocate temporary buffer space",Progname);
          break ;
        case FILTER_MINMAX:
          mri_filter_dst =
            MRIminmax(mri_filter_src, NULL, mri_dir, filter_window_size) ;
          if (!mri_filter_dst)
            ErrorExit(ERROR_NOMEMORY,
                      "%s: could not allocate space for filtered image",
                      Progname) ;
          break ;
        default:
          mri_filter_dst = MRIcopy(mri_filter_src, NULL) ; /* no filtering */
          break ;
        }
        MRIfree(&mri_dir) ;
        MRIfree(&mri_filter_src) ;

        if (no_offset)
        {
          mri_filtered = MRIcopy(mri_filter_dst, NULL) ;
        }
        else
        {
          if (DIAG_VERBOSE_ON && (Gdiag & DIAG_SHOW))
            fprintf(stderr, "applying offset field...") ;
          if (Gdiag & DIAG_WRITE)
            MRIwrite(mri_filter_dst, "minmax.mgz") ;
          mri_filtered = MRIapplyOffset(mri_filter_dst, NULL, mri_offset) ;
          if (!mri_filtered)
            ErrorExit(ERROR_NOMEMORY,
                      "%s: could not allocate filtered image", Progname) ;
          if (DIAG_VERBOSE_ON && (Gdiag & DIAG_SHOW))
            fprintf(stderr, "done.\n") ;
          if (region.x == 142)
          DiagBreak() ;
          MRIfree(&mri_offset) ;
        }
        MRIfree(&mri_filter_dst) ;
        if (Gdiag & DIAG_WRITE)
          MRIwrite(mri_filtered, "upfilt.mgz") ;
        mri_tmp = MRIdownsample2(mri_filtered, NULL) ;
        MRIfree(&mri_filtered) ;
        if (Gdiag & DIAG_WRITE)
          MRIwrite(mri_tmp, "downfilt.mgz") ;
        region.x += xborder ;
        region.y += yborder ;
        region.z += zborder ;
#if 0
        region.dx -=2*xborder;
        region.dy-= 2*yborder;
        region.dz -= 2 * zborder;
#else
        region.dx -= xrborder + xborder;
        region.dy -= yrborder + yborder;
        region.dz -= zrborder + zborder;
#endif
        if (region.dx <= 0 || region.dy <= 0 || region.dz <= 0) {
          fprintf(stderr, "invalid region: (%d,%d,%d) --> (%d,%d,%d)\n",
                  region.x,region.y,region.z,region.dx,region.dy,region.dz);
        } else
          MRIextractIntoRegion(mri_tmp,mri_dst,xborder,yborder,zborder,&region);
        MRIfree(&mri_tmp);
      }
    }
  }
  MRIextractIntoRegion(mri_dst,mri_full, 0, 0, 0, &clip_region);
  MRIfree(&mri_dst) ;
  if (DIAG_VERBOSE_ON && (Gdiag & DIAG_SHOW))
    fprintf(stderr, "writing output image %s...", out_fname) ;
  MRIwrite(mri_full, out_fname) ;
  MRIfree(&mri_full) ;
  if (DIAG_VERBOSE_ON && (Gdiag & DIAG_SHOW))
    fprintf(stderr, "done.\n") ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
示例#22
0
int
main(int argc, char *argv[])
{
  char        **av, *in_fname, *out_fname ;
  int         ac, nargs, i, label ;
  MRI         *mri_in, *mri_out, *mri_kernel, *mri_smoothed ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_extract_label.c,v 1.13 2011/03/02 00:04:15 nicks Exp $",
           "$Name:  $");
  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 < 4)
    usage_exit() ;

  in_fname = argv[1] ;
  out_fname = argv[argc-1] ;

  printf("reading volume from %s...\n", in_fname) ;
  mri_in = MRIread(in_fname) ;
  if (!mri_in)
    ErrorExit(ERROR_NOFILE, "%s: could not read MRI volume %s", Progname,
              in_fname) ;
  if (out_like_fname)
  {
    MRI *mri_tmp = MRIread(out_like_fname) ;
    if (!mri_tmp)
      ErrorExit
      (ERROR_NOFILE,
       "%s: could not read template volume from %s",
       out_like_fname) ;
    mri_out = MRIalloc(mri_tmp->width,
                       mri_tmp->height,
                       mri_tmp->depth,
                       mri_tmp->type) ;
    /*    MRIcopyHeader(mri_tmp, mri_out) ;*/
    MRIfree(&mri_tmp) ;
  }
  else
    mri_out = MRIclone(mri_in, NULL) ;

  for (i = 2 ; i < argc-1 ; i++)
  {
    label = atoi(argv[i]) ;
    printf("extracting label %d (%s)\n", label, cma_label_to_name(label)) ;
    extract_labeled_image(mri_in, transform, label, mri_out) ;
  }
  if (!FZERO(sigma))
  {
    printf("smoothing extracted volume...\n") ;
    mri_kernel = MRIgaussian1d(sigma, 10*sigma) ;
    mri_smoothed = MRIconvolveGaussian(mri_out, NULL, mri_kernel) ;
    MRIfree(&mri_out) ;
    mri_out = mri_smoothed ;
  }
  /* removed for gcc3.3
   * vsprintf(out_fname, out_fname, (va_list) &label) ;
   */
  if (dilate > 0)
  {
    int i ;
    printf("dilating output volume %d times...\n", dilate) ;
    for (i = 0 ; i < dilate ; i++)
      MRIdilate(mri_out, mri_out) ;
  }
  if (erode > 0)
  {
    int i ;
    printf("eroding output volume %d times...\n", erode) ;
    for (i = 0 ; i < erode ; i++)
      MRIerode(mri_out, mri_out) ;
  }
  printf("writing output to %s.\n", out_fname) ;
  MRIwrite(mri_out, out_fname) ;

  if (exit_none_found && (nvoxels == 0))
  {
    printf("No voxels with specified label were found!\n");
    exit(1);
  }

  exit(0) ;
  return(0) ;  /* for ansi */
}
示例#23
0
static int
discard_unlikely_control_points(GCA *gca, GCA_SAMPLE *gcas, int nsamples,
                                MRI *mri_in, TRANSFORM *transform, char *name)
{
  int    i, xv, yv, zv, n, peak, start, end, num ;
  HISTO *h, *hsmooth ;
  float  fmin, fmax ;
  Real   val,  mean_ratio ;

  if (nsamples == 0)
    return(NO_ERROR) ;

  for (num = n = 0 ; n < mri_in->nframes ; n++)
  {
    int niter = 0 ;
    MRIvalRangeFrame(mri_in, &fmin, &fmax, n) ;
    h = HISTOalloc(nint(fmax-fmin)+1) ;
    h->bin_size = (fmax-fmin)/(float)h->nbins ;
    for (i = 0 ; i < h->nbins ; i++)
      h->bins[i] = (i+1)*h->bin_size+fmin ;

    for (i = 0 ; i < nsamples ; i++)
    {
      xv = gcas[i].x ; yv = gcas[i].y ; zv = gcas[i].z ;
      if (xv == Gx && yv == Gy && zv == Gz)
        DiagBreak() ;
      MRIsampleVolumeFrame(mri_in, gcas[i].x,gcas[i].y,gcas[i].z, n, &val) ;
      if (FZERO(val))
        DiagBreak() ;
      h->counts[nint(val-fmin)]++ ;
    }

    /* check to see  if peak is unlikely */
    hsmooth = HISTOsmooth(h, NULL, 2) ;
    do
    {
      if (gca->ninputs == 1) /*  find  brightest peak as
                                 for  n=1 it is T1  weighted  */
        peak = HISTOfindLastPeak(hsmooth, HISTO_WINDOW_SIZE,MIN_HISTO_PCT);
      else
        peak = HISTOfindHighestPeakInRegion(hsmooth, 0, h->nbins-1) ;
      end = HISTOfindEndOfPeak(hsmooth, peak, 0.01) ;
      start = HISTOfindStartOfPeak(hsmooth, peak, 0.01) ;
      for (mean_ratio = 0.0, i = 0 ; i < nsamples ; i++)
      {
        mean_ratio += hsmooth->bins[peak] / gcas[i].means[0];
      }
      mean_ratio /= (Real)nsamples ;
      HISTOclearBins
        (hsmooth, hsmooth, hsmooth->bins[start], hsmooth->bins[end])  ;
      if (niter++ > 5)
        break ;
      if (niter > 1)
        DiagBreak() ;
    } while  (mean_ratio  < 0.5 || mean_ratio > 2.0) ;

    printf("%s: limiting intensities to %2.1f --> %2.1f\n",
           name, fmin+start, fmin+end) ;
    for (i = 0 ; i < nsamples ; i++)
    {
      xv = gcas[i].x ; yv = gcas[i].y ; zv = gcas[i].z ;
      if (xv == Gx && yv == Gy && zv == Gz)
        DiagBreak() ;
      MRIsampleVolumeFrame(mri_in,gcas[i].x,gcas[i].y,gcas[i].z,n,&val) ;
      if (val-fmin < start || val-fmin > end)
      {
        num++ ; gcas[i].label = 0 ;
      }
    }
    HISTOfree(&h) ; HISTOfree(&hsmooth) ;
  }

  printf("%d of %d (%2.1f%%) samples deleted\n",
         num, nsamples, 100.0f*(float)num/(float)nsamples) ;
  return(NO_ERROR) ;
}
示例#24
0
/*----------------------------------------------------------------------
            Parameters:

           Description:
----------------------------------------------------------------------*/
void
KernelNormalize(KIMAGE *kimage, int row, int col)
{
  KERNEL         *kernel ;
  register float *w, total ;
  int            krow, kcol, cols, krows, kcols ;

  kernel = KIMAGEpix(kimage, row, col) ;
  cols = kernel->cols ;

  /* set kernel locations outside of image to 0 */
  krows = -kernel->row0 ;
  for (krow = 0 ; krow < krows ; krow++)  /* erase 1st krows */
  {
    w = kernel->weights[krow] ;
    memset((char *)w, 0, kernel->cols*sizeof(float)) ;
  }
  kcols = -kernel->col0 ;
  if (kcols > 0)                          /* erase 1st kcols */
  {
    for (krow = 0 ; krow < kernel->rows ; krow++)
    {
      w = kernel->weights[krow] ;
      memset((char *)w, 0, kcols*sizeof(float)) ;
    }
  }
  kcols = kernel->col0 + kernel->cols - kimage->cols ;
  if (kcols > 0)                         /* erase last kcols */
  {
    for (krow = 0 ; krow < kernel->rows ; krow++)
    {
      w = kernel->weights[krow] ;
      memset((char *)(w+kernel->cols-kcols), 0, kcols*sizeof(float)) ;
    }
  }
  krows = kernel->row0 + kernel->rows - kimage->rows ;
  kcols = kernel->cols ;
  for (krow = kernel->rows-krows ; krow < kernel->rows ; krow++)
  {                                   /* erase last krows */
    w = kernel->weights[krow] ;
    memset((char *)w, 0, kcols*sizeof(float)) ;
  }

#if 0
  /* make kernel positive */
  for (kmin = 100000.0f, krow = 0 ; krow < kernel->rows ; krow++)
  {
    w = kernel->weights[krow] ;
    for (kcol = 0 ; kcol < cols ; kcol++, w++)
    {
      if (*w < kmin)
        kmin = *w ;
    }
  }
  for (krow = 0 ; krow < kernel->rows ; krow++)
  {
    w = kernel->weights[krow] ;
    for (kcol = 0 ; kcol < cols ; kcol++)
      *w++ -= kmin ;
  }
#endif

  /* now normalize total weights to be 1 */
  for (total = 0.0f, krow = 0 ; krow < kernel->rows ; krow++)
  {
    w = kernel->weights[krow] ;
    for (kcol = 0 ; kcol < cols ; kcol++)
    {
      total += (float)fabs(*w++) ;
    }
  }

  if (FZERO(total))    /* shouldn't happen */
  {
    fprintf(stderr, "KernelNormalize(%d, %d): zero total!\n", row, col) ;
    return ;
  }

  for (krow = 0 ; krow < kernel->rows ; krow++)
  {
    w = kernel->weights[krow] ;
    for (col = 0 ; col < cols ; col++)
      *w++ /= total ;
  }
}
示例#25
0
static GCA_SAMPLE *
find_control_points(GCA *gca, GCA_SAMPLE *gcas_total,
                    int total_samples, int *pnorm_samples, int nregions, int label,
                    MRI *mri_in, TRANSFORM *transform, double min_prior, double ctl_point_pct)
{
  int        i, j, *ordered_indices, nsamples,
    xmin, ymin, zmin, xmax, ymax, zmax, xv,yv,zv,
    x, y, z, xi, yi, zi, region_samples,
    used_in_region, prior_wsize=5, image_wsize=3, histo_peak, n,
    nbins ;
  GCA_SAMPLE *gcas, *gcas_region, *gcas_norm ;
  double     means[MAX_GCA_INPUTS], vars[MAX_GCA_INPUTS], val, nsigma ;
  HISTOGRAM  *histo, *hsmooth ;
  GC1D       *gc ;
  float      fmin, fmax ;
  MRI        *mri_T1 = NULL ;


  if (label == Gdiag_no)
    DiagBreak() ;

  MRIvalRange(mri_in, &fmin, &fmax) ;
  nbins = (int)(fmax-fmin+1);
  histo = HISTOalloc(nbins) ; hsmooth = HISTOalloc(nbins) ;
  for (nsamples = i = 0 ; i < total_samples ; i++)
  {
    if (gcas_total[i].label != label)
      continue ;
    nsamples++ ;
  }

  *pnorm_samples = 0 ;
  printf("found %d control points for structure...\n", nsamples) ;
  if (nsamples == 0)
  {
    DiagBreak() ;
    return(NO_ERROR) ;
  }
  gcas = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)) ;
  gcas_region = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)) ;
  gcas_norm = (GCA_SAMPLE *)calloc(nsamples, sizeof(GCA_SAMPLE)) ;
  if (!gcas || !gcas_region || !gcas_norm)
    ErrorExit
      (ERROR_NOMEMORY,
       "find_control_points: could not allocate %d samples\n",nsamples);

  for (j = i = 0 ; i < total_samples ; i++)
  {
    if (gcas_total[i].label != label)
      continue ;
    memmove(&gcas[j], &gcas_total[i], sizeof(GCA_SAMPLE)) ;
    j++ ;
  }
  ordered_indices = (int *)calloc(nsamples, sizeof(int)) ;

  gcas_bounding_box(gcas, nsamples, &xmin, &ymin, &zmin, &xmax, &ymax, &zmax, label) ;
  printf("bounding box (%d, %d, %d) --> (%d, %d, %d)\n",
         xmin, ymin, zmin, xmax, ymax, zmax) ;
  for (x = 0 ; x < nregions ; x++)
  {
    for (y = 0 ; y < nregions ; y++)
    {
      for (z = 0 ; z < nregions ; z++)
      {
        /* only process samples in this region */
        nsigma = 1.0 ;
        do
        {
          for (region_samples = i = 0 ; i < nsamples ; i++)
          {
            xi = (int)(nregions*(gcas[i].x - xmin) / (xmax-xmin+1)) ;
            yi = (int)(nregions*(gcas[i].y - ymin) / (ymax-ymin+1)) ;
            zi = (int)(nregions*(gcas[i].z - zmin) / (zmax-zmin+1)) ;
            if ((xi < 0 || xi >= nregions) ||
                (yi < 0 || yi >= nregions) ||
                (zi < 0 || zi >= nregions))
              DiagBreak() ;
            xv = gcas[i].x ; yv = gcas[i].y ; zv = gcas[i].z ;
            if (xi != x || yi != y || zi != z
                || gcas[i].prior < min_prior)
              continue ;

            if (xv == Gx && yv == Gy && zv == Gz)
              DiagBreak() ;
            if (sqrt(SQR(xv-Gx)+SQR(yv-Gy)+SQR(zv-Gz)) < 2)
              DiagBreak() ;
            if (min_region_prior(gca, gcas[i].xp, gcas[i].yp, gcas[i].zp,prior_wsize, label) < min_prior)
              continue ;
            if (uniform_region(gca, mri_in, transform,
                               xv, yv, zv,
                               image_wsize, &gcas[i], nsigma) == 0)
              continue ;
            memmove(&gcas_region[region_samples],
                    &gcas[i],
                    sizeof(GCA_SAMPLE)) ;
            region_samples++ ;
            if (gcas[i].x == Gx &&
                gcas[i].y == Gy &&
                gcas[i].z == Gz)
              DiagBreak() ;
          }
          nsigma *= 1.1 ;
        } while (region_samples < 8 && nsigma < 3) ;

        if (region_samples < 8)/* can't reliably estimate statistics */
          continue ;
        if (DIAG_VERBOSE_ON)
          printf("\t%d total samples found in region (%d, %d, %d)\n",
                 region_samples,x, y,z) ;
        /* compute mean and variance of label within this region */
        for (n = 0 ; n < mri_in->nframes ; n++)
        {
          HISTOclear(histo, histo) ;
          histo->bin_size = 1 ;
          for (means[n] = vars[n] = 0.0, i = 0 ;
               i < region_samples ;
               i++)
          {
            MRIsampleVolumeFrame
              (mri_in,
               gcas_region[i].x,gcas_region[i].y,gcas_region[i].z,
               n, &val) ;
            if (FZERO(val))
            {
              if (i < (region_samples-1))
                memmove(&gcas_region[i],
                        &gcas_region[i+1],
                        (region_samples-(i+1))*sizeof(GCA_SAMPLE));
              i-- ;
              region_samples-- ;
              continue ;
            }
            histo->counts[(int)val]++ ;
            means[n] += val ;
            vars[n] += (val*val) ;
          }

          HISTOsmooth(histo, hsmooth, 2) ;
          histo_peak =
            HISTOfindHighestPeakInRegion(hsmooth, 1, hsmooth->nbins) ;
          if (histo_peak < 0)   /* couldn't find a valid peak? */
            break ;

          for (means[n] = vars[n] = 0.0, i = 0 ;
               i < region_samples ;
               i++)
          {
            if (gcas_region[i].label < 0)
              continue ;
            MRIsampleVolumeFrame
              (mri_in,
               gcas_region[i].x,
               gcas_region[i].y,
               gcas_region[i].z,
               n, &val) ;
            means[n] += val ;
            vars[n] += (val*val) ;
          }
          means[n] /= (double)region_samples ;
          vars[n] = vars[n] / (double)region_samples - means[n]*means[n] ;

          means[n] = histo_peak ;
          if (DIAG_VERBOSE_ON)
            printf("\tlabel %s[%d]: %2.1f +- %2.1f\n",
                   cma_label_to_name(label),
                   n, means[n], sqrt(vars[n])) ;
        }

        /* ignore GCA mean and variance -
           use image instead (otherwise bias field will mess us up) */
        for (i = 0 ; i < region_samples ; i++)
        {
          int r ;

          for (r = 0 ; r < gca->ninputs ; r++)
            gcas_region[i].means[r] = means[r] ;
          /*          gcas_region[i].var = var ;*/
        }

        GCAcomputeLogSampleProbability
          (gca, gcas_region, mri_in, transform, region_samples) ;
        GCArankSamples
          (gca, gcas_region, region_samples, ordered_indices) ;
        GCAremoveOutlyingSamples
          (gca, gcas_region, mri_in, transform, region_samples, 2.0) ;
        for (used_in_region = i = 0 ; i < region_samples ; i++)
        {
          j = ordered_indices[i] ;
          if (gcas_region[j].label != label)  /* it was an outlier */
            continue ;
          memmove
            (&gcas_norm[*pnorm_samples],
             &gcas_region[j],
             sizeof(GCA_SAMPLE)) ;
          (*pnorm_samples)++ ; used_in_region++ ;
        }
        if ((used_in_region <= 0) && region_samples>0)
        {
          j = ordered_indices[0] ;
          /*          gcas_region[j].label = label ;*/
          printf("forcing use of sample %d @ (%d, %d, %d)\n", j,
                 gcas_region[j].x,
                 gcas_region[j].y,
                 gcas_region[j].z) ;
          memmove(&gcas_norm[*pnorm_samples],
                  &gcas_region[j],
                  sizeof(GCA_SAMPLE)) ;
          (*pnorm_samples)++ ; used_in_region++ ;
        }
        if (DIAG_VERBOSE_ON)
          printf("\t%d samples used in region\n", used_in_region) ;
      }
    }
  }

  /* put gca means back into samples */
  for (i = 0 ; i < *pnorm_samples ; i++)
  {
    gc = GCAfindPriorGC(gca,
                        gcas_norm[i].xp,
                        gcas_norm[i].yp,
                        gcas_norm[i].zp,
                        gcas_norm[i].label) ;
    if (gc)
    {
      int r, c, v ;

      for (v = r = 0 ; r < gca->ninputs ; r++)
      {
        for (c = r ; c < gca->ninputs ; c++, v++)
        {
          gcas_norm[i].means[v] = gc->means[v] ;
          gcas_norm[i].covars[v] = gc->covars[v] ;
        }
      }
    }
  }
  HISTOfree(&histo) ; HISTOfree(&hsmooth) ;
  free(gcas_region) ;
  free(gcas) ;
  if (mri_T1)
    MRIfree(&mri_T1) ;
  return(gcas_norm) ;
}
int
main(int argc, char *argv[]) {
  MRI_SURFACE  *mris ;
  char         **av, *curv_name, *surf_name, *hemi, fname[STRLEN],
  *cp, *subject_name, subjects_dir[STRLEN],
  **c1_subjects, **c2_subjects ;
  int          ac, nargs, n, num_class1, num_class2, i, nvertices,
  avgs, max_snr_avgs, nlabels = 0, done ;
  float        **c1_thickness, **c2_thickness, *curvs, *total_mean,
  *c1_mean, *c2_mean,
  *class_mean, *c1_var, *c2_var, *class_var,*pvals,
  **c1_avg_thickness,
  *vbest_snr, *vbest_avgs, *vtotal_var, *vsnr, **c2_avg_thickness,
  *vbest_pvalues, current_min_label_area, current_fthresh ;
  MRI_SP       *mrisp ;
  LABEL        *area, **labels = NULL ;
  FILE         *fp = NULL ;
  double       snr, max_snr ;
  struct timeb start ;
  int          msec, minutes, seconds ;
  double       **c1_label_thickness, **c2_label_thickness ;
  int          *sorted_indices = NULL, vno ;
  float        *test_thickness, *test_avg_thickness ;
  double       label_avg ;

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

  if (write_flag && DIAG_VERBOSE_ON)
    fp = fopen("scalespace.dat", "w") ;

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

  TimerStart(&start) ;

  /* subject_name hemi surface curvature */
  if (argc < 7)
    usage_exit() ;
  if (output_subject == NULL)
    ErrorExit(ERROR_BADPARM,
              "output subject must be specified with -o <subject name>");

  cp = getenv("SUBJECTS_DIR") ;
  if (!cp)
    ErrorExit(ERROR_BADPARM, "%s: SUBJECTS_DIR not defined in environment",
              Progname) ;

  strcpy(subjects_dir, cp) ;

  hemi = argv[1] ;
  surf_name = argv[2] ;
  curv_name = argv[3] ;

#define ARGV_OFFSET 4

  /* first determine the number of subjects in each class */
  num_class1 = 0 ;
  n = ARGV_OFFSET ;
  do {
    num_class1++ ;
    n++ ;
    if (argv[n] == NULL || n >= argc)
      ErrorExit(ERROR_BADPARM, "%s: must spectify ':' between class lists",
                Progname) ;
  } while (argv[n][0] != ':') ;

  /* find  # of vertices in output subject surface */
  sprintf(fname, "%s/%s/surf/%s.%s",
          subjects_dir,output_subject,hemi,surf_name);
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, fname) ;
  nvertices = mris->nvertices ;
  MRISfree(&mris) ;

  total_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!total_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate mean list of %d curvatures",
              Progname, n, nvertices) ;
  c1_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c1_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c1 mean list of %d curvatures",
              Progname, n, nvertices) ;
  pvals = (float *)calloc(nvertices, sizeof(float)) ;
  if (!pvals)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate pvals",
              Progname, n, nvertices) ;
  c2_mean = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c2_mean)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c2 mean list of %d curvatures",
              Progname, n, nvertices) ;

  c1_var = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c1_var)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c1 var list of %d curvatures",
              Progname, n, nvertices) ;
  c2_var = (float *)calloc(nvertices, sizeof(float)) ;
  if (!c2_var)
    ErrorExit(ERROR_NOMEMORY,
              "%s: could not allocate c2 var list of %d curvatures",
              Progname, n, nvertices) ;

  num_class2 = 0 ;
  n++ ; /* skip ':' */
  if (n >= argc)
    ErrorExit(ERROR_BADPARM, "%s: class2 list empty", Progname) ;
  do {
    num_class2++ ;
    n++ ;
    if (n >= argc)
      break ;
  } while (argv[n] != NULL) ;

  fprintf(stderr, "%d subjects in class 1, %d subjects in class 2\n",
          num_class1, num_class2) ;

  c1_subjects = (char **)calloc(num_class1, sizeof(char *)) ;
  c1_thickness = (float **)calloc(num_class1, sizeof(char *)) ;
  c1_avg_thickness = (float **)calloc(num_class1, sizeof(char *)) ;
  c2_subjects = (char **)calloc(num_class2, sizeof(char *)) ;
  c2_thickness = (float **)calloc(num_class2, sizeof(char *)) ;
  c2_avg_thickness = (float **)calloc(num_class2, sizeof(char *)) ;
  for (n = 0 ; n < num_class1 ; n++) {
    c1_subjects[n] = argv[ARGV_OFFSET+n] ;
    c1_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    c1_avg_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    if (!c1_thickness[n] || !c1_avg_thickness[n])
      ErrorExit(ERROR_NOMEMORY,
                "%s: could not allocate %dth list of %d curvatures",
                Progname, n, nvertices) ;

    strcpy(c1_subjects[n], argv[ARGV_OFFSET+n]) ;
    /*    fprintf(stderr, "class1[%d] - %s\n", n, c1_subjects[n]) ;*/
  }
  i = n+1+ARGV_OFFSET ;  /* starting index */
  for (n = 0 ; n < num_class2 ; n++) {
    c2_subjects[n] = argv[i+n] ;
    c2_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    c2_avg_thickness[n] = (float *)calloc(nvertices, sizeof(float)) ;
    if (!c2_thickness[n] || !c2_avg_thickness[n])
      ErrorExit(ERROR_NOMEMORY,
                "%s: could not allocate %dth list of %d curvatures",
                Progname, n, nvertices) ;
    strcpy(c2_subjects[n], argv[i+n]) ;
    /*    fprintf(stderr, "class2[%d] - %s\n", n, c2_subjects[n]) ;*/
  }

  if (label_name) {
    area = LabelRead(output_subject, label_name) ;
    if (!area)
      ErrorExit(ERROR_NOFILE, "%s: could not read label %s", Progname,
                label_name) ;
  } else
    area = NULL ;

  if (read_dir) {
    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,output_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;

    /* real all the curvatures in for group1 */
    for (n = 0 ; n < num_class1+num_class2 ; n++) {
      /* transform each subject's curvature into the output subject's space */
      subject_name = n < num_class1 ? c1_subjects[n]:c2_subjects[n-num_class1];
      fprintf(stderr, "reading subject %d of %d: %s\n",
              n+1, num_class1+num_class2, subject_name) ;
      sprintf(fname, "%s/%s.%s", read_dir,hemi,subject_name);
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror,
                  "%s: could not read curvature file %s",Progname,fname);
      if (area)
        MRISmaskNotLabel(mris, area) ;
      curvs = (n < num_class1) ? c1_thickness[n] : c2_thickness[n-num_class1] ;
      class_mean = (n < num_class1) ? c1_mean : c2_mean ;
      class_var = (n < num_class1) ? c1_var : c2_var ;
      MRISexportValVector(mris, curvs) ;
      cvector_accumulate(curvs, total_mean, nvertices) ;
      cvector_accumulate(curvs, class_mean, nvertices) ;
      cvector_accumulate_square(curvs, class_var, nvertices) ;
    }
  } else {

    /* real all the curvatures in for group1 */
    for (n = 0 ; n < num_class1+num_class2 ; n++) {
      /* transform each subject's curvature into the output subject's space */
      subject_name = n < num_class1 ? c1_subjects[n]:c2_subjects[n-num_class1];
      fprintf(stderr, "reading subject %d of %d: %s\n",
              n+1, num_class1+num_class2, subject_name) ;
      sprintf(fname, "%s/%s/surf/%s.%s",
              subjects_dir,subject_name,hemi,surf_name);
      mris = MRISread(fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, fname) ;
      MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
      if (strchr(curv_name, '/') != NULL)
        strcpy(fname, curv_name) ;  /* full path specified */
      else
        sprintf(fname,"%s/%s/surf/%s.%s",
                subjects_dir,subject_name,hemi,curv_name);
      if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
        ErrorExit(Gerror,"%s: could no read curvature file %s",Progname,fname);
      mrisp = MRIStoParameterization(mris, NULL, 1, 0) ;
      MRISfree(&mris) ;

      sprintf(fname, "%s/%s/surf/%s.%s",
              subjects_dir,output_subject,hemi,surf_name);
      mris = MRISread(fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, fname) ;
      MRISfromParameterization(mrisp, mris, 0) ;
      if (area)
        MRISmaskNotLabel(mris, area) ;
      curvs = (n < num_class1) ? c1_thickness[n] : c2_thickness[n-num_class1] ;
      class_mean = (n < num_class1) ? c1_mean : c2_mean ;
      class_var = (n < num_class1) ? c1_var : c2_var ;
      MRISextractCurvatureVector(mris, curvs) ;
      cvector_accumulate(curvs, total_mean, nvertices) ;
      cvector_accumulate(curvs, class_mean, nvertices) ;
      cvector_accumulate_square(curvs, class_var, nvertices) ;
      MRISPfree(&mrisp) ;
      MRISfree(&mris) ;
    }
  }

  /* compute within-group means, and total mean */
  cvector_normalize(total_mean, num_class1+num_class2, nvertices) ;
  cvector_normalize(c1_mean, num_class1, nvertices) ;
  cvector_normalize(c2_mean, num_class2, nvertices) ;
  cvector_compute_variance(c1_var, c1_mean, num_class1, nvertices) ;
  cvector_compute_variance(c2_var, c2_mean, num_class2, nvertices) ;
  cvector_compute_t_test(c1_mean, c1_var, c2_mean, c2_var,
                         num_class1, num_class2, pvals, nvertices) ;

  sprintf(fname, "%s/%s/surf/%s.%s",
          subjects_dir,output_subject,hemi,surf_name);
  fprintf(stderr, "reading output surface %s...\n", fname) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, fname) ;

  if (area)
    MRISripNotLabel(mris, area) ;
  vbest_snr = cvector_alloc(nvertices) ;
  vbest_pvalues = cvector_alloc(nvertices) ;
  vbest_avgs = cvector_alloc(nvertices) ;
  vtotal_var = cvector_alloc(nvertices) ;
  vsnr = cvector_alloc(nvertices) ;

  if (read_dir == NULL)  /* recompute everything */
  {
    if (use_buggy_snr)
      cvector_multiply_variances(c1_var, c2_var, num_class1, num_class2,
                                 vtotal_var, nvertices) ;
    else
      cvector_add_variances(c1_var, c2_var, num_class1, num_class2,
                            vtotal_var, nvertices) ;
    if (use_no_distribution)
      snr = cvector_compute_dist_free_snr(c1_thickness, num_class1,
                                          c2_thickness, num_class2,
                                          c1_mean, c2_mean,
                                          vsnr, nvertices, &i);
    else
      snr = cvector_compute_snr(c1_mean, c2_mean, vtotal_var, vsnr, nvertices,
                                &i, 0.0f);
    fprintf(stderr,
            "raw SNR %2.2f, n=%2.4f, d=%2.4f, vno=%d\n",
            sqrt(snr), c1_mean[i]-c2_mean[i], sqrt(vtotal_var[i]), i) ;
    max_snr = snr ;
    max_snr_avgs = 0 ;
    cvector_track_best_snr(vsnr, vbest_snr, vbest_avgs, 0, nvertices) ;

    for (n = 0 ; n < num_class1 ; n++)
      cvector_copy(c1_thickness[n], c1_avg_thickness[n], nvertices) ;
    for (n = 0 ; n < num_class2 ; n++)
      cvector_copy(c2_thickness[n], c2_avg_thickness[n], nvertices) ;

    /* now incrementally average the data, keeping track of the best
       snr at each location, and at what scale it occurred. vbest_avgs
       and vbest_snr will contain the scale and the snr at that scale.
    */
    for (avgs = 1 ; avgs <= max_avgs ; avgs++) {
      /* c?_avg_thickness is the thickness at the current scale */
      if (!(avgs % 50))
        fprintf(stderr, "testing %d averages...\n", avgs) ;
      cvector_clear(c1_mean, nvertices) ;
      cvector_clear(c2_mean, nvertices) ;
      cvector_clear(c1_var, nvertices) ;
      cvector_clear(c2_var, nvertices) ;
      cvector_clear(total_mean, nvertices) ;
      for (n = 0 ; n < num_class1 ; n++) {
        MRISimportCurvatureVector(mris, c1_avg_thickness[n]) ;
        MRISaverageCurvatures(mris, 1) ;
        MRISextractCurvatureVector(mris, c1_avg_thickness[n]) ;
        cvector_accumulate(c1_avg_thickness[n], total_mean, nvertices) ;
        cvector_accumulate(c1_avg_thickness[n], c1_mean, nvertices) ;
        cvector_accumulate_square(c1_avg_thickness[n], c1_var, nvertices) ;
      }
      for (n = 0 ; n < num_class2 ; n++) {
        MRISimportCurvatureVector(mris, c2_avg_thickness[n]) ;
        MRISaverageCurvatures(mris, 1) ;
        MRISextractCurvatureVector(mris, c2_avg_thickness[n]) ;
        cvector_accumulate(c2_avg_thickness[n], total_mean, nvertices) ;
        cvector_accumulate(c2_avg_thickness[n], c2_mean, nvertices) ;
        cvector_accumulate_square(c2_avg_thickness[n], c2_var, nvertices) ;
      }
      cvector_normalize(total_mean, num_class1+num_class2, nvertices) ;
      cvector_normalize(c1_mean, num_class1, nvertices) ;
      cvector_normalize(c2_mean, num_class2, nvertices) ;
      cvector_compute_variance(c1_var, c1_mean, num_class1, nvertices) ;
      cvector_compute_variance(c2_var, c2_mean, num_class2, nvertices) ;
      if (use_buggy_snr)
        cvector_multiply_variances(c1_var, c2_var, num_class1, num_class2,
                                   vtotal_var, nvertices) ;
      else
        cvector_add_variances(c1_var, c2_var, num_class1, num_class2,
                              vtotal_var, nvertices) ;
      if (use_no_distribution)
        snr =
          cvector_compute_dist_free_snr(c1_avg_thickness,num_class1,
                                        c2_avg_thickness, num_class2, c1_mean,
                                        c2_mean, vsnr, nvertices, &i);
      else
        snr =
          cvector_compute_snr(c1_mean, c2_mean, vtotal_var, vsnr, nvertices,&i,
                              bonferroni ? log((double)avgs) : 0.0f);
      if (write_flag && DIAG_VERBOSE_ON) {
        fprintf(fp, "%d %2.1f  %2.2f %2.2f %2.2f ",
                avgs, sqrt((float)avgs), sqrt(snr), c1_mean[i]-c2_mean[i],
                sqrt(vtotal_var[i])) ;
        fflush(fp) ;
        for (n = 0 ; n < num_class1 ; n++)
          fprintf(fp, "%2.2f ", c1_avg_thickness[n][i]) ;
        for (n = 0 ; n < num_class2 ; n++)
          fprintf(fp, "%2.2f ", c2_avg_thickness[n][i]) ;
        fprintf(fp, "\n") ;
        fclose(fp) ;
      }
      if (snr > max_snr) {
        fprintf(stderr,
                "new max SNR found at avgs=%d (%2.1f mm)=%2.1f, n=%2.4f, "
                "d=%2.4f, vno=%d\n",
                avgs, sqrt((float)avgs), sqrt(snr), c1_mean[i]-c2_mean[i],
                sqrt(vtotal_var[i]), i) ;
        max_snr = snr ;
        max_snr_avgs = avgs ;
      }
      cvector_track_best_snr(vsnr, vbest_snr, vbest_avgs, avgs, nvertices) ;
    }
    if (compute_stats)
      cvector_compute_t(vbest_snr, vbest_pvalues,num_class1+num_class2,
                        nvertices) ;
    printf("max snr=%2.2f at %d averages\n", max_snr, max_snr_avgs) ;
    if (write_flag) {
      MRISimportValVector(mris, vbest_snr) ;
      sprintf(fname, "./%s.%s_best_snr", hemi,prefix) ;
      MRISwriteValues(mris, fname) ;
      MRISimportValVector(mris, vbest_avgs) ;
      sprintf(fname, "./%s.%s_best_avgs", hemi, prefix) ;
      MRISwriteValues(mris, fname) ;
      if (compute_stats) {
        MRISimportValVector(mris, vbest_pvalues) ;
        sprintf(fname, "./%s.%s_best_pval", hemi,prefix) ;
        MRISwriteValues(mris, fname) ;
      }
    }
  }
  else  /* read from directory containing precomputed optimal values */
  {
    sprintf(fname, "%s/%s.%s_best_snr", read_dir, hemi, prefix) ;
    if (MRISreadValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISreadValues(%s) failed",Progname,fname) ;
    MRISexportValVector(mris, vbest_snr) ;

    sprintf(fname, "%s/%s.%s_best_avgs", read_dir, hemi, prefix) ;
    if (MRISreadValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISreadValues(%s) failed",Progname,fname) ;
    MRISexportValVector(mris, vbest_avgs) ;
  }

  if (write_dir) {
    sprintf(fname, "%s/%s.%s_best_snr", write_dir, hemi,prefix) ;
    MRISimportValVector(mris, vbest_snr) ;
    if (MRISwriteValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISwriteValues(%s) failed",Progname,fname) ;

    sprintf(fname, "%s/%s.%s_best_avgs", write_dir, hemi, prefix) ;
    MRISimportValVector(mris, vbest_avgs) ;
    if (MRISwriteValues(mris, fname) != NO_ERROR)
      ErrorExit(Gerror, "%s: MRISwriteValues(%s) failed",Progname,fname) ;
  }

  if (nsort < -1)
    nsort = mris->nvertices ;

  if (nsort <= 0) {
    nlabels = 0 ;
    current_min_label_area = min_label_area ;
    for (done = 0, current_fthresh = fthresh ;
         !FZERO(current_fthresh) && !done ;
         current_fthresh *= 0.95) {
      int   npos_labels, nneg_labels ;
      LABEL **pos_labels, **neg_labels ;

      for (current_min_label_area = min_label_area ;
           current_min_label_area > 0.5 ;
           current_min_label_area *= 0.75) {
        MRISclearMarks(mris) ;
        sprintf(fname, "%s-%s_thickness", hemi, prefix ? prefix : "") ;
        mark_thresholded_vertices(mris, vbest_snr, vbest_avgs,current_fthresh);
        segment_and_write_labels(output_subject, fname, mris,
                                 &pos_labels, &npos_labels, 0,
                                 current_min_label_area) ;
        MRISclearMarks(mris) ;
        mark_thresholded_vertices(mris, vbest_snr,vbest_avgs,-current_fthresh);
        segment_and_write_labels(output_subject, fname, mris, &neg_labels,
                                 &nneg_labels, npos_labels,
                                 current_min_label_area) ;

        nlabels = nneg_labels + npos_labels ;
        if (nlabels) {
          labels = (LABEL **)calloc(nlabels, sizeof(LABEL *)) ;
          for (i = 0 ; i < npos_labels ; i++)
            labels[i] = pos_labels[i] ;
          for (i = 0 ; i < nneg_labels ; i++)
            labels[i+npos_labels] = neg_labels[i] ;
          free(pos_labels) ;
          free(neg_labels) ;
        }
        done = (nlabels >= min_labels) ;
        if (done)  /* found enough points */
          break ;

        /* couldn't find enough  points - free stuff and try again */
        for (i = 0 ; i < nlabels ; i++)
          LabelFree(&labels[i]) ;
        if (nlabels)
          free(labels) ;
#if 0
        fprintf(stderr,"%d labels found (min %d), reducing constraints...\n",
                nlabels, min_labels) ;
#endif
      }
    }

    printf("%d labels found with F > %2.1f and area > %2.0f\n",
           nlabels, current_fthresh, current_min_label_area) ;
    for (i = 0 ; i < nlabels ; i++)
      fprintf(stderr, "label %d: %d points, %2.1f mm\n",
              i, labels[i]->n_points, LabelArea(labels[i], mris)) ;
  }

  /* read or compute thickness at optimal scale and put it into
     c?_avg_thickness.
  */
  if (!read_dir) {
    fprintf(stderr, "extracting thickness at optimal scale...\n") ;

    /* now build feature vectors for each subject */
    extract_thickness_at_best_scale(mris, c1_avg_thickness, vbest_avgs,
                                    c1_thickness, nvertices, num_class1);
    fprintf(stderr, "extracting thickness for class 2...\n") ;
    extract_thickness_at_best_scale(mris, c2_avg_thickness, vbest_avgs,
                                    c2_thickness, nvertices, num_class2);
  } else  /* read in precomputed optimal thicknesses */
  {
    char fname[STRLEN] ;

    fprintf(stderr, "reading precomputed thickness vectors\n") ;
    for (n = 0 ; n < num_class1 ; n++) {
      sprintf(fname, "%s/%s.%s", read_dir, hemi, argv[ARGV_OFFSET+n]) ;
      fprintf(stderr, "reading thickness vector from %s...\n", fname) ;
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read thickness file %s",
                  Progname,fname) ;
      MRISexportValVector(mris, c1_avg_thickness[n]) ;
    }
    for (n = 0 ; n < num_class2 ; n++) {
      sprintf(fname, "%s/%s.%s", read_dir, hemi,
              argv[n+num_class1+1+ARGV_OFFSET]) ;
      fprintf(stderr, "reading curvature vector from %s...\n", fname) ;
      if (MRISreadValues(mris, fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read thickness file %s",
                  Progname,fname) ;
      MRISexportValVector(mris, c2_avg_thickness[n]) ;
    }
  }

  if (write_dir)   /* write out optimal thicknesses */
  {
    char fname[STRLEN] ;

    for (n = 0 ; n < num_class1 ; n++) {
      sprintf(fname, "%s/%s.%s", write_dir, hemi, argv[ARGV_OFFSET+n]) ;
      fprintf(stderr, "writing curvature vector to %s...\n", fname) ;
      MRISimportValVector(mris, c1_avg_thickness[n]) ;
      MRISwriteValues(mris, fname) ;
    }
    for (n = 0 ; n < num_class2 ; n++) {
      sprintf(fname, "%s/%s.%s", write_dir, hemi,
              argv[n+num_class1+1+ARGV_OFFSET]) ;
      fprintf(stderr, "writing curvature vector to %s...\n", fname) ;
      MRISimportValVector(mris, c2_avg_thickness[n]) ;
      MRISwriteValues(mris, fname) ;
    }
  }


  /* should free c?_thickness here */

  if (nsort <= 0) {
    /* We have the thickness values at the most powerful scale stored for
       each subject in the c1_avg_thickness and c2_avg_thickness vectors.
       Now collapse them across each label and build  feature vector for
       classification.
    */
    c1_label_thickness = (double **)calloc(num_class1, sizeof(double *)) ;
    c2_label_thickness = (double **)calloc(num_class2, sizeof(double *)) ;
    for (n = 0 ; n < num_class1 ; n++)
      c1_label_thickness[n] = (double *)calloc(nlabels, sizeof(double)) ;
    for (n = 0 ; n < num_class2 ; n++)
      c2_label_thickness[n] = (double *)calloc(nlabels, sizeof(double)) ;

    fprintf(stderr, "collapsing thicknesses within labels for class 1\n") ;
    for (n = 0 ; n < num_class1 ; n++)
      for (i = 0 ; i < nlabels ; i++)
        c1_label_thickness[n][i] =
          cvector_average_in_label(c1_avg_thickness[n], labels[i], nvertices) ;
    fprintf(stderr, "collapsing thicknesses within labels for class 2\n") ;
    for (n = 0 ; n < num_class2 ; n++)
      for (i = 0 ; i < nlabels ; i++)
        c2_label_thickness[n][i] =
          cvector_average_in_label(c2_avg_thickness[n], labels[i], nvertices) ;
    sprintf(fname, "%s_%s_class1.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 1 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nlabels ; i++)  /* for each row */
    {
      for (n = 0 ; n < num_class1 ; n++)  /* for each column */
        fprintf(fp, "%2.2f  ", c1_label_thickness[n][i]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;

    sprintf(fname, "%s_%s_class2.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 2 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nlabels ; i++) {
      for (n = 0 ; n < num_class2 ; n++)
        fprintf(fp, "%2.2f  ", c2_label_thickness[n][i]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
  } else {
    sorted_indices = cvector_sort(vbest_snr, nvertices) ;
    vno = sorted_indices[0] ;
    write_vertex_data("c1.dat", vno, c1_avg_thickness,num_class1);
    write_vertex_data("c2.dat", vno, c2_avg_thickness,num_class2);
    printf("sorting complete\n") ;

    /* re-write class means at these locations */
    sprintf(fname, "%s_%s_class1.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 1 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nsort ; i++) {
      for (n = 0 ; n < num_class1 ; n++)
        fprintf(fp, "%2.2f  ", c1_avg_thickness[n][sorted_indices[i]]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
    sprintf(fname, "%s_%s_class2.dat", hemi,prefix) ;
    fprintf(stderr, "writing class 2 info to %s...\n", fname) ;
    fp = fopen(fname, "w") ;
    for (i = 0 ; i < nsort ; i++) {
      for (n = 0 ; n < num_class2 ; n++)
        fprintf(fp, "%2.2f  ", c2_avg_thickness[n][sorted_indices[i]]) ;
      fprintf(fp, "\n") ;
    }
    fclose(fp) ;
  }

  if (test_subject) {
    test_thickness = cvector_alloc(nvertices) ;
    test_avg_thickness = cvector_alloc(nvertices) ;
    MRISfree(&mris) ;
    fprintf(stderr, "reading subject %s\n", test_subject) ;
    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,test_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    if (strchr(curv_name, '/') != NULL)
      strcpy(fname, curv_name) ;  /* full path specified */
    else
      sprintf(fname,"%s/%s/surf/%s.%s",
              subjects_dir,test_subject,hemi,curv_name);
    if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
      ErrorExit(Gerror,"%s: could no read curvature file %s",Progname,fname);
    mrisp = MRIStoParameterization(mris, NULL, 1, 0) ;
    MRISfree(&mris) ;

    sprintf(fname, "%s/%s/surf/%s.%s",
            subjects_dir,output_subject,hemi,surf_name);
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISfromParameterization(mrisp, mris, 0) ;
    if (area)
      MRISmaskNotLabel(mris, area) ;
    MRISextractCurvatureVector(mris, test_thickness) ;
    for (avgs = 0 ; avgs <= max_avgs ; avgs++) {
      cvector_extract_best_avg(vbest_avgs, test_thickness,test_avg_thickness,
                               avgs-1, nvertices) ;
      MRISimportCurvatureVector(mris, test_thickness) ;
      MRISaverageCurvatures(mris, 1) ;
      MRISextractCurvatureVector(mris, test_thickness) ;
    }

    if (nsort <= 0) {
      sprintf(fname, "%s_%s.dat", hemi,test_subject) ;
      fprintf(stderr, "writing test subject feature vector to %s...\n",
              fname) ;
      fp = fopen(fname, "w") ;
      for (i = 0 ; i < nlabels ; i++)  /* for each row */
      {
        label_avg =
          cvector_average_in_label(test_avg_thickness, labels[i], nvertices) ;
        fprintf(fp, "%2.2f\n", label_avg) ;
      }
      fclose(fp) ;
    } else   /* use sorting instead of connected areas */
    {
      double classification, offset, w ;
      int    total_correct, total_wrong, first_wrong, vno ;


      sprintf(fname, "%s_%s.dat", hemi,test_subject) ;
      fprintf(stderr, "writing test subject feature vector to %s...\n",
              fname) ;
      fp = fopen(fname, "w") ;

      first_wrong = -1 ;
      total_wrong = total_correct = 0 ;
      for (i = 0 ; i < nsort ; i++) {
        vno = sorted_indices[i] ;
        fprintf(fp, "%2.2f\n ", test_avg_thickness[sorted_indices[i]]) ;
        offset = (c1_mean[vno]+c2_mean[vno])/2.0 ;
        w = (c1_mean[vno]-c2_mean[vno]) ;
        classification = (test_avg_thickness[vno] - offset) * w ;

        if (((classification < 0) && (true_class == 1)) ||
            ((classification > 0) && (true_class == 2))) {
          total_wrong++ ;
          if (first_wrong < 0)
            first_wrong = i ;
        } else
          total_correct++ ;
      }
      fclose(fp) ;
      fprintf(stderr, "%d of %d correct = %2.1f%% (first wrong %d (%d)),"
              "min snr=%2.1f\n",
              total_correct, total_correct+total_wrong,
              100.0*total_correct / (total_correct+total_wrong),
              first_wrong, first_wrong >= 0 ? sorted_indices[first_wrong]:-1,
              vbest_snr[sorted_indices[nsort-1]]) ;

      if (first_wrong >= 0) {
        write_vertex_data("c1w.dat", sorted_indices[first_wrong],
                          c1_avg_thickness,num_class1);
        write_vertex_data("c2w.dat", sorted_indices[first_wrong],
                          c2_avg_thickness,num_class2);
      }
    }
  }

  msec = TimerStop(&start) ;
  free(total_mean);
  free(c1_mean) ;
  free(c2_mean) ;
  free(c1_var);
  free(c2_var);
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "classification took %d minutes and %d seconds.\n",
          minutes, seconds) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
示例#27
0
int
main(int argc, char *argv[]) {
  char          **av, *hemi, *subject_name, *cp, fname[STRLEN];
  char          *parc_name, *annot_name ;
  int           ac, nargs, vno, i ;
  MRI_SURFACE   *mris ;
  MRI           *mri_parc ;
  VERTEX        *v ;
  double        d ;
  Real          x, y, z, xw, yw, zw ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv,
                                 "$Id: mris_sample_parc.c,v 1.31 2016/12/11 14:33:38 fischl Exp $", "$Name:  $");
  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 < 4)
    usage_exit() ;

  subject_name = argv[1] ;
  hemi = argv[2] ;
  parc_name = argv[3] ;
  annot_name = argv[4] ;

  if (strlen(sdir) == 0)  /* if not specified explicitly as option */
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,
                "%s: SUBJECTS_DIR not defined in environment.\n", Progname) ;
    strcpy(sdir, cp) ;
  }

  if (parc_name[0] == '/')  // full path specified
    strcpy(fname, parc_name) ;
  else
    sprintf(fname, "%s/%s/mri/%s", sdir, subject_name, parc_name) ;
  printf("reading parcellation volume from %s...\n", fname) ;
  mri_parc = MRIread(fname) ;
  if (!mri_parc)
    ErrorExit(ERROR_NOFILE, "%s: could not read input volume %s",
              Progname, fname) ;

  if (mask_fname) {
    MRI *mri_mask, *mri_tmp ;

    mri_tmp = MRIread(mask_fname) ;
    if (mri_tmp == NULL)
      ErrorExit(ERROR_BADPARM, "%s: could not load mask volume %s", Progname, mask_fname) ;
    mri_mask = MRIclone(mri_tmp, NULL) ;
    MRIcopyLabel(mri_tmp, mri_mask, mask_val) ;
    MRIdilate(mri_mask, mri_mask) ;
    MRIdilate(mri_mask, mri_mask) ;
    MRIdilate(mri_mask, mri_mask) ;
    MRIdilate(mri_mask, mri_mask) ;
    MRIfree(&mri_tmp) ;
    mri_tmp = MRIclone(mri_parc, NULL) ;
    MRIcopyLabeledVoxels(mri_parc, mri_mask, mri_tmp, mask_val) ;
    MRIfree(&mri_parc) ;
    mri_parc = mri_tmp ;
    if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
      MRIwrite(mri_parc, "p.mgz") ;
    MRIfree(&mri_mask) ;
  }

  for (i = 0 ; i < ntrans ; i++) {
    MRIreplaceValues(mri_parc, mri_parc, trans_in[i], trans_out[i]) ;
  }
  sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject_name, hemi, surf_name) ;
  printf("reading input surface %s...\n", fname) ;
  mris = MRISread(fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, fname) ;
  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  MRIScomputeMetricProperties(mris) ;
  if (avgs > 0)
    MRISaverageVertexPositions(mris, avgs) ;

  if (FZERO(proj_mm)) {
    if (MRISreadCurvatureFile(mris, thickness_name) != NO_ERROR)
      ErrorExit(ERROR_NOFILE, "%s: could not read thickness file %s",
                Progname, thickness_name) ;
  }

  if (color_table_fname) {
    mris->ct = CTABreadASCII(color_table_fname) ;
    if (mris->ct == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read color file %s",
                Progname, color_table_fname) ;
  }

  if (sample_from_vol_to_surf) // sample from volume to surface */
  {
    MRIsampleParcellationToSurface(mris, mri_parc) ;
  } else  /* sample from surface to volume */
  {
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->ripflag)
        continue ;
      if (vno == Gdiag_no)
        DiagBreak() ;

      if (!FZERO(proj_mm))
        d = proj_mm ;
      else
        d = v->curv*proj_frac ;  /* halfway out */
      x = v->x+d*v->nx ;
      y = v->y+d*v->ny ;
      z = v->z+d*v->nz ;
      MRIsurfaceRASToVoxel(mri_parc, x, y, z, &xw, &yw, &zw) ;
      v->annotation = v->val =
                        MRIfindNearestNonzero(mri_parc, wsize, xw, yw, zw, ((float)wsize-1)/2) ;
      if (v->val == 0xffffffff)
        DiagBreak() ;
    }
  }
  if (replace_label)
    replace_vertices_with_label(mris, mri_parc, replace_label, proj_mm);
  if (unknown_label >= 0) {
    LABEL **labels, *label ;
    int   nlabels, i, biggest_label, most_vertices, nzero ;

#define TMP_LABEL 1000
    for (nzero = vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->annotation == 0) {
        v->annotation = TMP_LABEL;
        nzero++ ;
      }
    }
    printf("%d unknown vertices found\n", nzero) ;
    MRISsegmentAnnotated(mris, &labels, &nlabels, 10) ;
    most_vertices = 0 ;
    biggest_label = -1 ;
    for (i = 0 ; i < nlabels ; i++) {
      label = labels[i] ;
      if (mris->vertices[label->lv[0].vno].annotation == TMP_LABEL) {
        if (label->n_points > most_vertices) {
          biggest_label = i ;
          most_vertices = label->n_points ;
        }
      }
    }
    if (biggest_label >= 0) {
      label = labels[biggest_label] ;
      printf("replacing label # %d with %d vertices "
             "(vno=%d) with label %d\n",
             biggest_label,
             label->n_points,
             label->lv[0].vno,
             unknown_label) ;
      for (i = 0 ; i < label->n_points ; i++) {
        v = &mris->vertices[label->lv[i].vno] ;
        v->annotation = v->val = unknown_label ;
      }
    }
    for (nzero = vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->annotation == TMP_LABEL) {
        v->annotation = 0;
        nzero++ ;
      }
    }
    printf("after replacement, %d unknown vertices found\n", nzero) ;
    MRISmodeFilterZeroVals(mris) ;  /* get rid of the rest
                                    of the unknowns by mode filtering */
    for (i = 0 ; i < nlabels ; i++)
      LabelFree(&labels[i]) ;
    free(labels) ;
  }

  MRIScopyValsToAnnotations(mris) ;
  if (fix_topology != 0)
    fix_label_topology(mris, fix_topology) ;

  if (mode_filter) {
    printf("mode filtering sample labels...\n") ;
#if 0
    MRISmodeFilterZeroVals(mris) ;
#else
    MRISmodeFilterVals(mris, mode_filter) ;
#endif
    for (vno = 0 ; vno < mris->nvertices ; vno++) {
      v = &mris->vertices[vno] ;
      if (v->ripflag)
        continue ;
      v->annotation = v->val ;
    }
  }

  /* this will fill in the v->annotation field from the v->val ones */
  translate_indices_to_annotations(mris, translation_fname) ;

  if (label_index >= 0)
  {
    int index ;
    LABEL *area ;

    printf("writing label to %s...\n", annot_name) ;
    MRISclearMarks(mris) ;
    for (vno = 0 ; vno < mris->nvertices ; vno++)
    {
      if (vno == Gdiag_no)
        DiagBreak() ;
      v = &mris->vertices[vno] ;
      if (v->annotation > 0)
        DiagBreak() ;
      CTABfindAnnotation(mris->ct, v->annotation, &index);
      if (index == label_index)
        v->marked = 1 ;
    }
    area = LabelFromMarkedSurface(mris) ;
    if (nclose > 0)
    {
      LabelDilate(area, mris, nclose, CURRENT_VERTICES) ;
      LabelErode(area, mris, nclose) ;
    }
    LabelWrite(area, annot_name) ;
  }
  else
  {
    printf("writing annotation to %s...\n", annot_name) ;
    MRISwriteAnnotation(mris, annot_name) ;
  }
  /*  MRISreadAnnotation(mris, fname) ;*/
  exit(0) ;

  return(0) ;  /* for ansi */
}
static double
estimateVoxelParameters(MRI **mri_flash, int nvolumes, int x,
                        int y, int z, MRI *mri_T1, MRI *mri_PD, int nsteps) {
  double   sse, last_sse, dT1, dPD, ival, estimate, err, T1, PD,
  last_dT1, last_dPD, min_T1, max_T1, min_PD, max_PD, search_size ;
  int      i, niter ;
  MRI      *mri ;

#define SEARCH_STEPS 4
  search_size = 3000 ;
  T1 = PD = 3000 ;
  for (i = 0 ; i < nsteps ; i++) {
    min_T1 = MAX(MIN_T1, T1-search_size) ;
    max_T1 = T1+search_size ;
    min_PD = MAX(MIN_PD, PD-search_size) ;
    max_PD = PD+search_size ;
    sse = findInitialParameters(mri_flash, nvolumes, x, y, z,
                                min_PD, max_PD, min_T1, max_T1,
                                &PD, &T1, SEARCH_STEPS) ;
    if (Gdiag == 99)
      printf("min rms %2.1f at (T1=%2.0f, PD=%2.0f)\n",
             sqrt(sse/nvolumes), T1, PD) ;
    search_size /= SEARCH_STEPS ;
  }

  last_sse = sse = computeVoxelSSE(mri_flash, nvolumes, x, y, z,PD,T1);

  niter = 0 ;
  last_dT1 = last_dPD = 0.0 ;
  do {
    for (dT1 = dPD = 0.0, i = 0 ; i < nvolumes ; i++) {
      mri = mri_flash[i] ;
      ival = (double)MRISvox(mri, x, y, z) ;
      estimate = FLASHforwardModel(mri->flip_angle, mri->tr, PD, T1) ;
      err = (ival - estimate) ;
      dT1 += err*dM_dT1(mri->flip_angle, mri->tr, PD, T1) ;
      dPD += err*dM_dPD(mri->flip_angle, mri->tr, PD, T1) ;
    }

    dT1 = STEP_SIZE * dT1 + momentum * last_dT1 ;
    T1 += dT1 ;
    last_dT1 = dT1 ;
    dPD = STEP_SIZE * dPD + momentum * last_dPD ;
    PD += dPD ;
    last_dPD = dPD ;
    sse = computeVoxelSSE(mri_flash, nvolumes, x, y, z, PD, T1);
#if 0
    if (Gdiag_no == 1)
      printf("%03d: sse=%2.2f (d=%2.2f), dT1=%2.4f, dPD=%2.4f, T1=%2.1f, PD=%2.1f\n",
             niter, sse, sse-last_sse, dT1, dPD, T1, PD) ;
#endif
    if (T1 < MIN_T1) {
      T1 = MIN_T1 ;
      sse = computeVoxelSSE(mri_flash, nvolumes, x, y, z, PD, T1);
      break ;
    }
    if ((last_sse < sse) || FZERO(sse))
      break ;
    if (((last_sse - sse)/last_sse < tol) && niter > MIN_ITER)
      break ;

    last_sse = sse ;
  } while (niter++ < MAX_ITER) ;
  MRISvox(mri_T1, x, y, z) = (short)(T1+0.5) ;
  ;
  MRISvox(mri_PD, x, y, z) = (short)(PD+0.5) ;
  if (MRISvox(mri_T1, x, y, z) == 0)
    DiagBreak() ;
  return(sse) ;
}
示例#29
0
int
main(int argc, char *argv[]) {
    char               **av, fname[STRLEN], *subject_name, *wfile_name,
                       *cp, *hemi ;
    int                ac, nargs, vno ;
    MRI_SURFACE        *mris ;
    VERTEX             *v ;
    double             entropy, total_len, min_w ;

    /* rkt: check for and handle version tag */
    nargs = handle_version_option (argc, argv, "$Id: mris_entropy.c,v 1.7 2011/03/02 00:04:31 nicks Exp $", "$Name:  $");
    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 < 3)
        print_help() ;

    subject_name = argv[1] ;
    hemi = argv[2] ;
    wfile_name = argv[3] ;

    if (strlen(sdir) == 0) {
        cp = getenv("SUBJECTS_DIR") ;
        if (!cp)
            ErrorExit(ERROR_UNSUPPORTED, "%s: must specifiy SUBJECTS_DIR in env",
                      Progname) ;
        strcpy(sdir, cp) ;
    }
    sprintf(fname, "%s/%s/surf/%s.%s", sdir, subject_name, hemi, ORIG_NAME) ;
    mris = MRISfastRead(fname) ;
    if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, fname) ;

    if (MRISreadValues(mris, wfile_name) != NO_ERROR)
        ErrorExit(ERROR_NOFILE, "%s: could not read w file %s",
                  Progname, wfile_name) ;

    if (navgs > 0) {
        printf("smoothing surface values for %d iterations...\n",navgs) ;
        MRISaverageVals(mris, navgs) ;
    }

    min_w = fabs(mris->vertices[0].val) ;
    for (total_len = vno = 0 ; vno < mris->nvertices ; vno++) {
        v = &mris->vertices[vno] ;
        if (v->ripflag)
            continue ;
        v->val = fabs(v->val) ;
        total_len += (v->val*v->val) ;
        if (v->val < min_w)
            min_w = v->val ;
    }

    total_len = sqrt(total_len) ;
    if (FZERO(total_len))
        ErrorExit(ERROR_BADPARM, "total vector len = 0, entropy = 0 (trivial case)") ;

    for (entropy = vno = 0 ; vno < mris->nvertices ; vno++) {
        v = &mris->vertices[vno] ;
        if (v->ripflag)
            continue ;
        if (DZERO(v->val))
            continue ;
        v->val = v->val / total_len ;
        entropy += v->val * log2(v->val) ;
    }

    entropy = -entropy ;
    printf("total entropy = %f\n", entropy) ;
    if (log_fname) {
        FILE *fp ;

        fp = fopen(log_fname, "a") ;
        if (!fp)
            ErrorExit(ERROR_NOFILE, "%s: could not open log file %s\n", Progname,log_fname) ;
        fprintf(fp, "%f\n", entropy) ;
        fclose(fp) ;
    }
    exit(0) ;
    return(0) ;  /* for ansi */
}
示例#30
0
int compute_tissue_modes( MRI *mri_inputs,
                          GCA *gca,
                          GCA_SAMPLE *gcas,
                          TRANSFORM *transform,
                          int nsamples,
                          double *pwm, double *pgm, double *pfluid )
{
    int        x, y, z, width, height, depth, i, xp, yp, zp ;
    float      vals[MAX_GCA_INPUTS] ;
    int        countOutside = 0, ngm, nwm, nfluid;
    double     gm, wm, fluid ;

    /* go through each GC in the sample and compute the probability of
       the image at that point.
    */
    width = mri_inputs->width ;
    height = mri_inputs->height;
    depth = mri_inputs->depth ;
    // store inverse transformation .. forward:input->gca template,
    // inv: gca template->input
    TransformInvert(transform, mri_inputs) ;

    // go through all sample points
    for (ngm = nwm = nfluid = 0, wm = gm = fluid = 0.0, i = 0 ;
            i < nsamples ;
            i++)
    {
        /////////////////// diag code /////////////////////////////
        if (i == Gdiag_no)
        {
            DiagBreak() ;
        }
        if (Gdiag_no == gcas[i].label)
        {
            DiagBreak() ;
        }
        if (i == Gdiag_no ||
                (gcas[i].xp == Gxp && gcas[i].yp == Gyp && gcas[i].zp == Gzp))
        {
            DiagBreak() ;
        }
        ///////////////////////////////////////////////////////////

        // get prior coordinates
        xp = gcas[i].xp ;
        yp = gcas[i].yp ;
        zp = gcas[i].zp ;
        // if it is inside the source voxel
        if (!GCApriorToSourceVoxel(gca, mri_inputs, transform,
                                   xp, yp, zp, &x, &y, &z))
        {
            if (x == Gx && y == Gy && z == Gz)
            {
                DiagBreak() ;
            }

            // (x,y,z) is the source voxel position
            gcas[i].x = x ;
            gcas[i].y = y ;
            gcas[i].z = z ;

            // get values from all inputs
            load_vals(mri_inputs, x, y, z, vals, gca->ninputs) ;
            if (FZERO(vals[0]) && gcas[i].label == Gdiag_no)
            {
                DiagBreak() ;
            }

            if (gcas[i].tissue_class == GM_CLASS)
            {
                ngm++ ;
                gm += vals[0] ;
            }
            else if (gcas[i].tissue_class == WM_CLASS)
            {
                nwm++ ;
                wm += vals[0] ;
            }
            else if (gcas[i].tissue_class == FLUID_CLASS)
            {
                nfluid++ ;
                fluid += vals[0] ;
            }

            if (!FZERO(vals[0]))
            {
                DiagBreak() ;
            }
            if (gcas[i].label != Unknown)
            {
                DiagBreak() ;
            }
            if (i == Gdiag_no)
            {
                DiagBreak() ;
            }
        }
        else  // outside the volume
        {
            countOutside++;
        }
    }

    if (nfluid == 0)
    {
        nfluid = 1 ;
    }
    if (ngm == 0)
    {
        ngm = 1 ;
    }
    if (nwm == 0)
    {
        nwm = 1 ;
    }
    wm /= nwm ;
    gm /= ngm ;
    fluid /= nfluid ;
    G_wm_mean = *pwm = wm ;
    G_gm_mean = *pgm = gm ;
    G_fluid_mean = *pfluid = fluid ;

    return(NO_ERROR) ;
}