This file is indexed.

/usr/include/ITK-4.5/itkFEMRobustSolver.hxx is in libinsighttoolkit4-dev 4.5.0-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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 __itkFEMRobustSolver_hxx
#define __itkFEMRobustSolver_hxx

#include "itkFEMRobustSolver.h"

#include "itkFEMLoadNode.h"
#include "itkFEMLoadElementBase.h"
#include "itkFEMLoadBC.h"
#include "itkFEMLoadBCMFC.h"
#include "itkFEMLoadLandmark.h"

namespace itk
{
namespace fem
{

template <unsigned int VDimension>
RobustSolver<VDimension>
::RobustSolver()
{
  this->m_ForceIndex = 0;
  this->m_LandmarkForceIndex = 1;
  this->m_ExternalForceIndex = 2;
  this->m_SolutionIndex = 0;
  this->m_MeshStiffnessMatrixIndex = 1;
  this->m_LandmarkStiffnessMatrixIndex = 2;
  this->m_StiffnessMatrixIndex = 0;

  this->m_OutlierRejectionSteps = 5;
  this->m_ApproximationSteps = 5;

  this->m_ToleranceToLargestDisplacement = 1.0;
  this->m_ConjugateGradientPrecision = 1e-3;
  this->m_FractionErrorRejected =.25;

  this->m_TradeOffImageMeshEnergy = 1.0;

  this->m_UseInterpolationGrid = true;
}


template <unsigned int VDimension>
RobustSolver<VDimension>
::~RobustSolver()
{
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::Initialization()
{
  this->SetLinearSystemWrapper(&m_Itpack);

  const FEMIndexType maximumNonZeroMatrixEntriesFactor = 100;

  const FEMIndexType maxNumberOfNonZeroValues = this->m_NGFN * maximumNonZeroMatrixEntriesFactor;

  if( maxNumberOfNonZeroValues > NumericTraits< FEMIndexType >::max() / 2 )
    {
    itkExceptionMacro("Too large system of equations");
    }

  this->m_Itpack.SetMaximumNonZeroValuesInMatrix( maxNumberOfNonZeroValues );

  // the NGFN is determined once the FEMObject is finalized
  this->m_ls->SetSystemOrder(this->m_NGFN);
  this->m_ls->SetNumberOfVectors(3);
  this->m_ls->SetNumberOfSolutions(1);
  this->m_ls->SetNumberOfMatrices(3);
  this->m_ls->InitializeMatrix(m_MeshStiffnessMatrixIndex);
  this->m_ls->InitializeMatrix(m_LandmarkStiffnessMatrixIndex);
  this->m_ls->InitializeMatrix(m_StiffnessMatrixIndex);
  this->m_ls->InitializeVector(m_ForceIndex);
  this->m_ls->InitializeVector(m_LandmarkForceIndex);
  this->m_ls->InitializeVector(m_ExternalForceIndex);
  this->m_ls->InitializeSolution(m_SolutionIndex);

  this->InitializeInterpolationGrid();

  this->InitializeLandmarks();
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::InitializeLandmarks()
{
  /*
   * Record the element, in which the landmark is located, and the shape function
   * value.
   */
  LoadContainerType *container = this->m_FEMObject->GetModifiableLoadContainer();

  if(!container)
    {
    itkExceptionMacro("Missing container");
    }

  LoadContainerIterator it = container->Begin();

  for(; it != container->End(); ++it)
    {
    Load::Pointer load = it.Value();

    LoadNoisyLandmark *landmark = dynamic_cast<LoadNoisyLandmark*>(load.GetPointer());

    itkAssertInDebugAndIgnoreInReleaseMacro(landmark != NULL);

    const VectorType & globalPosition = landmark->GetSource();

    InterpolationGridPointType point;
    for( unsigned int i = 0; i < this->FEMDimension; i++ )
      {
      point[i] = globalPosition[i];
      }

    if(this->m_UseInterpolationGrid)
      {
      // landmark is within the interpolation grid
      InterpolationGridIndexType index;
      if( this->m_InterpolationGrid->TransformPhysicalPointToIndex(point, index) )
        {
        const Element * element = this->m_InterpolationGrid->GetPixel(index);

        // landmark is inside the mesh
        if(element != NULL)
          {
          landmark->SetContainedElement( element );

          const FEMIndexType numberOfDimensions = element->GetNumberOfSpatialDimensions();
          VectorType localPos(numberOfDimensions);

          element->GetLocalFromGlobalCoordinates(globalPosition, localPos);
          landmark->SetShape(element->ShapeFunctions(localPos));
          landmark->SetIsOutOfMesh(false);
          }
        else
          {
          // remove the landmark
          landmark->SetIsOutOfMesh(true);
          }

        }

      }
    else
      {
      landmark->AssignToElement(this->m_FEMObject->GetModifiableElementContainer() );
      Element::ConstPointer ep = landmark->GetElement(0);
      VectorType localPos = landmark->GetPoint();
      landmark->SetShape(ep->ShapeFunctions(localPos));
      }
    }

    // remove landmarks outside of the mesh
    this->DeleteLandmarksOutOfMesh();
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::GenerateData()
{
  // initialize matrix, vector, solution, interpolation grid, and landmark.
  this->Initialization();

  // LS solver, which can be a VNL solver or a PETSc solver
  this->RunSolver();

  // copy the input to the output and add the
  // displacements to update the nodal coordinates
  FEMObjectType *femObject = this->GetOutput();
  femObject->DeepCopy(this->GetInput());

  // create DOF
  femObject->FinalizeMesh();

  this->UpdateDisplacements();
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::RunSolver()
{
  // Solve the displacement vector U
  this->AssembleMeshStiffnessMatrix();

  this->ComputeLandmarkTensor();

  this->AssembleLandmarkStiffnessMatrix();

  this->AssembleGlobalMatrixFromLandmarksAndMeshMatrices();

  this->AssembleF();

  if( this->m_OutlierRejectionSteps != 0 )
    {
    this->IncrementalSolverWithOutlierRejection();
    }
  else
    {
    // do "interpolation" only (no points discarded)
    this->IncrementalSolverWithoutOutlierRejection();
    }
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::IncrementalSolverWithOutlierRejection()
{
  // Solve the displacement vector U with outlier rejection

  const unsigned int numberOfLoads = this->m_FEMObject->GetNumberOfLoads();
  const double rejectionRate = this->m_FractionErrorRejected / this->m_OutlierRejectionSteps;

  const unsigned int numberOfRejectedLandmarksPerStep =
    static_cast<unsigned int>( floor(numberOfLoads * rejectionRate) );

  itkDebugMacro("numberOfRejectedLandmarksPerStep " << numberOfRejectedLandmarksPerStep);

  for (unsigned int outlierRejectionIteration = 0;
       outlierRejectionIteration < m_OutlierRejectionSteps; ++outlierRejectionIteration)
    {
    // get scaling parameter before outlier rejection
    const double oldPointTensorPonderation = this->GetLandmarkTensorPonderation();

    this->AddExternalForcesToSetMeshZeroEnergy();
    itkDebugMacro("external force added");

    // solve linear system of equations
    // solver to find possible outliers
    this->SolveSystem();
    itkDebugMacro("System solved");

    // compute simulated error for sorting
    this->ComputeLandmarkSimulatedDisplacementAndWeightedError();

    // sort the points in the *decreasing* order of error norm
    this->NthElementWRTDisplacementError(numberOfRejectedLandmarksPerStep);

    // set first n to "unselected", and decrease
    // numberOfSelectedBlocks accordingly
    this->UnselectLandmarks(numberOfRejectedLandmarksPerStep);

    this->RemoveUnselectedLandmarkContributionInPointStiffnessMatrix();
    itkDebugMacro("unselected points' contribution removed");

    this->DeleteFromLandmarkBeginning(numberOfRejectedLandmarksPerStep);
    itkDebugMacro("unselected points removed from the list");

    // rescale the point stiffness matrix with the new pointTensorPonderation
    this->RescaleLandmarkStiffnessMatrix(oldPointTensorPonderation);
    itkDebugMacro("matrix rescaled");

    this->AssembleGlobalMatrixFromLandmarksAndMeshMatrices();
    itkDebugMacro("matrix reassembled");

    this->AssembleF();
    itkDebugMacro("vector rebuilt");

    this->AddExternalForcesToSetMeshZeroEnergy();
    itkDebugMacro("external force added");

    // solver when some outliers are rejected
    this->SolveSystem();
    itkDebugMacro("system resolved");

    this->CalculateExternalForces();
    itkDebugMacro("approximation iteration with outlier rejection " << outlierRejectionIteration);
    }

  this->IncrementalSolverWithoutOutlierRejection();
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::IncrementalSolverWithoutOutlierRejection()
{
  // Solve the displacement vector U without outlier rejection

  for(unsigned int approximationStep = 0; approximationStep < this->m_ApproximationSteps; ++approximationStep)
    {
    this->AddExternalForcesToSetMeshZeroEnergy();
    itkDebugMacro("external force added");

    this->SolveSystem();

    this->CalculateExternalForces();
    itkDebugMacro("Approximation step without outlier rejection " << approximationStep);
    }
}

template <unsigned int VDimension>
void
RobustSolver<VDimension>
::ComputeLandmarkSimulatedDisplacementAndWeightedError()
{
  // Compute the approximation error for each landmark for subsequent outlier

  const double lambda = this->m_ToleranceToLargestDisplacement;

  LoadContainerType *container = this->m_FEMObject->GetModifiableLoadContainer();

  if(!container)
    {
    itkExceptionMacro("No container");
    }

  LoadContainerIterator it = container->Begin();

  while(it != container->End())
    {
    Load::Pointer load = it.Value();

    LoadNoisyLandmark *landmark = dynamic_cast<LoadNoisyLandmark*>(load.GetPointer());

    if(landmark == NULL)
      {
      itkExceptionMacro("Encounter landmark that is not a LoadNoisyLandmark");
      }

    if(!landmark->IsOutlier())
      {
      const VectorType & shape = landmark->GetShape();

      const Element * element = landmark->GetContainedElement();

      const FEMIndexType numberOfDOFs = element->GetNumberOfDegreesOfFreedomPerNode();
      const FEMIndexType numberOfNodes = element->GetNumberOfNodes();

      VectorType error(numberOfDOFs, 0.0);
      VectorType nodeSolution(numberOfDOFs);

      for(FEMIndexType nodeId = 0; nodeId < numberOfNodes; ++nodeId)
        {
        for(FEMIndexType dofId = 0; dofId < numberOfDOFs; ++dofId)
          {
          const int degreeOfFreedom = element->GetDegreeOfFreedom(nodeId * numberOfDOFs + dofId);
          nodeSolution[dofId] = this->m_ls->GetSolutionValue(degreeOfFreedom, m_SolutionIndex);
          }

        error += shape[nodeId] * nodeSolution;

        }

      landmark->SetSimulatedDisplacement(error);
      const double displacementNorm = error.two_norm();
      error = landmark->GetRealDisplacement() - error;

      const double confidence = landmark->GetConfidence();
      const VectorType weightedError = error / ((1-lambda) * displacementNorm + lambda);

      if(landmark->HasStructureTensor())
        {
        MatrixType structureTensor = landmark->GetStructureTensor();
        VectorType structureTensorPonderatedError = structureTensor * confidence * weightedError;
        landmark->SetErrorNorm(structureTensorPonderatedError.two_norm());
        }
      else
        {
        VectorType nonStructureTensorponderatedError = confidence * weightedError;
        landmark->SetErrorNorm(nonStructureTensorponderatedError.two_norm());
        }
      }

    ++it;
    }
}

template <unsigned int VDimension>
void
RobustSolver<VDimension>
::ComputeLandmarkTensor()
{
  // Compute landmark tensor weighted by a structure tensor if exists

  LoadContainerType *container = this->m_FEMObject->GetModifiableLoadContainer();

  if(!container)
    {
    itkExceptionMacro("Missing container");
    }

  LoadContainerIterator it = container->Begin();

  for(; it != container->End(); ++it)
    {
    Load::Pointer load = it.Value();

    LoadNoisyLandmark *landmark = dynamic_cast<LoadNoisyLandmark*>(load.GetPointer());

    itkAssertInDebugAndIgnoreInReleaseMacro(landmark != NULL);

    if(!landmark->IsOutlier())
      {
      const VectorType & shape = landmark->GetShape();

      const Element * element = landmark->GetContainedElement();

      const FEMIndexType numberOfDOFs = element->GetNumberOfDegreesOfFreedomPerNode();
      const FEMIndexType numberOfNodes = element->GetNumberOfNodes();

      MatrixType nodeTensor(numberOfDOFs, numberOfDOFs);
      MatrixType landmarkTensor(numberOfDOFs, numberOfDOFs);

      landmarkTensor.fill(0.0);

      for(FEMIndexType nodeId = 0; nodeId < numberOfNodes; ++nodeId)
        {
        for(FEMIndexType dofXId = 0; dofXId < numberOfDOFs; dofXId++)
          {
          for(FEMIndexType dofYId = 0; dofYId < numberOfDOFs; dofYId++)
            {
            unsigned nx = element->GetDegreeOfFreedom(nodeId * numberOfDOFs + dofXId);
            unsigned ny = element->GetDegreeOfFreedom(nodeId * numberOfDOFs + dofYId);
            nodeTensor[dofXId][dofYId] = this->m_ls->GetMatrixValue(nx, ny, m_MeshStiffnessMatrixIndex);
            }
          }

        landmarkTensor += nodeTensor * shape[nodeId];
        }

      if(landmark->HasStructureTensor())
        {
        landmarkTensor *= landmark->GetStructureTensor();
        }

      landmark->SetLandmarkTensor(landmarkTensor);

      }
    }
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::NthElementWRTDisplacementError(unsigned int nthPoint)
{
  // Sort the landmarks according to the error norm

  if(nthPoint == 0)
    {
    return;
    }

  typedef std::vector<Load::Pointer> LoadVectorType;

  LoadContainerType *container = this->m_FEMObject->GetModifiableLoadContainer();

  if(!container)
    {
    itkExceptionMacro("Missing container");
    }

  LoadVectorType &loadVector = container->CastToSTLContainer();

  LoadVectorType::iterator it = loadVector.begin();
  std::advance(it, nthPoint - 1);
  LoadVectorType::iterator nth = it;
  std::nth_element(loadVector.begin(), nth ,loadVector.end(), CompareLandmarkDisplacementError());
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::UnselectLandmarks(unsigned int nUnselected)
{
  if(nUnselected == 0)
    {
    return;
    }

  typedef std::vector<Load::Pointer> LoadVectorType;

  LoadContainerType *container = this->m_FEMObject->GetModifiableLoadContainer();

  if(!container)
    {
    itkExceptionMacro("Missing container");
    }

  LoadVectorType &loadVector = container->CastToSTLContainer();

  LoadVectorType::iterator it;
  it = loadVector.begin();
  std::advance(it, nUnselected - 1);
  LoadVectorType::iterator nth = it;

  for(it = loadVector.begin(); it <= nth; it++)
    {
    LoadNoisyLandmark * landmark = dynamic_cast<LoadNoisyLandmark*>((*it).GetPointer());
    itkAssertInDebugAndIgnoreInReleaseMacro(landmark != NULL);

    landmark->SetOutlier(true);
    }
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::DeleteFromLandmarkBeginning(unsigned int nDeleted)
{
  if(nDeleted == 0)
    {
    return;
    }

  typedef std::vector<Load::Pointer> LoadVectorType;

  LoadContainerType *container = this->m_FEMObject->GetModifiableLoadContainer();

  if(!container)
    {
    itkExceptionMacro("Missing container");
    }

  LoadVectorType &loadVector = container->CastToSTLContainer();

  LoadVectorType::iterator it;
  it = loadVector.begin();
  std::advance(it, nDeleted);
  LoadVectorType::iterator nth = it;
  loadVector.erase(loadVector.begin(), nth);
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::DeleteLandmarksOutOfMesh()
{
  typedef typename FEMObjectType::LoadIdentifier LoadIdentifier;

  typedef itk::VectorContainer< LoadIdentifier, Load::Pointer> VectorContainerType;
  typename VectorContainerType::Pointer newLoadContainer = VectorContainerType::New();

  LoadIdentifier numToRemoveLoads = NumericTraits< LoadIdentifier >::Zero;

  LoadContainerType * container = this->m_FEMObject->GetModifiableLoadContainer();

  if(!container)
    {
    itkExceptionMacro("Missing container");
    }

  for(LoadContainerIterator it = container->Begin(); it != container->End(); ++it)
    {
    Load::Pointer load = it.Value();

    LoadNoisyLandmark *landmark = dynamic_cast<LoadNoisyLandmark*>(load.GetPointer());

    if(landmark == NULL)
      {
      itkExceptionMacro("Encounter landmark that is not a LoadNoisyLandmark");
      }

    if(landmark->IsOutOfMesh())
      {
      numToRemoveLoads++;
      }
    else
      {
      newLoadContainer->push_back(landmark);
      }
    }

  // If there were landmarks outside of the mesh, then the load container must
  // be updated to hold only the landmarks that are inside of the Mesh.
  if( numToRemoveLoads )
    {
    // Empty the load container first.
    container->clear();

    // add the new loads to Load container
    for(LoadContainerIterator it = newLoadContainer->Begin(); it != newLoadContainer->End(); ++it)
      {
      this->m_FEMObject->AddNextLoad(it.Value());
      }
    }
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::RescaleLandmarkStiffnessMatrix(double oldPointTensorPonderation)
{
  // PointTensorPonderation is changing throughout outlier rejection.
  // This function scales the point stiffness matrix by the updated
  // pointTensorPonderation

  double newPointTensorPonderation =
    this->GetLandmarkTensorPonderation() / oldPointTensorPonderation;

  this->m_ls->ScaleMatrix(newPointTensorPonderation, m_LandmarkStiffnessMatrixIndex);
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::AssembleMeshStiffnessMatrix()
{
  // Assemble the mechanical stiffness matrix from the mesh

  // if no DOFs exist in a system, we have nothing to do
  if( this->m_NGFN <= 0 )
    {
    return;
    }

  // assemble the mechanical matrix by stepping over all elements
  FEMIndexType numberOfElements = this->m_FEMObject->GetNumberOfElements();
  for( FEMIndexType i = 0; i < numberOfElements; i++)
    {
    // call the function that actually moves the element matrix to the master matrix.
    Element::Pointer element = this->m_FEMObject->GetElement(i);

    this->AssembleElementMatrixWithID(element, this->m_MeshStiffnessMatrixIndex);
    }
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::AssembleElementMatrixWithID(const Element::Pointer & element, unsigned int matrixIndex)
{
  // copy the element stiffness matrix for faster access.
  Element::MatrixType Ke;

  element->GetStiffnessMatrix(Ke);

  // same for number of DOF
  const FEMIndexType numberOfDOFs = element->GetNumberOfDegreesOfFreedom();

  // step over all rows in element matrix
  for( FEMIndexType j = 0; j < numberOfDOFs; j++ )
    {
    // step over all columns in element matrix
    for( FEMIndexType k = 0; k < numberOfDOFs; k++ )
      {
      // error checking. all GFN should be >= 0 and < NGFN
      const unsigned int dofj = element->GetDegreeOfFreedom(j);
      const unsigned int dofk = element->GetDegreeOfFreedom(k);
      if( dofj >= this->m_NGFN || dofk >= this->m_NGFN )
        {
        throw FEMExceptionSolution(__FILE__, __LINE__, "Solver::AssembleElementMatrix()", "Illegal GFN!");
        }

      if( Ke[j][k] != Float(0.0) )
        {
        this->m_ls->AddMatrixValue(dofj, dofk, Ke[j][k], matrixIndex);
        }
      }
    }
}

template <unsigned int VDimension>
void
RobustSolver<VDimension>
::AssembleLandmarkStiffnessMatrix()
{
  // Assemble the contribution matrix of the landmarks

  const double pointTensorPonderation = this->GetLandmarkTensorPonderation();

  LoadContainerType *container = this->m_FEMObject->GetModifiableLoadContainer();

  if(!container)
    {
    itkExceptionMacro("Missing container");
    }

  LoadContainerIterator it = container->Begin();

  for(;it != container->End(); ++it)
    {
    Load::Pointer load = it.Value();

    LoadNoisyLandmark *landmark = dynamic_cast<LoadNoisyLandmark*>(load.GetPointer());

    if(landmark == NULL)
      {
      itkExceptionMacro("Encounter landmark that is not a LoadNoisyLandmark");
      }

    if(!landmark->IsOutlier())
      {
      const double confidence = landmark->GetConfidence();

      const MatrixType & tens = landmark->GetLandmarkTensor();

      const VectorType & shape = landmark->GetShape();

      const Element * element = landmark->GetContainedElement();

      const FEMIndexType numberOfDOFs = element->GetNumberOfDegreesOfFreedomPerNode();
      const FEMIndexType numberOfNodes = element->GetNumberOfNodes();

      // fill the diagonal matrices
      for(FEMIndexType k = 0; k < numberOfNodes; ++k)
        {
        const double barCoor = shape[k] * shape[k];

        for(FEMIndexType n = 0; n < numberOfDOFs; n++)
          {
          for(FEMIndexType m = 0; m < numberOfDOFs; m++)
            {
            const int dofn = element->GetDegreeOfFreedom(k * numberOfDOFs + n);
            const int dofm = element->GetDegreeOfFreedom(k * numberOfDOFs + m);
            const float value = static_cast<float>( barCoor * m_TradeOffImageMeshEnergy * pointTensorPonderation * (tens(n,m)) * confidence );

            this->m_ls->AddMatrixValue(dofn, dofm, value, m_LandmarkStiffnessMatrixIndex);
            }
          }
        }

      // fill the extradiagonal matrices
      for(FEMIndexType i = 0; i < numberOfNodes - 1; i++)
        {
        for(FEMIndexType j = i + 1; j < numberOfNodes; j++)
          {
          const double barCoor = shape[i] * shape[j];

          for(FEMIndexType n = 0; n < numberOfDOFs; n++)
            {
            for(FEMIndexType m = 0; m < numberOfDOFs; m++)
              {
              const int dofn = element->GetDegreeOfFreedom(i * numberOfDOFs + n);
              const int dofm = element->GetDegreeOfFreedom(j * numberOfDOFs + m);
              const float value = static_cast<float>( barCoor * m_TradeOffImageMeshEnergy * pointTensorPonderation * (tens(n, m)) * confidence );

              this->m_ls->AddMatrixValue(dofn, dofm, value, m_LandmarkStiffnessMatrixIndex);
              this->m_ls->AddMatrixValue(dofm, dofn, value, m_LandmarkStiffnessMatrixIndex);

              }
            }
          }
        }
      }
    }
}

template <unsigned int VDimension>
void
RobustSolver<VDimension>
::RemoveUnselectedLandmarkContributionInPointStiffnessMatrix()
{
  // Remove the contribution of the unselected landmarks from the landmark
  // stiffness matrix

  const double pointTensorPonderation = GetLandmarkTensorPonderation();

  itkDebugMacro("Removing unselected blocks contribution, " << "pointTensorPonderation is " << pointTensorPonderation);

  LoadContainerType *container = this->m_FEMObject->GetModifiableLoadContainer();

  if(!container)
    {
    itkExceptionMacro("Missing container");
    }

  LoadContainerIterator it = container->Begin();

  for(;it != container->End(); ++it)
    {
    Load::Pointer load = it.Value();

    LoadNoisyLandmark *landmark = dynamic_cast<LoadNoisyLandmark*>(load.GetPointer());

    itkAssertInDebugAndIgnoreInReleaseMacro(landmark != NULL);

    if(landmark->IsOutlier())
      {
      const float confidence = landmark->GetConfidence();

      const MatrixType & tens = landmark->GetLandmarkTensor();

      const VectorType & shape = landmark->GetShape();

      Element::ConstPointer element = landmark->GetElement(0);

      const FEMIndexType numberOfDOFs = element->GetNumberOfDegreesOfFreedomPerNode();
      const FEMIndexType numberOfNodes = element->GetNumberOfNodes();

      for(FEMIndexType k = 0; k < numberOfNodes; ++k)
        {
        const double barCoor = shape[k] * shape[k];

        for(FEMIndexType n = 0; n < numberOfDOFs; n++)
          {
          for(FEMIndexType m = 0; m < numberOfDOFs; m++)
            {
            const int dofn = element->GetDegreeOfFreedom(k * numberOfDOFs + n);
            const int dofm = element->GetDegreeOfFreedom(k * numberOfDOFs + m);
            const float value = static_cast<float>( -barCoor * m_TradeOffImageMeshEnergy * pointTensorPonderation * (tens(n, m)) * confidence );

            this->m_ls->AddMatrixValue(dofn, dofm, value, m_LandmarkStiffnessMatrixIndex);

            }
          }
        }

      for(FEMIndexType i = 0; i < numberOfNodes - 1; i++)
        {
        for(FEMIndexType j = i + 1; j < numberOfNodes; j++)
          {
          const double barCoor = shape[i] * shape[j];

          for(FEMIndexType n = 0; n < numberOfDOFs; n++)
            {
            for(FEMIndexType m = 0; m < numberOfDOFs; m++)
              {
              const int dofn = element->GetDegreeOfFreedom(i * numberOfDOFs + n);
              const int dofm = element->GetDegreeOfFreedom(j * numberOfDOFs + m);
              const float value = static_cast<float>( -barCoor * m_TradeOffImageMeshEnergy * pointTensorPonderation * (tens(n,m)) * confidence );

              this->m_ls->AddMatrixValue(dofn, dofm, value, m_LandmarkStiffnessMatrixIndex);
              this->m_ls->AddMatrixValue(dofm, dofn, value, m_LandmarkStiffnessMatrixIndex);

              }
            }
          }
        }
      }
    }
}


template <unsigned int VDimension>
float
RobustSolver<VDimension>
::GetLandmarkTensorPonderation(void) const
{
  const LoadContainerType * loadContainer = this->m_FEMObject->GetLoadContainer();

  if(!loadContainer)
    {
    itkExceptionMacro("Missing load container");
    }

  const NodeContainerType * nodeContainer = this->m_FEMObject->GetNodeContainer();

  if(!nodeContainer)
    {
    itkExceptionMacro("Missing node container");
    }

  const float ponderation =
    static_cast<float>( nodeContainer->Size() ) /
    static_cast<float>( loadContainer->Size() );

  return ponderation;
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::AssembleGlobalMatrixFromLandmarksAndMeshMatrices()
{
  this->m_ls->CopyMatrix( this->m_MeshStiffnessMatrixIndex, this->m_StiffnessMatrixIndex );
  this->m_ls->AddMatrixMatrix( this->m_StiffnessMatrixIndex, this->m_LandmarkStiffnessMatrixIndex);
}

template <unsigned int VDimension>
void
RobustSolver<VDimension>
::AssembleF()
{
  const double pointTensorPonderation = GetLandmarkTensorPonderation();

  this->m_ls->InitializeVector(m_LandmarkForceIndex);

  LoadContainerType *container = this->m_FEMObject->GetModifiableLoadContainer();

  if(!container)
    {
    itkExceptionMacro("Missing container");
    }

  LoadContainerIterator it = container->Begin();

  for(;it != container->End(); ++it)
    {
    Load::Pointer load = it.Value();

    LoadNoisyLandmark *landmark = dynamic_cast<LoadNoisyLandmark*>(load.GetPointer());

    itkAssertInDebugAndIgnoreInReleaseMacro(landmark != NULL);

    if(!landmark->IsOutlier())
      {
      const double confidence = landmark->GetConfidence();

      const VectorType & realDisplacement = landmark->GetRealDisplacement();

      const MatrixType & tensor = landmark->GetLandmarkTensor();

      const VectorType & shape = landmark->GetShape();

      const Element * element = landmark->GetContainedElement();

      const FEMIndexType numberOfDOFs = element->GetNumberOfDegreesOfFreedomPerNode();
      const FEMIndexType numberOfNodes = element->GetNumberOfNodes();

      for(FEMIndexType m = 0;m < numberOfNodes; ++m)
        {
        double barCoor = shape[m];

        const VectorType weightedRealDisplacement = confidence * barCoor * pointTensorPonderation * m_TradeOffImageMeshEnergy * ((tensor) * realDisplacement);

        for(FEMIndexType j = 0; j < numberOfDOFs; ++j)
          {
          const int index = element->GetDegreeOfFreedom(m * numberOfDOFs + j);
          this->m_ls->AddVectorValue(index, weightedRealDisplacement[j], this->m_LandmarkForceIndex);
          }
        }
      }
    }
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::CalculateExternalForces()
{
  this->m_ls->MultiplyMatrixSolution( this->m_ExternalForceIndex, this->m_MeshStiffnessMatrixIndex, this->m_SolutionIndex);
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::AddExternalForcesToSetMeshZeroEnergy()
{
   // Add exteranl force to set the mesh energy to be zero, which
   // is equivalent to starting FEM solver from the deformed mesh
  this->m_ls->CopyVector( this->m_LandmarkForceIndex, this->m_ForceIndex );
  this->m_ls->AddVectorVector( this->m_ForceIndex, this->m_ExternalForceIndex );
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::SolveSystem()
{
  // Solve the linear system of equations

  // note that VNL LS solver uses the matrix and vector with index zero to construct the LS
  this->m_ls->Solve();
}


template <unsigned int VDimension>
void
RobustSolver<VDimension>
::InitializeInterpolationGrid()
{
  const InterpolationGridRegionType & region = this->GetRegion();
  InterpolationGridSizeType size = region.GetSize();
  for( unsigned int i = 0; i < this->FEMDimension; i++ )
    {
    if( size[i] == 0 )
      {
      itkExceptionMacro("Size must be specified.");
      }
    }

  this->m_InterpolationGrid = InterpolationGridType::New();
  this->m_InterpolationGrid->SetOrigin( this->GetOrigin() );
  this->m_InterpolationGrid->SetSpacing( this->GetSpacing() );
  this->m_InterpolationGrid->SetDirection( this->GetDirection() );
  this->m_InterpolationGrid->SetRegions( this->GetRegion() );
  this->m_InterpolationGrid->Allocate();

   // initialize all pointers in interpolation grid image to 0
  this->m_InterpolationGrid->FillBuffer(0);

  // fill the interpolation grid with proper pointers to elements
  FEMIndexType numberOfElements = this->m_FEMObject->GetNumberOfElements();
  for( FEMIndexType index = 0; index < numberOfElements; index++ )
    {
    const Element * element = this->m_FEMObject->GetElement( index );
    // get square boundary box of an element
    VectorType v1 = element->GetNodeCoordinates(0);      // lower left corner
    VectorType v2 = v1;                            // upper right corner

    const FEMIndexType NumberOfDimensions = element->GetNumberOfSpatialDimensions();
    for( FEMIndexType n = 1; n < element->GetNumberOfNodes(); n++ )
      {
      const VectorType & v = element->GetNodeCoordinates(n);
      for( FEMIndexType d = 0; d < NumberOfDimensions; d++ )
        {
        if( v[d] < v1[d] )
          {
          v1[d] = v[d];
          }
        if( v[d] > v2[d] )
          {
          v2[d] = v[d];
          }
        }
      }

    // convert boundary box corner points into discrete image indexes.
    InterpolationGridIndexType vi1;
    InterpolationGridIndexType vi2;

    typedef Point<Float, FEMDimension> PointType;
    PointType vp1;
    PointType vp2;
    PointType pt;
    for( unsigned int i = 0; i < FEMDimension; i++ )
      {
      vp1[i] = v1[i];
      vp2[i] = v2[i];
      }

    // obtain the Index of BB corner and check whether it is within image.
    // if it is not, we ignore the entire element.
    if( !this->m_InterpolationGrid->TransformPhysicalPointToIndex(vp1, vi1) )
      {
      continue;
      }
    if( !this->m_InterpolationGrid->TransformPhysicalPointToIndex(vp2, vi2) )
      {
      continue;
      }

    InterpolationGridSizeType region_size;
    for( unsigned int i = 0; i < FEMDimension; i++ )
      {
      region_size[i] = vi2[i] - vi1[i] + 1;
      }

    InterpolationGridRegionType interRegion(vi1, region_size);

    // initialize the iterator that will step over all grid points within
    // element boundary box.
    ImageRegionIterator<InterpolationGridType> iter(this->m_InterpolationGrid, interRegion);

    // update the element pointers in the points defined within the region.
    VectorType global_point(NumberOfDimensions);

    VectorType local_point(NumberOfDimensions);

    // step over all points within the region
    for( iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
      {
      // note: Iteratior is guarantied to be within image, since the
      // elements with BB outside are skipped before.
      this->m_InterpolationGrid->TransformIndexToPhysicalPoint(iter.GetIndex(), pt);
      for( FEMIndexType d = 0; d < NumberOfDimensions; d++ )
        {
        global_point[d] = pt[d];
        }

      // if the point is within the element, we update the pointer at
      // this point in the interpolation grid image.
      if( element->GetLocalFromGlobalCoordinates(global_point, local_point) )
        {
        iter.Set( element );
        }
      } // next point in region
    }   // next element
}

}
}  // end namespace itk::fem
#endif // __itkFEMRobustSolver_hxx