1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 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 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 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 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 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 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 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 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 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
|
/*=========================================================================
*
* Copyright UMC Utrecht and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkParzenWindowHistogramImageToImageMetric_hxx
#define itkParzenWindowHistogramImageToImageMetric_hxx
#include "itkParzenWindowHistogramImageToImageMetric.h"
#include "itkBSplineKernelFunction2.h"
#include "itkBSplineDerivativeKernelFunction2.h"
#include "itkImageLinearIteratorWithIndex.h"
#include "itkImageScanlineIterator.h"
#include <vnl/vnl_math.h>
#include <cassert>
namespace itk
{
/**
* ********************* Constructor ****************************
*/
template <typename TFixedImage, typename TMovingImage>
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::ParzenWindowHistogramImageToImageMetric()
{
this->SetUseImageSampler(true);
this->SetUseFixedImageLimiter(true);
this->SetUseMovingImageLimiter(true);
/** Initialize the m_ParzenWindowHistogramThreaderParameters */
this->m_ParzenWindowHistogramThreaderParameters.m_Metric = this;
} // end Constructor
/**
* ********************* PrintSelf ******************************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::PrintSelf(std::ostream & os, Indent indent) const
{
/** Call the superclass' PrintSelf. */
Superclass::PrintSelf(os, indent);
/** Add debugging information. */
os << indent << "NumberOfFixedHistogramBins: " << this->m_NumberOfFixedHistogramBins << std::endl;
os << indent << "NumberOfMovingHistogramBins: " << this->m_NumberOfMovingHistogramBins << std::endl;
os << indent << "FixedKernelBSplineOrder: " << this->m_FixedKernelBSplineOrder << std::endl;
os << indent << "MovingKernelBSplineOrder: " << this->m_MovingKernelBSplineOrder << std::endl;
/*double m_MovingImageNormalizedMin;
double m_FixedImageNormalizedMin;
double m_FixedImageBinSize;
double m_MovingImageBinSize;
double m_FixedParzenTermToIndexOffset;
double m_MovingParzenTermToIndexOffset;
bool m_UseDerivative;
m_UseExplicitPDFDerivatives
bool m_UseFiniteDifferenceDerivative;
double m_FiniteDifferencePerturbation;*/
/** This function is not complete, but we don't use it anyway. */
} // end PrintSelf()
/**
* ********************* Initialize *****************************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::Initialize()
{
/** Call the superclass to check that standard components are available. */
this->Superclass::Initialize();
/** Set up the histograms. */
this->InitializeHistograms();
/** Set up the Parzen windows. */
this->InitializeKernels();
/** If the user plans to use a finite difference derivative,
* allocate some memory for the perturbed alpha variables.
*/
if (this->GetUseDerivative() && this->GetUseFiniteDifferenceDerivative())
{
this->m_PerturbedAlphaRight.SetSize(this->GetNumberOfParameters());
this->m_PerturbedAlphaLeft.SetSize(this->GetNumberOfParameters());
}
else
{
this->m_PerturbedAlphaRight.SetSize(0);
this->m_PerturbedAlphaLeft.SetSize(0);
}
} // end Initialize()
/**
* ****************** InitializeHistograms *****************************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::InitializeHistograms()
{
/* Compute binsize for the histogram.
*
* The binsize for the image intensities needs to be adjusted so that
* we can avoid dealing with boundary conditions using the cubic
* spline as the Parzen window. We do this by increasing the size
* of the bins so that the joint histogram becomes "padded" at the
* borders. Because we are changing the binsize,
* we also need to shift the minimum by the padded amount in order to
* avoid minimum values filling in our padded region.
*
* Note that there can still be non-zero bin values in the padded region,
* it's just that these bins will never be a central bin for the Parzen
* window.
*/
// int fixedPadding = 2; // this will pad by 2 bins
// int movingPadding = 2; // this will pad by 2 bins
int fixedPadding = this->m_FixedKernelBSplineOrder / 2; // should be enough
int movingPadding = this->m_MovingKernelBSplineOrder / 2;
/** The ratio times the expected bin size will be added twice to the image range. */
const double smallNumberRatio = 0.001;
const double smallNumberFixed = smallNumberRatio *
(Superclass::m_FixedImageMaxLimit - Superclass::m_FixedImageMinLimit) /
static_cast<double>(this->m_NumberOfFixedHistogramBins - 2 * fixedPadding - 1);
const double smallNumberMoving = smallNumberRatio *
(Superclass::m_MovingImageMaxLimit - Superclass::m_MovingImageMinLimit) /
static_cast<double>(this->m_NumberOfFixedHistogramBins - 2 * movingPadding - 1);
/** Compute binsizes. */
const auto fixedHistogramWidth = static_cast<double>(
static_cast<OffsetValueType>(this->m_NumberOfFixedHistogramBins) // requires cast to signed type!
- 2.0 * fixedPadding - 1.0);
this->m_FixedImageBinSize =
(Superclass::m_FixedImageMaxLimit - Superclass::m_FixedImageMinLimit + 2.0 * smallNumberFixed) /
fixedHistogramWidth;
this->m_FixedImageBinSize = std::max(this->m_FixedImageBinSize, 1e-10);
this->m_FixedImageBinSize = std::min(this->m_FixedImageBinSize, 1e+10);
this->m_FixedImageNormalizedMin = (Superclass::m_FixedImageMinLimit - smallNumberFixed) / this->m_FixedImageBinSize -
static_cast<double>(fixedPadding);
const auto movingHistogramWidth = static_cast<double>(
static_cast<OffsetValueType>(this->m_NumberOfMovingHistogramBins) // requires cast to signed type!
- 2.0 * movingPadding - 1.0);
this->m_MovingImageBinSize =
(Superclass::m_MovingImageMaxLimit - Superclass::m_MovingImageMinLimit + 2.0 * smallNumberMoving) /
movingHistogramWidth;
this->m_MovingImageBinSize = std::max(this->m_MovingImageBinSize, 1e-10);
this->m_MovingImageBinSize = std::min(this->m_MovingImageBinSize, 1e+10);
this->m_MovingImageNormalizedMin =
(Superclass::m_MovingImageMinLimit - smallNumberMoving) / this->m_MovingImageBinSize -
static_cast<double>(movingPadding);
/** Allocate memory for the marginal PDF. */
this->m_FixedImageMarginalPDF.SetSize(this->m_NumberOfFixedHistogramBins);
this->m_MovingImageMarginalPDF.SetSize(this->m_NumberOfMovingHistogramBins);
/** Allocate memory for the joint PDF and joint PDF derivatives. */
/** First set these ones to zero */
this->m_FixedIncrementalMarginalPDFRight = nullptr;
this->m_MovingIncrementalMarginalPDFRight = nullptr;
this->m_FixedIncrementalMarginalPDFLeft = nullptr;
this->m_MovingIncrementalMarginalPDFLeft = nullptr;
/** For the joint PDF define a region starting from {0,0}
* with size {this->m_NumberOfMovingHistogramBins, this->m_NumberOfFixedHistogramBins}
* The dimension represents moving image Parzen window index
* and fixed image Parzen window index, respectively.
* The moving Parzen index is chosen as the first dimension,
* because probably the moving B-spline kernel order will be larger
* than the fixed B-spline kernel order and it is faster to iterate along
* the first dimension.
*/
this->m_JointPDF = JointPDFType::New();
this->m_JointPDF->SetRegions(JointPDFSizeType{ m_NumberOfMovingHistogramBins, m_NumberOfFixedHistogramBins });
this->m_JointPDF->Allocate();
if (this->GetUseDerivative())
{
/** For the derivatives of the joint PDF define a region starting from {0,0,0}
* with size {GetNumberOfParameters(),m_NumberOfMovingHistogramBins,
* m_NumberOfFixedHistogramBins}. The dimension represents transform parameters,
* moving image Parzen window index and fixed image Parzen window index,
* respectively.
* For the incremental pdfs (used for finite difference derivative estimation)
* the same size happens to be valid.
*/
const JointPDFDerivativesSizeType jointPDFDerivativesSize{ this->GetNumberOfParameters(),
m_NumberOfMovingHistogramBins,
m_NumberOfFixedHistogramBins };
if (this->GetUseFiniteDifferenceDerivative())
{
this->m_JointPDFDerivatives = nullptr;
this->m_IncrementalJointPDFRight = JointPDFDerivativesType::New();
this->m_IncrementalJointPDFLeft = JointPDFDerivativesType::New();
this->m_IncrementalJointPDFRight->SetRegions(jointPDFDerivativesSize);
this->m_IncrementalJointPDFLeft->SetRegions(jointPDFDerivativesSize);
this->m_IncrementalJointPDFRight->Allocate();
this->m_IncrementalJointPDFLeft->Allocate();
/** Also initialize the incremental marginal pdfs. */
const IncrementalMarginalPDFSizeType fixedIMPDFSize{ this->GetNumberOfParameters(),
m_NumberOfFixedHistogramBins };
const IncrementalMarginalPDFSizeType movingIMPDFSize{ this->GetNumberOfParameters(),
m_NumberOfMovingHistogramBins };
this->m_FixedIncrementalMarginalPDFRight = IncrementalMarginalPDFType::New();
this->m_MovingIncrementalMarginalPDFRight = IncrementalMarginalPDFType::New();
this->m_FixedIncrementalMarginalPDFLeft = IncrementalMarginalPDFType::New();
this->m_MovingIncrementalMarginalPDFLeft = IncrementalMarginalPDFType::New();
this->m_FixedIncrementalMarginalPDFRight->SetRegions(fixedIMPDFSize);
this->m_MovingIncrementalMarginalPDFRight->SetRegions(movingIMPDFSize);
this->m_FixedIncrementalMarginalPDFLeft->SetRegions(fixedIMPDFSize);
this->m_MovingIncrementalMarginalPDFLeft->SetRegions(movingIMPDFSize);
this->m_FixedIncrementalMarginalPDFRight->Allocate();
this->m_MovingIncrementalMarginalPDFRight->Allocate();
this->m_FixedIncrementalMarginalPDFLeft->Allocate();
this->m_MovingIncrementalMarginalPDFLeft->Allocate();
} // end if this->GetUseFiniteDifferenceDerivative()
else
{
if (this->m_UseExplicitPDFDerivatives)
{
this->m_IncrementalJointPDFRight = nullptr;
this->m_IncrementalJointPDFLeft = nullptr;
this->m_JointPDFDerivatives = JointPDFDerivativesType::New();
this->m_JointPDFDerivatives->SetRegions(jointPDFDerivativesSize);
this->m_JointPDFDerivatives->Allocate();
}
else
{
/** De-allocate large amount of memory for the m_JointPDFDerivatives. */
// \todo Should not be allocated in the first place
if (!this->m_JointPDFDerivatives.IsNull())
{
this->m_JointPDFDerivatives->SetRegions(JointPDFDerivativesSizeType{});
this->m_JointPDFDerivatives->Allocate();
this->m_JointPDFDerivatives->GetPixelContainer()->Squeeze();
}
}
}
}
else
{
this->m_JointPDFDerivatives = nullptr;
this->m_IncrementalJointPDFRight = nullptr;
this->m_IncrementalJointPDFLeft = nullptr;
}
} // end InitializeHistograms()
/**
* ****************** InitializeKernels *****************************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::InitializeKernels()
{
switch (this->m_FixedKernelBSplineOrder)
{
case 0:
this->m_FixedKernel = BSplineKernelFunction2<0>::New();
break;
case 1:
this->m_FixedKernel = BSplineKernelFunction2<1>::New();
break;
case 2:
this->m_FixedKernel = BSplineKernelFunction2<2>::New();
break;
case 3:
this->m_FixedKernel = BSplineKernelFunction2<3>::New();
break;
default:
itkExceptionMacro(
"The following FixedKernelBSplineOrder is not implemented: " << this->m_FixedKernelBSplineOrder);
} // end switch FixedKernelBSplineOrder
switch (this->m_MovingKernelBSplineOrder)
{
case 0:
this->m_MovingKernel = BSplineKernelFunction2<0>::New();
/** The derivative of a zero order B-spline makes no sense. Using the
* derivative of a first order gives a kind of finite difference idea
* Anyway, if you plan to call GetValueAndDerivative you should use
* a higher B-spline order.
*/
this->m_DerivativeMovingKernel = BSplineDerivativeKernelFunction2<1>::New();
break;
case 1:
this->m_MovingKernel = BSplineKernelFunction2<1>::New();
this->m_DerivativeMovingKernel = BSplineDerivativeKernelFunction2<1>::New();
break;
case 2:
this->m_MovingKernel = BSplineKernelFunction2<2>::New();
this->m_DerivativeMovingKernel = BSplineDerivativeKernelFunction2<2>::New();
break;
case 3:
this->m_MovingKernel = BSplineKernelFunction2<3>::New();
this->m_DerivativeMovingKernel = BSplineDerivativeKernelFunction2<3>::New();
break;
default:
itkExceptionMacro(
"The following MovingKernelBSplineOrder is not implemented: " << this->m_MovingKernelBSplineOrder);
} // end switch MovingKernelBSplineOrder
/** The region of support of the Parzen window determines which bins
* of the joint PDF are effected by the pair of image values.
* For example, if we are using a cubic spline for the moving image Parzen
* window, four bins are affected. If the fixed image Parzen window is
* a zero-order spline (box car) only one bin is affected.
*/
/** Set the size of the Parzen window. */
JointPDFSizeType parzenWindowSize;
parzenWindowSize[0] = this->m_MovingKernelBSplineOrder + 1;
parzenWindowSize[1] = this->m_FixedKernelBSplineOrder + 1;
this->m_JointPDFWindow.SetSize(parzenWindowSize);
/** The ParzenIndex is the lowest bin number that is affected by a
* pixel and computed as:
* ParzenIndex = std::floor( ParzenTerm + ParzenTermToIndexOffset )
* where ParzenTermToIndexOffset = 1/2, 0, -1/2, or -1.
*/
this->m_FixedParzenTermToIndexOffset = 0.5 - static_cast<double>(this->m_FixedKernelBSplineOrder) / 2.0;
this->m_MovingParzenTermToIndexOffset = 0.5 - static_cast<double>(this->m_MovingKernelBSplineOrder) / 2.0;
} // end InitializeKernels()
/**
* ********************* InitializeThreadingParameters ****************************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::InitializeThreadingParameters() const
{
/** Call superclass implementation. */
Superclass::InitializeThreadingParameters();
/** Resize and initialize the threading related parameters.
* The SetSize() functions do not resize the data when this is not
* needed, which saves valuable re-allocation time.
* Filling the potentially large vectors is performed later, in each thread,
* which has performance benefits for larger vector sizes.
*/
/** Construct region size for the joint histograms. */
const JointPDFSizeType jointPDFSize{ m_NumberOfMovingHistogramBins, m_NumberOfFixedHistogramBins };
const ThreadIdType numberOfThreads = Self::GetNumberOfWorkUnits();
/** Only resize the array of structs when needed. */
m_ParzenWindowHistogramGetValueAndDerivativePerThreadVariables.resize(numberOfThreads);
/** Some initialization. */
for (auto & perThreadVariable : m_ParzenWindowHistogramGetValueAndDerivativePerThreadVariables)
{
perThreadVariable.st_NumberOfPixelsCounted = SizeValueType{};
// Initialize the joint pdf
JointPDFPointer & jointPDF = perThreadVariable.st_JointPDF;
if (jointPDF.IsNull())
{
jointPDF = JointPDFType::New();
}
if (jointPDF->GetLargestPossibleRegion() != JointPDFRegionType(jointPDFSize))
{
jointPDF->SetRegions(jointPDFSize);
jointPDF->Allocate();
}
}
} // end InitializeThreadingParameters()
/**
* ******************** GetDerivative ***************************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::GetDerivative(const ParametersType & parameters,
DerivativeType & derivative) const
{
/** Call the combined version, since the additional computation of
* the value does not take extra time.
*/
MeasureType value;
this->GetValueAndDerivative(parameters, value, derivative);
} // end GetDerivative()
/**
* ******************** GetValueAndDerivative ***************************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::GetValueAndDerivative(
const ParametersType & parameters,
MeasureType & value,
DerivativeType & derivative) const
{
if (this->GetUseFiniteDifferenceDerivative())
{
this->GetValueAndFiniteDifferenceDerivative(parameters, value, derivative);
}
else
{
this->GetValueAndAnalyticDerivative(parameters, value, derivative);
}
} // end GetValueAndDerivative()
/**
* ********************** EvaluateParzenValues ***************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::EvaluateParzenValues(
double parzenWindowTerm,
OffsetValueType parzenWindowIndex,
const KernelFunctionType & kernel,
PDFValueType * const parzenValues)
{
kernel.Evaluate(static_cast<double>(parzenWindowIndex) - parzenWindowTerm, parzenValues);
} // end EvaluateParzenValues()
/**
* ********************** UpdateJointPDFAndDerivatives ***************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::UpdateJointPDFAndDerivatives(
const RealType fixedImageValue,
const RealType movingImageValue,
const DerivativeType * imageJacobian,
const NonZeroJacobianIndicesType * nzji,
JointPDFType * jointPDF) const
{
using PDFIteratorType = ImageScanlineIterator<JointPDFType>;
/** Determine Parzen window arguments (see eq. 6 of Mattes paper [2]). */
const double fixedImageParzenWindowTerm =
fixedImageValue / this->m_FixedImageBinSize - this->m_FixedImageNormalizedMin;
const double movingImageParzenWindowTerm =
movingImageValue / this->m_MovingImageBinSize - this->m_MovingImageNormalizedMin;
/** The lowest bin numbers affected by this pixel: */
const auto fixedImageParzenWindowIndex =
static_cast<OffsetValueType>(std::floor(fixedImageParzenWindowTerm + this->m_FixedParzenTermToIndexOffset));
const auto movingImageParzenWindowIndex =
static_cast<OffsetValueType>(std::floor(movingImageParzenWindowTerm + this->m_MovingParzenTermToIndexOffset));
/** The Parzen values. */
const auto numberOfFixedParzenValues = m_JointPDFWindow.GetSize()[1];
const auto numberOfMovingParzenValues = m_JointPDFWindow.GetSize()[0];
// Create a buffer of Parzen values for both the fixed and the moving image.
const auto parzenValues = std::make_unique<PDFValueType[]>(numberOfFixedParzenValues + numberOfMovingParzenValues);
PDFValueType * const fixedParzenValues = parzenValues.get();
PDFValueType * const movingParzenValues = parzenValues.get() + numberOfFixedParzenValues;
Self::EvaluateParzenValues(
fixedImageParzenWindowTerm, fixedImageParzenWindowIndex, *m_FixedKernel, fixedParzenValues);
Self::EvaluateParzenValues(
movingImageParzenWindowTerm, movingImageParzenWindowIndex, *m_MovingKernel, movingParzenValues);
/** Position the JointPDFWindow. */
JointPDFIndexType pdfWindowIndex;
pdfWindowIndex[0] = movingImageParzenWindowIndex;
pdfWindowIndex[1] = fixedImageParzenWindowIndex;
/** For thread-safety, make a local copy of the support region,
* and use that one. Because each thread will modify it.
*/
JointPDFRegionType jointPDFWindow = this->m_JointPDFWindow;
jointPDFWindow.SetIndex(pdfWindowIndex);
PDFIteratorType it(jointPDF, jointPDFWindow);
if (!imageJacobian)
{
/** Loop over the Parzen window region and increment the values. */
for (unsigned int f = 0; f < numberOfFixedParzenValues; ++f)
{
const double fv = fixedParzenValues[f];
for (unsigned int m = 0; m < numberOfMovingParzenValues; ++m)
{
it.Value() += static_cast<PDFValueType>(fv * movingParzenValues[m]);
++it;
}
it.NextLine();
}
}
else
{
/** Compute the derivatives of the moving Parzen window. */
ParzenValueContainerType derivativeMovingParzenValues(numberOfMovingParzenValues);
Self::EvaluateParzenValues(movingImageParzenWindowTerm,
movingImageParzenWindowIndex,
*m_DerivativeMovingKernel,
derivativeMovingParzenValues.data_block());
const auto et = static_cast<double>(this->m_MovingImageBinSize);
/** Loop over the Parzen window region and increment the values
* Also update the pdf derivatives.
*/
for (unsigned int f = 0; f < numberOfFixedParzenValues; ++f)
{
const double fv = fixedParzenValues[f];
const double fv_et = fv / et;
for (unsigned int m = 0; m < numberOfMovingParzenValues; ++m)
{
it.Value() += static_cast<PDFValueType>(fv * movingParzenValues[m]);
this->UpdateJointPDFDerivatives(it.GetIndex(), fv_et * derivativeMovingParzenValues[m], *imageJacobian, *nzji);
++it;
}
it.NextLine();
}
}
} // end UpdateJointPDFAndDerivatives()
/**
* *************** UpdateJointPDFDerivatives ***************************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::UpdateJointPDFDerivatives(
const JointPDFIndexType & pdfIndex,
double factor,
const DerivativeType & imageJacobian,
const NonZeroJacobianIndicesType & nzji) const
{
/** Get the pointer to the element with index [0, pdfIndex[0], pdfIndex[1]]. */
PDFDerivativeValueType * derivPtr = this->m_JointPDFDerivatives->GetBufferPointer() +
(pdfIndex[0] * this->m_JointPDFDerivatives->GetOffsetTable()[1]) +
(pdfIndex[1] * this->m_JointPDFDerivatives->GetOffsetTable()[2]);
const auto numberOfParameters = this->GetNumberOfParameters();
if (nzji.size() == numberOfParameters)
{
/** Loop over all Jacobians. */
typename DerivativeType::const_iterator imjac = imageJacobian.begin();
for (unsigned int mu = 0; mu < numberOfParameters; ++mu)
{
*(derivPtr) -= static_cast<PDFDerivativeValueType>(*imjac * factor);
++derivPtr;
++imjac;
}
}
else
{
/** Loop only over the non-zero Jacobians. */
for (unsigned int i = 0; i < imageJacobian.GetSize(); ++i)
{
const unsigned int mu = nzji[i];
PDFDerivativeValueType * ptr = derivPtr + mu;
*(ptr) -= static_cast<PDFDerivativeValueType>(imageJacobian[i] * factor);
}
}
} // end UpdateJointPDFDerivatives()
/**
* *********************** NormalizeJointPDF ***********************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::NormalizeJointPDF(JointPDFType * pdf,
const double factor) const
{
using JointPDFIteratorType = ImageScanlineIterator<JointPDFType>;
JointPDFIteratorType it(pdf, pdf->GetBufferedRegion());
const auto castfac = static_cast<PDFValueType>(factor);
while (!it.IsAtEnd())
{
while (!it.IsAtEndOfLine())
{
it.Value() *= castfac;
++it;
}
it.NextLine();
}
} // end NormalizeJointPDF()
/**
* *********************** NormalizeJointPDFDerivatives ***********************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::NormalizeJointPDFDerivatives(
JointPDFDerivativesType * pdf,
const double factor) const
{
using JointPDFDerivativesIteratorType = ImageScanlineIterator<JointPDFDerivativesType>;
JointPDFDerivativesIteratorType it(pdf, pdf->GetBufferedRegion());
const PDFValueType castfac = static_cast<PDFValueType>(factor);
while (!it.IsAtEnd())
{
while (!it.IsAtEndOfLine())
{
it.Value() *= castfac;
++it;
}
it.NextLine();
}
} // end NormalizeJointPDFDerivatives()
/**
* ************************ ComputeMarginalPDF ***********************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::ComputeMarginalPDF(
const JointPDFType * itkNotUsed(jointPDF),
MarginalPDFType & marginalPDF,
const unsigned int direction) const
{
using JointPDFLinearIterator = ImageLinearIteratorWithIndex<JointPDFType>;
// \todo: bug? shouldn't this be over the function argument jointPDF ?
JointPDFLinearIterator linearIter(this->m_JointPDF, this->m_JointPDF->GetBufferedRegion());
linearIter.SetDirection(direction);
linearIter.GoToBegin();
unsigned int marginalIndex = 0;
while (!linearIter.IsAtEnd())
{
PDFValueType sum = 0.0;
while (!linearIter.IsAtEndOfLine())
{
sum += linearIter.Get();
++linearIter;
}
marginalPDF[marginalIndex] = sum;
linearIter.NextLine();
++marginalIndex;
}
} // end ComputeMarginalPDFs()
/**
* ******************** ComputeIncrementalMarginalPDFs *******************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::ComputeIncrementalMarginalPDFs(
const JointPDFDerivativesType * incrementalPDF,
IncrementalMarginalPDFType * fixedIncrementalMarginalPDF,
IncrementalMarginalPDFType * movingIncrementalMarginalPDF) const
{
using IncIteratorType = itk::ImageRegionConstIterator<JointPDFDerivativesType>;
using IncMargIteratorType = itk::ImageLinearIteratorWithIndex<IncrementalMarginalPDFType>;
fixedIncrementalMarginalPDF->FillBuffer(PDFValueType{});
movingIncrementalMarginalPDF->FillBuffer(PDFValueType{});
IncIteratorType incit(incrementalPDF, incrementalPDF->GetLargestPossibleRegion());
IncMargIteratorType fixincit(fixedIncrementalMarginalPDF, fixedIncrementalMarginalPDF->GetLargestPossibleRegion());
IncMargIteratorType movincit(movingIncrementalMarginalPDF, movingIncrementalMarginalPDF->GetLargestPossibleRegion());
const auto numberOfParameters = this->GetNumberOfParameters();
/** Loop over the incremental pdf and update the incremental marginal pdfs. */
for (unsigned int f = 0; f < this->m_NumberOfFixedHistogramBins; ++f)
{
for (unsigned int m = 0; m < this->m_NumberOfMovingHistogramBins; ++m)
{
for (unsigned int p = 0; p < numberOfParameters; ++p)
{
fixincit.Value() += incit.Get();
movincit.Value() += incit.Get();
++incit;
++fixincit;
++movincit;
}
fixincit.GoToBeginOfLine();
movincit.NextLine();
}
fixincit.NextLine();
movincit.GoToBegin();
}
} // end ComputeIncrementalMarginalPDFs()
/**
* ******************* UpdateJointPDFAndIncrementalPDFs *******************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::UpdateJointPDFAndIncrementalPDFs(
RealType fixedImageValue,
RealType movingImageValue,
RealType movingMaskValue,
const DerivativeType & movingImageValuesRight,
const DerivativeType & movingImageValuesLeft,
const DerivativeType & movingMaskValuesRight,
const DerivativeType & movingMaskValuesLeft,
const NonZeroJacobianIndicesType & nzji) const
{
/** Pointers to the first pixels in the incremental joint pdfs. */
PDFDerivativeValueType * incRightBasePtr = this->m_IncrementalJointPDFRight->GetBufferPointer();
PDFDerivativeValueType * incLeftBasePtr = this->m_IncrementalJointPDFLeft->GetBufferPointer();
/** The Parzen value containers. */
ParzenValueContainerType fixedParzenValues(this->m_JointPDFWindow.GetSize()[1]);
ParzenValueContainerType movingParzenValues(this->m_JointPDFWindow.GetSize()[0]);
/** Determine fixed image Parzen window arguments (see eq. 6 of Mattes paper [2]). */
const double fixedImageParzenWindowTerm =
fixedImageValue / this->m_FixedImageBinSize - this->m_FixedImageNormalizedMin;
/** The lowest bin numbers affected by this pixel: */
const auto fixedImageParzenWindowIndex =
static_cast<OffsetValueType>(std::floor(fixedImageParzenWindowTerm + this->m_FixedParzenTermToIndexOffset));
Self::EvaluateParzenValues(
fixedImageParzenWindowTerm, fixedImageParzenWindowIndex, *m_FixedKernel, fixedParzenValues.data_block());
if (movingMaskValue > 1e-10)
{
/** Determine moving image Parzen window arguments (see eq. 6 of Mattes paper [2]). */
const double movingImageParzenWindowTerm =
movingImageValue / this->m_MovingImageBinSize - this->m_MovingImageNormalizedMin;
const auto movingImageParzenWindowIndex =
static_cast<OffsetValueType>(std::floor(movingImageParzenWindowTerm + this->m_MovingParzenTermToIndexOffset));
Self::EvaluateParzenValues(
movingImageParzenWindowTerm, movingImageParzenWindowIndex, *m_MovingKernel, movingParzenValues.data_block());
/** Position the JointPDFWindow (set the start index). */
JointPDFIndexType pdfIndex;
pdfIndex[0] = movingImageParzenWindowIndex;
pdfIndex[1] = fixedImageParzenWindowIndex;
/** Loop over the Parzen window region and do the following update:
*
* m_JointPDF(M,F) += movingMask * fixedParzen(F) * movingParzen(M);
* m_IncrementalJointPDF<Right/Left>(k,M,F) -= movingMask * fixedParzen(F) * movingParzen(M);
* for all k with nonzero Jacobian.
*/
for (unsigned int f = 0; f < fixedParzenValues.GetSize(); ++f)
{
const double fv_mask = fixedParzenValues[f] * movingMaskValue;
for (unsigned int m = 0; m < movingParzenValues.GetSize(); ++m)
{
const auto fv_mask_mv = static_cast<PDFValueType>(fv_mask * movingParzenValues[m]);
this->m_JointPDF->GetPixel(pdfIndex) += fv_mask_mv;
auto offset = static_cast<unsigned long>(pdfIndex[0] * this->m_IncrementalJointPDFRight->GetOffsetTable()[1] +
pdfIndex[1] * this->m_IncrementalJointPDFRight->GetOffsetTable()[2]);
/** Get the pointer to the element with index [0, pdfIndex[0], pdfIndex[1]]. */
PDFDerivativeValueType * incRightPtr = incRightBasePtr + offset;
PDFDerivativeValueType * incLeftPtr = incLeftBasePtr + offset;
/** Loop only over the non-zero Jacobians. */
for (unsigned int i = 0; i < nzji.size(); ++i)
{
const unsigned int mu = nzji[i];
PDFDerivativeValueType * rPtr = incRightPtr + mu;
PDFDerivativeValueType * lPtr = incLeftPtr + mu;
*(rPtr) -= fv_mask_mv;
*(lPtr) -= fv_mask_mv;
} // end for i
++(pdfIndex[0]);
} // end for m
pdfIndex[0] = movingImageParzenWindowIndex;
++(pdfIndex[1]);
} // end for f
} // end if movingMaskValue > 1e-10
/** Loop only over the non-zero Jacobians and update the incremental pdfs and
* update the perturbed alphas:
*
* m_IncrementalJointPDF<Right/Left>(k,M,F) +=
* movingMask<Right/Left>[k] * fixedParzen(F) * movingParzen<Right/Left>(M)[k];
* m_PerturbedAlpha<Right/Left>[k] += movingMask<Right/Left>[k] - movingMask;
* for all k with nonzero Jacobian.
*/
JointPDFDerivativesIndexType rindex;
JointPDFDerivativesIndexType lindex;
for (unsigned int i = 0; i < nzji.size(); ++i)
{
const unsigned int mu = nzji[i];
const double maskr = movingMaskValuesRight[i];
const double maskl = movingMaskValuesLeft[i];
if (maskr > 1e-10)
{
/** Compute Parzen stuff; note: we reuse the movingParzenValues container. */
const double movr = movingImageValuesRight[i];
const double movParzenWindowTermRight = movr / this->m_MovingImageBinSize - this->m_MovingImageNormalizedMin;
const auto movParzenWindowIndexRight =
static_cast<OffsetValueType>(std::floor(movParzenWindowTermRight + this->m_MovingParzenTermToIndexOffset));
Self::EvaluateParzenValues(
movParzenWindowTermRight, movParzenWindowIndexRight, *m_MovingKernel, movingParzenValues.data_block());
/** Initialize index in IncrementalJointPDFRight. */
rindex[0] = mu;
rindex[1] = movParzenWindowIndexRight;
rindex[2] = fixedImageParzenWindowIndex;
/** Loop over Parzen window and update IncrementalJointPDFRight. */
for (unsigned int f = 0; f < fixedParzenValues.GetSize(); ++f)
{
const double fv_mask = fixedParzenValues[f] * maskr;
for (unsigned int m = 0; m < movingParzenValues.GetSize(); ++m)
{
const auto fv_mask_mv = static_cast<PDFValueType>(fv_mask * movingParzenValues[m]);
this->m_IncrementalJointPDFRight->GetPixel(rindex) += fv_mask_mv;
++(rindex[1]);
} // end for m
++(rindex[2]);
rindex[1] = movParzenWindowIndexRight;
} // end for f
} // end if maskr
if (maskl > 1e-10)
{
/** Compute Parzen stuff; note: we reuse the movingParzenValues container. */
const double movl = movingImageValuesLeft[i];
const double movParzenWindowTermLeft = movl / this->m_MovingImageBinSize - this->m_MovingImageNormalizedMin;
const auto movParzenWindowIndexLeft =
static_cast<OffsetValueType>(std::floor(movParzenWindowTermLeft + this->m_MovingParzenTermToIndexOffset));
Self::EvaluateParzenValues(
movParzenWindowTermLeft, movParzenWindowIndexLeft, *m_MovingKernel, movingParzenValues.data_block());
/** Initialize index in IncrementalJointPDFLeft. */
lindex[0] = mu;
lindex[1] = movParzenWindowIndexLeft;
lindex[2] = fixedImageParzenWindowIndex;
/** Loop over Parzen window and update IncrementalJointPDFLeft. */
for (unsigned int f = 0; f < fixedParzenValues.GetSize(); ++f)
{
const double fv_mask = fixedParzenValues[f] * maskl;
for (unsigned int m = 0; m < movingParzenValues.GetSize(); ++m)
{
const auto fv_mask_mv = static_cast<PDFValueType>(fv_mask * movingParzenValues[m]);
this->m_IncrementalJointPDFLeft->GetPixel(lindex) += fv_mask_mv;
++(lindex[1]);
} // end for m
++(lindex[2]);
lindex[1] = movParzenWindowIndexLeft;
} // end for f
} // end if maskl
/** Update the perturbed alphas. */
this->m_PerturbedAlphaRight[mu] += (maskr - movingMaskValue);
this->m_PerturbedAlphaLeft[mu] += (maskl - movingMaskValue);
} // end for i
} // end UpdateJointPDFAndIncrementalPDFs()
/**
* ************************ ComputePDFsSingleThreaded **************************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::ComputePDFsSingleThreaded(
const ParametersType & parameters) const
{
/** Initialize some variables. */
this->m_JointPDF->FillBuffer(0.0);
Superclass::m_NumberOfPixelsCounted = 0;
this->m_Alpha = 0.0;
/** Call non-thread-safe stuff, such as:
* this->SetTransformParameters( parameters );
* this->GetImageSampler()->Update();
* Because of these calls GetValueAndDerivative itself is not thread-safe,
* so cannot be called multiple times simultaneously.
* This is however needed in the CombinationImageToImageMetric.
* In that case, you need to:
* - switch the use of this function to on, using m_UseMetricSingleThreaded = true
* - call BeforeThreadedGetValueAndDerivative once (single-threaded) before
* calling GetValueAndDerivative
* - switch the use of this function to off, using m_UseMetricSingleThreaded = false
* - Now you can call GetValueAndDerivative multi-threaded.
*/
this->BeforeThreadedGetValueAndDerivative(parameters);
/** Get a handle to the sample container. */
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
/** Loop over sample container and compute contribution of each sample to pdfs. */
for (const auto & fixedImageSample : *sampleContainer)
{
/** Read fixed coordinates and initialize some variables. */
const FixedImagePointType & fixedPoint = fixedImageSample.m_ImageCoordinates;
RealType movingImageValue;
/** Transform point. */
const MovingImagePointType mappedPoint = this->TransformPoint(fixedPoint);
/** Check if the point is inside the moving mask. */
bool sampleOk = this->IsInsideMovingMask(mappedPoint);
/** Compute the moving image value and check if the point is
* inside the moving image buffer.
*/
if (sampleOk)
{
sampleOk = this->Superclass::EvaluateMovingImageValueAndDerivative(mappedPoint, movingImageValue, nullptr);
}
if (sampleOk)
{
Superclass::m_NumberOfPixelsCounted++;
/** Get the fixed image value. */
auto fixedImageValue = static_cast<RealType>(fixedImageSample.m_ImageValue);
/** Make sure the values fall within the histogram range. */
fixedImageValue = this->GetFixedImageLimiter()->Evaluate(fixedImageValue);
movingImageValue = this->GetMovingImageLimiter()->Evaluate(movingImageValue);
/** Compute this sample's contribution to the joint distributions. */
this->UpdateJointPDFAndDerivatives(
fixedImageValue, movingImageValue, nullptr, nullptr, this->m_JointPDF.GetPointer());
}
} // end iterating over fixed image spatial sample container for loop
/** Check if enough samples were valid. */
this->CheckNumberOfSamples();
/** Compute alpha. */
this->m_Alpha = 1.0 / static_cast<double>(Superclass::m_NumberOfPixelsCounted);
} // end ComputePDFsSingleThreaded()
/**
* ************************ ComputePDFs **************************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::ComputePDFs(const ParametersType & parameters) const
{
/** Option for now to still use the single threaded code. */
if (!Superclass::m_UseMultiThread)
{
return this->ComputePDFsSingleThreaded(parameters);
}
/** Call non-thread-safe stuff, such as:
* this->SetTransformParameters( parameters );
* this->GetImageSampler()->Update();
* Because of these calls GetValueAndDerivative itself is not thread-safe,
* so cannot be called multiple times simultaneously.
* This is however needed in the CombinationImageToImageMetric.
* In that case, you need to:
* - switch the use of this function to on, using m_UseMetricSingleThreaded = true
* - call BeforeThreadedGetValueAndDerivative once (single-threaded) before
* calling GetValueAndDerivative
* - switch the use of this function to off, using m_UseMetricSingleThreaded = false
* - Now you can call GetValueAndDerivative multi-threaded.
*/
this->BeforeThreadedGetValueAndDerivative(parameters);
/** Launch multi-threading JointPDF computation. */
this->LaunchComputePDFsThreaderCallback();
/** Gather the results from all threads. */
this->AfterThreadedComputePDFs();
} // end ComputePDFs()
/**
* ******************* ThreadedComputePDFs *******************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::ThreadedComputePDFs(ThreadIdType threadId)
{
/** Get a handle to the pre-allocated joint PDF for the current thread.
* The initialization is performed here, so that it is done multi-threadedly
* instead of sequentially in InitializeThreadingParameters().
*/
JointPDFPointer & jointPDF =
this->m_ParzenWindowHistogramGetValueAndDerivativePerThreadVariables[threadId].st_JointPDF;
jointPDF->FillBuffer(PDFValueType{});
/** Get a handle to the sample container. */
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
const size_t sampleContainerSize{ sampleContainer->size() };
/** Get the samples for this thread. */
const auto nrOfSamplesPerThreads = static_cast<unsigned long>(
std::ceil(static_cast<double>(sampleContainerSize) / static_cast<double>(Self::GetNumberOfWorkUnits())));
const auto pos_begin = std::min<size_t>(nrOfSamplesPerThreads * threadId, sampleContainerSize);
const auto pos_end = std::min<size_t>(nrOfSamplesPerThreads * (threadId + 1), sampleContainerSize);
/** Create iterator over the sample container. */
const auto beginOfSampleContainer = sampleContainer->cbegin();
const auto fbegin = beginOfSampleContainer + pos_begin;
const auto fend = beginOfSampleContainer + pos_end;
/** Create variables to store intermediate results. circumvent false sharing */
unsigned long numberOfPixelsCounted = 0;
/** Loop over sample container and compute contribution of each sample to pdfs. */
for (auto fiter = fbegin; fiter != fend; ++fiter)
{
/** Read fixed coordinates and initialize some variables. */
const FixedImagePointType & fixedPoint = fiter->m_ImageCoordinates;
RealType movingImageValue;
/** Transform point. */
const MovingImagePointType mappedPoint = this->TransformPoint(fixedPoint);
/** Check if the point is inside the moving mask. */
bool sampleOk = this->IsInsideMovingMask(mappedPoint);
/** Compute the moving image value and check if the point is
* inside the moving image buffer.
*/
if (sampleOk)
{
sampleOk = this->FastEvaluateMovingImageValueAndDerivative(mappedPoint, movingImageValue, nullptr, threadId);
}
if (sampleOk)
{
++numberOfPixelsCounted;
/** Get the fixed image value. */
auto fixedImageValue = static_cast<RealType>(fiter->m_ImageValue);
/** Make sure the values fall within the histogram range. */
fixedImageValue = this->GetFixedImageLimiter()->Evaluate(fixedImageValue);
movingImageValue = this->GetMovingImageLimiter()->Evaluate(movingImageValue);
/** Compute this sample's contribution to the joint distributions. */
this->UpdateJointPDFAndDerivatives(fixedImageValue, movingImageValue, nullptr, nullptr, jointPDF.GetPointer());
}
} // end iterating over fixed image spatial sample container for loop
/** Only update these variables at the end to prevent unnecessary "false sharing". */
this->m_ParzenWindowHistogramGetValueAndDerivativePerThreadVariables[threadId].st_NumberOfPixelsCounted =
numberOfPixelsCounted;
} // end ThreadedComputePDFs()
/**
* ******************* AfterThreadedComputePDFs *******************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::AfterThreadedComputePDFs() const
{
const ThreadIdType numberOfThreads = Self::GetNumberOfWorkUnits();
/** Accumulate the number of pixels. */
Superclass::m_NumberOfPixelsCounted =
this->m_ParzenWindowHistogramGetValueAndDerivativePerThreadVariables[0].st_NumberOfPixelsCounted;
for (ThreadIdType i = 1; i < numberOfThreads; ++i)
{
Superclass::m_NumberOfPixelsCounted +=
this->m_ParzenWindowHistogramGetValueAndDerivativePerThreadVariables[i].st_NumberOfPixelsCounted;
}
/** Check if enough samples were valid. */
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
this->CheckNumberOfSamples();
/** Compute alpha. */
this->m_Alpha = 1.0 / static_cast<double>(Superclass::m_NumberOfPixelsCounted);
/** Accumulate joint histogram. */
// could be multi-threaded too, by each thread updating only a part of the JointPDF.
using JointPDFIteratorType = ImageScanlineIterator<JointPDFType>;
JointPDFIteratorType it(this->m_JointPDF, this->m_JointPDF->GetBufferedRegion());
std::vector<JointPDFIteratorType> itT(numberOfThreads);
for (ThreadIdType i = 0; i < numberOfThreads; ++i)
{
itT[i] = JointPDFIteratorType(this->m_ParzenWindowHistogramGetValueAndDerivativePerThreadVariables[i].st_JointPDF,
this->m_JointPDF->GetBufferedRegion());
}
PDFValueType sum;
while (!it.IsAtEnd())
{
while (!it.IsAtEndOfLine())
{
sum = PDFValueType{};
for (ThreadIdType i = 0; i < numberOfThreads; ++i)
{
sum += itT[i].Value();
++itT[i];
}
it.Set(sum);
++it;
}
it.NextLine();
for (ThreadIdType i = 0; i < numberOfThreads; ++i)
{
itT[i].NextLine();
}
}
} // end AfterThreadedComputePDFs()
/**
* **************** ComputePDFsThreaderCallback *******
*/
template <typename TFixedImage, typename TMovingImage>
ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::ComputePDFsThreaderCallback(void * arg)
{
assert(arg);
const auto & infoStruct = *static_cast<ThreadInfoType *>(arg);
ThreadIdType threadId = infoStruct.WorkUnitID;
assert(infoStruct.UserData);
const auto & userData = *static_cast<ParzenWindowHistogramMultiThreaderParameterType *>(infoStruct.UserData);
userData.m_Metric->ThreadedComputePDFs(threadId);
return ITK_THREAD_RETURN_DEFAULT_VALUE;
} // end ComputePDFsThreaderCallback()
/**
* *********************** LaunchComputePDFsThreaderCallback***************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::LaunchComputePDFsThreaderCallback() const
{
/** Setup threader and launch. */
this->m_Threader->SetSingleMethodAndExecute(
this->ComputePDFsThreaderCallback,
const_cast<void *>(static_cast<const void *>(&this->m_ParzenWindowHistogramThreaderParameters)));
} // end LaunchComputePDFsThreaderCallback()
/**
* ************************ ComputePDFsAndPDFDerivatives *******************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::ComputePDFsAndPDFDerivatives(
const ParametersType & parameters) const
{
/** Initialize some variables. */
this->m_JointPDF->FillBuffer(0.0);
this->m_JointPDFDerivatives->FillBuffer(0.0);
this->m_Alpha = 0.0;
Superclass::m_NumberOfPixelsCounted = 0;
/** Array that stores dM(x)/dmu, and the sparse jacobian+indices. */
NonZeroJacobianIndicesType nzji(Superclass::m_AdvancedTransform->GetNumberOfNonZeroJacobianIndices());
DerivativeType imageJacobian(nzji.size());
TransformJacobianType jacobian;
/** Call non-thread-safe stuff, such as:
* this->SetTransformParameters( parameters );
* this->GetImageSampler()->Update();
* Because of these calls GetValueAndDerivative itself is not thread-safe,
* so cannot be called multiple times simultaneously.
* This is however needed in the CombinationImageToImageMetric.
* In that case, you need to:
* - switch the use of this function to on, using m_UseMetricSingleThreaded = true
* - call BeforeThreadedGetValueAndDerivative once (single-threaded) before
* calling GetValueAndDerivative
* - switch the use of this function to off, using m_UseMetricSingleThreaded = false
* - Now you can call GetValueAndDerivative multi-threaded.
*/
this->BeforeThreadedGetValueAndDerivative(parameters);
/** Get a handle to the sample container. */
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
/** Loop over sample container and compute contribution of each sample to pdfs. */
for (const auto & fixedImageSample : *sampleContainer)
{
/** Read fixed coordinates and initialize some variables. */
const FixedImagePointType & fixedPoint = fixedImageSample.m_ImageCoordinates;
RealType movingImageValue;
MovingImageDerivativeType movingImageDerivative;
/** Transform point. */
const MovingImagePointType mappedPoint = this->TransformPoint(fixedPoint);
/** Check if the point is inside the moving mask. */
bool sampleOk = this->IsInsideMovingMask(mappedPoint);
/** Compute the moving image value M(T(x)) and derivative dM/dx and check if
* the point is inside the moving image buffer.
*/
if (sampleOk)
{
sampleOk =
this->Superclass::EvaluateMovingImageValueAndDerivative(mappedPoint, movingImageValue, &movingImageDerivative);
}
if (sampleOk)
{
Superclass::m_NumberOfPixelsCounted++;
/** Get the fixed image value. */
auto fixedImageValue = static_cast<RealType>(fixedImageSample.m_ImageValue);
/** Make sure the values fall within the histogram range. */
fixedImageValue = this->GetFixedImageLimiter()->Evaluate(fixedImageValue);
movingImageValue = this->GetMovingImageLimiter()->Evaluate(movingImageValue, movingImageDerivative);
/** Get the TransformJacobian dT/dmu. */
this->EvaluateTransformJacobian(fixedPoint, jacobian, nzji);
/** Compute the inner product (dM/dx)^T (dT/dmu). */
this->EvaluateTransformJacobianInnerProduct(jacobian, movingImageDerivative, imageJacobian);
/** Update the joint pdf and the joint pdf derivatives. */
this->UpdateJointPDFAndDerivatives(
fixedImageValue, movingImageValue, &imageJacobian, &nzji, this->m_JointPDF.GetPointer());
} // end if-block check sampleOk
} // end iterating over fixed image spatial sample container for loop
/** Check if enough samples were valid. */
this->CheckNumberOfSamples();
/** Compute alpha. */
this->m_Alpha = 0.0;
if (Superclass::m_NumberOfPixelsCounted > 0)
{
this->m_Alpha = 1.0 / static_cast<double>(Superclass::m_NumberOfPixelsCounted);
}
} // end ComputePDFsAndPDFDerivatives()
/**
* ************************ ComputePDFsAndIncrementalPDFs *******************
*/
template <typename TFixedImage, typename TMovingImage>
void
ParzenWindowHistogramImageToImageMetric<TFixedImage, TMovingImage>::ComputePDFsAndIncrementalPDFs(
const ParametersType & parameters) const
{
/** Initialize some variables. */
this->m_JointPDF->FillBuffer(0.0);
this->m_IncrementalJointPDFRight->FillBuffer(0.0);
this->m_IncrementalJointPDFLeft->FillBuffer(0.0);
this->m_Alpha = 0.0;
this->m_PerturbedAlphaRight.Fill(0.0);
this->m_PerturbedAlphaLeft.Fill(0.0);
Superclass::m_NumberOfPixelsCounted = 0;
double sumOfMovingMaskValues = 0.0;
const double delta = this->GetFiniteDifferencePerturbation();
/** sparse jacobian+indices. */
NonZeroJacobianIndicesType nzji(Superclass::m_AdvancedTransform->GetNumberOfNonZeroJacobianIndices());
TransformJacobianType jacobian;
/** Arrays that store dM(x)/dmu and dMask(x)/dmu. */
DerivativeType movingImageValuesRight(nzji.size());
DerivativeType movingImageValuesLeft(nzji.size());
DerivativeType movingMaskValuesRight(nzji.size());
DerivativeType movingMaskValuesLeft(nzji.size());
/** Call non-thread-safe stuff, such as:
* this->SetTransformParameters( parameters );
* this->GetImageSampler()->Update();
* Because of these calls GetValueAndDerivative itself is not thread-safe,
* so cannot be called multiple times simultaneously.
* This is however needed in the CombinationImageToImageMetric.
* In that case, you need to:
* - switch the use of this function to on, using m_UseMetricSingleThreaded = true
* - call BeforeThreadedGetValueAndDerivative once (single-threaded) before
* calling GetValueAndDerivative
* - switch the use of this function to off, using m_UseMetricSingleThreaded = false
* - Now you can call GetValueAndDerivative multi-threaded.
*/
this->BeforeThreadedGetValueAndDerivative(parameters);
/** Get a handle to the sample container. */
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
/** Loop over sample container and compute contribution of each sample to pdfs. */
for (const auto & fixedImageSample : *sampleContainer)
{
/** Read fixed coordinates. */
const FixedImagePointType & fixedPoint = fixedImageSample.m_ImageCoordinates;
/** Transform point and check if it is inside the B-spline support region.
* if not, skip this sample.
*/
const MovingImagePointType mappedPoint = this->TransformPoint(fixedPoint);
{
/** Get the fixed image value and make sure the value falls within the histogram range. */
auto fixedImageValue = static_cast<RealType>(fixedImageSample.m_ImageValue);
fixedImageValue = this->GetFixedImageLimiter()->Evaluate(fixedImageValue);
/** Check if the point is inside the moving mask. */
bool sampleOk = this->IsInsideMovingMask(mappedPoint);
auto movingMaskValue = static_cast<RealType>(static_cast<unsigned char>(sampleOk));
/** Compute the moving image value M(T(x)) and check if
* the point is inside the moving image buffer.
*/
RealType movingImageValue{};
if (sampleOk)
{
sampleOk = this->Superclass::EvaluateMovingImageValueAndDerivative(mappedPoint, movingImageValue, nullptr);
if (sampleOk)
{
movingImageValue = this->GetMovingImageLimiter()->Evaluate(movingImageValue);
}
else
{
/** this movingImageValueRight is invalid, even though the mask indicated it is valid. */
movingMaskValue = 0.0;
}
}
/** Stop with this sample. It may be possible that with a perturbed parameter
* a valid voxel pair is obtained, but:
* - this chance is small,
* - quitting now saves a lot of time, especially because this situation
* occurs at border pixels (there are a lot of those)
* - if we would analytically compute the gradient the same choice is
* somehow made.
*/
if (!sampleOk)
{
continue;
}
/** Count how many samples were used. */
sumOfMovingMaskValues += movingMaskValue;
Superclass::m_NumberOfPixelsCounted += static_cast<unsigned int>(sampleOk);
/** Get the TransformJacobian dT/dmu. We assume the transform is a linear
* function of its parameters, so that we can evaluate T(x;\mu+delta_ek)
* as T(x) + delta * dT/dmu_k.
*/
this->EvaluateTransformJacobian(fixedPoint, jacobian, nzji);
MovingImagePointType mappedPointRight;
MovingImagePointType mappedPointLeft;
/** Loop over all parameters to perturb (parameters with nonzero Jacobian). */
for (unsigned int i = 0; i < nzji.size(); ++i)
{
/** Compute the transformed input point after perturbation. */
for (unsigned int j = 0; j < MovingImageDimension; ++j)
{
const double delta_jac = delta * jacobian[j][i];
mappedPointRight[j] = mappedPoint[j] + delta_jac;
mappedPointLeft[j] = mappedPoint[j] - delta_jac;
}
/** Compute the moving mask 'value' and moving image value at the right perturbed positions. */
sampleOk = this->IsInsideMovingMask(mappedPointRight);
auto movingMaskValueRight = static_cast<RealType>(static_cast<unsigned char>(sampleOk));
if (sampleOk)
{
RealType movingImageValueRight = 0.0;
sampleOk =
this->Superclass::EvaluateMovingImageValueAndDerivative(mappedPointRight, movingImageValueRight, nullptr);
if (sampleOk)
{
movingImageValueRight = this->GetMovingImageLimiter()->Evaluate(movingImageValueRight);
movingImageValuesRight[i] = movingImageValueRight;
}
else
{
/** this movingImageValueRight is invalid, even though the mask indicated it is valid. */
movingMaskValueRight = 0.0;
}
}
movingMaskValuesRight[i] = movingMaskValueRight;
/** Compute the moving mask and moving image value at the left perturbed positions. */
sampleOk = this->IsInsideMovingMask(mappedPointLeft);
auto movingMaskValueLeft = static_cast<RealType>(static_cast<unsigned char>(sampleOk));
if (sampleOk)
{
RealType movingImageValueLeft = 0.0;
sampleOk =
this->Superclass::EvaluateMovingImageValueAndDerivative(mappedPointLeft, movingImageValueLeft, nullptr);
if (sampleOk)
{
movingImageValueLeft = this->GetMovingImageLimiter()->Evaluate(movingImageValueLeft);
movingImageValuesLeft[i] = movingImageValueLeft;
}
else
{
/** this movingImageValueLeft is invalid, even though the mask indicated it is valid. */
movingMaskValueLeft = 0.0;
}
}
movingMaskValuesLeft[i] = movingMaskValueLeft;
} // next parameter to perturb
/** Update the joint pdf and the incremental joint pdfs, and the
* perturbed alpha arrays.
*/
this->UpdateJointPDFAndIncrementalPDFs(fixedImageValue,
movingImageValue,
movingMaskValue,
movingImageValuesRight,
movingImageValuesLeft,
movingMaskValuesRight,
movingMaskValuesLeft,
nzji);
} // end if-block check sampleOk
} // end iterating over fixed image spatial sample container for loop
/** Check if enough samples were valid. */
this->CheckNumberOfSamples();
/** Compute alpha and its perturbed versions. */
this->m_Alpha = 0.0;
if (sumOfMovingMaskValues > 1e-14)
{
this->m_Alpha = 1.0 / sumOfMovingMaskValues;
}
const auto numberOfParameters = this->GetNumberOfParameters();
for (unsigned int i = 0; i < numberOfParameters; ++i)
{
this->m_PerturbedAlphaRight[i] += sumOfMovingMaskValues;
this->m_PerturbedAlphaLeft[i] += sumOfMovingMaskValues;
if (this->m_PerturbedAlphaRight[i] > 1e-10)
{
this->m_PerturbedAlphaRight[i] = 1.0 / this->m_PerturbedAlphaRight[i];
}
else
{
this->m_PerturbedAlphaRight[i] = 0.0;
}
if (this->m_PerturbedAlphaLeft[i] > 1e-10)
{
this->m_PerturbedAlphaLeft[i] = 1.0 / this->m_PerturbedAlphaLeft[i];
}
else
{
this->m_PerturbedAlphaLeft[i] = 0.0;
}
}
} // end ComputePDFsAndIncrementalPDFs()
} // end namespace itk
#endif // end #ifndef itkParzenWindowHistogramImageToImageMetric_hxx
|