Esempio n. 1
0
MRI *
MRIScomputeDistanceMap(MRI_SURFACE *mris, MRI *mri_distance, int ref_vertex_no)
{
  int    vno ;
  VERTEX *v ;
  double circumference, angle, distance ;
  VECTOR *v1, *v2 ;

  if (mri_distance == NULL)
    mri_distance = MRIalloc(mris->nvertices, 1, 1, MRI_FLOAT) ;

  v1 = VectorAlloc(3, MATRIX_REAL) ; v2 = VectorAlloc(3, MATRIX_REAL) ;
  v = &mris->vertices[ref_vertex_no] ;
  VECTOR_LOAD(v1, v->x, v->y, v->z) ;  /* radius vector */
  circumference = M_PI * 2.0 * V3_LEN(v1) ;
  for (vno = 0 ; vno < mris->nvertices ; vno++)
  {
    v = &mris->vertices[vno] ;
    if (vno == Gdiag_no)
      DiagBreak() ;
    VECTOR_LOAD(v2, v->x, v->y, v->z) ;  /* radius vector */
    angle = fabs(Vector3Angle(v1, v2)) ;
    distance = circumference * angle / (2.0 * M_PI) ;
    MRIsetVoxVal(mri_distance, vno, 0, 0, 0, distance) ;
  }

  VectorFree(&v1) ; VectorFree(&v2) ;
  return(mri_distance) ;
}
Esempio n. 2
0
void ServerFreeSafe(struct server* st_server) {
    struct client* st_client;
    struct file* st_file;

    assert(!st_server->listening);

    /* Free memory related to the clients. */
    if(st_server->st_clients != NULL) {
        for(int i = 0; i < st_server->st_clients->current; i++) {
            st_client = (struct client*)VectorGetPointer(st_server->st_clients, i);

            if(ClientClose(st_client) == FAILED)
                printf("Could not gracefully terminate client %s:%d\n", st_client->ip, st_client->port);
            ClientDelete(st_client);
        }
        VectorFree(st_server->st_clients);
    }

    /* Free memory related to the clients. */
    if(st_server->st_files != NULL) {
        for(int i = 0; i < st_server->st_files->current; i++) {
            st_file = (struct file*)VectorGetPointer(st_server->st_files, i);
            ServerDeleteFile(st_server, st_file->descriptor);
        }
        VectorFree(st_server->st_files);
    }
}
Esempio n. 3
0
File: matrix.c Progetto: dkogan/PDL
void GaussSeidel(const int n, double **a, double *b, double *x, double eps, 
		 int max_iter) {

  int      iter, i, j;       /* counter        */
  double   sum;              /* temporary real */
  double  *x_old;            /* old solution   */ 
  double   norm;             /* L1-norm        */

  x_old=VectorAlloc(n);

  iter=0;
  do {                       /* repeat until safisfying sol. */
    iter++;
    for(i=0; i<n; i++)       /* copy old solution */
      x_old[i]=x[i];
    norm=0.0;                /* do an iteration */
    for(i=0; i<n; i++) {     
      sum=-a[i][i]*x[i];     /* don't include term i=j */
      for(j=0; j<n; j++) 
	sum+=a[i][j]*x[j];   
      x[i]=(b[i]-sum)/a[i][i];
      norm+=fabs(x_old[i]-x[i]);
    } /* for i */
  } while ((iter<=max_iter) && (norm>=eps));

  VectorFree(n, x_old);
} /* GaussSeidel */
Esempio n. 4
0
File: matrix.c Progetto: dkogan/PDL
void InversMatrix(const int n, double **b, double **ib) {

  double  **a;
  double   *e;
  int	    i,j;
  int  	   *p;

  a=MatrixAlloc(n);
  e=VectorAlloc(n);
  p=IntVectorAlloc(n);
  MatrixCopy(n, a, b);
  LUfact(n, a, p);
  for(i=0; i<n; i++) {
    for(j=0; j<n; j++)
      e[j]=0.0;
    e[i]=1.0;
    LUsubst(n, a, p, e);
    for(j=0; j<n; j++)
      ib[j][i]=e[j];
  } /* for i=1..n */

  MatrixFree(n, a);
  VectorFree(n, e);
  IntVectorFree(n, p);
} /* InversMatrix */
Esempio n. 5
0
// test vector's functions
int main(int argc, char **argv) {
  size_t i;
  vector_t v = VectorCreate(INITIAL_SIZE);

  if (v == NULL)
    return EXIT_FAILURE;

  for (i = 0; i < FINAL_SIZE; ++i) {
    int *x = (int*)malloc(sizeof(int));
    if (x == NULL)
      return EXIT_FAILURE;

    *x = FINAL_SIZE - i;
    element_t old;

    // set the value to the position i in the vector
    // terminate the program if VectorSet failed
    if (!(VectorSet(v, i, x, &old)))
      return EXIT_FAILURE;
  }

  PrintIntVector(v);

  // free the values stored in the vector
  for (i = 0; i < VectorLength(v); ++i)
    free(VectorGet(v, i));
  // free the vector
  VectorFree(v);

  return EXIT_SUCCESS;
}
static int
compute_cluster_statistics(MRI_SURFACE *mris, MRI *mri_profiles, CLUSTER *ct, int k) {
  int    i, vno, cluster, nsamples, num[MAX_CLUSTERS];
  VECTOR *v1 ;

  memset(num, 0, sizeof(num)) ;
  nsamples = mri_profiles->nframes ;

  v1 = VectorAlloc(nsamples, MATRIX_REAL) ;

  for (cluster = 0 ; cluster < k ; cluster++)
    VectorClear(ct[cluster].v_mean) ;

  // compute means
  for (vno = 0 ; vno < mris->nvertices ; vno++) {
    cluster = mris->vertices[vno].curv ;
    for (i = 0 ; i < nsamples ; i++) {
      VECTOR_ELT(v1, i+1) = MRIgetVoxVal(mri_profiles, vno, 0, 0, i) ;
    }
    num[cluster]++ ;
    VectorAdd(ct[cluster].v_mean, v1, ct[cluster].v_mean) ;
  }

  for (cluster = 0 ; cluster < k ; cluster++)
    if (num[cluster] > 0)
      VectorScalarMul(ct[cluster].v_mean, 1.0/(double)num[cluster], ct[cluster].v_mean) ;

  VectorFree(&v1) ;
  return(NO_ERROR) ;
}
Esempio n. 7
0
static MRI *
apply_bias(MRI *mri_orig, MRI *mri_norm, MRI *mri_bias) {
  MATRIX   *m_vox2vox;
  VECTOR   *v1, *v2;
  int      x, y, z ;
  double   xd, yd, zd, bias, val_orig, val_norm ;

  if (mri_norm == NULL)
    mri_norm = MRIclone(mri_orig, NULL) ;

  m_vox2vox = MRIgetVoxelToVoxelXform(mri_orig, mri_bias) ;
  v1 = VectorAlloc(4, MATRIX_REAL);
  v2 = VectorAlloc(4, MATRIX_REAL);
  VECTOR_ELT(v1, 4) = 1.0 ;
  VECTOR_ELT(v2, 4) = 1.0 ;

  for (x = 0 ; x < mri_orig->width ; x++) {
    V3_X(v1) = x ;
    for (y = 0 ; y < mri_orig->height ; y++) {
      V3_Y(v1) = y ;
      for (z = 0 ; z < mri_orig->depth ; z++) {
        V3_Z(v1) = z ;
        if (x == Gx && y == Gy && z == Gz)
          DiagBreak() ;
        val_orig = MRIgetVoxVal(mri_orig, x, y, z, 0) ;
        MatrixMultiply(m_vox2vox, v1, v2) ;
        xd = V3_X(v2) ;
        yd = V3_Y(v2) ;
        zd = V3_Z(v2);
        MRIsampleVolume(mri_bias, xd, yd, zd, &bias) ;
        val_norm = val_orig * bias ;
        if (mri_norm->type == MRI_UCHAR) {
          if (val_norm > 255)
            val_norm = 255 ;
          else if (val_norm < 0)
            val_norm = 0 ;
        }
        MRIsetVoxVal(mri_norm, x, y, z, 0, val_norm) ;
      }
    }
  }

  MatrixFree(&m_vox2vox) ;
  VectorFree(&v1) ;
  VectorFree(&v2) ;
  return(mri_norm) ;
}
static int
find_most_likely_unmarked_vertex(MRI_SURFACE *mris, MRI *mri_profiles, CLUSTER *ct, int k, int *pcluster_no) {
  double   dist, min_dist ;
  int      vno, c, min_cluster, min_vno, n, okay ;
  VECTOR   *v_vals ;
  VERTEX   *v, *vn ;

  v_vals = VectorAlloc(mri_profiles->nframes, MATRIX_REAL) ;

  min_dist = -1 ;
  min_vno = -1 ;
  min_cluster = -1 ;
  for (vno = 0 ; vno < mris->nvertices ; vno++) {
    v = &mris->vertices[vno] ;
    if (v->ripflag)
      continue ;
    if (v->curv < 0)   // not in a cluster yet
      continue ;

    c = v->curv ;
    for (n = 0 ; n < v->vnum ; n++) {
      vn = &mris->vertices[v->v[n]] ;
      if (vn->curv >= 0)
        continue ;
      if (vn->ripflag)
        continue ;
      load_vals(mri_profiles, v_vals, v->v[n]) ;
      dist = MatrixMahalanobisDistance(ct[c].v_mean, ct[c].m_cov, v_vals);
      if (min_vno < 0 || dist < min_dist) {
        if (ct[c].npoints == 1)
          okay = 1 ;
        else // check to make sure it has at least 2 nbrs of the right class
        {
          int n2, nc ;
          for (n2 = nc = 0 ; n2 < vn->vnum ; n2++)
            if (mris->vertices[vn->v[n2]].curv == c)
              nc++ ;
          okay = nc > 1 ;
        }
        if (okay) {
          min_cluster = c ;
          min_dist = dist ;
          min_vno = v->v[n] ;
        }
      }
    }
  }

  v = &mris->vertices[min_vno] ;
  *pcluster_no = min_cluster ;
  VectorFree(&v_vals) ;
  return(min_vno) ;
}
Esempio n. 9
0
File: matrix.c Progetto: dkogan/PDL
void Jacobi(const int n, double **a, double *b, double *x, double eps, 
	    int max_iter) {

  double    d;              /* temporary real */
  int       i, j, iter;     /* counters       */
  double  **a_new;          /* a is altered   */
  double   *b_new;          /* b is altered   */
  double   *u;              /* new solution   */
  double    norm;           /* L1-norm        */

  a_new=MatrixAlloc(3);
  b_new=VectorAlloc(3);
  u=VectorAlloc(3);

  for(i=0; i<n; i++) {       /* the trick */
    d=1.0/a[i][i];
    b_new[i]=d*b[i];
    for(j=0; j<n; j++)
      a_new[i][j]=d*a[i][j];
  } /* for i */

  iter=0;
  do {
    iter++;
    norm=0.0;
    for(i=0; i<n; i++) {       /* update process */
      d=-a_new[i][i]*x[i];     /* don't include term i=j */
      for(j=0; j<n; j++)
	d+=a_new[i][j]*x[j];   
      u[i]=b_new[i]-d;
      norm=fabs(u[i]-x[i]);
    } /* for i */
    for(i=0; i<n; i++)           /* copy solution */
      x[i]=u[i];
  } while ((iter<=max_iter) && (norm>=eps));
  
  MatrixFree(3, a_new);
  VectorFree(3, b_new);
  VectorFree(3, u);
} /* Jacobi */
Esempio n. 10
0
File: matrix.c Progetto: dkogan/PDL
void LUfact(const int n, double **a, int *p) {

  int      i, j, k;             /* counters           */
  double   z;                   /* temporary real     */
  double  *s;                   /* pivot elements     */
  int      not_finished;        /* loop control var.  */
  int      i_swap;              /* swap var.          */
  double   temp;                /* another temp. real */

  s=VectorAlloc(n);
  for(i=0; i<n; i++) {
    p[i]=i;
    s[i]=0.0;
    for(j=0; j<n; j++) {
      z=fabs(a[i][j]);
      if (s[i]<z)
	s[i]=z;
    } /* for j */
  } /* for i */

  for(k=0; k<(n-1); k++) {
    j=k-1;           /* select j>=k so ... */
    not_finished=1;
    while (not_finished) {
      j++;
      temp=fabs(a[p[j]][k]/s[p[j]]);
      for(i=k; i<n; i++)  
	if (temp>=(fabs(a[p[i]][k])/s[p[i]]))
	  not_finished=0;          /* end loop */
    } /* while */
    i_swap=p[k];
    p[k]=p[j];
    p[j]=i_swap;
    temp=1.0/a[p[k]][k];
    for(i=(k+1); i<n; i++) {
      z=a[p[i]][k]*temp;
      a[p[i]][k]=z;
      for(j=(k+1); j<n; j++) 
	a[p[i]][j]-=z*a[p[k]][j];
    } /* for i */
  } /* for k */

  VectorFree(n, s);
} /* LUfact */
Esempio n. 11
0
static int
mark_clusters(MRI_SURFACE *mris, MRI *mri_profiles, CLUSTER *ct, int k) {
  int    i, vno, min_i, nsamples, num[MAX_CLUSTERS], nchanged ;
  double min_dist, dist ;
  VECTOR *v1 ;
  VERTEX *v ;

  memset(num, 0, sizeof(num)) ;
  nsamples = mri_profiles->nframes ;
  v1 = VectorAlloc(nsamples, MATRIX_REAL) ;
  for (nchanged = vno = 0 ; vno < mris->nvertices ; vno++) {
    v = &mris->vertices[vno] ;
    if (v->ripflag)
      continue ;
    if (vno == Gdiag_no)
      DiagBreak() ;

    for (i = 0 ; i < nsamples ; i++)
      VECTOR_ELT(v1, i+1) = MRIgetVoxVal(mri_profiles, vno, 0, 0, i) ;
    min_dist = MatrixMahalanobisDistance(ct[0].v_mean, ct[0].m_cov, v1) ;
    min_i = 0 ;
    for (i = 1 ; i < k ; i++) {
      if (i == Gdiag_no)
        DiagBreak() ;
      dist = MatrixMahalanobisDistance(ct[i].v_mean, ct[i].m_cov, v1) ;
      if (dist < min_dist) {
        min_dist = dist ;
        min_i = i ;
      }
    }
    CTABannotationAtIndex(mris->ct, min_i, &v->annotation) ;
    if (v->curv != min_i)
      nchanged++ ;
    v->curv = min_i ;
    num[min_i]++ ;
  }
  for (i = 0 ; i < k ; i++)
    if (num[i] == 0)
      DiagBreak() ;
  VectorFree(&v1) ;
  printf("%d vertices changed clusters...\n", nchanged) ;
  return(nchanged) ;
}
Esempio n. 12
0
File: matrix.c Progetto: dkogan/PDL
void Tridiag(const int n, double *a, double *d, double *c, double *b) {

  int        i;            /* counter */
  double    *x;            /* solution */

  x=VectorAlloc(n);

  for(i=1; i<n; i++) {
    d[i]-=(a[i-1]/d[i-1])*c[i-1];
    b[i]-=(a[i-1]/d[i-1])*b[i-1];
  } /* for i */
  x[n-1]=b[n-1]/d[n-1];
  for(i=(n-2); i>=0; i--) 
    x[i]=(b[i]-c[i]*b[i+1])/d[i];

  for(i=0; i<n; i++)
    b[i]=x[i];
  VectorFree(n, x);
} /* Tridiag */
Esempio n. 13
0
File: matrix.c Progetto: dkogan/PDL
void LUsubst(const int n, double **a, int *p, double *b) {

  int        i, j, k;           /* counters               */
  double     sum;               /* temporary sum variable */
  double    *x;                 /* solution               */
  
  x=VectorAlloc(n);

  for(k=0; k<(n-1); k++)        /* forward subst */
    for(i=(k+1); i<n; i++)
      b[p[i]]-=a[p[i]][k]*b[p[k]];
  
  for(i=(n-1); i>=0; i--) {     /* back subst */
    sum=b[p[i]];
    for(j=(i+1); j<n; j++)
      sum-=a[p[i]][j]*x[j];
    x[i]=sum/a[p[i]][i];
  } /* for i */
    
  for(i=0; i<n; i++)             /* copy solution */
    b[i]=x[i];

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

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

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

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

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

  return(NO_ERROR) ;
}
Esempio n. 15
0
static int
compute_cluster_statistics(MRI_SURFACE *mris, MRI *mri_profiles, MATRIX **m_covs, VECTOR **v_means, int k) {
  int    i, vno, cluster, nsamples, num[MAX_CLUSTERS];
  int    singular, cno_pooled, cno ;
  MATRIX *m1, *mpooled, *m_inv_covs[MAX_CLUSTERS] ;
  VECTOR *v1 ;
  FILE   *fp ;
  double det, det_pooled ;

  memset(num, 0, sizeof(num)) ;
  nsamples = mri_profiles->nframes ;

  v1 = VectorAlloc(nsamples, MATRIX_REAL) ;
  m1 = MatrixAlloc(nsamples, nsamples, MATRIX_REAL) ;
  mpooled = MatrixAlloc(nsamples, nsamples, MATRIX_REAL) ;

  for (cluster = 0 ; cluster < k ; cluster++) {
    VectorClear(v_means[cluster]) ;
    MatrixClear(m_covs[cluster]) ;
  }

  // compute means
  // fp = fopen("co.dat", "w") ;
  fp = NULL ;
  for (vno = 0 ; vno < mris->nvertices ; vno++) {
    cluster = mris->vertices[vno].curv ;
    for (i = 0 ; i < nsamples ; i++) {
      VECTOR_ELT(v1, i+1) = MRIgetVoxVal(mri_profiles, vno, 0, 0, i) ;
      if (cluster == 0 && fp)
        fprintf(fp, "%f ", VECTOR_ELT(v1, i+1));
    }
    if (cluster == 0 && fp)
      fprintf(fp, "\n") ;
    num[cluster]++ ;
    VectorAdd(v_means[cluster], v1, v_means[cluster]) ;
  }

  if (fp)
    fclose(fp) ;
  for (cluster = 0 ; cluster < k ; cluster++)
    if (num[cluster] > 0)
      VectorScalarMul(v_means[cluster], 1.0/(double)num[cluster], v_means[cluster]) ;

  // compute inverse covariances
  for (vno = 0 ; vno < mris->nvertices ; vno++) {
    cluster = mris->vertices[vno].curv ;
    for (i = 0 ; i < nsamples ; i++)
      VECTOR_ELT(v1, i+1) = MRIgetVoxVal(mri_profiles, vno, 0, 0, i) ;
    VectorSubtract(v_means[cluster], v1, v1) ;
    VectorOuterProduct(v1, v1, m1) ;
    MatrixAdd(m_covs[cluster], m1, m_covs[cluster]) ;
    MatrixAdd(mpooled, m1, mpooled) ;
  }

  MatrixScalarMul(mpooled, 1.0/(double)mris->nvertices, mpooled) ;
  cno_pooled = MatrixConditionNumber(mpooled) ;
  det_pooled = MatrixDeterminant(mpooled) ;
  for (cluster = 0 ; cluster < k ; cluster++)
    if (num[cluster] > 0)
      MatrixScalarMul(m_covs[cluster], 1.0/(double)num[cluster], m_covs[cluster]) ;


  // invert all the covariance matrices
  MatrixFree(&m1) ;
  singular = 0 ;
  for (cluster = 0 ; cluster < k ; cluster++) {
    m1 = MatrixInverse(m_covs[cluster], NULL) ;
    cno = MatrixConditionNumber(m_covs[cluster]) ;
    det = MatrixDeterminant(m_covs[cluster]) ;
    if (m1 == NULL)
      singular++ ;
    while (cno > 100*cno_pooled || 100*det < det_pooled) {
      if (m1)
        MatrixFree(&m1) ;
      m1 = MatrixScalarMul(mpooled, 0.1, NULL) ;
      MatrixAdd(m_covs[cluster], m1, m_covs[cluster]) ;
      MatrixFree(&m1) ;
      cno = MatrixConditionNumber(m_covs[cluster]) ;
      m1 = MatrixInverse(m_covs[cluster], NULL) ;
      det = MatrixDeterminant(m_covs[cluster]) ;
    }
    m_inv_covs[cluster] = m1 ;
  }

  for (cluster = 0 ; cluster < k ; cluster++) {
    if (m_inv_covs[cluster] == NULL)
      DiagBreak() ;
    else {
      MatrixFree(&m_covs[cluster]) ;
      m_covs[cluster] = m_inv_covs[cluster] ;
      //   MatrixIdentity(m_covs[cluster]->rows, m_covs[cluster]);
    }
  }
  MatrixFree(&mpooled) ;
  VectorFree(&v1) ;
  return(NO_ERROR) ;
}
Esempio n. 16
0
void MPI_MatrixMultiplyToVector(double ** mat, double * vec, int N)
{
  int i, rowmin, rowmax, sendcount;
  int * recvcounts;
  double ThisElement;
  double * MyVector;


  /*
    Determine how many elements to receive from each task
  */

  recvcounts = malloc(NTasks * sizeof(int));

  for (i=0; i < NTasks; i++)
    {
      if (i != NTasks - 1)
	{
	  recvcounts[i] = ProcBoundaries[i+1] - ProcBoundaries[i];
	}
      else
	{
	  recvcounts[i] = TransferCount - ProcBoundaries[i];
	}
    }

  /*
    Determine how many elements to send
  */

  rowmin = ProcBoundaries[ThisTask];
  if (ThisTask != NTasks - 1)
    rowmax = ProcBoundaries[ThisTask + 1];
  else
    rowmax = TransferCount - ProcBoundaries[ThisTask];

  MyVector = VectorMalloc(recvcounts[ThisTask]);//VectorMalloc(rowmax - rowmin);

  //PrintMatrix(mat, recvcounts[ThisTask], TransferCount);

  // Get rowspan elements by exploiting the 1D partition
  for (i=0; i < /*rowmax - rowmin*/ recvcounts[ThisTask]; i++)
    {
      ThisElement = Dot(mat[i], vec, N);
      //printf("ThisElement = %f\n", ThisElement);
      MyVector[i] = ThisElement;
    }
  
  //printf("(min, max) on thread %d = %d, %d\n", ThisTask, rowmin, rowmax);
  sendcount = recvcounts[ThisTask];//rowmax - rowmin;
  //printf("sendcount[%d] = %d\n", ThisTask, sendcount);

  /*
  for (i=0; i < NTasks; i++)
    {
      printf("recvcounts[%d] = %d\n", i, recvcounts[i]);
      //printf("sendcount[%d] = %d\n", ThisTask, sendcount);
      }*/
  MPI_Allgatherv(MyVector, sendcount, MPI_DOUBLE, vec, recvcounts, ProcBoundaries, MPI_DOUBLE, MPI_COMM_WORLD);

  //for (i=0; i < N; i++)
  //  printf("Vector[%d] = %f\n",i, vec[i]);
  VectorFree(MyVector, sendcount);
}
Esempio n. 17
0
int
main(int argc, char *argv[]) {
  TRANSFORM    *transform = NULL ;
  char         **av, fname[STRLEN], *gca_fname, *subject_name, *cp ;
  int          ac, nargs, i, n ;
  int          msec, minutes, seconds, nsubjects ;
  struct timeb start ;
  GCA          *gca ;
  MRI          *mri_parc, *mri_T1, *mri_PD ;
  FILE         *fp ;

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

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

  TimerStart(&start) ;

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

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


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

  n = 0 ;

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

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

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

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


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

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

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

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

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

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

  if (write_flag)
    GCAwrite(gca, gca_fname) ;
  GCAfree(&gca) ;
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  printf("tissue parameter statistic calculation took %d minutes"
         " and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
MRI *
add_aseg_structures_outside_ribbon(MRI *mri_src, MRI *mri_aseg, MRI *mri_dst,
                                   int wm_val, int gm_val, int csf_val)
{
  VECTOR *v1, *v2 ;
  MATRIX *m_vox2vox ;
  int    x, y, z, xa, ya, za, seg_label, aseg_label ;

  if (mri_dst == NULL)
    mri_dst = MRIcopy(mri_src, NULL) ;
  v1 = VectorAlloc(4, MATRIX_REAL) ;
  v2 = VectorAlloc(4, MATRIX_REAL) ;
  VECTOR_ELT(v1, 4) = 1.0 ; VECTOR_ELT(v2, 4) = 1.0 ;
  m_vox2vox = MRIgetVoxelToVoxelXform(mri_src, mri_aseg) ;


  for (x = 0 ; x < mri_dst->width ; x++)
  {
    V3_X(v1) = x ;
    for (y = 0 ; y < mri_dst->height ; y++)
    {
      V3_Y(v1) = y ;
      for (z = 0 ; z < mri_dst->depth ; z++)
      {
        if (x == Gx && y == Gy && z == Gz)
          DiagBreak() ;
        seg_label = nint(MRIgetVoxVal(mri_dst, x, y, z, 0)) ;
        V3_Z(v1) = z ;
        MatrixMultiply(m_vox2vox, v1, v2) ;
        xa = (int)(nint(V3_X(v2))) ;
        ya = (int)(nint(V3_Y(v2))) ;
        za = (int)(nint(V3_Z(v2))) ;
        if (xa < 0 || ya < 0 || za < 0 ||
            xa >= mri_aseg->width || ya >= mri_aseg->height || za >= mri_aseg->depth)
          continue ;
        if (xa == Gx && ya == Gy && za == Gz)
          DiagBreak() ;
        aseg_label = nint(MRIgetVoxVal(mri_aseg, xa, ya, za, 0)) ;
        if (seg_label != 0 && !IS_MTL(aseg_label))  // already labeled and not amyg/hippo, skip it
          continue ;
        switch (aseg_label)
        {
        case Left_Cerebellum_White_Matter:
        case Right_Cerebellum_White_Matter:
        case Brain_Stem:
          MRIsetVoxVal(mri_dst, x, y, z, 0, wm_val) ;
          break ;
	case Left_Hippocampus:
	case Right_Hippocampus:
	case Left_Amygdala:
	case Right_Amygdala:
        case Left_Cerebellum_Cortex:
        case Right_Cerebellum_Cortex:
        case Left_Pallidum:
        case Right_Pallidum:
        case Left_Thalamus_Proper:
        case Right_Thalamus_Proper:
        case Right_Putamen:
        case Left_Putamen:
        case Right_Caudate:
        case Left_Caudate:
        case Left_Accumbens_area:
        case Right_Accumbens_area:  // remove them from cortex
          MRIsetVoxVal(mri_dst, x, y, z, 0, gm_val) ;
          break ;
        default:
          break ;
        }
      }
    }
  }

  VectorFree(&v1) ; VectorFree(&v2) ; MatrixFree(&m_vox2vox) ;
  return(mri_dst) ;
}
Esempio n. 19
0
int
main(int argc, char *argv[]) {
  char   **av, *label_name, *vol_name, *out_name ;
  int    ac, nargs ;
  int    msec, minutes, seconds,  i  ;
  LABEL  *area ;
  struct timeb start ;
  MRI    *mri,  *mri_seg ;
  Real   xw, yw, zw, xv, yv, zv, val;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mri_label_vals.c,v 1.16 2015/08/24 18:22:05 fischl Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

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

  TimerStart(&start) ;

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

  if (argc < 3)
    usage_exit(1) ;

  vol_name = argv[1] ;
  label_name = argv[2]  ;
  out_name = argv[3] ;

  mri = MRIread(vol_name) ;
  if (!mri)
    ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname, vol_name) ;
  if (scaleup_flag) {
    float scale, fov_x, fov_y, fov_z  ;

    scale = 1.0/MIN(MIN(mri->xsize, mri->ysize),mri->zsize) ;
    fprintf(stderr, "scaling voxel sizes up by %2.2f\n", scale) ;
    mri->xsize *= scale ;
    mri->ysize *= scale ;
    mri->zsize *= scale ;
    fov_x = mri->xsize * mri->width;
    fov_y = mri->ysize * mri->height;
    fov_z = mri->zsize * mri->depth;
    mri->xend = fov_x / 2.0;
    mri->xstart = -mri->xend;
    mri->yend = fov_y / 2.0;
    mri->ystart = -mri->yend;
    mri->zend = fov_z / 2.0;
    mri->zstart = -mri->zend;

    mri->fov = (fov_x > fov_y ? (fov_x > fov_z ? fov_x : fov_z) : (fov_y > fov_z ? fov_y : fov_z) );
  }

  if (segmentation_flag >= 0) {
    int x, y, z  ;
    VECTOR *v_seg, *v_mri ;
    MATRIX *m_seg_to_mri ;

    v_seg = VectorAlloc(4, MATRIX_REAL) ;
    v_mri = VectorAlloc(4, MATRIX_REAL) ;
    VECTOR_ELT(v_seg, 4) = 1.0 ;
    VECTOR_ELT(v_mri, 4) = 1.0 ;

    mri_seg = MRIread(argv[2]) ;
    if (!mri_seg)
      ErrorExit(ERROR_NOFILE, "%s: could not read volume from %s",Progname, argv[2]) ;
    if (erode) {
      MRI *mri_tmp ;

      mri_tmp = MRIclone(mri_seg, NULL) ;
      MRIcopyLabel(mri_seg, mri_tmp, segmentation_flag) ;
      while (erode-- > 0)
        MRIerode(mri_tmp, mri_tmp) ;
      MRIcopy(mri_tmp, mri_seg) ;
      MRIfree(&mri_tmp) ;
    }

    m_seg_to_mri = MRIgetVoxelToVoxelXform(mri_seg, mri) ;
    for (x = 0  ; x  < mri_seg->width ; x++) {
      V3_X(v_seg) = x ;
      for (y = 0  ; y  < mri_seg->height ; y++) {
        V3_Y(v_seg) = y ;
        for (z = 0  ; z  < mri_seg->depth ; z++) {
          V3_Z(v_seg) = z ;
          if (MRIvox(mri_seg, x, y,  z) == segmentation_flag) {
            MatrixMultiply(m_seg_to_mri, v_seg, v_mri) ;
            xv = V3_X(v_mri) ;
            yv = V3_Y(v_mri) ;
            zv = V3_Z(v_mri) ;
            MRIsampleVolumeType(mri, xv,  yv, zv, &val, SAMPLE_NEAREST);
#if  0
            if (val < .000001) {
              val *= 1000000;
              printf("%f*0.000001\n", val);
            } else
#endif
              if (coords)
                printf("%2.1f %2.1f %2.1f %f\n", xv, yv, zv, val);
              else
                printf("%f\n", val);
          }
        }
      }
    }
    MatrixFree(&m_seg_to_mri) ;
    VectorFree(&v_seg) ;
    VectorFree(&v_mri) ;
  } else {
    if (cras == 1)
      fprintf(stderr,"using the label coordinates to be c_(r,a,s) != 0.\n");

    if (surface_dir) {
      MRI_SURFACE *mris ;
      char fname[STRLEN] ;
      sprintf(fname, "%s/%s.white", surface_dir, hemi) ;
      mris = MRISread(fname) ;
      if (mris == NULL)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s...\n", Progname,fname) ;
      sprintf(fname, "%s/%s.thickness", surface_dir, hemi) ;
      if (MRISreadCurvatureFile(mris, fname) != NO_ERROR)
        ErrorExit(ERROR_BADPARM, "%s: could not read thickness file %s...\n", Progname,fname) ;

      if (annot_prefix)   /* read an annotation in and print vals in it */
      {
#define MAX_ANNOT 10000
        int   vno, annot_counts[MAX_ANNOT], index ;
        VERTEX *v ;
        Real  xw, yw, zw, xv, yv, zv, val ;
        float annot_means[MAX_ANNOT] ;
        FILE  *fp ;

        memset(annot_means, 0, sizeof(annot_means)) ;
        memset(annot_counts, 0, sizeof(annot_counts)) ;
        if (MRISreadAnnotation(mris, label_name) != NO_ERROR)
          ErrorExit(ERROR_BADPARM, "%s: could not read annotation file %s...\n", Progname,fname) ;
        if (mris->ct == NULL)
          ErrorExit(ERROR_BADPARM, "%s: annot file does not contain a color table, specifiy one with -t ", Progname);
        for (vno = 0 ; vno < mris->nvertices ; vno++) {
          v = &mris->vertices[vno] ;
          if (v->ripflag)
            continue ;
          CTABfindAnnotation(mris->ct, v->annotation, &index) ;
          if (index >= 0 && index < mris->ct->nentries) {
            annot_counts[index]++ ;
            xw = v->x + v->curv*.5*v->nx ;
            yw = v->y + v->curv*.5*v->ny ;
            zw = v->z + v->curv*.5*v->nz ;
            if (cras == 1)
              MRIworldToVoxel(mri, xw, yw,  zw, &xv, &yv, &zv) ;
            else
              MRIsurfaceRASToVoxel(mri, xw, yw, zw, &xv, &yv, &zv);
            MRIsampleVolume(mri, xv, yv, zv, &val) ;
            annot_means[index] += val ;
            sprintf(fname, "%s-%s-%s.dat", annot_prefix, hemi, mris->ct->entries[index]->name) ;
            fp = fopen(fname, "a") ;
            fprintf(fp, "%f\n", val) ;
            fclose(fp) ;
          }
        }
      }
      else  /* read label in and print vals in it */
      {
        area = LabelRead(NULL, label_name) ;
        if (!area)
          ErrorExit(ERROR_NOFILE, "%s: could not read label from %s",Progname, label_name) ;

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

      for (i = 0 ;  i  < area->n_points ; i++) {

        xw =  area->lv[i].x ;
        yw =  area->lv[i].y ;
        zw =  area->lv[i].z ;
        if (cras == 1)
          MRIworldToVoxel(mri, xw, yw,  zw, &xv, &yv, &zv) ;
        else
          MRIsurfaceRASToVoxel(mri, xw, yw, zw, &xv, &yv, &zv);
        MRIsampleVolumeType(mri, xv,  yv, zv, &val, SAMPLE_NEAREST);
#if 0
        if (val < .000001) {
          val *= 1000000;
          printf("%f*0.000001\n", val);
        } else
#endif
          printf("%f\n", val);
      }
    }
  }
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;

  if (DIAG_VERBOSE_ON)
    fprintf(stderr, "label value extractiong took %d minutes and %d seconds.\n",
            minutes, seconds) ;

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

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

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

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

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

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

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

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

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

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

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

  MatrixFree(&mRot) ;
  VectorFree(&mOrigin) ;
  return(m_L) ;
}
Esempio n. 21
0
static void computeCurvature(VerTex *vertex,int nvt,FaCe *face, int nfc,int* ref_tab,int nb,float* curv)
{
    int n,m,reference;
    VECTOR *v_n, *v_e1,*v_e2,*v;
    float nx,ny,nz,area,dx,dy,dz,y,r2,u1,u2,YR2,R4;

    v_n=VectorAlloc(3,MATRIX_REAL);
    v_e1=VectorAlloc(3,MATRIX_REAL);
    v_e2=VectorAlloc(3,MATRIX_REAL);
    v=VectorAlloc(3,MATRIX_REAL);
    for (n=0; n<nb; n++)
    {
        reference=ref_tab[n];
        //first need to compute normal
        nx=ny=nz=area=0;
        for (m=0; m<vertex[reference].fnum; m++)
        {
            nx+=face[vertex[reference].f[m]].nx*face[vertex[reference].f[m]].area;
            ny+=face[vertex[reference].f[m]].ny*face[vertex[reference].f[m]].area;
            nz+=face[vertex[reference].f[m]].nz*face[vertex[reference].f[m]].area;
            area+=face[vertex[reference].f[m]].area;
        }
        nx/=area;
        ny/=area;
        nz/=area;
        VECTOR_LOAD(v_n,nx,ny,nz);
        //now need to compute the tangent plane!
        VECTOR_LOAD(v,ny,nz,nx);
        V3_CROSS_PRODUCT(v_n,v,v_e1);
        if ((V3_LEN_IS_ZERO(v_e1)))
        {
            if (nz!=0)
                VECTOR_LOAD(v,ny,-nz,nx)
                else if (ny!=0)
                    VECTOR_LOAD(v,-ny,nz,nx)
                    else
                        VECTOR_LOAD(v,ny,nz,-nx);
            V3_CROSS_PRODUCT(v_n,v,v_e1);
        }
        V3_CROSS_PRODUCT(v_n,v_e1,v_e2);
        V3_NORMALIZE(v_e1,v_e1);
        V3_NORMALIZE(v_e2,v_e2);
        //finally compute curvature by fitting a 1-d quadratic r->a*r*r: curv=2*a

        for (YR2=0,R4=0,m=0; m<vertex[reference].vnum; m++)
        {
            dx=vertex[vertex[reference].v[m]].x-vertex[reference].x;
            dy=vertex[vertex[reference].v[m]].y-vertex[reference].y;
            dz=vertex[vertex[reference].v[m]].z-vertex[reference].z;
            VECTOR_LOAD(v,dx,dy,dz);

            y=V3_DOT(v,v_n);
            u1=V3_DOT(v_e1,v);
            u2=V3_DOT(v_e2,v);
            r2=u1*u1+u2*u2;
            YR2+=y*r2;
            R4+=r2*r2;
        }
        curv[n]=2*YR2/R4;
    }


    VectorFree(&v);
    VectorFree(&v_n);
    VectorFree(&v_e1);
    VectorFree(&v_e2);
}
static int
update_histograms(MRI_SURFACE *mris, MRI_SURFACE *mris_avg, float ***histograms, int nbins) {
  int    vno, vno2, vno_avg ;
  double volume_dist, surface_dist, circumference, angle ;
  VERTEX *v1, *v2 ;
  VECTOR *vec1, *vec2 ;
  MHT    *mht ;
  float  **histogram, min_dist ;

  mht = MHTfillVertexTableRes(mris_avg, NULL, CURRENT_VERTICES, 2.0) ;

  vec1 = VectorAlloc(3, MATRIX_REAL) ;
  vec2 = VectorAlloc(3, MATRIX_REAL) ;

  v1 = &mris->vertices[0] ;
  VECTOR_LOAD(vec1, v1->cx, v1->cy, v1->cz) ;  /* radius vector */
  circumference = M_PI * 2.0 * V3_LEN(vec1) ;
  MRISclearMarks(mris_avg) ;
#if 0
  for (vno = 0 ; vno < mris->nvertices ; vno++) {
    if ((vno % 1000) ==  0) {
      printf("\r%d of %d    ", vno, mris->nvertices) ;
      fflush(stdout) ;
    }
    v1 = &mris->vertices[vno] ;
    VECTOR_LOAD(vec1, v1->cx, v1->cy, v1->cz) ;  /* radius vector */
    vno_avg = MHTfindClosestVertexNo(mht, mris_avg, v1, &min_dist) ;  /* which histogram to increment */
    if (vno_avg < 0)
      continue ;
    if (vno_avg == Gdiag_no)
      DiagBreak() ;
    histogram = histograms[vno_avg] ;
    mris_avg->vertices[vno_avg].marked = 1 ;

    for (vno2 = 0 ; vno2 < mris->nvertices ; vno2++) {
      if (vno2 == vno)
        continue ;
      v2 = &mris->vertices[vno2] ;
      VECTOR_LOAD(vec2, v2->cx, v2->cy, v2->cz) ;  /* radius vector */
      volume_dist = sqrt(SQR(v1->origx-v2->origx)+SQR(v1->origy-v2->origy)+SQR(v1->origz-v2->origz)) ;
      if (nint(volume_dist) >= nbins || nint(volume_dist) < 0)
        continue ;
      angle = fabs(Vector3Angle(vec1, vec2)) ;
      surface_dist = circumference * angle / (2.0 * M_PI) ;
      if (surface_dist > nbins*MAX_SURFACE_SCALE)
        surface_dist = nbins*MAX_SURFACE_SCALE ;
      if (surface_dist < 1)
        surface_dist = 1 ;

      histogram[nint(volume_dist)][nint(surface_dist)]++ ;

      if (mht->buckets[0][0] != NULL)
        DiagBreak() ;
    }
  }
  MHTfree(&mht) ;
#endif

  /* map back ones that were missed */
  /* printf("\nfilling holes in mapping\n") ;*/
  mht = MHTfillVertexTableRes(mris, NULL, CURRENT_VERTICES, 2.0) ;
  for (vno_avg = 0 ; vno_avg < mris_avg->nvertices ; vno_avg++) {
    if (mris_avg->vertices[vno_avg].marked > 0)
      continue ;

    if ((vno_avg % 1000) ==  0) {
      printf("\r%d of %d    ", vno_avg, mris_avg->nvertices) ;
      fflush(stdout) ;
    }

    vno = MHTfindClosestVertexNo(mht, mris, &mris_avg->vertices[vno_avg], &min_dist) ;
    if (vno < 0)
      continue ;
    v1 = &mris->vertices[vno] ;
    VECTOR_LOAD(vec1, v1->cx, v1->cy, v1->cz) ;  /* radius vector */
    if (vno_avg < 0)
      continue ;
    if (vno_avg == Gdiag_no)
      DiagBreak() ;
    histogram = histograms[vno_avg] ;
    mris_avg->vertices[vno_avg].marked = 1 ;

    for (vno2 = 0 ; vno2 < mris->nvertices ; vno2++) {
      if (vno2 == vno)
        continue ;
      v2 = &mris->vertices[vno2] ;
      VECTOR_LOAD(vec2, v2->cx, v2->cy, v2->cz) ;  /* radius vector */
      volume_dist = sqrt(SQR(v1->origx-v2->origx)+SQR(v1->origy-v2->origy)+SQR(v1->origz-v2->origz)) ;
      if (nint(volume_dist) >= nbins || nint(volume_dist) < 0)
        continue ;
      angle = fabs(Vector3Angle(vec1, vec2)) ;
      surface_dist = circumference * angle / (2.0 * M_PI) ;
      if (surface_dist > nbins*MAX_SURFACE_SCALE)
        surface_dist = nbins*MAX_SURFACE_SCALE ;
      if (surface_dist < 1)
        surface_dist = 1 ;

      histogram[nint(volume_dist)][nint(surface_dist)]++ ;
    }
  }

  MHTfree(&mht) ;
  printf("\n") ;

  VectorFree(&vec1) ;
  VectorFree(&vec2) ;
  return(NO_ERROR) ;
}