コード例 #1
0
/*---------------------------------------------------------------------
  23 Feb 2012: Return the absolute value of the difference between 
               two volumes, divided by the number of voxels
               and the number of sub-bricks. Voxels that are zero
               in both sets are not counted.
               Comparisons are done after conversion of data to double
    return = -1.0 ERROR
           =  0.0 Exactly the same
-----------------------------------------------------------------------*/
double THD_diff_vol_vals(THD_3dim_dataset *d1, THD_3dim_dataset *d2, int scl) {
   double dd=0.0, denom=0.0;
   int i=0, k=0;
   double *a1=NULL, *a2=NULL;
   MRI_IMAGE *b1 = NULL , *b2 = NULL;
   
   ENTRY("THD_diff_vol_vals");
   
   if (!d1 && !d2) RETURN(dd);
   if (!d1 || !d2) RETURN(-1.0);

   if (!EQUIV_GRIDS(d1,d2)) RETURN(-1.0);
   if (DSET_NVALS(d1) != DSET_NVALS(d2)) RETURN(-1.0);
  
   DSET_mallocize(d1) ; DSET_load(d1) ;
   DSET_mallocize(d2) ; DSET_load(d2) ;
   dd = 0.0; denom = 0;
   for (i=0; i<DSET_NVALS(d1); ++i) {
      b1 = THD_extract_double_brick(i, d1);
      b2 = THD_extract_double_brick(i, d2);
      a1 = MRI_DOUBLE_PTR(b1);
      a2 = MRI_DOUBLE_PTR(b2);
      for (k=0; k<DSET_NVOX(d1); ++k) {
         dd += ABS(a1[k]-a2[k]);
         if (a1[k]!=0.0 || a2[k]!=0.0) ++denom;
      }
      mri_clear_data_pointer(b1); mri_free(b1) ;
      mri_clear_data_pointer(b2); mri_free(b2) ;
   }
   if (scl && denom>0.0) dd /= denom;
   
   RETURN(dd);   
}  
コード例 #2
0
Boolean THD_write_datablock( THD_datablock *blk , Boolean write_brick )
{
   THD_diskptr *dkptr ;
   Boolean good ;
   int id , nx , ny , nz , nv , nxy , nxyz , ibr ;
   int atrank[ATRSIZE_DATASET_RANK] , atdims[ATRSIZE_DATASET_DIMENSIONS] ;
   MRI_IMAGE *im ;
   int save_order ;
   int64_t nb , idone ;
   int do_mripurge ;

   /*-- sanity checks --*/

   if( ! ISVALID_DATABLOCK(blk) ) return False ;
   if( DBLK_IS_MASTERED(blk) )    return False ;  /* 11 Jan 1999 */
   if( DBLK_IS_MINC(blk) ) WRITE_ERR("MINC with bad name extension?") ;
                                                               /* 29 Oct 2001 */
   if( DBLK_IS_ANALYZE(blk) ) WRITE_ERR("ANALYZE but bad name extension?") ; 
                                                               /* 27 Aug 2002 */
   if( DBLK_IS_NIFTI(blk) ) WRITE_ERR("NIFTI but bad name extension?") ;  
                                                               /* 28 Aug 2003 */

   dkptr = blk->diskptr ;
   if( ! ISVALID_DISKPTR(dkptr) ) WRITE_ERR("illegal file type") ;

   if( strlen(dkptr->directory_name) == 0 ||
       strlen(dkptr->header_name)    == 0 ||
       strlen(dkptr->filecode)       == 0   )
     WRITE_ERR("illegal file names stored in dataset") ;

   if( dkptr->rank != 3 )
     WRITE_ERR("cannot write non-3D datablock") ;

   /*-- create directory if necessary --*/

   if( ! THD_is_directory(dkptr->directory_name) ){
     id = mkdir( dkptr->directory_name , THD_MKDIR_MODE ) ;
     if( id != 0 ){
       fprintf(stderr,
            "\n"
            "*** cannot mkdir new directory: %s\n"
            "  - Do you have permission to write to this disk?\n"
            "  - Is the disk full?\n" ,
            dkptr->directory_name) ;
       return False ;
     }
   }

   /* 25 April 1998: deal with byte order issues */

   if( native_order < 0 ){                /* initialization */
     native_order = mri_short_order() ;
     if( output_order < 0 ) THD_enviro_write_order() ;
   }
   if( dkptr->byte_order <= 0 ) dkptr->byte_order = native_order ;
   save_order = (output_order > 0) ? output_order
                                   : dkptr->byte_order ;

#if 0
fprintf(stderr,"THD_write_datablock: save_order=%d  dkptr->byte_order=%d\n",
               save_order, dkptr->byte_order ) ;
#endif

   if( save_order != LSB_FIRST && save_order != MSB_FIRST )
     save_order = native_order ;

   if( save_order == LSB_FIRST )
     THD_set_string_atr( blk , ATRNAME_BYTEORDER , LSB_FIRST_STRING ) ;
   else if( save_order == MSB_FIRST )
     THD_set_string_atr( blk , ATRNAME_BYTEORDER , MSB_FIRST_STRING ) ;

   /*-- actually write attributes to disk --*/

   good = THD_write_atr( blk ) ;
   if( good == False )
     WRITE_ERR(
     "failure to write attributes - is disk full? do you have write permission?");

   /*-- if not writing data, can exit --*/

   if( write_brick == False || blk->brick == NULL ||
       dkptr->storage_mode == STORAGE_UNDEFINED     ) return True ;

   if( dkptr->storage_mode == STORAGE_BY_VOLUMES ){  /* 20 Jun 2002 */
     fprintf(stderr,"** Writing dataset by VOLUMES not yet supported.\n") ;
     return False ;
   }

   /*-- check each brick for existence:
          if none exist, cannot write, but is OK
          if some but not all exist, cannot write, and is an error --*/

   id = THD_count_potential_databricks( blk ) ;
   if( id <= 0 )         return True ;
   if( id < blk->nvals ){
     ERROR_message("Write dataset error: only %d out of %d bricks in memory",
                   id,blk->nvals) ; return False ;
   }

   if( blk->malloc_type == DATABLOCK_MEM_UNDEFINED )
     WRITE_ERR("undefined data exists in memory") ;

   /*-- 13 Mar 2006: check for free disk space --*/

   { int mm = THD_freemegabytes( dkptr->header_name ) ;
     int rr = blk->total_bytes / (1024l * 1024l) ;
     if( mm >= 0 && mm <= rr )
       WARNING_message("Disk space: writing file %s (%d MB),"
                       " but only %d free MB on disk"        ,
         dkptr->brick_name , rr , mm ) ;
   }

   /*-- write data out in whatever format is ordered --*/

   nx = dkptr->dimsizes[0] ;
   ny = dkptr->dimsizes[1] ;  nxy  = nx * ny ;
   nz = dkptr->dimsizes[2] ;  nxyz = nxy * nz ;
   nv = dkptr->nvals ;        nb   = blk->total_bytes ;

   switch( dkptr->storage_mode ){

      default: WRITE_ERR("illegal storage_mode!") ; break ;

      case STORAGE_BY_BRICK:{
         FILE *far ;
         Boolean purge_when_done = False , ok ;
         int force_gzip=0 , csave=COMPRESS_NONE ;

         /** if we have a mmap-ed file, copy into RAM (ugh) **/

         if( blk->malloc_type == DATABLOCK_MEM_MMAP ){
            char *bnew , *bold ;
            int offset ;

            bnew = (char *) malloc( (size_t)nb ) ;  /* work space */
            bold = DBLK_ARRAY(blk,0) ;              /* start of mapped file */

            if( bnew == NULL )
              WRITE_ERR("cannot rewrite due to malloc failure - is memory exhausted?") ;

            memcpy( bnew , bold , (size_t)nb ) ;    /* make a copy,    */
            munmap( (void *) bold , (size_t)nb ) ;  /* then unmap file */

            /* fix sub-brick pointers */

            offset = 0 ;
            for( ibr=0 ; ibr < nv ; ibr++ ){
               mri_fix_data_pointer( (void *)(bnew+offset) , DBLK_BRICK(blk,ibr) ) ;
               offset += DBLK_BRICK_BYTES(blk,ibr) ;
               DBLK_BRICK(blk,ibr)->fondisk = 0 ;   /* 31 Jan 2007 */
            }

            purge_when_done = True ;

         } /** fall thru to here if have a malloc-ed dataset **/

         if( save_order != native_order ) purge_when_done = True ;

         /** delete old file, if any **/

         COMPRESS_unlink( dkptr->brick_name ) ; /* Feb 1998 */

         /** create new file **/

         id = strlen(dkptr->directory_name) ;
         ok = ( dkptr->directory_name[id-1] == '/' ) ;
         if( ok ) sprintf( dkptr->brick_name , "%s%s.%s",
                           dkptr->directory_name ,
                           dkptr->filecode , DATASET_BRICK_SUFFIX );

         else     sprintf( dkptr->brick_name , "%s/%s.%s",
                           dkptr->directory_name ,
                           dkptr->filecode , DATASET_BRICK_SUFFIX );

      /** COMPRESS for output added Feb 1998 */

         if( compress_mode == COMPRESS_NOFILE ) THD_enviro_write_compression() ;

#ifdef COMPRESS_GZIP
         /*-- 02 Mar 2001: check if we will force gzip --*/

         if( compress_mode == COMPRESS_NONE && AFNI_yesenv("AFNI_AUTOGZIP") ){
            double entrop = ENTROPY_datablock(blk) ;
            force_gzip = (entrop < 2.7) ;
#if 0
fprintf(stderr,"Entropy=%g ==> forcing write gzip on %s\n",entrop,dkptr->brick_name) ;
#endif
         } else {
            force_gzip = 0 ;
         }
         if( force_gzip ){
            csave = compress_mode ; compress_mode = COMPRESS_GZIP ;
         }
#endif

         far = COMPRESS_fopen_write( dkptr->brick_name , compress_mode ) ;
         if( far == NULL ){
           if( compress_mode != COMPRESS_NONE ){
             compress_mode = COMPRESS_NONE ; force_gzip = 0 ;
             far = COMPRESS_fopen_write( dkptr->brick_name , compress_mode ) ;
           }
         }
         if( far == NULL )
           WRITE_ERR("cannot open output brick file - do you have write permission?") ;

         /** write each brick out in a separate operation **/

         idone = 0 ;
         for( ibr=0 ; ibr < nv ; ibr++ ){

           do_mripurge = MRI_IS_PURGED( DBLK_BRICK(blk,ibr) ) ;
           if( do_mripurge ) mri_unpurge( DBLK_BRICK(blk,ibr) ) ;

           if( save_order != native_order ){       /* 25 April 1998 */
             switch( DBLK_BRICK_TYPE(blk,ibr) ){
               default: break ;
               case MRI_short:
                 mri_swap2( DBLK_BRICK_NVOX(blk,ibr) , DBLK_ARRAY(blk,ibr) ) ;
               break ;

               case MRI_complex:   /* 23 Nov 1999 */
                 mri_swap4( 2*DBLK_BRICK_NVOX(blk,ibr), DBLK_ARRAY(blk,ibr)) ;
               break ;

               case MRI_float:     /* 23 Nov 1999 */
               case MRI_int:
                 mri_swap4( DBLK_BRICK_NVOX(blk,ibr) , DBLK_ARRAY(blk,ibr) ) ;
               break ;
             }
           }

           idone += fwrite( DBLK_ARRAY(blk,ibr), 1, DBLK_BRICK_BYTES(blk,ibr), far );

           if( do_mripurge ){                    /* 31 Jan 2007 */
             if( !purge_when_done ) mri_purge( DBLK_BRICK(blk,ibr) ) ;
             else                   mri_clear( DBLK_BRICK(blk,ibr) ) ;
           }
         } /* end of loop over sub-bricks */

         COMPRESS_fclose(far) ;

         if( purge_when_done ){
           if( blk->malloc_type == DATABLOCK_MEM_MMAP ){
             free( DBLK_ARRAY(blk,0) ) ;
             for( ibr=0 ; ibr < nv ; ibr++ )
               mri_clear_data_pointer( DBLK_BRICK(blk,ibr) ) ;
           } else {
             THD_purge_datablock( blk , DATABLOCK_MEM_MALLOC ) ;
           }
         }

         if( compress_mode >= 0 || save_order != native_order ){
           blk->malloc_type = DATABLOCK_MEM_MALLOC ;
         }
         DBLK_mmapfix(blk) ;  /* 28 Mar 2005 */

         if( force_gzip ) compress_mode = csave ; /* 02 Mar 2001 */

         if( idone != blk->total_bytes )
           WRITE_ERR("Write error in brick file: Is disk full, or write_protected?") ;

         dkptr->byte_order = save_order ;  /* 23 Nov 1999 */

         return True ;
      }
      break ;

   }  /* end of switch over data storage mode */

   return False ;  /* should NEVER be reached */
}
コード例 #3
0
ファイル: fit_onesign.c プロジェクト: Gilles86/afni
int
main (int argc, char **argv)
{
   int   i=0, j=0, n=0, nl=0, k=0,
         posi=0, posj=0, posk=0, ncol=0, nrow=0;
   double xi=0.0, yi=0.0, yy=0.0, ei=0.0, sumsq=0.0,  med=0.0;
   gsl_matrix *X=NULL, *cov=NULL;
   gsl_vector *y=NULL, *w=NULL, *c=NULL;
   MRI_IMAGE *im = NULL;
   double *dar = NULL;
   gsl_multifit_linear_workspace *work=NULL;
   
   if (argc != 2)
   {
     fprintf (stderr,"usage: fitanje_1sign data > outfile\n");
     exit (-1);
   }

   /* slower than specific code you had but more convenient.
      It allows you to use all the column and row selections
      we can do with filenames. Also, keeps you fron worrying
      about dimensions. 
      The problem with your code was assuming you had 13 columns always 
      That was not the case for stat5_fitcoef. 
      OK, that was caused by a problem in the scripts. That is fixed,
      but I leave this change here anyway. 
      */
   fprintf(stderr,"Patience, reading %s... ", argv[1]);
   im = mri_read_double_1D (argv[1]);
   if (!im) {
      fprintf(stderr,"Error: Failed to read matrix data from %s\n",
                     argv[1]);
      return(-1);
   }
   ncol = im->ny;
   nrow = im->nx;
   fprintf (stderr,"Have %d cols, %d rows\nNow fitting...", ncol, nrow);
   n = ncol-3;
   /* now just get the array and kill the rest */
   dar = MRI_DOUBLE_PTR(im);
   /* make sure that pointer is set to NULL in im, or risk hell */
   mri_clear_data_pointer(im) ;
   if (im) mri_free(im); im = NULL; /* now kill im */
   
   X = gsl_matrix_alloc (n, 5);
   y = gsl_vector_alloc (n);
     
   c = gsl_vector_alloc (5);
   cov = gsl_matrix_alloc (5, 5);
     
   for (i = 0; i < n; i++)  {
      xi = i+1;
      gsl_matrix_set (X, i, 0, 1.0);
      gsl_matrix_set (X, i, 1, xi);
      gsl_matrix_set (X, i, 2, xi*xi);

      gsl_matrix_set (X, i, 3, xi*xi*xi);
      gsl_matrix_set (X, i, 4, xi*xi*xi*xi);
      //    printf ("%lg ",xi);
    }


    /*make header
      printf ("matrvola\n");
      ZSS: By adding # to the text line, 
           I made the output file be a .1D format */
    fprintf(stdout, "#%s_0\t%s_1\t%s_2\t%s_3\t%s_4\n",
                    argv[1],argv[1],argv[1],argv[1],argv[1]);

    // go by lines - signatures
    /* pre-allocate, I think this should be just fine, 
       there should be no need to reinitialize work 
       all the time */   
    work = gsl_multifit_linear_alloc (n, 5);
    for (nl=0; nl<nrow; ++nl) {
      posi = (int)dar[nl];
      posj = (int)dar[nl+  nrow];
      posk = (int)dar[nl+2*nrow];

      for (k = 3; k < ncol; k++) {
         gsl_vector_set (y, k-3, dar[nl+k*nrow]);
      }
        
        
      gsl_multifit_linear (X, y, c, cov,
                           &sumsq, work);
    
                          
      /* printf ( "\n # best fit: Y = %g + %g X + %g X^2 +%g X^3 + %g X^4\n",
                  C(0), C(1), C(2), C(3), C(4));
         printf ("# sumsq = %g\n", sumsq); */

      fprintf (stdout,  "%11g\t%11g\t%11g\t%11g\t%11g\n", 
                        C(0), C(1), C(2), C(3), C(4)); 

      /*
      printf ("# covariance matrix:\n");
      printf ("[ %+.5e, %+.5e, %+.5e  \n",
              COV(0,0), COV(0,1), COV(0,2));
      printf ("  %+.5e, %+.5e, %+.5e  \n", 
              COV(1,0), COV(1,1), COV(1,2));
      printf ("  %+.5e, %+.5e, %+.5e ]\n", 
              COV(2,0), COV(2,1), COV(2,2));
       printf ("# chisq = %g\n", chisq);
      */
      
   }
   gsl_multifit_linear_free (work); work = NULL;
   
   free(dar); dar = NULL; /* done with input array */

    gsl_vector_free (y);
    gsl_vector_free (c);
    gsl_matrix_free (cov);
    gsl_matrix_free (X);
    //gsl_vector_free (w);
    
    fprintf (stderr,"\n");
    return 0;

}
コード例 #4
0
ファイル: 3dAcost.c プロジェクト: CesarCaballeroGaudes/afni
int main( int argc , char *argv[] )
{
   MRI_IMAGE *xim , *yim ;
   float     *xar , *yar , *war ;
   int iarg , ndset , nvox , ii , jj, xyall , clip=0 ;
   THD_3dim_dataset *xset , *yset , * mask_dset=NULL ;
   float xbot=1.0f,xtop=0.0f , ybot=1.0f,ytop=0.0f , val ;
   float xsum,ysum , xsig,ysig ;
   byte *mmm=NULL ;
   char *save_hist=NULL, *save_hist_1D=NULL ;

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

   if( argc < 3 || strncmp(argv[1],"-help",5) == 0 ){
     printf("Usage: 3dAcost [options] xset yset\n"
            "Output = 3dAllineate cost functions between 2 dataset bricks\n"
            "         (for debugging purposes, mostly).\n"
            "\n"
            "Options:\n"
            "  -mask mset   Means to use the dataset 'mset' as a mask:\n"
            "                 Only voxels with nonzero values in 'mset'\n"
            "                 will be averaged from 'dataset'.  Note\n"
            "                 that the mask dataset and the input dataset\n"
            "                 must have the same number of voxels.\n"
            " -histpow p    Set histogram power to 'p'; number of bins in\n"
            "                 histogram (each axis) = n^p (n=# of points).\n"
            "                 (Default is p=0.33333.)\n"
            " -histbin m    Set histogram to use 'm' bins (each axis).\n"
            "                 (Max number of bins is 255.)\n"
            " -savehist ss  Save 2D histogram to image file 'ss'\n"
            "                 (floating point image; read with 'afni -im')\n"
            " -savehist_1D dd  Save original form of 2D histogram to 1D file 'dd'\n"
            "                 (-savehist produces the rootogram)\n"
            " -xrange a b   Use only xset values in range a..b.\n"
            " -yrange c d   Use only yset values in range c..d.\n"
            "                 (Default is to use all values.)\n"
            " -clip         Use values from min to mri_topclip()\n"
           ) ;
     exit(0) ;
   }

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

     if( strcmp(argv[iarg],"-xrange") == 0 ){
       if( ++iarg >= argc-1 ) ERROR_exit("no arguments after '%s'!",argv[iarg-1]) ;
       xbot = (float)strtod(argv[iarg++],NULL) ;
       xtop = (float)strtod(argv[iarg++],NULL) ;
       continue ;
     }

     if( strcmp(argv[iarg],"-yrange") == 0 ){
       if( ++iarg >= argc-1 ) ERROR_exit("no arguments after '%s'!",argv[iarg-1]) ;
       ybot = (float)strtod(argv[iarg++],NULL) ;
       ytop = (float)strtod(argv[iarg++],NULL) ;
       continue ;
     }

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

     if( strcmp(argv[iarg],"-savehist") == 0 ){
       if( ++iarg >= argc ) ERROR_exit("no argument after '%s'!",argv[iarg-1]) ;
       if( !THD_filename_ok(argv[iarg]) )
         ERROR_exit("badly formed filename: '%s' '%s'",argv[iarg-1],argv[iarg]);
       save_hist = argv[iarg] ; iarg++ ; continue ;
     }
     
     if( strcmp(argv[iarg],"-savehist_1D") == 0 ){
       if( ++iarg >= argc ) ERROR_exit("no argument after '%s'!",argv[iarg-1]) ;
       save_hist_1D= argv[iarg] ; iarg++ ; continue ;
     }
     
     if( strcmp(argv[iarg],"-histpow") == 0 ){
       double hist_pow ;
       if( ++iarg >= argc ) ERROR_exit("no argument after '%s'!",argv[iarg-1]) ;
       hist_pow = strtod(argv[iarg],NULL) ;
       set_2Dhist_hpower(hist_pow) ;
       iarg++ ; continue ;
     }

     if( strcmp(argv[iarg],"-histbin") == 0 ){
       int hist_nbin ;
       if( ++iarg >= argc ) ERROR_exit("no argument after '%s'!",argv[iarg-1]) ;
       hist_nbin = (int)strtod(argv[iarg],NULL) ;
       set_2Dhist_hbin(hist_nbin) ;
       iarg++ ; continue ;
     }

     if( strncmp(argv[iarg],"-mask",5) == 0 ){
       if( mask_dset != NULL ) ERROR_exit("Can't use -mask twice!") ;
       if( iarg+1 >= argc ) ERROR_exit("-mask needs a filename!") ;
       mask_dset = THD_open_dataset( argv[++iarg] ) ;
       CHECK_OPEN_ERROR(mask_dset,argv[iarg]) ;
       iarg++ ; continue ;
     }

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

   /* should have at least 2 more arguments */

   ndset = argc - iarg ;
   if( ndset <= 1 ){
      fprintf(stderr,"*** No input datasets!?\n") ; exit(1) ;
   }

   xset = THD_open_dataset(argv[iarg++]) ; CHECK_OPEN_ERROR(xset,argv[iarg-1]) ;
   yset = THD_open_dataset(argv[iarg++]) ; CHECK_OPEN_ERROR(yset,argv[iarg-1]) ;
   DSET_load(xset) ; DSET_load(yset) ;
   CHECK_LOAD_ERROR(xset) ; CHECK_LOAD_ERROR(yset) ;
   if( DSET_NVALS(xset) > 1 || DSET_NVALS(yset) > 1 )
     WARNING_message("Using only sub-brick [0] of input datasets") ;

   nvox = DSET_NVOX(xset) ;
   if( nvox != DSET_NVOX(yset) )
     ERROR_exit("Input datasets dimensions don't match!") ;

   xim = mri_scale_to_float( DSET_BRICK_FACTOR(xset,0) , DSET_BRICK(xset,0) );
   yim = mri_scale_to_float( DSET_BRICK_FACTOR(yset,0) , DSET_BRICK(yset,0) );
   xar = MRI_FLOAT_PTR(xim) ; yar = MRI_FLOAT_PTR(yim) ;

   DSET_unload(xset); DSET_unload(yset);

   /* make a byte mask from mask dataset */

   war = (float *)malloc(sizeof(float)*nvox) ;
   if( mask_dset != NULL ){
     int mcount ;
     if( DSET_NVOX(mask_dset) != nvox )
       ERROR_exit("Input and mask datasets are not same dimensions!");

     mmm = THD_makemask( mask_dset , 0 , 666.0,-666.0 ) ;
     mcount = THD_countmask( nvox , mmm ) ;
     if( mcount <= 5 ) ERROR_exit("Mask is too small: %d voxels",mcount) ;
     DSET_delete(mask_dset) ;
     for( ii=0 ; ii < nvox ; ii++ ) war[ii] = (float)mmm[ii] ;
     free((void *)mmm) ;
   } else {
     for( ii=0 ; ii < nvox ; ii++ ) war[ii] = 1.0f ;
   }

   if( clip ){
     xbot = mri_min(xim) ; xtop = mri_topclip(xim) ;
     INFO_message("xbot=%g  xclip=%g",xbot,xtop) ;
     ybot = mri_min(yim) ; ytop = mri_topclip(yim) ;
     INFO_message("ybot=%g  yclip=%g",ybot,ytop) ;
   }

   xyall = 0 ;
   if( xbot >= xtop ){
     xbot = 1.e+38 ; xtop = -1.e+38 ;
     for( ii=0 ; ii < nvox ; ii++ )
       if( war[ii] > 0.0f ){
              if( xar[ii] < xbot ) xbot = xar[ii] ;
         else if( xar[ii] > xtop ) xtop = xar[ii] ;
       }
     INFO_message("xbot=%g  xtop=%g",xbot,xtop) ;
     if( xbot >= xtop ) ERROR_exit("no x range?!") ;
     xyall++ ;
   }
   if( ybot >= ytop ){
     ybot = 1.e+38 ; ytop = -1.e+38 ;
     for( ii=0 ; ii < nvox ; ii++ )
       if( war[ii] > 0.0f ){
              if( yar[ii] < ybot ) ybot = yar[ii] ;
         else if( yar[ii] > ytop ) ytop = yar[ii] ;
       }
     INFO_message("ybot=%g  ytop=%g",ybot,ytop) ;
     if( ybot >= ytop ) ERROR_exit("no y range?!") ;
     xyall++ ;
   }
   if( xyall < 2 ){
     for( ii=0 ; ii < nvox ; ii++ )
       if( xar[ii] < xbot || xar[ii] > xtop ||
           yar[ii] < ybot || yar[ii] > ytop   ) war[ii] = 0.0f ;
   }
   xyall = 0 ;
   for( ii=0 ; ii < nvox ; ii++ ) xyall += (war[ii] > 0.0f) ;
   INFO_message("Processing %d voxels",xyall) ;
   if( xyall <= 5 ) ERROR_exit("Too few voxels to continue!") ;

   xsum = ysum = 0.0f ;
   for( ii=0 ; ii < nvox ; ii++ ){
     if( war[ii] > 0.0f ){ xsum += xar[ii]; ysum += yar[ii]; }
   }
   xsum /= xyall ; ysum /= xyall ;
   INFO_message("xmean=%g  ymean=%g",xsum,ysum) ;
   xsig = ysig = 0.0f ;
   for( ii=0 ; ii < nvox ; ii++ ){
     if( war[ii] > 0.0f ){
       val = (xar[ii]-xsum) ; xsig += val*val ;
       val = (yar[ii]-ysum) ; ysig += val*val ;
     }
   }
   xsig = sqrt( xsig/(xyall-1.0) ); ysig = sqrt( ysig/(xyall-1.0) );
   INFO_message("xsig =%g  ysig =%g",xsig,ysig) ;

   val = THD_pearson_corr_wt( nvox , xar , yar , war ) ;
   val = 1.0 - fabs(val) ;
   printf("1-Correlation     = %+.5f\n",val) ;

   val = -THD_mutual_info_scl( nvox , xbot,xtop,xar , ybot,ytop,yar , war ) ;
   printf("-Mutual Info      = %+.5f\n",val ) ;

   val = THD_norm_mutinf_scl( nvox , xbot,xtop,xar , ybot,ytop,yar , war ) ;
   printf("Norm Mutual Info  = %+.5f\n",val ) ;

#if 0
   INFO_message("THD_corr_ratio_scl(%d,%g,%g,xar,%g,%g,yar,war)",
                 nvox , xbot,xtop , ybot,ytop ) ;
#endif

   THD_corr_ratio_sym_mul ;
   val = THD_corr_ratio_scl( nvox , xbot,xtop,xar , ybot,ytop,yar , war ) ;
   val = 1.0 - fabs(val) ;
   printf("1-Corr ratio sym* = %+.5f\n",val) ;

   THD_corr_ratio_sym_add ;
   val = THD_corr_ratio_scl( nvox , xbot,xtop,xar , ybot,ytop,yar , war ) ;
   val = 1.0 - fabs(val) ;
   printf("1-Corr ratio sym+ = %+.5f\n",val) ;

   THD_corr_ratio_sym_not ;
   val = THD_corr_ratio_scl( nvox , xbot,xtop,xar , ybot,ytop,yar , war ) ;
   val = 1.0 - fabs(val) ;
   printf("1-Corr ratio unsym= %+.5f\n",val) ;

   val = -THD_hellinger_scl( nvox , xbot,xtop,xar , ybot,ytop,yar , war ) ;
   printf("-Hellinger metric = %+.5f\n",val) ;

   if( save_hist != NULL ){  /* Save 2D histogram */
     int nbin ; float *xyc ;
     nbin = retrieve_2Dhist( &xyc ) ;
     if( nbin > 0 && xyc != NULL ){
       MRI_IMAGE *fim,*qim ; double ftop ;
       fim = mri_new(nbin,nbin,MRI_float); mri_fix_data_pointer(xyc,fim);
#if 0
       for( ii=0 ; ii < nbin*nbin ; ii++ ) xyc[ii] = sqrtf(xyc[ii]) ;
       ftop = mri_max(fim); if( ftop == 0.0 ) ftop = 1.0;
       qim = mri_to_byte_scl(255.4/ftop,0.0,fim) ;
       mri_clear_data_pointer(fim); mri_free(fim);
       fim = mri_flippo(MRI_ROT_180,1,qim); mri_free(qim);
       mri_write_pnm(save_hist,fim); mri_free(fim);
#else
       qim = mri_flippo(MRI_ROT_180,1,fim);
       mri_clear_data_pointer(fim); mri_free(fim);
       mri_write(save_hist,qim); mri_free(qim);
#endif
       INFO_message("- Saved %dx%d histogram to %s",nbin,nbin,save_hist) ;
       
     }
   }
   
   if( save_hist_1D != NULL ){  /* Save 2D raw histogram */
     int nbin ; float *xyc ;
     nbin = retrieve_2Dhist( &xyc ) ;
     if( nbin > 0 && xyc != NULL ){
         FILE *fid=fopen(save_hist_1D,"w");
         for( ii=0 ; ii < nbin; ii++ ) {
            for( jj=0 ; jj < nbin; jj++ ) {
               fprintf(fid,"%.4f\t", xyc[ii*nbin+jj]); 
            }
            fprintf(fid,"\n");
         }
         fclose(fid);
      }
      INFO_message("- Saved %dx%d 1D histogram to %s",nbin,nbin,save_hist_1D) ;
       
  }
  
   exit(0) ;
}
コード例 #5
0
ファイル: 3dPolyfit.c プロジェクト: afni/afni
int main( int argc , char * argv[] )
{
   float mrad=0.0f , fwhm=0.0f ;
   int nrep=1 ;
   char *prefix = "Polyfit" ;
   char *resid  = NULL ;
   char *cfnam  = NULL ;
   int iarg , verb=0 , do_automask=0 , nord=3 , meth=2 , do_mclip=0 ;
   THD_3dim_dataset *inset ;
   MRI_IMAGE *imout , *imin ;
   byte *mask=NULL ; int nvmask=0 , nmask=0 , do_mone=0 , do_byslice=0 ;
   MRI_IMARR *exar=NULL ;
   floatvec *fvit=NULL ;   /* 26 Feb 2019 */

   if( argc < 2 || strcasecmp(argv[1],"-help") == 0 ){
      printf("\n"
             "Usage: 3dPolyfit [options] dataset   ~1~\n"
             "\n"
             "* Fits a polynomial in space to the input dataset and outputs that fitted dataset.\n"
             "\n"
             "* You can also add your own basis datasets to the fitting mix, using the\n"
             "  '-base' option.\n"
             "\n"
             "* You can get the fit coefficients using the '-1Dcoef' option.\n"
             "\n"
             "--------\n"
             "Options:   ~1~\n"
             "--------\n"
             "\n"
             "  -nord n    = Maximum polynomial order (0..9) [default order=3]\n"
             "                [n=0 is the constant 1]\n"
             "                [n=-1 means only use volumes from '-base']\n"
             "\n"
             "  -blur f    = Gaussian blur input dataset (inside mask) with FWHM='f' (mm)\n"
             "\n"
             "  -mrad r    = Radius (voxels) of preliminary median filter of input\n"
             "                [default is no blurring of either type; you can]\n"
             "                [do both types (Gaussian and median), but why??]\n"
             "                [N.B.: median blur is slower than Gaussian]\n"
             "\n"
             "  -prefix pp = Use 'pp' for prefix of output dataset (the fit).\n"
             "                [default prefix is 'Polyfit'; use NULL to skip this output]\n"
             "\n"
             "  -resid  rr = Use 'rr' for the prefix of the residual dataset.\n"
             "                [default is not to output residuals]\n"
             "\n"
             "  -1Dcoef cc = Save coefficients of fit into text file cc.1D.\n"
             "                [default is not to save these coefficients]\n"
             "\n"
             "  -automask  = Create a mask (a la 3dAutomask)\n"
             "  -mask mset = Create a mask from nonzero voxels in 'mset'.\n"
             "                [default is not to use a mask, which is probably a bad idea]\n"
             "\n"
             "  -mone      = Scale the mean value of the fit (inside the mask) to 1.\n"
             "                [probably this option is not useful for anything]\n"
             "\n"
             "  -mclip     = Clip fit values outside the rectilinear box containing the\n"
             "               mask to the edge of that box, to avoid weird artifacts.\n"
             "\n"
             "  -meth mm   = Set 'mm' to 2 for least squares fit;\n"
             "               set it to 1 for L1 fit [default method=2]\n"
             "                [Note that L1 fitting is slower than L2 fitting!]\n"
             "\n"
             "  -base bb   = In addition to the polynomial fit, also use\n"
             "               the volumes in dataset 'bb' as extra basis functions.\n"
             "                [If you use a base dataset, then you can set nord]\n"
             "                [to -1, to skip using any spatial polynomial fit.]\n"
             "\n"
             "  -verb      = Print fun and useful progress reports :-)\n"
             "\n"
             "------\n"
             "Notes:   ~1~\n"
             "------\n"
             "* Output dataset is always stored in float format.\n"
             "\n"
             "* If the input dataset has more than 1 sub-brick, only sub-brick #0\n"
             "  is processed. To fit more than one volume, you'll have to use a script\n"
             "  to loop over the input sub-bricks, and then glue (3dTcat) the results\n"
             "  together to get a final result. A simple example:\n"
             "     #!/bin/tcsh\n"
             "     set base = model.nii\n"
             "     set dset = errts.nii\n"
             "     set nval = `3dnvals $dset`\n"
             "     @ vtop = $nval - 1\n"
             "     foreach vv ( `count 0 $vtop` )\n"
             "       3dPolyfit -base \"$base\" -nord 0 -mask \"$base\" -1Dcoef QQ.$vv -prefix QQ.$vv.nii $dset\"[$vv]\"\n"
             "     end\n"
             "     3dTcat -prefix QQall.nii QQ.0*.nii\n"
             "     1dcat  QQ.0*.1D > QQall.1D\n"
             "     \rm QQ.0*\n"
             "     exit 0\n"
             "\n"
             "* If the '-base' dataset has multiple sub-bricks, all of them are used.\n"
             "\n"
             "* You can use the '-base' option more than once, if desired or needed.\n"
             "\n"
             "* The original motivation for this program was to fit a spatial model\n"
             "  to a field map MRI, but that didn't turn out to be useful. Nevertheless,\n"
             "  I make this program available to someone who might find it beguiling.\n"
             "\n"
             "* If you really want, I could allow you to put sign constraints on the\n"
             "  fit coefficients (e.g., say that the coefficient for a given base volume\n"
             "  should be non-negative). But you'll have to beg for this.\n"
             "\n"
             "-- Emitted by RWCox\n"
            ) ;
      PRINT_COMPILE_DATE ; exit(0) ;
   }

   /*-- startup paperwork --*/

   mainENTRY("3dPolyfit main"); machdep(); AFNI_logger("3dPolyfit",argc,argv);
   PRINT_VERSION("3dPolyfit") ;

   /*-- scan command line --*/

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

     if( strcasecmp(argv[iarg],"-base") == 0 ){
       THD_3dim_dataset *bset ; int kk ; MRI_IMAGE *bim ;
       if( ++iarg >= argc ) ERROR_exit("Need argument after '-base'") ;
       bset = THD_open_dataset(argv[iarg]) ;
       CHECK_OPEN_ERROR(bset,argv[iarg]) ;
       DSET_load(bset) ; CHECK_LOAD_ERROR(bset) ;
       if( exar == NULL ) INIT_IMARR(exar) ;
       for( kk=0 ; kk < DSET_NVALS(bset) ; kk++ ){
         bim = THD_extract_float_brick(kk,bset) ;
         if( bim != NULL ) ADDTO_IMARR(exar,bim) ;
         DSET_unload_one(bset,kk) ;
       }
       DSET_delete(bset) ;
       iarg++ ; continue ;
     }

     if( strcasecmp(argv[iarg],"-verb") == 0 ){
       verb++ ; iarg++ ; continue ;
     }

     if( strcasecmp(argv[iarg],"-hermite") == 0 ){ /* 25 Mar 2013 [New Year's Day] */
       mri_polyfit_set_basis("hermite") ;          /* HIDDEN */
       iarg++ ; continue ;
     }

     if( strcasecmp(argv[iarg],"-byslice") == 0 ){ /* 25 Mar 2013 [New Year's Day] */
       do_byslice++ ; iarg++ ; continue ;          /* HIDDEN */
     }

     if( strcasecmp(argv[iarg],"-mask") == 0 ){
       THD_3dim_dataset *mset ;
       if( ++iarg >= argc ) ERROR_exit("Need argument after '-mask'") ;
       if( mask != NULL || do_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) ;
       nvmask = DSET_NVOX(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]) ;
       nmask = THD_countmask( nvmask , mask ) ;
       if( nmask < 99 ) ERROR_exit("Too few voxels in mask (%d)",nmask) ;
       if( verb ) INFO_message("Number of voxels in mask = %d",nmask) ;
       iarg++ ; continue ;
     }

     if( strcasecmp(argv[iarg],"-nord") == 0 ){
       nord = (int)strtol( argv[++iarg], NULL , 10 ) ;
       if( nord < -1 || nord > 9 )
         ERROR_exit("Illegal value after -nord :(") ;
       iarg++ ; continue ;
     }

     if( strcasecmp(argv[iarg],"-meth") == 0 ){
       meth = (int)strtol( argv[++iarg], NULL , 10 ) ;
       if( meth < 1 || meth > 2 )
         ERROR_exit("Illegal value after -meth :(") ;
       iarg++ ; continue ;
     }

     if( strncmp(argv[iarg],"-automask",5) == 0 ){
       if( mask != NULL ) ERROR_exit("Can't use -mask and -automask together!") ;
       do_automask++ ; iarg++ ; continue ;
     }

     if( strncmp(argv[iarg],"-mclip",5) == 0 ){
       do_mclip++ ; iarg++ ; continue ;
     }

     if( strncmp(argv[iarg],"-mone",5) == 0 ){
       do_mone++ ; iarg++ ; continue ;
     }

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

     if( strcasecmp(argv[iarg],"-blur") == 0 ){
       fwhm = strtod( argv[++iarg] , NULL ) ; iarg++ ; continue ;
     }

     if( strcasecmp(argv[iarg],"-prefix") == 0 ){
       prefix = argv[++iarg] ;
       if( !THD_filename_ok(prefix) )
         ERROR_exit("Illegal value after -prefix :(");
       if( strcasecmp(prefix,"NULL") == 0 ) prefix = NULL ;
       iarg++ ; continue ;
     }

     if( strcasecmp(argv[iarg],"-resid") == 0 ){
       resid = argv[++iarg] ;
       if( !THD_filename_ok(resid) )
         ERROR_exit("Illegal value after -resid :(");
       if( strcasecmp(resid,"NULL") == 0 ) resid = NULL ;
       iarg++ ; continue ;
     }

     if( strcasecmp(argv[iarg],"-1Dcoef") == 0 ){  /* 26 Feb 2019 */
       cfnam = argv[++iarg] ;
       if( !THD_filename_ok(cfnam) )
         ERROR_exit("Illegal value after -1Dcoef :(");
       if( strcasecmp(cfnam,"NULL") == 0 ) cfnam = NULL ;
       iarg++ ; continue ;
     }

     ERROR_exit("Unknown option: %s\n",argv[iarg]);
   }

   /*--- check for blatant errors ---*/

   if( iarg >= argc )
     ERROR_exit("No input dataset name on command line?");

   if( prefix == NULL && resid == NULL && cfnam == NULL )
     ERROR_exit("-prefix and -resid and -1Dcoef are all NULL?!") ;

   if( do_byslice && cfnam != NULL ){
     WARNING_message("-byslice does not work with -1Dcoef option :(") ;
     cfnam = NULL ;
   }

   if( nord < 0 && exar == NULL )
     ERROR_exit("no polynomial fit AND no -base option ==> nothing to compute :(") ;

   /*-- read input --*/

   if( verb ) INFO_message("Load input dataset") ;

   inset = THD_open_dataset( argv[iarg] ) ;
   CHECK_OPEN_ERROR(inset,argv[iarg]) ;
   DSET_load(inset) ; CHECK_LOAD_ERROR(inset) ;
   if( DSET_NVALS(inset) > 1 )
     WARNING_message( "Only processing sub-brick #0 (out of %d)" , DSET_NVALS(inset) );

   /* check input mask or create automask */

   if( mask != NULL ){
     if( nvmask != DSET_NVOX(inset) )
      ERROR_exit("-mask and input datasets don't match in voxel counts :-(") ;
   } else if( do_automask ){
     THD_automask_verbose( (verb > 1) ) ;
     THD_automask_extclip( 1 ) ;
     mask = THD_automask( inset ) ; nvmask = DSET_NVOX(inset) ;
     nmask = THD_countmask( nvmask , mask ) ;
     if( nmask < 99 ) ERROR_exit("Too few voxels in automask (%d)",nmask) ;
     if( verb ) ININFO_message("Number of voxels in automask = %d",nmask) ;
   } else {
     WARNING_message("3dPolyfit is running without a mask") ;
   }

#undef  GOOD
#define GOOD(i) (mask == NULL || mask[i])

   /* check -base input datasets */

   if( exar != NULL ){
     int ii,kk , nvbad=0 , nvox=DSET_NVOX(inset),nm ; float *ex , exb ;
     for( kk=0 ; kk < IMARR_COUNT(exar) ; kk++ ){
       if( nvox != IMARR_SUBIM(exar,kk)->nvox ){
         if( IMARR_SUBIM(exar,kk)->nvox != nvbad ){
           ERROR_message("-base volume (%d voxels) doesn't match input dataset grid size (%d voxels)",
                         IMARR_SUBIM(exar,kk)->nvox , nvox ) ;
           nvbad = IMARR_SUBIM(exar,kk)->nvox ;
         }
       }
     }
     if( nvbad != 0 ) ERROR_exit("Cannot continue :-(") ;

     /* subtract mean from each base input, if is a constant polynomial in the fit */

     if( nord >= 0 ){
       if( verb ) INFO_message("subtracting spatial mean from '-base'") ;
       for( kk=0 ; kk < IMARR_COUNT(exar) ; kk++ ){
         exb = 0.0f ; ex = MRI_FLOAT_PTR(IMARR_SUBIM(exar,kk)) ;
         for( nm=ii=0 ; ii < nvox ; ii++ ){ if( GOOD(ii) ){ exb += ex[ii]; nm++; } }
         exb /= nm ;
         for( ii=0 ; ii < nvox ; ii++ ) ex[ii] -= exb ;
       }
     }
   }

   /* if blurring, edit mask a little */

   if( mask != NULL && (fwhm > 0.0f || mrad > 0.0f) ){
     int ii ;
     ii = THD_mask_remove_isolas( DSET_NX(inset),DSET_NY(inset),DSET_NZ(inset),mask ) ;
     if( ii > 0 ){
       nmask = THD_countmask( nvmask , mask ) ;
       if( verb )
         ININFO_message("Removed %d isola%s from mask, leaving %d voxels" ,
                        ii,(ii==1)?"\0":"s" , nmask ) ;
       if( nmask < 99 )
         ERROR_exit("Too few voxels left in mask after isola removal :-(") ;
     }
   }

   /* convert input to float, which is simpler to deal with */

   imin = THD_extract_float_brick(0,inset) ;
   if( imin == NULL ) ERROR_exit("Can't extract input dataset brick?! :-(") ;
   DSET_unload(inset) ;

   if( verb ) INFO_message("Start fitting process") ;

   /* do the Gaussian blurring */

   if( fwhm > 0.0f ){
     if( verb ) ININFO_message("Gaussian blur: FWHM=%g mm",fwhm) ;
     imin->dx = fabsf(DSET_DX(inset)) ;
     imin->dy = fabsf(DSET_DY(inset)) ;
     imin->dz = fabsf(DSET_DZ(inset)) ;
     mri_blur3D_addfwhm( imin , mask , fwhm ) ;
   }

   /* do the fitting */

   mri_polyfit_verb(verb) ;
   if( do_byslice )
     imout = mri_polyfit_byslice( imin , nord , exar , mask , mrad , meth ) ;
   else
     imout = mri_polyfit        ( imin , nord , exar , mask , mrad , meth ) ;

   /* WTF? */

   if( imout == NULL )
     ERROR_exit("Can't compute polynomial fit :-( !?") ;
   if( resid == NULL ) mri_free(imin) ;

   if( ! do_byslice )
     fvit = mri_polyfit_get_fitvec() ; /* get coefficients of fit [26 Feb 2019] */

   /* scale the fit dataset? */

   if( do_mone ){
     float sum=0.0f ; int nsum=0 , ii,nvox ; float *par=MRI_FLOAT_PTR(imout) ;
     nvox = imout->nvox ;
     for( ii=0 ; ii < nvox ; ii++ ){
       if( mask != NULL && mask[ii] == 0 ) continue ;
       sum += par[ii] ; nsum++ ;
     }
     if( nsum > 0 && sum != 0.0f ){
       sum = nsum / sum ;
       if( verb ) ININFO_message("-mone: scaling fit by %g",sum) ;
       for( ii=0 ; ii < nvox ; ii++ ) par[ii] *= sum ;
     }
   }

   /* if there's a mask, clip values outside of its box */

#undef  PF
#define PF(i,j,k) par[(i)+(j)*nx+(k)*nxy]
   if( mask != NULL && do_mclip ){
     int xm,xp,ym,yp,zm,zp , ii,jj,kk , nx,ny,nz,nxy ; float *par ;
     MRI_IMAGE *bim = mri_empty_conforming( imout , MRI_byte ) ;
     mri_fix_data_pointer(mask,bim) ;
     if( verb ) ININFO_message("-mclip: polynomial fit to autobox of mask") ;
     MRI_autobbox( bim , &xm,&xp , &ym,&yp , &zm,&zp ) ;
     mri_clear_data_pointer(bim) ; mri_free(bim) ;
     nx = imout->nx ; ny = imout->ny ; nz = imout->nz ; nxy = nx*ny ;
     par = MRI_FLOAT_PTR(imout) ;
     for( ii=0 ; ii < xm ; ii++ )
      for( kk=0 ; kk < nz ; kk++ )
       for( jj=0 ; jj < ny ; jj++ ) PF(ii,jj,kk) = PF(xm,jj,kk) ;
     for( ii=xp+1 ; ii < nx ; ii++ )
      for( kk=0 ; kk < nz ; kk++ )
       for( jj=0 ; jj < ny ; jj++ ) PF(ii,jj,kk) = PF(xp,jj,kk) ;
     for( jj=0 ; jj < ym ; jj++ )
      for( kk=0 ; kk < nz ; kk++ )
       for( ii=0 ; ii < nx ; ii++ ) PF(ii,jj,kk) = PF(ii,ym,kk) ;
     for( jj=yp+1 ; jj < ny ; jj++ )
      for( kk=0 ; kk < nz ; kk++ )
       for( ii=0 ; ii < nx ; ii++ ) PF(ii,jj,kk) = PF(ii,yp,kk) ;
     for( kk=0 ; kk < zm ; kk++ )
      for( jj=0 ; jj < ny ; jj++ )
       for( ii=0 ; ii < nx ; ii++ ) PF(ii,jj,kk) = PF(ii,jj,zm) ;
     for( kk=zp+1 ; kk < nz ; kk++ )
      for( jj=0 ; jj < ny ; jj++ )
       for( ii=0 ; ii < nx ; ii++ ) PF(ii,jj,kk) = PF(ii,jj,zp) ;
   }

   if( mask != NULL ) free(mask) ;

   /* write outputs */

   if( prefix != NULL ){
     THD_3dim_dataset *outset = EDIT_empty_copy( inset )  ;
     EDIT_dset_items( outset ,
                        ADN_prefix , prefix ,
                        ADN_nvals  , 1 ,
                        ADN_ntt    , 0 ,
                      ADN_none ) ;
     EDIT_substitute_brick( outset , 0 , MRI_float , MRI_FLOAT_PTR(imout) ) ;
     tross_Copy_History( inset , outset ) ;
     tross_Make_History( "3dPolyfit" , argc,argv , outset ) ;
     DSET_write(outset) ;
     WROTE_DSET(outset) ;
   }

   if( resid != NULL ){
     THD_3dim_dataset *outset = EDIT_empty_copy( inset )  ;
     float *inar=MRI_FLOAT_PTR(imin) , *outar=MRI_FLOAT_PTR(imout) ;
     int nx,ny,nz , nxyz , kk ;
     nx = imout->nx ; ny = imout->ny ; nz = imout->nz ; nxyz = nx*ny*nz ;
     for( kk=0 ; kk < nxyz ; kk++ ) outar[kk] = inar[kk] - outar[kk] ;
     mri_free(imin) ;
     EDIT_dset_items( outset ,
                        ADN_prefix , resid ,
                        ADN_nvals  , 1 ,
                        ADN_ntt    , 0 ,
                      ADN_none ) ;
     EDIT_substitute_brick( outset , 0 , MRI_float , MRI_FLOAT_PTR(imout) ) ;
     tross_Copy_History( inset , outset ) ;
     tross_Make_History( "3dPolyfit" , argc,argv , outset ) ;
     DSET_write(outset) ;
     WROTE_DSET(outset) ;
   }

   if( cfnam != NULL && fvit != NULL ){ /* won't work with '-byslice' */
     char *qn ;
     qn = STRING_HAS_SUFFIX(cfnam,".1D") ? cfnam : modify_afni_prefix(cfnam,NULL,".1D") ;
     mri_write_floatvec( qn , fvit ) ;
   }

   exit(0) ;
}
コード例 #6
0
ファイル: Aclustering_NOMASK.c プロジェクト: Gilles86/afni
int main(int argc, char **argv)
{ 
  int ii=0, ncol=0, nrow=0, nl=0, nc=0, posi=0, posj=0, posk=0;
  //int nclust=atoi(argv[2]);
  MRI_IMAGE *im = NULL;
  double *dar = NULL;
  double **D = NULL;
  //int **mask = NULL;
  double** distmatrix = NULL;
  //from command.c

  int i = 1;
  char* filename = 0;
  char* jobname = 0;
  int l = 0;
  int k = 0;
  int kh = 3;
  int r = 1;
  int s = 0;
  int x = 2;
  int y = 1;
  int Rows, Columns;
  char distmetric = 'u';
  char arraymetric = '\0';
  char method = 'm';
  char cg = '\0';
  char ca = '\0';
  int ng = 0;
  int na = 0;
  while (i < argc)
  { const char* const argument = argv[i];

  
    i++;
    if (strlen(argument)<2)
    { printf("ERROR: missing argument\n");
      return 0;
    }
    if (argument[0]!='-')
    { printf("ERROR: unknown argument\n");
      return 0;
    }
    if(!strcmp(argument,"--version") || !strcmp(argument,"-v"))
    { display_version();
      return 0;
    }
    if(!strcmp(argument,"--help") || !strcmp(argument,"-h"))
    { display_help();
      return 0;
    }
    if(!strcmp(argument,"-cg"))
    { if (i==argc || strlen(argv[i])>1 || !strchr("am",argv[i][0]))
      { printf ("Error reading command line argument cg\n");
        return 0;
      }
      cg = argv[i][0];
      i++;
      continue;
    }
    if(!strcmp(argument,"-ca"))
    { if (i==argc || strlen(argv[i])>1 || !strchr("am",argv[i][0]))
      { printf ("Error reading command line argument ca\n");
        return 0;
      }
      ca = argv[i][0];
      i++;
      continue;
    }
    if(!strcmp(argument,"-ng"))
    { ng = 1;
      continue;
    }
    if(!strcmp(argument,"-na"))
    { na = 1;
      continue;
    }
    switch (argument[1])
    { case 'l': l=1; break;
      case 'u':
      { if (i==argc)
        { printf ("Error reading command line argument u: "
                  "no job name specified\n");
          return 0;
        }
        jobname = setjobname(argv[i],0);
        i++;
        break;
      }
      case 'f':
      { if (i==argc)
        { printf ("Error reading command line argument f: "
                  "no file name specified\n");
          return 0;
        }
        filename = argv[i];
        i++;
        break;
      }
      case 'g':
      { int g;
        if (i==argc)
        { printf ("Error reading command line argument g: parameter missing\n");
          return 0;
        }
        g = readnumber(argv[i]);
        if (g < 0 || g > 9)
        { printf ("Error reading command line argument g: "
                  "should be between 0 and 9 inclusive\n");
          return 0;
        }
        i++;
        distmetric = getmetric(g);
        break;
      }

      case 'k':
      { if (i==argc)
        { printf ("Error reading command line argument k: "
                  "parameter missing\n");
          return 0;
        }
        k = readnumber(argv[i]);
        if (k < 1)
        { printf ("Error reading command line argument k: "
                  "a positive integer is required\n");
          return 0;
        }
        i++;
        break;
      }

    case 'c':
      { if (i==argc)
        { printf ("Error reading command line argument h: parameter missing\n");
          return 0;
        }
        kh = readnumber(argv[i]);
        if (kh < 1)
        { printf ("Error reading command line argument h: a positive integer is required\n");
          return 0;
        }
        i++;
        break;
      }
      case 'r':
      { if (i==argc)
        { printf ("Error reading command line argument r: parameter missing\n");
          return 0;
        }
        r = readnumber(argv[i]);
        if (r < 1)
        { printf ("Error reading command line argument r: "
                  "a positive integer is required\n");
          return 0;
        }
        i++;
        break;
      }
    case 'm':
      { if (i==argc || strlen(argv[i])>1 || !strchr("msca",argv[i][0]))
	  { printf ("Error reading command line argument m: should be 'm', 's', 'c', or 'a'\n");
	    return 0;
	  }
        method = argv[i][0];
        i++;
        break;
      }


      default: printf ("Unknown option\n");
    }
   }

   if(jobname==0) jobname = setjobname(filename,1);

   /*  else
   { display_help();
    return 0;
   }
   */

    if (argc < 2) {
      display_help();
      return 0;
    }

   //printf("num of clusters %d \n",nclust);
   fprintf(stderr,"Patience, reading %s...\n ", filename);
   im = mri_read_double_1D (filename);
   /* ZIAD I get this warning
   Aclustering.c:408: warning: passing argument 1 of mri_read_double_1D 
                           discards qualifiers from pointer target type 
   Andrej: filename was declared as (const char *), 
          but the function expects (char *)              */
   if (!im) {
    fprintf(stderr,"Error: Failed to read matrix data from %s\n",
	    argv[2]);
    return(-1);
   }
   ncol = im->ny;
   nrow = im->nx;
   fprintf (stderr,"Have %d cols, %d rows\nNow...\n", ncol, nrow);

   /* now just get the array and kill the rest */
   dar = MRI_DOUBLE_PTR(im);

   /* make sure that pointer is set to NULL in im, or risk hell */
   mri_clear_data_pointer(im);
   if (im) mri_free(im); im = NULL; /* now kill im */


   /* for double loop*/
   D = (double **)calloc(sizeof(double*), nrow-1);
   
   for (ii=0;ii<(nrow-1);++ii) {
    D[ii] = (double *)calloc(sizeof(double), ncol-1);
   }

   for (nl=1; nl<nrow; ++nl) {
    for (nc=1; nc<ncol; ++nc) {
      D[nl-1][nc-1] = dar[nl+nc*nrow];
    }
    //fprintf(stdout,"\n");
  }
  
  //show_data(nrows, ncols, data, mask);
  //example_mean_median(nrows, ncols, data, mask);
  //distmatrix = example_distance_gene(nrows, ncols, data, mask);
  //if (distmatrix) example_hierarchical(nrows, ncols, data, mask, distmatrix);
  //example_distance_array(nrows, ncols, data, mask);
  if(k>0) example_kmeans(nrow-1, ncol-1, D, k, r, distmetric, jobname);
  
  else
    {
      distmatrix = example_distance_gene(nrow-1, ncol-1, D); // ZIAD: goes2 SIGKILL error
        if (distmatrix) 
	  example_hierarchical(nrow-1, ncol-1, D, jobname, kh, distmatrix);
        }
      

  
   free(dar); dar = NULL; /* done with input array */
   // To free D 
   for (ii=0;ii<(nrow-1);++ii) {

    if (D[ii]) free(D[ii]);
   }
   free(D);
   free(jobname);
   //free();

   fprintf (stderr,"\n");
   return 0;
   }
コード例 #7
0
ファイル: 3dFDR.c プロジェクト: CesarCaballeroGaudes/afni
void process_volume (float * ffim, int statcode, float * stataux)

{
  int ixyz;                      /* voxel index */
  int icount;                    /* count of sorted p-values */
  float fval;                    /* voxel input statistical value */
  float pval;                    /* voxel input stat. p-value */
  float qval;                    /* voxel FDR q-value */
  float zval;                    /* voxel FDR z-score */
  float qval_min;                /* smallest previous q-value */
  voxel * head_voxel = NULL;     /* linked list of voxels */
  voxel * voxel_ptr  = NULL;     /* pointer to current voxel */
  int ibin;                      /* p-value bin */
  int   * iarray = NULL;         /* output array of voxel indices */
  float * parray = NULL;         /* output array of voxel p-values */
  float * qarray = NULL;         /* output array of voxel FDR q-values */
  float * zarray = NULL;         /* output array of voxel FDR z-scores */

  float numer ;


  /*------------ 18 Jan 2008: use the 'new' method? ------------*/

  if( FDR_old < 1 ){
    MRI_IMAGE *qim ; int flags=0 ;
    qim = mri_new_vol_empty( FDR_nxyz,1,1 , MRI_float ) ;
    mri_fix_data_pointer( ffim , qim ) ;
    if( FDR_mask != NULL ){
      float zz = (FUNC_IS_STAT(statcode)) ? 0.0f : 1.0f ;
      for( ixyz=0 ; ixyz < FDR_nxyz ; ixyz++ )
        if( !FDR_mask[ixyz] ) ffim[ixyz] = zz ;
    }
    if( FDR_curve ){ /* hidden option: produce t-z curve */
      floatvec *fv = mri_fdr_curve( qim , statcode , stataux ) ;
      if( fv == NULL ) ERROR_message("mri_fdr_curve fails!") ;
      else {
        printf("# FDR thresh-z curve\n") ;
        for( ixyz=0 ; ixyz < fv->nar ; ixyz++ )
          printf("%g %g\n", fv->x0+ixyz*fv->dx , fv->ar[ixyz] ) ;
      }
      exit(0) ;
    } else {         /* normal operation: convert to z(q) or q */
      if( FDR_pmask == 0    ) flags |= 1 ;  /* compatibility mode */
      if( FDR_cn    >  1.0f ) flags |= 2 ;  /* dependency flag */
      if( FDR_qval          ) flags |= 4 ;  /* qval flag */
      (void)mri_fdrize( qim , statcode,stataux , flags ) ;
    }
    mri_clear_data_pointer(qim); mri_free(qim);
    return ;
  }

  /*---------------- back to the 'old' method ------------------*/
  
  /*----- Allocate memory for screen output arrays -----*/
  if (FDR_list)
    {
      iarray = (int   *) malloc (sizeof(int)   * FDR_nthr);   MTEST(iarray);
      parray = (float *) malloc (sizeof(float) * FDR_nthr);   MTEST(parray);
      qarray = (float *) malloc (sizeof(float) * FDR_nthr);   MTEST(qarray);
      zarray = (float *) malloc (sizeof(float) * FDR_nthr);   MTEST(zarray);
    }
  
  
  /*----- Loop over all voxels; sort p-values -----*/
  icount = FDR_nthr;

  for (ixyz = 0;  ixyz < FDR_nxyz;  ixyz++)
    {

      /*----- First, check if voxel is inside the mask -----*/
      if( FDR_mask != NULL && !FDR_mask[ixyz] ) continue;


      /*----- Convert stats to p-values -----*/
      fval = fabs(ffim[ixyz]);
      if (statcode <= 0)
	pval = fval;
      else
	pval = THD_stat_to_pval (fval, statcode, stataux);

      if (pval >= 1.0)  
	{
	  /*----- Count but don't sort voxels with p-value = 1 -----*/
	  icount--;
	  if (FDR_list)
	    {
	      iarray[icount] = ixyz;
	      parray[icount] = 1.0;
	      qarray[icount] = 1.0;
	      zarray[icount] = 0.0;
	    }
	}
      else
	{ 
	  /*----- Place voxel in p-value bin -----*/
	  ibin = (int)  (pval * (FDR_MAX_LL));
	  if (ibin < 0)  ibin = 0;
	  if (ibin > FDR_MAX_LL-1)  ibin = FDR_MAX_LL-1;
	  head_voxel = new_voxel (ixyz, pval, FDR_head_voxel[ibin]);
	  FDR_head_voxel[ibin] = head_voxel;
	}
    }

  /*----- Calculate FDR q-values -----*/
  qval_min = 1.0;
  ibin = FDR_MAX_LL-1;
  numer = (FDR_pmask) ? icount : FDR_nthr ;  /* 18 Jan 2008 */
  while (ibin >= 0) 
    {
      voxel_ptr = FDR_head_voxel[ibin];
  
      while (voxel_ptr != NULL)
	{
          /*----- Convert sorted p-values to FDR q-values -----*/
	  pval = voxel_ptr->pvalue;
	  qval = FDR_cn * (pval*numer) / icount;
	  if (qval > qval_min)
	    qval = qval_min;
	  else
	    qval_min = qval;

	  /*----- Convert FDR q-value to FDR z-score -----*/
          if( !FDR_qval ){
            if (qval < 1.0e-20) zval = 10.0;
            else                zval = normal_p2t(qval);
          } else {              zval = qval ; }

	  icount--;

	  /*----- Save calculated values -----*/
	  if (FDR_list)
	    {
	      iarray[icount] = voxel_ptr->ixyz;
	      parray[icount] = pval;
	      qarray[icount] = qval;
	      zarray[icount] = zval;
	    }

	  voxel_ptr->pvalue = zval;
	  voxel_ptr = voxel_ptr->next_voxel;
	}

      ibin--;
    }


  /*----- Write out the calculated values -----*/
  if (FDR_list)
    {
      printf ("%12s %12s %12s %12s \n", 
	      "Index", "p-value", "q-value", "z-score");
      for (icount = 0;  icount < FDR_nthr;  icount++)
	{
	  if (FDR_input1D_filename != NULL)
	    ixyz = iarray[icount] + 1;
	  else
	    ixyz = iarray[icount];
	  printf ("%12d %12.6f %12.6f %12.6f \n",  
		  ixyz, parray[icount], qarray[icount], zarray[icount]);
	}

      /*----- Deallocate memory for output arrays -----*/
      free (iarray);   free (parray);   free (qarray);   free (zarray);
    }


  /*----- Place FDR z-scores into float array -----*/
  save_all_voxels (ffim);


  /*----- Deallocate linked-list memory -----*/
  delete_all_voxels();

}
コード例 #8
0
static char * BFIT_main( PLUGIN_interface * plint )
{
   MCW_idcode * idc ;
   THD_3dim_dataset * input_dset , * mask_dset = NULL ;

   BFIT_data * bfd ;
   BFIT_result * bfr ;

   int nvals,ival , nran,nvox , nbin , miv=0 , sqr,sqt ;
   float abot,atop,bbot,btop,pcut , eps,eps1 , hlast ;
   float *bval , *cval ;
   double aa,bb,xc ;
   double chq,ccc,cdf ;
   int    ihqbot,ihqtop ;

   int mcount,mgood , ii , jj , ibot,itop ;
   float mask_bot=666.0 , mask_top=-666.0 , hbot,htop,dbin ;
   char buf[THD_MAX_NAME+128] , tbuf[THD_MAX_NAME+128] , * tag ;
   int   * hbin , * jbin,*kbin=NULL , *jist[2] ;
   MRI_IMAGE * flim ;

   double aext=-1.0,bext=-1.0 ;

   /*--------------------------------------------------------------------*/
   /*----- Check inputs from AFNI to see if they are reasonable-ish -----*/

   if( plint == NULL )
      return "************************\n"
             "BFIT_main:  NULL input\n"
             "************************"  ;

   /*-- read 1st line --*/

   PLUTO_next_option(plint) ;
   idc        = PLUTO_get_idcode(plint) ;
   input_dset = PLUTO_find_dset(idc) ;
   if( input_dset == NULL )
      return "****************************\n"
             "BFIT_main: bad input dataset\n"
             "****************************"  ;

   nvox  = DSET_NVOX(input_dset) ;
   nvals = DSET_NVALS(input_dset) ;
   ival  = (int) PLUTO_get_number(plint) ;
   if( ival < 0 || ival >= nvals )
      return "**************************\n"
             "BFIT_main: bad Brick index\n"
             "**************************" ;

   DSET_load(input_dset) ;
   if( DSET_ARRAY(input_dset,0) == NULL )
      return "*****************************\n"
             "BFIT_main: can't load dataset\n"
             "*****************************"  ;

   tag = PLUTO_get_string(plint) ;
   sqr = PLUTO_string_index(tag,NYESNO,YESNO_strings) ;

   /*-- read 2nd line --*/

   PLUTO_next_option(plint) ;
   abot = PLUTO_get_number(plint) ;
   atop = PLUTO_get_number(plint) ;
   if( atop <= abot )
      return "*** atop <= abot! ***" ;

   PLUTO_next_option(plint) ;
   bbot = PLUTO_get_number(plint) ;
   btop = PLUTO_get_number(plint) ;
   if( atop <= abot )
      return "*** btop <= bbot! ***" ;
   hlast = PLUTO_get_number(plint) ;

   PLUTO_next_option(plint) ;
   nran = (int) PLUTO_get_number(plint) ;
   pcut = PLUTO_get_number(plint) ;

   tag = PLUTO_get_string(plint) ;
   sqt = PLUTO_string_index(tag,NYESNO,YESNO_strings) ;

   /*-- read optional lines --*/

   while( (tag=PLUTO_get_optiontag(plint)) != NULL ){

      /*-- Mask itself --*/

      if( strcmp(tag,"Mask") == 0 ){

         idc       = PLUTO_get_idcode(plint) ;
         mask_dset = PLUTO_find_dset(idc) ;

         if( mask_dset == NULL ){
            return "******************************\n"
                   "BFIT_main:  bad mask dataset\n"
                   "******************************"  ;
         }

         if( DSET_NVOX(mask_dset) != nvox ){
           return "************************************************************\n"
                  "BFIT_main: mask input dataset doesn't match source dataset\n"
                  "************************************************************" ;
         }

         miv = (int) PLUTO_get_number(plint) ;
         if( miv >= DSET_NVALS(mask_dset) || miv < 0 ){
            return "****************************************************\n"
                   "BFIT_main: mask dataset sub-brick index is illegal\n"
                   "****************************************************"  ;
         }

         DSET_load(mask_dset) ;
         if( DSET_ARRAY(mask_dset,miv) == NULL ){
            return "*************************************\n"
                   "BFIT_main:  can't load mask dataset\n"
                   "*************************************"  ;
         }
         continue ;
      }

      /*-- Mask range of values --*/

      if( strcmp(tag,"Range") == 0 ){
         if( mask_dset == NULL ){
            return "******************************************\n"
                   "BFIT_main:  Can't use Range without Mask\n"
                   "******************************************"  ;
         }

         mask_bot = PLUTO_get_number(plint) ;
         mask_top = PLUTO_get_number(plint) ;
         continue ;
      }

      /*-- Extra plot --*/

      if( strcmp(tag,"Extra") == 0 ){
         aext = PLUTO_get_number(plint) ;
         bext = PLUTO_get_number(plint) ;
         continue ;
      }
   }

   /*------------------------------------------------------*/
   /*---------- At this point, the inputs are OK ----------*/

   bfd = BFIT_prepare_dataset( input_dset , ival , sqr ,
                               mask_dset , miv , mask_bot , mask_top ) ;

   if( bfd == NULL ) return "*** BFIT_prepare_dataset fails ***" ;

   bfr = BFIT_compute( bfd ,
                       pcut , abot,atop , bbot,btop , nran,200 ) ;

   if( bfr == NULL ){
      BFIT_free_data( bfd ) ;
      return "*** BFIT_compute fails! ***" ;
   }

   itop  = bfr->itop ;
   mgood = bfr->mgood ;

   ibot   = bfd->ibot ;
   bval   = bfd->bval ;
   cval   = bfd->cval ;
   mcount = bfd->mcount ;

   xc   = bfr->xcut ;
   aa   = bfr->a ;
   bb   = bfr->b ;
   eps  = bfr->eps ;
   eps1 = 1.0 - eps ;
   if( eps1 > 1.0 ) eps1 = 1.0 ;
   eps1 = (mcount-ibot) * eps1 ;

   /*-- compute and plot histogram --*/

   /* original data was already squared (e.g., R**2 values) */

   if( !sqr ){
      hbot = 0.0 ; htop = 1.0 ; nbin = 200 ;
      if( bval[mcount-1] < 1.0 ) htop = bval[mcount-1] ;
      dbin = (htop-hbot)/nbin ;

      hbin = (int *) calloc((nbin+1),sizeof(int)) ;  /* actual histogram */
      jbin = (int *) calloc((nbin+1),sizeof(int)) ;  /* theoretical fit */

      for( ii=0 ; ii < nbin ; ii++ ){  /* beta fit */
         jbin[ii] = (int)( eps1 * ( beta_t2p(hbot+ii*dbin,aa,bb)
                                   -beta_t2p(hbot+ii*dbin+dbin,aa,bb) ) ) ;
      }

      jist[0] = jbin ;

      flim = mri_new_vol_empty( mcount-ibot,1,1 , MRI_float ) ;
      mri_fix_data_pointer( bval+ibot , flim ) ;
      mri_histogram( flim , hbot,htop , TRUE , nbin,hbin ) ;

      /* "extra" histogram (nominal values?) */

      if( aext > 0.0 ){
         kbin = (int *) calloc((nbin+1),sizeof(int)) ;
         jist[1] = kbin ;
         for( ii=0 ; ii < nbin ; ii++ ){  /* beta fit */
            kbin[ii] = (int)( eps1 * ( beta_t2p(hbot+ii*dbin,aext,bext)
                                      -beta_t2p(hbot+ii*dbin+dbin,aext,bext) ) ) ;
         }
      }

   } else {   /* original data was not squared (e.g., correlations) */

      double hb,ht ;
      htop = 1.0 ; nbin = 200 ;
      if( bval[mcount-1] < 1.0 ) htop = sqrt(bval[mcount-1]) ;
      hbot = -htop ;
      dbin = (htop-hbot)/nbin ;

      hbin = (int *) calloc((nbin+1),sizeof(int)) ;  /* actual histogram */
      jbin = (int *) calloc((nbin+1),sizeof(int)) ;  /* theoretical fit */

      for( ii=0 ; ii < nbin ; ii++ ){  /* beta fit */
         hb = hbot+ii*dbin ; ht = hb+dbin ;
         hb = hb*hb ; ht = ht*ht ;
         if( hb > ht ){ double qq=hb ; hb=ht ; ht=qq ; }
         jbin[ii] = (int)( 0.5*eps1 * ( beta_t2p(hb,aa,bb)
                                       -beta_t2p(ht,aa,bb) ) ) ;
      }

      jist[0] = jbin ;

      flim = mri_new_vol_empty( mcount-ibot,1,1 , MRI_float ) ;
      mri_fix_data_pointer( cval+ibot , flim ) ;
      mri_histogram( flim , hbot,htop , TRUE , nbin,hbin ) ;

      /* nominal fit */

      if( aext > 0.0 ){
         kbin = (int *) calloc((nbin+1),sizeof(int)) ;
         jist[1] = kbin ;
         for( ii=0 ; ii < nbin ; ii++ ){  /* beta fit */
            hb = hbot+ii*dbin ; ht = hb+dbin ;
            hb = hb*hb ; ht = ht*ht ;
            if( hb > ht ){ double qq=hb ; hb=ht ; ht=qq ; }
            kbin[ii] = (int)( 0.5*eps1 * ( beta_t2p(hb,aext,bext)
                                          -beta_t2p(ht,aext,bext) ) ) ;
         }
      }
   }

   sprintf(buf,"%s[%d] a=%.2f b=%.2f \\epsilon=%.2f %%=%.0f",
           DSET_FILECODE(input_dset),ival,aa,bb,eps,pcut ) ;

   ccc = bfr->q_chisq ;

   /* blow up histogram details by sqrt-ing, if ordered */

   if( sqt ){
      for( ii=0 ; ii < nbin ; ii++ ){
         hbin[ii] = (int) sqrt( (double)(100*hbin[ii]+0.5) ) ;
         jbin[ii] = (int) sqrt( (double)(100*jbin[ii]+0.5) ) ;
         if( kbin!=NULL )
            kbin[ii] = (int) sqrt( (double)(100*kbin[ii]+0.5) ) ;
      }
   }

   /* and plot */

   sprintf(tbuf,"\\beta fit: cutoff=%.2f nvox=%d q(\\chi^2)=%8.2e",
           (sqr)?sqrt(xc):xc , mgood , ccc ) ;
   if( sqt ){
      ii = strlen(tbuf) ;
      sprintf( tbuf+ii , " \\surd ogram" ) ;
   }

   if( hlast > 0.0 ){
      hbin[nbin-1] = jbin[nbin-1] = hlast ;
      if( kbin != NULL ) kbin[nbin-1] = hlast ;
   }

   PLUTO_histoplot( nbin,hbot,htop,hbin ,
                    tbuf,NULL,buf , (kbin==NULL)?1:2 , jist ) ;

   /* cleanup */

   mri_clear_data_pointer(flim) ; mri_free(flim) ;
   free(hbin) ; free(jbin) ; if( kbin != NULL ) free(kbin);

   BFIT_free_data(bfd) ; BFIT_free_result(bfr) ;
   return NULL ;
}
コード例 #9
0
ファイル: plug_imreg.c プロジェクト: ccraddock/afni
char * IMREG_main( PLUGIN_interface * plint )
{
    MCW_idcode * idc ;                          /* input dataset idcode */
    THD_3dim_dataset * old_dset , * new_dset ;  /* input and output datasets */
    char * new_prefix , * str ;                 /* strings from user */
    int base , ntime , datum , nx,ny,nz , ii,kk , npix ;
    float                      dx,dy,dz ;
    MRI_IMARR * ims_in , * ims_out ;
    MRI_IMAGE * im , * imbase ;

    byte   ** bptr = NULL , ** bout = NULL ;
    short  ** sptr = NULL , ** sout = NULL ;
    float  ** fptr = NULL , ** fout = NULL ;

    float * dxar = NULL , * dyar = NULL , * phiar = NULL ;

    /*--------------------------------------------------------------------*/
    /*----- Check inputs from AFNI to see if they are reasonable-ish -----*/

    /*--------- go to first input line ---------*/

    PLUTO_next_option(plint) ;

    idc      = PLUTO_get_idcode(plint) ;   /* get dataset item */
    old_dset = PLUTO_find_dset(idc) ;      /* get ptr to dataset */
    if( old_dset == NULL )
        return "*************************\n"
               "Cannot find Input Dataset\n"
               "*************************"  ;

    ntime = DSET_NUM_TIMES(old_dset) ;
    if( ntime < 2 )
        return "*****************************\n"
               "Dataset has only 1 time point\n"
               "*****************************"  ;

    ii = DSET_NVALS_PER_TIME(old_dset) ;
    if( ii > 1 )
        return "************************************\n"
               "Dataset has > 1 value per time point\n"
               "************************************"  ;

    nx = old_dset->daxes->nxx ;
    dx = old_dset->daxes->xxdel ;
    ny = old_dset->daxes->nyy ;
    dy = old_dset->daxes->yydel ;
    npix = nx*ny ;
    nz = old_dset->daxes->nzz ;
    dz = old_dset->daxes->zzdel ;

    if( nx != ny || fabs(dx) != fabs(dy) ) {

#ifdef IMREG_DEBUG
        fprintf(stderr,"\nIMREG: nx=%d ny=%d nz=%d  dx=%f dy=%f dz=%f\n",
                nx,ny,nz,dx,dy,dz ) ;
#endif

        return "***********************************\n"
               "Dataset does not have square slices\n"
               "***********************************"  ;
    }

    new_prefix = PLUTO_get_string(plint) ;   /* get string item (the output prefix) */
    if( ! PLUTO_prefix_ok(new_prefix) )      /* check if it is OK */
        return "************************\n"
               "Output Prefix is illegal\n"
               "************************"  ;

    /*--------- go to next input line ---------*/

    PLUTO_next_option(plint) ;

    base = PLUTO_get_number(plint) ;
    if( base >= ntime )
        return "********************\n"
               "Base value too large\n"
               "********************"  ;

    /*--------- see if the 3rd option line is present --------*/

    str = PLUTO_get_optiontag( plint ) ;
    if( str != NULL ) {
        float fsig , fdxy , fdph ;
        fsig = PLUTO_get_number(plint) * 0.42466090 ;
        fdxy = PLUTO_get_number(plint) ;
        fdph = PLUTO_get_number(plint) ;
        mri_align_params( 0 , 0.0,0.0,0.0 , fsig,fdxy,fdph ) ;
        /* fprintf(stderr,"Set fine params = %f %f %f\n",fsig,fdxy,fdph) ; */
    }

    /*------------- ready to compute new dataset -----------*/

#ifdef IMREG_DEBUG
    fprintf(stderr,"IMREG: loading dataset\n") ;
#endif

    DSET_load( old_dset ) ;

    /*** 1) Copy the dataset in toto ***/

#ifdef IMREG_DEBUG
    fprintf(stderr,"IMREG: Copying dataset\n") ;
#endif

    new_dset = PLUTO_copy_dset( old_dset , new_prefix ) ;
    if( new_dset == NULL )
        return "****************************\n"
               "Failed to copy input dataset\n"
               "****************************"  ;

    /*** 2) Make an array of empty images ***/

#ifdef IMREG_DEBUG
    fprintf(stderr,"IMREG: making empty images\n") ;
#endif

    datum = DSET_BRICK_TYPE(new_dset,0) ;

    INIT_IMARR(ims_in) ;
    for( ii=0 ; ii < ntime ; ii++ ) {
        im = mri_new_vol_empty( nx , ny , 1 , datum ) ;
        ADDTO_IMARR(ims_in,im) ;
    }

    imbase = mri_new_vol_empty( nx , ny , 1 , datum ) ;

    dxar  = (float *) malloc( sizeof(float) * ntime ) ;
    dyar  = (float *) malloc( sizeof(float) * ntime ) ;
    phiar = (float *) malloc( sizeof(float) * ntime ) ;

    /*** 3) Get pointers to sub-bricks in old and new datasets ***/

#ifdef IMREG_DEBUG
    fprintf(stderr,"IMREG: getting input brick pointers\n") ;
#endif

    switch( datum ) { /* pointer type depends on input datum type */
    case MRI_byte:
        bptr = (byte **) malloc( sizeof(byte *) * ntime ) ;
        bout = (byte **) malloc( sizeof(byte *) * ntime ) ;
        for( ii=0 ; ii < ntime ; ii++ ) {
            bptr[ii] = (byte *) DSET_ARRAY(old_dset,ii) ;
            bout[ii] = (byte *) DSET_ARRAY(new_dset,ii) ;
        }
        break ;

    case MRI_short:
        sptr = (short **) malloc( sizeof(short *) * ntime ) ;
        sout = (short **) malloc( sizeof(short *) * ntime ) ;
        for( ii=0 ; ii < ntime ; ii++ ) {
            sptr[ii] = (short *) DSET_ARRAY(old_dset,ii) ;
            sout[ii] = (short *) DSET_ARRAY(new_dset,ii) ;
        }

#ifdef IMREG_DEBUG
        fprintf(stderr,"IMREG: sptr[0] = %p  sout[0] = %p\n",sptr[0],sout[0]) ;
#endif

        break ;

    case MRI_float:
        fptr = (float **) malloc( sizeof(float *) * ntime ) ;
        fout = (float **) malloc( sizeof(float *) * ntime ) ;
        for( ii=0 ; ii < ntime ; ii++ ) {
            fptr[ii] = (float *) DSET_ARRAY(old_dset,ii) ;
            fout[ii] = (float *) DSET_ARRAY(new_dset,ii) ;
        }
        break ;
    }

    /*** 4) Loop over slices ***/

    PLUTO_popup_meter(plint) ;

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

        /*** 4a) Setup ims_in images to point to input slices ***/

#ifdef IMREG_DEBUG
        fprintf(stderr,"IMREG: slice %d -- setup input images\n",kk) ;
#endif

        for( ii=0 ; ii < ntime ; ii++ ) {
            im = IMARR_SUBIMAGE(ims_in,ii) ;
            switch( datum ) {
            case MRI_byte:
                mri_fix_data_pointer( bptr[ii] + kk*npix, im ) ;
                break ;
            case MRI_short:
                mri_fix_data_pointer( sptr[ii] + kk*npix, im ) ;
                break ;
            case MRI_float:
                mri_fix_data_pointer( fptr[ii] + kk*npix, im ) ;
                break ;
            }
        }

        /*** 4b) Setup im to point to base image ***/

#ifdef IMREG_DEBUG
        fprintf(stderr,"IMREG: slice %d -- setup base image\n",kk) ;
#endif

        switch( datum ) {
        case MRI_byte:
            mri_fix_data_pointer( bptr[base] + kk*npix, imbase ) ;
            break ;
        case MRI_short:
            mri_fix_data_pointer( sptr[base] + kk*npix, imbase ) ;
            break ;
        case MRI_float:
            mri_fix_data_pointer( fptr[base] + kk*npix, imbase ) ;
            break ;
        }

        /*** 4c) Register this slice at all times ***/

#ifdef IMREG_DEBUG
        fprintf(stderr,"IMREG: slice %d -- register\n",kk) ;
#endif

        ims_out = mri_align_dfspace( imbase , NULL , ims_in ,
                                     ALIGN_REGISTER_CODE , dxar,dyar,phiar ) ;

        if( ims_out == NULL )
            fprintf(stderr,"IMREG: mri_align_dfspace return NULL\n") ;

        /*** 4d) Put the output back in on top of the input;
                 note that the output is always in MRI_float format ***/

#ifdef IMREG_DEBUG
        fprintf(stderr,"IMREG: slice %d -- put output back into dataset\n",kk) ;
#endif

        for( ii=0 ; ii < ntime ; ii++ ) {
            switch( datum ) {
            case MRI_byte:
                im = mri_to_mri( MRI_byte , IMARR_SUBIMAGE(ims_out,ii) ) ;
                memcpy( bout[ii] + kk*npix , MRI_BYTE_PTR(im) , sizeof(byte)*npix ) ;
                mri_free(im) ;
                break ;

            case MRI_short:
#ifdef IMREG_DEBUG
                if( ii==0 )fprintf(stderr,"IMREG: conversion to short at ii=%d\n",ii) ;
#endif

                im = mri_to_mri( MRI_short , IMARR_SUBIMAGE(ims_out,ii) ) ;

#ifdef IMREG_DEBUG
                if( ii==0 )fprintf(stderr,"IMREG: copying to %p from %p\n",sout[ii] + kk*npix,MRI_SHORT_PTR(im)) ;
#endif

                memcpy( sout[ii] + kk*npix , MRI_SHORT_PTR(im) , sizeof(short)*npix ) ;

#ifdef IMREG_DEBUG
                if( ii==0 )fprintf(stderr,"IMREG: freeing\n") ;
#endif

                mri_free(im) ;
                break ;

            case MRI_float:
                im = IMARR_SUBIMAGE(ims_out,ii) ;
                memcpy( fout[ii] + kk*npix , MRI_FLOAT_PTR(im) , sizeof(float)*npix ) ;
                break ;
            }
        }

        PLUTO_set_meter(plint, (100*(kk+1))/nz ) ;

        /*** 4e) Destroy the output images ***/

#ifdef IMREG_DEBUG
        fprintf(stderr,"IMREG: destroying aligned output\n") ;
#endif

        DESTROY_IMARR( ims_out ) ;
    }

    /*** 5) Destroy the empty images and other workspaces ***/

#ifdef IMREG_DEBUG
    fprintf(stderr,"IMREG: destroy workspaces\n") ;
#endif

    mri_clear_data_pointer(imbase) ;
    mri_free(imbase) ;
    for( ii=0 ; ii < ntime ; ii++ ) {
        im = IMARR_SUBIMAGE(ims_in,ii) ;
        mri_clear_data_pointer(im) ;
    }
    DESTROY_IMARR(ims_in) ;
    FREE_WORKSPACE ;

    /*------------- let AFNI know about the new dataset ------------*/

#ifdef IMREG_DEBUG
    fprintf(stderr,"IMREG: send result to AFNI\n") ;
#endif

    PLUTO_add_dset( plint , new_dset , DSET_ACTION_MAKE_CURRENT ) ;

    return NULL ;  /* null string returned means all was OK */
}