Example #1
0
MRI_IMAGE * mri_sharpen_rgb( float phi , MRI_IMAGE *im )
{
   MRI_IMAGE *flim , *shim , *newim ;
   byte  *iar , *nar ;
   float *sar , *far ;
   int ii , nvox , rr,gg,bb ;
   float fac ;

ENTRY("mri_sharpen_rgb") ;

   if( im == NULL ) RETURN( NULL );

   if( im->kind != MRI_rgb ) RETURN( mri_sharpen(phi,0,im) );

   flim  = mri_to_float( im ) ;                  /* intensity of input */
   shim  = mri_sharpen( phi , 0 , flim ) ;       /* sharpen intensity */
   newim = mri_new_conforming( im , MRI_rgb ) ;  /* will be output    */

   nar = MRI_BYTE_PTR(newim) ; iar = MRI_BYTE_PTR(im) ;
   far = MRI_FLOAT_PTR(flim) ; sar = MRI_FLOAT_PTR(shim) ;

   nvox = newim->nvox ;
   for( ii=0 ; ii < nvox ; ii++ ){
     if( far[ii] <= 0.0 || sar[ii] <= 0.0 ){
       nar[3*ii] = nar[3*ii+1] = nar[3*ii+2] = 0 ;
     } else {
       fac = sar[ii] / far[ii] ; /* will be positive */
       rr  = fac * iar[3*ii]   ;
       gg  = fac * iar[3*ii+1] ;
       bb  = fac * iar[3*ii+2] ;
       nar[3*ii  ] = (rr > 255) ? 255 : rr ;
       nar[3*ii+1] = (gg > 255) ? 255 : gg ;
       nar[3*ii+2] = (bb > 255) ? 255 : bb ;
     }
   }

   mri_free(flim) ; mri_free(shim) ;
   MRI_COPY_AUX(newim,im) ;
   RETURN( newim );
}
Example #2
0
MRI_IMAGE * mri_double_up( MRI_IMAGE *fim , int xadd,int yadd,int zadd )
{
   MRI_IMAGE *gim ;
   int nxf,nyf,nzf , nxg,nyg,nzg , nxyf,nxyg , ii,jj,kk , im,jm,km,ip,jp,kp ;
   float *far , *gar ;

ENTRY("mri_double_up") ;

   if( fim == NULL ) RETURN(NULL) ;

   /* process a non-float image? */

   if( fim->kind != MRI_float ){
     MRI_IMAGE *qim = mri_to_float(fim) ;
     gim = mri_double_up(qim,xadd,yadd,zadd) ; mri_free(qim) ; RETURN(gim) ;
   }

   /* f=input  g=output */

   nxf = fim->nx ; nyf = fim->ny ; nzf = fim->nz  ;

   nxg = (nxf == 1) ? 1 : (2*nxf+(xadd != 0)) ;
   nyg = (nyf == 1) ? 1 : (2*nyf+(yadd != 0)) ;
   nzg = (nzf == 1) ? 1 : (2*nzf+(zadd != 0)) ;

   nxyf = nxf*nyf ; nxyg = nxg*nyg ;

   gim = mri_new_vol(nxg,nyg,nzg,MRI_float) ;
   gar = MRI_FLOAT_PTR(gim) ;
   far = MRI_FLOAT_PTR(fim) ;

   /* for even output indexes, use the corresponding index in the input;
      for odd output indexes, use the neighboring indexes in the input. */

   for( kk=0 ; kk < nzg ; kk++ ){
    kp = km = kk/2 ;  if( kp >= nzf ) kp = km = nzf-1 ;
    if( kk%2 ){ kp++; if( kp >= nzf ) kp = nzf-1; }
    for( jj=0 ; jj < nyg ; jj++ ){
      jp = jm = jj/2 ;  if( jp >= nyf ) jp = jm = nyf-1 ;
      if( jj%2 ){ jp++; if( jp >= nyf ) jp = nyf-1; }
      for( ii=0 ; ii < nxg ; ii++ ){
        ip = im = ii/2 ;  if( ip >= nxf ) ip = im = nxf-1 ;
        if( ii%2 ){ ip++; if( ip >= nxf ) ip = nxf-1; }
        FSUB(gar,ii,jj,kk,nxg,nxyg) =
          0.125f * ( FSUB(far,im,jm,km,nxf,nxyf) + FSUB(far,ip,jm,km,nxf,nxyf)
                    +FSUB(far,im,jp,km,nxf,nxyf) + FSUB(far,ip,jp,km,nxf,nxyf)
                    +FSUB(far,im,jm,kp,nxf,nxyf) + FSUB(far,ip,jm,kp,nxf,nxyf)
                    +FSUB(far,im,jp,kp,nxf,nxyf) + FSUB(far,ip,jp,kp,nxf,nxyf) ) ;
   }}}

   RETURN(gim) ;
}
Example #3
0
MRI_IMAGE * mri_jointhist( MRI_IMAGE *imp , MRI_IMAGE *imq , byte *mmm )
{
   int nvox , nmmm=0 ;
   float *rst ;
   byte *par, *qar ;
   float fac ;
   register int ii,jj,kk ;
   MRI_IMAGE *imqq, *impp , *imh ;

   if( imp == NULL || imq == NULL || imp->nvox != imq->nvox ) return NULL;

   nvox = imp->nvox ;

   impp = (imp->kind==MRI_byte) ? imp : mri_to_byte(imp) ;
   imqq = (imq->kind==MRI_byte) ? imq : mri_to_byte(imq) ;
   par  = MRI_BYTE_PTR(impp) ;
   qar  = MRI_BYTE_PTR(imqq) ;
   imh  = mri_new( 256,256,MRI_float ) ;
   rst  = MRI_FLOAT_PTR(imh) ;

   if( mmm != NULL ){
     for( kk=0 ; kk < nvox ; kk++ ) if( mmm[kk] ) nmmm++ ;
     fac = 1.0f / nmmm ;
     for( kk=0 ; kk < nvox ; kk++ ){
       if( mmm[kk] == 0 ) continue ;
       ii = par[kk] ; jj = qar[kk] ; rst[ii+256*jj] += fac ;
     }
   } else {
     fac = 1.0f / nvox ;
     for( kk=0 ; kk < nvox ; kk++ ){
       ii = par[kk] ; jj = qar[kk] ; rst[ii+256*jj] += fac ;
     }
   }

   if( impp != imp ) mri_free(impp) ;
   if( imqq != imq ) mri_free(imqq) ;

   return imh ;
}
Example #4
0
static float mri_svd_max( MRI_IMAGE *fim )
{
   MRI_IMAGE *aim ;
   double ev=0.0 ;
   int mm ; float sv ;

   aim = mri_make_xxt( fim ) ; if( aim == NULL ) return -1.0f ;
   mm  = aim->nx ;

   (void)symeig_irange( mm, MRI_DOUBLE_PTR(aim) , &ev , mm-1,mm-1 , 1 ) ;
   mri_free(aim) ;
   sv = (ev > 0.0) ? (float)sqrt(ev) : 0.0f ;
   return sv ;
}
Example #5
0
int mri_write_1D( char *fname , MRI_IMAGE *im )  /* 16 Nov 1999 */
{
   MRI_IMAGE *fim ;
   int jj ;

ENTRY("mri_write_1D") ;

   if( im == NULL || im->nz > 1 ) RETURN( 0 ) ; /* stoopid user */

   fim = mri_transpose( im ) ;
   jj  = mri_write_ascii( fname , fim ) ;
   mri_free(fim) ;
   RETURN( jj );
}
Example #6
0
MRI_IMAGE *mri_to_rgb( MRI_IMAGE *oldim )  /* 11 Feb 1999 */
{
   MRI_IMAGE *newim ;
   register int ii , npix ;
   register byte * rgb ;

ENTRY("mri_to_rgb") ;

   if( oldim == NULL ) RETURN( NULL );

   newim = mri_new_conforming( oldim , MRI_rgb ) ; rgb = MRI_RGB_PTR(newim) ;
   npix  = oldim->nvox ;

   switch( oldim->kind ){

      case MRI_byte:{ byte *qar = MRI_BYTE_PTR(oldim) ;
        for( ii=0 ; ii < npix ; ii++ )
          rgb[3*ii] = rgb[3*ii+1] = rgb[3*ii+2] = qar[ii] ;
      } break ;

      case MRI_float:{ float *qar = MRI_FLOAT_PTR(oldim) ;
        for( ii=0 ; ii < npix ; ii++ )
          rgb[3*ii] = rgb[3*ii+1] = rgb[3*ii+2] = qar[ii] ;
      } break ;

      case MRI_short:{ short *qar = MRI_SHORT_PTR(oldim) ;
        for( ii=0 ; ii < npix ; ii++ )
          rgb[3*ii] = rgb[3*ii+1] = rgb[3*ii+2] = qar[ii] ;
      } break ;

      case MRI_rgb:
        memcpy( rgb , MRI_RGB_PTR(oldim) , 3*npix ) ;
      break ;

      case MRI_rgba:{ rgba *qar = MRI_RGBA_PTR(oldim) ;
        for( ii=0 ; ii < npix ; ii++ ){
          rgb[3*ii]   = qar[ii].r ;
          rgb[3*ii+1] = qar[ii].g ;
          rgb[3*ii+2] = qar[ii].b ;
        }
      } break ;

      default:
        ERROR_message("mri_to_rgb: unrecognized image conversion %d",oldim->kind) ;
        mri_free(newim) ; RETURN(NULL);
   }

   MRI_COPY_AUX(newim,oldim) ;
   RETURN( newim );
}
Example #7
0
MRI_IMAGE * DES_get_psinv( int ntim , int nref , float **ref )
{
   MRI_IMAGE *refim , *psinv ; float *refar , *jar ; int ii , jj ;

   refim = mri_new(ntim,nref,MRI_float) ;
   refar = MRI_FLOAT_PTR(refim) ;
   for( jj=0 ; jj < nref ; jj++ ){
     jar = refar + jj*ntim ;
     for( ii=0 ; ii < ntim ; ii++ ) jar[ii] = ref[jj][ii] ;
   }
   mri_matrix_psinv_svd(1) ;
   psinv = mri_matrix_psinv(refim,NULL,0.0f) ;
   mri_free(refim) ;
   return psinv ;
}
Example #8
0
static void * PH_popup_image( void * handle , MRI_IMAGE * im )
{
   PLUGIN_impopper * imp = (PLUGIN_impopper *) handle ;

   /*-- input image is NULL ==> popdown, if applicable --*/

   if( im == NULL ){
      if( imp != NULL )
         drive_MCW_imseq( imp->seq , isqDR_destroy , NULL ) ;

      return ((void *) imp) ;
   }

   /*-- input = no popper handle ==> create one --*/

   if( imp == NULL ){
      imp      = XtNew(PLUGIN_impopper) ;
      imp->seq = NULL ; imp->im  = NULL ;
   }

   /*-- input = non-null image ==> replace image --*/

   mri_free( imp->im ) ;                   /* toss old copy */
   imp->im = mri_to_mri( im->kind , im ) ; /* make new copy */

   /*-- input = inactive popper handle ==> activate it --*/

   if( imp->seq == NULL ){
      imp->seq = open_MCW_imseq( MAIN_dc ,
                                 PLUGIN_imseq_getim , (XtPointer) imp ) ;

      drive_MCW_imseq( imp->seq , isqDR_realize, NULL ) ;
      drive_MCW_imseq( imp->seq , isqDR_onoffwid , (XtPointer) isqDR_offwid ) ;

      XtVaSetValues( imp->seq->wtop ,
                       XmNmwmDecorations , MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MENU ,
                       XmNmwmFunctions   , MWM_FUNC_MOVE | MWM_FUNC_CLOSE ,
                       XmNtitle          , "Xphace Images" ,
                     NULL ) ;

   }

   drive_MCW_imseq( imp->seq , isqDR_clearstat , NULL ) ;
   drive_MCW_imseq( imp->seq , isqDR_reimage , (XtPointer) 0 ) ;

   return ((void *) imp) ;
}
Example #9
0
void PLUGIN_seq_send_CB( MCW_imseq * seq , XtPointer handle , ISQ_cbs * cbs )
{
   PLUGIN_impopper * imp = (PLUGIN_impopper *) handle ;

   if( imp == NULL ) return ;

   switch( cbs->reason ){

      case isqCR_destroy:{
         XtFree((char*)imp->seq->status) ;
         XtFree((char*)imp->seq)         ; imp->seq = NULL ;
         mri_free( imp->im )             ; imp->im  = NULL ;
      }
      break ;
   }
   return ;
}
Example #10
0
MRI_IMAGE * mri_3to_rgb( MRI_IMAGE *rim , MRI_IMAGE *gim , MRI_IMAGE *bim )
{
   MRI_IMAGE *newim ;
   register int ii , npix ;
   register byte * rgb ;

ENTRY("mri_3to_rgb") ;

   if( rim == NULL || bim == NULL || gim == NULL ) RETURN( NULL );

   newim = mri_new_conforming( rim , MRI_rgb ) ; rgb = MRI_BYTE_PTR(newim) ;
   npix  = rim->nvox ;

   switch( rim->kind ){

      case MRI_byte:{
        byte *rr=MRI_BYTE_PTR(rim), *gg=MRI_BYTE_PTR(gim), *bb=MRI_BYTE_PTR(bim) ;
        for( ii=0 ; ii < npix ; ii++ ){
          rgb[3*ii  ] = rr[ii] ;
          rgb[3*ii+1] = gg[ii] ;
          rgb[3*ii+2] = bb[ii] ;
        }
      }
      break ;

      case MRI_float:{
        float *rr=MRI_FLOAT_PTR(rim), *gg=MRI_FLOAT_PTR(gim), *bb=MRI_FLOAT_PTR(bim) ;
        for( ii=0 ; ii < npix ; ii++ ){
          rgb[3*ii  ] = rr[ii] ;
          rgb[3*ii+1] = gg[ii] ;
          rgb[3*ii+2] = bb[ii] ;
        }
      }
      break ;

      default:
        ERROR_message("mri_3to_rgb: unrecognized image conversion %d",rim->kind) ;
        mri_free(newim) ; RETURN(NULL) ;
   }

   MRI_COPY_AUX(newim,rim) ;
   RETURN( newim );
}
Example #11
0
MRI_IMAGE * THD_extract_series( int ind , THD_3dim_dataset *dset , int raw )
{
   int nv , typ , ii ;
   MRI_IMAGE *im ;
   void *imar ;

ENTRY("THD_extract_series") ;

   if( !ISVALID_DSET(dset) ) RETURN(NULL) ;

   nv  = dset->dblk->nvals ;
   if( raw ) typ = DSET_BRICK_TYPE(dset,0) ;  /* type of output array */
   else      typ = MRI_float ;

   im   = mri_new( nv , 1 , typ ) ;           /* output image */
   imar = mri_data_pointer(im) ;

   ii = THD_extract_array( ind , dset , raw , imar ) ; /* get data */

   if( ii != 0 ){ mri_free(im) ; RETURN(NULL) ; }      /* bad */

   if( dset->taxis != NULL ){  /* 21 Oct 1996 */
      float zz , tt ;
      int kz = ind / ( dset->daxes->nxx * dset->daxes->nyy ) ;

      zz = dset->daxes->zzorg + kz * dset->daxes->zzdel ;
      tt = THD_timeof( 0 , zz , dset->taxis ) ;

      im->xo = tt ; im->dx = dset->taxis->ttdel ;   /* origin and delta */

      if( dset->taxis->units_type == UNITS_MSEC_TYPE ){ /* convert to sec */
         im->xo *= 0.001 ; im->dx *= 0.001 ;
      }
   } else {
      im->xo = 0.0 ; im->dx = 1.0 ;  /* 08 Nov 1996 */
   }

   RETURN(im) ;
}
Example #12
0
MRI_IMAGE * mri_extract_from_mask( MRI_IMAGE *imin , byte *mask , int invert )
{
   byte bmmm = (invert == 0) ? 1 : 0 ;
   int ii,jj , ngood , nvox ;
   float *iar , *oar ;
   MRI_IMAGE *outim ;

ENTRY("mri_extract_mask") ;

   if( imin == NULL || mask == NULL ) RETURN(NULL) ;  /* bad user == luser */

   /*-- not float?  create a float image and recurse! --*/

   if( imin->kind != MRI_float ){
     MRI_IMAGE *qim = mri_to_float(imin) ;
     outim = mri_extract_from_mask( qim , mask , invert ) ;
     mri_free(qim) ;
     RETURN(outim) ;
   }

   /*-- count up the good voxels --*/

   nvox = imin->nvox ;
   for( ngood=ii=0 ; ii < nvox ; ii++ ) if( GOOD(ii) ) ngood++ ;
   if( ngood == 0 ) RETURN(NULL) ;

   /*-- create the output --*/

   outim = mri_new( ngood , 1 , MRI_float ) ;
   oar   = MRI_FLOAT_PTR(outim) ;
   iar   = MRI_FLOAT_PTR(imin) ;

   /*-- fill the output --*/

   for( jj=ii=0 ; ii < nvox ; ii++ ) if( GOOD(ii) ) oar[jj++] = iar[ii] ;

   RETURN(outim) ;
}
Example #13
0
int main (int argc,char *argv[])
{/* Main */
   static char FuncName[]={"ScaleToMap"};
   char  *IntName = NULL, *Prfx, h[9], 
         *CmapFileName = NULL, *dbfile = NULL, *MapName=NULL; 
   MRI_IMAGE *im = NULL;
   float *far=NULL;
   int N_V, N_Int, kar, k, ii, i, icol=-1, vcol=-1, Sgn, interpmode, k3;
   int Vminloc, Vmaxloc, *iV = NULL;
   float Vmin, Vmax, brfact;
   float *V = NULL, *Vsort = NULL;
   float IntRange[2], MaskColor[3], MaskRange[2]={0.0, 0.0}, arange;
   SUMA_Boolean ApplyClip, ApplyMask, setMaskCol, ApplyPercClip, Vopt;
   SUMA_Boolean iVopt, inopt, NoMaskCol, MapSpecified, alaAFNI, MaskZero;
   SUMA_Boolean brk, frf, ShowMap, ShowMapdb;
   SUMA_COLOR_MAP *CM;
   SUMA_SCALE_TO_MAP_OPT * OptScl;
   int MapType, freecm = 1;
   SUMA_COLOR_SCALED_VECT * SV;
   SUMA_AFNI_COLORS *SAC=NULL;
   SUMA_Boolean FromAFNI = NOPE;
   int imap, isPmap, isNmap;
   SUMA_Boolean LocalHead = NOPE;
   
   
   SUMA_STANDALONE_INIT;
   SUMAg_CF->isGraphical = YUP;
   SUMA_mainENTRY;
   
   /* this is placed down here to */
   /* 
   if (argc < 3) {
      SUMA_ScaleToMap_usage();
      exit (1);
   }
   */
   
   kar = 1;
   brfact = 1; /* the brightness factor */
   MaskColor[0] = MaskColor[1] = MaskColor[2] = 0.3;
   ApplyClip = NOPE;
   ApplyPercClip = NOPE;
   ApplyMask = NOPE;
   NoMaskCol = NOPE;
   MaskZero = NOPE;
   setMaskCol = NOPE;
   Vopt = NOPE;
   iVopt = NOPE;
   inopt = NOPE;
   MapType = SUMA_CMAP_RGYBR20;
   brk = NOPE;
   MapSpecified = NOPE;
   CmapFileName = NULL;
   interpmode = SUMA_UNDEFINED_MODE;
   ShowMap = NOPE;
   alaAFNI = NOPE;   /* applying the alaAFNI mapping */
   frf = NOPE;
   arange  = -1.0; /* afni range specified */
   Sgn = 0;
   ShowMapdb = NOPE;
   while (kar < argc) { /* loop accross command ine options */
      /*fprintf(stdout, "%s verbose: Parsing command line...\n", FuncName);*/
      if (strcmp(argv[kar], "-h") == 0 || strcmp(argv[kar], "-help") == 0) {
         SUMA_ScaleToMap_usage();
         exit (1);
      }
      
      SUMA_SKIP_COMMON_OPTIONS(brk, kar);
      
      if (!brk && strcmp(argv[kar], "-verb") == 0) {
         LocalHead = NOPE;
         brk = YUP;
      }
      
      if (!brk && strcmp(argv[kar], "-ionot") == 0) {
         SUMA_SL_Err("-ionot is obsolete. \n"
                     "Use -trace option.");
         exit (1);
         SUMA_INOUT_NOTIFY_ON;
         brk = YUP;
      }
      
      if (!brk && strcmp(argv[kar], "-msk_zero") == 0) {
         MaskZero = YUP;
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-input") == 0)) {
         kar ++;
         if (kar+2 >= argc)  {
            fprintf (SUMA_STDERR, "need 3 arguments after -input \n");
            exit (1);
         }
         IntName = argv[kar]; kar ++;
         icol = atoi(argv[kar]); kar ++;
         vcol = atoi(argv[kar]); 
         inopt = YUP;
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-apr") == 0)) {
         if (arange >= 0) {
            fprintf (SUMA_STDERR, "range has already been specified.\n");
            exit (1);
         }
         kar ++;
         if (kar >= argc)  {
            fprintf (SUMA_STDERR, "need argument after -apr \n");
            exit (1);
         }
         arange = atof(argv[kar]);
         if (arange < 0) {
            fprintf (SUMA_STDERR, "range must be positive.\n");
            exit (1);
         }
         Sgn = 1;
         alaAFNI = YUP;
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-anr") == 0)) {
         if (arange >= 0) {
            fprintf (SUMA_STDERR, "range has already been specified.\n");
            exit (1);
         }
         kar ++;
         if (kar >= argc)  {
            fprintf (SUMA_STDERR, "need argument after -anr \n");
            exit (1);
         }
         arange = atof(argv[kar]);
         if (arange < 0) {
            fprintf (SUMA_STDERR, "range must be positive.\n");
            exit (1);
         }
         
         Sgn = -1;
         alaAFNI = YUP;
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-v") == 0)) {
         fprintf (SUMA_STDERR, "\n -v option is now obsolete.\nUse -input option instead.\n");
         exit (1);
         kar ++;
         if (kar >= argc)  {
            fprintf (SUMA_STDERR, "need argument after -v \n");
            exit (1);
         }
         IntName = argv[kar];
         Vopt = YUP;
         brk = YUP;
      }      
      
      if (!brk && (strcmp(argv[kar], "-iv") == 0)) {
         fprintf (SUMA_STDERR, "\n -iv option is now obsolete.\nUse -input option instead.\n");
         exit (1);
         kar ++;
         if (kar >= argc)  {
              fprintf (SUMA_STDERR, "need argument after -iv \n");
            exit (1);
         }
         IntName = argv[kar];
         iVopt = YUP;
         brk = YUP;
      }   
      
      if (!brk && (strcmp(argv[kar], "-br") == 0)) {
         kar ++;
         if (kar >= argc)  {
              fprintf (SUMA_STDERR, "need argument after -br \n");
            exit (1);
         }
         brfact = atof(argv[kar]);

         brk = YUP;
      }   
      
      if (!brk && (strcmp(argv[kar], "-frf") == 0)) {
         frf = YUP;
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-showmap") == 0)) {
         ShowMap = YUP;
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-showdb") == 0)) {
         ShowMapdb = YUP;
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-nointerp") == 0)) {
         if (interpmode != SUMA_UNDEFINED_MODE) {
            fprintf (SUMA_STDERR, "Color interpolation mode already set.\n");
         }
         interpmode = SUMA_NO_INTERP;
         brk = YUP;
      } 
      
      if (!brk && (strcmp(argv[kar], "-direct") == 0)) {
         if (interpmode != SUMA_UNDEFINED_MODE) {
            fprintf (SUMA_STDERR, "Color interpolation mode already set.\n");
         }
         interpmode = SUMA_DIRECT;
         brk = YUP;
      } 
      
      if (!brk && (strcmp(argv[kar], "-interp") == 0)) {
         if (interpmode != SUMA_UNDEFINED_MODE) {
            fprintf (SUMA_STDERR, "Color interpolation mode already set.\n(-nointerp, -direct and -interp are mutually exclusive.\n");
         }
         interpmode = SUMA_INTERP;
         brk = YUP;
      } 
        
      if (!brk && (strcmp(argv[kar], "-clp") == 0)) {
         kar ++;
         if (kar+1 >= argc)  {
              fprintf (SUMA_STDERR, "need 2 arguments after -clp \n");
            exit (1);
         }
         ApplyClip = YUP;
         IntRange[0] = atof(argv[kar]); kar ++;
         IntRange[1] = atof(argv[kar]);
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-perc_clp") == 0)) {
         kar ++;
         if (kar+1 >= argc)  {
              fprintf (SUMA_STDERR, "need 2 arguments after -perc_clp ");
            exit (1);
         }
         ApplyPercClip = YUP;
         IntRange[0] = atof(argv[kar]); kar ++;
         IntRange[1] = atof(argv[kar]);
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-msk") == 0)) {
         kar ++;
         if (kar+1 >= argc)  {
              fprintf (SUMA_STDERR, "need 2 arguments after -msk ");
            exit (1);
         }
         ApplyMask = YUP;
         MaskRange[0] = atof(argv[kar]); kar ++;
         MaskRange[1] = atof(argv[kar]);
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-nomsk_col") == 0)) {
         NoMaskCol = YUP;
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-msk_col") == 0)) {
         kar ++;
         if (kar+2 >= argc)  {
              fprintf (SUMA_STDERR, "need 3 arguments after -msk_col ");
            exit (1);
         }
         setMaskCol = YUP;
         MaskColor[0] = atof(argv[kar]); kar ++;
         MaskColor[1] = atof(argv[kar]); kar ++;
         MaskColor[2] = atof(argv[kar]);
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-cmapfile") ==0)) {
         if (MapSpecified) {
            fprintf (SUMA_STDERR, "Color map already specified.\n-cmap and -cmapfile are mutually exclusive\n");
            exit (1);
         }
         MapSpecified = YUP;
         kar ++;
         if (kar >= argc)  {
            fprintf (SUMA_STDERR, "need 1 arguments after -cmapfile ");
            exit (1);
         }
         
         CmapFileName = argv[kar];
         brk = YUP;
      }
      
      if (!brk && (strcmp(argv[kar], "-cmapdb") ==0)) {
         kar ++;
         if (kar >= argc)  {
            fprintf (SUMA_STDERR, "need 1 arguments after -cmapdb ");
            exit (1);
         }
         
         dbfile = argv[kar];
         brk = YUP;
      }
      
      
      if (!brk && (strcmp(argv[kar], "-cmap") ==0)) {
         if (MapSpecified) {
            fprintf (SUMA_STDERR, "Color map already specified.\n-cmap and -cmapfile are mutually exclusive\n");
            exit (1);
         }
         MapSpecified = YUP;
         kar ++;
         if (kar >= argc)  {
            fprintf (SUMA_STDERR, "need 1 arguments after -cmap ");
            exit (1);
         }
         MapName = argv[kar];
         
         brk = YUP;
      }
      
      if (!brk) {
         fprintf (SUMA_STDERR,"Error %s: Option %s not understood. Try -help for usage\n", FuncName, argv[kar]);
         exit (1);
      } else {   
         brk = NOPE;
         kar ++;
      }
      
   }/* loop accross command ine options */
   
   /* Get your colors straightened out */
   if (!SUMAg_CF->scm) {   
      SUMAg_CF->scm = SUMA_Build_Color_maps();
      if (!SUMAg_CF->scm) {
         SUMA_SL_Err("Failed to build color maps.\n");
         exit(1);
      }
   }

   SAC = SUMAg_CF->scm;
   /* are there database files to read */
   if (dbfile) {
      SUMA_LH("Now trying to read db file");
      if (SUMA_AFNI_Extract_Colors ( dbfile, SAC ) < 0) {
         SUMA_S_Errv("Failed to read %s colormap file.\n", dbfile);
         exit(1);
      }
   }
   
   FromAFNI = NOPE; /* assume colormap is not coming from SAC
                       (the colormap database structure) */
   if (CmapFileName) { 
      /* load the color map */
      CM = SUMA_Read_Color_Map_1D (CmapFileName);
      if (CM == NULL) {
         SUMA_S_Err("Could not load colormap.\n");
         exit (1); 
      }
      if (frf) {
         SUMA_LH("Flipping colormap");
         SUMA_Flip_Color_Map (CM);
      }   

      if (!CM->Sgn) CM->Sgn = Sgn; 
   }else{
      /* dunno what kind of map yet. Try default first */
      if (MapName) {
         CM = SUMA_FindNamedColMap (MapName);
         freecm = 0;
         if (CM) {
            /* good, sign it and out you go */   
            CM->Sgn = Sgn;
         } else {
            SUMA_S_Err("Could not get standard colormap.\n");
            exit (1); 
         }
      } else {
         SUMA_LH("An AFNI color map ");
         /* a color from AFNI's maps */
         FromAFNI = YUP;
         imap = SUMA_Find_ColorMap ( MapName, SAC->CMv, SAC->N_maps, -2);
         if (imap < 0) {
            SUMA_S_Errv("Could not find colormap %s.\n", MapName);
            exit (1); 
         }
         CM = SAC->CMv[imap];
      }
   }
   
   
   /* show the colromap on STDERR */
   if (ShowMap) {
      fprintf (SUMA_STDERR, "%s: Colormap used:\n", FuncName);
      SUMA_Show_ColorMapVec (&CM, 1, NULL, 2);
      {
         SUMA_SurfaceObject *SO = NULL;
         float orig[3]     = { SUMA_CMAP_ORIGIN  };
         float topright[3] = { SUMA_CMAP_TOPLEFT };
         
         SO = SUMA_Cmap_To_SO (CM, orig, topright, 2);
         if (SO) SUMA_Free_Surface_Object(SO);
      }
      exit(0);
   }
   
   /* show all the colors and colormaps in SAC on STDERR */
   if (ShowMapdb) {
      fprintf (SUMA_STDERR, "%s: AFNI colormaps found in db:\n", FuncName);
      SUMA_Show_ColorVec (SAC->Cv, SAC->N_cols, NULL);
      SUMA_Show_ColorMapVec (SAC->CMv, SAC->N_maps, NULL, 2);
      exit(0);
   }


   if (!IntName) {
      fprintf (SUMA_STDERR,"Error %s: No input file specified.\n", FuncName);
      exit(1);
   }
   
   /* default interpolation mode */
   if (interpmode == SUMA_UNDEFINED_MODE) interpmode = SUMA_INTERP; 
   
   /* check input */
   if (!SUMA_filexists (IntName)) {
      fprintf (SUMA_STDERR,"Error %s: File %s could not be found.\n", FuncName, IntName);
      exit(1);
   }
   
   if (frf && !CmapFileName) {
      fprintf (SUMA_STDERR,"Error %s: -frf option is only valid with -cmapfile.\n", FuncName);
      exit(1);
   }
   
   if (ApplyPercClip && ApplyClip) {
      fprintf (SUMA_STDERR,"Error %s: Simultaneous use of -clp and -perc_clp. You should be punished.\n", FuncName);
      exit(1);
   }
   
   if ((ApplyPercClip || ApplyClip) && arange >= 0.0) {
      fprintf (SUMA_STDERR,"Error %s: Simultaneous use of -clp/-perc_clp and -apr/anr.\n Read the help.\n", FuncName);
      exit(1);
   }
   
   if (iVopt || Vopt) {
      fprintf (SUMA_STDERR,"Error %s: -v and -iv are obsolete.\n Use -input option instead.\n", FuncName);
      exit(1);
   }
   
   if (!inopt) {
      fprintf (SUMA_STDERR,"Error %s: -input option must be specified.\n", FuncName);
      exit(1);
   }
   
   im = mri_read_1D (IntName);
   
   if (!im) {
      SUMA_S_Err("Failed to read file");
      exit (1);
   }
   
   if (vcol < 0) {
      fprintf (SUMA_STDERR,"Error %s: vcol must be > 0\n", FuncName);
      exit(1);
   }
   
   far = MRI_FLOAT_PTR(im);
   if (icol < 0 && icol != -1) {
      fprintf (SUMA_STDERR,"Error %s: icol(%d) can only have -1 for a negative value\n", FuncName, icol);
      exit(1);
   }
   
   if (icol >= im->ny || vcol >= im->ny) {
      fprintf (SUMA_STDERR,"Error %s: icol(%d) and vcol(%d) must be < %d\nwhich is the number of columns in %s\n",
          FuncName, icol, vcol, im->ny, IntName);
      exit(1);
   }
   
   
   if (brfact <=0 || brfact > 1) {
      fprintf (SUMA_STDERR,"Error %s: BrightFact must be > 0 and <= 1.\n", FuncName);
      exit (1);
   }
   
   if (MaskColor[0] < 0 || MaskColor[0] > 1 || MaskColor[1] < 0 || MaskColor[1] > 1 || MaskColor[2] < 0 || MaskColor[2] > 1) {
      fprintf (SUMA_STDERR,"Error %s: MaskColor values must be >=0 <=1.\n", FuncName);
      exit(1);
   }
     
   
   N_V = im->nx;
   V = (float *) SUMA_calloc (N_V, sizeof(float));
   iV = (int *) SUMA_calloc (N_V, sizeof(int));
   if (!V || !iV) {
      fprintf (SUMA_STDERR,"Error %s: Could not allocate for V or iV.\n", FuncName);
      exit(1);
   }
   
   if (icol < 0) {
     for (ii=0; ii < N_V; ++ii) {
         iV[ii] = ii; 
         V[ii] = far[vcol*N_V+ii]; 
     } 
   } else {
      for (ii=0; ii < N_V; ++ii) {
         iV[ii] = (int)far[icol*N_V+ii]; 
         V[ii] = far[vcol*N_V+ii]; 
      }
   }
   
   mri_free(im); im = NULL;

   /* read values per node */
   /* SUMA_disp_vect (V, 3);  */
   
   /* find the min/max of V */
   SUMA_MIN_MAX_VEC(V, N_V, Vmin, Vmax, Vminloc, Vmaxloc)
   /* fprintf (SUMA_STDERR,"%s: Vmin=%f, Vmax = %f\n", FuncName, Vmin, Vmax);*/ 
   
   if (arange == 0.0) {
      if (fabs((double)Vmin) > fabs((double)Vmax)) arange = (float)fabs((double)Vmin);
      else arange = (float)fabs((double)Vmax);
   }
   /* figure out the range if PercRange is used */
   if (ApplyPercClip) {
      
      fprintf (SUMA_STDERR,"%s: Percentile range [%f..%f] is equivalent to ", FuncName, IntRange[0], IntRange[1]);
      Vsort = SUMA_PercRange (V, NULL, N_V, IntRange, IntRange, NULL);
      fprintf (SUMA_STDERR,"[%f..%f]\n", IntRange[0], IntRange[1]);
      ApplyClip = YUP;
      
      if (Vsort) SUMA_free(Vsort);
      else {
         fprintf (SUMA_STDERR,"Error %s: Error in SUMA_PercRange.\n", FuncName);
         exit(1);
      }
   }
   
   
   /* get the options for creating the scaled color mapping */
   OptScl = SUMA_ScaleToMapOptInit();
   if (!OptScl) {
      fprintf (SUMA_STDERR,
               "Error %s: Could not get scaling option structure.\n", FuncName);
      exit (1); 
   }
   
   /* work the options a bit */
   if (ApplyMask) {
      OptScl->ApplyMask = ApplyMask;
      OptScl->MaskRange[0] = MaskRange[0]; 
      OptScl->MaskRange[1] = MaskRange[1]; 
      OptScl->MaskColor[0] = MaskColor[0]; 
      OptScl->MaskColor[1] = MaskColor[1]; 
      OptScl->MaskColor[2] = MaskColor[2];
   }
   
   if (ApplyClip) {
      OptScl->ApplyClip = YUP;
      OptScl->IntRange[0] = IntRange[0]; OptScl->IntRange[1] = IntRange[1];
   }

   OptScl->interpmode = interpmode;
   
   OptScl->BrightFact = brfact;
   
   if (MaskZero) OptScl->MaskZero = YUP;
      
   /* map the values in V to the colormap */
      /* allocate space for the result */
      SV = SUMA_Create_ColorScaledVect(N_V, 0);
      if (!SV) {
         fprintf (SUMA_STDERR,
                  "Error %s: Could not allocate for SV.\n", FuncName);
         exit(1);
      }
      
      /* finally ! */
      if (alaAFNI) {
         if (LocalHead) {
            fprintf (SUMA_STDERR,
                     "%s: Calling SUMA_ScaleToMap_alaAFNI\n", FuncName);
            fprintf (SUMA_STDERR,"%s: arange = %f\n",  FuncName, arange);
         }
         if (CM->frac) {
            if (CM->frac[0] > 0 && CM->Sgn == -1) {
               SUMA_S_Err ("Color map fractions positive with -anr option");
               exit(1);
            }
            if (CM->frac[0] < 0 && CM->Sgn == 1) {
               SUMA_S_Err ("Color map fractions negative with -apr option");
               exit(1);
            }
         }
      
         if (Sgn) {
            if (Sgn != CM->Sgn) {
               SUMA_S_Warn ("Mixing positive maps (all fractions > 0) "
                            "with -anr option\n"
                            "or vice versa. That is allowed but know what"
                            " you're doing.\n");
            }
         }
         if (!SUMA_ScaleToMap_alaAFNI (V, N_V, arange, CM, OptScl, SV)) {
            fprintf (SUMA_STDERR,
               "Error %s: Failed in SUMA_ScaleToMap_alaAFNI.\n", FuncName);
            exit(1);
         }
      } else {
         if (LocalHead) 
            fprintf (SUMA_STDERR,"%s: Calling SUMA_ScaleToMap\n", FuncName);
         if (!SUMA_ScaleToMap (V, N_V, Vmin, Vmax, CM, OptScl, SV)) {
            fprintf (SUMA_STDERR,
                     "Error %s: Failed in SUMA_ScaleToMap.\n", FuncName);
            exit(1);
         }
      }
   
   /* Now write the colored vector back to disk */
   if (NoMaskCol) {
      for (k=0; k < N_V; ++k) {
         k3 = 3*k;
         if (!SV->isMasked[k]) 
            fprintf (SUMA_STDOUT, "%d %f %f %f\n", 
                     iV[k], SV->cV[k3  ], SV->cV[k3+1], SV->cV[k3+2]);
      }
   } else {
      for (k=0; k < N_V; ++k) {
         k3 = 3*k;
         fprintf (SUMA_STDOUT, "%d %f %f %f\n", 
                  iV[k], SV->cV[k3  ], SV->cV[k3+1], SV->cV[k3+2]);
      }
   }
   
   /* freeing time */
   if (V) SUMA_free(V);
   if (iV) SUMA_free(iV);
   if (!FromAFNI && freecm) if (CM) SUMA_Free_ColorMap (CM); /* only free CM if 
                                       it was a pointer copy from a map in SAC */
   if (OptScl) SUMA_free(OptScl);
   if (SV) SUMA_Free_ColorScaledVect (SV);
   #if 0
      if (SAC) SAC = SUMA_DestroyAfniColors(SAC); /* destroy SAC */
   #else
      SAC = NULL; /* freeing is done in SUMAg_CF */
   #endif
   SUMA_Free_CommonFields(SUMAg_CF); 
   
   SUMA_RETURN (0);
}   
Example #14
0
int main( int argc , char * argv[] )
{
   int lin , kim , kbot,ktop , nx,ny , npix , ii ,
       lbase , lup,ldown ;
   MRI_IMAGE ** stat_ret ;
   MRI_IMAGE * imb=NULL ;
   float     * bar , * bav ;

   printf(
    "MCW SFIM: Stepwise Functional IMages, by RW Cox\n") ;

   if( argc < 2 ) SFIM_syntax("type sfim -help for usage details") ;
   else if( strcmp(argv[1],"-help") == 0 ) SFIM_syntax(NULL) ;

   machdep() ;

   SFIM_getopts( argc , argv ) ;

   /*----- average over each interval -----*/

   nx = SF_imts->imarr[0]->nx ;
   ny = SF_imts->imarr[0]->ny ; npix = nx * ny ;

   lin = 0 ; kbot = 0 ;
   do {
      ktop = kbot + SF_int[lin].count ;
      if( ktop > SF_imts->num ) ktop = SF_imts->num ;

      if( isalpha(SF_int[lin].name[0]) ){     /* average if a good name */
         for( kim=kbot ; kim < ktop ; kim++ )
           (void) mri_stat_seq( SF_imts->imarr[kim] ) ;

         stat_ret         = mri_stat_seq( NULL ) ;
         SF_int[lin].avim = stat_ret[0] ;
         SF_int[lin].sdim = stat_ret[1] ;
      }

      kbot = ktop ; lin ++ ;
   } while( SF_int[lin].count > 0 && kbot < SF_imts->num ) ;
   SF_numint = lin ;

   /*----- find the number of base intervals -----*/

   lbase = 0 ;
   for( lin=0 ; lin < SF_numint ; lin++ )
      if( strcmp(SF_int[lin].name,SF_bname) == 0 ) lbase++ ;

   /* no bases --> write averages out now and quit */

   if( lbase <= 0 ){
      printf("** no 'base' intervals --> task means not adjusted\n") ;
      SFIM_write_avs() ;
      exit(0) ;
   }

   /* bases yes, but not localbase --> compute global average of bases */

   if( ! SF_localbase ){
      int knum = 0 ;

      kbot = 0 ;
      for( lin=0 ; lin < SF_numint ; lin++ ){
         ktop = kbot + SF_int[lin].count ;
         if( ktop > SF_imts->num ) ktop = SF_imts->num ;
         if( strcmp(SF_int[lin].name,SF_bname) == 0 ){  /* if a base */
            for( kim=kbot ; kim < ktop ; kim++ ){
               (void) mri_stat_seq( SF_imts->imarr[kim] ) ; /* average in */
               knum ++ ;
            }
         }
         kbot = ktop ;
      }
      stat_ret = mri_stat_seq( NULL ) ;
      imb      = stat_ret[0] ;           /* average of all bases */
      mri_free( stat_ret[1] ) ;          /* don't keep st. dev.  */

      printf("** global base = average of %d images\n",knum) ;
   }

   /*----- for each non-base interval,
           subtract the relevant base average -----*/

   for( lin=0 ; lin < SF_numint ; lin++ ){
      int free_imb = 0 ;

      if( !isalpha(SF_int[lin].name[0]) ||
          strcmp(SF_int[lin].name,SF_bname) == 0 ) continue ;  /* skip this */

      if( SF_localbase ){
         for( lup=lin+1 ; lup < SF_numint ; lup++ )  /* look for a base above */
            if( strcmp(SF_int[lup].name,SF_bname) == 0 ) break ;

         for( ldown=lin-1 ; ldown >=0 ; ldown-- )    /* look for a base below */
            if( strcmp(SF_int[ldown].name,SF_bname) == 0 ) break ;

         if( ldown < 0 && lup >= SF_numint ){  /* no base?  an error! */
            fprintf(stderr,"*** can't find base above or below at lin=%d\n",lin) ;
            SFIM_syntax("INTERNAL ERROR -- should not occur!") ;
         }

         /* if only have one neighbor, use it, otherwise make average */

         if( ldown <  0         ){
            imb = SF_int[lup].avim ; free_imb = 0 ;
            printf("** local base for %s = average of %d images above\n",
                   SF_int[lin].name , SF_int[lup].count ) ;
         }
         else if( lup   >= SF_numint ){
            imb = SF_int[ldown].avim ; free_imb = 0 ;
            printf("** local base for %s = average of %d images below\n",
                   SF_int[lin].name , SF_int[ldown].count ) ;
         }
         else {
            float * bup , * bdown ;
            bup   = mri_data_pointer( SF_int[lup].avim ) ;
            bdown = mri_data_pointer( SF_int[ldown].avim ) ;
            imb   = mri_new( nx , ny , MRI_float ) ; free_imb = 1 ;
            bar   = mri_data_pointer( imb ) ;
            for( ii=0 ; ii < npix ; ii++ )
               bar[ii] = 0.5 * ( bup[ii] + bdown[ii] ) ;

            printf("** local base for %s = average of %d below, %d above\n",
                   SF_int[lin].name, SF_int[ldown].count, SF_int[lup].count ) ;
         }
      }

      /* subtract imb (base average) from current interval average */

      bar = mri_data_pointer( imb ) ;
      bav = mri_data_pointer( SF_int[lin].avim ) ;
      for( ii=0 ; ii < npix ; ii++ ) bav[ii] -= bar[ii] ;

      if( SF_localbase && free_imb ) mri_free( imb ) ;
   }

   /*----- now write the averages out -----*/

   SFIM_write_avs() ;
   exit(0) ;
}
void initialize_program
(
    int * im1,               /* index of 1st image in time series for analysis */
    char ** nname,           /* noise model name */
    char ** sname,           /* signal model name */
    vfp * nmodel,            /* pointer to noise model */
    vfp * smodel,            /* pointer to signal model */
    int * r,                 /* number of parameters in the noise model */
    int * p,                 /* number of parameters in the signal model */
    char *** npname,         /* noise parameter names */
    char *** spname,         /* signal parameter names */
    float ** min_nconstr,    /* minimum parameter constraints for noise model */
    float ** max_nconstr,    /* maximum parameter constraints for noise model */
    float ** min_sconstr,    /* minimum parameter constraints for signal model */
    float ** max_sconstr,    /* maximum parameter constraints for signal model */
    int * nabs,              /* use absolute constraints for noise parameters */
    int * nrand,             /* number of random vectors to generate */
    int * nbest,             /* number of random vectors to keep */
    float * rms_min,         /* minimum rms error to reject reduced model */

    float ** par_rdcd,       /* estimated parameters for the reduced model */
    float ** par_full,       /* estimated parameters for the full model */
    float ** tpar_full,      /* t-statistic of parameters in the full model */

    int ts_length,           /* length of time series data */
    char ** tfilename,       /* file name for time point series */
    float *** x_array,       /* independent variable matrix */

    float ** fit
)

{
    int dimension;           /* dimension of full model */
    int ip;                  /* parameter index */
    int it;                  /* time index */
    MRI_IMAGE * im, * flim;  /* pointers to image structures
                              -- used to read 1D ASCII */
    int nt;                  /* number of points in 1D x data file */
    float * tar;


    /*----- intialize options -----*/
    initialize_options (im1, nname, sname, nmodel, smodel, r, p, npname, spname,
                        min_nconstr, max_nconstr, min_sconstr, max_sconstr,
                        nabs, nrand, nbest, rms_min, tfilename);

    /*----- check for valid inputs -----*/
    check_for_valid_inputs ();


    /*----- allocate space for independent variable matrix -----*/
    *x_array = (float **) malloc (sizeof(float *) * ts_length);
    if (*x_array == NULL)
        NLfit_error ("Unable to allocate memory for x_array");
    for (it = 0;  it < ts_length;  it++)
    {
        (*x_array)[it] = (float *) malloc (sizeof(float) * 3);
        if ((*x_array)[it] == NULL)
            NLfit_error ("Unable to allocate memory for x_array[it]");
    }

    /*----- initialize independent variable matrix -----*/
    if (!plug_timeref)
    {
        static float old_DELT = -1.0 ;
        DELT = (inTR && dsTR > 0.0) ? dsTR : 1.0 ;  /* 22 July 1998 */
        if( DELT != old_DELT ) {
            old_DELT = DELT ;
            printf("NLfit: switch to TR = %g\n",DELT) ;
        }

        for (it = 0;  it < ts_length;  it++)
        {
            (*x_array)[it][0] = 1.0;
            (*x_array)[it][1] = it * DELT;
            (*x_array)[it][2] = (it * DELT) * (it * DELT);
        }
    }
    else
    {
        flim = mri_read_1D (*tfilename);
        if (flim == NULL)
            NLfit_error ("Unable to read time reference file \n");
        nt = flim -> nx;
        if (nt < ts_length)
            NLfit_error ("Time reference array is too short");
        tar = MRI_FLOAT_PTR(flim) ;
        for (it = 0;  it < ts_length;  it++)
        {
            (*x_array)[it][0] = 1.0;
            (*x_array)[it][1] = tar[it] ;
            (*x_array)[it][2] = tar[it] * tar[it];
        }
        mri_free (flim);
    }

    /*--- 24 Jul 2006: special change to x_array[][2] for Linear+Ort [RWCox] ---*/
    if( strcmp(*nname,"Linear+Ort") == 0 ) {
        char *fname=NULL;
        MRI_IMAGE *fim=NULL;
        int nx;
        float *far;
        static int nwarn=0;
        fname = my_getenv("AFNI_ORTMODEL_REF") ;
        if( fname == NULL ) {
            ERROR_message("Linear+Ort model: 'AFNI_ORTMODEL_REF' not set") ;
            goto PLO_done ;
        }

        fim = mri_read_1D(fname) ;
        if( fim == NULL || fim->nx < 2 ) {
            ERROR_message(
                "Linear+Ort model: can't read AFNI_ORTMODEL_REF='%s'",fname) ;
            goto PLO_done ;
        }

        if( fim->ny > 1 && nwarn < 2 ) {
            WARNING_message(
                "Linear+Ort model: file AFNI_ORTMODEL_REF='%s' has more than 1 column",
                fname ) ;
            nwarn++ ;
        }

        nx = fim->nx ;
        far = MRI_FLOAT_PTR(fim) ;
        if( nx != ts_length && nwarn ) {
            WARNING_message("Linear+Ort: length(%s)=%d but length(dataset)=%d",
                            fname , nx , ts_length ) ;
            nwarn++ ;
        }
        for( it=0 ; it < ts_length;  it++)
            (*x_array)[it][2] = (it < nx) ? far[it] : 0.0f ;

PLO_done: ; /* nada */
    }


    dimension = (*r) + (*p);

    /*----- allocate memory space -----*/
    *par_rdcd = (float *) malloc (sizeof(float) * dimension);
    if (*par_rdcd == NULL)
        NLfit_error ("Unable to allocate memory for par_rdcd");
    *par_full = (float *) malloc (sizeof(float) * dimension);
    if (*par_full == NULL)
        NLfit_error ("Unable to allocate memory for par_full");
    *tpar_full = (float *) malloc (sizeof(float) * dimension);
    if (*tpar_full == NULL)
        NLfit_error ("Unable to allocate memory for tpar_full");
    *fit = (float *) malloc (sizeof(float) * (ts_length));
    if (*fit == NULL)
        NLfit_error ("Unable to allocate memory for fit");

}
Example #16
0
int main( int argc , char * argv[] )
{
   /* --- variable declarations --- */
   THD_3dim_dataset * dset ;
   THD_diskptr * dskptr;
   int nx, ny, nz, nv, itim;
   Boolean verbose, nsize;
   int ok;
   MRI_IMAGE * im, * im2d, * tim2d;
   MRI_TYPE kind;
   int ibr, iz, count, izz,izsub ;
   int zfirst, zlast, tfirst, tlast;
   char input_filename[THD_MAX_NAME],
        prefix_filename[THD_MAX_NAME], 
        output_filename[THD_MAX_NAME],
        str[THD_MAX_NAME];

   /* --- get user command line inputs --- */
   F3D_initialize_user_data (argc, argv, 
      &verbose, &nsize,
      &zfirst, &zlast, &tfirst, &tlast,
      input_filename, prefix_filename );
      
   /* --- open 3d data set --- */
   dset = THD_open_one_dataset( input_filename ) ;
   if( dset == NULL )  FatalError ("Unable to open input file") ;
   if ( verbose )  printf("EPsim: 3d Dataset File = %s\n" , input_filename ) ; 
      
   /* --- load data block --- */
   ok = THD_load_datablock( dset->dblk );
   if ( !ok )  FatalError ("Unable to load data block") ;

   /* --- get data dimensions --- */
   dskptr = dset->dblk->diskptr;
   nx = dskptr->dimsizes[0];
   ny = dskptr->dimsizes[1];
   nz = dskptr->dimsizes[2];
   nv = dskptr->nvals;
   if ( verbose )  
      printf ("EPsim: nx=%d  ny=%d  nz=%d  nv=%d\n",   nx, ny, nz, nv);

   /* --- check for valid user inputs --- */
   if (zfirst < 1) zfirst = 1;
   if (zlast > nz) zlast = nz;
   if (tfirst < 1) tfirst = 1;
   if (tlast > nv) tlast = nv;
   if (zfirst > nz)  FatalError ("No data selected -- zfirst too large.");
   if (zlast < 1)    FatalError ("No data selected -- zlast too small.");
   if (tfirst > nv)  FatalError ("No data selected -- tfirst too large.");
   if (tlast < 1)    FatalError ("No data selected -- tlast too small.");    

   /* --- get data type --- */
   kind = IMAGE_IN_IMARR ( dset->dblk->brick, 0 ) -> kind;
   if ( verbose )  printf ("EPsim: datum = %s \n", MRI_TYPE_name[kind]);

   /* --- create 2d data pointer --- */
   im2d = mri_new_vol_empty ( nx, ny, 1, kind );

   /*** open channel to AFNI ***/

   sprintf( buf , "tcp:%s:%d" , host , get_port_named("CONTROL_PORT") ) ;
   ioc = iochan_init( buf , "create" ) ;
   if( ioc == NULL ) FatalError("Cannot open control channel to AFNI") ;

   if( verbose ) printf("EPsim: waiting for AFNI") ; fflush(stdout) ;

   while(1){
      iz = iochan_goodcheck( ioc , 1000 ) ;
      if( iz < 0 ) FatalError("control channel failed") ;
      if( iz > 0 ) break ;
      if( verbose ){ printf(".") ; fflush(stdout) ; }
   }
   if( verbose ){ printf("!\n") ; fflush(stdout) ; }

   if( use_shm ) strcpy( buf , SHM_NAME ) ;
   else          sprintf(buf , "tcp:%s:%d" , 
                         host , get_port_named("AFNI_PLUGOUT_TCP_BASE") ) ;

   if( use_child ){
      jj = strlen(buf) ;
      sprintf(buf+jj,"\ncat epsim.out") ;
   } else if( use_3T ){
      jj = strlen(buf) ;
      sprintf(buf+jj,"\n3T_toafni -dummy < %s" , fname_3T ) ;
   }

   if( verbose ) printf("sending control data: %s\n",buf) ;

   jj = iochan_sendall( ioc , buf , strlen(buf)+1 ) ;
   if( jj < 0 ) FatalError("send control data failed") ;
   iochan_sleep(LONG_DELAY) ;                      /* wait a bit */
   while( ! iochan_clearcheck(ioc,LONG_DELAY) )    /* loop until cleared */
      iochan_sleep(LONG_DELAY) ;

   if( verbose ) printf("EPsim: closing control channel\n") ;
   IOCHAN_CLOSE(ioc) ;

   /*** now open data channel ***/

   ioc = iochan_init( buf , "create" ) ;
   if( ioc == NULL ) FatalError("Cannot open data channel to AFNI") ;

   if( verbose ) printf("EPsim: waiting for AFNI") ; fflush(stdout) ;

   while(1){
      iz = iochan_goodcheck( ioc , 1000 ) ;
      if( iz < 0 ) FatalError("data channel failed") ;
      if( iz > 0 ) break ;
      if( verbose ){ printf(".") ; fflush(stdout) ; }
   }
   if( verbose ){ printf("!\n") ; fflush(stdout) ; }

   if( use_child ){
      FILE * fp = fopen( "epsim.out" , "w" ) ;
      if( fp == NULL ){fprintf(stderr,"Can't open epsim.out!\n");IOCHAN_CLOSE(ioc);exit(1);}
      fprintf( fp ,  "ZNUM %d\n"
                     "ZDELTA %g\n"
                     "XYFOV %g %g\n"
                     "ZFIRST %g%c\n"
                     "ZORDER seq\n"
                     "XYZAXES %s %s %s\n"
                     "ACQUISITION_TYPE %s\n"
                   ,
                     nz ,
                     fabs(dset->daxes->zzdel) ,
                     fabs(dset->daxes->xxdel)*nx , fabs(dset->daxes->yydel)*ny ,
                     fabs(dset->daxes->zzorg) , ORIENT_first[dset->daxes->zzorient] ,
                     ORIENT_shortstr[dset->daxes->xxorient] ,
                       ORIENT_shortstr[dset->daxes->yyorient] ,
                       ORIENT_shortstr[dset->daxes->zzorient] ,
                     ( ((zlast-zfirst)>0) ? "2D+zt" : "2D+z" )
                   ) ;
      fclose(fp) ;
      if( verbose ) printf("EPsim: wrote epsim.out file\n") ;

      sprintf( buf , "XYMATRIX %d %d\n"
                     "DATUM %s\n"
                   ,
                     nx , ny ,
                     MRI_TYPE_name[kind]
                   ) ;
   } else if( use_3T ){
      sprintf( buf , "XYMATRIX %d %d\n"
                     "DATUM %s\n"
                   ,
                     nx , ny ,
                     MRI_TYPE_name[kind]
                   ) ;
   } else {
      sprintf( buf , "ZNUM %d\n"
                     "ZDELTA %g\n"
                     "XYFOV %g %g\n"
                     "ZFIRST %g%c\n"
                     "ZORDER seq\n"
                     "XYZAXES %s %s %s\n"
                     "ACQUISITION_TYPE %s\n"
                     "XYMATRIX %d %d\n"
                     "DATUM %s\n"
                   ,
                     nz ,
                     fabs(dset->daxes->zzdel) ,
                     fabs(dset->daxes->xxdel)*nx , fabs(dset->daxes->yydel)*ny ,
                     fabs(dset->daxes->zzorg) , ORIENT_first[dset->daxes->zzorient] ,
                     ORIENT_shortstr[dset->daxes->xxorient] ,
                       ORIENT_shortstr[dset->daxes->yyorient] ,
                       ORIENT_shortstr[dset->daxes->zzorient] ,
                     ( ((zlast-zfirst)>0) ? "2D+zt" : "2D+z" ) ,
                     nx , ny ,
                     MRI_TYPE_name[kind]
                   ) ;
   }

   nbytes = im2d->nvox * im2d->pixel_size ;

   for( itim=0 ; itim < ntimes ; itim++ ){
   count = 0;

   if( use_3T ) izsub = (nz%2 == 0) ? (nz-1) : (nz) ;

   for ( ibr = tfirst-1 ; ibr < tlast ; ibr++ )
   {
      for ( iz = zfirst-1 ; iz < zlast ; iz++ )
      {
         /* --- set 2d data pointer into 3d data set --- */
         im = IMAGE_IN_IMARR ( dset->dblk->brick, ibr ); 

         if( use_3T ){
           izz = 2*iz ; if( izz >= nz ) izz -= izsub ;  /* alt ordering */
         } else {
           izz = iz ;                                   /* seq ordering */
         }

         switch ( kind )
         {
            case MRI_byte :
               mri_set_data_pointer(im2d, MRI_BYTE_PTR(im) + iz*nx*ny) ;
            break;
            case MRI_short :
               mri_set_data_pointer(im2d, MRI_SHORT_PTR(im) + iz*nx*ny) ;
            break;
            case MRI_int :
               mri_set_data_pointer(im2d, MRI_INT_PTR(im) + iz*nx*ny) ;
            break;
            case MRI_float :
               mri_set_data_pointer(im2d, MRI_FLOAT_PTR(im) + iz*nx*ny) ;
            break;
            case MRI_double :
               mri_set_data_pointer(im2d, MRI_DOUBLE_PTR(im) + iz*nx*ny) ;
            break;
            case MRI_complex :
               mri_set_data_pointer(im2d, MRI_COMPLEX_PTR(im) + iz*nx*ny) ;
            break;
            case MRI_rgb :
               mri_set_data_pointer(im2d, MRI_RGB_PTR(im) + 3*iz*nx*ny) ;
            break;
            default :
               FatalError ("Illegal data type encountered.");
         } 

#if 0
         /* --- create 2d data file name --- */
         strcpy ( output_filename, prefix_filename );
         if ( nv > 1 )  
            sprintf ( str, "%02d.%04d", izz+1, ibr+1 );
         else
            if ( nz > 999 )
               sprintf ( str, ".%04d", izz+1 );
            else
               sprintf ( str, ".%03d", izz+1 );
         strcat ( output_filename, str );
#endif

         if( first ){
            if( verbose )
               printf("EPsim: sending this data as header info in image channel:\n%s\n",buf) ;
            jj = iochan_sendall( ioc , buf , strlen(buf)+1 ) ;
            if( jj < 0 ) FatalError("send header info failed") ;
            first = 0 ;
         }
 
         if ( verbose )
            printf ( "EPsim: sending 2D image izz=%d ibr=%d\n", izz,ibr ); 

         jj = iochan_sendall( ioc , mri_data_pointer(im2d) , nbytes ) ;
         if( jj < 0 ) FatalError("send image failed") ;
         iochan_sleep( delay ) ;

#if 0
         if ( !nsize )
            ok = mri_write ( output_filename, im2d );
         else
         {
            tim2d = mri_nsize (im2d);
            ok = mri_write ( output_filename, tim2d);
            mri_free (tim2d);
         }
#endif
         
         count ++ ;

      }  /* --- iz --- */
   }  /* --- ibr --- */ 
   sleep(20) ;
   } /* -- itim --*/

   if ( verbose )  printf ("Sent %d 2D images. \n", count);

   if( verbose ){ printf("Waiting for AFNI") ; fflush(stdout) ; }
   while(1){
      jj = iochan_clearcheck(ioc,1000) ;
      if( jj ) break ;
      if( verbose ){ printf(".") ; fflush(stdout) ; }
   }
   if( verbose ) printf("!\n") ;
   iochan_sleep(100) ; IOCHAN_CLOSE(ioc) ;

   exit(0) ;
}
Example #17
0
int main( int argc , char * argv[] )
{
   int iarg , pos = 0 ;
   float thresh=0.0 ;
   MRI_IMAGE * maskim=NULL , *imin , *imout ;
   float * maskar ;
   int nxim , nyim , ii , npix ;

   if( argc < 3 || strncmp(argv[1],"-help",4) == 0 ){
      printf("Usage: immask [-thresh #] [-mask mask_image] [-pos] input_image output_image\n"
             "* Masks the input_image and produces the output_image;\n"
             "* Use of -thresh # means all pixels with absolute value below # in\n"
             "   input_image will be set to zero in the output_image\n"
             "* Use of -mask mask_image means that only locations that are nonzero\n"
             "   in the mask_image will be nonzero in the output_image\n"
             "* Use of -pos means only positive pixels from input_image will be used\n"
             "* At least one of -thresh, -mask, -pos must be used; more than one is OK.\n"
            ) ;
     exit(0) ;
   }

   machdep() ;

   iarg = 1 ;
   while( iarg < argc && argv[iarg][0] == '-' ){

      /*** -pos ***/

      if( strncmp(argv[iarg],"-pos",4) == 0 ){
         pos = 1 ;
         iarg++ ; continue ;
      }

      /*** -thresh # ***/

      if( strncmp(argv[iarg],"-thresh",5) == 0 ){
         thresh = strtod( argv[++iarg] , NULL ) ;
         if( iarg >= argc || thresh <= 0.0 ){
            fprintf(stderr,"Illegal -thresh!\a\n") ; exit(1) ;
         }
         iarg++ ; continue ;
      }

      if( strncmp(argv[iarg],"-mask",5) == 0 ){
         maskim = mri_read_just_one( argv[++iarg] ) ;
         if( maskim == NULL || iarg >= argc || ! MRI_IS_2D(maskim) ){
            fprintf(stderr,"Illegal -mask!\a\n") ; exit(1) ;
         }
         if( maskim->kind != MRI_float ){
            imin = mri_to_float( maskim ) ;
            mri_free( maskim ) ;
            maskim = imin ;
         }
         iarg++ ; continue ;
      }

      fprintf(stderr,"** Illegal option: %s\a\n",argv[iarg]) ;
      exit(1) ;
   }
   if( thresh <= 0.0 && maskim == NULL && pos == 0 ){
      fprintf(stderr,"No -thresh, -mask, -pos ==> can't go on!\a\n") ; exit(1) ;
   }
   if( iarg+1 >= argc ){
      fprintf(stderr,"Must have input_image and output_image on command line!\a\n") ;
      exit(1) ;
   }

   imin = mri_read_just_one( argv[iarg++] ) ;
   if( imin == NULL ) exit(1) ;
   if( ! MRI_IS_2D(imin) ){
      fprintf(stderr,"can only process 2D images!\a\n") ;
      exit(1) ;
   }

   nxim = imin->nx ;
   nyim = imin->ny ;
   npix = nxim * nyim ;

   if( maskim == NULL ){
      maskim = mri_new( nxim , nyim , MRI_float ) ;
      maskar = MRI_FLOAT_PTR(maskim) ;
      for( ii=0 ; ii < npix ; ii++ ) maskar[ii] = 1.0 ;
   } else if( maskim->nx != nxim || maskim->ny != nyim ){
      fprintf(stderr,"Mask and input image not same size!\a\n") ;
      exit(1) ;
   } else {
      maskar = MRI_FLOAT_PTR(maskim) ;
   }
   imout = mri_new( nxim , nyim , imin->kind ) ;

   switch( imin->kind ){

      default:
         fprintf(stderr,"Unrecognized input image type!\a\n") ;
         exit(1) ;

      case MRI_byte:{
         byte * arin , * arout , val ;
         arin  = mri_data_pointer(imin) ;
         arout = mri_data_pointer(imout) ;
         for( ii=0 ; ii < npix ; ii++ ){
            val = arin[ii] ;
            if( maskar[ii] != 0.0 && ABS(val) >= thresh ) arout[ii] = val ;
            else                                          arout[ii] = 0 ;
         }
      } break ;

      case MRI_short:{
         short * arin , * arout , val ;
         arin  = mri_data_pointer(imin) ;
         arout = mri_data_pointer(imout) ;
         for( ii=0 ; ii < npix ; ii++ ){
            val = arin[ii] ;
            if( maskar[ii] != 0.0 && ABS(val) >= thresh ) arout[ii] = val ;
            else                                          arout[ii] = 0 ;
         }
         if( pos ) for( ii=0 ; ii < npix ; ii++ ) if( arout[ii] < 0 ) arout[ii] = 0 ;
      } break ;

      case MRI_float:{
         float * arin , * arout , val ;
         arin  = mri_data_pointer(imin) ;
         arout = mri_data_pointer(imout) ;
         for( ii=0 ; ii < npix ; ii++ ){
            val = arin[ii] ;
            if( maskar[ii] != 0.0 && ABS(val) >= thresh ) arout[ii] = val ;
            else                                          arout[ii] = 0 ;
         }
         if( pos ) for( ii=0 ; ii < npix ; ii++ ) if( arout[ii] < 0 ) arout[ii] = 0 ;
      } break ;

      case MRI_int:{
         int * arin , * arout , val ;
         arin  = mri_data_pointer(imin) ;
         arout = mri_data_pointer(imout) ;
         for( ii=0 ; ii < npix ; ii++ ){
            val = arin[ii] ;
            if( maskar[ii] != 0.0 && ABS(val) >= thresh ) arout[ii] = val ;
            else                                          arout[ii] = 0 ;
         }
         if( pos ) for( ii=0 ; ii < npix ; ii++ ) if( arout[ii] < 0 ) arout[ii] = 0 ;
      } break ;

      case MRI_double:{
         double * arin , * arout , val ;
         arin  = mri_data_pointer(imin) ;
         arout = mri_data_pointer(imout) ;
         for( ii=0 ; ii < npix ; ii++ ){
            val = arin[ii] ;
            if( maskar[ii] != 0.0 && ABS(val) >= thresh ) arout[ii] = val ;
            else                                          arout[ii] = 0 ;
         }
         if( pos ) for( ii=0 ; ii < npix ; ii++ ) if( arout[ii] < 0 ) arout[ii] = 0 ;
      } break ;

      case MRI_complex:{
         complex * arin , * arout , val ;
         arin  = mri_data_pointer(imin) ;
         arout = mri_data_pointer(imout) ;
         for( ii=0 ; ii < npix ; ii++ ){
            val = arin[ii] ;
            if( maskar[ii] != 0.0 && CABS(val) >= thresh ) arout[ii] = val ;
            else                                           arout[ii] = CMPLX(0,0) ;
         }
      } break ;
   }

   mri_write( argv[iarg] , imout ) ;
   exit(0) ;
}
Example #18
0
int main( int argc , char * argv[] )
{
   char prefix[255]="obi-wan-kenobi" , fname[255] ;
   int datum = -1 ;
   int iarg = 1 ;
   int gnim , nx , ny , nz , kz ;
   char ** gname ;
   MRI_IMARR * arr ;
   MRI_IMAGE * im , * qim ;
   FILE * fp ;

   /***** help? *****/

   if( argc < 2 || strcmp(argv[1],"-help") == 0 ){
      printf(
       "Usage: imstack [options] image_filenames ...\n"
       "Stacks up a set of 2D images into one big file (a la MGH).\n"
       "Options:\n"
       "  -datum type   Converts the output data file to be 'type',\n"
       "                  which is either 'short' or 'float'.\n"
       "                  The default type is the type of the first image.\n"
       "  -prefix name  Names the output files to be 'name'.b'type' and 'name'.hdr.\n"
       "                  The default name is 'obi-wan-kenobi'.\n"
      ) ;

      exit(0) ;
   }

   machdep() ;

   /***** scan for option *****/

   while( iarg < argc && argv[iarg][0] == '-' ){

      /*** -datum ***/

      if( strcmp(argv[iarg],"-datum") == 0 ){
         if( ++iarg >= argc ){
            fprintf(stderr,"-datum needs a type!\n") ; exit(1) ;
         }
         if( strcmp(argv[iarg],"short") == 0 ){
            datum = MRI_short ;
         } else if( strcmp(argv[iarg],"float") == 0 ){
            datum = MRI_float ;
         } else {
            fprintf(stderr,"-datum %s is illegal!\n",argv[iarg]) ; exit(1) ;
         }
         iarg++ ; continue ;
      }

      /*** -prefix ***/

      if( strcmp(argv[iarg],"-prefix") == 0 ){
         if( ++iarg >= argc ){
            fprintf(stderr,"-prefix needs a name!\n") ; exit(1) ;
         }
         strcpy(prefix,argv[iarg]) ;
         iarg++ ; continue ;
      }

      /*** ERROR ***/

      fprintf(stderr,"Unrecognized option: %s\n",argv[iarg]) ; exit(1) ;
   }

   /***** Check if any filenames left *****/

   if( iarg >= argc ){
      fprintf(stderr,"No input image filenames?!\n") ; exit(1) ;
   }

   /***** Perform filename expansion on the input list *****/

   MCW_warn_expand(1) ;
   MCW_file_expand( argc - iarg , argv + iarg , &gnim , &gname ) ;
   MCW_warn_expand(0) ;

   if( gnim < 1 ){
      fprintf(stderr,"Filename expansion fails on input filenames?!\n") ; exit(1) ;
   }

   /***** Read all files *****/

   arr = mri_read_many_files( gnim , gname ) ;
   if( arr == NULL || IMARR_COUNT(arr) <= 0 ){
      fprintf(stderr,"Can't read input files?!\n") ; exit(1) ;
   }
   MCW_free_expand( gnim , gname ) ;
   fprintf(stderr,"Read in %d 2D slices\n",IMARR_COUNT(arr)) ;

   /***** Set output datum, if not already fixed *****/

   if( datum < 0 ){
      datum = IMARR_SUBIMAGE(arr,0)->kind ;

      if( datum != MRI_short && datum != MRI_float ){
         fprintf(stderr,"Input image type is %s -- you must use -datum!\n",
                 MRI_TYPE_name[datum]) ;
         exit(1) ;
      }
   }

   /***** Check images for equal sizes *****/

   nx = IMARR_SUBIMAGE(arr,0)->nx ;
   ny = IMARR_SUBIMAGE(arr,0)->ny ;
   nz = IMARR_COUNT(arr) ;

   for( kz=1 ; kz < nz ; kz++ ){
      if( IMARR_SUBIMAGE(arr,kz)->nx != nx ||
          IMARR_SUBIMAGE(arr,kz)->ny != ny   ){

         fprintf(stderr,"All images must be the same size (%d x %d)\n",nx,ny) ;
         exit(1) ;
      }
   }

   /***** Write the output brick *****/

   sprintf(fname,"%s.b%s",prefix,MRI_TYPE_name[datum]) ;
   fp = fopen( fname , "w" ) ;
   if( fp == NULL ){
      fprintf(stderr,"Can't open output file %s\n",fname) ; exit(1) ;
   }

   for( kz=0 ; kz < nz ; kz++ ){

      im = IMARR_SUBIMAGE(arr,kz) ;
      if( im->kind != datum ) qim = mri_to_mri( datum , im ) ;
      else                    qim = im ;

      fwrite( mri_data_pointer(qim) , qim->pixel_size , qim->nx * qim->ny , fp ) ;

      if( qim != im ) mri_free(qim) ;
      mri_free(im);
   }
   fclose( fp ) ;
   fprintf(stderr,"Wrote output brick %s\n",fname) ;

   /***** Write the output header *****/

   sprintf(fname,"%s.hdr",prefix) ;
   fp = fopen( fname , "w" ) ;
   if( fp == NULL ){
      fprintf(stderr,"Can't open output file %s\n",fname) ; exit(1) ;
   }

   fprintf( fp , "%d %d %d 0\n" , nx,ny,nz ) ;
   fclose(fp) ;
   fprintf(stderr,"Wrote output header %s: %d %d %d\n",fname,nx,ny,nz) ;

   exit(0) ;
}
Example #19
0
int main( int argc , char * argv[] )
{
   THD_3dim_dataset * dset ;
   THD_dataxes      * daxes ;
   FD_brick        ** brarr , * baxi , * bsag , * bcor ;

   int iarg , ii ;
   Boolean ok ;
   MRI_IMAGE * pim , * flim , * slim ;
   float * flar ;
   dset_range dr ;
   float val , fimfac ;
   int  ival,ityp , kk ;

   float xbot=BIGG,xtop=BIGG , ybot=BIGG,ytop=BIGG , zbot=BIGG,ztop=BIGG ;
   int   xgood=0 , ygood=0 , zgood=0 ,
         proj_code=PROJ_SUM , mirror_code=MIRR_NO , nsize=0 ;
   char  root[THD_MAX_NAME] = "proj." ;
   char  fname[THD_MAX_NAME] ;

   int ixbot=0,ixtop=0 , jybot=0,jytop=0 , kzbot=0,kztop=0 ;
   THD_fvec3 fv ;
   THD_ivec3 iv ;

   /*--- read command line arguments ---*/

   if( argc < 2 || strncmp(argv[1],"-help",6) == 0 ) Syntax() ;

   INIT_EDOPT( &PRED_edopt ) ;
   iarg = 1 ;
   while( iarg < argc && argv[iarg][0] == '-' ){

DB("new arg:",argv[iarg]) ;

      /**** check for editing option ****/

      ii = EDIT_check_argv( argc , argv , iarg , &PRED_edopt ) ;
      if( ii > 0 ){
         iarg += ii ;
         continue ;
      }

      /**** -sum or -max ****/

      if( strncmp(argv[iarg],"-sum",6) == 0 ){
         proj_code = PROJ_SUM ;
         iarg++ ; continue ;
      }

      if( strncmp(argv[iarg],"-max",6) == 0 ){
         proj_code = PROJ_MMAX ;
         iarg++ ; continue ;
      }

      if( strncmp(argv[iarg],"-amax",6) == 0 ){
         proj_code = PROJ_AMAX ;
         iarg++ ; continue ;
      }

      if( strncmp(argv[iarg],"-smax",6) == 0 ){
         proj_code = PROJ_SMAX ;
         iarg++ ; continue ;
      }

      if( strcmp(argv[iarg],"-first") == 0 ){  /* 02 Nov 2000 */
         proj_code = PROJ_FIRST ;
         first_thresh = strtod( argv[++iarg] , NULL ) ;
         iarg++ ; continue ;
      }

      /**** -mirror ****/

      if( strncmp(argv[iarg],"-mirror",6) == 0 ){
         mirror_code = MIRR_YES ;
         iarg++ ; continue ;
      }

      /**** -nsize ****/

      if( strncmp(argv[iarg],"-nsize",6) == 0 ){
         nsize = 1 ;
         iarg++ ; continue ;
      }

      /**** -output root ****/

      if( strncmp(argv[iarg],"-output",6) == 0 ||
          strncmp(argv[iarg],"-root",6)   == 0   ){

         if( iarg+1 >= argc ){
            fprintf(stderr,"\n*** no argument after option %s\n",argv[iarg]) ;
            exit(-1) ;
         }

         MCW_strncpy( root , argv[++iarg] , THD_MAX_NAME-1 ) ;
         ii = strlen(root) ;
         if( ii == 0 ){
            fprintf(stderr,"\n*** illegal rootname!\n") ; exit(-1) ;
         }
         if( root[ii-1] != '.' ){ root[ii] = '.' ; root[ii+1] = '\0' ; }
         iarg++ ; continue ;
      }

      /**** -ALL ****/

      if( strncmp(argv[iarg],"-ALL",6) == 0 ||
          strncmp(argv[iarg],"-all",6) == 0   ){

         xgood = ygood = zgood = 1 ;
         xbot  = ybot  = zbot  = -BIGG ;
         xtop  = ytop  = ztop  =  BIGG ;
         iarg++ ; continue ;
      }

      /**** -RL {all | x1 x2} ****/

      if( strncmp(argv[iarg],"-RL",6) == 0 ||
          strncmp(argv[iarg],"-LR",6) == 0 ||
          strncmp(argv[iarg],"-rl",6) == 0 ||
          strncmp(argv[iarg],"-lr",6) == 0 ||
          strncmp(argv[iarg],"-sag",6)== 0  ){

         char * cerr ; float tf ;

         xgood = 1 ;  /* mark for x projection */

         if( iarg+1 >= argc ){
            fprintf(stderr,"\n*** no argument after option %s\n",argv[iarg]) ;
            exit(-1) ;
         }

         if( strncmp(argv[iarg+1],"all",6) == 0 ||
             strncmp(argv[iarg+1],"ALL",6) == 0   ){

            xbot = -BIGG;
            xtop =  BIGG ;
            iarg += 2 ; continue ;
         }

         if( iarg+2 >= argc ){
            fprintf(stderr,"\n*** no argument after option %s\n",argv[iarg]) ;
            exit(-1) ;
         }

         xbot = strtod( argv[iarg+1] , &cerr ) ;
         if( cerr == argv[iarg+1] ){
            fprintf(stderr,"\n*** illegal argument after %s: %s\n",
                    argv[iarg],argv[iarg+1] ) ; exit(-1) ;
         }
         if( *cerr == 'R' && xbot > 0.0 ) xbot = -xbot ;

         xtop = strtod( argv[iarg+2] , &cerr ) ;
         if( cerr == argv[iarg+2] ){
            fprintf(stderr,"\n*** illegal argument after %s: %s\n",
                    argv[iarg],argv[iarg+2] ) ; exit(-1) ;
         }
         if( *cerr == 'R' && xtop > 0.0 ) xtop = -xtop ;

         if( xbot > xtop ){ tf = xbot ; xbot = xtop ; xtop = tf ; }
         iarg +=3 ; continue ;
      }

      /**** -AP {all | y1 y2} ****/

      if( strncmp(argv[iarg],"-AP",6) == 0 ||
          strncmp(argv[iarg],"-PA",6) == 0 ||
          strncmp(argv[iarg],"-ap",6) == 0 ||
          strncmp(argv[iarg],"-pa",6) == 0 ||
          strncmp(argv[iarg],"-cor",6)== 0  ){

         char * cerr ; float tf ;

         ygood = 1 ;  /* mark for y projection */

         if( iarg+1 >= argc ){
            fprintf(stderr,"\n*** no argument after option %s\n",argv[iarg]) ;
            exit(-1) ;
         }

         if( strncmp(argv[iarg+1],"all",6) == 0 ||
             strncmp(argv[iarg+1],"ALL",6) == 0   ){

            ybot = -BIGG ;
            ytop =  BIGG ;
            iarg += 2 ; continue ;
         }

         if( iarg+2 >= argc ){
            fprintf(stderr,"\n*** no argument after option %s\n",argv[iarg]) ;
            exit(-1) ;
         }

         ybot = strtod( argv[iarg+1] , &cerr ) ;
         if( cerr == argv[iarg+1] ){
            fprintf(stderr,"\n*** illegal argument after %s: %s\n",
                    argv[iarg],argv[iarg+1] ) ; exit(-1) ;
         }
         if( *cerr == 'A' && ybot > 0.0 ) ybot = -ybot ;

         ytop = strtod( argv[iarg+2] , &cerr ) ;
         if( cerr == argv[iarg+2] ){
            fprintf(stderr,"\n*** illegal argument after %s: %s\n",
                    argv[iarg],argv[iarg+2] ) ; exit(-1) ;
         }
         if( *cerr == 'A' && ytop > 0.0 ) ytop = -ytop ;

         if( ybot > ytop ){ tf = ybot ; ybot = ytop ; ytop = tf ; }
         iarg +=3 ; continue ;
      }

      /**** -IS {all | z1 z2} ****/

      if( strncmp(argv[iarg],"-IS",6) == 0 ||
          strncmp(argv[iarg],"-SI",6) == 0 ||
          strncmp(argv[iarg],"-is",6) == 0 ||
          strncmp(argv[iarg],"-si",6) == 0 ||
          strncmp(argv[iarg],"-axi",6)== 0   ){

         char * cerr ; float tf ;

         zgood = 1 ;  /* mark for y projection */

         if( iarg+1 >= argc ){
            fprintf(stderr,"\n*** no argument after option %s\n",argv[iarg]) ;
            exit(-1) ;
         }

         if( strncmp(argv[iarg+1],"all",6) == 0 ||
             strncmp(argv[iarg+1],"ALL",6) == 0   ){

            zbot = -BIGG ;
            ztop =  BIGG ;
            iarg += 2 ; continue ;
         }

         if( iarg+2 >= argc ){
            fprintf(stderr,"\n*** no argument after option %s\n",argv[iarg]) ;
            exit(-1) ;
         }

         zbot = strtod( argv[iarg+1] , &cerr ) ;
         if( cerr == argv[iarg+1] ){
            fprintf(stderr,"\n*** illegal argument after %s: %s\n",
                    argv[iarg],argv[iarg+1] ) ; exit(-1) ;
         }
         if( *cerr == 'I' && zbot > 0.0 ) zbot = -zbot ;

         ztop = strtod( argv[iarg+2] , &cerr ) ;
         if( cerr == argv[iarg+2] ){
            fprintf(stderr,"\n*** illegal argument after %s: %s\n",
                    argv[iarg],argv[iarg+2] ) ; exit(-1) ;
         }
         if( *cerr == 'I' && ztop > 0.0 ) ztop = -ztop ;

         if( zbot > ztop ){ tf = zbot ; zbot = ztop ; ztop = tf ; }
         iarg +=3 ; continue ;
      }

      /**** unknown option ****/

      fprintf(stderr,"\n*** Unknown option: %s\n",argv[iarg]) ;
      exit(-1) ;
   }  /* end of loop over input options */

   if( ! xgood && ! ygood && ! zgood ){
      fprintf(stderr,"\n*** No projections ordered!?\n") ; exit(-1) ;
   }

   /*--- open dataset and set up to extract data slices ---*/

   dset = THD_open_dataset( argv[iarg] ) ;
   if( dset == NULL ){
      fprintf(stderr,"\n*** Can't open dataset file %s\n",argv[iarg]) ;
      exit(-1) ;
   }
   if( DSET_NUM_TIMES(dset) > 1 ){
      fprintf(stderr,"\n*** Can't project time-dependent dataset!\n") ;
      exit(1) ;
   }
   EDIT_one_dataset( dset, &PRED_edopt ) ;
   daxes = dset->daxes ;
   brarr = THD_setup_bricks( dset ) ;
   baxi  = brarr[0] ; bsag = brarr[1] ; bcor = brarr[2] ;

   /*--- determine index range for each direction ---*/

   dr = PR_get_range( dset ) ;

   if( xgood ){
      if( xbot < dr.xbot ) xbot = dr.xbot ;
      if( xtop > dr.xtop ) xtop = dr.xtop ;

      fv = THD_dicomm_to_3dmm( dset , TEMP_FVEC3(xbot,0,0) ) ;
      iv = THD_3dmm_to_3dind ( dset , fv ) ;
      iv = THD_3dind_to_fdind( bsag , iv ) ; ixbot = iv.ijk[2] ;

      fv = THD_dicomm_to_3dmm( dset , TEMP_FVEC3(xtop,0,0) ) ;
      iv = THD_3dmm_to_3dind ( dset , fv ) ;
      iv = THD_3dind_to_fdind( bsag , iv ) ; ixtop = iv.ijk[2] ;

      if( ixbot > ixtop ) { ii = ixbot ; ixbot = ixtop ; ixtop = ii ; }

      if( ixbot <  0        ) ixbot = 0 ;
      if( ixtop >= bsag->n3 ) ixtop = bsag->n3 - 1 ;
   }

   if( ygood ){
      if( ybot < dr.ybot ) ybot = dr.ybot ;
      if( ytop > dr.ytop ) ytop = dr.ytop ;

      fv = THD_dicomm_to_3dmm( dset , TEMP_FVEC3(0,ybot,0) ) ;
      iv = THD_3dmm_to_3dind ( dset , fv ) ;
      iv = THD_3dind_to_fdind( bcor , iv ) ; jybot = iv.ijk[2] ;

      fv = THD_dicomm_to_3dmm( dset , TEMP_FVEC3(0,ytop,0) ) ;
      iv = THD_3dmm_to_3dind ( dset , fv ) ;
      iv = THD_3dind_to_fdind( bcor , iv ) ; jytop = iv.ijk[2] ;

      if( jybot > jytop ) { ii = jybot ; jybot = jytop ; jytop = ii ; }

      if( jybot <  0        ) jybot = 0 ;
      if( jytop >= bcor->n3 ) jytop = bcor->n3 - 1 ;
   }

   if( zgood ){
      if( zbot < dr.zbot ) zbot = dr.zbot ;
      if( ztop > dr.ztop ) ztop = dr.ztop ;

      fv = THD_dicomm_to_3dmm( dset , TEMP_FVEC3(0,0,zbot) ) ;
      iv = THD_3dmm_to_3dind ( dset , fv ) ;
      iv = THD_3dind_to_fdind( baxi , iv ) ; kzbot = iv.ijk[2] ;

      fv = THD_dicomm_to_3dmm( dset , TEMP_FVEC3(0,0,ztop) ) ;
      iv = THD_3dmm_to_3dind ( dset , fv ) ;
      iv = THD_3dind_to_fdind( baxi , iv ) ; kztop = iv.ijk[2] ;

      if( kzbot > kztop ) { ii = kzbot ; kzbot = kztop ; kztop = ii ; }

      if( kzbot <  0        ) kzbot = 0 ;
      if( kztop >= baxi->n3 ) kztop = baxi->n3 - 1 ;
   }

   ival   = DSET_PRINCIPAL_VALUE(dset) ;    /* index to project */
   ityp   = DSET_BRICK_TYPE(dset,ival) ;    /* type of this data */
   fimfac = DSET_BRICK_FACTOR(dset,ival) ;  /* scale factor of this data */

   /*--- project the x direction, if desired ---*/

   if( xgood ){
      int n1 = bsag->n1 , n2 = bsag->n2 ;
      int ss , npix ;
      float fmax , fmin , scl ;

      /*-- set up --*/

      npix = n1*n2 ;
      flim = mri_new( n1 , n2 , MRI_float ) ;
      flar = mri_data_pointer( flim ) ;
      for( ii=0 ; ii < npix ; ii++ ) flar[ii] = 0.0 ;

      /*-- actually project --*/

      for( ss=ixbot ; ss <= ixtop ; ss++ ){
         slim = FD_brick_to_mri( ss , ival , bsag ) ;
         if( slim->kind != MRI_float ){
            pim = mri_to_float( slim ) ;
            mri_free( slim ) ; slim = pim ;
         }
         PR_one_slice( proj_code , slim , flim ) ;
         mri_free( slim ) ;
      }

      /*-- form output --*/

      if( fimfac != 0.0 && fimfac != 1.0 ){
         slim = mri_scale_to_float( 1.0/fimfac , flim ) ;
         mri_free(flim) ; flim = slim ;
      }

      scl = PR_type_scale( ityp , flim ) ;
      pim = mri_to_mri_scl( ityp , scl , flim ) ; mri_free( flim ) ;
      if( nsize ){
         slim = mri_nsize( pim ) ;
         if( slim != NULL && slim != pim ) { mri_free(pim) ; pim = slim ; }
      }

      if( scl != 1.0 )
         printf("Sagittal projection pixels scaled by %g to avoid overflow!\n",
                scl ) ;

      fmax = mri_max(pim) ; fmin = mri_min(pim) ;
      printf("Sagittal projection min = %g  max = %g\n",fmin,fmax) ;

      strcpy(fname,root) ; strcat(fname,"sag") ;
      mri_write( fname, pim ) ;
      mri_free(pim) ;
   }

   /*--- project the y direction, if desired ---*/

   if( ygood ){
      int n1 = bcor->n1 , n2 = bcor->n2 ;
      int ss , npix ;
      float fmax , fmin , scl ;

      /*-- set up --*/

      npix = n1*n2 ;
      flim = mri_new( n1 , n2 , MRI_float ) ;
      flar = mri_data_pointer( flim ) ;
      for( ii=0 ; ii < npix ; ii++ ) flar[ii] = 0.0 ;

      /*-- actually project --*/

      for( ss=jybot ; ss <= jytop ; ss++ ){
         slim = FD_brick_to_mri( ss , ival , bcor ) ;
         if( slim->kind != MRI_float ){
            pim = mri_to_float( slim ) ;
            mri_free( slim ) ; slim = pim ;
         }
         PR_one_slice( proj_code , slim , flim ) ;
         mri_free( slim ) ;
      }

      /*-- form output --*/

      if( fimfac != 0.0 && fimfac != 1.0 ){
         slim = mri_scale_to_float( 1.0/fimfac , flim ) ;
         mri_free(flim) ; flim = slim ;
      }

      scl = PR_type_scale( ityp , flim ) ;
      pim = mri_to_mri_scl( ityp , scl , flim ) ; mri_free( flim ) ;
      if( nsize ){
         slim = mri_nsize( pim ) ;
         if( slim != NULL && slim != pim ) { mri_free(pim) ; pim = slim ; }
      }

      if( scl != 1.0 )
         printf("Coronal projection pixels scaled by %g to avoid overflow!\n",
                scl ) ;

      fmax = mri_max(pim) ; fmin = mri_min(pim) ;
      printf("Coronal projection min = %g  max = %g\n",fmin,fmax) ;

      if( mirror_code == MIRR_YES ){
         slim = mri_flippo( MRI_ROT_0 , TRUE , pim ) ;
         mri_free(pim) ; pim = slim ;
      }
      strcpy(fname,root) ; strcat(fname,"cor") ;
      mri_write( fname, pim ) ;
      mri_free(pim) ;
   }

   /*--- project the z direction, if desired ---*/

   if( zgood ){
      int n1 = baxi->n1 , n2 = baxi->n2 ;
      int ss , npix ;
      float fmax , fmin , scl ;

      /*-- set up --*/

      npix = n1*n2 ;
      flim = mri_new( n1 , n2 , MRI_float ) ;
      flar = mri_data_pointer( flim ) ;
      for( ii=0 ; ii < npix ; ii++ ) flar[ii] = 0.0 ;

      /*-- actually project --*/

      for( ss=kzbot ; ss <= kztop ; ss++ ){
         slim = FD_brick_to_mri( ss , ival , baxi ) ;
         if( slim->kind != MRI_float ){
            pim = mri_to_float( slim ) ;
            mri_free( slim ) ; slim = pim ;
         }
         PR_one_slice( proj_code , slim , flim ) ;
         mri_free( slim ) ;
      }

      /*-- form output --*/

      if( fimfac != 0.0 && fimfac != 1.0 ){
         slim = mri_scale_to_float( 1.0/fimfac , flim ) ;
         mri_free(flim) ; flim = slim ;
      }

      scl = PR_type_scale( ityp , flim ) ;
      pim = mri_to_mri_scl( ityp , scl , flim ) ; mri_free( flim ) ;
      if( nsize ){
         slim = mri_nsize( pim ) ;
         if( slim != NULL && slim != pim ) { mri_free(pim) ; pim = slim ; }
      }

      if( scl != 1.0 )
         printf("Axial projection pixels scaled by %g to avoid overflow!\n",
                scl ) ;

      fmax = mri_max(pim) ; fmin = mri_min(pim) ;
      printf("Axial projection min = %g  max = %g\n",fmin,fmax) ;

      if( mirror_code == MIRR_YES ){
         slim = mri_flippo( MRI_ROT_0 , TRUE , pim ) ;
         mri_free(pim) ; pim = slim ;
      }
      strcpy(fname,root) ; strcat(fname,"axi") ;
      mri_write( fname, pim ) ;
      mri_free(pim) ;
   }

   exit(0) ;
}
Example #20
0
float_pair mri_twoquantiles( MRI_IMAGE *im, float alpha, float beta )
{
   int ii , nvox ;
   float fi ;
   float_pair qt = {0.0f,0.0f} ;
   float qalph=WAY_BIG,qbeta=WAY_BIG ;

ENTRY("mri_twoquantiles") ;

   /*** sanity checks ***/

   if( im == NULL ) RETURN( qt );

   if( alpha == beta ){
     qt.a = qt.b = mri_quantile(im,alpha) ; RETURN( qt );
   }

        if( alpha <= 0.0f ) qalph = (float) mri_min(im) ;
   else if( alpha >= 1.0f ) qalph = (float) mri_max(im) ;
        if( beta  <= 0.0f ) qbeta = (float) mri_min(im) ;
   else if( beta  >= 1.0f ) qbeta = (float) mri_max(im) ;

   if( qalph != WAY_BIG && qbeta != WAY_BIG ){
     qt.a = qalph; qt.b = qbeta; RETURN(qt);
   }

   nvox = im->nvox ;

   switch( im->kind ){

      /*** create a float image copy of the data,
           sort it, then interpolate the percentage points ***/

      default:{
         MRI_IMAGE *inim ;
         float *far ;

         inim = mri_to_float( im ) ;
         far  = MRI_FLOAT_PTR(inim) ;
         qsort_float( nvox , far ) ;

         if( alpha > 0.0f && alpha < 1.0f ){
           fi    = alpha * nvox ;
           ii    = (int) fi ; if( ii >= nvox ) ii = nvox-1 ;
           fi    = fi - ii ;
           qalph = (1.0-fi) * far[ii] + fi * far[ii+1] ;
         }
         if( beta > 0.0f && beta < 1.0f ){
           fi    = beta * nvox ;
           ii    = (int) fi ; if( ii >= nvox ) ii = nvox-1 ;
           fi    = fi - ii ;
           qbeta = (1.0-fi) * far[ii] + fi * far[ii+1] ;
         }
         mri_free( inim ) ;
      }
      break ;

      /*** create a short image copy of the data,
           sort it, then interpolate the percentage points ***/

      case MRI_short:
      case MRI_byte:{
         MRI_IMAGE *inim ;
         short *sar ;

         inim = mri_to_short( 1.0 , im ) ;
         sar  = MRI_SHORT_PTR(inim) ;
         qsort_short( nvox , sar ) ;

         if( alpha > 0.0f && alpha < 1.0f ){
           fi    = alpha * nvox ;
           ii    = (int) fi ; if( ii >= nvox ) ii = nvox-1 ;
           fi    = fi - ii ;
           qalph = (1.0-fi) * sar[ii] + fi * sar[ii+1] ;
         }
         if( beta > 0.0f && beta < 1.0f ){
           fi    = beta * nvox ;
           ii    = (int) fi ; if( ii >= nvox ) ii = nvox-1 ;
           fi    = fi - ii ;
           qbeta = (1.0-fi) * sar[ii] + fi * sar[ii+1] ;
         }
         mri_free( inim ) ;
      }
      break ;
   }

   qt.a = qalph; qt.b = qbeta; RETURN(qt);
}
Example #21
0
MRI_IMAGE * mri_warp3D_align_one( MRI_warp3D_align_basis *bas, MRI_IMAGE *im )
{
   float *fit , *dfit , *qfit , *tol ;
   int iter , good,ngood , ii, pp , skip_first ;
   MRI_IMAGE *tim , *fim ;
   float *pmat=MRI_FLOAT_PTR(bas->imps) , /* pseudo inverse: n X m matrix */
         *tar , tv , sfit ;
   int n=bas->imps->nx ,          /* = nfree+1 */
       m=bas->imps->ny ,          /* = imap->nx = length of ima */
    npar=bas->nparam   ,          /* = number of warp parameters */
   nfree=bas->nfree    ,          /* = number of free warp parameters */
    *ima=MRI_INT_PTR(bas->imap) , /* = indexes in fim of voxels to use */
    *pma ;                        /* = map of free to total params */
   int ctstart ;
   int do_twopass=(bas->imps_blur != NULL && bas->twoblur > 0.0f) , passnum=1 ;
   int blur_pass ;
   char      *save_prefix ;
   static int save_index=0 ;

#define AITMAX  3.33
#define NMEM    5
   float *fitmem[NMEM] ;
   int mm , last_aitken , num_aitken=0 ;
   float  sdif , fitdif[NMEM] ;   /* 28 Sep 2005 */
   int    num_bad_diff ;
   float  best_dif , best_par[999] ;  /* 09 Jan 2006 */
   int    best_ite=0 ;

ENTRY("mri_warp3D_align_one") ;

   ctstart = NI_clock_time() ;

   save_prefix = getenv("AFNI_WARPDRIVE_SAVER") ;

   /** pma[k] = external parameter index for the k-th free parameter **/

   pma = (int *)malloc(sizeof(int) * nfree) ;
   for( pp=ii=0 ; ii < npar ; ii++ )
     if( !bas->param[ii].fixed ) pma[pp++] = ii ;

#if 0
fprintf(stderr,"pma=") ;
for(pp=0;pp<nfree;pp++)fprintf(stderr," %d",pma[pp]);
fprintf(stderr,"\n") ;
#endif

   fit  = (float *)malloc(sizeof(float) * npar ) ;
   dfit = (float *)malloc(sizeof(float) * npar ) ;
   qfit = (float *)malloc(sizeof(float) * nfree) ;
   tol  = (float *)malloc(sizeof(float) * npar ) ;

   for( mm=0 ; mm < NMEM ; mm++ ) fitmem[mm] = NULL ;
   for( mm=0 ; mm < NMEM ; mm++ ) fitdif[mm] = 3.e+33 ;

   /*--- loop back point for two pass alignment ---*/

   bas->num_iter = 0 ;
   mri_warp3D_set_womask( bas->imsk ) ;

 ReStart:

   best_dif  = -666.0f ;                     /* 09 Jan 2006 */
   blur_pass = (do_twopass && passnum==1) ;
   mri_warp3D_method( blur_pass ? MRI_LINEAR : bas->regmode ) ;

   /* load initial fit parameters;
      if they are all the identity transform value,
      then skip the first transformation of the fim volume */

   if( passnum == 1 ){
     skip_first = 1 ;
     for( pp=0 ; pp < npar ; pp++ ){
       if( bas->param[pp].fixed ){
         fit[pp] = bas->param[pp].val_fixed ;
       } else {
         fit[pp] = bas->param[pp].val_init ;
       }
       skip_first = skip_first && (fit[pp] == bas->param[pp].ident) ;
     }
   } else {
     skip_first = 0 ;  /* and fit[] is unchanged */
   }

   fitmem[0] = (float *)malloc(sizeof(float)*npar) ;
   memcpy( fitmem[0] , fit , sizeof(float)*npar ) ;

   for( pp=0 ; pp < npar ; pp++ ) tol[pp] = bas->param[pp].toler ;

   if( blur_pass ){
     float fac = (1.0f+bas->twoblur) ;
     if( fac < 3.0f ) fac = 3.0f ;
     for( pp=0 ; pp < npar ; pp++ ) tol[pp] *= fac ;
   }

   if( bas->verb )
     fprintf(stderr,"++ mri_warp3D_align_one: START PASS #%d\n",passnum) ;

   /* setup base image for registration into fim,
      and pseudo-inverse of base+derivative images into pmat */

   if( blur_pass ){             /* first pass ==> registering blurred images */
     float *far , blur=bas->twoblur ;
     int nx=im->nx , ny=im->ny , nz=im->nz ;
     fim = mri_to_float( im ) ; far = MRI_FLOAT_PTR(fim) ;
     EDIT_blur_volume_3d( nx,ny,nz ,       1.0f,1.0f,1.0f ,
                          MRI_float , far, blur,blur,blur  ) ;
     pmat = MRI_FLOAT_PTR(bas->imps_blur) ;
   } else {                           /* registering original image */
     if( im->kind == MRI_float ) fim = im ;
     else                        fim = mri_to_float( im ) ;
     pmat = MRI_FLOAT_PTR(bas->imps) ;
   }

   /******** iterate fit ********/

   iter = 0 ; good = 1 ; last_aitken = 3 ; num_bad_diff = 0 ;
   while( good ){
     if( skip_first ){
       tim = fim ; skip_first = 0 ;
     } else {
       bas->vwset( npar , fit ) ;                     /**************************/
       tim = mri_warp3D( fim , 0,0,0 , bas->vwfor ) ; /* warp on current params */
     }                                                /**************************/
     tar = MRI_FLOAT_PTR(tim) ;

     sdif = mri_scaled_diff( bas->imbase , tim , bas->imsk ) ;
     if( bas->verb )
       fprintf(stderr,"++++++++++ Start iter=%d  RMS_diff=%g\n",iter+1,sdif) ;

     if( best_dif < 0.0f || sdif < best_dif ){        /* 09 Jan 2006 */
       best_dif = sdif ; best_ite = iter ;
       memcpy( best_par , fit , sizeof(float)*npar ) ;
     }

     /* find least squares fit of base + derivatives to warped image */

     sfit = 0.0f ;
     for( pp=0 ; pp < npar  ; pp++ ) dfit[pp] = 0.0f ;
     for( pp=0 ; pp < nfree ; pp++ ) qfit[pp] = 0.0f ;
     for( ii=0 ; ii < m ; ii++ ){
       tv = tar[ima[ii]] ; sfit += P(nfree,ii) * tv ;
       for( pp=0 ; pp < nfree ; pp++ ) qfit[pp] += P(pp,ii) * tv ;
     }
     if( tim != fim ) mri_free( tim ) ;
#if 0
fprintf(stderr,"qfit=");
for(pp=0;pp<nfree;pp++)fprintf(stderr," %g",qfit[pp]);
fprintf(stderr,"\n") ;
#endif
     for( pp=0 ; pp < nfree ; pp++ ) dfit[pma[pp]] = qfit[pp] ;
     for( pp=0 ; pp < npar  ; pp++ ){
       fit[pp] += dfit[pp] ;
            if( fit[pp] > bas->param[pp].max ) fit[pp] = bas->param[pp].max ;
       else if( fit[pp] < bas->param[pp].min ) fit[pp] = bas->param[pp].min ;
     }

     if( bas->verb ){
       fprintf(stderr,"+   Delta:") ;
       for( pp=0 ; pp < npar ; pp++ ) fprintf(stderr," %13.6g",dfit[pp]) ;
       fprintf(stderr,"\n") ;
       fprintf(stderr,"+   Total: scale factor=%g\n"
                      "+  #%5d:",sfit,iter+1) ;
       for( pp=0 ; pp < npar ; pp++ ) fprintf(stderr," %13.6g", fit[pp]) ;
       fprintf(stderr,"\n") ;
     }

     /* save fit results for a while into the past, and then maybe do Aitken */

     if( fitmem[NMEM-1] != NULL ) free((void *)fitmem[NMEM-1]) ;
     for( mm=NMEM-1 ; mm > 0 ; mm-- ) fitmem[mm] = fitmem[mm-1] ;
     fitmem[0] = (float *)malloc(sizeof(float)*npar) ;
     memcpy( fitmem[0] , fit , sizeof(float)*npar ) ;

     /* 28 Sep 2005: if RMS went up, back off the changes! */

     for( mm=NMEM-1 ; mm > 0 ; mm-- ) fitdif[mm] = fitdif[mm-1] ;
     fitdif[0] = sdif ;

     if( iter > 1          && num_bad_diff < 2                   &&
         fitmem[1] != NULL && fitdif[0]    > 1.0666f * fitdif[1]   ){
       for( pp=0 ; pp < npar ; pp++ )
         fit[pp] = 0.5 * ( fitmem[0][pp] + fitmem[1][pp] ) ;
       memcpy( fitmem[0] , fit , sizeof(float)*npar ) ;
       last_aitken = iter+1 ; num_bad_diff++ ;
       if( bas->verb )
         fprintf(stderr,"+++ RMS_diff changes too much! Shrinking!\n") ;
     } else {
       num_bad_diff = 0 ;
     }

     iter++ ;
     if( iter > last_aitken+NMEM && !AFNI_noenv("AFNI_WARPDRIVE_AITKEN") ){
       double s0,s1,s2 , dd , de,df ;
       num_aitken = 0 ;
       for( pp=0 ; pp < npar ; pp++ ){
         dd = fabs(fitmem[1][pp]-fit[pp]) ;
         if( dd <= tol[pp] ) continue ; /* done here */
         de = dd ;
         for( mm=2 ; mm < NMEM ; mm++ ){
           df = fabs(fitmem[mm][pp]-fitmem[mm-1][pp]) ;
           if( df <= de ) break ;
           de = df ;
         }
         if( mm == NMEM ){  /* do Aitken */
           s2 = fit[pp] ; s1 = fitmem[1][pp] ; s0 = fitmem[2][pp] ;
           de = ( (s2-s1) - (s1-s0) ) ;
           if( de != 0.0 ){
             de = -(s2-s1)*(s2-s1) / de ; dd *= AITMAX ;
             if( fabs(de) > dd ){ de = (de > 0.0) ? dd : -dd ; }
             fit[pp] += de ;
                  if( fit[pp] > bas->param[pp].max ) fit[pp] = bas->param[pp].max ;
             else if( fit[pp] < bas->param[pp].min ) fit[pp] = bas->param[pp].min ;
             num_aitken++ ;
           }
         }
       }
       if( num_aitken > 0 ) last_aitken = iter ;

       if( bas->verb && num_aitken > 0 ){
         fprintf(stderr,"+   Aitken on %d params:\n"
                        "+________:",num_aitken) ;
         for( pp=0 ; pp < npar ; pp++ ){
           if( fit[pp] != fitmem[0][pp] ){
             fprintf(stderr," %13.6g", fit[pp]) ; fitmem[0][pp] = fit[pp] ;
           } else {
             fprintf(stderr," _____________") ;
           }
         }
         fprintf(stderr,"\n") ;
       }
     }

     /* save intermediate image? */

     if( save_prefix != NULL ){
       char sname[THD_MAX_NAME] ; FILE *fp ;
       mri_warp3D_set_womask( NULL ) ;        /* must warp the whole thing */
       bas->vwset( npar , fit ) ;
       tim = mri_warp3D( fim , 0,0,0 , bas->vwfor ) ;
       tar = MRI_FLOAT_PTR(tim) ;
       mri_warp3D_set_womask( bas->imsk ) ;
       sprintf(sname,"%s_%04d.mmm",save_prefix,save_index++) ;
       fprintf(stderr,"+   Saving intermediate image to binary file %s\n",sname) ;
       fp = fopen( sname , "w" ) ;
       if( fp != NULL ){
         fwrite( tar, tim->pixel_size, tim->nvox, fp ) ; fclose(fp) ;
       }

       if( bas->vwdet != NULL ){
         int i,j,k , nx=tim->nx,ny=tim->ny,nz=tim->nz ;
         for( k=0 ; k < nz ; k++ ){
          for( j=0 ; j < ny ; j++ ){
           for( i=0 ; i < nx ; i++ ){
             tar[i+(j+k*ny)*nx] = bas->vwdet( (float)i,(float)j,(float)k ) ;
         }}}
         sprintf(sname,"%s_%04d.ddd",save_prefix,save_index-1) ;
         fprintf(stderr,"+   Saving determinant image to binary file %s\n",sname) ;
         fp = fopen( sname , "w" ) ;
         if( fp != NULL ){
           fwrite( tar, tim->pixel_size, tim->nvox, fp ) ; fclose(fp) ;
         }
       }
       mri_free( tim ) ;
     }

     /* loop back for more iterations? */

     if( last_aitken == iter ) continue ;  /* don't test, just loop */
     if( fitmem[2]   == NULL ) continue ;

     ngood = 0 ;
     for( pp=0 ; pp < npar ; pp++ )
       if( !bas->param[pp].fixed )
         ngood += ( ( fabs(fitmem[1][pp]-fitmem[0][pp]) <= tol[pp] ) &&
                    ( fabs(fitmem[2][pp]-fitmem[1][pp]) <= tol[pp] )   ) ;

     good = (ngood < nfree) && (iter < bas->max_iter) ;

   } /******** end while loop for iteration of fitting procedure ********/

   for( mm=0 ; mm < NMEM ; mm++ )
     if( fitmem[mm] != NULL ){ free((void *)fitmem[mm]); fitmem[mm] = NULL; }

   /*--- 09 Jan 2006: if prior best fit was better than current, replace ---*/

   if( best_dif > 0.0f && 1.0666f*best_dif < sdif ){
     memcpy( fit , best_par , sizeof(float)*npar ) ;
     if( bas->verb )
       fprintf(stderr,"+++++ Replacing final fit with iter #%d's fit +++++\n",
               best_ite+1) ;
   }

   /*--- do the second pass? ---*/

   if( blur_pass ){
     if( bas->verb )
       fprintf(stderr,"+++++++++++++ Loop back for next pass +++++++++++++\n");
     mri_free(fim) ; fim = NULL ; passnum++ ; goto ReStart ;
   } else {
     if( bas->verb )
       fprintf(stderr,"+++++++++++++ Convergence test passed +++++++++++++\n");
   }

   /*--- done! ---*/

   bas->num_iter = iter ;

   for( pp=0 ; pp < npar ; pp++ ) bas->param[pp].val_out = fit[pp] ;

   /*-- do the actual realignment to get the output image --*/

   if( bas->regfinal > 0 ) mri_warp3D_method( bas->regfinal ) ;
   mri_warp3D_set_womask( NULL ) ;
   bas->vwset( npar , fit ) ;
   tim = mri_warp3D( fim , 0,0,0 , bas->vwfor ) ;

   if( fim != im ) mri_free(fim) ;  /* if it was a copy, junk it */
   free((void *)dfit) ; free((void *)fit) ;
   free((void *)qfit) ; free((void *)pma) ; free((void *)tol) ;

   if( bas->verb ){
     double st = (NI_clock_time()-ctstart) * 0.001 ;
     fprintf(stderr,"++ mri_warp3D_align_one EXIT: %.2f seconds elapsed\n",st) ;
   }

   RETURN( tim ) ;
}
Example #22
0
static MRI_IMAGE * mri_warp3D_align_fitim( MRI_warp3D_align_basis *bas ,
                                           MRI_IMAGE *cim ,
                                           int warp_mode , float delfac )
{
   MRI_IMAGE *fitim , *pim , *mim ;
   float *fitar , *car=MRI_FLOAT_PTR(cim) ;
   int nfree=bas->nfree , *ima=MRI_INT_PTR(bas->imap) , nmap=bas->imap->nx ;
   int npar =bas->nparam ;
   float *pvec , *par , *mar ;
   int ii , pp , cc ;
   float dpar , delta ;

   /*-- create image containing basis columns --*/

   fitim = mri_new( nmap , nfree+1 , MRI_float ) ;
   fitar = MRI_FLOAT_PTR(fitim) ;
   pvec  = (float *)malloc(sizeof(float) * npar) ;

#undef  FMAT
#define FMAT(i,j) fitar[(i)+(j)*nmap]  /* col dim=nmap, row dim=nfree+1 */

   /* column #nfree = base image itself */

   for( ii=0 ; ii < nmap ; ii++ ) FMAT(ii,nfree) = car[ima[ii]] ;

   pvec = (float *)malloc(sizeof(float) * npar) ;

   /* for each free parameter:
       apply inverse transform to base image with param value up and down
       compute central difference to approximate derivative of base
        image wrt parameter
       store as a column in the fitim matrix */

   mri_warp3D_method( warp_mode ) ;  /* set interpolation mode */
   mri_warp3D_set_womask( bas->imsk ) ;

   for( pp=0,cc=0 ; pp < npar ; pp++ ){

     if( bas->param[pp].fixed ) continue ;  /* don't do this one! */

     /* init all params to their identity transform value */

     for( ii=0 ; ii < npar ; ii++ )
       pvec[ii] = (bas->param[ii].fixed) ? bas->param[ii].val_fixed
                                         : bas->param[ii].ident ;

     /* change in the pp-th parameter to use for derivative */

     dpar = delfac * bas->param[pp].delta ;

     if( bas->verb )
       fprintf(stderr,"+   difference base by %f in param#%d [%s]\n",
               dpar , pp+1 , bas->param[pp].name ) ;

     pvec[pp] = bas->param[pp].ident + dpar ;   /* set positive change */
     bas->vwset( npar , pvec ) ;                 /* put into transform */
     pim = mri_warp3D( cim , 0,0,0 , bas->vwinv ) ;      /* warp image */

     pvec[pp] = bas->param[pp].ident - dpar ;   /* set negative change */
     bas->vwset( npar , pvec ) ;
     mim = mri_warp3D( cim , 0,0,0 , bas->vwinv ) ;

     /* compute derivative */

     delta = bas->scale_init / ( 2.0f * dpar ) ;
     par = MRI_FLOAT_PTR(pim) ; mar = MRI_FLOAT_PTR(mim) ;
     for( ii=0 ; ii < nmap ; ii++ )
       FMAT(ii,cc) = delta * ( par[ima[ii]] - mar[ima[ii]] ) ;

#if 0
{ float psum=0.0f,msum=0.0f,dsum=0.0f;
  for( ii=0 ; ii < nmap ; ii++ ){
    psum += fabsf(par[ima[ii]]) ;
    msum += fabsf(mar[ima[ii]]) ;
    dsum += fabsf(FMAT(ii,cc)) ;
  }
  fprintf(stderr,"  pp=%d  psum=%g  msum=%g  dsum=%g\n",pp,psum,msum,dsum) ;
}
#endif

     mri_free(pim) ; mri_free(mim) ;  /* no longer needed */

     cc++ ;  /* oopsie */
   }

   mri_warp3D_set_womask( NULL ) ;
   free((void *)pvec) ;

#if 0
{ int zz , jj ;
  for( jj=0 ; jj <= nfree ; jj++ ){
    zz = 0 ;
    for( ii=0 ; ii < nmap ; ii++ ) if( FMAT(ii,jj) == 0.0 ) zz++ ;
    fprintf(stderr,"  fitim: col#%d has %d zeros out of %d\n",jj,zz,nmap) ;
  }
}
#endif

   return(fitim) ;
}
Example #23
0
int mri_warp3D_align_setup( MRI_warp3D_align_basis *bas )
{
   MRI_IMAGE *cim , *fitim ;
   int nx, ny, nz, nxy, nxyz , ii,jj,kk , nmap, *im ;
   float *wf , *wtar , clip , clip2 ;
   int   *ima , pp , wtproc , npar , nfree ;
   byte  *msk ;
   int ctstart ;

ENTRY("mri_warp3D_align_setup") ;

   ctstart = NI_clock_time() ;

   /*- check for good inputs -*/

   if( bas == NULL     || bas->imbase == NULL ) RETURN(1) ;
   if( bas->nparam < 1 || bas->param  == NULL ) RETURN(1) ;
   if( bas->vwfor == NULL ||
       bas->vwinv == NULL || bas->vwset == NULL ) RETURN(1) ;

   /*- set defaults in bas, if values weren't set by user -*/

   if( bas->scale_init <= 0.0f ) bas->scale_init = 1.0f ;
   if( bas->delfac     <= 0.0f ) bas->delfac     = 1.0f ;
   if( bas->regmode    <= 0    ) bas->regmode    = MRI_LINEAR ;
   if( bas->max_iter   <= 0    ) bas->max_iter   = 9 ;

   /* process the weight image? */

   wtproc = (bas->imwt == NULL) ? 1 : bas->wtproc ;
   npar   = bas->nparam ;

   nfree = npar ;
   for( pp=0 ; pp < npar ; pp++ )
     if( bas->param[pp].fixed ) nfree-- ;
   if( nfree <= 0 ) RETURN(1) ;
   bas->nfree = nfree ;

   /*- clean out anything from last call -*/

   mri_warp3D_align_cleanup( bas ) ;

   /*-- need local copy of input base image --*/

   cim = mri_to_float( bas->imbase ) ;
   nx=cim->nx ; ny=cim->ny ; nz=cim->nz ; nxy = nx*ny ; nxyz=nxy*nz ;

   /*-- make weight image up from the base image if it isn't supplied --*/

   if( bas->verb ) fprintf(stderr,"++ mri_warp3D_align_setup ENTRY\n") ;

   if( bas->imwt == NULL   ||
       bas->imwt->nx != nx ||
       bas->imwt->ny != ny ||
       bas->imwt->nz != nz   ) bas->imww = mri_copy( cim ) ;
   else                        bas->imww = mri_to_float( bas->imwt ) ;

   if( bas->twoblur > 0.0f ){
     float bmax = cbrt((double)nxyz) * 0.03 ;
     if( bmax < bas->twoblur ){
       if( bas->verb )
         fprintf(stderr,"+   shrink bas->twoblur from %.3f to %.3f\n",
                        bas->twoblur , bmax ) ;
       bas->twoblur = bmax ;
     }
   }

   if( bas->verb ) fprintf(stderr,"+   processing weight:") ;

   /* make sure weight is non-negative */

   wf = MRI_FLOAT_PTR(bas->imww) ;
   for( ii=0 ; ii < nxyz ; ii++ ) wf[ii] = fabs(wf[ii]) ;

   /* trim off edges of weight */

   if( wtproc ){
     int ff ;
     int xfade=bas->xedge , yfade=bas->yedge , zfade=bas->zedge ;

     if( xfade < 0 || yfade < 0 || zfade < 0 )
       mri_warp3D_align_edging_default(nx,ny,nz,&xfade,&yfade,&zfade) ;

     if( bas->twoblur > 0.0f ){
       xfade += (int)rint(1.5*bas->twoblur) ;
       yfade += (int)rint(1.5*bas->twoblur) ;
       zfade += (int)rint(1.5*bas->twoblur) ;
     }

     if( 3*zfade >= nz ) zfade = (nz-1)/3 ;
     if( 3*xfade >= nx ) xfade = (nx-1)/3 ;
     if( 3*yfade >= ny ) yfade = (ny-1)/3 ;

     if( bas->verb ) fprintf(stderr," [edge(%d,%d,%d)]",xfade,yfade,zfade) ;

     for( jj=0 ; jj < ny ; jj++ )
      for( ii=0 ; ii < nx ; ii++ )
       for( ff=0 ; ff < zfade ; ff++ )
         WW(ii,jj,ff) = WW(ii,jj,nz-1-ff) = 0.0f ;

     for( kk=0 ; kk < nz ; kk++ )
      for( jj=0 ; jj < ny ; jj++ )
       for( ff=0 ; ff < xfade ; ff++ )
         WW(ff,jj,kk) = WW(nx-1-ff,jj,kk) = 0.0f ;

     for( kk=0 ; kk < nz ; kk++ )
      for( ii=0 ; ii < nx ; ii++ )
       for( ff=0 ; ff < yfade ; ff++ )
        WW(ii,ff,kk) = WW(ii,ny-1-ff,kk) = 0.0f ;

   }

   /* spatially blur weight a little */

   if( wtproc ){
     float blur ;
     blur = 1.0f + MAX(1.5f,bas->twoblur) ;
     if( bas->verb ) fprintf(stderr," [blur(%.1f)]",blur) ;
     EDIT_blur_volume_3d( nx,ny,nz ,       1.0f,1.0f,1.0f ,
                          MRI_float , wf , blur,blur,blur  ) ;
   }

   /* get rid of low-weight voxels */

   clip  = 0.035 * mri_max(bas->imww) ;
   clip2 = 0.5*THD_cliplevel(bas->imww,0.4) ;
   if( clip2 > clip ) clip = clip2 ;
   if( bas->verb ) fprintf(stderr," [clip(%.1f)]",clip) ;
   for( ii=0 ; ii < nxyz ; ii++ ) if( wf[ii] < clip ) wf[ii] = 0.0f ;

   /* keep only the largest cluster of nonzero voxels */

   { byte *mmm = (byte *)malloc( sizeof(byte)*nxyz ) ;
     for( ii=0 ; ii < nxyz ; ii++ ) mmm[ii] = (wf[ii] > 0.0f) ;
     THD_mask_clust( nx,ny,nz, mmm ) ;
     THD_mask_erode( nx,ny,nz, mmm, 1 ) ;  /* cf. thd_automask.c */
     THD_mask_clust( nx,ny,nz, mmm ) ;
     for( ii=0 ; ii < nxyz ; ii++ ) if( !mmm[ii] ) wf[ii] = 0.0f ;
     free((void *)mmm) ;
   }

   if( bas->verb ) fprintf(stderr,"\n") ;

   /*-- make integer index map of weight > 0 voxels --*/

   nmap = 0 ;
   for( ii=0 ; ii < nxyz ; ii++ ) if( wf[ii] > 0.0f ) nmap++ ;

   if( bas->verb )
     fprintf(stderr,"+   using %d [%.3f%%] voxels\n",nmap,(100.0*nmap)/nxyz);

   if( nmap < 7*nfree+13 ){
     fprintf(stderr,"** mri_warp3D_align error: weight image too zero-ish!\n") ;
     mri_warp3D_align_cleanup( bas ) ; mri_free(cim) ;
     RETURN(1) ;
   }

   bas->imap = mri_new( nmap , 1 , MRI_int ) ;
   ima       = MRI_INT_PTR(bas->imap) ;
   bas->imsk = mri_new_conforming( bas->imww , MRI_byte ) ;
   msk       = MRI_BYTE_PTR(bas->imsk) ;
   for( ii=jj=0 ; ii < nxyz ; ii++ ){
     if( wf[ii] > 0.0f ){ ima[jj++] = ii; msk[ii] = 1; }
   }

   /* make copy of sqrt(weight), but only at mapped indexes */

   wtar = (float *)malloc(sizeof(float)*nmap) ;
   for( ii=0 ; ii < nmap ; ii++ ) wtar[ii] = sqrt(wf[ima[ii]]) ;

   /*-- for parameters that don't come with a step size, find one --*/

   clip = bas->tolfac ; if( clip <= 0.0f ) clip = 0.03f ;

   for( ii=0 ; ii < npar ; ii++ ){
     if( bas->param[ii].fixed ) continue ; /* don't need this */
     if( bas->param[ii].delta <= 0.0f )
       mri_warp3D_get_delta( bas , ii ) ;  /* find step size */
     if( bas->param[ii].toler <= 0.0f ){   /* and set default tolerance */
       bas->param[ii].toler = clip * bas->param[ii].delta ;
       if( bas->verb )
         fprintf(stderr,"+   set toler param#%d [%s] = %f\n",
                 ii+1,bas->param[ii].name,bas->param[ii].toler) ;
     }
   }

   /* don't need the computed weight image anymore */

   mri_free(bas->imww) ; bas->imww = NULL ; wf = NULL ;

   /*-- create image containing basis columns, then pseudo-invert it --*/

   if( bas->verb ) fprintf(stderr,"+  Compute Derivatives of Base\n") ;
   fitim = mri_warp3D_align_fitim( bas , cim , bas->regmode , bas->delfac ) ;
   if( bas->verb ) fprintf(stderr,"+   calculate pseudo-inverse\n") ;
   bas->imps = mri_psinv( fitim , wtar ) ;
   mri_free(fitim) ;

   if( bas->imps == NULL ){  /* bad bad bad */
     fprintf(stderr,"** mri_warp3D_align error: can't invert Base matrix!\n") ;
     free((void *)wtar) ; mri_warp3D_align_cleanup( bas ) ; mri_free(cim) ;
     RETURN(1) ;
   }

   /*--- twoblur? ---*/

   if( bas->twoblur > 0.0f ){
     float *car=MRI_FLOAT_PTR(cim) ;
     float blur = bas->twoblur ;
     float bfac = blur ;
          if( bfac < 1.1234f ) bfac = 1.1234f ;
     else if( bfac > 1.3456f ) bfac = 1.3456f ;

     if( bas->verb ) fprintf(stderr,"+  Compute Derivatives of Blurred Base\n") ;
     EDIT_blur_volume_3d( nx,ny,nz ,       1.0f,1.0f,1.0f ,
                          MRI_float , car, blur,blur,blur  ) ;
     fitim = mri_warp3D_align_fitim( bas , cim , MRI_LINEAR , bfac*bas->delfac ) ;
     if( bas->verb ) fprintf(stderr,"+   calculate pseudo-inverse\n") ;
     bas->imps_blur = mri_psinv( fitim , wtar ) ;
     mri_free(fitim) ;
     if( bas->imps_blur == NULL ){  /* bad */
       fprintf(stderr,"** mri_warp3D_align error: can't invert Blur matrix!\n") ;
     }
   }

   /*--- done ---*/

   mri_free(cim) ; free((void *)wtar) ;

   if( bas->verb ){
     double st = (NI_clock_time()-ctstart) * 0.001 ;
     fprintf(stderr,"++ mri_warp3D_align_setup EXIT: %.2f seconds elapsed\n",st);
   }

   RETURN(0);
}
Example #24
0
MRI_IMAGE *mri_rota_bilinear( MRI_IMAGE *im, float aa, float bb, float phi )
{
   float rot_dx , rot_dy , rot_cph , rot_sph ;
   MRI_IMAGE *imfl , *newImg ;
   MRI_IMARR *impair ;
   float *far , *nar ;
   float xx,yy , fx,fy ;
   int ii,jj, nx,ny , ix,jy ;
   float f_j00,f_jp1 , wt_00,wt_p1 ;

   if( im == NULL || ! MRI_IS_2D(im) ){
      fprintf(stderr,"*** mri_rota_bilinear only works on 2D images!\n") ; EXIT(1) ;
   }

   /** if complex image, break into pairs, do each separately, put back together **/

   if( im->kind == MRI_complex ){
      MRI_IMARR *impair ;
      MRI_IMAGE * rim , * iim , * tim ;
      impair = mri_complex_to_pair( im ) ;
      if( impair == NULL ){
         fprintf(stderr,"*** mri_complex_to_pair fails in mri_rota!\n") ; EXIT(1) ;
      }
      rim = IMAGE_IN_IMARR(impair,0) ;
      iim = IMAGE_IN_IMARR(impair,1) ;  FREE_IMARR(impair) ;
      tim = mri_rota_bilinear( rim , aa,bb,phi ) ; mri_free( rim ) ; rim = tim ;
      tim = mri_rota_bilinear( iim , aa,bb,phi ) ; mri_free( iim ) ; iim = tim ;
      newImg = mri_pair_to_complex( rim , iim ) ;
      mri_free( rim ) ; mri_free( iim ) ;
      MRI_COPY_AUX(newImg,im) ;
      return newImg ;
   }

   /** rotation params **/

   rot_cph = cos(phi) ; rot_sph = sin(phi) ;

   rot_dx  = (0.5 * im->nx) * (1.0-rot_cph) - aa*rot_cph - bb*rot_sph
            -(0.5 * im->ny) * rot_sph ;

   rot_dy  = (0.5 * im->nx) * rot_sph + aa*rot_sph - bb*rot_cph
            +(0.5 * im->ny) * (1.0-rot_cph) ;

   /** other initialization **/

   nx = im->nx ;  /* image dimensions */
   ny = im->ny ;

   if( im->kind == MRI_float ) imfl = im ;
   else                        imfl = mri_to_float( im ) ;

   far = MRI_FLOAT_PTR(imfl) ;              /* access to float data */
   newImg = mri_new( nx , nx , MRI_float ) ;   /* output image */
   nar = MRI_FLOAT_PTR(newImg) ;               /* output image data */

   /*** loop over output points and warp to them ***/

   for( jj=0 ; jj < nx ; jj++ ){
      xx = rot_sph * jj + rot_dx - rot_cph ;
      yy = rot_cph * jj + rot_dy + rot_sph ;
      for( ii=0 ; ii < nx ; ii++ ){

         xx += rot_cph ;  /* get x,y in original image */
         yy -= rot_sph ;

         ix = (xx >= 0.0) ? ((int) xx) : ((int) xx)-1 ;  /* floor */
         jy = (yy >= 0.0) ? ((int) yy) : ((int) yy)-1 ;

         fx = xx-ix ; wt_00 = 1.0 - fx ; wt_p1 = fx ;

         if( ix >= 0 && ix < nx-1 && jy >= 0 && jy < ny-1 ){
            float *fy00 , *fyp1 ;

            fy00 = far + (ix + jy*nx) ; fyp1 = fy00 + nx ;

            f_j00 = wt_00 * fy00[0] + wt_p1 * fy00[1] ;
            f_jp1 = wt_00 * fyp1[0] + wt_p1 * fyp1[1] ;

         } else {
            f_j00 = wt_00 * FINS(ix,jy  ) + wt_p1 * FINS(ix+1,jy  ) ;
            f_jp1 = wt_00 * FINS(ix,jy+1) + wt_p1 * FINS(ix+1,jy+1) ;
         }

         fy  = yy-jy ; nar[ii+jj*nx] = (1.0-fy) * f_j00 + fy * f_jp1 ;

      }
   }

   /*** cleanup and return ***/

   if( im != imfl ) mri_free(imfl) ;  /* throw away unneeded workspace */
   MRI_COPY_AUX(newImg,im) ;
   return newImg ;
}
Example #25
0
MRI_IMAGE * mri_flatten( MRI_IMAGE * im )
{
   MRI_IMAGE * flim , * intim , * outim ;
   float * far , * outar ;
   int * iar ;
   int ii , nvox , ibot,itop , nvox1 ;
   float fac , val ;

#ifdef DEBUG
printf("Entry: mri_flatten\n") ;
#endif

   if( im == NULL ) return NULL ;

   /*** make an image that is just the voxel index in its array ***/
   /*** also, make the output image while we are at it          ***/

   nvox  = im->nvox ;
   intim = mri_new_conforming( im , MRI_int ) ;
   outim = mri_new_conforming( im , MRI_float ) ;

   iar = MRI_INT_PTR(intim) ; outar = MRI_FLOAT_PTR(outim) ;

   for( ii=0 ; ii < nvox ; ii++ ) iar[ii] = ii ;

   /*** copy the input data to a floating point image ***/

   flim = mri_to_float( im ) ; far = MRI_FLOAT_PTR(flim) ;

   /*** sort this image, with the index array being carried along
        so that we know where every pixel came from originally  ***/

   qsort_pair( nvox , far , iar ) ;

   /*** The "far" array is now sorted.  Thus, if the pixel that was in
        voxel i is now in voxel j, then its place in the histogram is
        j/nvox.  The only difficulty is that there may be ties.  We need
        to resolve these ties so that pixels with the same intensity
        don't get different output values.  We do this by scanning
        through far, finding blocks of equal values, and replacing
        them by their average position in the histogram.
   ***/

   fac = 1.0 / nvox ; nvox1 = nvox - 1 ;

   for( ibot=0 ; ibot < nvox1 ; ){

      /** if this value is unique, just set the value and move on **/

      val = far[ibot] ; itop = ibot+1 ;
      if( val != far[itop] ){
         far[ibot] = fac * ibot ;
         ibot++ ; continue ;
      }

      /** scan itop up until value is distinct **/

      for( ; itop < nvox1 && val == far[itop] ; itop++ ) ; /* nada */

      val = 0.5*fac * (ibot+itop-1) ;
      for( ii=ibot ; ii < itop ; ii++ ) far[ii] = val ;
      ibot = itop ;
   }
   far[nvox1] = 1.0 ;

   /*** now propagate these values back to the output image ***/

   for( ii=0 ; ii < nvox ; ii++ ) outar[iar[ii]] = far[ii] ;

   mri_free( flim ) ; mri_free( intim ) ;

   MRI_COPY_AUX( outim , im ) ;
   return outim ;
}
Example #26
0
MRI_IMAGE *mri_rota( MRI_IMAGE *im, float aa, float bb, float phi )
{
   float rot_dx , rot_dy , rot_cph , rot_sph , top,bot,val ;
   MRI_IMAGE *imfl , *newImg ;
   MRI_IMARR *impair ;
   float *far , *nar ;
   float xx,yy , fx,fy ;
   int ii,jj, nx,ny , ix,jy , ifx,jfy ;
   float f_jm1,f_j00,f_jp1,f_jp2 , wt_m1,wt_00,wt_p1,wt_p2 ;

#ifdef USE_CGRID
   if( p_first ){
      p_first = 0 ;
      xx      = 1.0 / CGRID ;
      for( ii=0 ; ii <= CGRID ; ii++ ){
         yy       = ii * xx ;
         p_m1[ii] = P_M1(yy) ;
         p_00[ii] = P_00(yy) ;
         p_p1[ii] = P_P1(yy) ;
         p_p2[ii] = P_P2(yy) ;
      }
   }
#endif

   if( im == NULL || ! MRI_IS_2D(im) ){
      fprintf(stderr,"*** mri_rota only works on 2D images!\n") ; EXIT(1) ;
   }

   /** if complex image, break into pairs, do each separately, put back together **/

   if( im->kind == MRI_complex ){
      MRI_IMARR *impair ;
      MRI_IMAGE * rim , * iim , * tim ;
      impair = mri_complex_to_pair( im ) ;
      if( impair == NULL ){
         fprintf(stderr,"*** mri_complex_to_pair fails in mri_rota!\n") ; EXIT(1) ;
      }
      rim = IMAGE_IN_IMARR(impair,0) ;
      iim = IMAGE_IN_IMARR(impair,1) ;  FREE_IMARR(impair) ;
      tim = mri_rota( rim , aa,bb,phi ) ; mri_free( rim ) ; rim = tim ;
      tim = mri_rota( iim , aa,bb,phi ) ; mri_free( iim ) ; iim = tim ;
      newImg = mri_pair_to_complex( rim , iim ) ;
      mri_free( rim ) ; mri_free( iim ) ;
      MRI_COPY_AUX(newImg,im) ;
      return newImg ;
   }

   /** rotation params **/

   rot_cph = cos(phi) ; rot_sph = sin(phi) ;

   rot_dx  = (0.5 * im->nx) * (1.0-rot_cph) - aa*rot_cph - bb*rot_sph
            -(0.5 * im->ny) * rot_sph ;

   rot_dy  = (0.5 * im->nx) * rot_sph + aa*rot_sph - bb*rot_cph
            +(0.5 * im->ny) * (1.0-rot_cph) ;

   /** other initialization **/

   nx = im->nx ;  /* image dimensions */
   ny = im->ny ;

   if( im->kind == MRI_float ) imfl = im ;
   else                        imfl = mri_to_float( im ) ;

   far = MRI_FLOAT_PTR(imfl) ;              /* access to float data */
   newImg = mri_new( nx , nx , MRI_float ) ;   /* output image */
   nar = MRI_FLOAT_PTR(newImg) ;               /* output image data */

   bot = top = far[0] ;
   for( ii=0 ; ii < nx*ny ; ii++ )
           if( far[ii] < bot ) bot = far[ii] ;
      else if( far[ii] > top ) top = far[ii] ;

   /*** loop over output points and warp to them ***/

   for( jj=0 ; jj < nx ; jj++ ){
      xx = rot_sph * jj + rot_dx - rot_cph ;
      yy = rot_cph * jj + rot_dy + rot_sph ;
      for( ii=0 ; ii < nx ; ii++ ){

         xx += rot_cph ;  /* get x,y in original image */
         yy -= rot_sph ;

         ix = (xx >= 0.0) ? ((int) xx) : ((int) xx)-1 ;  /* floor */
         jy = (yy >= 0.0) ? ((int) yy) : ((int) yy)-1 ;

#ifdef USE_CGRID
         ifx   = (xx-ix)*CGRID + 0.499 ;
         wt_m1 = p_m1[ifx] ; wt_00 = p_00[ifx] ;
         wt_p1 = p_p1[ifx] ; wt_p2 = p_p2[ifx] ;
#else
         fx    = xx-ix ;
         wt_m1 = P_M1(fx) ; wt_00 = P_00(fx) ;
         wt_p1 = P_P1(fx) ; wt_p2 = P_P2(fx) ;
#endif

         if( ix > 0 && ix < nx-2 && jy > 0 && jy < ny-2 ){
            float * fym1, *fy00 , *fyp1 , *fyp2 ;

            fym1 = far + (ix-1 + (jy-1)*nx) ;
            fy00 = fym1 + nx ;
            fyp1 = fy00 + nx ;
            fyp2 = fyp1 + nx ;

            f_jm1 =  wt_m1 * fym1[0] + wt_00 * fym1[1]
                   + wt_p1 * fym1[2] + wt_p2 * fym1[3] ;

            f_j00 =  wt_m1 * fy00[0] + wt_00 * fy00[1]
                   + wt_p1 * fy00[2] + wt_p2 * fy00[3] ;

            f_jp1 =  wt_m1 * fyp1[0] + wt_00 * fyp1[1]
                   + wt_p1 * fyp1[2] + wt_p2 * fyp1[3] ;

            f_jp2 =  wt_m1 * fyp2[0] + wt_00 * fyp2[1]
                   + wt_p1 * fyp2[2] + wt_p2 * fyp2[3] ;

         } else {

            f_jm1 =  wt_m1 * FINS(ix-1,jy-1)
                   + wt_00 * FINS(ix  ,jy-1)
                   + wt_p1 * FINS(ix+1,jy-1)
                   + wt_p2 * FINS(ix+2,jy-1) ;

            f_j00 =   wt_m1 * FINS(ix-1,jy)
                    + wt_00 * FINS(ix  ,jy)
                    + wt_p1 * FINS(ix+1,jy)
                    + wt_p2 * FINS(ix+2,jy) ;

            f_jp1 =   wt_m1 * FINS(ix-1,jy+1)
                    + wt_00 * FINS(ix  ,jy+1)
                    + wt_p1 * FINS(ix+1,jy+1)
                    + wt_p2 * FINS(ix+2,jy+1) ;

            f_jp2 =   wt_m1 * FINS(ix-1,jy+2)
                    + wt_00 * FINS(ix  ,jy+2)
                    + wt_p1 * FINS(ix+1,jy+2)
                    + wt_p2 * FINS(ix+2,jy+2) ;
         }

#define THIRTYSIX 2.7777778e-2  /* 1./36.0, actually */

#ifdef USE_CGRID
         jfy = (yy-jy)*CGRID + 0.499 ;
         val = (  p_m1[jfy] * f_jm1 + p_00[jfy] * f_j00
                + p_p1[jfy] * f_jp1 + p_p2[jfy] * f_jp2 ) * THIRTYSIX ;
#else
         fy  = yy-jy ;
         val = (  P_M1(fy) * f_jm1 + P_00(fy) * f_j00
                + P_P1(fy) * f_jp1 + P_P2(fy) * f_jp2 ) * THIRTYSIX ;
#endif

              if( val < bot ) nar[ii+jj*nx] = bot ;  /* too small! */
         else if( val > top ) nar[ii+jj*nx] = top ;  /* too big!   */
         else                 nar[ii+jj*nx] = val ;  /* just right */

      }
   }

   /*** cleanup and return ***/

   if( im != imfl ) mri_free(imfl) ;  /* throw away unneeded workspace */
   MRI_COPY_AUX(newImg,im) ;
   return newImg ;
}
Example #27
0
int main( int argc , char * argv[] )
{
   THD_3dim_dataset *dset ;
   int iarg=1 ;
   char *cc1="x",*cc2="y",*cc3="z" ;
   float th1=0.0, th2=0.0, th3=0.0 ;
   float thx,thy,thz ;
   int   axx,ayy,azz ;
   char *fname="testcox.ppm" , fn[128] ;
   void * rhand ;
   int bot=1 , ii , nim=0 ;
   float omap[128] , bfac ;
   MRI_IMAGE * im , * brim ;
   int hbr[256] , nperc,ibot,itop,sum ;
   byte * bar ;
   double ctim ;
   int imode=CREN_TWOSTEP ;
   int pmode=CREN_SUM_VOX ;

   if( argc < 2 || strcmp(argv[1],"-help") == 0 ){
      printf("Usage: testcox [-rotate a b c] [-mip|-MIP] [-out f] [-bot b] [-nn|-ts|-li] dset\n") ;
      exit(0) ;
   }

   enable_mcw_malloc() ;

   while( iarg < argc && argv[iarg][0] == '-' ){

      if( strcmp(argv[iarg],"-MIP") == 0 ){
        pmode = CREN_MIP_VOX ; iarg++ ; continue ;
      }
      if( strcmp(argv[iarg],"-mip") == 0 ){
        pmode = CREN_MINIP_VOX ; iarg++ ; continue ;
      }

      if( strcmp(argv[iarg],"-nn") == 0 ){
         imode = CREN_NN ;
         iarg++ ; continue ;
      }

      if( strcmp(argv[iarg],"-ts") == 0 ){
         imode = CREN_TWOSTEP ;
         iarg++ ; continue ;
      }

      if( strcmp(argv[iarg],"-li") == 0 ){
         imode = CREN_LINEAR ;
         iarg++ ; continue ;
      }

      if( strcmp(argv[iarg],"-bot") == 0 ){
         bot = strtod( argv[++iarg] , NULL ) ;
         iarg++ ; continue ;
      }

      if( strcmp(argv[iarg],"-rotate") == 0 ){
         th1 = (PI/180.0) * strtod( argv[++iarg] , &cc1 ) ;
         th2 = (PI/180.0) * strtod( argv[++iarg] , &cc2 ) ;
         th3 = (PI/180.0) * strtod( argv[++iarg] , &cc3 ) ;

         iarg++ ; continue ;
      }

      if( strcmp(argv[iarg],"-out") == 0 ){
         fname = argv[++iarg] ;
         iarg++ ; continue ;
      }

      fprintf(stderr,"Illegal option: %s\n",argv[iarg]); exit(1);
   }

   if( iarg >= argc ){fprintf(stderr,"No dataset?\n"); exit(1); }

   dset = THD_open_dataset( argv[iarg] ) ;
   if( dset == NULL ){fprintf(stderr,"Can't open dataset!\n");exit(1);}
   if( DSET_BRICK_TYPE(dset,0) != MRI_byte ){
      fprintf(stderr,"Non-byte dataset input!\n");exit(1);
   }
   DSET_mallocize(dset) ; DSET_load(dset) ;
   if( !DSET_LOADED(dset) ){
      fprintf(stderr,"Can't load dataset!\n");exit(1);
   }

   rhand = new_CREN_renderer() ;

#if 0
   THD_rotangle_user_to_dset( dset ,
                              th1,*cc1  , th2,*cc2  , th3,*cc3 ,
                              &thx,&axx , &thy,&ayy , &thz,&azz ) ;
   CREN_set_viewpoint( rhand , axx,thx,ayy,thy,azz,thz ) ;
#else
   CREN_set_angles( rhand , th1,th2,th3 ) ;
#endif

   for( ii=0 ; ii < 128 ; ii++ )
      omap[ii] = (ii <= bot) ? 0.0
                             : (ii-bot)/(127.0-bot) ;

   CREN_set_opamap( rhand , omap , 1.0 ) ;

   brim = DSET_BRICK(dset,0) ; bar = MRI_BYTE_PTR(brim) ;
   mri_histobyte( brim , hbr ) ;
   nperc = 0.02 * brim->nvox ;
   for( sum=0,ibot=0   ; ibot < 128  && sum < nperc ; ibot++ ) sum += hbr[ibot] ;
   for( sum=0,itop=255 ; itop > ibot && sum < nperc ; itop-- ) sum += hbr[itop] ;
   if( ibot >= itop ){ ibot = 64 ; itop = 192 ; }
   bfac = 127.5 / (itop-ibot) ;
   for( ii=0 ; ii < brim->nvox ; ii++ )
           if( bar[ii] <= ibot ) bar[ii] = 0 ;
      else if( bar[ii] >= itop ) bar[ii] = 127 ;
      else                       bar[ii] = bfac * (bar[ii]-ibot) ;


   ctim = COX_cpu_time() ;

   CREN_set_databytes( rhand , brim->nx,brim->ny,brim->nz , bar ) ;
   CREN_dset_axes( rhand , dset ) ;

   CREN_set_render_mode( rhand , pmode ) ;

   CREN_set_interp( rhand , imode ) ;

   for( th3=0 ; th3 < 360.0 ; th3+=5.0 ){
      CREN_set_angles( rhand , th1,th2,(PI/180.0)*th3 ) ;
      im = CREN_render( rhand, NULL ) ;  /* added NULL   2002.08.28 - rickr */
      if( im == NULL ){
        fprintf(stderr,"renderer fails!\n") ; exit(1) ;
      }

      sprintf(fn,"tc%03d.jpg",(int)rint(th3)) ;
      mri_write_pnm( fn, im ) ;
      fprintf(stderr,"+++ Output to file %s\n",fn);
      mri_free(im) ; nim++ ;
   }
   ctim = COX_cpu_time() - ctim ;
   fprintf(stderr,"+++ Rendering CPU time = %g s = %g/im\n",ctim,ctim/nim) ;

   exit(0) ;
}
Example #28
0
MRI_IMAGE * mri_rota_shear( MRI_IMAGE *im, float aa, float bb, float phi )
{
   double cph , sph ;
   float a , b , bot,top ;
   MRI_IMAGE *flim ;
   float *flar ;
   int ii , nxy ;

   if( im == NULL || ! MRI_IS_2D(im) ){
      fprintf(stderr,"*** mri_rota_shear only works on 2D images!\n") ; EXIT(1) ;
   }

   /** if complex image, break into pairs, do each separately, put back together **/

   if( im->kind == MRI_complex ){
      MRI_IMARR *impair ;
      MRI_IMAGE * rim , * iim , * tim ;
      impair = mri_complex_to_pair( im ) ;
      if( impair == NULL ){
         fprintf(stderr,"*** mri_complex_to_pair fails in mri_rota!\n") ; EXIT(1) ;
      }
      rim  = IMAGE_IN_IMARR(impair,0) ;
      iim  = IMAGE_IN_IMARR(impair,1) ;  FREE_IMARR(impair) ;
      tim  = mri_rota_shear( rim , aa,bb,phi ) ; mri_free( rim ) ; rim = tim ;
      tim  = mri_rota_shear( iim , aa,bb,phi ) ; mri_free( iim ) ; iim = tim ;
      flim = mri_pair_to_complex( rim , iim ) ;
      mri_free( rim ) ; mri_free( iim ) ;
      MRI_COPY_AUX(flim,im) ;
      return flim ;
   }

   /** copy input to output **/

   flim = mri_to_float( im ) ;
   flar = MRI_FLOAT_PTR( flim ) ;

   /* find range of image data */

   bot = top = flar[0] ; nxy = im->nx * im->ny ;
   for( ii=1 ; ii < nxy ; ii++ )
           if( flar[ii] < bot ) bot = flar[ii] ;
      else if( flar[ii] > top ) top = flar[ii] ;

   /** rotation params **/

   cph = cos(phi) ; sph = sin(phi) ;

   /* More than 90 degrees?
      Must be reduced to less than 90 degrees by a 180 degree flip. */

   if( cph < 0.0 ){
      int ii , jj , top , nx=flim->nx , ny=flim->ny ;
      float val ;

      top = (nx+1)/2 ;
      for( jj=0 ; jj < ny ; jj++ ){
         for( ii=1 ; ii < top ; ii++ ){
            val               = flar[jj*nx+ii] ;
            flar[jj*nx+ii]    = flar[jj*nx+nx-ii] ;
            flar[jj*nx+nx-ii] = val ;
         }
      }

      top = (ny+1)/2 ;
      for( ii=0 ; ii < nx ; ii++ ){
         for( jj=1 ; jj < top ; jj++ ){
            val                 = flar[ii+jj*nx] ;
            flar[ii+jj*nx]      = flar[ii+(ny-jj)*nx] ;
            flar[ii+(ny-jj)*nx] = val ;
         }
      }

      cph = -cph ; sph = -sph ;
   }

   /* compute shear factors for each direction */

   b = sph ;
   a = (b != 0.0 ) ? ((cph - 1.0) / b) : (0.0) ;

   /* shear thrice */

   ft_xshear( a , 0.0       , im->nx , im->ny , flar ) ;
   ft_yshear( b , bb        , im->nx , im->ny , flar ) ;
   ft_xshear( a , aa - a*bb , im->nx , im->ny , flar ) ;

   /* make sure data does not go out of original range */

   for( ii=0 ; ii < nxy ; ii++ )
           if( flar[ii] < bot ) flar[ii] = bot ;
      else if( flar[ii] > top ) flar[ii] = top ;

   return flim ;
}
Example #29
0
int WB_netw_corr(int Do_r, 
                 int Do_Z,
                 int HAVE_ROIS, 
                 char *prefix, 
                 int NIFTI_OUT,
                 int *NROI_REF,
                 int *Dim,
                 double ***ROI_AVE_TS,
                 int **ROI_LABELS_REF,
                 THD_3dim_dataset *insetTIME,
                 byte *mskd2,
                 int Nmask,
                 int argc,
                 char *argv[])
{
   int i,j,k;
   float **AVE_TS_fl=NULL;    // not great, but another format of TS
   char OUT_indiv0[300];
   char OUT_indiv[300];
   char OUT_indivZ[300];
   MRI_IMAGE *mri=NULL;
   THD_3dim_dataset *OUT_CORR_MAP=NULL;
   THD_3dim_dataset *OUT_Z_MAP=NULL;
   float *zscores=NULL;
   int Nvox;


   Nvox = Dim[0]*Dim[1]*Dim[2];

   // make average time series per voxel
   AVE_TS_fl = calloc( 1,sizeof(AVE_TS_fl));  
   for(i=0 ; i<1 ; i++) 
      AVE_TS_fl[i] = calloc(Dim[3],sizeof(float)); 
   
   if( (AVE_TS_fl == NULL) ) {
      fprintf(stderr, "\n\n MemAlloc failure (time series out).\n\n");
      exit(123);
   }

   fprintf(stderr,"\nHAVE_ROIS=%d",HAVE_ROIS);
   for( k=0 ; k<HAVE_ROIS ; k++) { // each netw gets own file
      sprintf(OUT_indiv0,"%s_%03d_INDIV", prefix, k);
      mkdir(OUT_indiv0, 0777);
      for( i=0 ; i<NROI_REF[k] ; i++ ) {
         fprintf(stderr,"\nNROI_REF[%d]= %d",k,NROI_REF[k]);
         for( j=0 ; j<Dim[3] ; j++)
            AVE_TS_fl[0][j] = (float) ROI_AVE_TS[k][i][j];
         if( NIFTI_OUT )
            sprintf(OUT_indiv,"%s/WB_CORR_ROI_%03d.nii.gz",
                    OUT_indiv0,ROI_LABELS_REF[k][i+1]);
         else
            sprintf(OUT_indiv,"%s/WB_CORR_ROI_%03d",
                    OUT_indiv0,ROI_LABELS_REF[k][i+1]);
         mri = mri_float_arrays_to_image(AVE_TS_fl,Dim[3],1);
         OUT_CORR_MAP = THD_Tcorr1D(insetTIME, mskd2, Nmask,
                                    mri,
                                    "pearson", OUT_indiv);
         if(Do_r){
            THD_load_statistics(OUT_CORR_MAP);
            tross_Copy_History( insetTIME , OUT_CORR_MAP ) ;
            tross_Make_History( "3dNetcorr", argc, argv, OUT_CORR_MAP );
            if( !THD_ok_overwrite() && 
                THD_is_ondisk(DSET_HEADNAME(OUT_CORR_MAP)) )
               ERROR_exit("Can't overwrite existing dataset '%s'",
                          DSET_HEADNAME(OUT_CORR_MAP));
            THD_write_3dim_dataset(NULL, NULL, OUT_CORR_MAP, True);
            INFO_message("Wrote dataset: %s\n",DSET_BRIKNAME(OUT_CORR_MAP));

         }
         if(Do_Z){
          if( NIFTI_OUT )
             sprintf(OUT_indivZ,"%s/WB_Z_ROI_%03d.nii.gz",
                     OUT_indiv0,ROI_LABELS_REF[k][i+1]);
          else
             sprintf(OUT_indivZ,"%s/WB_Z_ROI_%03d",
                     OUT_indiv0,ROI_LABELS_REF[k][i+1]);

            OUT_Z_MAP = EDIT_empty_copy(OUT_CORR_MAP);
            EDIT_dset_items( OUT_Z_MAP,
                             ADN_nvals, 1,
                             ADN_datum_all , MRI_float , 
                             ADN_prefix    , OUT_indivZ,
                             ADN_none ) ;
            if( !THD_ok_overwrite() && 
                THD_is_ondisk(DSET_HEADNAME(OUT_Z_MAP)) )
               ERROR_exit("Can't overwrite existing dataset '%s'",
                          DSET_HEADNAME(OUT_Z_MAP));

            zscores = (float *)calloc(Nvox,sizeof(float)); 
            if( (zscores == NULL) ) {
               fprintf(stderr, "\n\n MemAlloc failure (zscores).\n\n");
               exit(123);
            }

            for( j=0 ; j<Nvox ; j++ )
              if( mskd2[j] ) // control for r ==1
                 BOBatanhf( THD_get_voxel(OUT_CORR_MAP, j, 0) );
                 /*
                 if( THD_get_voxel(OUT_CORR_MAP, j, 0) > MAX_R )
                   zscores[j] = (float) atanh(MAX_R);
                 else if ( THD_get_voxel(OUT_CORR_MAP, j, 0) < -MAX_R )
                   zscores[j] =  (float) atanh(-MAX_R);
                 else
                 zscores[j] = (float) atanh(THD_get_voxel(OUT_CORR_MAP, j, 0));*/
            
            EDIT_substitute_brick(OUT_Z_MAP, 0, MRI_float, zscores); 
            zscores=NULL;

            THD_load_statistics(OUT_Z_MAP);
            tross_Copy_History(insetTIME, OUT_Z_MAP);
            tross_Make_History("3dNetcorr", argc, argv, OUT_Z_MAP);
            THD_write_3dim_dataset(NULL, NULL, OUT_Z_MAP, True);
            INFO_message("Wrote dataset: %s\n",DSET_BRIKNAME(OUT_Z_MAP));

            DSET_delete(OUT_Z_MAP);
            free(OUT_Z_MAP);
            OUT_Z_MAP=NULL;
         }

         DSET_delete(OUT_CORR_MAP);
         free(OUT_CORR_MAP);
         OUT_CORR_MAP=NULL;
      }
   }
   
   free(zscores);
   mri_free(mri);
   for( i=0 ; i<1 ; i++) 
      free(AVE_TS_fl[i]);
   free(AVE_TS_fl);

   RETURN(1);
}
Example #30
0
int main( int argc , char *argv[] )
{
   THD_3dim_dataset *inset=NULL , *outset=NULL ;
   MCW_cluster *nbhd=NULL ;
   byte *mask=NULL ; int mask_nx,mask_ny,mask_nz , automask=0 ;
   char *prefix="./LocalCormat" ;
   int iarg=1 , verb=1 , ntype=0 , kk,nx,ny,nz,nxy,nxyz,nt , xx,yy,zz, vstep ;
   float na,nb,nc , dx,dy,dz ;
   MRI_IMARR *imar=NULL ; MRI_IMAGE *pim=NULL ;
   int mmlag=10 , ii,jj , do_arma=0 , nvout ;
   MRI_IMAGE *concim=NULL ; float *concar=NULL ;

   if( argc < 2 || strcmp(argv[1],"-help") == 0 ){
     printf(
       "Usage: 3dLocalCORMAT [options] inputdataset\n"
       "\n"
       "Compute the correlation matrix (in time) of the input dataset,\n"
       "up to lag given by -maxlag.  The matrix is averaged over the\n"
       "neighborhood specified by the -nbhd option, and then the entries\n"
       "are output at each voxel in a new dataset.\n"
       "\n"
       "Normally, the input to this program would be the -errts output\n"
       "from 3dDeconvolve, or the equivalent residuals from some other\n"
       "analysis.  If you input a non-residual time series file, you at\n"
       "least should use an appropriate -polort level for detrending!\n"
       "\n"
       "Options:\n"
       "  -input inputdataset\n"
       "  -prefix ppp\n"
       "  -mask mset    {these 2 options are}\n"
       "  -automask     {mutually exclusive.}\n"
       "  -nbhd nnn     [e.g., 'SPHERE(9)' for 9 mm radius]\n"
       "  -polort ppp   [default = 0, which is reasonable for -errts output]\n"
       "  -concat ccc   [as in 3dDeconvolve]\n"
       "  -maxlag mmm   [default = 10]\n"
       "  -ARMA         [estimate ARMA(1,1) parameters into last 2 sub-bricks]\n"
       "\n"
       "A quick hack for my own benignant purposes -- RWCox -- June 2008\n"
     ) ;
     PRINT_COMPILE_DATE ; exit(0) ;
   }

   /*---- official startup ---*/

   PRINT_VERSION("3dLocalCormat"); mainENTRY("3dLocalCormat main"); machdep();
   AFNI_logger("3dLocalCormat",argc,argv); AUTHOR("Zhark the Toeplitzer");

   /*---- loop over options ----*/

   while( iarg < argc && argv[iarg][0] == '-' ){

#if 0
fprintf(stderr,"argv[%d] = %s\n",iarg,argv[iarg]) ;
#endif

     if( strcmp(argv[iarg],"-ARMA") == 0 ){
       do_arma = 1 ; iarg++ ; continue ;
     }

     if( strcmp(argv[iarg],"-polort") == 0 ){
       char *cpt ;
       if( ++iarg >= argc )
         ERROR_exit("Need argument after option %s",argv[iarg-1]) ;
       pport = (int)strtod(argv[iarg],&cpt) ;
       if( *cpt != '\0' )
         WARNING_message("Illegal non-numeric value after -polort") ;
       if( pport > 3 ){
         pport = 3 ; WARNING_message("-polort set to 3 == max implemented") ;
       } else if( pport < 0 ){
         pport = 0 ; WARNING_message("-polort set to 0 == min implemented") ;
       }
       iarg++ ; continue ;
     }

     if( strcmp(argv[iarg],"-input") == 0 ){
       if( inset != NULL  ) ERROR_exit("Can't have two -input options") ;
       if( ++iarg >= argc ) ERROR_exit("Need argument after '-input'") ;
       inset = THD_open_dataset( argv[iarg] ) ;
       CHECK_OPEN_ERROR(inset,argv[iarg]) ;
       iarg++ ; continue ;
     }

     if( strcmp(argv[iarg],"-prefix") == 0 ){
       if( ++iarg >= argc ) ERROR_exit("Need argument after '-prefix'") ;
       prefix = strdup(argv[iarg]) ;
       iarg++ ; continue ;
     }

     if( strcmp(argv[iarg],"-mask") == 0 ){
       THD_3dim_dataset *mset ; int mmm ;
       if( ++iarg >= argc ) ERROR_exit("Need argument after '-mask'") ;
       if( mask != NULL || automask ) ERROR_exit("Can't have two mask inputs") ;
       mset = THD_open_dataset( argv[iarg] ) ;
       CHECK_OPEN_ERROR(mset,argv[iarg]) ;
       DSET_load(mset) ; CHECK_LOAD_ERROR(mset) ;
       mask_nx = DSET_NX(mset); mask_ny = DSET_NY(mset); mask_nz = DSET_NZ(mset);
       mask = THD_makemask( mset , 0 , 0.5f, 0.0f ) ; DSET_delete(mset) ;
       if( mask == NULL ) ERROR_exit("Can't make mask from dataset '%s'",argv[iarg]) ;
       mmm = THD_countmask( mask_nx*mask_ny*mask_nz , mask ) ;
       INFO_message("Number of voxels in mask = %d",mmm) ;
       if( mmm < 2 ) ERROR_exit("Mask is too small to process") ;
       iarg++ ; continue ;
     }

     if( strcmp(argv[iarg],"-automask") == 0 ){
       if( mask != NULL ) ERROR_exit("Can't have -automask and -mask") ;
       automask = 1 ;
       iarg++ ; continue ;
     }

     if( strcmp(argv[iarg],"-nbhd") == 0 ){
       char *cpt ;
       if( ntype  >  0    ) ERROR_exit("Can't have 2 '-nbhd' options") ;
       if( ++iarg >= argc ) ERROR_exit("Need argument after '-nbhd'") ;

       cpt = argv[iarg] ;
       if( strncasecmp(cpt,"SPHERE",6) == 0 ){
         sscanf( cpt+7 , "%f" , &na ) ;
         if( na == 0.0f ) ERROR_exit("Can't have a SPHERE of radius 0") ;
         ntype = NTYPE_SPHERE ;
       } else if( strncasecmp(cpt,"RECT",4) == 0 ){
         sscanf( cpt+5 , "%f,%f,%f" , &na,&nb,&nc ) ;
         if( na == 0.0f && nb == 0.0f && nc == 0.0f )
           ERROR_exit("'RECT(0,0,0)' is not a legal neighborhood") ;
         ntype = NTYPE_RECT ;
       } else if( strncasecmp(cpt,"RHDD",4) == 0 ){
         sscanf( cpt+5 , "%f" , &na ) ;
         if( na == 0.0f ) ERROR_exit("Can't have a RHDD of radius 0") ;
         ntype = NTYPE_RHDD ;
       } else {
          ERROR_exit("Unknown -nbhd shape: '%s'",cpt) ;
       }
       iarg++ ; continue ;
     }
       
     if( strcmp(argv[iarg],"-maxlag") == 0 ){
       if( ++iarg >= argc )
         ERROR_exit("Need argument after option %s",argv[iarg-1]) ;
       mmlag = (int)strtod(argv[iarg],NULL) ;
       iarg++ ; continue ;
     }   

     if( strcmp(argv[iarg],"-concat") == 0 ){
       if( concim != NULL )
         ERROR_exit("Can't have two %s options!",argv[iarg]) ;
       if( ++iarg >= argc )
         ERROR_exit("Need argument after option %s",argv[iarg-1]) ;
       concim = mri_read_1D( argv[iarg] ) ;
       if( concim == NULL )
         ERROR_exit("Can't read -concat file '%s'",argv[iarg]) ;
       if( concim->nx < 2 )
         ERROR_exit("-concat file '%s' must have at least 2 entries!",
                    argv[iarg]) ;
       concar = MRI_FLOAT_PTR(concim) ;
       for( ii=1 ; ii < concim->nx ; ii++ )
         if( (int)concar[ii-1] >= (int)concar[ii] )
           ERROR_exit("-concat file '%s' is not ordered increasingly!",
                      argv[iarg]) ;
       iarg++ ; continue ;
     }

     ERROR_exit("Unknown option '%s'",argv[iarg]) ;

   } /*--- end of loop over options ---*/

   if( do_arma && mmlag > 0 && mmlag < 5 )
     ERROR_exit("Can't do -ARMA with -maxlag %d",mmlag) ;

   /*---- deal with input dataset ----*/

   if( inset == NULL ){
     if( iarg >= argc ) ERROR_exit("No input dataset on command line?") ;
     inset = THD_open_dataset( argv[iarg] ) ;
     CHECK_OPEN_ERROR(inset,argv[iarg]) ;
   }
   ntime = DSET_NVALS(inset) ;
   if( ntime < 9 )
     ERROR_exit("Must have at least 9 values per voxel") ;

   DSET_load(inset) ; CHECK_LOAD_ERROR(inset) ;

   if( mask != NULL ){
     if( mask_nx != DSET_NX(inset) ||
         mask_ny != DSET_NY(inset) ||
         mask_nz != DSET_NZ(inset)   )
       ERROR_exit("-mask dataset grid doesn't match input dataset") ;

   } else if( automask ){
     int mmm ;
     mask = THD_automask( inset ) ;
     if( mask == NULL )
       ERROR_message("Can't create -automask from input dataset?") ;
     mmm = THD_countmask( DSET_NVOX(inset) , mask ) ;
     INFO_message("Number of voxels in automask = %d",mmm) ;
     if( mmm < 2 ) ERROR_exit("Automask is too small to process") ;
   }

   /*-- set up blocks of continuous time data --*/
       
   if( DSET_IS_TCAT(inset) ){
     if( concim != NULL ){
       WARNING_message("Ignoring -concat, since dataset is auto-catenated") ;
       mri_free(concim) ;
     }
     concim = mri_new(inset->tcat_num,1,MRI_float) ;
     concar = MRI_FLOAT_PTR(concim) ;
     concar[0] = 0.0 ;
     for( ii=0 ; ii < inset->tcat_num-1 ; ii++ )
       concar[ii+1] = concar[ii] + inset->tcat_len[ii] ;
   } else if( concim == NULL ){ 
     concim = mri_new(1,1,MRI_float) ;
     concar = MRI_FLOAT_PTR(concim)  ; concar[0] = 0 ;
   }
   nbk = concim->nx ;
   bk  = (int *)malloc(sizeof(int)*(nbk+1)) ;
   for( ii=0 ; ii < nbk ; ii++ ) bk[ii] = (int)concar[ii] ;
   bk[nbk] = ntime ;
   mri_free(concim) ;
   mlag = DSET_NVALS(inset) ;
   for( ii=0 ; ii < nbk ; ii++ ){
     jj = bk[ii+1]-bk[ii] ; if( jj < mlag ) mlag = jj ;
     if( bk[ii] < 0 || jj < 9 )
       ERROR_exit("something is rotten in the dataset run lengths") ;
   }
   mlag-- ;
   if( mmlag > 0 && mlag > mmlag ) mlag = mmlag ;
   else                            INFO_message("Max lag set to %d",mlag) ;

   if( do_arma && mlag < 5 )
     ERROR_exit("Can't do -ARMA with maxlag=%d",mlag) ;

   /*---- create neighborhood (as a cluster) -----*/

   if( ntype <= 0 ){         /* default neighborhood */
     ntype = NTYPE_SPHERE ; na = -1.01f ;
     INFO_message("Using default neighborhood = self + 6 neighbors") ;
   }

   switch( ntype ){
     default:
       ERROR_exit("WTF?  ntype=%d",ntype) ;

     case NTYPE_SPHERE:{
       if( na < 0.0f ){ dx = dy = dz = 1.0f ; na = -na ; }
       else           { dx = fabsf(DSET_DX(inset)) ;
                        dy = fabsf(DSET_DY(inset)) ;
                        dz = fabsf(DSET_DZ(inset)) ; }
       nbhd = MCW_spheremask( dx,dy,dz , na ) ;
     }
     break ;

     case NTYPE_RECT:{
       if( na < 0.0f ){ dx = 1.0f; na = -na; } else dx = fabsf(DSET_DX(inset));
       if( nb < 0.0f ){ dy = 1.0f; nb = -nb; } else dy = fabsf(DSET_DY(inset));
       if( nc < 0.0f ){ dz = 1.0f; nc = -nc; } else dz = fabsf(DSET_DZ(inset));
       nbhd = MCW_rectmask( dx,dy,dz , na,nb,nc ) ;
     }
     break ;

     case NTYPE_RHDD:{
       if( na < 0.0f ){ dx = dy = dz = 1.0f ; na = -na ; }
       else           { dx = fabsf(DSET_DX(inset)) ;
                        dy = fabsf(DSET_DY(inset)) ;
                        dz = fabsf(DSET_DZ(inset)) ; }
       nbhd = MCW_rhddmask( dx,dy,dz , na ) ;
     }
     break ;
   }
   MCW_radsort_cluster( nbhd , dx,dy,dz ) ;  /* 26 Feb 2008 */

   INFO_message("Neighborhood comprises %d voxels",nbhd->num_pt) ;

   /** create output dataset **/

   outset = EDIT_empty_copy(inset) ;
   nvout  = mlag ; if( do_arma ) nvout += 2 ;
   EDIT_dset_items( outset,
                      ADN_prefix   , prefix,
                      ADN_brick_fac, NULL  ,
                      ADN_nvals    , nvout ,
                      ADN_ntt      , nvout ,
                    ADN_none );
   tross_Copy_History( inset , outset ) ;
   tross_Make_History( "3dLocalCormat" , argc,argv , outset ) ;
   for( kk=0 ; kk < nvout ; kk++ )
     EDIT_substitute_brick( outset , kk , MRI_float , NULL ) ;

   nx = DSET_NX(outset) ;
   ny = DSET_NY(outset) ; nxy  = nx*ny  ;
   nz = DSET_NZ(outset) ; nxyz = nxy*nz ;
   vstep = (verb && nxyz > 999) ? nxyz/50 : 0 ;
   if( vstep ) fprintf(stderr,"++ voxel loop: ") ;

   /** actually do the long long slog through all voxels **/

   for( kk=0 ; kk < nxyz ; kk++ ){
     if( vstep && kk%vstep==vstep-1 ) vstep_print() ;
     if( !INMASK(kk) ) continue ;
     IJK_TO_THREE( kk , xx,yy,zz , nx,nxy ) ;
     imar = THD_get_dset_nbhd_array( inset , mask , xx,yy,zz , nbhd ) ;
     if( imar == NULL ) continue ;
     pim = mri_cormat_vector(imar) ; DESTROY_IMARR(imar) ;
     if( pim == NULL ) continue ;
     THD_insert_series( kk, outset, pim->nx, MRI_float, MRI_FLOAT_PTR(pim), 0 ) ;

     if( do_arma ){  /* estimate ARMA(1,1) params and store those, too */
       float_pair ab ;
       float *aa=DSET_ARRAY(outset,mlag), *bb=DSET_ARRAY(outset,mlag+1) ;
       ab = estimate_arma11( pim->nx , MRI_FLOAT_PTR(pim) ) ;
       aa[kk] = ab.a ; bb[kk] = ab.b ;
     }

     mri_free(pim) ;
   }
   if( vstep ) fprintf(stderr,"\n") ;

   DSET_delete(inset) ;
   DSET_write(outset) ;
   WROTE_DSET(outset) ;

   exit(0) ;
}