コード例 #1
0
ファイル: RANSAC.c プロジェクト: HiromuIshikawa/MakePanoExp
  Matrix* makeTranceMT(Image *im, Image* im2,char *imName, char *imName2){
    Matrix *mt, *ans;
    int i,nm,snm;
    int match[999][2],ansAry[100][4];
    int x1[30][2], N1=30, x2[30][2], N2=30;

    TKfilter(x1, imName);
    TKfilter(x2, imName2);

    mt=MatrixAlloc(N1,N2);
    calcSSDtable(mt,im,x1,N1,im2,x2,N2);

  //  nm = greedyMethod(match,mt,im,x1,N1,im2,x2,N2);
    nm = matchMethod2(match,mt,im,x1,N1,im2,x2,N2);
    /* for(i = 0; i < nm; i++)
      printf("%d:(%d,%d,%d,%d)\n",i,x1[match[i][0]][0],x1[match[i][0]][1],
      x2[match[i][1]][0],x2[match[i][1]][1]);*/

    snm = ransacMethod(N1, ansAry, match, x1, x2);
    double xy[snm][2], uv[snm][2];
    for(i = 0; i < snm; i++) {
      xy[i][0] = ansAry[i][0];
      xy[i][1] = ansAry[i][1];
      uv[i][0] = ansAry[i][2];
      uv[i][1] = ansAry[i][3];
      printf("(%f %f %f %f)\n", xy[i][0],xy[i][1],uv[i][0],uv[i][1]);
    }
    ans = MatrixAlloc(1,8);
    printf("-----------------%d\n",snm);
    ans = lsq(snm,xy,uv);
    return ans;
  }
コード例 #2
0
ファイル: test_matrix.cpp プロジェクト: guo2004131/freesurfer
int
MatrixTest::DoesCreateValidEigenSystem( MATRIX* matrix )
{
    const float TOLERANCE = 2e-5;

    int eigenSystemState = EIGENSYSTEM_INVALID;

    int size = matrix->rows;
    int cols = matrix->cols;

    float *eigenValues = new float[ size ];
    MATRIX *eigenVectors = MatrixAlloc( size, cols, MATRIX_REAL );

    MATRIX *eigenSystem = MatrixEigenSystem( matrix, eigenValues, eigenVectors );
    if (eigenSystem == NULL)
    {
        return EIGENSYSTEM_INVALID;
    }

    bool isInDecendingOrder = true;
    for ( int i=1; i<size; i++ )
    {
        if ( fabs( eigenValues[ i-1 ] ) < fabs( eigenValues[i] ) )
        {
            isInDecendingOrder = false;
            std::cerr << "DoesCreateValidEigenSystem::not in descending order: (" <<
                      eigenValues[ i-1 ] << ", " << eigenValues[i] << ")\n";
        }
    }

    if ( !isInDecendingOrder )
    {
        eigenSystemState = EIGENSYSTEM_NOT_DESCENDING;
    }

    MATRIX* eigenValuesMatrix = MatrixAlloc( size, size, MATRIX_REAL );

    for ( int i=0; i<size; i++ )
    {
        // index of the diagonal
        int index = i + i * size;
        eigenValuesMatrix->data[index] = eigenValues[i];
    }

    MATRIX* xv = MatrixMultiply( matrix, eigenVectors, NULL );
    MATRIX* vd = MatrixMultiply( eigenVectors, eigenValuesMatrix, NULL );

    if ( isInDecendingOrder && AreMatricesEqual( xv, vd, TOLERANCE ) )
    {
        eigenSystemState = EIGENSYSTEM_VALID;
    }

    delete []eigenValues;
    DeleteMatrix( eigenVectors );
    DeleteMatrix( eigenValuesMatrix );

    return eigenSystemState;
}
コード例 #3
0
ファイル: lsq.c プロジェクト: HiromuIshikawa/MakePanoExp
main(){
  Matrix *cmA, *vt, *mtR, *tmp;
  int i;
  double z=1;

  double xy[][2]={ // from 0.jpg
    148,537,
    347,220,
    263,367,
    413,315,
  },uv[][2]={ // from 1.jpg
    371,230,
    463,230,
    383,379,
    530,327,
  };
  double ans[3][3];
  cmA=MatrixAlloc(8,8);
  vt=MatrixAlloc(1,8);

  // create A (col-major)
  for(i=0;i<4;i++){
    cmA->data[cmA->W*0+(i*2  )]=z*xy[i][0];
    cmA->data[cmA->W*1+(i*2  )]=z*xy[i][1];
    cmA->data[cmA->W*2+(i*2  )]=z*z;
    cmA->data[cmA->W*3+(i*2  )]=0;
    cmA->data[cmA->W*4+(i*2  )]=0;
    cmA->data[cmA->W*5+(i*2  )]=0;
    cmA->data[cmA->W*6+(i*2  )]=-xy[i][0]*uv[i][0];
    cmA->data[cmA->W*7+(i*2  )]=-xy[i][1]*uv[i][0];
    cmA->data[cmA->W*0+(i*2+1)]=0;
    cmA->data[cmA->W*1+(i*2+1)]=0;
    cmA->data[cmA->W*2+(i*2+1)]=0;
    cmA->data[cmA->W*3+(i*2+1)]=z*xy[i][0];
    cmA->data[cmA->W*4+(i*2+1)]=z*xy[i][1];
    cmA->data[cmA->W*5+(i*2+1)]=z*z;
    cmA->data[cmA->W*6+(i*2+1)]=-xy[i][0]*uv[i][1];
    cmA->data[cmA->W*7+(i*2+1)]=-xy[i][1]*uv[i][1];
    vt->data[i*2  ]=z*uv[i][0];
    vt->data[i*2+1]=z*uv[i][1];
  }

  // solve Least-squares equation
  mtR=MatrixAlloc(8,8);
  MatrixQRDecompColMajor(mtR,cmA);
  tmp=MatrixAlloc(1,8);
  MatrixMultT(tmp,vt,cmA);
  MatrixSimeqLr(tmp,mtR);
  MatrixPrint(tmp);
}
コード例 #4
0
ファイル: matrix.c プロジェクト: 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 */
コード例 #5
0
ファイル: shadervar.cpp プロジェクト: GameLemur/Crystal-Space
csShaderVariable::csShaderVariable (const csShaderVariable& other)
  : csRefCount (), nameAndType (other.nameAndType)
{
  if (other.accessor)
    AllocAccessor (*other.accessor);
  else
    accessor = 0;

  // Handle payload
  switch (GetTypeI())
  {
  case UNKNOWN:
    break;
  case INT:
    Int = other.Int;
    break;
  case FLOAT:
  case VECTOR2:
  case VECTOR3:
  case VECTOR4:
    memcpy (&Vector, &other.Vector, sizeof (Vector));
    break;

  case TEXTURE:
    texture = other.texture;
    if (texture.HandValue)
      texture.HandValue->IncRef ();
    if (texture.WrapValue)
      texture.WrapValue->IncRef ();
    break;

  case RENDERBUFFER:
    RenderBuffer = other.RenderBuffer;
    if (RenderBuffer)
      RenderBuffer->IncRef ();
    break;

  case MATRIX3X3:
    MatrixValuePtr = MatrixAlloc()->Alloc (*other.MatrixValuePtr);
    break;

  case MATRIX4X4:
    Matrix4ValuePtr = Matrix4Alloc()->Alloc ();
    break;

  case TRANSFORM:
    TransformPtr = TransformAlloc()->Alloc (*other.TransformPtr);
    break;

  case ARRAY:
    ShaderVarArray = ShaderVarArrayAlloc()->Alloc ();
    *ShaderVarArray = *other.ShaderVarArray;
    break;

  default:
    ;
  }
}
コード例 #6
0
ファイル: registerio.c プロジェクト: guo2004131/freesurfer
/* --------------------------------------------------------------
   regio_read_xfm4() - reads a 4x4 transform as the last four
   lines of the xfmfile. Blank lines at the end will defeat it.
   -------------------------------------------------------------- */
int regio_read_xfm4(char *xfmfile, MATRIX **R)
{
  FILE *fp;
  char tmpstr[1000];
  int r,c,n,nlines;
  float val;

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

  fp = fopen(xfmfile,"r");
  if (fp==NULL)
  {
    perror("regio_read_xfm4");
    fprintf(stderr,"Could read %s\n",xfmfile);
    return(1);
  }

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

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

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

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

  fclose(fp);
  return(0);
}
コード例 #7
0
MATRIX *ComputeAdjMatrix(MRI *mri_label, MRI *mri_mask, int minlabel, int maxlabel)
{
  MATRIX *AdjMatrix;
  int i, j, label1, label2, offset, numLabels;
  int depth, width, height;
  int x,y,z,cx,cy,cz;

  numLabels = maxlabel - minlabel + 1;

  depth = mri_label->depth;
  width = mri_label->width;
  height = mri_label->height;

  AdjMatrix = (MATRIX *)MatrixAlloc(numLabels, numLabels, MATRIX_REAL);

  if (!AdjMatrix)
    ErrorExit(ERROR_BADPARM, "%s: unable to allowcate memory.\n", Progname);
  /* The diagnoal entries of AdjMatrix is set to zero and remain zero */
  for (i=1; i <= numLabels;i++)
    for (j=i; j <= numLabels; j++)
    {
      AdjMatrix->rptr[i][j] = 0.0;
      AdjMatrix->rptr[j][i] = 0.0;
    }


  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++)
      {
        if (MRIvox(mri_mask, x, y, z) == 0) continue;
        label1 = (int) MRIgetVoxVal(mri_label, x, y, z,0);
        if (label1 < minlabel || label1 > maxlabel) continue;

        /* Find all 6-neighbor with different label */
        for (offset = 0; offset < 6; offset++)
        {
          cx = x + xoff[offset];
          cy = y + yoff[offset];
          cz = z + zoff[offset];
          if (cx < 0 || cx >= width || cy < 0 || cy >= height
              || cz < 0 || cz >= depth) continue;

          label2 = (int) MRIgetVoxVal(mri_label, cx, cy, cz,0);
          if (label2 < minlabel || label2 > maxlabel || label2 == label1)
            continue;

          AdjMatrix->rptr[label1-minlabel+1][label2-minlabel+1] = 1.0;
          AdjMatrix->rptr[label2-minlabel+1][label1-minlabel+1] = 1.0;
        } /* for_offset */
      }

  return (AdjMatrix);
}
コード例 #8
0
ファイル: shadervar.cpp プロジェクト: GameLemur/Crystal-Space
csShaderVariable::~csShaderVariable ()
{
  switch (GetTypeI())
  {
  case UNKNOWN:     
  case INT:      
  case FLOAT:
    break; //Nothing to deallocate

  case TEXTURE:
    if (texture.HandValue)
      texture.HandValue->DecRef ();
    if (texture.WrapValue)
      texture.WrapValue->DecRef ();
    break;

  case RENDERBUFFER:
    if (RenderBuffer)
      RenderBuffer->DecRef ();
    break;

  case VECTOR2:
  case VECTOR3:
  case VECTOR4:
    break; //Nothing to deallocate      

  case MATRIX3X3:
    MatrixAlloc()->Free (MatrixValuePtr);
    break;

  case MATRIX4X4:
    Matrix4Alloc()->Free (Matrix4ValuePtr);
    break;

  case TRANSFORM:
    TransformAlloc()->Free (TransformPtr);
    break;

  case ARRAY:
    ShaderVarArrayAlloc()->Free (ShaderVarArray);
    break;

  default:
    ;
  }

  if (accessor != 0)
  {
    AccessorValuesAlloc()->Free (accessor);
  }
}
コード例 #9
0
ファイル: mri_gdfglm.c プロジェクト: guo2004131/freesurfer
/*-----------------------------------------------------*/
DVT *DVTalloc(int nrows, int ncols, char *dvtfile) {
  DVT *dvt;

  dvt = (DVT *)calloc(sizeof(DVT),1);

  if (dvtfile != NULL) {
    dvt->dvtfile = (char *) calloc(sizeof(char),strlen(dvtfile)+1);
    memmove(dvt->dvtfile,dvtfile,strlen(dvtfile));
  }

  dvt->D = MatrixAlloc(nrows,ncols,MATRIX_REAL);
  dvt->RowNames = (char **)calloc(sizeof(char *),nrows);
  dvt->ColNames = (char **)calloc(sizeof(char *),ncols);

  return(dvt);
}
コード例 #10
0
ファイル: test_matrix.cpp プロジェクト: guo2004131/freesurfer
void
MatrixTest::TestMatrixSVDPseudoInverse()
{
    float tolerance = 1e-5;

    std::cout << "\rMatrixTest::TestMatrixSVDPseudoInverse()\n";

    // check the low-level routine first
    MATRIX *Ux = MatrixRead( (char*) ( SVD_U_MATRIX.c_str() ) );
    MATRIX *Vx = MatrixRead( (char*) ( SVD_V_MATRIX.c_str() ) );
    VECTOR *Sx = MatrixRead( (char*) ( SVD_S_VECTOR.c_str() ) );
    CPPUNIT_ASSERT (Ux != NULL);
    CPPUNIT_ASSERT (Vx != NULL);
    CPPUNIT_ASSERT (Sx != NULL);

    MATRIX *U=MatrixCopy(mSquareMatrix,NULL);
    MATRIX *V=MatrixAlloc(U->cols, U->cols, MATRIX_REAL) ;
    VECTOR *S=VectorAlloc(U->cols, MATRIX_REAL) ;
    OpenSvdcmp( U, S, V ) ;
    CPPUNIT_ASSERT (U != NULL);
    CPPUNIT_ASSERT (V != NULL);
    CPPUNIT_ASSERT (S != NULL);
    CPPUNIT_ASSERT ( AreMatricesEqual( U, Ux, tolerance ) );
    CPPUNIT_ASSERT ( AreMatricesEqual( V, Vx, tolerance ) );
    CPPUNIT_ASSERT ( AreMatricesEqual( S, Sx, tolerance ) );

    // now check MatrixSVDPseudoInverse, which uses sc_linalg_SV_decomp

    tolerance = 1e-5;

    MATRIX *actualInverse = MatrixSVDPseudoInverse( mNonSquareMatrix, NULL );
    MATRIX *expectedInverse =
        MatrixRead( (char*) ( NON_SQUARE_MATRIX_PSEUDO_INVERSE.c_str() ) );
    CPPUNIT_ASSERT( AreMatricesEqual( actualInverse, expectedInverse ) );

    actualInverse = MatrixSVDPseudoInverse( mSquareMatrix, NULL );
    expectedInverse =
        MatrixRead( (char*) ( SQUARE_MATRIX_PSEUDO_INVERSE.c_str() ) );
    CPPUNIT_ASSERT
    ( AreMatricesEqual( actualInverse, expectedInverse, tolerance ) );
}
コード例 #11
0
ファイル: matrix.c プロジェクト: 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 */
コード例 #12
0
ファイル: mri_concat.c プロジェクト: guo2004131/freesurfer
MATRIX *GroupedMeanMatrix(int ngroups, int ntotal)
{
  int nper,r,c;
  MATRIX *M;

  nper = ntotal/ngroups;
  if(nper*ngroups != ntotal)
  {
    printf("ERROR: --gmean, Ng must be integer divisor of Ntotal\n");
    return(NULL);
  }

  M = MatrixAlloc(nper,ntotal,MATRIX_REAL);
  for(r=1; r <= nper; r++)
  {
    for(c=r; c <= ntotal; c += nper)
    {
      M->rptr[r][c] = 1.0/ngroups;
    }
  }
  return(M);
}
コード例 #13
0
/*---------------------------------------------------------------*/
int FindClosestLRWPVertexNo(int c, int r, int s,
                            int *lhwvtx, int *lhpvtx,
                            int *rhwvtx, int *rhpvtx,
                            MATRIX *Vox2RAS,
                            MRIS *lhwite,  MRIS *lhpial,
                            MRIS *rhwhite, MRIS *rhpial,
                            MHT *lhwhite_hash, MHT *lhpial_hash,
                            MHT *rhwhite_hash, MHT *rhpial_hash)
{
    static MATRIX *CRS = NULL;
    static MATRIX *RAS = NULL;
    static VERTEX vtx;
    static float dlhw, dlhp, drhw, drhp,dmin;
    int annot, hemi, annotid;

    if (CRS == NULL)
    {
        CRS = MatrixAlloc(4,1,MATRIX_REAL);
        CRS->rptr[4][1] = 1;
        RAS = MatrixAlloc(4,1,MATRIX_REAL);
        RAS->rptr[4][1] = 1;
    }

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

    *lhwvtx = MHTfindClosestVertexNo(lhwhite_hash,lhwhite,&vtx,&dlhw);
    *lhpvtx = MHTfindClosestVertexNo(lhpial_hash, lhpial, &vtx,&dlhp);
    *rhwvtx = MHTfindClosestVertexNo(rhwhite_hash,rhwhite,&vtx,&drhw);
    *rhpvtx = MHTfindClosestVertexNo(rhpial_hash, rhpial, &vtx,&drhp);

    printf("lh white: %d %g\n",*lhwvtx,dlhw);
    printf("lh pial:  %d %g\n",*lhpvtx,dlhp);
    printf("rh white: %d %g\n",*rhwvtx,drhw);
    printf("rh pial:  %d %g\n",*rhpvtx,drhp);

    hemi = 0;
    dmin = -1;
    if (*lhwvtx < 0 && *lhpvtx < 0 && *rhwvtx < 0 && *rhpvtx < 0)
    {
        printf("ERROR2: could not map to any surface.\n");
        printf("crs = %d %d %d, ras = %6.4f %6.4f %6.4f \n",
               c,r,s,vtx.x,vtx.y,vtx.z);
        printf("Using Bruce Force\n");
        *lhwvtx = MRISfindClosestVertex(lhwhite,vtx.x,vtx.y,vtx.z,&dlhw);
        *lhpvtx = MRISfindClosestVertex(lhpial,vtx.x,vtx.y,vtx.z,&dlhp);
        *rhwvtx = MRISfindClosestVertex(rhwhite,vtx.x,vtx.y,vtx.z,&drhw);
        *rhpvtx = MRISfindClosestVertex(rhpial,vtx.x,vtx.y,vtx.z,&drhp);
        printf("lh white: %d %g\n",*lhwvtx,dlhw);
        printf("lh pial:  %d %g\n",*lhpvtx,dlhp);
        printf("rh white: %d %g\n",*rhwvtx,drhw);
        printf("rh pial:  %d %g\n",*rhpvtx,drhp);
        return(1);
    }
    if (dlhw <= dlhp && dlhw < drhw && dlhw < drhp && lhwvtx >= 0)
    {
        annot = lhwhite->vertices[*lhwvtx].annotation;
        hemi = 1;
        if (lhwhite->ct)
        {
            CTABfindAnnotation(lhwhite->ct, annot, &annotid);
        }
        else
        {
            annotid = annotation_to_index(annot);
        }
        dmin = dlhw;
    }
    if (dlhp < dlhw && dlhp < drhw && dlhp < drhp && lhpvtx >= 0)
    {
        annot = lhwhite->vertices[*lhpvtx].annotation;
        hemi = 1;
        if (lhwhite->ct)
        {
            CTABfindAnnotation(lhwhite->ct, annot, &annotid);
        }
        else
        {
            annotid = annotation_to_index(annot);
        }
        dmin = dlhp;
    }

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

    printf("hemi = %d, annotid = %d, dist = %g\n",hemi,annotid,dmin);

    return(0);
}
コード例 #14
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) ;
}
コード例 #15
0
ファイル: registerio.c プロジェクト: guo2004131/freesurfer
/* ----------------------------------------------------------
  Name: regio_read_register()
  Reads a registration file.

  subject -- name of subject as found in the data base
  inplaneres -- in-plane resolution
  betplaneres -- between-plane resolution
  intensity -- for the register program
  R - matrix to convert from xyz in COR space to xyz in Volume space,
      ie, xyzVol = R*xyzCOR
  float2int - if the regfile has a line after the matrix, the string
      is passed to float2int_code(), the result of which is passed
      back as float2int. If there is no extra line, FLT2INT_TKREG
      is returned (indicating that the regfile was created by
      tkregister).
  -------------------------------------------------------------*/
int regio_read_register(char *regfile, char **subject, float *inplaneres,
                        float *betplaneres, float *intensity,  MATRIX **R,
                        int *float2int)
{
  FILE *fp;
  char tmp[1000];
  int r,c,n;
  float val;

  if (!stricmp(FileNameExtension(regfile, tmp), "LTA"))
  {
    LTA *lta ;
    printf("regio_read_register: loading lta\n");
    lta = LTAread(regfile) ;
    if(lta == NULL) return(1) ;
    if(lta->subject[0]==0) strcpy(lta->subject, "subject-unknown"); 
    *subject = (char *) calloc(strlen(lta->subject)+2,sizeof(char));
    strcpy(*subject, lta->subject) ;

    *intensity = lta->fscale ;
    *float2int = FLT2INT_ROUND ;
    *inplaneres  = lta->xforms[0].src.xsize ;
    *betplaneres = lta->xforms[0].src.zsize ;
    *R = TransformLTA2RegDat(lta);
    LTAfree(&lta) ;
    return(0) ;
  }

  fp = fopen(regfile,"r");
  if (fp==NULL)
  {
    perror("regio_read_register()");
    fprintf(stderr,"Could not open %s\n",regfile);
    return(1);
  }

  /* subject name */
  n = fscanf(fp,"%s",tmp);
  if (n != 1)
  {
    perror("regio_read_register()");
    fprintf(stderr,"Error reading subject from %s\n",regfile);
    fclose(fp);
    return(1);
  }
  *subject = (char *) calloc(strlen(tmp)+2,sizeof(char));
  sprintf(*subject,"%s",tmp);

  /* in-plane resolution */
  n = fscanf(fp,"%f",inplaneres);
  if (n != 1)
  {
    perror("regio_read_register()");
    fprintf(stderr,"Error reading inplaneres from %s\n",regfile);
    fclose(fp);
    return(1);
  }

  /* between-plane resolution */
  n = fscanf(fp,"%f",betplaneres);
  if (n != 1)
  {
    perror("regio_read_register()");
    fprintf(stderr,"Error reading betplaneres from %s\n",regfile);
    fclose(fp);
    return(1);
  }

  /* intensity*/
  n = fscanf(fp,"%f",intensity);
  if (n != 1)
  {
    perror("regio_read_register()");
    fprintf(stderr,"Error reading intensity from %s\n",regfile);
    fclose(fp);
    return(1);
  }

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

  /* registration matrix */
  for (r=0;r<4;r++)
  {
    for (c=0;c<4;c++)
    {
      n = fscanf(fp,"%f",&val);
      if (n != 1)
      {
        perror("regio_read_register()");
        fprintf(stderr,"Error reading R[%d][%d] from %s\n",r,c,regfile);
        fclose(fp);
        return(1);
      }
      (*R)->rptr[r+1][c+1] = val;
    }
  }

  /* Get the float2int method string */
  n = fscanf(fp,"%s",&tmp[0]);
  fclose(fp);

  if (n == EOF)
    *float2int = FLT2INT_TKREG;
  else
  {
    *float2int = float2int_code(tmp);
    if ( *float2int == -1 )
    {
      printf("ERROR: regio_read_register(): float2int method %s from file %s,"
             " match not found\n",tmp,regfile);
      return(1);
    }
  }

  return(0);
}
コード例 #16
0
ファイル: mri_fwhm.c プロジェクト: ewong718/freesurfer
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
  int nargs, n, Ntp, nsearch, nsearch2=0;
  double fwhm = 0, nresels, voxelvolume, nvoxperresel, reselvolume;
  double car1mn, rar1mn,sar1mn,cfwhm,rfwhm,sfwhm, ftmp;
  double car2mn, rar2mn,sar2mn;
  double gmean, gstd, gmax;
  FILE *fp;

  sprintf(tmpstr, "S%sER%sRONT%sOR", "URF", "_F", "DO") ;
  setenv(tmpstr,"1",0);

  nargs = handle_version_option (argc, argv, vcid, "$Name:  $");
  if (nargs && argc - nargs == 1) exit (0);
  argc -= nargs;
  cmdline = argv2cmdline(argc,argv);
  uname(&uts);
  getcwd(cwd,2000);

  Progname = argv[0] ;
  argc --;
  argv++;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  if (argc == 0) usage_exit();
  parse_commandline(argc, argv);
  check_options();
  if (checkoptsonly) return(0);

  if (SynthSeed < 0) SynthSeed = PDFtodSeed();
  if (debug) dump_options(stdout);

  // ------------- load or synthesize input ---------------------
  InVals = MRIreadType(inpath,InValsType);
  if(InVals == NULL) exit(1);
  if(SetTR){
    printf("Setting TR to %g ms\n",TR);
    InVals->tr = TR;
  }
  if((nframes < 0 && synth) || !synth) nframes = InVals->nframes;
  if(nframes < nframesmin && !SmoothOnly && !sum2file) {
    printf("ERROR: nframes = %d, need at least %d\n",
	   nframes,nframesmin);
    exit(1);
  }
  if (InVals->type != MRI_FLOAT) {
    mritmp = MRISeqchangeType(InVals, MRI_FLOAT, 0, 0, 0);
    MRIfree(&InVals);
    InVals = mritmp;
  }
  if(synth) {
    printf("Synthesizing %d frames, Seed = %d\n",nframes,SynthSeed);
    mritmp = MRIcloneBySpace(InVals,MRI_FLOAT,nframes);
    MRIfree(&InVals);
    MRIrandn(mritmp->width, mritmp->height, mritmp->depth, 
	     nframes, 0, 1, mritmp);
    InVals = mritmp;
  }
  voxelvolume = InVals->xsize * InVals->ysize * InVals->zsize ;
  printf("voxelvolume %g mm3\n",voxelvolume);

  if(DoSqr){
    printf("Computing square of input\n");
    MRIsquare(InVals,NULL,InVals);
  }

  // -------------------- handle masking ------------------------
  if (maskpath) {
    printf("Loading mask %s\n",maskpath);
    mask = MRIread(maskpath);
    if(mask==NULL) exit(1);
    if(MRIdimMismatch(mask,InVals,0)){
      printf("ERROR: dimension mismatch between mask and input\n");
      exit(1);
    }
    MRIbinarize2(mask, mask, maskthresh, 0, 1);
  }
  if (automask) {
    RFglobalStats(InVals, NULL, &gmean, &gstd, &gmax);
    maskthresh = gmean * automaskthresh;
    printf("Computing mask, relative threshold = %g, gmean = %g, absthresh = %g\n",
           automaskthresh,gmean,maskthresh);
    mritmp = MRIframeMean(InVals,NULL);
    //MRIwrite(mritmp,"fmean.mgh");
    mask = MRIbinarize2(mritmp, NULL, maskthresh, 0, 1);
    MRIfree(&mritmp);
  }
  if (mask) {
    if (maskinv) {
      printf("Inverting mask\n");
      MRImaskInvert(mask,mask);
    }
    nsearch = MRInMask(mask);
    if (nsearch == 0) {
      printf("ERROR: no voxels found in mask\n");
      exit(1);
    }
    // Erode the mask -----------------------------------------------
    if (nerode > 0) {
      printf("Eroding mask %d times\n",nerode);
      for (n=0; n<nerode; n++) MRIerode(mask,mask);
      nsearch2 = MRInMask(mask);
      if (nsearch2 == 0) {
        printf("ERROR: no voxels found in mask after eroding\n");
        exit(1);
      }
      printf("%d voxels in mask after eroding\n",nsearch2);
    }
    //---- Save mask -----
    if (outmaskpath) MRIwrite(mask,outmaskpath);
  } else nsearch = InVals->width * InVals->height * InVals->depth;
  printf("Search region is %d voxels = %lf mm3\n",nsearch,nsearch*voxelvolume);

  if( (infwhm > 0 || infwhmc > 0 || infwhmr > 0 || infwhms > 0) && SmoothOnly) {
    if(SaveUnmasked) mritmp = NULL;
    else             mritmp = mask;
    if(infwhm > 0) {
      printf("Smoothing input by fwhm=%lf, gstd=%lf\n",infwhm,ingstd);
      MRImaskedGaussianSmooth(InVals, mritmp, ingstd, InVals);
    }
    if(infwhmc > 0 || infwhmr > 0 || infwhms > 0) {
      printf("Smoothing input by fwhm=(%lf,%lf,%lf) gstd=(%lf,%lf,%lf)\n",
	     infwhmc,infwhmr,infwhms,ingstdc,ingstdr,ingstds);
      MRIgaussianSmoothNI(InVals, ingstdc, ingstdr, ingstds, InVals);
    }
    printf("Saving to %s\n",outpath);
    MRIwrite(InVals,outpath);
    printf("SmoothOnly requested, so exiting now\n");
    exit(0);
  }

  // Make a copy, if needed, prior to doing anything to data
  if(outpath) InValsCopy = MRIcopy(InVals,NULL);

  // Compute variance reduction factor -------------------
  if(sum2file){
    ftmp = MRIsum2All(InVals);
    fp = fopen(sum2file,"w");
    if(fp == NULL){
      printf("ERROR: opening %s\n",sum2file);
      exit(1);
    }
    printf("sum2all: %20.10lf\n",ftmp);
    printf("vrf: %20.10lf\n",1/ftmp);
    fprintf(fp,"%20.10lf\n",ftmp);
    exit(0);
  }

  //------------------------ Detrend ------------------
  if(DetrendOrder >= 0) {
    Ntp = InVals->nframes;
    printf("Polynomial detrending, order = %d\n",DetrendOrder);
    X = MatrixAlloc(Ntp,DetrendOrder+1,MATRIX_REAL);
    for (n=0;n<Ntp;n++) X->rptr[n+1][1] = 1.0;
    ftmp = Ntp/2.0;
    if (DetrendOrder >= 1)
      for (n=0;n<Ntp;n++) X->rptr[n+1][2] = (n-ftmp)/ftmp;
    if (DetrendOrder >= 2)
      for (n=0;n<Ntp;n++) X->rptr[n+1][3] = pow((n-ftmp),2.0)/(ftmp*ftmp);
  }
  if(X){
    printf("Detrending\n");
    if (X->rows != InVals->nframes) {
      printf("ERROR: dimension mismatch between X and input\n");
      exit(1);
    }
    mritmp = fMRIdetrend(InVals,X);
    if (mritmp == NULL) exit(1);
    MRIfree(&InVals);
    InVals = mritmp;
  }

  // ------------ Smooth Input BY infwhm -------------------------
  if(infwhm > 0) {
    printf("Smoothing input by fwhm=%lf, gstd=%lf\n",infwhm,ingstd);
    MRImaskedGaussianSmooth(InVals, mask, ingstd, InVals);
  }
  // ------------ Smooth Input BY infwhm -------------------------
  if(infwhmc > 0 || infwhmr > 0 || infwhms > 0) {
    printf("Smoothing input by fwhm=(%lf,%lf,%lf) gstd=(%lf,%lf,%lf)\n",
	   infwhmc,infwhmr,infwhms,ingstdc,ingstdr,ingstds);
    MRIgaussianSmoothNI(InVals, ingstdc, ingstdr, ingstds, InVals);
  }

  // ------------ Smooth Input TO fwhm -------------------------
  if (tofwhm > 0) {
    printf("Attempting to smooth to %g +/- %g mm fwhm (nitersmax=%d)\n",
           tofwhm,tofwhmtol,tofwhmnitersmax);
    mritmp = MRImaskedGaussianSmoothTo(InVals, mask, tofwhm,
                                       tofwhmtol, tofwhmnitersmax,
                                       &byfwhm, &tofwhmact, &tofwhmniters,
                                       InVals);
    if (mritmp == NULL) exit(1);
    printf("Smoothed by %g to %g in %d iterations\n",
           byfwhm,tofwhmact,tofwhmniters);
    if (tofwhmfile) {
      fp = fopen(tofwhmfile,"w");
      if (!fp) {
        printf("ERROR: opening %s\n",tofwhmfile);
        exit(1);
      }
      fprintf(fp,"tofwhm    %lf\n",tofwhm);
      fprintf(fp,"tofwhmtol %lf\n",tofwhmtol);
      fprintf(fp,"tofwhmact %lf\n",tofwhmact);
      fprintf(fp,"byfwhm    %lf\n",byfwhm);
      fprintf(fp,"niters    %d\n",tofwhmniters);
      fprintf(fp,"nitersmax %d\n",tofwhmnitersmax);
      fclose(fp);
    }
  }

  // ------ Save smoothed/detrended ------------------------------
  if(outpath) {
    // This is a bit of a hack in order to be able to save undetrended
    // Operates on InValsCopy, which has not been modified (requires
    // smoothing twice, which is silly:).
    printf("Saving to %s\n",outpath);
    // Smoothed output will not be masked
    if (SaveDetrended && X) {
      mritmp = fMRIdetrend(InValsCopy,X);
      if (mritmp == NULL) exit(1);
      MRIfree(&InValsCopy);
      InValsCopy = mritmp;
    }
    if (SaveUnmasked) mritmp = NULL;
    else             mritmp = mask;
    if(infwhm > 0)
      MRImaskedGaussianSmooth(InValsCopy, mritmp, ingstd, InValsCopy);
    if(infwhmc > 0 || infwhmr > 0 || infwhms > 0) 
      MRIgaussianSmoothNI(InValsCopy, ingstdc, ingstdr, ingstds, InValsCopy);
    if(tofwhm > 0) {
      bygstd = byfwhm/sqrt(log(256.0));
      MRImaskedGaussianSmooth(InValsCopy, mritmp, bygstd, InValsCopy);
    }
    MRIwrite(InValsCopy,outpath);
    MRIfree(&InValsCopy);
  }


  // ----------- Compute smoothness -----------------------------
  printf("Computing spatial AR1 in volume.\n");
  ar1 = fMRIspatialAR1(InVals, mask, NULL);
  if (ar1 == NULL) exit(1);
  fMRIspatialAR1Mean(ar1, mask, &car1mn, &rar1mn, &sar1mn);

  cfwhm = RFar1ToFWHM(car1mn, InVals->xsize);
  rfwhm = RFar1ToFWHM(rar1mn, InVals->ysize);
  sfwhm = RFar1ToFWHM(sar1mn, InVals->zsize);
  fwhm = sqrt((cfwhm*cfwhm + rfwhm*rfwhm + sfwhm*sfwhm)/3.0);
  printf("ar1mn = (%lf,%lf,%lf)\n",car1mn,rar1mn,sar1mn);
  printf("colfwhm   = %lf\n",cfwhm);
  printf("rowfwhm   = %lf\n",rfwhm);
  printf("slicefwhm = %lf\n",sfwhm);
  printf("outfwhm = %lf\n",fwhm);

  reselvolume = cfwhm*rfwhm*sfwhm;
  nvoxperresel = reselvolume/voxelvolume;
  nresels = voxelvolume*nsearch/reselvolume;
  printf("reselvolume %lf\n",reselvolume);
  printf("nresels %lf\n",nresels);
  printf("nvoxperresel %lf\n",nvoxperresel);

  if(DoAR2){
    printf("Computing spatial AR2 in volume.\n");
    fMRIspatialAR2Mean(InVals, mask, &car2mn, &rar2mn, &sar2mn);
    printf("ar2mn = (%lf,%lf,%lf)\n",car2mn,rar2mn,sar2mn);
  }

  if(ar1path) MRIwrite(ar1,ar1path);

  fflush(stdout);

  // ---------- Save summary file ---------------------
  if(sumfile) {
    fp = fopen(sumfile,"w");
    if (fp == NULL) {
      printf("ERROR: opening %s\n",sumfile);
      exit(1);
    }
    dump_options(fp);
    fprintf(fp,"nsearch2        %d\n",nsearch2);
    fprintf(fp,"searchspace_vox %d\n",nsearch);
    fprintf(fp,"searchspace_mm3 %lf\n",nsearch*voxelvolume);
    fprintf(fp,"voxelvolume_mm3 %g\n",voxelvolume);
    fprintf(fp,"voxelsize_mm %g %g %g\n",InVals->xsize,InVals->ysize,InVals->zsize);
    fprintf(fp,"ar1mn  %lf %lf %lf\n",car1mn,rar1mn,sar1mn);
    fprintf(fp,"colfwhm_mm      %lf\n",cfwhm);
    fprintf(fp,"rowfwhm_mm      %lf\n",rfwhm);
    fprintf(fp,"slicefwhm_mm    %lf\n",sfwhm);
    fprintf(fp,"outfwhm_mm      %lf\n",fwhm);
    fprintf(fp,"reselvolume_mm3 %lf\n",reselvolume);
    fprintf(fp,"nresels         %lf\n",nresels);
    fprintf(fp,"nvox_per_resel  %lf\n",nvoxperresel);
    fclose(fp);
  }

  if(datfile) {
    fp = fopen(datfile,"w");
    if(fp == NULL) {
      printf("ERROR: opening %s\n",datfile);
      exit(1);
    }
    fprintf(fp,"%lf\n",fwhm);
    fclose(fp);
  }


  printf("mri_fwhm done\n");

  return 0;
}
コード例 #17
0
ファイル: shadervar.cpp プロジェクト: GameLemur/Crystal-Space
void csShaderVariable::NewType (VariableType nt)
{
  if (GetTypeI() == nt)
    return;

  switch (GetTypeI())
  {
  case UNKNOWN:
  case INT:
  case FLOAT:
    break; //Nothing to deallocate

  case TEXTURE:
    if (texture.HandValue)
      texture.HandValue->DecRef ();
    if (texture.WrapValue)
      texture.WrapValue->DecRef ();
    break;
  
  case RENDERBUFFER:
    if (RenderBuffer)
      RenderBuffer->DecRef ();
    break;

  case VECTOR2:      
  case VECTOR3:      
  case VECTOR4:
    break; //Nothing to deallocate      
  
  case MATRIX3X3:
    MatrixAlloc()->Free (MatrixValuePtr);
    break;
  
  case MATRIX4X4:
    Matrix4Alloc()->Free (Matrix4ValuePtr);
    break;
  
  case TRANSFORM:
    TransformAlloc()->Free (TransformPtr);
    break;

  case ARRAY:
    ShaderVarArrayAlloc()->Free (ShaderVarArray);
    break;

  default:
    ;
  }

  switch (nt)
  {
  case INT:      
  case TEXTURE:
  case RENDERBUFFER:
  case UNKNOWN:     
  case FLOAT:
  case VECTOR2:      
  case VECTOR3:      
  case VECTOR4:
    break; //Nothing to allocate      

  case MATRIX3X3:
    MatrixValuePtr = MatrixAlloc()->Alloc ();
    break;

  case MATRIX4X4:
    Matrix4ValuePtr = Matrix4Alloc()->Alloc ();
    break;

  case TRANSFORM:
    TransformPtr = TransformAlloc()->Alloc ();
    break;

  case ARRAY:
    ShaderVarArray = ShaderVarArrayAlloc()->Alloc ();
    break;

  default:
    ;
  }
  
  nameAndType &= nameMask;
  nameAndType |= nt << typeShift;
}
コード例 #18
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) ;
}
コード例 #19
0
ファイル: inverse.c プロジェクト: ewong718/freesurfer
IOP *
IOPRead(char *fname, int hemi)
{
  IOP   *iop ;
  int   i,j,k,jc,d, dipoles_in_decimation ;
  FILE  *fp;
  char  c,str[STRLEN];
  float f;
  int   z ;

  printf("read_iop(%s,%d)\n",fname,hemi);

  fp = fopen(fname,"r");
  if (fp==NULL)
    ErrorReturn(NULL,
                (ERROR_NOFILE, "IOPRead: can't open file %s\n",fname));
  iop = calloc(1, sizeof(IOP)) ;
  if (!iop)
    ErrorReturn(NULL,
                (ERROR_NOMEMORY, "IOPRead: can't allocate struct\n"));
  iop->pthresh = 1000;
  c = getc(fp);
  if (c=='#')
  {
    fscanf(fp,"%s",str);
    if (!strcmp(str,"version"))
      fscanf(fp,"%d",&iop->version);
    printf("iop version = %d\n",iop->version);
    fscanf(fp,"%d %d %d %d",
           &iop->neeg_channels,
           &iop->nmeg_channels,
           &iop->ndipoles_per_location,
           &iop->ndipole_files);

    iop->nchan = iop->neeg_channels+iop->nmeg_channels;
    for (i=1;i<=hemi;i++)
    {
      fscanf(fp,"%d %d",&dipoles_in_decimation,&iop->ndipoles);
      if (i==hemi)
      {
#if 0
        if (iop->ndipoles_per_location != sol_ndec)
        {
          fclose(fp);
          IOPFree(&iop) ;
          ErrorReturn(NULL,
                      (ERROR_BADFILE,
                       "IOPRead: .dec and .iop file mismatch (%d!=%d)\n",
                       sol_ndec,iop->ndipoles_per_location));
        }
#endif
        iop->m_iop =
          MatrixAlloc(iop->ndipoles*iop->ndipoles_per_location,iop->nchan,
                      MATRIX_REAL);
        if (iop->version==1)
          iop->m_forward =
            MatrixAlloc(iop->nchan,iop->ndipoles*iop->ndipoles_per_location,
                        MATRIX_REAL);

#if 0
        sol_M = matrix(iop->nchan,iop->nchan); /* temporary space for xtalk */
        sol_Mi = matrix(iop->nchan,iop->nchan);
        sol_sensvec1 = vector(iop->nchan);
        sol_sensvec2 = vector(iop->nchan);
        sol_sensval = vector(iop->nchan);
#endif

        iop->dipole_normalization = calloc(iop->ndipoles, sizeof(float));
        iop->dipole_vertices = calloc(iop->ndipoles, sizeof(int));
        if (!iop->dipole_vertices)
          ErrorReturn(NULL,
                      (ERROR_NOMEMORY,
                       "IOPRead: could not allocated %d v indices",
                       iop->ndipoles)) ;
        iop->pvals = VectorAlloc(iop->ndipoles, MATRIX_REAL);
        iop->spatial_priors = VectorAlloc(iop->ndipoles, MATRIX_REAL);


        iop->bad_sensors = calloc(iop->nchan, sizeof(int));
        if (!iop->bad_sensors)
          ErrorReturn(NULL,
                      (ERROR_NOMEMORY,
                       "IOPRead: could not allocate bad sensor array",
                       iop->nchan)) ;

        /* initialize bad sensor locations*/
        for (z=0;z<iop->nchan;z++)
          iop->bad_sensors[z] = 0;

      }
      for (j=0;j<iop->ndipoles;j++)
      {
        if (i==hemi)
        {
          fscanf(fp,"%d",&d);
          iop->dipole_vertices[j] = d;
        }
        else
          fscanf(fp,"%*d");
      }
      for (j=0;j<iop->ndipoles;j++)
      {
        if (i==hemi)
        {
          fscanf(fp,"%f",&f);
          *MATRIX_RELT(iop->pvals,j+1,1) = f;
          f = fabs(f);
          if (f<iop->pthresh)
            iop->pthresh = f;
        }
        else
          fscanf(fp,"%*f");
      }
      for (j=0;j<iop->ndipoles;j++)
      {
        if (i==hemi)
        {
          fscanf(fp,"%f",&f);
          *MATRIX_RELT(iop->spatial_priors,j+1,1) = f;
#if 0
          vertex[iop->dipole_vertices[j]].val = f;
#endif
        }
        else
          fscanf(fp,"%*f");
      }
      for (j=0;j<iop->ndipoles;j++)
      {
        for (jc=0;jc<iop->ndipoles_per_location;jc++)
        {
          for (k=0;k<iop->nchan;k++)
          {
            if (i==hemi)
            {
              fscanf(fp,"%f",&f);
              *MATRIX_RELT(iop->m_iop, j*iop->ndipoles_per_location+jc+1,k+1)
              = f;
            }
            else
              fscanf(fp,"%*f");
          }
        }
      }
      if (iop->version==1)
      {
        for (j=0;j<iop->ndipoles;j++)
        {
          for (jc=0;jc<iop->ndipoles_per_location;jc++)
          {
            for (k=0;k<iop->nchan;k++)
            {
              if (i==hemi)
              {
                fscanf(fp,"%f",&f);
                *MATRIX_RELT(iop->m_forward,
                             k+1,
                             j*iop->ndipoles_per_location+jc+1) = f;
              }
              else
                fscanf(fp,"%*f");
            }
          }
        }
      }
    }
  }
  else
  {
    printf("Can't read binary .iop files\n");
  }
  fclose(fp);
  printf("neeg_channels=%d, nmeg_channels=%d, iop->ndipoles_per_location=%d, "
         "iop->ndipole_files=%d\n",
         iop->neeg_channels, iop->nmeg_channels,iop->ndipoles_per_location,
         iop->ndipole_files);
  return(iop) ;
}
コード例 #20
0
ファイル: registerio.c プロジェクト: guo2004131/freesurfer
/* --------------------------------------------------------------
   regio_read_mincxfm() - reads a 3x4 transform as the last three
   lines of the xfmfile. Blank lines at the end will defeat it.
   If fileinfo != NULL, reads in the "fileinfo". This is the 3rd
   line in the minc xfm file. It will contain information about
   the center of the transform (-center). This is used by
   ltaMNIreadEx() to account for the non-zero center of the MNI
   talairach template. If the center infomation is not there,
   ltaMNIreadEx() assumes that the center is 0 and will produce
   the wrong transform. Thus, if one is going to write out the
   xfm, then one needs to keep track of this information when
   reading it in. regio_write_mincxfm() takes fileinfo as an
   argument. If one is not going to write out the xfm, then
   simply set fileinfo to NULL.
   -------------------------------------------------------------- */
int regio_read_mincxfm(char *xfmfile, MATRIX **R, char **fileinfo)
{
  FILE *fp;
  char tmpstr[1000];
  int r,c,n,nlines;
  float val;

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

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

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

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

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

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

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

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

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

  fclose(fp);
  return(0);
}
コード例 #21
0
ファイル: rec.c プロジェクト: ewong718/freesurfer
REC *
RecRead(char *fname, int iop_neeg, int iop_nmeg)
{
  int   i,j,tnchan;
  float f;
  FILE  *fp;
  REC   *rec ;

  printf("read_rec(%s)\n",fname);


  fp = fopen(fname,"r");
  if (fp==NULL)
    ErrorReturn(NULL,
                (ERROR_BADFILE, "RecRead: could not open file %s",fname)) ;

  rec = (REC *)calloc(1, sizeof(REC)) ;
  if (rec==NULL)
    ErrorExit(ERROR_NOMEMORY, "RecRead: couldn't allocate rec struct") ;

  fscanf(fp,"%*s");
  fscanf(fp,"%d %d %d",&rec->ntimepts,&rec->nmeg_channels,&rec->neeg_channels);
  tnchan = rec->nmeg_channels+rec->neeg_channels ;
  rec->ptime = (int)(2*pow(2.0,ceil(log((float)rec->ntimepts)/log(2.0))));
  printf("ntimepts=%d, ptime=%d\n",rec->ntimepts, rec->ptime);
#if 0
  if (sol_ntime>0 && sol_ntime!=rec->ntimepts)
  {
    printf("ntime does not match rec->ntimepts (%d != %d)\n",sol_ntime,rec->ntimepts);
    exit(0);
  }

  sol_ntime = rec->ntimepts;
  sol_ptime = tptime;

  if (rec->nmeg_channels>0 && rec->nmeg_channels!=tnmeg)
  {
    printf("nmeg does not match tnmeg (%d != %d)\n",rec->nmeg_channels,tnmeg);
    exit(0);
  }
  if (sol_neeg>0 && sol_neeg!=tneeg)
  {
    printf("neeg does not match tnmeg (%d != %d)\n",sol_neeg,tneeg);
    exit(0);
  }
#endif

  rec->latencies = (float *)calloc(rec->ptime, sizeof(float));
  if (!rec->latencies)
    ErrorExit(ERROR_NOMEMORY, "RecRead(%s): could not allocate latency vector",
              fname) ;
  rec->m_data = MatrixAlloc(tnchan,rec->ptime, MATRIX_REAL);
  for (j=0;j<rec->ntimepts;j++)
  {
    fscanf(fp,"%f",&f);
    rec->latencies[j] = f;
    for (i=0;i<rec->neeg_channels;i++)
    {
      fscanf(fp,"%f",&f);
      if (iop_neeg > 0)
        *MATRIX_RELT(rec->m_data,i+1,j+1) = f;
    }
    for (i=0;i<rec->nmeg_channels;i++)
    {
      fscanf(fp,"%f",&f);
      if (iop_nmeg > 0)
        *MATRIX_RELT(rec->m_data,i+iop_neeg+1,j+1) = f;
    }
  }
  fclose(fp);
  printf("rec file read, sample period %2.4f, starting latency %2.4f\n",
         rec->latencies[1]-rec->latencies[0], rec->latencies[0]);

#if 0
  sol_dipcmp_val[sol_nrec] = matrix(sol_nnz*sol_nperdip,sol_ntime);
#endif
  return(rec) ;
}
コード例 #22
0
ファイル: surfcluster.c プロジェクト: ewong718/freesurfer
/*----------------------------------------------------------------
  SurfClusterSummaryFast() - gives identical results as
    SurfClusterSummary() but much, much faster.
  ----------------------------------------------------------------*/
SCS *SurfClusterSummaryFast(MRI_SURFACE *Surf, MATRIX *T, int *nClusters)
{
  int n,vtx,clusterno;
  SURFCLUSTERSUM *scs;
  MATRIX *xyz, *xyzxfm;
  float vtxarea, vtxval;
  struct timeb  mytimer;
  int msecTime;
  double *weightvtx, *weightarea; // to be consistent with orig code
  VERTEX *v;

  if(Gdiag_no > 0) printf("SurfClusterSummaryFast()\n");

  TimerStart(&mytimer) ;

  *nClusters = sclustCountClusters(Surf);
  if(*nClusters == 0) return(NULL);

  xyz    = MatrixAlloc(4,1,MATRIX_REAL);
  xyz->rptr[4][1] = 1;
  xyzxfm = MatrixAlloc(4,1,MATRIX_REAL);

  scs = (SCS *) calloc(*nClusters, sizeof(SCS));
  weightvtx  = (double *) calloc(*nClusters, sizeof(double));
  weightarea = (double *) calloc(*nClusters, sizeof(double));

  for(vtx=0; vtx < Surf->nvertices; vtx++){
    v = &(Surf->vertices[vtx]);
    clusterno = v->undefval;
    if(clusterno == 0) continue;

    n = clusterno-1;
    scs[n].nmembers ++;
    vtxval = v->val;

    // Initialize
    if(scs[n].nmembers == 1){
      scs[n].maxval     = vtxval;
      scs[n].vtxmaxval  = vtx;
      weightvtx[n]  = 0.0;
      weightarea[n] = 0.0;
      scs[n].cx = 0.0;
      scs[n].cy = 0.0;
      scs[n].cz = 0.0;
    }

    if(! Surf->group_avg_vtxarea_loaded) vtxarea = v->area;
    else                                 vtxarea = v->group_avg_area;
    scs[n].area += vtxarea;
    
    if(fabs(vtxval) > fabs(scs[n].maxval)){
      scs[n].maxval = vtxval;
      scs[n].vtxmaxval = vtx;
    }
    weightvtx[n]  += vtxval;
    weightarea[n] += (vtxval*vtxarea);
    scs[n].cx += v->x;
    scs[n].cy += v->y;
    scs[n].cz += v->z;
  } // end loop over vertices

  for (n = 0; n < *nClusters ; n++){
    scs[n].clusterno = n+1;
    scs[n].x = Surf->vertices[scs[n].vtxmaxval].x;
    scs[n].y = Surf->vertices[scs[n].vtxmaxval].y;
    scs[n].z = Surf->vertices[scs[n].vtxmaxval].z;
    scs[n].weightvtx  = weightvtx[n];  
    scs[n].weightarea = weightarea[n];  
    scs[n].cx /= scs[n].nmembers;
    scs[n].cy /= scs[n].nmembers;
    scs[n].cz /= scs[n].nmembers;
    if (T != NULL){
      xyz->rptr[1][1] = scs[n].x;
      xyz->rptr[2][1] = scs[n].y;
      xyz->rptr[3][1] = scs[n].z;
      MatrixMultiply(T,xyz,xyzxfm);
      scs[n].xxfm = xyzxfm->rptr[1][1];
      scs[n].yxfm = xyzxfm->rptr[2][1];
      scs[n].zxfm = xyzxfm->rptr[3][1];

      xyz->rptr[1][1] = scs[n].cx;
      xyz->rptr[2][1] = scs[n].cy;
      xyz->rptr[3][1] = scs[n].cz;
      MatrixMultiply(T,xyz,xyzxfm);
      scs[n].cxxfm = xyzxfm->rptr[1][1];
      scs[n].cyxfm = xyzxfm->rptr[2][1];
      scs[n].czxfm = xyzxfm->rptr[3][1];
    }
  }

  MatrixFree(&xyz);
  MatrixFree(&xyzxfm);
  free(weightvtx);
  free(weightarea);
  msecTime = TimerStop(&mytimer) ;
  if(Gdiag_no > 0) printf("SurfClusterSumFast: n=%d, t = %g\n",*nClusters,msecTime/1000.0);

  return(scs);
}
コード例 #23
0
/*--------------------------------------------------*/
int main(int argc, char **argv)
{
    int nargs, err, asegid, c, r, s, nctx, annot,vtxno,nripped;
    int annotid, IsCortex=0, IsWM=0, IsHypo=0, hemi=0, segval=0;
    int RibbonVal=0,nbrute=0;
    float dmin=0.0, lhRibbonVal=0, rhRibbonVal=0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


    return(0);
}
コード例 #24
0
ファイル: evschutils.c プロジェクト: guo2004131/freesurfer
/*--------------------------------------------------------------------
  EVSdesignMtxStats() - computes statistics about design relevant for
  optimization. stats should have at least 6 elements. Returns 1 is
  the design is singular, 0 otherwise.  ERROR: This needs to be
  modified to compute the VRF differently when there are different
  numbers of stimuli in each event type.x
  -------------------------------------------------------------------*/
int EVSdesignMtxStats(MATRIX *Xtask, MATRIX *Xnuis, EVSCH *EvSch, MATRIX *C, MATRIX *W)
{
  MATRIX *X=NULL, *Xt=NULL, *XtX=NULL;
  MATRIX *iXtX=NULL, *VRF=NULL, *Ct=NULL, *CiXtX=NULL, *CiXtXCt=NULL;
  int r,m,nTaskAvgs,nNuisAvgs,nAvgs,Cfree,J;
  float diagsum;
  double dtmp, dtmp1, dtmp2;

  X = MatrixHorCat(Xtask,Xnuis,NULL);
  nTaskAvgs = Xtask->cols;
  if (Xnuis != NULL) nNuisAvgs = Xnuis->cols;
  else              nNuisAvgs = 0;
  nAvgs     = X->cols;

  if (W != NULL) X = MatrixMultiply(W,X,NULL);

  Xt = MatrixTranspose(X,Xt);
  XtX = MatrixMultiply(Xt,X,XtX);

  /* Compute the Inverse */
  iXtX = MatrixInverse(XtX,NULL);

  Cfree = 0;
  if (C==NULL)
  {
    C = MatrixZero(nTaskAvgs,nAvgs,NULL);
    for (m=0; m < nTaskAvgs; m++) C->rptr[m+1][m+1] = 1;
    Cfree = 1;
  }
  J = C->rows;
  Ct = MatrixTranspose(C,NULL);

  /* Make sure that it was actually inverted */
  if (iXtX != NULL)
  {
    r = 0;

    CiXtX   = MatrixMultiply(C,iXtX,NULL);
    CiXtXCt = MatrixMultiply(CiXtX,Ct,NULL);

    VRF = MatrixAlloc(J,1,MATRIX_REAL);

    diagsum = 0.0;
    for (m=0; m < J; m++)
    {/* exctract diag */
      diagsum += CiXtXCt->rptr[m+1][m+1];
      VRF->rptr[m+1][1] = 1.0/(CiXtXCt->rptr[m+1][m+1]);
    }
    EvSch->eff = 1.0/diagsum;
    if (J>1) EvSch->vrfstd = VectorStdDev(VRF,&dtmp);
    else    EvSch->vrfstd = 0.0;
    EvSch->vrfavg = dtmp;
    EvSch->vrfrange = VectorRange(VRF,&dtmp1,&dtmp2);
    EvSch->vrfmin = dtmp1;
    EvSch->vrfmax = dtmp2;

    MatrixFree(&iXtX);
    MatrixFree(&CiXtX);
    MatrixFree(&CiXtXCt);
    MatrixFree(&VRF);
  }
  else r = 1;

  MatrixFree(&X);
  MatrixFree(&Xt);
  MatrixFree(&XtX);
  if (Cfree) MatrixFree(&C);
  MatrixFree(&Ct);

  return(r);
}
コード例 #25
0
ファイル: evschutils.c プロジェクト: guo2004131/freesurfer
/*-------------------------------------------------------------
  EVSfirXtXIdeal() - computes the ideal XtX matrix for the FIR
  signal model. The XtX matrix can be broken down into nEvTypes-
  by-nEvTypes blocks, each nPSD-by-nPSD. The value at the nth row
  and mth col within the block at i,j within the block matrix
  represents the number of times one would expect to see Event
  Type i followed (n-m) dPSDs by Event Type j. If m > n, then
  j actually preceeds i.

  The block at row=i and col=j within the block matrix represents
  EVT j (col) being followed by EVT i (row).

  Within block i,j, the nth col corresponds to condition j being
  shifted by n, and the mth row corresponds to condition i being
  shifted by m, with respect to the start of the scan. In other
  words, element m,n represents condition i appearing (n-m) dPSDs
  after condition j.

  For example, for two conditions in block i=2,j=1, the number at the
  first row (m=1) and third column (n=3) represents the expected
  number of times that EVT1 (j=1) should be followed by EVT2 (i=2) by
  3-1=2 dPSDs.
  -------------------------------------------------------------*/
MATRIX *EVSfirXtXIdeal(int nEvTypes, int *nEvReps, float *EvDur,
                       float TR, int Ntp,
                       float PSDMin, float PSDMax, float dPSD)
{
  MATRIX *XtX=NULL;
  int Npsd, Navgs, npsd1, npsd2, nevt1, nevt2;
  int n, nslots, nshift;
  int r,c;
  int *EvDur_dPSD;
  float vx;

  Npsd = (int)(rint((PSDMax-PSDMin)/dPSD));
  Navgs = nEvTypes * Npsd;

  EvDur_dPSD = (int *) calloc(sizeof(int),nEvTypes);
  for (n=0;n<nEvTypes;n++) EvDur_dPSD[n] = (int)(rint(EvDur[n]/dPSD));

  nslots = (int)(rint(TR*Ntp/dPSD));

  XtX = MatrixAlloc(Navgs,Navgs,MATRIX_REAL);

  /* Loop through the Event Type Block matrix */
  for (nevt1 = 0; nevt1 < nEvTypes; nevt1++)
  {   /* block rows (j)*/
    for (nevt2 = 0; nevt2 < nEvTypes; nevt2++)
    { /* block cols (i)*/

      for (npsd1=0; npsd1 < Npsd; npsd1++)
      {   /* rows (m)*/
        for (npsd2=0; npsd2 < Npsd; npsd2++)
        { /* cols (n)*/

          /* nshift is the number of dPSDs that EVT1 follows EVT2*/
          nshift = npsd2-npsd1; /* n-m */
          r = nevt1*Npsd + npsd1 + 1;
          c = nevt2*Npsd + npsd2 + 1;

          if (nevt1==nevt2)
          {
            /* diagonal block */
            if (nshift==0) vx = nEvReps[nevt1];
            else if (abs(nshift) < EvDur_dPSD[nevt1])  vx = 0.0;
            else vx = nEvReps[nevt1]*nEvReps[nevt1]/nslots;
          }
          else
          {
            /* off-diagonal block */
            if (nshift == 0 ||
                (nshift > 0 && nshift < EvDur_dPSD[nevt2]) ||
                (nshift < 0 && -nshift < EvDur_dPSD[nevt1])) vx = 0.0;
            else vx = (float)nEvReps[nevt1]*nEvReps[nevt2]/nslots;
          }
          XtX->rptr[r][c] = vx;
        }
      }

    }
  }

  free(EvDur_dPSD);
  return(XtX);
}
コード例 #26
0
ファイル: evschutils.c プロジェクト: guo2004131/freesurfer
/*-------------------------------------------------------------
  EVS2FIRmtx() - convert an event schedule for a given event id into
  an FIR design matrix.
  -------------------------------------------------------------*/
MATRIX *EVS2FIRmtx(int EvId, EVSCH *EvSch, float tDelay, float TR,
                   int Ntps, float PSDMin, float PSDMax, float dPSD,
                   MATRIX *X)
{
  float tMax, tmp, PSDWindow, tPSD, PSD;
  int RSR, Npsds, nthPSD, n, rA, rB;

  /* Compute number of PSDs in the window */
  PSDWindow = PSDMax-PSDMin;
  tmp = rint(PSDWindow/dPSD) - PSDWindow/dPSD;
  if (tmp > .0001)
  {
    printf("ERROR: EVS2FIRmtx: PSDWindow (%g) is not an integer multiple of dPSD (%g)\n",
           PSDWindow,dPSD);
    return(NULL);
  }
  Npsds = rint(PSDWindow/dPSD);

  /* Compute resampling rate */
  tmp = rint(TR/dPSD) - TR/dPSD;
  if (tmp > .0001)
  {
    printf("ERROR: EVS2FIRmtx: TR (%g) is not an integer multiple "
           " of dPSD (%g)\n", TR, dPSD);
    return(NULL);
  }
  RSR = rint(TR/dPSD);

  /* Compute the time of the last row in X */
  tMax = TR*(Ntps-1);

  /* Create X with all zeros */
  if (X==NULL)  X = MatrixAlloc(Ntps,Npsds,MATRIX_REAL);
  else
  {
    if (X->rows != Ntps || X->rows != Npsds)
    {
      printf("ERROR: EVS2FIRmtx: dimensions of X mismatch\n");
      return(NULL);
    }
    X = MatrixZero(Ntps,Npsds,X);
  }

  /* Fill-in the non-zero entries of X for each event */
  /* nthPSD will be the column in X */
  for (nthPSD = 0; nthPSD < Npsds; nthPSD++)
  {
    PSD = nthPSD*dPSD + PSDMin;

    for (n = 0; n < EvSch->nevents; n++)
    {

      if (EvSch->eventid[n] != EvId) continue;

      tPSD = EvSch->tevent[n] + tDelay + PSD;
      if (tPSD < 0.0)  continue;
      if (tPSD > tMax) break;

      /* Could compute the time of the closest row, then skip if
      fabs(tRow-tPSD) > dPSD/2 ????? This would be easily
         extended to the cases where the data were not aquired
      uniformly in time. */

      /* rA would be the row of X if the rows of X were separated by dPSD */
      rA = (int)rint(tPSD/dPSD);

      /* If rA does not fall into a row of X, skip */
      if ( (rA % RSR) != 0) continue;

      /* rB is the row of X */
      rB = rA/RSR;
      if (EvSch->weight != NULL) X->rptr[rB+1][nthPSD+1] = EvSch->weight[n];
      else                      X->rptr[rB+1][nthPSD+1] = 1;

    }
  }

  return(X);
}
コード例 #27
0
static MATRIX *
align_pca(MRI *mri_in, MRI *mri_ref) {
  int    row, col, i ;
  float  dot ;
  MATRIX *m_ref_evectors = NULL, *m_in_evectors = NULL ;
  float  in_evalues[3], ref_evalues[3] ;
  double  ref_means[3], in_means[3] ;
#if 0
  MRI     *mri_in_windowed, *mri_ref_windowed ;

  mri_in_windowed = MRIwindow(mri_in, NULL, WINDOW_HANNING,127,127,127,100.0f);
  mri_ref_windowed = MRIwindow(mri_ref,NULL,WINDOW_HANNING,127,127,127,100.0f);
  if (Gdiag & DIAG_WRITE) {
    MRIwriteImageViews(mri_in_windowed, "in_windowed", 400) ;
    MRIwriteImageViews(mri_ref_windowed, "ref_windowed", 400) ;
  }
#endif

  if (!m_ref_evectors)
    m_ref_evectors = MatrixAlloc(3,3,MATRIX_REAL) ;
  if (!m_in_evectors)
    m_in_evectors = MatrixAlloc(3,3,MATRIX_REAL) ;

  MRIprincipleComponents(mri_ref, m_ref_evectors, ref_evalues,
                         ref_means, thresh_low);
  MRIprincipleComponents(mri_in,m_in_evectors,in_evalues,in_means,thresh_low);

  /* check to make sure eigenvectors aren't reversed */
  for (col = 1 ; col <= 3 ; col++) {
#if 0
    float theta ;
#endif

    for (dot = 0.0f, row = 1 ; row <= 3 ; row++)
      dot += m_in_evectors->rptr[row][col] * m_ref_evectors->rptr[row][col] ;

    if (dot < 0.0f) {
      printf("WARNING: mirror image detected in eigenvector #%d\n",
             col) ;
      dot *= -1.0f ;
      for (row = 1 ; row <= 3 ; row++)
        m_in_evectors->rptr[row][col] *= -1.0f ;
    }
#if 0
    theta = acos(dot) ;
    printf("angle[%d] = %2.1f\n", col, DEGREES(theta)) ;
#endif
  }
  printf("ref_evectors = \n") ;
  for (i = 1 ; i <= 3 ; i++)
    printf("\t\t%2.2f    %2.2f    %2.2f\n",
           m_ref_evectors->rptr[i][1],
           m_ref_evectors->rptr[i][2],
           m_ref_evectors->rptr[i][3]) ;

  printf("\nin_evectors = \n") ;
  for (i = 1 ; i <= 3 ; i++)
    printf("\t\t%2.2f    %2.2f    %2.2f\n",
           m_in_evectors->rptr[i][1],
           m_in_evectors->rptr[i][2],
           m_in_evectors->rptr[i][3]) ;

  return(pca_matrix(m_in_evectors, in_means,m_ref_evectors, ref_means)) ;
}
コード例 #28
0
ファイル: mri_ms_LDA.c プロジェクト: ewong718/freesurfer
void computeLDAweights(float *weights, MRI **mri_flash, MRI *mri_label, MRI *mri_mask, float *LDAmean1, float *LDAmean2, int nvolumes_total, int classID1, int classID2) {
  /* To make it consistent with later CNR computation */

  int m1, m2, x, y, z, depth, height, width;
  double denom, denom1, denom2, sumw;
  float data1, data2;
  int label;
  double Mdistance;

  MATRIX *InvSW, *SW1, *SW2;

  depth = mri_flash[0]->depth;
  width = mri_flash[0]->width;
  height = mri_flash[0]->height;

  SW1 = (MATRIX *)MatrixAlloc(nvolumes_total, nvolumes_total, MATRIX_REAL);
  SW2 = (MATRIX *)MatrixAlloc(nvolumes_total, nvolumes_total, MATRIX_REAL);

  for (m1=1; m1 <= nvolumes_total; m1++) {
    for (m2=m1; m2 <= nvolumes_total; m2++) {
      SW1->rptr[m1][m2] = 0.0; /* index starts from 1 for matrix */
      SW2->rptr[m1][m2] = 0.0; /* index starts from 1 for matrix */
    }
  }

  /* printf("SW matrix initialized \n"); */
  denom1 = 0.0;
  denom2 = 0.0;
  for (z=0; z < depth; z++)
    for (y=0; y< height; y++)
      for (x=0; x < width; x++) {
        if (MRIvox(mri_mask, x, y, z) == 0) continue;

        label = (int) MRIgetVoxVal(mri_label, x, y, z,0);

        if (label != classID1 &&
            label != classID2)
          continue;

        if (label == classID1) {
          denom1 += 1.0;
          for (m1=0; m1 < nvolumes_total; m1++) {
            data1 = MRIFvox(mri_flash[m1], x, y, z) - LDAmean1[m1];
            for (m2=m1; m2 < nvolumes_total; m2++) {
              data2 = MRIFvox(mri_flash[m2], x, y, z) - LDAmean1[m2];
              SW1->rptr[m1+1][m2+1] += data1*data2;
            }
          }
        } else if (label == classID2) {
          denom2 += 1.0;
          for (m1=0; m1 < nvolumes_total; m1++) {
            data1 = MRIFvox(mri_flash[m1], x, y, z) - LDAmean2[m1];
            for (m2=m1; m2 < nvolumes_total; m2++) {
              data2 = MRIFvox(mri_flash[m2], x, y, z) - LDAmean2[m2];
              SW2->rptr[m1+1][m2+1] += data1*data2;
            }
          }
        }

      } /* for all data points */

  if (denom1 <= 0.0 || denom2 <= 0)
    ErrorExit(ERROR_BADPARM, "%s: one or two classes is empty. \n", Progname);

  if (DEBUG)
    printf("brain size = %g\n", denom);

  if (USE_ONE) {
    printf("ONLY use SW from first class\n");
    printf("Seems reducing background noise\n");
    for (m1=1; m1 <= nvolumes_total; m1++) {
      for (m2=m1; m2 <= nvolumes_total; m2++) {
        SW1->rptr[m1][m2] = SW1->rptr[m1][m2]/denom1;
        SW1->rptr[m2][m1] = SW1->rptr[m1][m2];
      }
    } /* for m1, m2 */

  } else {
    /* The following matches HBM2005 abstract's CNR definition */
    for (m1=1; m1 <= nvolumes_total; m1++) {
      for (m2=m1; m2 <= nvolumes_total; m2++) {
        SW1->rptr[m1][m2] = SW1->rptr[m1][m2]/denom1 + SW2->rptr[m1][m2]/denom2;
        SW1->rptr[m2][m1] = SW1->rptr[m1][m2];
      }
    } /* for m1, m2 */

    if (regularize) {
      printf("regularization of the covariance estimate\n");
      for (m1=1; m1 <= nvolumes_total; m1++)
        SW1->rptr[m1][m1] += eps;  /* prevent SW1 to be singular */

      /* Borrow SW2 to store its inverse */
      SW2 = MatrixInverse(SW1, SW2);
      if (SW2 == NULL) {
        printf("Inverse matrix is NULL. Exit. \n");
        exit(1);
      }

      /* (1-lambda)* inv(SW + eps I) + labmda*I */
      for (m1=1; m1 <= nvolumes_total; m1++) {
        for (m2=m1; m2 <= nvolumes_total; m2++) {
          SW2->rptr[m1][m2] = (1.0 - lambda)*SW2->rptr[m1][m2];
          SW2->rptr[m2][m1] = SW2->rptr[m1][m2];
        }
        SW2->rptr[m1][m1] += lambda;
      }

      SW1 = MatrixInverse(SW2, SW1); // this inverse is quite redundant, since it will be inverted back again later

    }
  }

  if (0) {
    printf("SW is:\n");
    MatrixPrint(stdout, SW1);
  }

#if 0
  /* The following approach is equivalent to use -regularize; i.e., regularizing is equivalent to set SW to indentity */
  /* Compute inverse of SW */
  if (just_test == 0)
    InvSW = MatrixInverse(SW1, NULL);
  else {
    InvSW = (MATRIX *)MatrixAlloc(nvolumes_total, nvolumes_total, MATRIX_REAL);
    for (m1=1; m1 <= nvolumes_total; m1++) {
      for (m2=1; m2 <= nvolumes_total; m2++) {
        InvSW->rptr[m1][m2] = 0.0; /* index starts from 1 for matrix */
      }
      InvSW->rptr[m1][m1] = 1.0;
    }
  }
#else
  /* Here, we try to ignore the covariance term */
  if (just_test) {
    for (m1=1; m1 < nvolumes_total; m1++) {
      for (m2=m1+1; m2 <= nvolumes_total; m2++) {
        SW1->rptr[m1][m2] = 0.0; /* index starts from 1 for matrix */
        SW1->rptr[m2][m1] = 0.0; /* index starts from 1 for matrix */
      }
    }
  }

  InvSW = MatrixInverse(SW1, NULL);

#endif

  if (InvSW == NULL) { /* inverse doesn't exist */
    ErrorExit(ERROR_BADPARM, "%s: singular fuzzy covariance matrix.\n", Progname);
  }


  if (0) {
    printf("Inverse SW is:\n");
    MatrixPrint(stdout, InvSW);
  }

  if (0) {
    printf("Means for class 2 is \n");
    for (m1=1; m1 <= nvolumes_total; m1++) {
      printf("%g ", LDAmean1[m1-1]);
    }
    printf("\n");
    printf("Means for class 3 is \n");
    for (m1=1; m1 <= nvolumes_total; m1++) {
      printf("%g ", LDAmean2[m1-1]);
    }
  }
  /* Compute weights */
  denom = 0.0;
  sumw = 0.0;
  if (CHOICE == 1) {
    /* Do not use invSW, assume SW is diagonal */
    printf("Ignore off-diagonal of SW\n");
    for (m1=1; m1 <= nvolumes_total; m1++) {
      weights[m1-1]= (LDAmean1[m1-1] - LDAmean2[m1-1])/(SW1->rptr[m1][m1] + 1e-15);

      sumw += weights[m1-1];
      denom += weights[m1-1]*weights[m1-1];
    }
  } else {
    for (m1=1; m1 <= nvolumes_total; m1++) {
      weights[m1-1]= 0.0;
      for (m2=1; m2 <= nvolumes_total; m2++) {
        weights[m1-1] += InvSW->rptr[m1][m2] *(LDAmean1[m2-1] - LDAmean2[m2-1]);
      }
      sumw += weights[m1-1];
      denom += weights[m1-1]*weights[m1-1];
    }
  }

  if (compute_m_distance) {
    Mdistance = 0;
    for (m1=0; m1 < nvolumes_total; m1++) {
      Mdistance += weights[m1]*(LDAmean1[m1] - LDAmean2[m1]);
    }
    printf("Mdistance = %g \n", Mdistance);
  }

  denom = sqrt(denom + 0.0000001);
  /* Normalized weights to have norm 1 */
  for (m1=1; m1 <= nvolumes_total; m1++) {
    if (sumw > 0)
      weights[m1-1] /= denom;
    else
      weights[m1-1] /= -denom;
  }

  MatrixFree(&InvSW);

  MatrixFree(&SW1);
  MatrixFree(&SW2);

  return;
}
コード例 #29
0
ファイル: surfcluster.c プロジェクト: ewong718/freesurfer
/*----------------------------------------------------------------*/
SCS *SurfClusterSummary(MRI_SURFACE *Surf, MATRIX *T, int *nClusters)
{
  int n;
  SURFCLUSTERSUM *scs;
  MATRIX *xyz, *xyzxfm;
  double centroidxyz[3];
  struct timeb  mytimer;
  int msecTime;
  char *UFSS;

  // Must explicity "setenv USE_FAST_SURF_SMOOTHER 0" to turn off fast
  UFSS = getenv("USE_FAST_SURF_SMOOTHER");
  if(!UFSS) UFSS = "1";
  if(strcmp(UFSS,"0")){
    scs = SurfClusterSummaryFast(Surf, T, nClusters);
    return(scs);
  }
  if(Gdiag_no > 0) printf("SurfClusterSummary()\n");

  TimerStart(&mytimer) ;

  *nClusters = sclustCountClusters(Surf);
  if (*nClusters == 0) return(NULL);

  xyz    = MatrixAlloc(4,1,MATRIX_REAL);
  xyz->rptr[4][1] = 1;
  xyzxfm = MatrixAlloc(4,1,MATRIX_REAL);

  scs = (SCS *) calloc(*nClusters, sizeof(SCS));

  for (n = 0; n < *nClusters ; n++)
  {
    scs[n].clusterno = n+1;
    scs[n].area       = sclustSurfaceArea(n+1, Surf, &scs[n].nmembers);
    scs[n].weightvtx  = sclustWeight(n+1, Surf, NULL, 0);
    scs[n].weightarea = sclustWeight(n+1, Surf, NULL, 1);
    scs[n].maxval     = sclustSurfaceMax(n+1,  Surf, &scs[n].vtxmaxval);
    scs[n].x = Surf->vertices[scs[n].vtxmaxval].x;
    scs[n].y = Surf->vertices[scs[n].vtxmaxval].y;
    scs[n].z = Surf->vertices[scs[n].vtxmaxval].z;
    sclustSurfaceCentroid(n+1,  Surf, &centroidxyz[0]);
    scs[n].cx = centroidxyz[0];
    scs[n].cy = centroidxyz[1];
    scs[n].cz = centroidxyz[2];
    if (T != NULL){
      xyz->rptr[1][1] = scs[n].x;
      xyz->rptr[2][1] = scs[n].y;
      xyz->rptr[3][1] = scs[n].z;
      MatrixMultiply(T,xyz,xyzxfm);
      scs[n].xxfm = xyzxfm->rptr[1][1];
      scs[n].yxfm = xyzxfm->rptr[2][1];
      scs[n].zxfm = xyzxfm->rptr[3][1];

      xyz->rptr[1][1] = scs[n].cx;
      xyz->rptr[2][1] = scs[n].cy;
      xyz->rptr[3][1] = scs[n].cz;
      MatrixMultiply(T,xyz,xyzxfm);
      scs[n].cxxfm = xyzxfm->rptr[1][1];
      scs[n].cyxfm = xyzxfm->rptr[2][1];
      scs[n].czxfm = xyzxfm->rptr[3][1];
    }
  }

  MatrixFree(&xyz);
  MatrixFree(&xyzxfm);
  msecTime = TimerStop(&mytimer) ;
  if(Gdiag_no > 0) printf("SurfClusterSum: n=%d, t = %g\n",*nClusters,msecTime/1000.0);

  return(scs);
}
コード例 #30
0
ファイル: gclass.c プロジェクト: ewong718/freesurfer
/*-----------------------------------------------------
        Parameters:

        Returns value:

        Description
------------------------------------------------------*/
GCLASSIFY *
GCalloc(int nclasses, int nvars, char *class_names[])
{
  GCLASSIFY  *gc ;
  GCLASS     *gcl ;
  int        cno ;

  gc = (GCLASSIFY *)calloc(1, sizeof(GCLASSIFY)) ;
  if (!gc)
    ErrorReturn(NULL,
                (ERROR_NO_MEMORY,"GCalloc(%d): could not allocate GC",nclasses));

  gc->nclasses = nclasses ;
  gc->nvars = nvars ;
  gc->classes = (GCLASS *)calloc(nclasses, sizeof(GCLASS)) ;
  if (!gc->classes)
    ErrorReturn(NULL,
                (ERROR_NO_MEMORY,
                 "GFalloc(%d): could not allocated class table",nclasses));

  gc->log_probabilities = (float *)calloc(nclasses, sizeof(float)) ;
  if (!gc->log_probabilities)
  {
    GCfree(&gc) ;
    ErrorReturn(NULL,
                (ERROR_NO_MEMORY,
                 "GFalloc(%d): could not probability table",nclasses));
  }

  for (cno = 0 ; cno < nclasses ; cno++)
  {
    gcl = &gc->classes[cno] ;
    gcl->classno = cno ;
    gcl->m_covariance = MatrixAlloc(nvars,nvars,MATRIX_REAL);
    if (!gcl->m_covariance)
    {
      GCfree(&gc) ;
      ErrorReturn(NULL,
                  (ERROR_NO_MEMORY,
                   "GFalloc(%d): could not allocated %d x %d cov. matrix"
                   "for %dth class", nclasses, nvars, nvars, cno)) ;
    }
    gcl->m_u = MatrixAlloc(nvars,1,MATRIX_REAL);
    if (!gcl->m_u)
    {
      GCfree(&gc) ;
      ErrorReturn(NULL,
                  (ERROR_NO_MEMORY,
                   "GFalloc(%d): could not allocated %d x 1 mean vector"
                   "for %dth class", nclasses, nvars, cno)) ;
    }
    gcl->m_W = MatrixAlloc(nvars,nvars,MATRIX_REAL);
    if (!gcl->m_W)
    {
      GCfree(&gc) ;
      ErrorReturn(NULL,
                  (ERROR_NO_MEMORY,
                   "GFalloc(%d): could not allocated %d x %d matrix"
                   "for %dth class", nclasses, nvars, nvars, cno)) ;
    }
#if 1
    gcl->m_wT =
      MatrixAlloc(gcl->m_u->cols, gcl->m_covariance->rows, MATRIX_REAL);
    if (!gcl->m_wT)
    {
      GCfree(&gc) ;
      ErrorReturn(NULL,
                  (ERROR_NO_MEMORY,
                   "GFalloc(%d): could not allocated %d x %d matrix"
                   "for %dth class", nclasses, gcl->m_u->cols,
                   gcl->m_covariance->rows, cno)) ;
    }
#endif
    if (class_names)
      strncpy(gcl->class_name, class_names[cno], 29) ;
    else
      sprintf(gcl->class_name, "class %d", cno) ;
  }

  return(gc) ;
}