_reg_nmi.cpp 40.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 *  _reg_mutualinformation.cpp
 *
 *
 *  Created by Marc Modat on 25/03/2009.
 *  Copyright (c) 2009, University College London. All rights reserved.
 *  Centre for Medical Image Computing (CMIC)
 *  See the LICENSE.txt file in the nifty_reg root folder
 *
 */

#ifndef _REG_NMI_CPP
#define _REG_NMI_CPP

#include "_reg_nmi.h"

/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
reg_nmi::reg_nmi()
20
   : reg_measure()
21
{
22 23 24 25 26 27
   this->forwardJointHistogramPro=NULL;
   this->forwardJointHistogramLog=NULL;
   this->forwardEntropyValues=NULL;
   this->backwardJointHistogramPro=NULL;
   this->backwardJointHistogramLog=NULL;
   this->backwardEntropyValues=NULL;
28

29 30 31 32 33
   for(int i=0; i<255; ++i)
   {
      this->referenceBinNumber[i]=68;
      this->floatingBinNumber[i]=68;
   }
34
#ifndef NDEBUG
35
   printf("[NiftyReg DEBUG] reg_nmi constructor called\n");
36 37 38 39 40 41
#endif
}
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
reg_nmi::~reg_nmi()
{
42
   this->ClearHistogram();
43
#ifndef NDEBUG
44
   printf("[NiftyReg DEBUG] reg_nmi destructor called\n");
45 46 47 48 49
#endif
}
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
void reg_nmi::ClearHistogram()
{
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
   int timepoint=this->referenceTimePoint;
   // Free the joint histograms and the entropy arrays
   if(this->forwardJointHistogramPro!=NULL)
   {
      for(int i=0; i<timepoint; ++i)
      {
         if(this->forwardJointHistogramPro[i]!=NULL)
            free(this->forwardJointHistogramPro[i]);
         this->forwardJointHistogramPro[i]=NULL;
      }
      free(this->forwardJointHistogramPro);
   }
   this->forwardJointHistogramPro=NULL;
   if(this->backwardJointHistogramPro!=NULL)
   {
      for(int i=0; i<timepoint; ++i)
      {
         if(this->backwardJointHistogramPro[i]!=NULL)
            free(this->backwardJointHistogramPro[i]);
         this->backwardJointHistogramPro[i]=NULL;
      }
      free(this->backwardJointHistogramPro);
   }
   this->backwardJointHistogramPro=NULL;
74

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
   if(this->forwardJointHistogramLog!=NULL)
   {
      for(int i=0; i<timepoint; ++i)
      {
         if(this->forwardJointHistogramLog[i]!=NULL)
            free(this->forwardJointHistogramLog[i]);
         this->forwardJointHistogramLog[i]=NULL;
      }
      free(this->forwardJointHistogramLog);
   }
   this->forwardJointHistogramLog=NULL;
   if(this->backwardJointHistogramLog!=NULL)
   {
      for(int i=0; i<timepoint; ++i)
      {
         if(this->backwardJointHistogramLog[i]!=NULL)
            free(this->backwardJointHistogramLog[i]);
         this->backwardJointHistogramLog[i]=NULL;
      }
      free(this->backwardJointHistogramLog);
   }
   this->backwardJointHistogramLog=NULL;
97

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
   if(this->forwardEntropyValues!=NULL)
   {
      for(int i=0; i<timepoint; ++i)
      {
         if(this->forwardEntropyValues[i]!=NULL)
            free(this->forwardEntropyValues[i]);
         this->forwardEntropyValues[i]=NULL;
      }
      free(this->forwardEntropyValues);
   }
   this->forwardEntropyValues=NULL;
   if(this->backwardEntropyValues!=NULL)
   {
      for(int i=0; i<timepoint; ++i)
      {
         if(this->backwardEntropyValues[i]!=NULL)
            free(this->backwardEntropyValues[i]);
         this->backwardEntropyValues[i]=NULL;
      }
      free(this->backwardEntropyValues);
   }
   this->backwardEntropyValues=NULL;
120
#ifndef NDEBUG
121
   printf("[NiftyReg DEBUG] reg_nmi::ClearHistogram called\n");
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
#endif
}
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
void reg_nmi::InitialiseMeasure(nifti_image *refImgPtr,
                                nifti_image *floImgPtr,
                                int *maskRefPtr,
                                nifti_image *warFloImgPtr,
                                nifti_image *warFloGraPtr,
                                nifti_image *forVoxBasedGraPtr,
                                int *maskFloPtr,
                                nifti_image *warRefImgPtr,
                                nifti_image *warRefGraPtr,
                                nifti_image *bckVoxBasedGraPtr)
{
137 138 139 140 141 142 143 144 145 146 147
   // Set the pointers using the parent class function
   reg_measure::InitialiseMeasure(refImgPtr,
                                  floImgPtr,
                                  maskRefPtr,
                                  warFloImgPtr,
                                  warFloGraPtr,
                                  forVoxBasedGraPtr,
                                  maskFloPtr,
                                  warRefImgPtr,
                                  warRefGraPtr,
                                  bckVoxBasedGraPtr);
148

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
   // Clear all allocated arrays
   this->ClearHistogram();
   // Extract the number of time point
   int timepoint=this->referenceTimePoint;
   // Reference and floating are resampled between 2 and bin-3
   for(int i=0; i<timepoint; ++i)
   {
      if(this->activeTimePoint[i])
      {
         reg_intensityRescale(this->referenceImagePointer,
                              i,
                              2.f,
                              this->referenceBinNumber[i]-3);
         reg_intensityRescale(this->floatingImagePointer,
                              i,
                              2.f,
                              this->floatingBinNumber[i]-3);
      }
   }
   // Create the joint histograms
   this->forwardJointHistogramPro=(double**)malloc(255*sizeof(double *));
   this->forwardJointHistogramLog=(double**)malloc(255*sizeof(double *));
   this->forwardEntropyValues=(double**)malloc(255*sizeof(double *));
   if(this->isSymmetric)
   {
      this->backwardJointHistogramPro=(double**)malloc(255*sizeof(double *));
      this->backwardJointHistogramLog=(double**)malloc(255*sizeof(double *));
      this->backwardEntropyValues=(double**)malloc(255*sizeof(double *));
   }
   for(int i=0; i<timepoint; ++i)
   {
      if(this->activeTimePoint[i])
      {
         // Compute the total number of bin
         this->totalBinNumber[i]=this->referenceBinNumber[i]*this->floatingBinNumber[i] +
                                 this->referenceBinNumber[i] + this->floatingBinNumber[i];
         this->forwardJointHistogramLog[i]=(double *)
                                           calloc(this->totalBinNumber[i],sizeof(double));
         this->forwardJointHistogramPro[i]=(double *)
                                           calloc(this->totalBinNumber[i],sizeof(double));
         this->forwardEntropyValues[i]=(double *)
                                       calloc(4,sizeof(double));
         if(this->isSymmetric)
         {
            this->backwardJointHistogramLog[i]=(double *)
                                               calloc(this->totalBinNumber[i],sizeof(double));
            this->backwardJointHistogramPro[i]=(double *)
                                               calloc(this->totalBinNumber[i],sizeof(double));
            this->backwardEntropyValues[i]=(double *)
                                           calloc(4,sizeof(double));
         }
      }
      else
      {
         this->forwardJointHistogramLog[i]=NULL;
         this->forwardJointHistogramPro[i]=NULL;
         this->forwardEntropyValues[i]=NULL;
         if(this->isSymmetric)
         {
            this->backwardJointHistogramLog[i]=NULL;
            this->backwardJointHistogramPro[i]=NULL;
            this->backwardEntropyValues[i]=NULL;
         }
      }
   }
214
#ifndef NDEBUG
215 216 217 218 219
   printf("[NiftyReg DEBUG] reg_nmi::InitialiseMeasure called. Active time point:");
   for(int i=0; i<this->referenceImagePointer->nt; ++i)
      if(this->activeTimePoint[i])
         printf(" %i",i);
   printf("\n");
220 221 222 223 224 225 226
#endif
}
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
template<class PrecisionTYPE>
PrecisionTYPE GetBasisSplineValue(PrecisionTYPE x)
{
227 228 229 230 231 232 233 234 235 236 237 238 239
   x=fabs(x);
   PrecisionTYPE value=0.0;
   if(x<2.0)
   {
      if(x<1.0)
         value = (PrecisionTYPE)(2.0f/3.0f + (0.5f*x-1.0)*x*x);
      else
      {
         x-=2.0f;
         value = -x*x*x/6.0f;
      }
   }
   return value;
240 241 242 243 244
}
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
template<class PrecisionTYPE>
PrecisionTYPE GetBasisSplineDerivativeValue(PrecisionTYPE ori)
{
245 246 247 248 249 250 251 252 253 254 255 256 257 258
   PrecisionTYPE x=fabs(ori);
   PrecisionTYPE value=0.0;
   if(x<2.0)
   {
      if(x<1.0)
         value = (PrecisionTYPE)((1.5f*x-2.0)*ori);
      else
      {
         x-=2.0f;
         value = -0.5f * x * x;
         if(ori<0.0f) value =-value;
      }
   }
   return value;
259 260 261 262 263 264 265 266 267 268 269 270 271 272
}
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
template <class DTYPE>
void reg_getNMIValue(nifti_image *referenceImage,
                     nifti_image *warpedImage,
                     bool *activeTimePoint,
                     unsigned short *referenceBinNumber,
                     unsigned short *floatingBinNumber,
                     unsigned short *totalBinNumber,
                     double **jointHistogramLog,
                     double **jointhistogramPro,
                     double **entropyValues,
                     int *referenceMask
273
                    )
274
{
275 276 277 278 279 280 281 282 283 284 285 286
   // Create pointers to the image data arrays
   DTYPE *refImagePtr = static_cast<DTYPE *>(referenceImage->data);
   DTYPE *warImagePtr = static_cast<DTYPE *>(warpedImage->data);
   // Useful variable
   size_t voxelNumber = (size_t)referenceImage->nx *
                        referenceImage->ny *
                        referenceImage->nz;
   // Iterate over all active time points
   for(int t=0; t<referenceImage->nt; ++t)
   {
      if(activeTimePoint[t])
      {
287
#ifndef NDEBUG
288
         printf("[NiftyReg DEBUG] Computing NMI for time point %i\n",t);
289
#endif
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
         // Define some pointers to the current histograms
         double *jointHistoProPtr = jointhistogramPro[t];
         double *jointHistoLogPtr = jointHistogramLog[t];
         // Empty the joint histogram
         memset(jointHistoProPtr,0,totalBinNumber[t]*sizeof(double));
         // Fill the joint histograms using an approximation
         DTYPE *refPtr = &refImagePtr[t*voxelNumber];
         DTYPE *warPtr = &warImagePtr[t*voxelNumber];
         for(size_t voxel=0; voxel<voxelNumber; ++voxel)
         {
            if(referenceMask[voxel]>-1)
            {
               DTYPE refValue=refPtr[voxel];
               DTYPE warValue=warPtr[voxel];
               if(refValue==refValue && warValue==warValue &&
                     refValue>=0 && warValue>=0 &&
                     refValue<referenceBinNumber[t] &&
                     warValue<floatingBinNumber[t])
               {
                  ++jointHistoProPtr[static_cast<int>(refValue) +
                                     static_cast<int>(warValue) * referenceBinNumber[t]];
               }
312
            }
313 314 315 316 317 318 319 320 321 322 323 324 325 326
         }
         // Convolve the histogram with a cubic B-spline kernel
         double kernel[3];
         kernel[0]=kernel[2]=GetBasisSplineValue(-1.);
         kernel[1]=GetBasisSplineValue(0.);
         // Histogram is first smooth along the reference axis
         memset(jointHistoLogPtr,0,totalBinNumber[t]*sizeof(double));
         for(int f=0; f<floatingBinNumber[t]; ++f)
         {
            for(int r=0; r<referenceBinNumber[t]; ++r)
            {
               double value=0.0;
               int index = r-1;
               double *ptrHisto = &jointHistoProPtr[index+referenceBinNumber[t]*f];
327

328 329 330 331 332 333 334 335 336 337
               for(int it=0; it<3; it++)
               {
                  if(-1<index && index<referenceBinNumber[t])
                  {
                     value += *ptrHisto * kernel[it];
                  }
                  ++ptrHisto;
                  ++index;
               }
               jointHistoLogPtr[r+referenceBinNumber[t]*f] = value;
338
            }
339 340 341 342 343 344 345 346 347
         }
         // Histogram is then smooth along the warped floating axis
         for(int r=0; r<referenceBinNumber[t]; ++r)
         {
            for(int f=0; f<floatingBinNumber[t]; ++f)
            {
               double value=0.;
               int index = f-1;
               double *ptrHisto = &jointHistoLogPtr[r+referenceBinNumber[t]*index];
348

349 350 351 352 353 354 355 356 357 358
               for(int it=0; it<3; it++)
               {
                  if(-1<index && index<floatingBinNumber[t])
                  {
                     value += *ptrHisto * kernel[it];
                  }
                  ptrHisto+=referenceBinNumber[t];
                  ++index;
               }
               jointHistoProPtr[r+referenceBinNumber[t]*f] = value;
359
            }
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
         }
         // Normalise the histogram
         double activeVoxel=0.f;
         for(int i=0; i<totalBinNumber[t]; ++i)
            activeVoxel+=jointHistoProPtr[i];
         entropyValues[t][3]=activeVoxel;
         for(int i=0; i<totalBinNumber[t]; ++i)
            jointHistoProPtr[i]/=activeVoxel;
         // Marginalise over the reference axis
         for(int r=0; r<referenceBinNumber[t]; ++r)
         {
            double sum=0.;
            int index=r;
            for(int f=0; f<floatingBinNumber[t]; ++f)
            {
               sum+=jointHistoProPtr[index];
               index+=referenceBinNumber[t];
377
            }
378 379 380 381 382 383 384 385 386 387 388 389
            jointHistoProPtr[referenceBinNumber[t]*
                             floatingBinNumber[t]+r]=sum;
         }
         // Marginalise over the warped floating axis
         for(int f=0; f<floatingBinNumber[t]; ++f)
         {
            double sum=0.;
            int index=referenceBinNumber[t]*f;
            for(int r=0; r<referenceBinNumber[t]; ++r)
            {
               sum+=jointHistoProPtr[index];
               ++index;
390
            }
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
            jointHistoProPtr[referenceBinNumber[t]*
                             floatingBinNumber[t]+referenceBinNumber[t]+f]=sum;
         }
         // Set the log values to zero
         memset(jointHistoLogPtr,0,totalBinNumber[t]*sizeof(double));
         // Compute the entropy of the reference image
         double referenceEntropy=0.;
         for(int r=0; r<referenceBinNumber[t]; ++r)
         {
            double valPro=jointHistoProPtr[referenceBinNumber[t]*floatingBinNumber[t]+r];
            if(valPro>0)
            {
               double valLog=log(valPro);
               referenceEntropy -= valPro * valLog;
               jointHistoLogPtr[referenceBinNumber[t]*floatingBinNumber[t]+r]=valLog;
406
            }
407 408 409 410 411 412 413 414 415 416 417 418 419 420
         }
         entropyValues[t][0]=referenceEntropy;
         // Compute the entropy of the warped floating image
         double warpedEntropy=0.;
         for(int f=0; f<floatingBinNumber[t]; ++f)
         {
            double valPro=jointHistoProPtr[referenceBinNumber[t]*floatingBinNumber[t]+
                                           referenceBinNumber[t]+f];
            if(valPro>0)
            {
               double valLog=log(valPro);
               warpedEntropy -= valPro * valLog;
               jointHistoLogPtr[referenceBinNumber[t]*floatingBinNumber[t]+
                                referenceBinNumber[t]+f]=valLog;
421
            }
422 423 424 425 426 427 428 429 430 431 432 433
         }
         entropyValues[t][1]=warpedEntropy;
         // Compute the joint entropy
         double jointEntropy=0.;
         for(int i=0; i<referenceBinNumber[t]*floatingBinNumber[t]; ++i)
         {
            double valPro=jointHistoProPtr[i];
            if(valPro>0)
            {
               double valLog=log(valPro);
               jointEntropy -= valPro * valLog;
               jointHistoLogPtr[i]=valLog;
434
            }
435 436 437 438
         }
         entropyValues[t][2]=jointEntropy;
      } // if active time point
   } // iterate over all time point in the reference image
439 440 441 442 443 444 445 446
}
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
template void reg_getNMIValue<float>(nifti_image *,nifti_image *,bool *,unsigned short *,unsigned short *,unsigned short *,double **,double **,double **,int *);
template void reg_getNMIValue<double>(nifti_image *,nifti_image *,bool *,unsigned short *,unsigned short *,unsigned short *,double **,double **,double **,int *);
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */
double reg_nmi::GetSimilarityMeasureValue()
{
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
   // Check that all the specified image are of the same datatype
   if(this->warpedFloatingImagePointer->datatype !=this->referenceImagePointer->datatype)
   {
      fprintf(stderr, "[NiftyReg ERROR] reg_nmi::GetSimilarityMeasureValue\n");
      fprintf(stderr, "[NiftyReg ERROR] Both input images are exepected to have the same type\n");
      reg_exit(1);
   }
   switch(this->referenceImagePointer->datatype)
   {
   case NIFTI_TYPE_FLOAT32:
      reg_getNMIValue<float>
      (this->referenceImagePointer,
       this->warpedFloatingImagePointer,
       this->activeTimePoint,
       this->referenceBinNumber,
       this->floatingBinNumber,
       this->totalBinNumber,
       this->forwardJointHistogramLog,
       this->forwardJointHistogramPro,
       this->forwardEntropyValues,
       this->referenceMaskPointer
      );
      break;
   case NIFTI_TYPE_FLOAT64:
      reg_getNMIValue<double>
      (this->referenceImagePointer,
       this->warpedFloatingImagePointer,
       this->activeTimePoint,
       this->referenceBinNumber,
       this->floatingBinNumber,
       this->totalBinNumber,
       this->forwardJointHistogramLog,
       this->forwardJointHistogramPro,
       this->forwardEntropyValues,
       this->referenceMaskPointer
      );
      break;
   default:
      fprintf(stderr,"[NiftyReg ERROR] reg_nmi::GetSimilarityMeasureValue\tThe reference image data type is not supported\n");
      reg_exit(1);
   }
488

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
   if(this->isSymmetric)
   {
      // Check that all the specified image are of the same datatype
      if(this->floatingImagePointer->datatype !=this->warpedReferenceImagePointer->datatype)
      {
         fprintf(stderr, "[NiftyReg ERROR] reg_nmi::GetSimilarityMeasureValue\n");
         fprintf(stderr, "[NiftyReg ERROR] Both input images are exepected to have the same type\n");
         reg_exit(1);
      }
      switch(this->floatingImagePointer->datatype)
      {
      case NIFTI_TYPE_FLOAT32:
         reg_getNMIValue<float>
         (this->floatingImagePointer,
          this->warpedReferenceImagePointer,
          this->activeTimePoint,
          this->floatingBinNumber,
          this->referenceBinNumber,
          this->totalBinNumber,
          this->backwardJointHistogramLog,
          this->backwardJointHistogramPro,
          this->backwardEntropyValues,
          this->floatingMaskPointer
         );
         break;
      case NIFTI_TYPE_FLOAT64:
         reg_getNMIValue<double>
         (this->floatingImagePointer,
          this->warpedReferenceImagePointer,
          this->activeTimePoint,
          this->floatingBinNumber,
          this->referenceBinNumber,
          this->totalBinNumber,
          this->backwardJointHistogramLog,
          this->backwardJointHistogramPro,
          this->backwardEntropyValues,
          this->floatingMaskPointer
         );
         break;
      default:
         fprintf(stderr,"[NiftyReg ERROR] reg_nmi::GetSimilarityMeasureValue\tThe reference image data type is not supported\n");
         reg_exit(1);
      }
   }
533

534 535 536 537 538 539 540 541 542 543 544 545
   double nmi_value=0.;
   for(int t=0; t<this->referenceTimePoint; ++t)
   {
      if(this->activeTimePoint[t])
      {
         nmi_value += (this->forwardEntropyValues[t][0] + this->forwardEntropyValues[t][1] ) /
                      this->forwardEntropyValues[t][2];
         if(this->isSymmetric)
            nmi_value += (this->backwardEntropyValues[t][0] + this->backwardEntropyValues[t][1] ) /
                         this->backwardEntropyValues[t][2];
      }
   }
546
#ifndef NDEBUG
547
   printf("[NiftyReg DEBUG] reg_nmi::GetSimilarityMeasureValue called\n");
548
#endif
549
   return nmi_value;
550 551 552 553 554 555 556 557 558 559 560 561 562
}
/* *************************************************************** */
template <class DTYPE>
void reg_getVoxelBasedNMIGradient2D(nifti_image *referenceImage,
                                    nifti_image *warpedImage,
                                    bool *activeTimePoint,
                                    unsigned short *referenceBinNumber,
                                    unsigned short *floatingBinNumber,
                                    double **jointHistogramLog,
                                    double **entropyValues,
                                    nifti_image *warpedGradientImage,
                                    nifti_image *nmiGradientImage,
                                    int *referenceMask
563
                                   )
564
{
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
   //
   size_t voxelNumber = (size_t)referenceImage->nx*referenceImage->ny*referenceImage->nz;
   // Pointers to the image data
   DTYPE *refImagePtr = static_cast<DTYPE *>(referenceImage->data);
   DTYPE *warImagePtr = static_cast<DTYPE *>(warpedImage->data);
   DTYPE *warGradImagePtr = static_cast<DTYPE *>(warpedGradientImage->data);
   DTYPE *nmiGradPtrX = static_cast<DTYPE *>(nmiGradientImage->data);
   DTYPE *nmiGradPtrY = &nmiGradPtrX[voxelNumber];
   // Iterative over all the time point as defined in the reference image
   for(int t=0; t<referenceImage->nt; ++t)
   {
      // Check if the current time point has been defined as active
      if(activeTimePoint[t])
      {
         // Create pointers to the current volume
         DTYPE *refPtr = &refImagePtr[t*voxelNumber];
         DTYPE *warPtr = &warImagePtr[t*voxelNumber];
         DTYPE *warGradPtrX = &warGradImagePtr[t*voxelNumber*2];
         DTYPE *warGradPtrY = &warGradPtrX[voxelNumber];
         // Create pointers to the current joint histogram
         double *logHistoPtr = jointHistogramLog[t];
         double *entropyPtr = entropyValues[t];
         double nmi = (entropyPtr[0]+entropyPtr[1])/entropyPtr[2];
         size_t referenceOffset=referenceBinNumber[t]*floatingBinNumber[t];
         size_t floatingOffset=referenceOffset+referenceBinNumber[t];
         // Iterate over all voxel
         for(size_t i=0; i<voxelNumber; ++i)
         {
            // Check if the voxel belongs to the image mask
            if(referenceMask[i]>-1)
            {
               DTYPE refValue = refPtr[i];
               DTYPE warValue = warPtr[i];
               if(refValue==refValue && warValue==warValue)
               {
                  DTYPE gradX = warGradPtrX[i];
                  DTYPE gradY = warGradPtrY[i];
602

603 604 605
                  double jointDeriv[2]= {0.};
                  double refDeriv[2]= {0.};
                  double warDeriv[2]= {0.};
606

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
                  for(int r=(int)(refValue-1.0); r<(int)(refValue+3.0); ++r)
                  {
                     if(-1<r && r<referenceBinNumber[t])
                     {
                        for(int w=(int)(warValue-1.0); w<(int)(warValue+3.0); ++w)
                        {
                           if(-1<w && w<floatingBinNumber[t])
                           {
                              double commun =
                                 GetBasisSplineValue((double)refValue - (double)r) *
                                 GetBasisSplineDerivativeValue((double)warValue - (double)w);
                              double jointLog = logHistoPtr[r+w*referenceBinNumber[t]];
                              double refLog = logHistoPtr[r+referenceOffset];
                              double warLog = logHistoPtr[w+floatingOffset];
                              jointDeriv[0] += commun * gradX * jointLog;
                              jointDeriv[1] += commun * gradY * jointLog;
                              refDeriv[0] += commun * gradX * refLog;
                              refDeriv[1] += commun * gradY * refLog;
                              warDeriv[0] += commun * gradX * warLog;
                              warDeriv[1] += commun * gradY * warLog;
                           }
628
                        }
629 630 631 632 633 634 635 636 637 638 639
                     }
                  }
                  nmiGradPtrX[i] += (DTYPE)((refDeriv[0] + warDeriv[0] -
                                             nmi * jointDeriv[0]) / (entropyPtr[2]*entropyPtr[3]));
                  nmiGradPtrY[i] += (DTYPE)((refDeriv[1] + warDeriv[1] -
                                             nmi * jointDeriv[1]) / (entropyPtr[2]*entropyPtr[3]));
               }// Check that the values are defined
            } // mask
         } // loop over all voxel
      } // if active time point
   } // for all time point
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
}
/* *************************************************************** */
template void reg_getVoxelBasedNMIGradient2D<float>(nifti_image *,nifti_image *,bool *,unsigned short *,unsigned short *,double **,double **,nifti_image *,nifti_image *,int *);
template void reg_getVoxelBasedNMIGradient2D<double>(nifti_image *,nifti_image *,bool *,unsigned short *,unsigned short *,double **,double **,nifti_image *,nifti_image *,int *);
/* *************************************************************** */
template <class DTYPE>
void reg_getVoxelBasedNMIGradient3D(nifti_image *referenceImage,
                                    nifti_image *warpedImage,
                                    bool *activeTimePoint,
                                    unsigned short *referenceBinNumber,
                                    unsigned short *floatingBinNumber,
                                    double **jointHistogramLog,
                                    double **entropyValues,
                                    nifti_image *warpedGradientImage,
                                    nifti_image *nmiGradientImage,
                                    int *referenceMask
656
                                   )
657
{
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
   //
   size_t voxelNumber = (size_t)referenceImage->nx*referenceImage->ny*referenceImage->nz;
   // Pointers to the image data
   DTYPE *refImagePtr = static_cast<DTYPE *>(referenceImage->data);
   DTYPE *warImagePtr = static_cast<DTYPE *>(warpedImage->data);
   DTYPE *warGradImagePtr = static_cast<DTYPE *>(warpedGradientImage->data);
   DTYPE *nmiGradPtrX = static_cast<DTYPE *>(nmiGradientImage->data);
   DTYPE *nmiGradPtrY = &nmiGradPtrX[voxelNumber];
   DTYPE *nmiGradPtrZ = &nmiGradPtrY[voxelNumber];
   // Iterative over all the time point as defined in the reference image
   for(int t=0; t<referenceImage->nt; ++t)
   {
      // Check if the current time point has been defined as active
      if(activeTimePoint[t])
      {
         // Create pointers to the current volume
         DTYPE *refPtr = &refImagePtr[t*voxelNumber];
         DTYPE *warPtr = &warImagePtr[t*voxelNumber];
         DTYPE *warGradPtrX = &warGradImagePtr[t*voxelNumber*3];
         DTYPE *warGradPtrY = &warGradPtrX[voxelNumber];
         DTYPE *warGradPtrZ = &warGradPtrY[voxelNumber];
         // Create pointers to the current joint histogram
         double *logHistoPtr = jointHistogramLog[t];
         double *entropyPtr = entropyValues[t];
         double nmi = (entropyPtr[0]+entropyPtr[1])/entropyPtr[2];
         size_t referenceOffset=referenceBinNumber[t]*floatingBinNumber[t];
         size_t floatingOffset=referenceOffset+referenceBinNumber[t];
         int r,w,i;
         DTYPE refValue,warValue,gradX,gradY,gradZ;
         double jointDeriv[3],refDeriv[3],warDeriv[3],commun,jointLog,refLog,warLog;
         // Iterate over all voxel
689
#if defined (NDEBUG) && defined (_OPENMP)
690 691 692 693 694 695
         #pragma omp parallel for default(none) \
         private(i,r,w,refValue,warValue,gradX,gradY,gradZ, \
                 jointDeriv,refDeriv,warDeriv,commun,jointLog,refLog,warLog) \
         shared(voxelNumber,referenceMask,refPtr,warPtr,referenceBinNumber,floatingBinNumber, \
                logHistoPtr,referenceOffset,floatingOffset,nmiGradPtrX,nmiGradPtrY,nmiGradPtrZ, \
                warGradPtrX,warGradPtrY,warGradPtrZ,entropyPtr,nmi,t)
696
#endif // _OPENMP
697 698 699 700 701 702 703 704 705 706 707 708
         for(i=0; i<voxelNumber; ++i)
         {
            // Check if the voxel belongs to the image mask
            if(referenceMask[i]>-1)
            {
               refValue = refPtr[i];
               warValue = warPtr[i];
               if(refValue==refValue && warValue==warValue)
               {
                  gradX = warGradPtrX[i];
                  gradY = warGradPtrY[i];
                  gradZ = warGradPtrZ[i];
709

710 711 712
                  jointDeriv[0]=jointDeriv[1]=jointDeriv[2]=0.f;
                  refDeriv[0]=refDeriv[1]=refDeriv[2]=0.f;
                  warDeriv[0]=warDeriv[1]=warDeriv[2]=0.f;
713

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
                  for(r=(int)(refValue-1.0); r<(int)(refValue+3.0); ++r)
                  {
                     if(-1<r && r<referenceBinNumber[t])
                     {
                        for(w=(int)(warValue-1.0); w<(int)(warValue+3.0); ++w)
                        {
                           if(-1<w && w<floatingBinNumber[t])
                           {
                              commun= GetBasisSplineValue((double)refValue - (double)r) *
                                      GetBasisSplineDerivativeValue((double)warValue - (double)w);
                              jointLog = logHistoPtr[r+w*referenceBinNumber[t]];
                              refLog = logHistoPtr[r+referenceOffset];
                              warLog = logHistoPtr[w+floatingOffset];
                              jointDeriv[0] += commun * gradX * jointLog;
                              jointDeriv[1] += commun * gradY * jointLog;
                              jointDeriv[2] += commun * gradZ * jointLog;
                              refDeriv[0] += commun * gradX * refLog;
                              refDeriv[1] += commun * gradY * refLog;
                              refDeriv[2] += commun * gradZ * refLog;
                              warDeriv[0] += commun * gradX * warLog;
                              warDeriv[1] += commun * gradY * warLog;
                              warDeriv[2] += commun * gradZ * warLog;
                           }
737
                        }
738 739 740 741 742 743 744 745 746 747 748 749 750
                     }
                  }
                  nmiGradPtrX[i] += (DTYPE)((refDeriv[0] + warDeriv[0] -
                                             nmi * jointDeriv[0]) / (entropyPtr[2]*entropyPtr[3]));
                  nmiGradPtrY[i] += (DTYPE)((refDeriv[1] + warDeriv[1] -
                                             nmi * jointDeriv[1]) / (entropyPtr[2]*entropyPtr[3]));
                  nmiGradPtrZ[i] += (DTYPE)((refDeriv[2] + warDeriv[2] -
                                             nmi * jointDeriv[2]) / (entropyPtr[2]*entropyPtr[3]));
               }// Check that the values are defined
            } // mask
         } // loop over all voxel
      } // if active time point
   } // for all time point
751 752 753 754 755 756 757
}
/* *************************************************************** */
template void reg_getVoxelBasedNMIGradient3D<float>(nifti_image *,nifti_image *,bool *,unsigned short *,unsigned short *,double **,double **,nifti_image *,nifti_image *,int *);
template void reg_getVoxelBasedNMIGradient3D<double>(nifti_image *,nifti_image *,bool *,unsigned short *,unsigned short *,double **,double **,nifti_image *,nifti_image *,int *);
/* *************************************************************** */
void reg_nmi::GetVoxelBasedSimilarityMeasureGradient()
{
758 759 760 761 762 763 764 765 766 767 768
   // Check if all required input images are of the same data type
   int dtype = this->referenceImagePointer->datatype;
   if(this->warpedFloatingImagePointer->datatype != dtype ||
         this->warpedFloatingGradientImagePointer->datatype != dtype ||
         this->forwardVoxelBasedGradientImagePointer->datatype != dtype
     )
   {
      fprintf(stderr, "[NiftyReg ERROR] reg_nmi::GetVoxelBasedSimilarityMeasureGradient\n");
      fprintf(stderr, "[NiftyReg ERROR] Input images are exepected to be of the same type\n");
      reg_exit(1);
   }
769 770 771

   //call compute similarity measure to calculate joint histogram
   this->GetSimilarityMeasureValue();
772

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
   // Compute the gradient of the nmi for the forward transformation
   if(this->referenceImagePointer->nz>1)  // 3D input images
   {
      switch(dtype)
      {
      case NIFTI_TYPE_FLOAT32:
         reg_getVoxelBasedNMIGradient3D<float>(this->referenceImagePointer,
                                               this->warpedFloatingImagePointer,
                                               this->activeTimePoint,
                                               this->referenceBinNumber,
                                               this->floatingBinNumber,
                                               this->forwardJointHistogramLog,
                                               this->forwardEntropyValues,
                                               this->warpedFloatingGradientImagePointer,
                                               this->forwardVoxelBasedGradientImagePointer,
                                               this->referenceMaskPointer);
         break;
      case NIFTI_TYPE_FLOAT64:
         reg_getVoxelBasedNMIGradient3D<double>(this->referenceImagePointer,
                                                this->warpedFloatingImagePointer,
                                                this->activeTimePoint,
                                                this->referenceBinNumber,
                                                this->floatingBinNumber,
                                                this->forwardJointHistogramLog,
                                                this->forwardEntropyValues,
                                                this->warpedFloatingGradientImagePointer,
                                                this->forwardVoxelBasedGradientImagePointer,
                                                this->referenceMaskPointer);
         break;
      default:
         fprintf(stderr,"[NiftyReg ERROR] reg_nmi::GetVoxelBasedSimilarityMeasureGradient\n");
         fprintf(stderr,"[NiftyReg ERROR] The input image data type is not supported\n");
         reg_exit(1);
      }
   }
   else  // 2D input images
   {
      switch(dtype)
      {
      case NIFTI_TYPE_FLOAT32:
         reg_getVoxelBasedNMIGradient2D<float>(this->referenceImagePointer,
                                               this->warpedFloatingImagePointer,
                                               this->activeTimePoint,
                                               this->referenceBinNumber,
                                               this->floatingBinNumber,
                                               this->forwardJointHistogramLog,
                                               this->forwardEntropyValues,
                                               this->warpedFloatingGradientImagePointer,
                                               this->forwardVoxelBasedGradientImagePointer,
                                               this->referenceMaskPointer);
         break;
      case NIFTI_TYPE_FLOAT64:
         reg_getVoxelBasedNMIGradient2D<double>(this->referenceImagePointer,
                                                this->warpedFloatingImagePointer,
                                                this->activeTimePoint,
                                                this->referenceBinNumber,
                                                this->floatingBinNumber,
                                                this->forwardJointHistogramLog,
                                                this->forwardEntropyValues,
                                                this->warpedFloatingGradientImagePointer,
                                                this->forwardVoxelBasedGradientImagePointer,
                                                this->referenceMaskPointer);
         break;
      default:
         fprintf(stderr,"[NiftyReg ERROR] reg_nmi::GetVoxelBasedSimilarityMeasureGradient\n");
         fprintf(stderr,"[NiftyReg ERROR] The input image data type is not supported\n");
         reg_exit(1);
      }
   }

   if(this->isSymmetric)
   {
      dtype = this->floatingImagePointer->datatype;
      if(this->warpedReferenceImagePointer->datatype != dtype ||
            this->warpedReferenceGradientImagePointer->datatype != dtype ||
            this->backwardVoxelBasedGradientImagePointer->datatype != dtype
        )
      {
         fprintf(stderr, "[NiftyReg ERROR] reg_nmi::GetVoxelBasedSimilarityMeasureGradient\n");
         fprintf(stderr, "[NiftyReg ERROR] Input images are exepected to be of the same type\n");
         reg_exit(1);
      }
      // Compute the gradient of the nmi for the backward transformation
      if(this->floatingImagePointer->nz>1)  // 3D input images
      {
         switch(dtype)
         {
         case NIFTI_TYPE_FLOAT32:
            reg_getVoxelBasedNMIGradient3D<float>(this->floatingImagePointer,
                                                  this->warpedReferenceImagePointer,
863 864
                                                  this->activeTimePoint,
                                                  this->floatingBinNumber,
865 866 867 868 869 870
                                                  this->referenceBinNumber,
                                                  this->backwardJointHistogramLog,
                                                  this->backwardEntropyValues,
                                                  this->warpedReferenceGradientImagePointer,
                                                  this->backwardVoxelBasedGradientImagePointer,
                                                  this->floatingMaskPointer);
871
            break;
872 873 874
         case NIFTI_TYPE_FLOAT64:
            reg_getVoxelBasedNMIGradient3D<double>(this->floatingImagePointer,
                                                   this->warpedReferenceImagePointer,
875 876
                                                   this->activeTimePoint,
                                                   this->floatingBinNumber,
877 878 879 880 881 882
                                                   this->referenceBinNumber,
                                                   this->backwardJointHistogramLog,
                                                   this->backwardEntropyValues,
                                                   this->warpedReferenceGradientImagePointer,
                                                   this->backwardVoxelBasedGradientImagePointer,
                                                   this->floatingMaskPointer);
883
            break;
884
         default:
885 886 887
            fprintf(stderr,"[NiftyReg ERROR] reg_nmi::GetVoxelBasedSimilarityMeasureGradient\n");
            fprintf(stderr,"[NiftyReg ERROR] The input image data type is not supported\n");
            reg_exit(1);
888 889 890 891 892 893 894 895 896
         }
      }
      else  // 2D input images
      {
         switch(dtype)
         {
         case NIFTI_TYPE_FLOAT32:
            reg_getVoxelBasedNMIGradient2D<float>(this->floatingImagePointer,
                                                  this->warpedReferenceImagePointer,
897 898
                                                  this->activeTimePoint,
                                                  this->floatingBinNumber,
899 900 901 902 903 904
                                                  this->referenceBinNumber,
                                                  this->backwardJointHistogramLog,
                                                  this->backwardEntropyValues,
                                                  this->warpedReferenceGradientImagePointer,
                                                  this->backwardVoxelBasedGradientImagePointer,
                                                  this->floatingMaskPointer);
905
            break;
906 907 908
         case NIFTI_TYPE_FLOAT64:
            reg_getVoxelBasedNMIGradient2D<double>(this->floatingImagePointer,
                                                   this->warpedReferenceImagePointer,
909 910
                                                   this->activeTimePoint,
                                                   this->floatingBinNumber,
911 912 913 914 915 916
                                                   this->referenceBinNumber,
                                                   this->backwardJointHistogramLog,
                                                   this->backwardEntropyValues,
                                                   this->warpedReferenceGradientImagePointer,
                                                   this->backwardVoxelBasedGradientImagePointer,
                                                   this->floatingMaskPointer);
917
            break;
918
         default:
919 920 921
            fprintf(stderr,"[NiftyReg ERROR] reg_nmi::GetVoxelBasedSimilarityMeasureGradient\n");
            fprintf(stderr,"[NiftyReg ERROR] The input image data type is not supported\n");
            reg_exit(1);
922 923 924
         }
      }
   }
925
#ifndef NDEBUG
926
   printf("[NiftyReg DEBUG] reg_nmi::GetVoxelBasedSimilarityMeasureGradient called\n");
927 928 929 930 931 932
#endif
}
/* *************************************************************** */
/* *************************************************************** */

#endif // _REG_NMI